summaryrefslogtreecommitdiff
path: root/android
diff options
context:
space:
mode:
authormirror <mirror@localhost>2026-11-22 08:41:00 +0900
committermirror <mirror@localhost>2026-11-22 08:41:00 +0900
commit449d8b74bd6d9dae98a07254cdfad677b920e7b0 (patch)
treec131c3528c4d517f56e19b854a7453fedb097d40 /android
downloadaves-src-master.tar.gz
aves-src-master.zip
snapshot of aves v1.13.12 (secrets removed: android/app/google-services.json)HEADv1.13.12master
Diffstat (limited to 'android')
-rw-r--r--android/.gitignore16
-rw-r--r--android/app/agconnect-services.json82
-rw-r--r--android/app/build.gradle220
-rw-r--r--android/app/proguard-rules.pro6
-rw-r--r--android/app/src/debug/res/values/colors.xml4
-rw-r--r--android/app/src/debug/res/values/strings.xml4
-rw-r--r--android/app/src/libre/res/values/strings.xml4
-rw-r--r--android/app/src/libreDebug/res/values/strings.xml4
-rw-r--r--android/app/src/libreProfile/res/values/strings.xml4
-rw-r--r--android/app/src/main/AndroidManifest.xml350
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/AnalysisWorker.kt234
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetConfigureActivity.kt66
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetProvider.kt342
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/MainActivity.kt656
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/MediaPlaybackService.kt18
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverService.kt155
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverSettingsActivity.kt12
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/SearchSuggestionsProvider.kt147
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/WallpaperActivity.kt56
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AccessibilityHandler.kt107
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AnalysisHandler.kt110
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppAdapterHandler.kt500
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppProfileHandler.kt97
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/Coresult.kt71
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DebugHandler.kt436
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DeviceHandler.kt174
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/EmbeddedDataHandler.kt361
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GeocodingHandler.kt83
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GlobalSearchHandler.kt42
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/HomeWidgetHandler.kt32
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaEditHandler.kt77
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaFetchObjectHandler.kt68
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaSessionHandler.kt169
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaStoreHandler.kt85
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataEditHandler.kt206
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataFetchHandler.kt1521
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/SecurityHandler.kt80
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/StorageHandler.kt269
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/WallpaperHandler.kt58
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ActivityWindowHandler.kt203
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ServiceWindowHandler.kt59
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/WindowHandler.kt72
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/BaseStreamHandler.kt108
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ActivityResultStreamHandler.kt278
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageByteStreamHandler.kt277
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageOpStreamHandler.kt221
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/MediaStoreStreamHandler.kt36
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/AnalysisStreamHandler.kt15
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/ErrorStreamHandler.kt15
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/IntentStreamHandler.kt15
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaCommandStreamHandler.kt61
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaStoreChangeStreamHandler.kt49
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/SettingsChangeStreamHandler.kt82
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/WindowChangeStreamHandler.kt15
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/decoding/RegionFetcher.kt227
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/decoding/SvgRegionFetcher.kt145
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/decoding/ThumbnailFetcher.kt182
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/decoding/TiffRegionFetcher.kt51
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/glide/AvesAppGlideModule.kt92
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/glide/MultiPageImageGlideModule.kt89
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/glide/SvgGlideModule.kt102
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/glide/TiffGlideModule.kt127
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/glide/VideoThumbnailGlideModule.kt192
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/DngTags.kt229
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifInterfaceHelper.kt420
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifTags.kt61
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/GeoTiffTags.kt116
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/MediaMetadataRetrieverHelper.kt187
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/Metadata.kt186
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/Mp4ParserHelper.kt436
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiPage.kt451
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiTrackMedia.kt59
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/PixyMetaHelper.kt172
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/QuickTimeMetadata.kt99
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/SphericalVideo.kt109
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/SvgHelper.kt33
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/Helper.kt403
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/PngActlDirectory.kt22
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeExifTiffHandler.kt28
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4BoxHandler.kt20
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4UuidBoxHandler.kt20
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePhotoshopReader.kt116
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePngMetadataReader.kt335
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdMetadataReader.kt13
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdReader.kt93
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeXmpReader.kt179
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntry.kt37
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntryDirectory.kt64
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfDirectory.kt36
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfReader.kt95
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleDeviceContainer.kt85
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleXMP.kt205
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/XMP.kt317
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/AvesEntry.kt37
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/EntryFields.kt29
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/ExifOrientationOp.kt5
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/FieldMap.kt3
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/NameConflictStrategy.kt16
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/SourceEntry.kt280
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/provider/AvesEmbeddedMediaProvider.kt18
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/provider/FileImageProvider.kt126
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProvider.kt1443
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProviderFactory.kt26
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/provider/MediaStoreImageProvider.kt1079
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/model/provider/UnknownContentProvider.kt85
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/BitmapUtils.kt301
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/BmpWriter.kt110
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/ByteUtils.kt15
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/CollectionUtils.kt44
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat.kt84
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat33.kt30
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/ContextUtils.kt61
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/ExceptionUtils.kt10
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/FileUtils.kt45
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/FlutterUtils.kt72
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/HashUtils.kt35
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/LogUtils.kt26
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/MathUtils.kt9
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/MemoryUtils.kt19
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/MimeTypes.kt192
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/PermissionManager.kt243
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt788
-rw-r--r--android/app/src/main/kotlin/deckers/thibault/aves/utils/UriUtils.kt18
-rw-r--r--android/app/src/main/res/drawable-nodpi/banner.pngbin0 -> 8081 bytes
-rw-r--r--android/app/src/main/res/drawable-v26/ic_shortcut_collection_foreground.xml16
-rw-r--r--android/app/src/main/res/drawable-v26/ic_shortcut_movie_foreground.xml16
-rw-r--r--android/app/src/main/res/drawable-v26/ic_shortcut_search_foreground.xml16
-rw-r--r--android/app/src/main/res/drawable/ic_launcher_foreground.xml38
-rw-r--r--android/app/src/main/res/drawable/ic_launcher_mono.xml38
-rw-r--r--android/app/src/main/res/drawable/ic_notification.xml38
-rw-r--r--android/app/src/main/res/drawable/ic_outline_stop_24.xml9
-rw-r--r--android/app/src/main/res/drawable/ic_shortcut_collection.xml16
-rw-r--r--android/app/src/main/res/drawable/ic_shortcut_map.xml16
-rw-r--r--android/app/src/main/res/drawable/ic_shortcut_map_foreground.xml16
-rw-r--r--android/app/src/main/res/drawable/ic_shortcut_movie.xml16
-rw-r--r--android/app/src/main/res/drawable/ic_shortcut_search.xml16
-rw-r--r--android/app/src/main/res/layout/app_widget.xml5
-rw-r--r--android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml6
-rw-r--r--android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml6
-rw-r--r--android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_collection.xml5
-rw-r--r--android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_map.xml5
-rw-r--r--android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_movie.xml5
-rw-r--r--android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_search.xml5
-rw-r--r--android/app/src/main/res/mipmap-hdpi/ic_launcher.pngbin0 -> 3099 bytes
-rw-r--r--android/app/src/main/res/mipmap-hdpi/ic_launcher_round.pngbin0 -> 5433 bytes
-rw-r--r--android/app/src/main/res/mipmap-mdpi/ic_launcher.pngbin0 -> 1835 bytes
-rw-r--r--android/app/src/main/res/mipmap-mdpi/ic_launcher_round.pngbin0 -> 3263 bytes
-rw-r--r--android/app/src/main/res/mipmap-xhdpi/ic_launcher.pngbin0 -> 4249 bytes
-rw-r--r--android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.pngbin0 -> 7621 bytes
-rw-r--r--android/app/src/main/res/mipmap-xxhdpi/ic_launcher.pngbin0 -> 6973 bytes
-rw-r--r--android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.pngbin0 -> 12800 bytes
-rw-r--r--android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.pngbin0 -> 9996 bytes
-rw-r--r--android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.pngbin0 -> 17791 bytes
-rw-r--r--android/app/src/main/res/values-ar/strings.xml12
-rw-r--r--android/app/src/main/res/values-az/strings.xml12
-rw-r--r--android/app/src/main/res/values-b+zxx+Shaw/strings.xml12
-rw-r--r--android/app/src/main/res/values-be/strings.xml11
-rw-r--r--android/app/src/main/res/values-bg/strings.xml12
-rw-r--r--android/app/src/main/res/values-bn/strings.xml11
-rw-r--r--android/app/src/main/res/values-ca/strings.xml12
-rw-r--r--android/app/src/main/res/values-ckb/strings.xml12
-rw-r--r--android/app/src/main/res/values-cs/strings.xml12
-rw-r--r--android/app/src/main/res/values-da/strings.xml12
-rw-r--r--android/app/src/main/res/values-de/strings.xml12
-rw-r--r--android/app/src/main/res/values-el/strings.xml12
-rw-r--r--android/app/src/main/res/values-es/strings.xml12
-rw-r--r--android/app/src/main/res/values-et/strings.xml12
-rw-r--r--android/app/src/main/res/values-eu/strings.xml12
-rw-r--r--android/app/src/main/res/values-fa/strings.xml12
-rw-r--r--android/app/src/main/res/values-fi/strings.xml12
-rw-r--r--android/app/src/main/res/values-fr/strings.xml12
-rw-r--r--android/app/src/main/res/values-gl/strings.xml12
-rw-r--r--android/app/src/main/res/values-hi/strings.xml12
-rw-r--r--android/app/src/main/res/values-hu/strings.xml12
-rw-r--r--android/app/src/main/res/values-id/strings.xml12
-rw-r--r--android/app/src/main/res/values-is/strings.xml12
-rw-r--r--android/app/src/main/res/values-it/strings.xml12
-rw-r--r--android/app/src/main/res/values-iw/strings.xml12
-rw-r--r--android/app/src/main/res/values-ja/strings.xml12
-rw-r--r--android/app/src/main/res/values-kmr/strings.xml12
-rw-r--r--android/app/src/main/res/values-kn/strings.xml12
-rw-r--r--android/app/src/main/res/values-ko/strings.xml12
-rw-r--r--android/app/src/main/res/values-lt/strings.xml12
-rw-r--r--android/app/src/main/res/values-ml/strings.xml9
-rw-r--r--android/app/src/main/res/values-my/strings.xml12
-rw-r--r--android/app/src/main/res/values-nb-rNO/strings.xml11
-rw-r--r--android/app/src/main/res/values-ne/strings.xml4
-rw-r--r--android/app/src/main/res/values-night/styles.xml11
-rw-r--r--android/app/src/main/res/values-nl/strings.xml12
-rw-r--r--android/app/src/main/res/values-nn/strings.xml11
-rw-r--r--android/app/src/main/res/values-or/strings.xml4
-rw-r--r--android/app/src/main/res/values-pl/strings.xml12
-rw-r--r--android/app/src/main/res/values-pt/strings.xml12
-rw-r--r--android/app/src/main/res/values-ro/strings.xml12
-rw-r--r--android/app/src/main/res/values-ru/strings.xml12
-rw-r--r--android/app/src/main/res/values-sat/strings.xml5
-rw-r--r--android/app/src/main/res/values-sk/strings.xml12
-rw-r--r--android/app/src/main/res/values-sl/strings.xml11
-rw-r--r--android/app/src/main/res/values-sr/strings.xml11
-rw-r--r--android/app/src/main/res/values-sv/strings.xml12
-rw-r--r--android/app/src/main/res/values-ta/strings.xml12
-rw-r--r--android/app/src/main/res/values-th/strings.xml11
-rw-r--r--android/app/src/main/res/values-tr/strings.xml12
-rw-r--r--android/app/src/main/res/values-uk/strings.xml12
-rw-r--r--android/app/src/main/res/values-ur/strings.xml4
-rw-r--r--android/app/src/main/res/values-vi/strings.xml12
-rw-r--r--android/app/src/main/res/values-zh-rTW/strings.xml12
-rw-r--r--android/app/src/main/res/values-zh/strings.xml12
-rw-r--r--android/app/src/main/res/values/colors.xml9
-rw-r--r--android/app/src/main/res/values/strings.xml12
-rw-r--r--android/app/src/main/res/values/styles.xml11
-rw-r--r--android/app/src/main/res/xml/app_widget_info.xml14
-rw-r--r--android/app/src/main/res/xml/data_extraction_rules.xml37
-rw-r--r--android/app/src/main/res/xml/full_backup_content.xml18
-rw-r--r--android/app/src/main/res/xml/provider_paths.xml19
-rw-r--r--android/app/src/main/res/xml/screen_saver.xml2
-rw-r--r--android/app/src/main/res/xml/searchable.xml8
-rw-r--r--android/app/src/profile/res/values/colors.xml4
-rw-r--r--android/app/src/profile/res/values/strings.xml4
-rw-r--r--android/app/src/test/kotlin/deckers/thibault/aves/model/provider/ImageProviderTest.kt18
-rw-r--r--android/app/src/test/kotlin/deckers/thibault/aves/utils/MathUtilsTest.kt17
-rw-r--r--android/build.gradle52
-rw-r--r--android/exifinterface/.gitignore1
-rw-r--r--android/exifinterface/LICENSE.txt178
-rw-r--r--android/exifinterface/build.gradle31
-rw-r--r--android/exifinterface/consumer-rules.pro0
-rw-r--r--android/exifinterface/proguard-rules.pro21
-rw-r--r--android/exifinterface/src/main/AndroidManifest.xml2
-rw-r--r--android/exifinterface/src/main/java/androidx/exifinterface/media/ExifInterfaceFork.java8553
-rw-r--r--android/exifinterface/src/main/java/androidx/exifinterface/media/ExifInterfaceUtilsFork.java170
-rw-r--r--android/gradle.properties9
-rw-r--r--android/gradle/wrapper/gradle-wrapper.properties5
-rw-r--r--android/key_template.properties5
-rw-r--r--android/settings.gradle.kts28
234 files changed, 29648 insertions, 0 deletions
diff --git a/android/.gitignore b/android/.gitignore
new file mode 100644
index 0000000..5343532
--- /dev/null
+++ b/android/.gitignore
@@ -0,0 +1,16 @@
+gradle-wrapper.jar
+/.gradle
+/captures/
+/gradlew
+/gradlew.bat
+/local.properties
+GeneratedPluginRegistrant.java
+.cxx/
+.kotlin/
+/build/
+
+# Remember to never publicly share your keystore.
+# See https://flutter.dev/to/reference-keystore
+key.properties
+**/*.keystore
+**/*.jks
diff --git a/android/app/agconnect-services.json b/android/app/agconnect-services.json
new file mode 100644
index 0000000..d406d5c
--- /dev/null
+++ b/android/app/agconnect-services.json
@@ -0,0 +1,82 @@
+{
+ "agcgw_all":{
+ "CN":"connect-drcn.dbankcloud.cn",
+ "CN_back":"connect-drcn.hispace.hicloud.com",
+ "DE":"connect-dre.dbankcloud.cn",
+ "DE_back":"connect-dre.hispace.hicloud.com",
+ "RU":"connect-drru.hispace.dbankcloud.ru",
+ "RU_back":"connect-drru.hispace.dbankcloud.cn",
+ "SG":"connect-dra.dbankcloud.cn",
+ "SG_back":"connect-dra.hispace.hicloud.com"
+ },
+ "websocketgw_all":{
+ "CN":"connect-ws-drcn.hispace.dbankcloud.cn",
+ "CN_back":"connect-ws-drcn.hispace.dbankcloud.com",
+ "DE":"connect-ws-dre.hispace.dbankcloud.cn",
+ "DE_back":"connect-ws-dre.hispace.dbankcloud.com",
+ "RU":"connect-ws-drru.hispace.dbankcloud.ru",
+ "RU_back":"connect-ws-drru.hispace.dbankcloud.cn",
+ "SG":"connect-ws-dra.hispace.dbankcloud.cn",
+ "SG_back":"connect-ws-dra.hispace.dbankcloud.com"
+ },
+ "client":{
+ "cp_id":"2640082000020010713",
+ "product_id":"99536292102197525",
+ "project_id":"99536292102197525",
+ "app_id":"106014023",
+ "package_name":"deckers.thibault.aves"
+ },
+ "oauth_client":{
+ "client_id":"106014023",
+ "client_type":1
+ },
+ "app_info":{
+ "app_id":"106014023",
+ "package_name":"deckers.thibault.aves"
+ },
+ "configuration_version":"3.0",
+ "appInfos":[
+ {
+ "package_name":"deckers.thibault.aves",
+ "client":{
+ "app_id":"106014023"
+ },
+ "app_info":{
+ "package_name":"deckers.thibault.aves",
+ "app_id":"106014023"
+ },
+ "oauth_client":{
+ "client_type":1,
+ "client_id":"106014023"
+ }
+ },
+ {
+ "package_name":"deckers.thibault.aves.debug",
+ "client":{
+ "app_id":"106014297"
+ },
+ "app_info":{
+ "package_name":"deckers.thibault.aves.debug",
+ "app_id":"106014297"
+ },
+ "oauth_client":{
+ "client_type":1,
+ "client_id":"106014297"
+ }
+ },
+ {
+ "package_name":"deckers.thibault.aves.profile",
+ "client":{
+ "app_id":"106031461"
+ },
+ "app_info":{
+ "package_name":"deckers.thibault.aves.profile",
+ "app_id":"106031461"
+ },
+ "oauth_client":{
+ "client_type":1,
+ "client_id":"106031461"
+ }
+ }
+ ]
+} \ No newline at end of file
diff --git a/android/app/build.gradle b/android/app/build.gradle
new file mode 100644
index 0000000..6afa8ea
--- /dev/null
+++ b/android/app/build.gradle
@@ -0,0 +1,220 @@
+plugins {
+ id 'com.android.application'
+ id 'com.google.devtools.ksp'
+ id 'kotlin-android'
+ id 'dev.flutter.flutter-gradle-plugin'
+}
+
+def packageName = "deckers.thibault.aves"
+
+// Keys
+
+def keystoreProperties = new Properties()
+def keystorePropertiesFile = rootProject.file('key.properties')
+if (keystorePropertiesFile.exists()) {
+ // for release using credentials stored in a local file
+ keystorePropertiesFile.withReader('UTF-8') { reader -> keystoreProperties.load(reader)
+ }
+} else {
+ // for release using credentials in environment variables set up by GitHub Actions
+ // warning: in property file, single quotes should be escaped with a backslash
+ // but they should not be escaped when stored in env variables
+ keystoreProperties["storeFile"] = System.getenv("AVES_STORE_FILE") ?: "<NONE>"
+ keystoreProperties["storePassword"] = System.getenv("AVES_STORE_PASSWORD") ?: "<NONE>"
+ keystoreProperties["keyAlias"] = System.getenv("AVES_KEY_ALIAS") ?: "<NONE>"
+ keystoreProperties["keyPassword"] = System.getenv("AVES_KEY_PASSWORD") ?: "<NONE>"
+ keystoreProperties["googleApiKey"] = System.getenv("AVES_GOOGLE_API_KEY") ?: "<NONE>"
+}
+
+kotlin {
+ jvmToolchain 17
+}
+
+android {
+ namespace = 'deckers.thibault.aves'
+ compileSdk = 36
+
+ compileOptions {
+ // enable support for the new language APIs on older devices
+ // e.g. `java/util/function/Supplier` on Android 5.0 (API 21)
+ coreLibraryDesugaringEnabled = true
+ // should match `kotlin.jvmToolchain`
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ defaultConfig {
+ applicationId = packageName
+ minSdk = flutter.minSdkVersion
+ targetSdk = 36
+ versionCode = flutter.versionCode
+ versionName = flutter.versionName
+ manifestPlaceholders = [googleApiKey: keystoreProperties["googleApiKey"] ?: "<NONE>"]
+ multiDexEnabled = true
+ }
+
+ signingConfigs {
+ release {
+ keyAlias keystoreProperties["keyAlias"]
+ keyPassword keystoreProperties["keyPassword"]
+ storeFile keystoreProperties["storeFile"] ? file(keystoreProperties["storeFile"]) : null
+ storePassword keystoreProperties["storePassword"]
+ }
+ }
+
+ flavorDimensions += "store"
+
+ productFlavors {
+ play {
+ // Google Play
+ dimension "store"
+ // generate a universal APK without x86 native libs
+ ext.useNdkAbiFilters = true
+ }
+
+ izzy {
+ // IzzyOnDroid
+ // check offending libraries with `scanapk`
+ // cf https://android.izzysoft.de/articles/named/app-modules-2
+ dimension "store"
+ // generate APK by ABI, but NDK ABI filters are incompatible with split APK generation
+ ext.useNdkAbiFilters = false
+ }
+
+ libre {
+ // F-Droid
+ // check offending libraries with `fdroidserver`
+ // cf https://f-droid.org/en/docs/Submitting_to_F-Droid_Quick_Start_Guide/
+ dimension "store"
+ // generate APK by ABI, but NDK ABI filters are incompatible with split APK generation
+ ext.useNdkAbiFilters = false
+ applicationIdSuffix ".libre"
+ }
+
+ libre_rom {
+ // integration in custom ROM
+ dimension "store"
+ // generate a universal APK without x86 native libs
+ ext.useNdkAbiFilters = true
+ applicationIdSuffix ".libre"
+
+ packagingOptions {
+ // disable compression for native libraries (.so files)
+ jniLibs.useLegacyPackaging false
+ }
+ }
+ }
+
+ buildTypes {
+ debug {
+ applicationIdSuffix ".debug"
+ }
+ profile {
+ applicationIdSuffix ".profile"
+ }
+ release {
+ signingConfig = signingConfigs.release
+ minifyEnabled = true
+ shrinkResources = true
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ }
+
+ applicationVariants.all { variant ->
+ variant.resValue 'string', 'screen_saver_settings_activity', "${applicationId}/${packageName}.ScreenSaverSettingsActivity"
+ variant.resValue 'string', 'search_provider', "${applicationId}.search_provider"
+
+ variant.outputs.each { output ->
+ def baseAbiVersionCode = rootProject.ext.abiCodes.get(output.getFilter('ABI'))
+ if (baseAbiVersionCode != null) {
+ output.versionCodeOverride = variant.versionCode * 100 + baseAbiVersionCode
+ }
+ }
+ }
+
+ android.productFlavors.each { flavor ->
+ def tasks = gradle.startParameter.taskNames.toString().toLowerCase()
+ if (tasks.contains(flavor.name) && flavor.ext.useNdkAbiFilters) {
+ release {
+ // specify architectures, to specifically exclude native libs for x86,
+ // which lead to: UnsatisfiedLinkError...couldn't find "libflutter.so"
+ // cf https://github.com/flutter/flutter/issues/37566#issuecomment-640879500
+ ndk {
+ //noinspection ChromeOsAbiSupport
+ abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86_64'
+ }
+ }
+ }
+ }
+ }
+}
+
+flutter {
+ source '../..'
+}
+
+repositories {
+ maven {
+ url = 'https://jitpack.io'
+ content {
+ includeGroup "com.github.deckerst"
+ includeGroup "com.github.deckerst.mp4parser"
+ }
+ }
+ maven {
+ url = 'https://s3.amazonaws.com/repo.commonsware.com'
+ content {
+ excludeGroupByRegex "com\\.github\\.deckerst.*"
+ }
+ }
+}
+
+dependencies {
+ // cf https://developer.android.com/studio/write/java8-support#library-desugaring
+ coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.5")
+
+ implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2'
+
+ implementation 'androidx.annotation:annotation:1.9.1'
+ implementation "androidx.appcompat:appcompat:1.7.1"
+ implementation 'androidx.core:core-ktx:1.17.0'
+ // `lifecycle-process:2.10.0` requires `minSdkVersion` 23+
+ implementation 'androidx.lifecycle:lifecycle-process:2.9.4'
+ implementation 'androidx.media:media:1.7.1'
+ implementation 'androidx.multidex:multidex:2.0.1'
+ // Jetpack `security-crypto` library is deprecated:
+ // https://developer.android.com/privacy-and-security/cryptography#security-crypto-jetpack-deprecated
+ implementation 'androidx.security:security-crypto:1.1.0'
+ // `work-runtime:2.11.0` requires `minSdkVersion` 23+
+ implementation 'androidx.work:work-runtime:2.10.5'
+
+ implementation 'com.commonsware.cwac:document:0.5.0'
+ implementation 'com.drewnoakes:metadata-extractor:2.19.0'
+ implementation "com.github.bumptech.glide:glide:$glide_version"
+ implementation 'com.google.android.material:material:1.13.0'
+ // SLF4J implementation for `mp4parser`
+ implementation 'org.slf4j:slf4j-simple:2.0.17'
+
+ // forked, built by JitPack:
+ // - https://jitpack.io/p/deckerst/Android-TiffBitmapFactory
+ // - https://jitpack.io/p/deckerst/androidsvg
+ // - https://jitpack.io/p/deckerst/mp4parser
+ // - https://jitpack.io/p/deckerst/pixymeta-android
+ implementation 'com.github.deckerst:Android-TiffBitmapFactory:424b18a4ae'
+ implementation 'com.github.deckerst:androidsvg:c7e58e8e59'
+ implementation 'com.github.deckerst.mp4parser:isoparser:c2898f1832'
+ implementation 'com.github.deckerst.mp4parser:muxer:c2898f1832'
+ implementation 'com.github.deckerst:pixymeta-android:f4513291b7'
+ implementation project(':exifinterface')
+
+ testImplementation 'org.junit.jupiter:junit-jupiter-engine:6.0.1'
+
+ ksp "com.github.bumptech.glide:ksp:$glide_version"
+
+ compileOnly rootProject.findProject(':streams_channel')
+}
+
+if (useCrashlytics) {
+ println("Building flavor with Crashlytics plugin")
+ apply plugin: 'com.google.gms.google-services'
+ apply plugin: 'com.google.firebase.crashlytics'
+}
diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro
new file mode 100644
index 0000000..06e861e
--- /dev/null
+++ b/android/app/proguard-rules.pro
@@ -0,0 +1,6 @@
+-keep class org.beyka.tiffbitmapfactory.**{ *; }
+-keep class org.mp4parser.**{ *; }
+
+# referenced from: com.google.crypto.tink
+-dontwarn com.google.errorprone.annotations.**
+-dontwarn javax.annotation.**
diff --git a/android/app/src/debug/res/values/colors.xml b/android/app/src/debug/res/values/colors.xml
new file mode 100644
index 0000000..023cc20
--- /dev/null
+++ b/android/app/src/debug/res/values/colors.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="ic_launcher_flavour">#815AFA</color>
+</resources> \ No newline at end of file
diff --git a/android/app/src/debug/res/values/strings.xml b/android/app/src/debug/res/values/strings.xml
new file mode 100644
index 0000000..e5c92d3
--- /dev/null
+++ b/android/app/src/debug/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves [Debug]</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/libre/res/values/strings.xml b/android/app/src/libre/res/values/strings.xml
new file mode 100644
index 0000000..b451c08
--- /dev/null
+++ b/android/app/src/libre/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves Libre</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/libreDebug/res/values/strings.xml b/android/app/src/libreDebug/res/values/strings.xml
new file mode 100644
index 0000000..4c84517
--- /dev/null
+++ b/android/app/src/libreDebug/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves Libre [Debug]</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/libreProfile/res/values/strings.xml b/android/app/src/libreProfile/res/values/strings.xml
new file mode 100644
index 0000000..2918b24
--- /dev/null
+++ b/android/app/src/libreProfile/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves Libre [Profile]</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..98fd6f8
--- /dev/null
+++ b/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,350 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:installLocation="auto">
+
+ <uses-feature
+ android:name="android.hardware.touchscreen"
+ android:required="false" />
+ <uses-feature
+ android:name="android.hardware.wifi"
+ android:required="false" />
+ <uses-feature
+ android:name="android.software.leanback"
+ android:required="false" />
+
+ <uses-permission android:name="android.permission.READ_MEDIA_VISUAL_USER_SELECTED" />
+ <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
+ <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
+ <uses-permission
+ android:name="android.permission.READ_EXTERNAL_STORAGE"
+ android:maxSdkVersion="32" />
+ <!--
+ Scoped storage on Android 10 (API 29) is inconvenient because users need to confirm edition on each individual file.
+ So we request `WRITE_EXTERNAL_STORAGE` until Android 10 (API 29), and enable `requestLegacyExternalStorage`
+ -->
+ <uses-permission
+ android:name="android.permission.WRITE_EXTERNAL_STORAGE"
+ android:maxSdkVersion="29"
+ tools:ignore="ScopedStorage" />
+
+ <!-- to access media with original metadata with scoped storage (API >=29) -->
+ <uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />
+ <!-- to provide a foreground service type, as required from Android 14 (API 34) -->
+ <uses-permission
+ android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"
+ android:maxSdkVersion="34"
+ tools:ignore="SystemPermissionTypo" />
+ <uses-permission
+ android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROCESSING"
+ tools:ignore="SystemPermissionTypo" />
+ <!-- TODO TLAD still needed to fetch map tiles / reverse geocoding / else ? check in release mode -->
+ <uses-permission android:name="android.permission.INTERNET" />
+ <!-- from Android 12 (API 31), users can optionally grant access to the media management special permission -->
+ <uses-permission
+ android:name="android.permission.MANAGE_MEDIA"
+ tools:ignore="ProtectedPermissions" />
+ <!-- to show analysis service progress via notification -->
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+ <!-- to change wallpaper -->
+ <uses-permission android:name="android.permission.SET_WALLPAPER" />
+ <!-- TODO TLAD remove this permission when this is fixed: https://github.com/flutter/flutter/issues/42451 -->
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
+
+ <uses-permission
+ android:name="com.android.launcher.permission.INSTALL_SHORTCUT"
+ android:maxSdkVersion="25" />
+
+ <!-- additional permissions added by plugins:
+
+ `{package}.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION` by `androidx.appcompat:appcompat`
+
+ `android.permission.ACCESS_NETWORK_STATE`,
+ `android.permission.FOREGROUND_SERVICE`,
+ `android.permission.RECEIVE_BOOT_COMPLETED`,
+ `android.permission.WAKE_LOCK` by `androidx.work:work-runtime-ktx`, to analyze media in a service
+
+ `android.permission.ACCESS_NETWORK_STATE` by `dev.fluttercommunity.plus.connectivity`, TODO TLAD still needed?
+
+ `android.permission.USE_BIOMETRIC` by `io.flutter.plugins.localauth`, to unlock vaults (API >=28)
+ -->
+
+ <!--
+ allow install on API 21, despite the `minSdk` declared in dependencies:
+ - FFmpegKit for Flutter is from API 24 (when not LTS)
+ -->
+ <uses-sdk tools:overrideLibrary="com.arthenica.ffmpegkit.flutter" />
+
+ <!-- from Android 11 (API 30), we should define <queries> to make other apps visible to this app -->
+ <queries>
+ <intent>
+ <action android:name="android.intent.action.MAIN" />
+ </intent>
+ <!-- necessary to resolve image editor apps that are not visible in the launcher -->
+ <intent>
+ <action android:name="android.intent.action.EDIT" />
+ <data android:mimeType="image/*" />
+ </intent>
+ <!-- necessary to resolve video editor apps that are not visible in the launcher -->
+ <intent>
+ <action android:name="android.intent.action.EDIT" />
+ <data android:mimeType="video/*" />
+ </intent>
+ <!--
+ from Android 11 (API 30), `url_launcher` method `canLaunchUrl()` will return false,
+ if appropriate intents are not declared, cf https://pub.dev/packages/url_launcher#configuration=
+ -->
+ <!-- to open https URLs -->
+ <intent>
+ <action android:name="android.intent.action.VIEW" />
+ <data android:scheme="https" />
+ </intent>
+ </queries>
+
+ <!--
+ as of Flutter v3.22.2, predictive back gesture does not work
+ as expected when extending `FlutterFragmentActivity`
+ so we disable `enableOnBackInvokedCallback`
+ -->
+ <application
+ android:allowBackup="true"
+ android:appCategory="image"
+ android:banner="@drawable/banner"
+ android:dataExtractionRules="@xml/data_extraction_rules"
+ android:enableOnBackInvokedCallback="false"
+ android:fullBackupContent="@xml/full_backup_content"
+ android:fullBackupOnly="true"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:requestLegacyExternalStorage="true"
+ android:roundIcon="@mipmap/ic_launcher_round"
+ android:supportsRtl="true"
+ tools:targetApi="tiramisu">
+ <activity
+ android:name=".MainActivity"
+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
+ android:exported="true"
+ android:hardwareAccelerated="true"
+ android:launchMode="singleTop"
+ android:supportsPictureInPicture="true"
+ android:theme="@style/NormalTheme"
+ android:windowSoftInputMode="adjustResize">
+ <intent-filter>
+ <!-- main entry point, navigating to home page -->
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ <category android:name="android.intent.category.APP_GALLERY" />
+ </intent-filter>
+ <intent-filter tools:ignore="AppLinkUrlError">
+ <!-- viewer for media with no specified scheme -->
+ <action android:name="android.intent.action.GET_CONTENT" />
+ <action android:name="android.intent.action.PICK" />
+ <action android:name="android.intent.action.SEND" />
+ <action android:name="android.intent.action.VIEW" />
+ <action android:name="android.provider.action.REVIEW" />
+ <action android:name="android.provider.action.REVIEW_SECURE" />
+ <action android:name="com.android.camera.action.REVIEW" />
+ <action android:name="com.android.camera.action.SPLIT_SCREEN_REVIEW" />
+
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <category android:name="android.intent.category.OPENABLE" />
+
+ <data android:mimeType="image/*" />
+ <data android:mimeType="video/*" />
+ <data android:mimeType="vnd.android.cursor.dir/image" />
+ <data android:mimeType="vnd.android.cursor.dir/video" />
+
+ <!-- no specified scheme -->
+ </intent-filter>
+ <intent-filter tools:ignore="AppLinkUrlError">
+ <!-- viewer for media with a specified scheme -->
+ <action android:name="android.intent.action.GET_CONTENT" />
+ <action android:name="android.intent.action.PICK" />
+ <action android:name="android.intent.action.SEND" />
+ <action android:name="android.intent.action.VIEW" />
+ <action android:name="android.provider.action.REVIEW" />
+ <action android:name="android.provider.action.REVIEW_SECURE" />
+ <action android:name="com.android.camera.action.REVIEW" />
+ <action android:name="com.android.camera.action.SPLIT_SCREEN_REVIEW" />
+
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <category android:name="android.intent.category.OPENABLE" />
+
+ <data android:mimeType="image/*" />
+ <data android:mimeType="video/*" />
+ <data android:mimeType="vnd.android.cursor.dir/image" />
+ <data android:mimeType="vnd.android.cursor.dir/video" />
+
+ <data android:scheme="content" />
+ <data android:scheme="file" />
+ </intent-filter>
+ <intent-filter>
+ <!-- `geo` URI handling (view on map, or fill location editor) -->
+ <action android:name="android.intent.action.VIEW" />
+
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+
+ <data android:scheme="geo" />
+ </intent-filter>
+ <!--
+ <intent-filter>
+ <action android:name="android.intent.action.EDIT" />
+ <category android:name="android.intent.category.DEFAULT" />
+
+ <data android:mimeType="image/*" />
+ <data android:mimeType="vnd.android.cursor.dir/image" />
+ </intent-filter>
+ -->
+ <intent-filter>
+ <action android:name="android.intent.action.SEARCH" />
+ </intent-filter>
+
+ <!-- Specifies an Android theme to apply to this Activity as soon as
+ the Android process has started. This theme is visible to the user
+ while the Flutter UI initializes. After that, this theme continues
+ to determine the Window background behind the Flutter UI. -->
+ <meta-data
+ android:name="io.flutter.embedding.android.NormalTheme"
+ android:resource="@style/NormalTheme" />
+ <meta-data
+ android:name="android.app.searchable"
+ android:resource="@xml/searchable" />
+ <!-- launch size in desktop environments, like ChromeOS -->
+ <meta-data
+ android:name="WindowManagerPreference:FreeformWindowSize"
+ android:value="maximize" />
+ <meta-data
+ android:name="WindowManagerPreference:FreeformWindowOrientation"
+ android:value="landscape" />
+ </activity>
+
+ <activity
+ android:name=".ScreenSaverSettingsActivity"
+ android:exported="true"
+ android:theme="@style/NormalTheme" />
+
+ <activity
+ android:name=".WallpaperActivity"
+ android:exported="true"
+ android:label="@string/wallpaper"
+ android:theme="@style/NormalTheme">
+ <intent-filter>
+ <action android:name="android.intent.action.ATTACH_DATA" />
+ <category android:name="android.intent.category.DEFAULT" />
+
+ <data android:mimeType="image/*" />
+ <data android:mimeType="video/*" />
+ </intent-filter>
+
+ <intent-filter>
+ <action android:name="android.intent.action.SET_WALLPAPER" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ </activity>
+
+ <!-- exported for Android API 19 launcher to access this activity -->
+ <activity
+ android:name=".HomeWidgetSettingsActivity"
+ android:exported="true"
+ android:theme="@style/NormalTheme">
+ <intent-filter>
+ <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
+ </intent-filter>
+ </activity>
+
+ <receiver
+ android:name=".HomeWidgetProvider"
+ android:exported="false"
+ android:label="@string/app_widget_label">
+ <intent-filter>
+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
+ </intent-filter>
+
+ <meta-data
+ android:name="android.appwidget.provider"
+ android:resource="@xml/app_widget_info" />
+ </receiver>
+
+ <receiver
+ android:name="androidx.media.session.MediaButtonReceiver"
+ android:exported="false">
+ <intent-filter>
+ <action android:name="android.intent.action.MEDIA_BUTTON" />
+ </intent-filter>
+ </receiver>
+
+ <!--
+ anonymous service for analysis worker is specified here to provide service type:
+ - `dataSync` for Android 14 (API 34)
+ - `mediaProcessing` from Android 15 (API 35)
+ -->
+ <service
+ android:name="androidx.work.impl.foreground.SystemForegroundService"
+ android:foregroundServiceType="dataSync|mediaProcessing"
+ tools:node="merge" />
+
+ <service
+ android:name=".MediaPlaybackService"
+ android:exported="false"
+ android:foregroundServiceType="mediaPlayback">
+ <intent-filter>
+ <action android:name="android.media.browse.MediaBrowserService" />
+ </intent-filter>
+ </service>
+
+ <service
+ android:name=".ScreenSaverService"
+ android:exported="true"
+ android:icon="@mipmap/ic_launcher"
+ android:label="@string/app_name"
+ android:permission="android.permission.BIND_DREAM_SERVICE">
+ <intent-filter>
+ <action android:name="android.service.dreams.DreamService" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+
+ <meta-data
+ android:name="android.service.dream"
+ android:resource="@xml/screen_saver" />
+ </service>
+
+ <!-- file provider to share files having a file:// URI -->
+ <provider
+ android:name="androidx.core.content.FileProvider"
+ android:authorities="${applicationId}.file_provider"
+ android:exported="false"
+ android:grantUriPermissions="true">
+ <meta-data
+ android:name="android.support.FILE_PROVIDER_PATHS"
+ android:resource="@xml/provider_paths" />
+ </provider>
+
+ <provider
+ android:name=".SearchSuggestionsProvider"
+ android:authorities="@string/search_provider"
+ android:exported="true"
+ tools:ignore="ExportedContentProvider" />
+
+ <meta-data
+ android:name="com.google.android.geo.API_KEY"
+ android:value="${googleApiKey}" />
+ <meta-data
+ android:name="firebase_crashlytics_collection_enabled"
+ android:value="false" />
+ <!-- Don't delete the meta-data below.
+ This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
+ <meta-data
+ android:name="flutterEmbedding"
+ android:value="2" />
+ <meta-data
+ android:name="io.flutter.embedding.android.EnableImpeller"
+ android:value="false" />
+ </application>
+</manifest>
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/AnalysisWorker.kt b/android/app/src/main/kotlin/deckers/thibault/aves/AnalysisWorker.kt
new file mode 100644
index 0000000..9fa7496
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/AnalysisWorker.kt
@@ -0,0 +1,234 @@
+package deckers.thibault.aves
+
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Build
+import android.util.Log
+import androidx.core.app.NotificationChannelCompat
+import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
+import androidx.work.CoroutineWorker
+import androidx.work.ForegroundInfo
+import androidx.work.WorkInfo
+import androidx.work.WorkManager
+import androidx.work.WorkerParameters
+import app.loup.streams_channel.StreamsChannel
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safeSuspend
+import deckers.thibault.aves.channel.calls.DeviceHandler
+import deckers.thibault.aves.channel.calls.GeocodingHandler
+import deckers.thibault.aves.channel.calls.MediaFetchObjectHandler
+import deckers.thibault.aves.channel.calls.MediaStoreHandler
+import deckers.thibault.aves.channel.calls.MetadataFetchHandler
+import deckers.thibault.aves.channel.calls.StorageHandler
+import deckers.thibault.aves.channel.streams.darttoplatform.ImageByteStreamHandler
+import deckers.thibault.aves.channel.streams.darttoplatform.MediaStoreStreamHandler
+import deckers.thibault.aves.utils.FlutterUtils
+import deckers.thibault.aves.utils.LogUtils
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import kotlinx.coroutines.CancellableContinuation
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.suspendCancellableCoroutine
+import kotlin.coroutines.resume
+import kotlin.coroutines.resumeWithException
+
+class AnalysisWorker(context: Context, parameters: WorkerParameters) : CoroutineWorker(context, parameters) {
+ private val defaultScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ private var workCont: CancellableContinuation<Any?>? = null
+ private var flutterEngine: FlutterEngine? = null
+ private var backgroundChannel: MethodChannel? = null
+
+ override suspend fun doWork(): Result {
+ Log.i(LOG_TAG, "Start analysis worker $id")
+ createNotificationChannel()
+ val foregroundInfo = createForegroundInfo()
+ if (!isStopped) {
+ setForeground(foregroundInfo)
+ suspendCancellableCoroutine { cont ->
+ workCont = cont
+ cont.invokeOnCancellation {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ val stopReasonString = when(stopReason) {
+ WorkInfo.STOP_REASON_CANCELLED_BY_APP -> "CANCELLED_BY_APP"
+ WorkInfo.STOP_REASON_FOREGROUND_SERVICE_TIMEOUT -> "FOREGROUND_SERVICE_TIMEOUT"
+ else -> "[$stopReason]"
+ }
+ Log.i(LOG_TAG, "Analysis worker got cancelled with stopReason=$stopReasonString")
+ } else {
+ Log.i(LOG_TAG, "Analysis worker got cancelled")
+ }
+ stopDartAnalysisService()
+ workCont?.resumeWithException(CancellationException())
+ }
+ onStart()
+ }
+ dispose()
+ }
+ return Result.success()
+ }
+
+ private suspend fun dispose() {
+ Log.i(LOG_TAG, "Clean analysis worker $id")
+ flutterEngine?.let {
+ FlutterUtils.runOnUiThread {
+ it.destroy()
+ }
+ flutterEngine = null
+ }
+ }
+
+ private fun onStart() {
+ runBlocking {
+ FlutterUtils.initFlutterEngine(applicationContext, SHARED_PREFERENCES_KEY, PREF_CALLBACK_HANDLE_KEY) {
+ flutterEngine = it
+ }
+ }
+
+ try {
+ initChannels(applicationContext)
+
+ val preferences = applicationContext.getSharedPreferences(SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE)
+ val entryIdStrings = preferences.getStringSet(PREF_ENTRY_IDS_KEY, null)
+ startDartAnalysisService(entryIdStrings)
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to initialize worker", e)
+ workCont?.resumeWithException(e)
+ }
+ }
+
+ private fun initChannels(context: Context) {
+ val engine = flutterEngine
+ engine ?: throw Exception("Flutter engine is not initialized")
+
+ val messenger = engine.dartExecutor
+
+ // channels for analysis
+
+ // dart -> platform -> dart
+ // - need Context
+ MethodChannel(messenger, DeviceHandler.CHANNEL).setMethodCallHandler(DeviceHandler(context))
+ MethodChannel(messenger, GeocodingHandler.CHANNEL).setMethodCallHandler(GeocodingHandler(context))
+ MethodChannel(messenger, MediaFetchObjectHandler.CHANNEL).setMethodCallHandler(MediaFetchObjectHandler(context))
+ MethodChannel(messenger, MediaStoreHandler.CHANNEL).setMethodCallHandler(MediaStoreHandler(context))
+ MethodChannel(messenger, MetadataFetchHandler.CHANNEL).setMethodCallHandler(MetadataFetchHandler(context))
+ MethodChannel(messenger, StorageHandler.CHANNEL).setMethodCallHandler(StorageHandler(context))
+
+ // result streaming: dart -> platform ->->-> dart
+ // - need Context
+ StreamsChannel(messenger, ImageByteStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ImageByteStreamHandler(context, args) }
+ StreamsChannel(messenger, MediaStoreStreamHandler.CHANNEL).setStreamHandlerFactory { args -> MediaStoreStreamHandler(context, args) }
+
+ // channel for service management
+ backgroundChannel = MethodChannel(messenger, BACKGROUND_CHANNEL).apply {
+ setMethodCallHandler { call, result -> onMethodCall(call, result) }
+ }
+ }
+
+ private fun startDartAnalysisService(entryIdStrings: Set<String>?) {
+ runBlocking {
+ FlutterUtils.runOnUiThread {
+ backgroundChannel?.invokeMethod(
+ "start", hashMapOf(
+ "entryIds" to entryIdStrings?.map { Integer.parseUnsignedInt(it) }?.toList(),
+ "force" to inputData.getBoolean(KEY_FORCE, false),
+ )
+ )
+ }
+ }
+ }
+
+ private fun stopDartAnalysisService() {
+ runBlocking {
+ FlutterUtils.runOnUiThread {
+ backgroundChannel?.invokeMethod("stop", null)
+ }
+ }
+ }
+
+ private fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "initialized" -> {
+ Log.d(LOG_TAG, "Analysis background channel is ready")
+ result.success(null)
+ }
+
+ "updateNotification" -> defaultScope.launch { safeSuspend(call, result, ::updateNotification) }
+
+ "stop" -> {
+ workCont?.takeIf { it.isActive }?.resume(null)
+ result.success(null)
+ }
+
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun createNotificationChannel() {
+ val channel = NotificationChannelCompat.Builder(NOTIFICATION_CHANNEL, NotificationManagerCompat.IMPORTANCE_LOW)
+ .setName(applicationContext.getText(R.string.analysis_channel_name))
+ .setShowBadge(false)
+ .build()
+ NotificationManagerCompat.from(applicationContext).createNotificationChannel(channel)
+ }
+
+ private fun createForegroundInfo(title: String? = null, message: String? = null): ForegroundInfo {
+ val pendingIntentFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
+ } else {
+ PendingIntent.FLAG_UPDATE_CURRENT
+ }
+ val openAppIntent = Intent(applicationContext, MainActivity::class.java).let {
+ PendingIntent.getActivity(applicationContext, MainActivity.OPEN_FROM_ANALYSIS_SERVICE, it, pendingIntentFlags)
+ }
+ val stopAction = NotificationCompat.Action.Builder(
+ R.drawable.ic_outline_stop_24,
+ applicationContext.getString(R.string.analysis_notification_action_stop),
+ WorkManager.getInstance(applicationContext).createCancelPendingIntent(id)
+ ).build()
+ val contentTitle = title ?: applicationContext.getText(R.string.analysis_notification_default_title)
+ val notification = NotificationCompat.Builder(applicationContext, NOTIFICATION_CHANNEL)
+ .setContentTitle(contentTitle)
+ .setTicker(contentTitle)
+ .setContentText(message)
+ .setSmallIcon(R.drawable.ic_notification)
+ .setOngoing(true)
+ .setContentIntent(openAppIntent)
+ .addAction(stopAction)
+ .build()
+ // from Android 14 (API 34), foreground service type is mandatory for long-running workers:
+ // https://developer.android.com/guide/background/persistent/how-to/long-running
+ return when {
+ Build.VERSION.SDK_INT >= 35 -> ForegroundInfo(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROCESSING)
+ Build.VERSION.SDK_INT == 34 -> ForegroundInfo(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
+ else -> ForegroundInfo(NOTIFICATION_ID, notification)
+ }
+ }
+
+ private suspend fun updateNotification(call: MethodCall, result: MethodChannel.Result) {
+ val title = call.argument<String>("title")
+ val message = call.argument<String>("message")
+ setForeground(createForegroundInfo(title, message))
+ result.success(null)
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<AnalysisWorker>()
+ private const val BACKGROUND_CHANNEL = "deckers.thibault/aves/analysis_service_background"
+ const val SHARED_PREFERENCES_KEY = "analysis_service"
+ const val PREF_CALLBACK_HANDLE_KEY = "callback_handle"
+ const val PREF_ENTRY_IDS_KEY = "entry_ids"
+
+ const val NOTIFICATION_CHANNEL = "analysis"
+ const val NOTIFICATION_ID = 1
+
+ const val KEY_FORCE = "force"
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetConfigureActivity.kt b/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetConfigureActivity.kt
new file mode 100644
index 0000000..dad5ed8
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetConfigureActivity.kt
@@ -0,0 +1,66 @@
+package deckers.thibault.aves
+
+import android.appwidget.AppWidgetManager
+import android.content.Intent
+import android.os.Bundle
+import deckers.thibault.aves.model.FieldMap
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.MethodChannel
+
+class HomeWidgetSettingsActivity : MainActivity() {
+ private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID
+
+ public override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+
+ // cancel if user does not complete widget setup
+ setResult(RESULT_CANCELED)
+
+ intent.extras?.let {
+ appWidgetId = it.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)
+ intentDataMap = extractIntentData(intent)
+ }
+
+ if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
+ finish()
+ return
+ }
+ }
+
+ override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
+ super.configureFlutterEngine(flutterEngine)
+
+ val messenger = flutterEngine.dartExecutor
+ MethodChannel(messenger, CHANNEL).setMethodCallHandler { call, result ->
+ when (call.method) {
+ "configure" -> {
+ result.success(null)
+ saveWidget()
+ }
+ else -> result.notImplemented()
+ }
+ }
+ }
+
+ private fun saveWidget() {
+ val appWidgetManager = AppWidgetManager.getInstance(this)
+ val widgetInfo = appWidgetManager.getAppWidgetOptions(appWidgetId)
+ HomeWidgetProvider().onAppWidgetOptionsChanged(this, appWidgetManager, appWidgetId, widgetInfo)
+
+ val intent = Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
+ setResult(RESULT_OK, intent)
+ finish()
+ }
+
+ override fun extractIntentData(intent: Intent?): FieldMap {
+ return hashMapOf(
+ INTENT_DATA_KEY_ACTION to INTENT_ACTION_WIDGET_SETTINGS,
+ INTENT_DATA_KEY_WIDGET_ID to appWidgetId,
+ )
+ }
+
+ companion object {
+ private const val CHANNEL = "deckers.thibault/aves/widget_configure"
+ }
+}
+
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetProvider.kt
new file mode 100644
index 0000000..0d0b2ba
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/HomeWidgetProvider.kt
@@ -0,0 +1,342 @@
+package deckers.thibault.aves
+
+import android.app.PendingIntent
+import android.appwidget.AppWidgetManager
+import android.appwidget.AppWidgetProvider
+import android.content.Context
+import android.content.Intent
+import android.content.res.Configuration
+import android.graphics.Bitmap
+import android.os.Build
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import android.util.SizeF
+import android.widget.RemoteViews
+import androidx.core.graphics.createBitmap
+import androidx.core.net.toUri
+import app.loup.streams_channel.StreamsChannel
+import deckers.thibault.aves.channel.calls.DeviceHandler
+import deckers.thibault.aves.channel.calls.MediaFetchObjectHandler
+import deckers.thibault.aves.channel.calls.MediaStoreHandler
+import deckers.thibault.aves.channel.calls.StorageHandler
+import deckers.thibault.aves.channel.streams.darttoplatform.ImageByteStreamHandler
+import deckers.thibault.aves.channel.streams.darttoplatform.MediaStoreStreamHandler
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.ContextUtils.devicePixelRatio
+import deckers.thibault.aves.utils.FlutterUtils
+import deckers.thibault.aves.utils.LogUtils
+import io.flutter.FlutterInjector
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.embedding.engine.dart.DartExecutor
+import io.flutter.plugin.common.MethodChannel
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import java.nio.ByteBuffer
+import kotlin.coroutines.Continuation
+import kotlin.coroutines.resume
+import kotlin.coroutines.resumeWithException
+import kotlin.coroutines.suspendCoroutine
+import kotlin.math.roundToInt
+
+class HomeWidgetProvider : AppWidgetProvider() {
+ private val defaultScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
+ Log.d(LOG_TAG, "Widget onUpdate widgetIds=${appWidgetIds.contentToString()}")
+ val pendingResult = goAsync()
+ defaultScope.launch {
+ for (widgetId in appWidgetIds) {
+ val widgetInfo = appWidgetManager.getAppWidgetOptions(widgetId)
+
+ val backgroundProps = getProps(context, widgetId, widgetInfo, drawEntryImage = false)
+ updateWidgetImage(context, appWidgetManager, widgetId, backgroundProps)
+
+ val imageProps = getProps(context, widgetId, widgetInfo, drawEntryImage = true, reuseEntry = false)
+ updateWidgetImage(context, appWidgetManager, widgetId, imageProps)
+ }
+ try {
+ pendingResult?.finish()
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to finish update for widgetIds=${appWidgetIds.contentToString()}", e)
+ }
+ }
+ }
+
+ override fun onAppWidgetOptionsChanged(context: Context, appWidgetManager: AppWidgetManager?, widgetId: Int, widgetInfo: Bundle?) {
+ Log.d(LOG_TAG, "Widget onAppWidgetOptionsChanged widgetId=$widgetId")
+ appWidgetManager ?: return
+ widgetInfo ?: return
+
+ if (imageByteFetchJob != null) {
+ imageByteFetchJob?.cancel()
+ }
+ imageByteFetchJob = defaultScope.launch {
+ delay(500)
+ val imageProps = getProps(context, widgetId, widgetInfo, drawEntryImage = true, reuseEntry = true)
+ updateWidgetImage(context, appWidgetManager, widgetId, imageProps)
+ }
+ }
+
+ private fun getWidgetSizesDip(context: Context, widgetInfo: Bundle): List<SizeF> {
+ var sizes: List<SizeF>? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ widgetInfo.getParcelableArrayList(AppWidgetManager.OPTION_APPWIDGET_SIZES, SizeF::class.java)
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ @Suppress("deprecation")
+ widgetInfo.getParcelableArrayList(AppWidgetManager.OPTION_APPWIDGET_SIZES)
+ } else {
+ null
+ }
+
+ if (sizes.isNullOrEmpty()) {
+ val isPortrait = context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT
+ val widthKey = if (isPortrait) AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH else AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH
+ val heightKey = if (isPortrait) AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT else AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT
+ val widthDip = widgetInfo.getInt(widthKey)
+ val heightDip = widgetInfo.getInt(heightKey)
+ sizes = listOf(SizeF(widthDip.toFloat(), heightDip.toFloat()))
+ }
+
+ return sizes
+ }
+
+ private suspend fun getProps(
+ context: Context,
+ widgetId: Int,
+ widgetInfo: Bundle,
+ drawEntryImage: Boolean,
+ reuseEntry: Boolean = false,
+ ): FieldMap? {
+ val sizesDip = getWidgetSizesDip(context, widgetInfo)
+ if (sizesDip.isEmpty()) return null
+
+ val sizeDip = sizesDip.first()
+ if (sizeDip.width == 0f || sizeDip.height == 0f) return null
+
+ val sizesDipMap = sizesDip.map { size -> hashMapOf("widthDip" to size.width, "heightDip" to size.height) }
+ val isNightModeOn = (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
+
+ val params = hashMapOf(
+ "widgetId" to widgetId,
+ "sizesDip" to sizesDipMap,
+ "devicePixelRatio" to context.devicePixelRatio(),
+ "drawEntryImage" to drawEntryImage,
+ "reuseEntry" to reuseEntry,
+ "isSystemThemeDark" to isNightModeOn,
+ ).apply {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ put("cornerRadiusPx", context.resources.getDimension(android.R.dimen.system_app_widget_background_radius))
+ }
+ }
+
+ initFlutterEngine(context)
+ try {
+ val props = suspendCoroutine { cont ->
+ defaultScope.launch {
+ FlutterUtils.runOnUiThread {
+ tryDrawWidget(params, cont, 0)
+ }
+ }
+ }
+ @Suppress("unchecked_cast")
+ return props as FieldMap?
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to draw widget for widgetId=$widgetId sizesPx=$sizesDip", e)
+ }
+ return null
+ }
+
+ private fun tryDrawWidget(params: HashMap<String, Any>, cont: Continuation<Any?>, drawRetry: Int) {
+ val messenger = flutterEngine!!.dartExecutor
+ val channel = MethodChannel(messenger, WIDGET_DRAW_CHANNEL)
+ channel.invokeMethod("drawWidget", params, object : MethodChannel.Result {
+ override fun success(result: Any?) {
+ cont.resume(result)
+ }
+
+ override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
+ cont.resumeWithException(Exception("$errorCode: $errorMessage\n$errorDetails"))
+ }
+
+ override fun notImplemented() {
+ if (drawRetry > DRAW_RETRY_MAX) {
+ cont.resumeWithException(Exception("not implemented"))
+ } else {
+ Handler(Looper.getMainLooper()).postDelayed({
+ tryDrawWidget(params, cont, drawRetry + 1)
+ }, 2000L)
+ }
+ }
+ })
+ }
+
+ private fun updateWidgetImage(
+ context: Context,
+ appWidgetManager: AppWidgetManager,
+ widgetId: Int,
+ props: FieldMap?,
+ ) {
+ props ?: return
+
+ val bytesBySizeDip = (props["bytesBySizeDip"] as List<*>?)?.mapNotNull {
+ if (it is Map<*, *>) {
+ val widthDip = (it["widthDip"] as Number?)?.toFloat()
+ val heightDip = (it["heightDip"] as Number?)?.toFloat()
+ val bytes = it["bytes"] as ByteArray?
+ if (widthDip != null && heightDip != null && bytes != null) {
+ Pair(SizeF(widthDip, heightDip), bytes)
+ } else null
+ } else null
+ }
+ val updateOnTap = props["updateOnTap"] as Boolean?
+ if (bytesBySizeDip == null || updateOnTap == null) {
+ Log.e(LOG_TAG, "missing arguments")
+ return
+ }
+
+ if (bytesBySizeDip.isEmpty()) {
+ Log.e(LOG_TAG, "empty image list")
+ return
+ }
+
+ val bitmaps = ArrayList<Bitmap>()
+
+ fun createRemoteViewsForSize(
+ context: Context,
+ widgetId: Int,
+ sizeDip: SizeF,
+ bytes: ByteArray,
+ updateOnTap: Boolean,
+ ): RemoteViews? {
+ val density = context.devicePixelRatio()
+ val widthPx = (sizeDip.width * density).roundToInt()
+ val heightPx = (sizeDip.height * density).roundToInt()
+
+ try {
+ val bitmap = createBitmap(widthPx, heightPx, Bitmap.Config.ARGB_8888).also {
+ bitmaps.add(it)
+ it.copyPixelsFromBuffer(ByteBuffer.wrap(bytes))
+ }
+
+ val pendingIntent = if (updateOnTap) buildUpdateIntent(context, widgetId) else buildOpenAppIntent(context, widgetId)
+
+ return RemoteViews(context.packageName, R.layout.app_widget).apply {
+ setImageViewBitmap(R.id.widget_img, bitmap)
+ setOnClickPendingIntent(R.id.widget_img, pendingIntent)
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to draw widget", e)
+ }
+ return null
+ }
+
+ try {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ // multiple rendering for all possible sizes
+ val views = RemoteViews(
+ bytesBySizeDip.associateBy(
+ { (sizeDip, _) -> sizeDip },
+ { (sizeDip, bytes) -> createRemoteViewsForSize(context, widgetId, sizeDip, bytes, updateOnTap) },
+ ).filterValues { it != null }.mapValues { (_, view) -> view!! }
+ )
+ appWidgetManager.updateAppWidget(widgetId, views)
+ } else {
+ // single rendering
+ val (sizeDip, bytes) = bytesBySizeDip.first()
+ val views = createRemoteViewsForSize(context, widgetId, sizeDip, bytes, updateOnTap)
+ appWidgetManager.updateAppWidget(widgetId, views)
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to draw widget", e)
+ } finally {
+ bitmaps.forEach { it.recycle() }
+ bitmaps.clear()
+ }
+ }
+
+ private fun buildUpdateIntent(context: Context, widgetId: Int): PendingIntent {
+ val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE, "widget://$widgetId".toUri(), context, HomeWidgetProvider::class.java)
+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, intArrayOf(widgetId))
+
+ return PendingIntent.getBroadcast(
+ context,
+ 0,
+ intent,
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ } else {
+ PendingIntent.FLAG_UPDATE_CURRENT
+ }
+ )
+ }
+
+ private fun buildOpenAppIntent(context: Context, widgetId: Int): PendingIntent {
+ // set a unique URI to prevent the intent (and its extras) from being shared by different widgets
+ val intent = Intent(MainActivity.INTENT_ACTION_WIDGET_OPEN, "widget://$widgetId".toUri(), context, MainActivity::class.java)
+ .putExtra(MainActivity.EXTRA_KEY_WIDGET_ID, widgetId)
+
+ return PendingIntent.getActivity(
+ context,
+ 0,
+ intent,
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ } else {
+ PendingIntent.FLAG_UPDATE_CURRENT
+ }
+ )
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<HomeWidgetProvider>()
+ private const val WIDGET_DART_ENTRYPOINT = "widgetMain"
+ private const val WIDGET_DRAW_CHANNEL = "deckers.thibault/aves/widget_draw"
+ private const val DRAW_RETRY_MAX = 5
+
+ private var flutterEngine: FlutterEngine? = null
+ private var imageByteFetchJob: Job? = null
+
+ private suspend fun initFlutterEngine(context: Context) {
+ if (flutterEngine != null) return
+
+ FlutterUtils.runOnUiThread {
+ flutterEngine = FlutterEngine(context.applicationContext)
+ }
+ initChannels(context)
+
+ flutterEngine!!.apply {
+ if (!dartExecutor.isExecutingDart) {
+ val appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath()
+ val entrypoint = DartExecutor.DartEntrypoint(appBundlePathOverride, WIDGET_DART_ENTRYPOINT)
+ FlutterUtils.runOnUiThread {
+ dartExecutor.executeDartEntrypoint(entrypoint)
+ }
+ }
+ }
+ }
+
+ private fun initChannels(context: Context) {
+ val engine = flutterEngine
+ engine ?: throw Exception("Flutter engine is not initialized")
+
+ val messenger = engine.dartExecutor
+
+ // dart -> platform -> dart
+ // - need Context
+ MethodChannel(messenger, DeviceHandler.CHANNEL).setMethodCallHandler(DeviceHandler(context))
+ MethodChannel(messenger, MediaStoreHandler.CHANNEL).setMethodCallHandler(MediaStoreHandler(context))
+ MethodChannel(messenger, MediaFetchObjectHandler.CHANNEL).setMethodCallHandler(MediaFetchObjectHandler(context))
+ MethodChannel(messenger, StorageHandler.CHANNEL).setMethodCallHandler(StorageHandler(context))
+
+ // result streaming: dart -> platform ->->-> dart
+ // - need Context
+ StreamsChannel(messenger, ImageByteStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ImageByteStreamHandler(context, args) }
+ StreamsChannel(messenger, MediaStoreStreamHandler.CHANNEL).setStreamHandlerFactory { args -> MediaStoreStreamHandler(context, args) }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/MainActivity.kt b/android/app/src/main/kotlin/deckers/thibault/aves/MainActivity.kt
new file mode 100644
index 0000000..84d56fd
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/MainActivity.kt
@@ -0,0 +1,656 @@
+package deckers.thibault.aves
+
+import android.annotation.SuppressLint
+import android.app.KeyguardManager
+import android.app.SearchManager
+import android.appwidget.AppWidgetManager
+import android.content.ClipData
+import android.content.Intent
+import android.content.res.Configuration
+import android.net.Uri
+import android.os.Build
+import android.os.Bundle
+import android.os.Handler
+import android.os.Looper
+import android.os.TransactionTooLargeException
+import android.provider.MediaStore
+import android.util.Log
+import androidx.annotation.RequiresApi
+import androidx.core.content.pm.ShortcutInfoCompat
+import androidx.core.content.pm.ShortcutManagerCompat
+import androidx.core.graphics.drawable.IconCompat
+import androidx.core.net.toUri
+import app.loup.streams_channel.StreamsChannel
+import deckers.thibault.aves.channel.calls.AccessibilityHandler
+import deckers.thibault.aves.channel.calls.AnalysisHandler
+import deckers.thibault.aves.channel.calls.AppAdapterHandler
+import deckers.thibault.aves.channel.calls.AppProfileHandler
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.channel.calls.DebugHandler
+import deckers.thibault.aves.channel.calls.DeviceHandler
+import deckers.thibault.aves.channel.calls.EmbeddedDataHandler
+import deckers.thibault.aves.channel.calls.GeocodingHandler
+import deckers.thibault.aves.channel.calls.GlobalSearchHandler
+import deckers.thibault.aves.channel.calls.HomeWidgetHandler
+import deckers.thibault.aves.channel.calls.MediaEditHandler
+import deckers.thibault.aves.channel.calls.MediaFetchObjectHandler
+import deckers.thibault.aves.channel.calls.MediaSessionHandler
+import deckers.thibault.aves.channel.calls.MediaStoreHandler
+import deckers.thibault.aves.channel.calls.MetadataEditHandler
+import deckers.thibault.aves.channel.calls.MetadataFetchHandler
+import deckers.thibault.aves.channel.calls.SecurityHandler
+import deckers.thibault.aves.channel.calls.StorageHandler
+import deckers.thibault.aves.channel.calls.WallpaperHandler
+import deckers.thibault.aves.channel.calls.window.ActivityWindowHandler
+import deckers.thibault.aves.channel.calls.window.WindowHandler
+import deckers.thibault.aves.channel.streams.darttoplatform.ActivityResultStreamHandler
+import deckers.thibault.aves.channel.streams.darttoplatform.ImageByteStreamHandler
+import deckers.thibault.aves.channel.streams.darttoplatform.ImageOpStreamHandler
+import deckers.thibault.aves.channel.streams.darttoplatform.MediaStoreStreamHandler
+import deckers.thibault.aves.channel.streams.platformtodart.AnalysisStreamHandler
+import deckers.thibault.aves.channel.streams.platformtodart.ErrorStreamHandler
+import deckers.thibault.aves.channel.streams.platformtodart.IntentStreamHandler
+import deckers.thibault.aves.channel.streams.platformtodart.MediaCommandStreamHandler
+import deckers.thibault.aves.channel.streams.platformtodart.MediaStoreChangeStreamHandler
+import deckers.thibault.aves.channel.streams.platformtodart.SettingsChangeStreamHandler
+import deckers.thibault.aves.channel.streams.platformtodart.WindowChangeStreamHandler
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.anyCauseIs
+import deckers.thibault.aves.utils.getParcelableExtraCompat
+import io.flutter.embedding.android.FlutterFragmentActivity
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.EventChannel
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import java.util.concurrent.CompletableFuture
+import java.util.concurrent.ConcurrentHashMap
+
+// `FlutterFragmentActivity` because of local auth plugin
+open class MainActivity : FlutterFragmentActivity() {
+ private val defaultScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ private lateinit var mediaStoreChangeStreamHandler: MediaStoreChangeStreamHandler
+ private lateinit var settingsChangeStreamHandler: SettingsChangeStreamHandler
+ private lateinit var windowChangeStreamHandler: WindowChangeStreamHandler
+ private lateinit var intentStreamHandler: IntentStreamHandler
+ private lateinit var analysisStreamHandler: AnalysisStreamHandler
+ internal lateinit var intentDataMap: MutableMap<String, Any?>
+ private lateinit var analysisHandler: AnalysisHandler
+ private lateinit var mediaSessionHandler: MediaSessionHandler
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ Log.i(LOG_TAG, "onCreate intent=$intent")
+ logExtras(intent, "onCreate")
+
+// StrictMode.setThreadPolicy(
+// StrictMode.ThreadPolicy.Builder()
+// .detectAll()
+// .penaltyLog()
+// .build()
+// )
+// StrictMode.setVmPolicy(
+// StrictMode.VmPolicy.Builder()
+// .detectAll()
+// .penaltyLog()
+// .build()
+// )
+ super.onCreate(savedInstanceState)
+ }
+
+ private fun logExtras(intent: Intent?, method: String) {
+ try {
+ intent?.extras?.takeUnless { it.isEmpty }?.let {
+ Log.i(LOG_TAG, "$method intent extras=$it")
+ }
+ } catch (e: Exception) {
+ // accessing extras may fail if their type comes from sending app
+ Log.w(LOG_TAG, "failed to parse extras", e)
+ }
+ }
+
+ override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
+ super.configureFlutterEngine(flutterEngine)
+
+ val messenger = flutterEngine.dartExecutor
+
+ // notification: platform -> dart
+ analysisStreamHandler = AnalysisStreamHandler().apply {
+ EventChannel(messenger, AnalysisStreamHandler.CHANNEL).setStreamHandler(this)
+ }
+ errorStreamHandler = ErrorStreamHandler().apply {
+ EventChannel(messenger, ErrorStreamHandler.CHANNEL).setStreamHandler(this)
+ }
+ mediaStoreChangeStreamHandler = MediaStoreChangeStreamHandler(this).apply {
+ EventChannel(messenger, MediaStoreChangeStreamHandler.CHANNEL).setStreamHandler(this)
+ }
+ settingsChangeStreamHandler = SettingsChangeStreamHandler(this).apply {
+ EventChannel(messenger, SettingsChangeStreamHandler.CHANNEL).setStreamHandler(this)
+ }
+ windowChangeStreamHandler = WindowChangeStreamHandler().apply {
+ EventChannel(messenger, WindowChangeStreamHandler.CHANNEL).setStreamHandler(this)
+ }
+ val mediaCommandStreamHandler = MediaCommandStreamHandler().apply {
+ EventChannel(messenger, MediaCommandStreamHandler.CHANNEL).setStreamHandler(this)
+ }
+
+ // dart -> platform -> dart
+ // - need Context
+ analysisHandler = AnalysisHandler(this, ::onAnalysisCompleted)
+ mediaSessionHandler = MediaSessionHandler(this, mediaCommandStreamHandler)
+ MethodChannel(messenger, AnalysisHandler.CHANNEL).setMethodCallHandler(analysisHandler)
+ MethodChannel(messenger, AppAdapterHandler.CHANNEL).setMethodCallHandler(AppAdapterHandler(this))
+ MethodChannel(messenger, DebugHandler.CHANNEL).setMethodCallHandler(DebugHandler(this))
+ MethodChannel(messenger, DeviceHandler.CHANNEL).setMethodCallHandler(DeviceHandler(this))
+ MethodChannel(messenger, EmbeddedDataHandler.CHANNEL).setMethodCallHandler(EmbeddedDataHandler(this))
+ MethodChannel(messenger, GeocodingHandler.CHANNEL).setMethodCallHandler(GeocodingHandler(this))
+ MethodChannel(messenger, GlobalSearchHandler.CHANNEL).setMethodCallHandler(GlobalSearchHandler(this))
+ MethodChannel(messenger, HomeWidgetHandler.CHANNEL).setMethodCallHandler(HomeWidgetHandler(this))
+ MethodChannel(messenger, MediaFetchObjectHandler.CHANNEL).setMethodCallHandler(MediaFetchObjectHandler(this))
+ MethodChannel(messenger, MediaSessionHandler.CHANNEL).setMethodCallHandler(mediaSessionHandler)
+ MethodChannel(messenger, MediaStoreHandler.CHANNEL).setMethodCallHandler(MediaStoreHandler(this))
+ MethodChannel(messenger, MetadataFetchHandler.CHANNEL).setMethodCallHandler(MetadataFetchHandler(this))
+ MethodChannel(messenger, SecurityHandler.CHANNEL).setMethodCallHandler(SecurityHandler(this))
+ MethodChannel(messenger, StorageHandler.CHANNEL).setMethodCallHandler(StorageHandler(this))
+ // - need ContextWrapper
+ MethodChannel(messenger, AccessibilityHandler.CHANNEL).setMethodCallHandler(AccessibilityHandler(this))
+ MethodChannel(messenger, MediaEditHandler.CHANNEL).setMethodCallHandler(MediaEditHandler(this))
+ MethodChannel(messenger, MetadataEditHandler.CHANNEL).setMethodCallHandler(MetadataEditHandler(this))
+ MethodChannel(messenger, WallpaperHandler.CHANNEL).setMethodCallHandler(WallpaperHandler(this))
+ // - need Activity
+ MethodChannel(messenger, AppProfileHandler.CHANNEL).setMethodCallHandler(AppProfileHandler(this))
+ MethodChannel(messenger, WindowHandler.CHANNEL).setMethodCallHandler(ActivityWindowHandler(this))
+
+ // result streaming: dart -> platform ->->-> dart
+ // - need Context
+ StreamsChannel(messenger, ImageByteStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ImageByteStreamHandler(this, args) }
+ StreamsChannel(messenger, MediaStoreStreamHandler.CHANNEL).setStreamHandlerFactory { args -> MediaStoreStreamHandler(this, args) }
+ // - need Activity
+ StreamsChannel(messenger, ImageOpStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ImageOpStreamHandler(this, args) }
+ StreamsChannel(messenger, ActivityResultStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ActivityResultStreamHandler(this, args) }
+
+ // intent handling
+ // notification: platform -> dart
+ intentStreamHandler = IntentStreamHandler().apply {
+ EventChannel(messenger, IntentStreamHandler.CHANNEL).setStreamHandler(this)
+ }
+ // intent detail & result: dart -> platform
+ intentDataMap = extractIntentData(intent)
+ MethodChannel(messenger, INTENT_CHANNEL).setMethodCallHandler { call, result ->
+ when (call.method) {
+ "getIntentData" -> {
+ result.success(intentDataMap)
+ intentDataMap.clear()
+ }
+
+ "submitPickedItems" -> safe(call, result, ::submitPickedItems)
+ "submitPickedCollectionFilters" -> submitPickedCollectionFilters(call)
+ }
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
+ defaultScope.launch { setupShortcuts() }
+ }
+ }
+
+ override fun onStart() {
+ Log.i(LOG_TAG, "onStart")
+ super.onStart()
+ analysisHandler.attachToActivity()
+
+ // as of Flutter v3.0.1, the window `viewInsets` and `viewPadding`
+ // are incorrect on startup in some environments (e.g. API 29 emulator),
+ // so we manually request to apply the insets to update the window metrics
+ Handler(Looper.getMainLooper()).postDelayed({
+ window.decorView.requestApplyInsets()
+ }, 100)
+ }
+
+ override fun onStop() {
+ Log.i(LOG_TAG, "onStop")
+ super.onStop()
+ }
+
+ override fun onDestroy() {
+ Log.i(LOG_TAG, "onDestroy")
+ mediaSessionHandler.dispose()
+ mediaStoreChangeStreamHandler.dispose()
+ settingsChangeStreamHandler.dispose()
+ try {
+ super.onDestroy()
+ } catch (e: Exception) {
+ // on Android 11, app may crash as follows:
+ // `Fatal Exception:`
+ // `java.lang.RuntimeException: Unable to destroy activity {deckers.thibault.aves/deckers.thibault.aves.MainActivity}:`
+ // `java.lang.IllegalArgumentException: NetworkCallback was not registered`
+ // related to this error:
+ // `Package android does not belong to 10162`
+ // cf https://issuetracker.google.com/issues/175055271
+ Log.e(LOG_TAG, "failed while destroying activity", e)
+ }
+ }
+
+ override fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean) {
+ super.onMultiWindowModeChanged(isInMultiWindowMode)
+ notifyWindowModeChanged()
+ }
+
+ override fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean, newConfig: Configuration) {
+ super.onMultiWindowModeChanged(isInMultiWindowMode, newConfig)
+ notifyWindowModeChanged()
+ }
+
+ override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) {
+ super.onPictureInPictureModeChanged(isInPictureInPictureMode)
+ notifyWindowModeChanged()
+ }
+
+ override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) {
+ super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig)
+ notifyWindowModeChanged()
+ }
+
+ private fun notifyWindowModeChanged() = windowChangeStreamHandler.notifyWindowModeChange()
+
+ override fun onNewIntent(intent: Intent) {
+ Log.i(LOG_TAG, "onNewIntent intent=$intent")
+ logExtras(intent, "onNewIntent")
+ super.onNewIntent(intent)
+ intentStreamHandler.notifyNewIntent(extractIntentData(intent))
+ }
+
+ @Deprecated("Deprecated in Java")
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ Log.i(LOG_TAG, "onActivityResult requestCode=$requestCode resultCode=$resultCode data=$data")
+ logExtras(data, "onActivityResult")
+ super.onActivityResult(requestCode, resultCode, data)
+ when (requestCode) {
+ DOCUMENT_TREE_ACCESS_REQUEST -> onDocumentTreeAccessResult(requestCode, resultCode, data)
+ DELETE_SINGLE_PERMISSION_REQUEST,
+ MEDIA_WRITE_BULK_PERMISSION_REQUEST -> onScopedStoragePermissionResult(resultCode)
+
+ CREATE_FILE_REQUEST,
+ OPEN_FILE_REQUEST -> onStorageAccessResult(requestCode, data?.data)
+
+ PICK_COLLECTION_FILTERS_REQUEST -> onCollectionFiltersPickResult(resultCode, data)
+ EDIT_REQUEST -> onEditResult(resultCode, data)
+ }
+ }
+
+ private fun onCollectionFiltersPickResult(resultCode: Int, intent: Intent?) {
+ val filters = if (resultCode == RESULT_OK) extractFiltersFromIntent(intent) else null
+ pendingCollectionFilterPickHandler?.let { it(filters) }
+ }
+
+ private fun onEditResult(resultCode: Int, intent: Intent?) {
+ val fields: FieldMap? = if (resultCode == RESULT_OK) hashMapOf(
+ "uri" to intent?.data?.toString(),
+ "mimeType" to intent?.type,
+ ) else null
+ pendingEditIntentHandler?.let { it(fields) }
+ }
+
+ private fun onDocumentTreeAccessResult(requestCode: Int, resultCode: Int, intent: Intent?) {
+ val treeUri = intent?.data
+ if (resultCode != RESULT_OK || treeUri == null) {
+ onStorageAccessResult(requestCode, null)
+ return
+ }
+
+ val canPersist = (intent.flags and Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0
+ @SuppressLint("WrongConstant")
+ if (canPersist) {
+ // save access permissions across reboots
+ val takeFlags = (intent.flags
+ and (Intent.FLAG_GRANT_READ_URI_PERMISSION
+ or Intent.FLAG_GRANT_WRITE_URI_PERMISSION))
+ try {
+ contentResolver.takePersistableUriPermission(treeUri, takeFlags)
+ } catch (e: SecurityException) {
+ Log.w(LOG_TAG, "failed to take persistable URI permission for uri=$treeUri", e)
+ }
+ }
+
+ // resume pending action
+ onStorageAccessResult(requestCode, treeUri)
+ }
+
+ private fun onScopedStoragePermissionResult(resultCode: Int) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ pendingScopedStoragePermissionCompleter?.complete(resultCode == RESULT_OK)
+ }
+ }
+
+ open fun extractIntentData(intent: Intent?): FieldMap {
+ when (val action = intent?.action) {
+ Intent.ACTION_MAIN -> {
+ return hashMapOf(
+ INTENT_DATA_KEY_PAGE to intent.getStringExtra(EXTRA_KEY_PAGE),
+ INTENT_DATA_KEY_FILTERS to extractFiltersFromIntent(intent),
+ INTENT_DATA_KEY_EXPLORER_PATH to intent.getStringExtra(EXTRA_KEY_EXPLORER_PATH),
+ )
+ }
+
+ Intent.ACTION_VIEW,
+ Intent.ACTION_SEND,
+ MediaStore.ACTION_REVIEW,
+ MediaStore.ACTION_REVIEW_SECURE,
+ "com.android.camera.action.REVIEW",
+ "com.android.camera.action.SPLIT_SCREEN_REVIEW" -> {
+ (intent.data ?: intent.getParcelableExtraCompat<Uri>(Intent.EXTRA_STREAM))?.let { uri ->
+ if (uri.scheme == "geo") {
+ return hashMapOf(
+ INTENT_DATA_KEY_ACTION to INTENT_ACTION_VIEW_GEO,
+ INTENT_DATA_KEY_URI to uri.toString(),
+ INTENT_DATA_KEY_FILTERS to extractFiltersFromIntent(intent),
+ )
+ }
+
+ // MIME type is optional
+ val type = intent.type ?: intent.resolveType(this)
+ val fields = hashMapOf<String, Any?>(
+ INTENT_DATA_KEY_ACTION to INTENT_ACTION_VIEW,
+ INTENT_DATA_KEY_MIME_TYPE to type,
+ INTENT_DATA_KEY_URI to uri.toString(),
+ )
+
+ val keyguardManager = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
+ val isLocked = keyguardManager.isKeyguardLocked
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
+ setShowWhenLocked(isLocked)
+ }
+ if (isLocked) {
+ // device is locked, so access to content is limited to intent URI by default
+ fields[INTENT_DATA_KEY_SECURE_URIS] = listOf(uri.toString())
+ }
+
+ if (action == MediaStore.ACTION_REVIEW_SECURE) {
+ val uris = ArrayList<String>()
+ intent.clipData?.let { clipData ->
+ for (i in 0 until clipData.itemCount) {
+ clipData.getItemAt(i).uri?.let { uris.add(it.toString()) }
+ }
+ }
+ if (uris.isNotEmpty()) {
+ fields[INTENT_DATA_KEY_SECURE_URIS] = uris
+ }
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && intent.hasExtra(MediaStore.EXTRA_BRIGHTNESS)) {
+ fields[INTENT_DATA_KEY_BRIGHTNESS] = intent.getFloatExtra(MediaStore.EXTRA_BRIGHTNESS, 0f)
+ }
+
+ return fields
+ }
+ }
+
+ Intent.ACTION_EDIT -> {
+ (intent.data ?: intent.getParcelableExtraCompat<Uri>(Intent.EXTRA_STREAM))?.let { uri ->
+ // MIME type is optional
+ val type = intent.type ?: intent.resolveType(this)
+ return hashMapOf(
+ INTENT_DATA_KEY_ACTION to INTENT_ACTION_EDIT,
+ INTENT_DATA_KEY_MIME_TYPE to type,
+ INTENT_DATA_KEY_URI to uri.toString(),
+ )
+ }
+ }
+
+ Intent.ACTION_GET_CONTENT, Intent.ACTION_PICK -> {
+ return hashMapOf(
+ INTENT_DATA_KEY_ACTION to INTENT_ACTION_PICK_ITEMS,
+ INTENT_DATA_KEY_MIME_TYPE to intent.type,
+ INTENT_DATA_KEY_MIME_TYPES to intent.getStringArrayExtra(Intent.EXTRA_MIME_TYPES)?.toList(),
+ INTENT_DATA_KEY_ALLOW_MULTIPLE to intent.getBooleanExtra(Intent.EXTRA_ALLOW_MULTIPLE, false),
+ )
+ }
+
+ Intent.ACTION_SEARCH -> {
+ val viewUri = intent.dataString
+ return if (viewUri != null) hashMapOf(
+ INTENT_DATA_KEY_ACTION to INTENT_ACTION_VIEW,
+ INTENT_DATA_KEY_MIME_TYPE to intent.getStringExtra(SearchManager.EXTRA_DATA_KEY),
+ INTENT_DATA_KEY_URI to viewUri,
+ ) else hashMapOf(
+ INTENT_DATA_KEY_ACTION to INTENT_ACTION_SEARCH,
+ INTENT_DATA_KEY_QUERY to intent.getStringExtra(SearchManager.QUERY),
+ )
+ }
+
+ INTENT_ACTION_PICK_COLLECTION_FILTERS -> {
+ val initialFilters = extractFiltersFromIntent(intent)
+ return hashMapOf(
+ INTENT_DATA_KEY_ACTION to action,
+ INTENT_DATA_KEY_FILTERS to initialFilters,
+ )
+ }
+
+ INTENT_ACTION_WIDGET_OPEN -> {
+ val widgetId = intent.getIntExtra(EXTRA_KEY_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)
+ if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
+ return hashMapOf(
+ INTENT_DATA_KEY_ACTION to action,
+ INTENT_DATA_KEY_WIDGET_ID to widgetId,
+ )
+ }
+ }
+
+ Intent.ACTION_RUN -> {
+ // flutter run
+ }
+
+ else -> {
+ Log.w(LOG_TAG, "unhandled intent action=${intent?.action}")
+ }
+ }
+ return HashMap()
+ }
+
+ private fun extractFiltersFromIntent(intent: Intent?): List<String>? {
+ intent ?: return null
+
+ val filters = intent.getStringArrayExtra(EXTRA_KEY_FILTERS_ARRAY)?.toList()
+ if (filters != null) return filters
+
+ // fallback for shortcuts created on API <26
+ val filterString = intent.getStringExtra(EXTRA_KEY_FILTERS_STRING)
+ if (filterString != null) {
+ return filterString.split(EXTRA_STRING_ARRAY_SEPARATOR)
+ }
+
+ return null
+ }
+
+ open fun submitPickedItems(call: MethodCall, result: MethodChannel.Result) {
+ val pickedUris = call.argument<List<String>>("uris")
+ if (pickedUris.isNullOrEmpty()) {
+ setResult(RESULT_CANCELED)
+ // move code triggering `Binder` call off the main thread
+ defaultScope.launch { finish() }
+ return
+ }
+
+ val toUri = { uriString: String -> AppAdapterHandler.getShareableUri(this@MainActivity, uriString.toUri()) }
+ val intent = Intent().apply {
+ val firstUri = toUri(pickedUris.first())
+ if (pickedUris.size == 1) {
+ data = firstUri
+ } else {
+ clipData = ClipData.newUri(contentResolver, null, firstUri).apply {
+ pickedUris.drop(1).forEach {
+ addItem(ClipData.Item(toUri(it)))
+ }
+ }
+ }
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
+ }
+ // move code triggering `Binder` call off the main thread
+ defaultScope.launch {
+ submitPickedItemsIntent(intent, result)
+ }
+ }
+
+ private fun submitPickedItemsIntent(intent: Intent, result: MethodChannel.Result) {
+ try {
+ setResult(RESULT_OK, intent)
+ finish()
+ } catch (e: Exception) {
+ setResult(RESULT_CANCELED)
+ if (e is SecurityException && intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0) {
+ // in some environments, providing the write flag yields a `SecurityException`:
+ // "UID XXXX does not have permission to content://XXXX"
+ // so we retry without it
+ Log.i(LOG_TAG, "retry submitting picked items without FLAG_GRANT_WRITE_URI_PERMISSION")
+ intent.flags = intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION.inv()
+ submitPickedItemsIntent(intent, result)
+ } else if (e.anyCauseIs<TransactionTooLargeException>()) {
+ result.error("submitPickedItems-large", "transaction too large with ${intent.clipData?.itemCount} URIs", e)
+ } else {
+ result.error("submitPickedItems-exception", "failed to pick ${intent.clipData?.itemCount} URIs", e)
+ }
+ }
+ }
+
+ private fun submitPickedCollectionFilters(call: MethodCall) {
+ val filters = call.argument<List<String>>("filters")
+ if (filters != null) {
+ val intent = Intent()
+ .putExtra(EXTRA_KEY_FILTERS_ARRAY, filters.toTypedArray())
+ .putExtra(EXTRA_KEY_FILTERS_STRING, filters.joinToString(EXTRA_STRING_ARRAY_SEPARATOR))
+ setResult(RESULT_OK, intent)
+ } else {
+ setResult(RESULT_CANCELED)
+ }
+ finish()
+ }
+
+ @RequiresApi(Build.VERSION_CODES.N_MR1)
+ private fun setupShortcuts() {
+ // do not use 'route' as extra key, as the Flutter framework acts on it
+
+ // shortcut adaptive icons are placed in `mipmap`, not `drawable`,
+ // so that foreground is rendered at the intended scale
+ val supportAdaptiveIcon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
+
+ val search = ShortcutInfoCompat.Builder(this, "search")
+ .setShortLabel(getString(R.string.search_shortcut_short_label))
+ .setIcon(IconCompat.createWithResource(this, if (supportAdaptiveIcon) R.mipmap.ic_shortcut_search else R.drawable.ic_shortcut_search))
+ .setIntent(
+ Intent(Intent.ACTION_MAIN, null, this, MainActivity::class.java)
+ .putExtra(EXTRA_KEY_PAGE, SEARCH_PAGE_ROUTE_NAME)
+ )
+ .build()
+
+ val map = ShortcutInfoCompat.Builder(this, "map")
+ .setShortLabel(getString(R.string.map_shortcut_short_label))
+ .setIcon(IconCompat.createWithResource(this, if (supportAdaptiveIcon) R.mipmap.ic_shortcut_map else R.drawable.ic_shortcut_map))
+ .setIntent(
+ Intent(Intent.ACTION_MAIN, null, this, MainActivity::class.java)
+ .putExtra(EXTRA_KEY_PAGE, MAP_PAGE_ROUTE_NAME)
+ )
+ .build()
+
+ val videos = ShortcutInfoCompat.Builder(this, "videos")
+ .setShortLabel(getString(R.string.videos_shortcut_short_label))
+ .setIcon(IconCompat.createWithResource(this, if (supportAdaptiveIcon) R.mipmap.ic_shortcut_movie else R.drawable.ic_shortcut_movie))
+ .setIntent(
+ Intent(Intent.ACTION_MAIN, null, this, MainActivity::class.java)
+ .putExtra(EXTRA_KEY_PAGE, COLLECTION_PAGE_ROUTE_NAME)
+ .putExtra("filters", arrayOf("{\"type\":\"mime\",\"mime\":\"video/*\"}"))
+ )
+ .build()
+
+ val shortcutInfoList = listOf(videos, search, map)
+ ShortcutManagerCompat.setDynamicShortcuts(this, shortcutInfoList)
+ Log.i(LOG_TAG, "set shortcuts: ${shortcutInfoList.joinToString(", ") { v -> v.id }}")
+ }
+
+ private fun onAnalysisCompleted() {
+ analysisStreamHandler.notifyCompletion()
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<MainActivity>()
+ const val INTENT_CHANNEL = "deckers.thibault/aves/intent"
+ const val EXTRA_STRING_ARRAY_SEPARATOR = "###"
+ const val DOCUMENT_TREE_ACCESS_REQUEST = 1
+ const val OPEN_FROM_ANALYSIS_SERVICE = 2
+ const val CREATE_FILE_REQUEST = 3
+ const val OPEN_FILE_REQUEST = 4
+ const val DELETE_SINGLE_PERMISSION_REQUEST = 5
+ const val MEDIA_WRITE_BULK_PERMISSION_REQUEST = 6
+ const val PICK_COLLECTION_FILTERS_REQUEST = 7
+ const val EDIT_REQUEST = 8
+
+ const val INTENT_ACTION_EDIT = "edit"
+ const val INTENT_ACTION_PICK_ITEMS = "pick_items"
+ const val INTENT_ACTION_PICK_COLLECTION_FILTERS = "pick_collection_filters"
+ const val INTENT_ACTION_SCREEN_SAVER = "screen_saver"
+ const val INTENT_ACTION_SCREEN_SAVER_SETTINGS = "screen_saver_settings"
+ const val INTENT_ACTION_SEARCH = "search"
+ const val INTENT_ACTION_SET_WALLPAPER = "set_wallpaper"
+ const val INTENT_ACTION_VIEW = "view"
+ const val INTENT_ACTION_VIEW_GEO = "view_geo"
+ const val INTENT_ACTION_WIDGET_OPEN = "widget_open"
+ const val INTENT_ACTION_WIDGET_SETTINGS = "widget_settings"
+
+ const val INTENT_DATA_KEY_ACTION = "action"
+ const val INTENT_DATA_KEY_ALLOW_MULTIPLE = "allowMultiple"
+ const val INTENT_DATA_KEY_BRIGHTNESS = "brightness"
+ const val INTENT_DATA_KEY_EXPLORER_PATH = "explorerPath"
+ const val INTENT_DATA_KEY_FILTERS = "filters"
+ const val INTENT_DATA_KEY_MIME_TYPE = "mimeType"
+ const val INTENT_DATA_KEY_MIME_TYPES = "mimeTypes"
+ const val INTENT_DATA_KEY_PAGE = "page"
+ const val INTENT_DATA_KEY_QUERY = "query"
+ const val INTENT_DATA_KEY_SECURE_URIS = "secureUris"
+ const val INTENT_DATA_KEY_URI = "uri"
+ const val INTENT_DATA_KEY_WIDGET_ID = "widgetId"
+
+ const val EXTRA_KEY_PAGE = "page"
+ const val EXTRA_KEY_EXPLORER_PATH = "explorerPath"
+ const val EXTRA_KEY_FILTERS_ARRAY = "filters"
+ const val EXTRA_KEY_FILTERS_STRING = "filtersString"
+ const val EXTRA_KEY_WIDGET_ID = "widgetId"
+
+ // dart page routes
+ const val COLLECTION_PAGE_ROUTE_NAME = "/collection"
+ const val ENTRY_VIEWER_PAGE_ROUTE_NAME = "/viewer"
+ const val EXPLORER_PAGE_ROUTE_NAME = "/explorer"
+ const val MAP_PAGE_ROUTE_NAME = "/map"
+ const val SEARCH_PAGE_ROUTE_NAME = "/search"
+
+ // request code to pending runnable
+ val pendingStorageAccessResultHandlers = ConcurrentHashMap<Int, PendingStorageAccessResultHandler>()
+
+ var pendingScopedStoragePermissionCompleter: CompletableFuture<Boolean>? = null
+
+ var pendingCollectionFilterPickHandler: ((filters: List<String>?) -> Unit)? = null
+
+ var pendingEditIntentHandler: ((fields: FieldMap?) -> Unit)? = null
+
+ private fun onStorageAccessResult(requestCode: Int, uri: Uri?) {
+ Log.i(LOG_TAG, "onStorageAccessResult with requestCode=$requestCode, uri=$uri")
+ val handler = pendingStorageAccessResultHandlers.remove(requestCode) ?: return
+ if (uri != null) {
+ handler.onGranted(uri)
+ } else {
+ handler.onDenied()
+ }
+ }
+
+ private var errorStreamHandler: ErrorStreamHandler? = null
+
+ fun notifyError(error: String) {
+ Log.e(LOG_TAG, "notifyError error=$error")
+ errorStreamHandler?.notifyError(error)
+ }
+ }
+}
+
+// onGranted: user selected a directory/file (with no guarantee that it matches the requested `path`)
+// onDenied: user cancelled
+data class PendingStorageAccessResultHandler(val path: String?, val onGranted: (uri: Uri) -> Unit, val onDenied: () -> Unit)
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/MediaPlaybackService.kt b/android/app/src/main/kotlin/deckers/thibault/aves/MediaPlaybackService.kt
new file mode 100644
index 0000000..ed97c54
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/MediaPlaybackService.kt
@@ -0,0 +1,18 @@
+package deckers.thibault.aves
+
+import android.os.Bundle
+import android.support.v4.media.MediaBrowserCompat
+import androidx.media.MediaBrowserServiceCompat
+
+// dummy service to handle media button events
+// when there is no active media sessions
+class MediaPlaybackService : MediaBrowserServiceCompat() {
+ override fun onGetRoot(clientPackageName: String, clientUid: Int, rootHints: Bundle?): BrowserRoot? {
+ return null
+ }
+
+ override fun onLoadChildren(parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) {
+ val children = mutableListOf<MediaBrowserCompat.MediaItem>()
+ result.sendResult(children)
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverService.kt b/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverService.kt
new file mode 100644
index 0000000..d65e708
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverService.kt
@@ -0,0 +1,155 @@
+package deckers.thibault.aves
+
+import android.service.dreams.DreamService
+import android.util.Log
+import android.view.View
+import app.loup.streams_channel.StreamsChannel
+import deckers.thibault.aves.channel.calls.AccessibilityHandler
+import deckers.thibault.aves.channel.calls.DeviceHandler
+import deckers.thibault.aves.channel.calls.EmbeddedDataHandler
+import deckers.thibault.aves.channel.calls.MediaFetchObjectHandler
+import deckers.thibault.aves.channel.calls.MediaSessionHandler
+import deckers.thibault.aves.channel.calls.MediaStoreHandler
+import deckers.thibault.aves.channel.calls.MetadataFetchHandler
+import deckers.thibault.aves.channel.calls.StorageHandler
+import deckers.thibault.aves.channel.calls.window.ServiceWindowHandler
+import deckers.thibault.aves.channel.calls.window.WindowHandler
+import deckers.thibault.aves.channel.streams.darttoplatform.ImageByteStreamHandler
+import deckers.thibault.aves.channel.streams.darttoplatform.MediaStoreStreamHandler
+import deckers.thibault.aves.channel.streams.platformtodart.MediaCommandStreamHandler
+import deckers.thibault.aves.utils.LogUtils
+import io.flutter.FlutterInjector
+import io.flutter.embedding.android.FlutterActivity
+import io.flutter.embedding.android.FlutterSurfaceView
+import io.flutter.embedding.android.FlutterView
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.embedding.engine.dart.DartExecutor.DartEntrypoint
+import io.flutter.embedding.engine.plugins.util.GeneratedPluginRegister
+import io.flutter.plugin.common.EventChannel
+import io.flutter.plugin.common.MethodChannel
+
+// for FlutterView-level integration, cf https://docs.flutter.dev/development/add-to-app/android/add-flutter-view
+class ScreenSaverService : DreamService() {
+ private var flutterEngine: FlutterEngine? = null
+ private var flutterView: FlutterView? = null
+ private lateinit var mediaSessionHandler: MediaSessionHandler
+
+ override fun onAttachedToWindow() {
+ Log.i(LOG_TAG, "onAttachedToWindow")
+ super.onAttachedToWindow()
+ initDream()
+ createEngine()
+ setContentView(createView())
+ }
+
+ override fun onDreamingStarted() {
+ Log.i(LOG_TAG, "onDreamingStarted")
+ super.onDreamingStarted()
+ onStart()
+ }
+
+ override fun onDreamingStopped() {
+ Log.i(LOG_TAG, "onDreamingStopped")
+ release()
+ super.onDreamingStopped()
+ }
+
+ override fun onDetachedFromWindow() {
+ Log.i(LOG_TAG, "onDetachedFromWindow")
+ destroyView()
+ super.onDetachedFromWindow()
+ }
+
+ private fun initDream() {
+ isInteractive = false
+ isFullscreen = true
+ }
+
+ private fun createEngine() {
+ flutterEngine = flutterEngine ?: FlutterEngine(this, null, false)
+ GeneratedPluginRegister.registerGeneratedPlugins(flutterEngine!!)
+ initChannels()
+ }
+
+ private fun createView(): View {
+ flutterView = FlutterView(this, FlutterSurfaceView(this)).apply {
+ id = FlutterActivity.FLUTTER_VIEW_ID
+ attachToFlutterEngine(flutterEngine!!)
+ }
+ return flutterView!!
+ }
+
+ private fun destroyView() {
+ flutterEngine?.lifecycleChannel?.appIsDetached()
+ flutterView?.detachFromFlutterEngine()
+ }
+
+ private fun release() {
+ destroyView()
+ mediaSessionHandler.dispose()
+ flutterEngine = null
+ flutterView = null
+ }
+
+ private fun onStart() {
+ flutterEngine!!.apply {
+ if (!dartExecutor.isExecutingDart) {
+ navigationChannel.setInitialRoute(DEFAULT_INITIAL_ROUTE)
+ val appBundlePathOverride = FlutterInjector.instance().flutterLoader().findAppBundlePath()
+ val entrypoint = DartEntrypoint(appBundlePathOverride, DEFAULT_DART_ENTRYPOINT)
+ dartExecutor.executeDartEntrypoint(entrypoint)
+ }
+ lifecycleChannel.appIsResumed()
+ }
+ }
+
+ private fun initChannels() {
+ val messenger = flutterEngine!!.dartExecutor
+
+ // notification: platform -> dart
+ val mediaCommandStreamHandler = MediaCommandStreamHandler().apply {
+ EventChannel(messenger, MediaCommandStreamHandler.CHANNEL).setStreamHandler(this)
+ }
+
+ // dart -> platform -> dart
+ // - need Context
+ mediaSessionHandler = MediaSessionHandler(this, mediaCommandStreamHandler)
+ MethodChannel(messenger, DeviceHandler.CHANNEL).setMethodCallHandler(DeviceHandler(this))
+ MethodChannel(messenger, EmbeddedDataHandler.CHANNEL).setMethodCallHandler(EmbeddedDataHandler(this))
+ MethodChannel(messenger, MediaFetchObjectHandler.CHANNEL).setMethodCallHandler(MediaFetchObjectHandler(this))
+ MethodChannel(messenger, MediaSessionHandler.CHANNEL).setMethodCallHandler(mediaSessionHandler)
+ MethodChannel(messenger, MediaStoreHandler.CHANNEL).setMethodCallHandler(MediaStoreHandler(this))
+ MethodChannel(messenger, MetadataFetchHandler.CHANNEL).setMethodCallHandler(MetadataFetchHandler(this))
+ MethodChannel(messenger, StorageHandler.CHANNEL).setMethodCallHandler(StorageHandler(this))
+ // - need ContextWrapper
+ MethodChannel(messenger, AccessibilityHandler.CHANNEL).setMethodCallHandler(AccessibilityHandler(this))
+ // - need Service
+ MethodChannel(messenger, WindowHandler.CHANNEL).setMethodCallHandler(ServiceWindowHandler(this))
+
+ // result streaming: dart -> platform ->->-> dart
+ // - need Context
+ StreamsChannel(messenger, ImageByteStreamHandler.CHANNEL).setStreamHandlerFactory { args -> ImageByteStreamHandler(this, args) }
+ StreamsChannel(messenger, MediaStoreStreamHandler.CHANNEL).setStreamHandlerFactory { args -> MediaStoreStreamHandler(this, args) }
+
+ // intent handling
+ // detail fetch: dart -> platform
+ MethodChannel(messenger, MainActivity.INTENT_CHANNEL).setMethodCallHandler { call, result ->
+ when (call.method) {
+ "getIntentData" -> {
+ result.success(intentDataMap)
+ }
+ }
+ }
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<ScreenSaverService>()
+ private val intentDataMap: Map<String, Any?> = hashMapOf(
+ MainActivity.INTENT_DATA_KEY_ACTION to MainActivity.INTENT_ACTION_SCREEN_SAVER,
+ )
+
+ // from `FlutterActivityLaunchConfigs`
+ const val DEFAULT_DART_ENTRYPOINT = "main"
+ const val DEFAULT_INITIAL_ROUTE = "/"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverSettingsActivity.kt b/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverSettingsActivity.kt
new file mode 100644
index 0000000..2d7e070
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/ScreenSaverSettingsActivity.kt
@@ -0,0 +1,12 @@
+package deckers.thibault.aves
+
+import android.content.Intent
+import deckers.thibault.aves.model.FieldMap
+
+class ScreenSaverSettingsActivity : MainActivity() {
+ override fun extractIntentData(intent: Intent?): FieldMap {
+ return hashMapOf(
+ INTENT_DATA_KEY_ACTION to INTENT_ACTION_SCREEN_SAVER_SETTINGS,
+ )
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/SearchSuggestionsProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/SearchSuggestionsProvider.kt
new file mode 100644
index 0000000..e182f56
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/SearchSuggestionsProvider.kt
@@ -0,0 +1,147 @@
+package deckers.thibault.aves
+
+import android.app.SearchManager
+import android.content.ContentProvider
+import android.content.ContentValues
+import android.content.Context
+import android.database.Cursor
+import android.database.MatrixCursor
+import android.net.Uri
+import android.os.Build
+import android.text.format.DateFormat
+import android.util.Log
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.ContextUtils.resourceUri
+import deckers.thibault.aves.utils.FlutterUtils
+import deckers.thibault.aves.utils.LogUtils
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.MethodChannel
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import java.util.Locale
+import kotlin.coroutines.resume
+import kotlin.coroutines.resumeWithException
+import kotlin.coroutines.suspendCoroutine
+
+class SearchSuggestionsProvider : ContentProvider() {
+ private val defaultScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? {
+ return selectionArgs?.firstOrNull()?.let { query ->
+ // Samsung Finder does not support:
+ // - resource ID as value for SUGGEST_COLUMN_ICON_1
+ // - SUGGEST_COLUMN_ICON_2
+ // - SUGGEST_COLUMN_RESULT_CARD_IMAGE
+ val columns = arrayOf(
+ SearchManager.SUGGEST_COLUMN_INTENT_DATA,
+ SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA,
+ SearchManager.SUGGEST_COLUMN_CONTENT_TYPE,
+ SearchManager.SUGGEST_COLUMN_TEXT_1,
+ SearchManager.SUGGEST_COLUMN_TEXT_2,
+ SearchManager.SUGGEST_COLUMN_ICON_1,
+ )
+
+ val matrixCursor = MatrixCursor(columns)
+ context?.let { context ->
+ // shortcut adaptive icons are placed in `mipmap`, not `drawable`,
+ // so that foreground is rendered at the intended scale
+ val supportAdaptiveIcon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
+
+ val searchShortcutTitle = "${context.resources.getString(R.string.search_shortcut_short_label)} $query"
+ val searchShortcutIcon = context.resourceUri(if (supportAdaptiveIcon) R.mipmap.ic_shortcut_search else R.drawable.ic_shortcut_search)
+ matrixCursor.addRow(arrayOf(null, null, null, searchShortcutTitle, null, searchShortcutIcon))
+
+ runBlocking {
+ getSuggestions(context, query).forEach {
+ val data = it["data"]
+ val mimeType = it["mimeType"]
+ val title = it["title"]
+ val subtitle = it["subtitle"]
+ val iconUri = it["iconUri"]
+ matrixCursor.addRow(arrayOf(data, mimeType, mimeType, title, subtitle, iconUri))
+ }
+ }
+ }
+ matrixCursor
+ }
+ }
+
+ private suspend fun getSuggestions(context: Context, query: String): List<FieldMap> {
+ if (flutterEngine == null) {
+ FlutterUtils.initFlutterEngine(context, SHARED_PREFERENCES_KEY, CALLBACK_HANDLE_KEY) {
+ flutterEngine = it
+ }
+ }
+
+ val engine = flutterEngine
+ engine ?: throw Exception("Flutter engine is not initialized")
+
+ val messenger = engine.dartExecutor
+ val backgroundChannel = MethodChannel(messenger, BACKGROUND_CHANNEL).apply {
+ setMethodCallHandler { call, result ->
+ when (call.method) {
+ "initialized" -> {
+ Log.d(LOG_TAG, "background channel is ready")
+ result.success(null)
+ }
+ else -> result.notImplemented()
+ }
+ }
+ }
+
+ try {
+ return suspendCoroutine { cont ->
+ defaultScope.launch {
+ FlutterUtils.runOnUiThread {
+ backgroundChannel.invokeMethod("getSuggestions", hashMapOf(
+ "query" to query,
+ "locale" to Locale.getDefault().toString(),
+ "use24hour" to DateFormat.is24HourFormat(context),
+ ), object : MethodChannel.Result {
+ override fun success(result: Any?) {
+ @Suppress("unchecked_cast")
+ cont.resume(result as List<FieldMap>)
+ }
+
+ override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
+ cont.resumeWithException(Exception("$errorCode: $errorMessage\n$errorDetails"))
+ }
+
+ override fun notImplemented() {
+ cont.resumeWithException(Exception("not implemented"))
+ }
+ })
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to get suggestions", e)
+ return ArrayList()
+ }
+ }
+
+ override fun onCreate(): Boolean = true
+
+ override fun getType(uri: Uri): String? = null
+
+ override fun insert(uri: Uri, values: ContentValues?): Uri =
+ throw UnsupportedOperationException("`insert` is not supported by this content provider")
+
+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int =
+ throw UnsupportedOperationException("`delete` is not supported by this content provider")
+
+ override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int =
+ throw UnsupportedOperationException("`update` is not supported by this content provider")
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<SearchSuggestionsProvider>()
+ private const val BACKGROUND_CHANNEL = "deckers.thibault/aves/global_search_background"
+ const val SHARED_PREFERENCES_KEY = "platform_search"
+ const val CALLBACK_HANDLE_KEY = "callback_handle"
+
+ private var flutterEngine: FlutterEngine? = null
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/WallpaperActivity.kt b/android/app/src/main/kotlin/deckers/thibault/aves/WallpaperActivity.kt
new file mode 100644
index 0000000..e06aea9
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/WallpaperActivity.kt
@@ -0,0 +1,56 @@
+package deckers.thibault.aves
+
+import android.content.Intent
+import android.net.Uri
+import androidx.core.net.toUri
+import deckers.thibault.aves.channel.calls.AppAdapterHandler
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.getParcelableExtraCompat
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+
+class WallpaperActivity : MainActivity() {
+ private var originalIntent: String? = null
+
+ override fun extractIntentData(intent: Intent?): FieldMap {
+ if (intent != null) {
+ when (intent.action) {
+ Intent.ACTION_ATTACH_DATA, Intent.ACTION_SET_WALLPAPER -> {
+ (intent.data ?: intent.getParcelableExtraCompat<Uri>(Intent.EXTRA_STREAM))?.let { uri ->
+ // MIME type is optional
+ val type = intent.type ?: intent.resolveType(this)
+ return hashMapOf(
+ INTENT_DATA_KEY_ACTION to INTENT_ACTION_SET_WALLPAPER,
+ INTENT_DATA_KEY_MIME_TYPE to type,
+ INTENT_DATA_KEY_URI to uri.toString(),
+ )
+ }
+
+ // if the media URI is not provided we need to pick one first
+ originalIntent = intent.action
+ intent.action = Intent.ACTION_PICK
+ }
+ }
+ }
+
+ return super.extractIntentData(intent)
+ }
+
+ override fun submitPickedItems(call: MethodCall, result: MethodChannel.Result) {
+ if (originalIntent != null) {
+ val pickedUris = call.argument<List<String>>("uris")
+ if (!pickedUris.isNullOrEmpty()) {
+ val toUri = { uriString: String -> AppAdapterHandler.getShareableUri(this, uriString.toUri()) }
+ onNewIntent(Intent().apply {
+ action = originalIntent
+ data = toUri(pickedUris.first())
+ })
+ } else {
+ setResult(RESULT_CANCELED)
+ finish()
+ }
+ } else {
+ super.submitPickedItems(call, result)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AccessibilityHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AccessibilityHandler.kt
new file mode 100644
index 0000000..0e61c1f
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AccessibilityHandler.kt
@@ -0,0 +1,107 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.Context
+import android.content.ContextWrapper
+import android.content.res.Configuration
+import android.os.Build
+import android.provider.Settings
+import android.util.Log
+import android.view.ViewConfiguration
+import android.view.accessibility.AccessibilityManager
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.utils.LogUtils
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+
+class AccessibilityHandler(private val contextWrapper: ContextWrapper) : MethodCallHandler {
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "areAnimationsRemoved" -> safe(call, result, ::areAnimationsRemoved)
+ "getLongPressTimeout" -> safe(call, result, ::getLongPressTimeout)
+ "hasRecommendedTimeouts" -> safe(call, result, ::hasRecommendedTimeouts)
+ "getRecommendedTimeoutMillis" -> safe(call, result, ::getRecommendedTimeoutMillis)
+ "shouldUseBoldFont" -> safe(call, result, ::shouldUseBoldFont)
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun areAnimationsRemoved(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ var removed = false
+ try {
+ removed = Settings.Global.getFloat(contextWrapper.contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE) == 0f
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get settings with error=${e.message}", null)
+ }
+ result.success(removed)
+ }
+
+ private fun getLongPressTimeout(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ result.success(ViewConfiguration.getLongPressTimeout())
+ }
+
+ private fun hasRecommendedTimeouts(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
+ }
+
+ private fun getRecommendedTimeoutMillis(call: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
+ result.error("getRecommendedTimeoutMillis-sdk", "unsupported SDK version=${Build.VERSION.SDK_INT}", null)
+ return
+ }
+
+ val originalTimeoutMillis = call.argument<Int>("originalTimeoutMillis")
+ val content = call.argument<List<String>>("content")
+ if (originalTimeoutMillis == null || content == null) {
+ result.error("getRecommendedTimeoutMillis-args", "missing arguments", null)
+ return
+ }
+
+ var uiContentFlags = 0
+ content.forEach {
+ uiContentFlags = when (it) {
+ "controls" -> uiContentFlags or AccessibilityManager.FLAG_CONTENT_CONTROLS
+ "icons" -> uiContentFlags or AccessibilityManager.FLAG_CONTENT_ICONS
+ "text" -> uiContentFlags or AccessibilityManager.FLAG_CONTENT_TEXT
+ else -> {
+ result.error("getRecommendedTimeoutMillis-flag", "unsupported UI content flag=$it", null)
+ return
+ }
+ }
+ }
+
+ val am = contextWrapper.getSystemService(Context.ACCESSIBILITY_SERVICE) as? AccessibilityManager
+ if (am == null) {
+ result.error("getRecommendedTimeoutMillis-service", "failed to get accessibility manager", null)
+ return
+ }
+
+ val millis = am.getRecommendedTimeoutMillis(originalTimeoutMillis, uiContentFlags)
+ result.success(millis)
+ }
+
+ // Flutter v3.4 already checks the system `Configuration.fontWeightAdjustment` to update `MediaQuery`
+ // but we need to also check the non-standard Samsung field `bf` representing the bold font toggle
+ private fun shouldUseBoldFont(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ var shouldBold = false
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ val config = contextWrapper.resources.configuration
+ val fontWeightAdjustment = config.fontWeightAdjustment
+ shouldBold = if (fontWeightAdjustment != Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED && fontWeightAdjustment != 0) {
+ fontWeightAdjustment >= BOLD_TEXT_WEIGHT_ADJUSTMENT
+ } else {
+ // fallback to Samsung non-standard field
+ Regex(" bf=([01]) ").find(config.toString())?.groups?.get(1)?.value == "1"
+ }
+ }
+ result.success(shouldBold)
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<AccessibilityHandler>()
+ const val CHANNEL = "deckers.thibault/aves/accessibility"
+
+ // match Flutter way: https://github.com/flutter/engine/blob/main/shell/platform/android/io/flutter/view/AccessibilityBridge.java#L125
+ const val BOLD_TEXT_WEIGHT_ADJUSTMENT = 300
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AnalysisHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AnalysisHandler.kt
new file mode 100644
index 0000000..cc7b46e
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AnalysisHandler.kt
@@ -0,0 +1,110 @@
+package deckers.thibault.aves.channel.calls
+
+import android.app.ActivityManager
+import android.content.Context
+import androidx.core.content.edit
+import androidx.work.ExistingWorkPolicy
+import androidx.work.OneTimeWorkRequestBuilder
+import androidx.work.WorkInfo
+import androidx.work.WorkManager
+import androidx.work.workDataOf
+import deckers.thibault.aves.AnalysisWorker
+import deckers.thibault.aves.utils.FlutterUtils
+import io.flutter.embedding.android.FlutterFragmentActivity
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+
+class AnalysisHandler(private val activity: FlutterFragmentActivity, private val onAnalysisCompleted: () -> Unit) : MethodChannel.MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "registerCallback" -> ioScope.launch { Coresult.safe(call, result, ::registerCallback) }
+ "startAnalysis" -> Coresult.safe(call, result, ::startAnalysis)
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun registerCallback(call: MethodCall, result: MethodChannel.Result) {
+ val callbackHandle = call.argument<Number>("callbackHandle")?.toLong()
+ if (callbackHandle == null) {
+ result.error("registerCallback-args", "missing arguments", null)
+ return
+ }
+
+ val preferences = activity.getSharedPreferences(AnalysisWorker.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE)
+ preferences.edit {
+ putLong(AnalysisWorker.PREF_CALLBACK_HANDLE_KEY, callbackHandle)
+ }
+ result.success(true)
+ }
+
+ private fun startAnalysis(call: MethodCall, result: MethodChannel.Result) {
+ val force = call.argument<Boolean>("force")
+ if (force == null) {
+ result.error("startAnalysis-args", "missing arguments", null)
+ return
+ }
+
+ val activityManager: ActivityManager = activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
+ val runningAppProcesses = activityManager.runningAppProcesses
+ if (runningAppProcesses != null) {
+ val importance = runningAppProcesses[0].importance
+ if (importance < ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
+ // the app is in the background
+ result.error("startAnalysis-background", "app is in the background (process importance=$importance)", null)
+ return
+ }
+ }
+
+ // can be null or empty
+ val allEntryIds = call.argument<List<Int>>("entryIds")
+
+ // work `Data` cannot occupy more than 10240 bytes when serialized
+ // so we save the possibly long list of entry IDs to shared preferences
+ val preferences = activity.getSharedPreferences(AnalysisWorker.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE)
+ preferences.edit {
+ putStringSet(AnalysisWorker.PREF_ENTRY_IDS_KEY, allEntryIds?.map { it.toString() }?.toSet())
+ }
+
+ val workData = workDataOf(
+ AnalysisWorker.KEY_FORCE to force,
+ )
+
+ WorkManager.getInstance(activity).beginUniqueWork(
+ ANALYSIS_WORK_NAME,
+ ExistingWorkPolicy.KEEP,
+ OneTimeWorkRequestBuilder<AnalysisWorker>().apply { setInputData(workData) }.build(),
+ ).enqueue()
+
+ attachToActivity()
+ result.success(null)
+ }
+
+ private var attached = false
+
+ fun attachToActivity() {
+ if (!attached) {
+ attached = true
+ WorkManager.getInstance(activity).getWorkInfosForUniqueWorkLiveData(ANALYSIS_WORK_NAME).observe(activity) { list ->
+ if (list.any { it.state == WorkInfo.State.SUCCEEDED }) {
+ runBlocking {
+ FlutterUtils.runOnUiThread {
+ onAnalysisCompleted()
+ }
+ }
+ }
+ }
+ }
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/analysis"
+ private const val ANALYSIS_WORK_NAME = "analysis_work"
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppAdapterHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppAdapterHandler.kt
new file mode 100644
index 0000000..f93d89e
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppAdapterHandler.kt
@@ -0,0 +1,500 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.ClipData
+import android.content.ClipboardManager
+import android.content.ContentResolver
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ApplicationInfo
+import android.content.res.Configuration
+import android.content.res.Resources
+import android.graphics.BitmapFactory
+import android.net.Uri
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.os.TransactionTooLargeException
+import android.util.Log
+import androidx.core.content.FileProvider
+import androidx.core.content.pm.ShortcutInfoCompat
+import androidx.core.content.pm.ShortcutManagerCompat
+import androidx.core.graphics.drawable.IconCompat
+import androidx.core.graphics.scale
+import androidx.core.net.toUri
+import com.bumptech.glide.Glide
+import com.bumptech.glide.load.DecodeFormat
+import com.bumptech.glide.request.RequestOptions
+import deckers.thibault.aves.MainActivity
+import deckers.thibault.aves.MainActivity.Companion.COLLECTION_PAGE_ROUTE_NAME
+import deckers.thibault.aves.MainActivity.Companion.ENTRY_VIEWER_PAGE_ROUTE_NAME
+import deckers.thibault.aves.MainActivity.Companion.EXPLORER_PAGE_ROUTE_NAME
+import deckers.thibault.aves.MainActivity.Companion.EXTRA_KEY_EXPLORER_PATH
+import deckers.thibault.aves.MainActivity.Companion.EXTRA_KEY_FILTERS_ARRAY
+import deckers.thibault.aves.MainActivity.Companion.EXTRA_KEY_FILTERS_STRING
+import deckers.thibault.aves.MainActivity.Companion.EXTRA_KEY_PAGE
+import deckers.thibault.aves.MainActivity.Companion.EXTRA_STRING_ARRAY_SEPARATOR
+import deckers.thibault.aves.MainActivity.Companion.MAP_PAGE_ROUTE_NAME
+import deckers.thibault.aves.R
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safeSuspend
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.BitmapUtils
+import deckers.thibault.aves.utils.ContextUtils.devicePixelRatio
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.anyCauseIs
+import deckers.thibault.aves.utils.getApplicationInfoCompat
+import deckers.thibault.aves.utils.queryIntentActivitiesCompat
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import java.io.File
+import java.util.Locale
+import java.util.UUID
+import kotlin.math.min
+import kotlin.math.roundToInt
+
+class AppAdapterHandler(private val context: Context) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "getPackages" -> ioScope.launch { safe(call, result, ::getPackages) }
+ "getAppIcon" -> ioScope.launch { safeSuspend(call, result, ::getAppIcon) }
+ "copyToClipboard" -> ioScope.launch { safe(call, result, ::copyToClipboard) }
+ "open" -> safe(call, result, ::open)
+ "openMap" -> safe(call, result, ::openMap)
+ "setAs" -> safe(call, result, ::setAs)
+ "share" -> safe(call, result, ::share)
+ "pinShortcut" -> ioScope.launch { safe(call, result, ::pinShortcut) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun getPackages(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ val packages = HashMap<String, FieldMap>()
+
+ fun addPackageDetails(intent: Intent) {
+ // apps tend to use their name in English when creating directories
+ // so we get their names in English as well as the current locale
+ val englishConfig = Configuration().apply {
+ setLocale(Locale.ENGLISH)
+ }
+
+ val pm = context.packageManager
+ for (resolveInfo in pm.queryIntentActivitiesCompat(intent, 0)) {
+ val appInfo = resolveInfo.activityInfo.applicationInfo
+ val packageName = appInfo.packageName
+ if (!packages.containsKey(packageName)) {
+ val currentLabel = pm.getApplicationLabel(appInfo).toString()
+ val englishLabel: String? = appInfo.labelRes.takeIf { it != 0 }?.let { labelRes ->
+ var englishLabel: String? = null
+ try {
+ val resources = pm.getResourcesForApplication(appInfo)
+ // `updateConfiguration` is deprecated but it seems to be the only way
+ // to query resources from another app with a specific locale.
+ // The following methods do not work:
+ // - `resources.getConfiguration().setLocale(...)`
+ // - getting a package manager from a custom context with `context.createConfigurationContext(config)`
+ @Suppress("deprecation")
+ resources.updateConfiguration(englishConfig, resources.displayMetrics)
+ englishLabel = resources.getString(labelRes)
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get app label in English for packageName=$packageName", e)
+ }
+ englishLabel
+ }
+ packages[packageName] = hashMapOf(
+ "packageName" to packageName,
+ "categoryLauncher" to intent.hasCategory(Intent.CATEGORY_LAUNCHER),
+ "isSystem" to (appInfo.flags and ApplicationInfo.FLAG_SYSTEM != 0),
+ "currentLabel" to currentLabel,
+ "englishLabel" to englishLabel,
+ )
+ }
+ }
+ }
+
+ // identify launcher category packages, which typically include user apps
+ // they should be fetched before the other packages, to be marked as launcher packages
+ try {
+ addPackageDetails(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER))
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to list launcher packages", e)
+ }
+
+ try {
+ // complete with all the other packages
+ addPackageDetails(Intent(Intent.ACTION_MAIN))
+ } catch (e: Exception) {
+ // `PackageManager.queryIntentActivities()` may kill the package manager if the response is too large
+ Log.w(LOG_TAG, "failed to list all packages", e)
+
+ // fallback to the default category packages, which typically include system and OEM tools
+ try {
+ addPackageDetails(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_DEFAULT))
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to list default packages", e)
+ }
+ }
+
+ result.success(ArrayList(packages.values))
+ }
+
+ private suspend fun getAppIcon(call: MethodCall, result: MethodChannel.Result) {
+ val packageName = call.argument<String>("packageName")
+ val sizeDip = call.argument<Number>("sizeDip")?.toDouble()
+ if (packageName == null || sizeDip == null) {
+ result.error("getAppIcon-args", "missing arguments", null)
+ return
+ }
+
+ // convert DIP to physical pixels here, instead of using `devicePixelRatio` in Flutter
+ val density = context.devicePixelRatio()
+ val size = (sizeDip * density).roundToInt()
+ var bytes: ByteArray? = null
+ try {
+ val iconResourceId = context.packageManager.getApplicationInfoCompat(packageName, 0).icon
+ if (iconResourceId != Resources.ID_NULL) {
+ val uri = Uri.Builder()
+ .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
+ .authority(packageName)
+ .path(iconResourceId.toString())
+ .build()
+
+ val options = RequestOptions()
+ .format(DecodeFormat.PREFER_ARGB_8888)
+ .override(size, size)
+ val target = Glide.with(context)
+ .asBitmap()
+ .apply(options)
+ .load(uri)
+ .submit(size, size)
+
+ try {
+ var bitmap = withContext(Dispatchers.IO) { target.get() }
+ if (bitmap.width > size && bitmap.height > size) {
+ // rescale when the resulting bitmap is larger than requested
+ val scalingFactor: Double = min(bitmap.width.toDouble() / size, bitmap.height.toDouble() / size)
+ val dstWidth = (bitmap.width / scalingFactor).roundToInt()
+ val dstHeight = (bitmap.height / scalingFactor).roundToInt()
+ Log.d(
+ LOG_TAG, "rescale app icon for packageName=$packageName" +
+ ", with bitmap byteCount=${bitmap.byteCount} size=${bitmap.width}x${bitmap.height}" +
+ ", to target=${size}x${size}"
+ )
+ bitmap = bitmap.scale(dstWidth, dstHeight)
+ }
+
+ // do not recycle bitmaps fetched from `ContentResolver` as their lifecycle is unknown
+ bytes = BitmapUtils.getBytes(bitmap, recycle = false, decoded = true, mimeType = null)
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to decode app icon for packageName=$packageName", e)
+ }
+ Glide.with(context).clear(target)
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get app info for packageName=$packageName", e)
+ return
+ }
+ if (bytes != null) {
+ result.success(bytes)
+ } else {
+ result.error("getAppIcon-null", "failed to get icon for packageName=$packageName", null)
+ }
+ }
+
+ private fun copyToClipboard(call: MethodCall, result: MethodChannel.Result) {
+ val uri = call.argument<String>("uri")?.toUri()
+ val label = call.argument<String>("label")
+ if (uri == null) {
+ result.error("copyToClipboard-args", "missing arguments", null)
+ return
+ }
+
+ // on older devices, `ClipboardManager` initialization must happen on the main thread
+ // (e.g. Samsung S7 with Android 8.0 / API 26, but not on Tab A 10.1 with Android 8.1 / API 27)
+ Handler(Looper.getMainLooper()).post {
+ try {
+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
+ if (clipboard != null) {
+ val clip = ClipData.newUri(context.contentResolver, label, getShareableUri(context, uri))
+ clipboard.setPrimaryClip(clip)
+ result.success(true)
+ } else {
+ result.success(false)
+ }
+ } catch (e: Exception) {
+ result.error("copyToClipboard-exception", "failed to set clip", e.message)
+ }
+ }
+ }
+
+ private fun open(call: MethodCall, result: MethodChannel.Result) {
+ val title = call.argument<String>("title")
+ val uri = call.argument<String>("uri")?.toUri()
+ val mimeType = call.argument<String>("mimeType")
+ val forceChooser = call.argument<Boolean>("forceChooser")
+ if (uri == null || forceChooser == null) {
+ result.error("open-args", "missing arguments", null)
+ return
+ }
+
+ val intent = Intent(Intent.ACTION_VIEW)
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ .setDataAndType(getShareableUri(context, uri), mimeType)
+ val started = if (forceChooser) safeStartActivityChooser(title, intent) else safeStartActivity(intent)
+
+ result.success(started)
+ }
+
+ private fun openMap(call: MethodCall, result: MethodChannel.Result) {
+ val geoUri = call.argument<String>("geoUri")?.toUri()
+ if (geoUri == null) {
+ result.error("openMap-args", "missing arguments", null)
+ return
+ }
+
+ val intent = Intent(Intent.ACTION_VIEW, geoUri)
+ val started = safeStartActivity(intent)
+
+ result.success(started)
+ }
+
+ private fun setAs(call: MethodCall, result: MethodChannel.Result) {
+ val title = call.argument<String>("title")
+ val uri = call.argument<String>("uri")?.toUri()
+ val mimeType = call.argument<String>("mimeType")
+ if (uri == null) {
+ result.error("setAs-args", "missing arguments", null)
+ return
+ }
+
+ val intent = Intent(Intent.ACTION_ATTACH_DATA)
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ .setDataAndType(getShareableUri(context, uri), mimeType)
+ val started = safeStartActivityChooser(title, intent)
+
+ result.success(started)
+ }
+
+ private fun share(call: MethodCall, result: MethodChannel.Result) {
+ val title = call.argument<String>("title")
+ val urisByMimeType = call.argument<Map<String, List<String>>>("urisByMimeType")
+ if (urisByMimeType == null) {
+ result.error("share-args", "missing arguments", null)
+ return
+ }
+
+ val uriList = ArrayList(urisByMimeType.values.flatten().mapNotNull { getShareableUri(context, it.toUri()) })
+ val mimeTypes = urisByMimeType.keys.toTypedArray()
+
+ // simplify share intent for a single item, as some apps can handle one item but not more
+ val intent = if (uriList.size == 1) {
+ val uri = uriList.first()
+ val mimeType = mimeTypes.first()
+
+ Intent(Intent.ACTION_SEND)
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ .setType(mimeType)
+ .putExtra(Intent.EXTRA_STREAM, uri)
+ } else {
+ var mimeType = "*/*"
+ if (mimeTypes.size == 1) {
+ // items have the same MIME type & subtype
+ mimeType = mimeTypes.first()
+ } else {
+ // items have different subtypes
+ val mimeTypeTypes = mimeTypes.map { it.split("/") }.distinct()
+ if (mimeTypeTypes.size == 1) {
+ // items have the same MIME type
+ mimeType = "${mimeTypeTypes.first()}/*"
+ }
+ }
+
+ Intent(Intent.ACTION_SEND_MULTIPLE)
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ .putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriList)
+ .setType(mimeType)
+ }
+ try {
+ val started = safeStartActivityChooser(title, intent)
+ result.success(started)
+ } catch (e: Exception) {
+ if (e.anyCauseIs<TransactionTooLargeException>()) {
+ result.error("share-large", "transaction too large with ${uriList.size} URIs", e)
+ } else {
+ result.error("share-exception", "failed to share ${uriList.size} URIs", e)
+ }
+ }
+ }
+
+ private fun safeStartActivity(intent: Intent): Boolean {
+ if (intent.resolveActivity(context.packageManager) == null) return false
+ try {
+ context.startActivity(intent)
+ return true
+ } catch (e: SecurityException) {
+ if (intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0) {
+ // in some environments, providing the write flag yields a `SecurityException`:
+ // "UID XXXX does not have permission to content://XXXX"
+ // so we retry without it
+ Log.i(LOG_TAG, "retry intent=$intent without FLAG_GRANT_WRITE_URI_PERMISSION")
+ intent.flags = intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION.inv()
+ return safeStartActivity(intent)
+ } else {
+ Log.w(LOG_TAG, "failed to start activity for intent=$intent", e)
+ }
+ }
+ return false
+ }
+
+ private fun safeStartActivityChooser(title: String?, intent: Intent): Boolean {
+ if (intent.resolveActivity(context.packageManager) == null) return false
+ try {
+ context.startActivity(Intent.createChooser(intent, title))
+ return true
+ } catch (e: SecurityException) {
+ if (intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0) {
+ // in some environments, providing the write flag yields a `SecurityException`:
+ // "UID XXXX does not have permission to content://XXXX"
+ // so we retry without it
+ Log.i(LOG_TAG, "retry intent=$intent without FLAG_GRANT_WRITE_URI_PERMISSION")
+ intent.flags = intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION.inv()
+ return safeStartActivityChooser(title, intent)
+ } else {
+ Log.w(LOG_TAG, "failed to start activity chooser for intent=$intent", e)
+ }
+ }
+ return false
+ }
+
+ // shortcuts
+
+ private fun pinShortcut(call: MethodCall, result: MethodChannel.Result) {
+ // common arguments
+ val label = call.argument<String>("label")
+ val iconBytes = call.argument<ByteArray>("iconBytes")
+ val route = call.argument<String>("route")
+ // route dependent arguments
+ val filters = call.argument<List<String>>("filters")
+ val explorerPath = call.argument<String>("path")
+ val viewUri = call.argument<String>("viewUri")?.toUri()
+ val geoUri = call.argument<String>("geoUri")?.toUri()
+
+ if (label == null || route == null) {
+ result.error("pin-args", "missing arguments", null)
+ return
+ }
+
+ if (!ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
+ result.error("pin-unsupported", "failed because the launcher does not support pinning shortcuts", null)
+ return
+ }
+
+ var icon: IconCompat? = null
+ if (iconBytes?.isNotEmpty() == true) {
+ var bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.size)
+ bitmap = BitmapUtils.centerSquareCrop(context, bitmap, 256)
+ if (bitmap != null) {
+ // adaptive, so the bitmap is used as background and covers the whole icon
+ icon = IconCompat.createWithAdaptiveBitmap(bitmap)
+ }
+ }
+ if (icon == null) {
+ // shortcut adaptive icons are placed in `mipmap`, not `drawable`,
+ // so that foreground is rendered at the intended scale
+ val supportAdaptiveIcon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
+
+ val resId = when (route) {
+ MAP_PAGE_ROUTE_NAME -> if (supportAdaptiveIcon) R.mipmap.ic_shortcut_map else R.drawable.ic_shortcut_map
+ else -> if (supportAdaptiveIcon) R.mipmap.ic_shortcut_collection else R.drawable.ic_shortcut_collection
+ }
+ icon = IconCompat.createWithResource(context, resId)
+ }
+
+ val intent: Intent = when (route) {
+ COLLECTION_PAGE_ROUTE_NAME -> {
+ if (filters == null) {
+ result.error("pin-filters", "collection shortcut requires filters", null)
+ return
+ }
+ Intent(Intent.ACTION_MAIN, null, context, MainActivity::class.java)
+ .putExtra(EXTRA_KEY_PAGE, route)
+ .putExtra(EXTRA_KEY_FILTERS_ARRAY, filters.toTypedArray())
+ // on API 25, `String[]` or `ArrayList` extras are null when using the shortcut
+ // so we use a joined `String` as fallback
+ .putExtra(EXTRA_KEY_FILTERS_STRING, filters.joinToString(EXTRA_STRING_ARRAY_SEPARATOR))
+ }
+
+ ENTRY_VIEWER_PAGE_ROUTE_NAME -> {
+ if (viewUri == null) {
+ result.error("pin-viewUri", "viewer shortcut requires URI", null)
+ return
+ }
+ Intent(Intent.ACTION_VIEW, viewUri, context, MainActivity::class.java)
+ }
+
+ EXPLORER_PAGE_ROUTE_NAME -> {
+ Intent(Intent.ACTION_MAIN, null, context, MainActivity::class.java)
+ .putExtra(EXTRA_KEY_PAGE, route)
+ .putExtra(EXTRA_KEY_EXPLORER_PATH, explorerPath)
+ }
+
+ MAP_PAGE_ROUTE_NAME -> {
+ if (geoUri == null) {
+ result.error("pin-geoUri", "map shortcut requires URI", null)
+ return
+ }
+ Intent(Intent.ACTION_VIEW, geoUri, context, MainActivity::class.java).apply {
+ putExtra(EXTRA_KEY_PAGE, route)
+ // filters are optional
+ filters?.let {
+ putExtra(EXTRA_KEY_FILTERS_ARRAY, it.toTypedArray())
+ // on API 25, `String[]` or `ArrayList` extras are null when using the shortcut
+ // so we use a joined `String` as fallback
+ putExtra(EXTRA_KEY_FILTERS_STRING, it.joinToString(EXTRA_STRING_ARRAY_SEPARATOR))
+ }
+ }
+ }
+
+ else -> {
+ result.error("pin-route", "unsupported shortcut route=$route", null)
+ return
+ }
+ }
+
+ // multiple shortcuts sharing the same ID cannot be created with different labels or icons
+ // so we provide a unique ID for each one, and let the user manage duplicates (i.e. same filter set), if any
+ val shortcut = ShortcutInfoCompat.Builder(context, UUID.randomUUID().toString())
+ .setShortLabel(label)
+ .setIcon(icon)
+ .setIntent(intent)
+ .build()
+ ShortcutManagerCompat.requestPinShortcut(context, shortcut, null)
+
+ result.success(true)
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<AppAdapterHandler>()
+ const val CHANNEL = "deckers.thibault/aves/app"
+
+ fun getShareableUri(context: Context, uri: Uri): Uri? {
+ return when (uri.scheme?.lowercase(Locale.ROOT)) {
+ ContentResolver.SCHEME_FILE -> {
+ uri.path?.let { path ->
+ val authority = "${context.applicationContext.packageName}.file_provider"
+ FileProvider.getUriForFile(context, authority, File(path))
+ }
+ }
+
+ else -> uri
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppProfileHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppProfileHandler.kt
new file mode 100644
index 0000000..41682c0
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/AppProfileHandler.kt
@@ -0,0 +1,97 @@
+package deckers.thibault.aves.channel.calls
+
+import android.app.Activity
+import android.content.Context
+import android.content.pm.CrossProfileApps
+import android.os.Build
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+
+class AppProfileHandler(private val activity: Activity) : MethodCallHandler {
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "canInteractAcrossProfiles" -> safe(call, result, ::canInteractAcrossProfiles)
+ "canRequestInteractAcrossProfiles" -> safe(call, result, ::canRequestInteractAcrossProfiles)
+ "requestInteractAcrossProfiles" -> safe(call, result, ::requestInteractAcrossProfiles)
+ "switchProfile" -> safe(call, result, ::switchProfile)
+ "getProfileSwitchingLabel" -> safe(call, result, ::getProfileSwitchingLabel)
+ "getTargetUserProfiles" -> safe(call, result, ::getTargetUserProfiles)
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun canInteractAcrossProfiles(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ result.success(false)
+ return
+ }
+
+ val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps
+ result.success(crossProfileApps.canInteractAcrossProfiles())
+ }
+
+ private fun canRequestInteractAcrossProfiles(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ result.success(false)
+ return
+ }
+
+ val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps
+ result.success(crossProfileApps.canRequestInteractAcrossProfiles())
+ }
+
+ private fun requestInteractAcrossProfiles(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ result.success(false)
+ return
+ }
+
+ val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps
+ val intent = crossProfileApps.createRequestInteractAcrossProfilesIntent()
+ val started = activity.startActivity(intent)
+
+ result.success(started)
+ }
+
+ private fun switchProfile(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
+ result.success(false)
+ return
+ }
+
+ val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps
+ val userHandles = crossProfileApps.targetUserProfiles
+ crossProfileApps.startMainActivity(activity.componentName, userHandles.first())
+ result.success(null)
+ }
+
+ private fun getProfileSwitchingLabel(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
+ result.success(null)
+ return
+ }
+
+ val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps
+ val userHandles = crossProfileApps.targetUserProfiles
+ val label = if (userHandles.isEmpty()) "" else crossProfileApps.getProfileSwitchingLabel(userHandles.first())
+
+ result.success(label)
+ }
+
+ private fun getTargetUserProfiles(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
+ result.success(false)
+ return
+ }
+
+ val crossProfileApps = activity.getSystemService(Context.CROSS_PROFILE_APPS_SERVICE) as CrossProfileApps
+ val userProfiles = crossProfileApps.targetUserProfiles.map { it.toString() }.toList()
+ result.success(userProfiles)
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/app_profile"
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/Coresult.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/Coresult.kt
new file mode 100644
index 0000000..c447a76
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/Coresult.kt
@@ -0,0 +1,71 @@
+package deckers.thibault.aves.channel.calls
+
+import deckers.thibault.aves.MainActivity
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+
+// ensure `result` methods are called on the main looper thread
+class Coresult internal constructor(private val call: MethodCall, private val methodResult: MethodChannel.Result) : MethodChannel.Result {
+ private val mainScope = CoroutineScope(Dispatchers.Main)
+
+ override fun success(result: Any?) {
+ mainScope.launch {
+ try {
+ methodResult.success(result)
+ } catch (e: Exception) {
+ MainActivity.notifyError("failed to reply success for method=${call.method}, result=$result, exception=\n${e.stackTraceToString()}")
+ }
+ }
+ }
+
+ override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
+ mainScope.launch {
+ try {
+ methodResult.error(errorCode, errorMessage, errorDetails)
+ } catch (e: Exception) {
+ MainActivity.notifyError("failed to reply error for method=${call.method}, errorCode=$errorCode, errorMessage=$errorMessage, errorDetails=$errorDetails, exception=\n${e.stackTraceToString()}")
+ }
+ }
+ }
+
+ override fun notImplemented() {
+ mainScope.launch {
+ try {
+ methodResult.notImplemented()
+ } catch (e: Exception) {
+ MainActivity.notifyError("failed to reply notImplemented for method=${call.method}, exception=\n${e.stackTraceToString()}")
+ }
+ }
+ }
+
+ companion object {
+ fun safe(
+ call: MethodCall,
+ result: MethodChannel.Result,
+ function: (call: MethodCall, result: MethodChannel.Result) -> Unit
+ ) {
+ val res = Coresult(call, result)
+ try {
+ function(call, res)
+ } catch (e: Exception) {
+ res.error("safe-exception", e.message, e.stackTraceToString())
+ }
+ }
+
+ suspend fun safeSuspend(
+ call: MethodCall,
+ result: MethodChannel.Result,
+ function: suspend (call: MethodCall, result: MethodChannel.Result) -> Unit
+ ) {
+ val res = Coresult(call, result)
+ try {
+ function(call, res)
+ } catch (e: Exception) {
+ res.error("safeSuspend-exception", e.message, e.stackTraceToString())
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DebugHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DebugHandler.kt
new file mode 100644
index 0000000..1af8699
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DebugHandler.kt
@@ -0,0 +1,436 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.ContentUris
+import android.content.Context
+import android.database.Cursor
+import android.graphics.BitmapFactory
+import android.media.MediaCodecInfo
+import android.media.MediaCodecList
+import android.net.Uri
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.provider.MediaStore
+import android.util.Log
+import androidx.core.net.toUri
+import com.drew.metadata.file.FileTypeDirectory
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.glide.TiffFetcher
+import deckers.thibault.aves.metadata.ExifInterfaceHelper
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper
+import deckers.thibault.aves.metadata.Metadata
+import deckers.thibault.aves.metadata.Mp4ParserHelper
+import deckers.thibault.aves.metadata.Mp4ParserHelper.dumpBoxes
+import deckers.thibault.aves.metadata.PixyMetaHelper
+import deckers.thibault.aves.metadata.metadataextractor.Helper
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.canReadWithExifInterface
+import deckers.thibault.aves.utils.MimeTypes.canReadWithMetadataExtractor
+import deckers.thibault.aves.utils.MimeTypes.canReadWithPixyMeta
+import deckers.thibault.aves.utils.MimeTypes.isImage
+import deckers.thibault.aves.utils.MimeTypes.isVideo
+import deckers.thibault.aves.utils.StorageUtils
+import deckers.thibault.aves.utils.UriUtils.tryParseId
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import io.flutter.util.PathUtils
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import org.beyka.tiffbitmapfactory.TiffBitmapFactory
+import org.mp4parser.IsoFile
+import java.io.FileInputStream
+import java.io.IOException
+import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface
+
+class DebugHandler(private val context: Context) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "crash" -> Handler(Looper.getMainLooper()).postDelayed({ throw TestException() }, 50)
+ "exception" -> throw TestException()
+ "safeException" -> safe(call, result) { _, _ -> throw TestException() }
+ "exceptionInCoroutine" -> ioScope.launch { throw TestException() }
+ "safeExceptionInCoroutine" -> ioScope.launch { safe(call, result) { _, _ -> throw TestException() } }
+
+ "getContextDirs" -> ioScope.launch { safe(call, result, ::getContextDirs) }
+ "getCodecs" -> safe(call, result, ::getCodecs)
+ "getEnv" -> safe(call, result, ::getEnv)
+
+ "getBitmapFactoryInfo" -> ioScope.launch { safe(call, result, ::getBitmapFactoryInfo) }
+ "getContentResolverMetadata" -> ioScope.launch { safe(call, result, ::getContentResolverMetadata) }
+ "getExifInterfaceMetadata" -> ioScope.launch { safe(call, result, ::getExifInterfaceMetadata) }
+ "getMediaMetadataRetrieverMetadata" -> ioScope.launch { safe(call, result, ::getMediaMetadataRetrieverMetadata) }
+ "getMetadataExtractorSummary" -> ioScope.launch { safe(call, result, ::getMetadataExtractorSummary) }
+ "getMp4ParserDump" -> ioScope.launch { safe(call, result, ::getMp4ParserDump) }
+ "getPixyMetadata" -> ioScope.launch { safe(call, result, ::getPixyMetadata) }
+ "getTiffStructure" -> ioScope.launch { safe(call, result, ::getTiffStructure) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun getContextDirs(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ val dirs = hashMapOf(
+ "cacheDir" to context.cacheDir,
+ "filesDir" to context.filesDir,
+ "obbDir" to context.obbDir,
+ "externalCacheDir" to context.externalCacheDir,
+ "externalFilesDir" to context.getExternalFilesDir(null),
+ "codeCacheDir" to context.codeCacheDir,
+ "noBackupFilesDir" to context.noBackupFilesDir,
+ ).apply {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ put("dataDir", context.dataDir)
+ }
+ }.mapValues { it.value?.path }.toMutableMap()
+ dirs["externalCacheDirs"] = context.externalCacheDirs.joinToString { it.path }
+ dirs["externalFilesDirs"] = context.getExternalFilesDirs(null).joinToString { it?.path ?: "null" }
+
+ // used by flutter plugin `path_provider`
+ dirs.putAll(
+ hashMapOf(
+ "flutter / cacheDir" to PathUtils.getCacheDirectory(context),
+ "flutter / dataDir" to PathUtils.getDataDirectory(context),
+ "flutter / filesDir" to PathUtils.getFilesDir(context),
+ )
+ )
+
+ result.success(dirs)
+ }
+
+ private fun getCodecs(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ fun getFields(info: MediaCodecInfo): FieldMap {
+ val fields: FieldMap = hashMapOf(
+ "name" to info.name,
+ "isEncoder" to info.isEncoder,
+ "supportedTypes" to info.supportedTypes.joinToString(", "),
+ )
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ if (info.canonicalName != info.name) fields["canonicalName"] = info.canonicalName
+ if (info.isAlias) fields["isAlias"] to info.isAlias
+ if (info.isHardwareAccelerated) fields["isHardwareAccelerated"] to info.isHardwareAccelerated
+ if (info.isSoftwareOnly) fields["isSoftwareOnly"] to info.isSoftwareOnly
+ if (info.isVendor) fields["isVendor"] to info.isVendor
+ }
+ return fields
+ }
+
+ val codecs = MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos.map(::getFields).toList()
+ result.success(codecs)
+ }
+
+ private fun getEnv(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ result.success(System.getenv())
+ }
+
+ private fun getBitmapFactoryInfo(call: MethodCall, result: MethodChannel.Result) {
+ val uri = call.argument<String>("uri")?.toUri()
+ if (uri == null) {
+ result.error("getBitmapDecoderInfo-args", "missing arguments", null)
+ return
+ }
+
+ val metadataMap = HashMap<String, String>()
+ try {
+ StorageUtils.openInputStream(context, uri)?.use { input ->
+ val options = BitmapFactory.Options().apply {
+ inJustDecodeBounds = true
+ }
+ BitmapFactory.decodeStream(input, null, options)
+ options.outMimeType?.let { metadataMap["MimeType"] = it }
+ options.outWidth.takeIf { it >= 0 }?.let { metadataMap["Width"] = it.toString() }
+ options.outHeight.takeIf { it >= 0 }?.let { metadataMap["Height"] = it.toString() }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ options.outColorSpace?.let { metadataMap["ColorSpace"] = it.toString() }
+ options.outConfig?.let { metadataMap["Config"] = it.toString() }
+ }
+ }
+ } catch (_: IOException) {
+ // ignore
+ }
+ result.success(metadataMap)
+ }
+
+ private fun getContentResolverMetadata(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ if (mimeType == null || uri == null) {
+ result.error("getContentResolverMetadata-args", "missing arguments", null)
+ return
+ }
+
+ var contentUri: Uri = uri
+ if (StorageUtils.isMediaStoreContentUri(uri)) {
+ uri.tryParseId()?.let { id ->
+ contentUri = when {
+ isImage(mimeType) -> ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
+ isVideo(mimeType) -> ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
+ else -> uri
+ }
+ contentUri = StorageUtils.getOriginalUri(context, contentUri)
+ }
+ }
+
+ // prefer image/video content URI, fallback to original URI (possibly a file content URI)
+ val metadataMap = getContentResolverMetadataForUri(contentUri) ?: getContentResolverMetadataForUri(uri)
+ if (metadataMap != null) {
+ result.success(metadataMap)
+ } else {
+ result.error("getContentResolverMetadata-null", "failed to get cursor for contentUri=$contentUri", null)
+ }
+ }
+
+ private fun getContentResolverMetadataForUri(contentUri: Uri): FieldMap? {
+ val cursor = context.contentResolver.query(contentUri, null, null, null, null)
+ if (cursor != null && cursor.moveToFirst()) {
+ val metadataMap = HashMap<String, Any?>()
+ val columnCount = cursor.columnCount
+ val columnNames = cursor.columnNames
+ for (i in 0 until columnCount) {
+ val key = columnNames[i]
+ try {
+ metadataMap[key] = when (cursor.getType(i)) {
+ Cursor.FIELD_TYPE_NULL -> null
+ Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(i)
+ Cursor.FIELD_TYPE_FLOAT -> cursor.getFloat(i)
+ Cursor.FIELD_TYPE_STRING -> cursor.getString(i)
+ Cursor.FIELD_TYPE_BLOB -> cursor.getBlob(i)
+ else -> null
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get value for key=$key", e)
+ }
+ }
+ cursor.close()
+ return metadataMap
+ }
+ return null
+ }
+
+ private fun getExifInterfaceMetadata(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ if (mimeType == null || uri == null) {
+ result.error("getExifInterfaceMetadata-args", "missing arguments", null)
+ return
+ }
+
+ val metadataMap = HashMap<String, String?>()
+ if (canReadWithExifInterface(mimeType, strict = false)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val exif = ExifInterface(input)
+ for (tag in ExifInterfaceHelper.allTags.keys.filter { exif.hasAttribute(it) }) {
+ metadataMap[tag] = exif.getAttribute(tag)
+ }
+ }
+ } catch (e: Exception) {
+ // ExifInterface initialization can fail with a RuntimeException
+ // caused by an internal MediaMetadataRetriever failure
+ result.error("getExifInterfaceMetadata-failure", "failed to get exif for uri=$uri", e.message)
+ return
+ }
+ }
+ result.success(metadataMap)
+ }
+
+ private fun getMediaMetadataRetrieverMetadata(call: MethodCall, result: MethodChannel.Result) {
+ val uri = call.argument<String>("uri")?.toUri()
+ if (uri == null) {
+ result.error("getMediaMetadataRetrieverMetadata-args", "missing arguments", null)
+ return
+ }
+
+ val metadataMap = HashMap<String, String>()
+ val retriever = StorageUtils.openMetadataRetriever(context, uri)
+ if (retriever != null) {
+ try {
+ for ((code, name) in MediaMetadataRetrieverHelper.allKeys) {
+ retriever.extractMetadata(code)?.let { metadataMap[name] = it }
+ }
+ } catch (_: Exception) {
+ // ignore
+ } finally {
+ // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs
+ retriever.release()
+ }
+ }
+ result.success(metadataMap)
+ }
+
+ private fun getMetadataExtractorSummary(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ if (mimeType == null || uri == null) {
+ result.error("getMetadataExtractorSummary-args", "missing arguments", null)
+ return
+ }
+
+ val metadataMap = HashMap<String, String>()
+ if (canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ metadataMap["mimeType"] = metadata.getDirectoriesOfType(FileTypeDirectory::class.java).joinToString { dir ->
+ if (dir.containsTag(FileTypeDirectory.TAG_DETECTED_FILE_MIME_TYPE)) {
+ dir.getString(FileTypeDirectory.TAG_DETECTED_FILE_MIME_TYPE)
+ } else ""
+ }
+ metadataMap["typeName"] = metadata.getDirectoriesOfType(FileTypeDirectory::class.java).joinToString { dir ->
+ if (dir.containsTag(FileTypeDirectory.TAG_DETECTED_FILE_TYPE_NAME)) {
+ dir.getString(FileTypeDirectory.TAG_DETECTED_FILE_TYPE_NAME)
+ } else ""
+ }
+ for (dir in metadata.directories) {
+ val dirName = dir.name ?: ""
+ var index = 0
+ while (metadataMap.containsKey("$dirName ($index)")) index++
+ var value = "${dir.tagCount} tags"
+ dir.parent?.let { value += ", parent: ${it.name}" }
+ metadataMap["$dirName ($index)"] = value
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get metadata by metadata-extractor for uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to get metadata by metadata-extractor for uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to get metadata by metadata-extractor for uri=$uri", e)
+ }
+ }
+ result.success(metadataMap)
+ }
+
+ private fun getMp4ParserDump(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ if (mimeType == null || uri == null) {
+ result.error("getMp4ParserDump-args", "missing arguments", null)
+ return
+ }
+
+ val sb = StringBuilder()
+ if (mimeType == MimeTypes.MP4 || MimeTypes.isIsoBMFFImage(mimeType)) {
+ try {
+ // we can skip uninteresting boxes with a seekable data source
+ val pfd = StorageUtils.openInputFileDescriptor(context, uri) ?: throw Exception("failed to open file descriptor for uri=$uri")
+ pfd.use {
+ FileInputStream(it.fileDescriptor).use { stream ->
+ stream.channel.use { channel ->
+ IsoFile(channel, Mp4ParserHelper.metadataBoxParser()).use { isoFile ->
+ isoFile.dumpBoxes(sb)
+ }
+ }
+ }
+ }
+ } catch (e: Exception) {
+ result.error("getMp4ParserDump-exception", e.message, e.stackTraceToString())
+ return
+ }
+ }
+ result.success(sb.toString())
+ }
+
+ private fun getPixyMetadata(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ if (mimeType == null || uri == null) {
+ result.error("getPixyMetadata-args", "missing arguments", null)
+ return
+ }
+
+ val metadataMap = HashMap<String, String>()
+ if (canReadWithPixyMeta(mimeType)) {
+ try {
+ StorageUtils.openInputStream(context, uri)?.use { input ->
+ metadataMap.putAll(PixyMetaHelper.describe(input))
+ }
+ } catch (e: Exception) {
+ result.error("getPixyMetadata-exception", e.message, e.stackTraceToString())
+ return
+ }
+ }
+ result.success(metadataMap)
+ }
+
+ private fun getTiffStructure(call: MethodCall, result: MethodChannel.Result) {
+ val uri = call.argument<String>("uri")?.toUri()
+ if (uri == null) {
+ result.error("getTiffStructure-args", "missing arguments", null)
+ return
+ }
+
+ try {
+ val metadataMap = HashMap<String, FieldMap>()
+ var fd = context.contentResolver.openFileDescriptor(uri, "r")?.detachFd()
+ if (fd == null) {
+ result.error("getTiffStructure-fd", "failed to get file descriptor", null)
+ return
+ }
+ var options = TiffFetcher.buildOptions().apply {
+ inJustDecodeBounds = true
+ }
+ TiffBitmapFactory.decodeFileDescriptor(fd, options)
+ metadataMap["0"] = tiffOptionsToMap(options)
+ val dirCount = options.outDirectoryCount
+ for (page in 1 until dirCount) {
+ fd = context.contentResolver.openFileDescriptor(uri, "r")?.detachFd()
+ if (fd == null) {
+ result.error("getTiffStructure-fd", "failed to get file descriptor", null)
+ return
+ }
+ options = TiffFetcher.buildOptions().apply {
+ inJustDecodeBounds = true
+ inDirectoryNumber = page
+ }
+ TiffBitmapFactory.decodeFileDescriptor(fd, options)
+ metadataMap["$page"] = tiffOptionsToMap(options)
+ }
+ result.success(metadataMap)
+ } catch (e: Exception) {
+ result.error("getTiffStructure-read", "failed to read tiff", e.message)
+ }
+ }
+
+ private fun tiffOptionsToMap(options: TiffBitmapFactory.Options): FieldMap = hashMapOf(
+ "Author" to options.outAuthor,
+ "BitsPerSample" to options.outBitsPerSample.toString(),
+ "CompressionScheme" to options.outCompressionScheme?.toString(),
+ "Copyright" to options.outCopyright,
+ "CurDirectoryNumber" to options.outCurDirectoryNumber.toString(),
+ "Datetime" to options.outDatetime,
+ "DirectoryCount" to options.outDirectoryCount.toString(),
+ "FillOrder" to options.outFillOrder?.toString(),
+ "Height" to options.outHeight.toString(),
+ "HostComputer" to options.outHostComputer,
+ "ImageDescription" to options.outImageDescription,
+ "ImageOrientation" to options.outImageOrientation?.toString(),
+ "NumberOfStrips" to options.outNumberOfStrips.toString(),
+ "Photometric" to options.outPhotometric?.toString(),
+ "PlanarConfig" to options.outPlanarConfig?.toString(),
+ "ResolutionUnit" to options.outResolutionUnit?.toString(),
+ "RowPerStrip" to options.outRowPerStrip.toString(),
+ "SamplePerPixel" to options.outSamplePerPixel.toString(),
+ "Software" to options.outSoftware,
+ "StripSize" to options.outStripSize.toString(),
+ "TileHeight" to options.outTileHeight.toString(),
+ "TileWidth" to options.outTileWidth.toString(),
+ "Width" to options.outWidth.toString(),
+ "XResolution" to options.outXResolution.toString(),
+ "YResolution" to options.outYResolution.toString(),
+ )
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<DebugHandler>()
+ const val CHANNEL = "deckers.thibault/aves/debug"
+ }
+
+ class TestException internal constructor() : RuntimeException("oops")
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DeviceHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DeviceHandler.kt
new file mode 100644
index 0000000..f03a33d
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/DeviceHandler.kt
@@ -0,0 +1,174 @@
+package deckers.thibault.aves.channel.calls
+
+import android.annotation.SuppressLint
+import android.app.LocaleConfig
+import android.app.LocaleManager
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.content.res.Resources
+import android.location.Geocoder
+import android.os.Build
+import android.os.LocaleList
+import android.provider.MediaStore
+import android.provider.Settings
+import androidx.core.content.pm.ShortcutManagerCompat
+import androidx.core.net.toUri
+import androidx.core.text.util.LocalePreferences
+import com.google.android.material.color.DynamicColors
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.MemoryUtils
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import java.util.Locale
+
+class DeviceHandler(private val context: Context) : MethodCallHandler {
+ private val defaultScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "canManageMedia" -> safe(call, result, ::canManageMedia)
+ "getCapabilities" -> defaultScope.launch { safe(call, result, ::getCapabilities) }
+ "getLocales" -> safe(call, result, ::getLocales)
+ "setLocaleConfig" -> safe(call, result, ::setLocaleConfig)
+ "getFirstDayOfWeek" -> safe(call, result, ::getFirstDayOfWeek)
+ "getPerformanceClass" -> safe(call, result, ::getPerformanceClass)
+ "getWidgetCornerRadiusPx" -> safe(call, result, ::getWidgetCornerRadiusPx)
+ "isLocked" -> safe(call, result, ::isLocked)
+ "isSystemFilePickerEnabled" -> safe(call, result, ::isSystemFilePickerEnabled)
+ "requestMediaManagePermission" -> safe(call, result, ::requestMediaManagePermission)
+ "getAvailableHeapSize" -> safe(call, result, ::getAvailableHeapSize)
+ "requestGarbageCollection" -> safe(call, result, ::requestGarbageCollection)
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun canManageMedia(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ result.success(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) MediaStore.canManageMedia(context) else false)
+ }
+
+ private fun getCapabilities(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ val sdkInt = Build.VERSION.SDK_INT
+ result.success(
+ hashMapOf(
+ "canPinShortcut" to ShortcutManagerCompat.isRequestPinShortcutSupported(context),
+ "canRenderFlagEmojis" to (sdkInt >= Build.VERSION_CODES.M),
+ "canRenderSubdivisionFlagEmojis" to (sdkInt >= Build.VERSION_CODES.O),
+ "canRequestManageMedia" to (sdkInt >= Build.VERSION_CODES.S),
+ "canSetLockScreenWallpaper" to (sdkInt >= Build.VERSION_CODES.N),
+ "hasGeocoder" to Geocoder.isPresent(),
+ "isDynamicColorAvailable" to DynamicColors.isDynamicColorAvailable(),
+ "showPinShortcutFeedback" to (sdkInt >= Build.VERSION_CODES.O),
+ "supportEdgeToEdgeUIMode" to (sdkInt >= Build.VERSION_CODES.Q),
+ "supportPictureInPicture" to supportPictureInPicture(),
+ )
+ )
+ }
+
+ private fun supportPictureInPicture(): Boolean {
+ // minimum version for `PictureInPictureParams.Builder#setAutoEnterEnabled`
+ val supportPipOnLeave = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
+ return supportPipOnLeave && context.packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)
+ }
+
+ private fun getLocales(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ fun toMap(locale: Locale): FieldMap = hashMapOf(
+ "language" to locale.language,
+ "country" to locale.country,
+ "script" to locale.script,
+ )
+
+ val locales = ArrayList<FieldMap>()
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ // when called from a window-less service, locales from `context.resources`
+ // do not reflect the current system settings, so we use `Resources.getSystem()` instead
+ val list = Resources.getSystem().configuration.locales
+ for (i in 0 until list.size()) {
+ locales.add(toMap(list.get(i)))
+ }
+ } else {
+ locales.add(toMap(Locale.getDefault()))
+ }
+ result.success(locales)
+ }
+
+ private fun setLocaleConfig(call: MethodCall, result: MethodChannel.Result) {
+ val locales = call.argument<List<String>>("locales")
+ if (locales.isNullOrEmpty()) {
+ result.error("setLocaleConfig-args", "missing arguments", null)
+ return
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
+ @SuppressLint("WrongConstant")
+ val lm = context.getSystemService(Context.LOCALE_SERVICE) as? LocaleManager
+ lm?.overrideLocaleConfig = LocaleConfig(LocaleList.forLanguageTags(locales.joinToString(",")))
+ }
+
+ result.success(true)
+ }
+
+ private fun getFirstDayOfWeek(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ result.success(LocalePreferences.getFirstDayOfWeek())
+ }
+
+ private fun getPerformanceClass(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ val performanceClass = Build.VERSION.MEDIA_PERFORMANCE_CLASS
+ if (performanceClass > 0) {
+ result.success(performanceClass)
+ return
+ }
+ }
+ result.success(Build.VERSION.SDK_INT)
+ }
+
+ private fun getWidgetCornerRadiusPx(@Suppress("unused_parameter") methodCall: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ result.success(context.resources.getDimension(android.R.dimen.system_app_widget_background_radius))
+ } else {
+ result.success(null)
+ }
+ }
+
+ private fun isLocked(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ val keyguardManager = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
+ val isLocked = keyguardManager.isKeyguardLocked
+ result.success(isLocked)
+ }
+
+ private fun isSystemFilePickerEnabled(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ val enabled = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).resolveActivity(context.packageManager) != null
+ result.success(enabled)
+ }
+
+ private fun requestMediaManagePermission(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
+ result.error("requestMediaManagePermission-unsupported", "media management permission is not available before Android 12", null)
+ return
+ }
+
+ val intent = Intent(Settings.ACTION_REQUEST_MANAGE_MEDIA, "package:${context.packageName}".toUri())
+ context.startActivity(intent)
+ result.success(true)
+ }
+
+ private fun getAvailableHeapSize(@Suppress("unused_parameter") methodCall: MethodCall, result: MethodChannel.Result) {
+ result.success(MemoryUtils.getAvailableHeapSize())
+ }
+
+ private fun requestGarbageCollection(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ Runtime.getRuntime().gc()
+ result.success(true)
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/device"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/EmbeddedDataHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/EmbeddedDataHandler.kt
new file mode 100644
index 0000000..30d4001
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/EmbeddedDataHandler.kt
@@ -0,0 +1,361 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.Context
+import android.util.Log
+import androidx.core.content.FileProvider
+import androidx.core.net.toUri
+import androidx.exifinterface.media.ExifInterface
+import com.adobe.internal.xmp.XMPException
+import com.adobe.internal.xmp.XMPUtils
+import com.bumptech.glide.load.resource.bitmap.TransformationUtils
+import com.drew.metadata.xmp.XmpDirectory
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safeSuspend
+import deckers.thibault.aves.metadata.Metadata
+import deckers.thibault.aves.metadata.MultiPage
+import deckers.thibault.aves.metadata.metadataextractor.Helper
+import deckers.thibault.aves.metadata.xmp.GoogleDeviceContainer
+import deckers.thibault.aves.metadata.xmp.GoogleXMP
+import deckers.thibault.aves.metadata.xmp.XMP.getSafeStructField
+import deckers.thibault.aves.metadata.xmp.XMPPropName
+import deckers.thibault.aves.model.EntryFields
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.model.provider.ImageProvider
+import deckers.thibault.aves.model.provider.ImageProviderFactory.getProvider
+import deckers.thibault.aves.utils.BitmapUtils
+import deckers.thibault.aves.utils.FileUtils.transferFrom
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.canReadWithExifInterface
+import deckers.thibault.aves.utils.MimeTypes.canReadWithMetadataExtractor
+import deckers.thibault.aves.utils.MimeTypes.extensionFor
+import deckers.thibault.aves.utils.MimeTypes.isImage
+import deckers.thibault.aves.utils.MimeTypes.isVideo
+import deckers.thibault.aves.utils.StorageUtils
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import java.io.InputStream
+
+class EmbeddedDataHandler(private val context: Context) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "getExifThumbnails" -> ioScope.launch { safeSuspend(call, result, ::getExifThumbnails) }
+ "extractGoogleDeviceItem" -> ioScope.launch { safe(call, result, ::extractGoogleDeviceItem) }
+ "extractJpegMpfItem" -> ioScope.launch { safe(call, result, ::extractJpegMpfItem) }
+ "extractMotionPhotoImage" -> ioScope.launch { safe(call, result, ::extractMotionPhotoImage) }
+ "extractMotionPhotoVideo" -> ioScope.launch { safe(call, result, ::extractMotionPhotoVideo) }
+ "extractVideoEmbeddedPicture" -> ioScope.launch { safe(call, result, ::extractVideoEmbeddedPicture) }
+ "extractXmpDataProp" -> ioScope.launch { safe(call, result, ::extractXmpDataProp) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private suspend fun getExifThumbnails(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ if (mimeType == null || uri == null) {
+ result.error("getExifThumbnails-args", "missing arguments", null)
+ return
+ }
+
+ val thumbnails = ArrayList<ByteArray>()
+ if (canReadWithExifInterface(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val exif = ExifInterface(input)
+ val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
+ exif.thumbnailBitmap?.let { bitmap ->
+ TransformationUtils.rotateImageExif(BitmapUtils.getBitmapPool(context), bitmap, orientation)?.let {
+ // do not recycle bitmaps fetched from `ExifInterface` as their lifecycle is unknown
+ BitmapUtils.getBytes(it, recycle = false, decoded = true, mimeType = null)?.let { bytes -> thumbnails.add(bytes) }
+ }
+ }
+ }
+ } catch (_: Exception) {
+ // ExifInterface initialization can fail with a RuntimeException
+ // caused by an internal MediaMetadataRetriever failure
+ }
+ }
+ result.success(thumbnails)
+ }
+
+ private fun extractGoogleDeviceItem(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ val displayName = call.argument<String>("displayName")
+ val dataUri = call.argument<String>("dataUri")
+ if (mimeType == null || uri == null || sizeBytes == null || dataUri == null) {
+ result.error("extractGoogleDeviceItem-args", "missing arguments", null)
+ return
+ }
+
+ var container: GoogleDeviceContainer? = null
+
+ if (canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ // data can be large and stored in "Extended XMP",
+ // which is returned as a second XMP directory
+ val xmpDirs = metadata.getDirectoriesOfType(XmpDirectory::class.java)
+ try {
+ container = xmpDirs.firstNotNullOfOrNull { GoogleXMP.getDeviceContainer(it.xmpMeta) }
+ } catch (e: XMPException) {
+ result.error("extractGoogleDeviceItem-xmp", "failed to read XMP directory for uri=$uri dataUri=$dataUri", e.message)
+ return
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to extract file from XMP", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to extract file from XMP", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to extract file from XMP", e)
+ }
+ }
+
+ container?.let {
+ it.findOffsets(context, uri, mimeType, sizeBytes)
+
+ val index = it.itemIndex(dataUri)
+ val itemStartOffset = it.itemStartOffset(index)
+ val itemLength = it.itemLength(index)
+ val itemMimeType = it.itemMimeType(index)
+ if (itemStartOffset != null && itemLength != null && itemMimeType != null) {
+ StorageUtils.openInputStream(context, uri)?.let { input ->
+ input.skip(itemStartOffset)
+ copyEmbeddedBytes(result, itemMimeType, displayName, input, itemLength)
+ return
+ }
+ }
+ }
+
+ result.error("extractGoogleDeviceItem-empty", "failed to extract item from Google Device XMP at uri=$uri dataUri=$dataUri", null)
+ }
+
+ private fun extractJpegMpfItem(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ val displayName = call.argument<String>("displayName")
+ val id = call.argument<Int>("id")
+ if (mimeType == null || uri == null || sizeBytes == null || id == null) {
+ result.error("extractJpegMpfItem-args", "missing arguments", null)
+ return
+ }
+
+ val pageIndex = id - 1
+ val mpEntries = MultiPage.getJpegMpfEntries(context, uri, sizeBytes)
+ if (mpEntries != null && pageIndex < mpEntries.size) {
+ val mpEntry = mpEntries[pageIndex]
+ mpEntry.mimeType?.let { embedMimeType ->
+ var dataOffset = mpEntry.dataOffset
+ if (dataOffset > 0) {
+ val baseOffset = MultiPage.getJpegMpfBaseOffset(context, uri, sizeBytes)
+ if (baseOffset != null) {
+ dataOffset += baseOffset
+ }
+ }
+ StorageUtils.openInputStream(context, uri)?.let { input ->
+ input.skip(dataOffset)
+ copyEmbeddedBytes(result, embedMimeType, displayName, input, mpEntry.size)
+ }
+ return
+ }
+ }
+
+ result.error("extractJpegMpfItem-empty", "failed to extract file index=$id from MPF at uri=$uri", null)
+ }
+
+ private fun extractMotionPhotoImage(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ val displayName = call.argument<String>("displayName")
+ if (mimeType == null || uri == null || sizeBytes == null) {
+ result.error("extractMotionPhotoImage-args", "missing arguments", null)
+ return
+ }
+
+ MultiPage.getTrailerVideoSize(context, uri, mimeType, sizeBytes)?.let { videoSizeBytes ->
+ val imageSizeBytes = sizeBytes - videoSizeBytes
+ StorageUtils.openInputStream(context, uri)?.let { input ->
+ copyEmbeddedBytes(result, mimeType, displayName, input, imageSizeBytes)
+ }
+ return
+ }
+
+ result.error("extractMotionPhotoImage-empty", "failed to extract image from motion photo at uri=$uri", null)
+ }
+
+ private fun extractMotionPhotoVideo(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ val displayName = call.argument<String>("displayName")
+ if (mimeType == null || uri == null || sizeBytes == null) {
+ result.error("extractMotionPhotoVideo-args", "missing arguments", null)
+ return
+ }
+
+ MultiPage.getMotionPhotoVideoSizing(context, uri, mimeType, sizeBytes)?.let { (videoOffset, videoSize) ->
+ StorageUtils.openInputStream(context, uri)?.let { input ->
+ input.skip(videoOffset)
+ copyEmbeddedBytes(result, MimeTypes.MP4, displayName, input, videoSize)
+ }
+ return
+ }
+
+ result.error("extractMotionPhotoVideo-empty", "failed to extract video from motion photo at uri=$uri", null)
+ }
+
+ private fun extractVideoEmbeddedPicture(call: MethodCall, result: MethodChannel.Result) {
+ val uri = call.argument<String>("uri")?.toUri()
+ val displayName = call.argument<String>("displayName")
+ if (uri == null) {
+ result.error("extractVideoEmbeddedPicture-args", "missing arguments", null)
+ return
+ }
+
+ val retriever = StorageUtils.openMetadataRetriever(context, uri)
+ if (retriever != null) {
+ try {
+ retriever.embeddedPicture?.let { bytes ->
+ var embedMimeType: String? = null
+ bytes.inputStream().use { input ->
+ Helper.readMimeType(input)?.let { embedMimeType = it }
+ }
+ embedMimeType?.let { mime ->
+ copyEmbeddedBytes(result, mime, displayName, bytes.inputStream(), bytes.size.toLong())
+ return
+ }
+ }
+ } catch (e: Exception) {
+ result.error("extractVideoEmbeddedPicture-fetch", "failed to fetch picture for uri=$uri", e.message)
+ } finally {
+ // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs
+ retriever.release()
+ }
+ }
+ result.error("extractVideoEmbeddedPicture-empty", "failed to extract picture for uri=$uri", null)
+ }
+
+ private fun extractXmpDataProp(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ val displayName = call.argument<String>("displayName")
+ val dataProp = call.argument<List<Any>>("propPath")
+ val embedMimeType = call.argument<String>("propMimeType")
+ if (mimeType == null || uri == null || dataProp == null || embedMimeType == null) {
+ result.error("extractXmpDataProp-args", "missing arguments", null)
+ return
+ }
+
+ val props = dataProp.mapNotNull {
+ when (it) {
+ is List<*> -> XMPPropName(it.first() as String, it.last() as String)
+ is Int -> it
+ else -> null
+ }
+ }
+
+ if (canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ // data can be large and stored in "Extended XMP",
+ // which is returned as a second XMP directory
+ val xmpDirs = metadata.getDirectoriesOfType(XmpDirectory::class.java)
+ try {
+ val embedBytes: ByteArray = if (props.size == 1) {
+ val prop = props.first() as XMPPropName
+ xmpDirs.firstNotNullOf { it.xmpMeta.getPropertyBase64(prop.nsUri, prop.toString()) }
+ } else {
+ xmpDirs.firstNotNullOf { it.xmpMeta.getSafeStructField(props) }.let {
+ XMPUtils.decodeBase64(it.value)
+ }
+ }
+
+ copyEmbeddedBytes(result, embedMimeType, displayName, embedBytes.inputStream(), embedBytes.size.toLong())
+ return
+ } catch (e: XMPException) {
+ result.error("extractXmpDataProp-xmp", "failed to read XMP directory for uri=$uri prop=$dataProp", e.message)
+ return
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to extract file from XMP", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to extract file from XMP", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to extract file from XMP", e)
+ }
+ }
+ result.error("extractXmpDataProp-empty", "failed to extract file from XMP uri=$uri prop=$dataProp", null)
+ }
+
+ private fun copyEmbeddedBytes(
+ result: MethodChannel.Result,
+ mimeType: String,
+ displayName: String?,
+ embeddedByteStream: InputStream,
+ embeddedByteLength: Long,
+ ) {
+ val extension = extensionFor(mimeType, defaultExtension = null)
+ val targetFile = StorageUtils.createTempFile(context, extension).apply {
+ transferFrom(embeddedByteStream, embeddedByteLength)
+ }
+
+ val authority = "${context.applicationContext.packageName}.file_provider"
+ val uri = if (displayName != null) {
+ // add extension to ease type identification when sharing this content
+ val displayNameWithExtension = if (displayName.endsWith(extension, ignoreCase = true)) {
+ displayName
+ } else {
+ "$displayName$extension"
+ }
+ FileProvider.getUriForFile(context, authority, targetFile, displayNameWithExtension)
+ } else {
+ FileProvider.getUriForFile(context, authority, targetFile)
+ }
+ val resultFields: FieldMap = hashMapOf(
+ EntryFields.URI to uri.toString(),
+ EntryFields.MIME_TYPE to mimeType,
+ )
+ if (isImage(mimeType) || isVideo(mimeType)) {
+ val provider = getProvider(context, uri)
+ if (provider == null) {
+ result.error("copyEmbeddedBytes-provider", "failed to find provider for uri=$uri", null)
+ return
+ }
+
+ ioScope.launch {
+ provider.fetchSingle(context, uri, mimeType, false, object : ImageProvider.ImageOpCallback {
+ override fun onSuccess(fields: FieldMap) {
+ resultFields.putAll(fields)
+ result.success(resultFields)
+ }
+
+ override fun onFailure(throwable: Throwable) = result.error("copyEmbeddedBytes-failure", "failed to get entry for uri=$uri mime=$mimeType", throwable.message)
+ })
+ }
+ } else {
+ result.success(resultFields)
+ }
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<EmbeddedDataHandler>()
+ const val CHANNEL = "deckers.thibault/aves/embedded"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GeocodingHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GeocodingHandler.kt
new file mode 100644
index 0000000..d8379b5
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GeocodingHandler.kt
@@ -0,0 +1,83 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.Context
+import android.location.Address
+import android.location.Geocoder
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.utils.getFromLocationCompat
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import java.util.Locale
+
+// as of 2021/03/10, geocoding packages exist but:
+// - `geocoder` is unmaintained
+// - `geocoding` method does not return `addressLine` (v2.0.0)
+class GeocodingHandler(private val context: Context) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private var geocoder: Geocoder? = null
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "getAddress" -> ioScope.launch { safe(call, result, ::getAddress) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun getAddress(call: MethodCall, result: MethodChannel.Result) {
+ val latitude = call.argument<Number>("latitude")?.toDouble()
+ val longitude = call.argument<Number>("longitude")?.toDouble()
+ val localeLanguageTag = call.argument<String>("localeLanguageTag")
+ val maxResults = call.argument<Int>("maxResults") ?: 1
+ if (latitude == null || longitude == null) {
+ result.error("getAddress-args", "missing arguments", null)
+ return
+ }
+
+ if (!Geocoder.isPresent()) {
+ result.error("getAddress-unavailable", "Geocoder is unavailable", null)
+ return
+ }
+
+ geocoder = geocoder ?: if (localeLanguageTag != null) {
+ Geocoder(context, Locale.forLanguageTag(localeLanguageTag))
+ } else {
+ Geocoder(context)
+ }
+
+ fun processAddresses(addresses: List<Address>) {
+ if (addresses.isEmpty()) {
+ result.error("getAddress-empty", "failed to find any address for latitude=$latitude, longitude=$longitude", null)
+ } else {
+ val addressMapList: ArrayList<Map<String, String?>> = ArrayList(addresses.map { address ->
+ hashMapOf(
+ "addressLine" to (0..address.maxAddressLineIndex).joinToString(", ") { i -> address.getAddressLine(i) },
+ "adminArea" to address.adminArea,
+ "countryCode" to address.countryCode,
+ "countryName" to address.countryName,
+ "featureName" to address.featureName,
+ "locality" to address.locality,
+ "postalCode" to address.postalCode,
+ "subAdminArea" to address.subAdminArea,
+ "subLocality" to address.subLocality,
+ "subThoroughfare" to address.subThoroughfare,
+ "thoroughfare" to address.thoroughfare,
+ )
+ })
+ result.success(addressMapList)
+ }
+ }
+
+ geocoder!!.getFromLocationCompat(
+ latitude, longitude, maxResults, ::processAddresses,
+ ) { code, message, details -> result.error(code, message, details) }
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/geocoding"
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GlobalSearchHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GlobalSearchHandler.kt
new file mode 100644
index 0000000..b3704db
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/GlobalSearchHandler.kt
@@ -0,0 +1,42 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.Context
+import androidx.core.content.edit
+import deckers.thibault.aves.SearchSuggestionsProvider
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+
+class GlobalSearchHandler(private val context: Context) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "registerCallback" -> ioScope.launch { safe(call, result, ::registerCallback) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun registerCallback(call: MethodCall, result: MethodChannel.Result) {
+ val callbackHandle = call.argument<Number>("callbackHandle")?.toLong()
+ if (callbackHandle == null) {
+ result.error("registerCallback-args", "missing arguments", null)
+ return
+ }
+
+ val preferences = context.getSharedPreferences(SearchSuggestionsProvider.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE)
+ preferences.edit {
+ putLong(SearchSuggestionsProvider.CALLBACK_HANDLE_KEY, callbackHandle)
+ }
+ result.success(true)
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/global_search"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/HomeWidgetHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/HomeWidgetHandler.kt
new file mode 100644
index 0000000..eb6e8e8
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/HomeWidgetHandler.kt
@@ -0,0 +1,32 @@
+package deckers.thibault.aves.channel.calls
+
+import android.appwidget.AppWidgetManager
+import android.content.Context
+import deckers.thibault.aves.HomeWidgetProvider
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+
+class HomeWidgetHandler(private val context: Context) : MethodChannel.MethodCallHandler {
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "update" -> Coresult.safe(call, result, ::update)
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun update(call: MethodCall, result: MethodChannel.Result) {
+ val widgetId = call.argument<Int>("widgetId")
+ if (widgetId == null) {
+ result.error("update-args", "missing arguments", null)
+ return
+ }
+
+ val appWidgetManager = AppWidgetManager.getInstance(context)
+ HomeWidgetProvider().onUpdate(context, appWidgetManager, intArrayOf(widgetId))
+ result.success(null)
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/widget_update"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaEditHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaEditHandler.kt
new file mode 100644
index 0000000..4f48d73
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaEditHandler.kt
@@ -0,0 +1,77 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.ContextWrapper
+import android.util.Log
+import androidx.core.net.toUri
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safeSuspend
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.model.NameConflictStrategy
+import deckers.thibault.aves.model.provider.ImageProvider.ImageOpCallback
+import deckers.thibault.aves.model.provider.ImageProviderFactory.getProvider
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.StorageUtils.ensureTrailingSeparator
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+
+class MediaEditHandler(private val contextWrapper: ContextWrapper) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "cancelFileOp" -> safe(call, result, ::cancelFileOp)
+ "captureFrame" -> ioScope.launch { safeSuspend(call, result, ::captureFrame) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun cancelFileOp(call: MethodCall, result: MethodChannel.Result) {
+ val opId = call.argument<String>("opId")
+ if (opId == null) {
+ result.error("cancelFileOp-args", "missing arguments", null)
+ return
+ }
+
+ Log.i(LOG_TAG, "cancelling file op $opId")
+ cancelledOps.add(opId)
+
+ result.success(null)
+ }
+
+ private suspend fun captureFrame(call: MethodCall, result: MethodChannel.Result) {
+ val uri = call.argument<String>("uri")?.toUri()
+ val desiredName = call.argument<String>("desiredName")
+ val exifFields = call.argument<FieldMap>("exif") ?: HashMap()
+ val bytes = call.argument<ByteArray>("bytes")
+ var destinationDir = call.argument<String>("destinationPath")
+ val nameConflictStrategy = NameConflictStrategy.get(call.argument<String>("nameConflictStrategy"))
+ if (uri == null || desiredName == null || bytes == null || destinationDir == null || nameConflictStrategy == null) {
+ result.error("captureFrame-args", "missing arguments", null)
+ return
+ }
+
+ val provider = getProvider(contextWrapper, uri)
+ if (provider == null) {
+ result.error("captureFrame-provider", "failed to find provider for uri=$uri", null)
+ return
+ }
+
+ destinationDir = ensureTrailingSeparator(destinationDir)
+ provider.captureFrame(contextWrapper, desiredName, exifFields, bytes, destinationDir, nameConflictStrategy, object : ImageOpCallback {
+ override fun onSuccess(fields: FieldMap) = result.success(fields)
+ override fun onFailure(throwable: Throwable) = result.error("captureFrame-failure", "failed to capture frame for uri=$uri", throwable.message)
+ })
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<MediaEditHandler>()
+ const val CHANNEL = "deckers.thibault/aves/media_edit"
+
+ val cancelledOps = HashSet<String>()
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaFetchObjectHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaFetchObjectHandler.kt
new file mode 100644
index 0000000..ead151e
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaFetchObjectHandler.kt
@@ -0,0 +1,68 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.Context
+import android.os.Handler
+import android.os.Looper
+import androidx.core.net.toUri
+import com.bumptech.glide.Glide
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.model.provider.ImageProvider.ImageOpCallback
+import deckers.thibault.aves.model.provider.ImageProviderFactory.getProvider
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+
+class MediaFetchObjectHandler(private val context: Context) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "getEntry" -> ioScope.launch { safe(call, result, ::getEntry) }
+ "clearImageDiskCache" -> ioScope.launch { safe(call, result, ::clearImageDiskCache) }
+ "clearImageMemoryCache" -> ioScope.launch { safe(call, result, ::clearImageMemoryCache) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun getEntry(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType") // MIME type is optional
+ val uri = call.argument<String>("uri")?.toUri()
+ val allowUnsized = call.argument<Boolean>("allowUnsized") ?: false
+ if (uri == null) {
+ result.error("getEntry-args", "missing arguments", null)
+ return
+ }
+
+ val provider = getProvider(context, uri)
+ if (provider == null) {
+ result.error("getEntry-provider", "failed to find provider for uri=$uri mimeType=$mimeType", null)
+ return
+ }
+
+ provider.fetchSingle(context, uri, mimeType, allowUnsized, object : ImageOpCallback {
+ override fun onSuccess(fields: FieldMap) = result.success(fields)
+ override fun onFailure(throwable: Throwable) = result.error("getEntry-failure", "failed to get entry for uri=$uri mimeType=$mimeType", throwable.message)
+ })
+ }
+
+ private fun clearImageDiskCache(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ Glide.get(context).clearDiskCache()
+ result.success(null)
+ }
+
+ private fun clearImageMemoryCache(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ Handler(Looper.getMainLooper()).post {
+ Glide.get(context).clearMemory()
+ }
+ result.success(null)
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/media_fetch_object"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaSessionHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaSessionHandler.kt
new file mode 100644
index 0000000..6a4023e
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaSessionHandler.kt
@@ -0,0 +1,169 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.BroadcastReceiver
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.media.AudioManager
+import android.media.session.PlaybackState
+import android.support.v4.media.MediaMetadataCompat
+import android.support.v4.media.session.MediaSessionCompat
+import android.support.v4.media.session.PlaybackStateCompat
+import androidx.core.net.toUri
+import androidx.media.session.MediaButtonReceiver
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safeSuspend
+import deckers.thibault.aves.channel.streams.platformtodart.MediaCommandStreamHandler
+import deckers.thibault.aves.utils.FlutterUtils
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+
+class MediaSessionHandler(private val context: Context, private val mediaCommandHandler: MediaCommandStreamHandler) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ private var session: MediaSessionCompat? = null
+ private var wasPlaying = false
+ private var isNoisyAudioReceiverRegistered = false
+ private val noisyAudioReceiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) {
+ mediaCommandHandler.callback.onStop()
+ }
+ }
+ }
+
+ fun dispose() {
+ unregisterNoisyAudioReceiver()
+ }
+
+ private fun registerNoisyAudioReceiver() {
+ context.registerReceiver(noisyAudioReceiver, IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY))
+ isNoisyAudioReceiverRegistered = true
+ }
+
+ private fun unregisterNoisyAudioReceiver() {
+ if (isNoisyAudioReceiverRegistered) {
+ context.unregisterReceiver(noisyAudioReceiver)
+ isNoisyAudioReceiverRegistered = false
+ }
+ }
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "update" -> ioScope.launch { safeSuspend(call, result, ::updateSession) }
+ "release" -> ioScope.launch { safe(call, result, ::releaseSession) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private suspend fun updateSession(call: MethodCall, result: MethodChannel.Result) {
+ val uri = call.argument<String>("uri")?.toUri()
+ val title = call.argument<String>("title") ?: uri?.toString()
+ val durationMillis = call.argument<Number>("durationMillis")?.toLong()
+ val stateString = call.argument<String>("state")
+ val positionMillis = call.argument<Number>("positionMillis")?.toLong()
+ val playbackSpeed = call.argument<Number>("playbackSpeed")?.toFloat()
+ val canSkipToNext = call.argument<Boolean>("canSkipToNext")
+ val canSkipToPrevious = call.argument<Boolean>("canSkipToPrevious")
+
+ if (uri == null || title == null || durationMillis == null || stateString == null || positionMillis == null || playbackSpeed == null || canSkipToNext == null || canSkipToPrevious == null) {
+ result.error(
+ "updateSession-args", "missing arguments: uri=$uri, title=$title, durationMillis=$durationMillis" +
+ ", stateString=$stateString, positionMillis=$positionMillis, playbackSpeed=$playbackSpeed, canSkipToNext=$canSkipToNext, canSkipToPrevious=$canSkipToPrevious", null
+ )
+ return
+ }
+
+ val state = when (stateString) {
+ STATE_STOPPED -> PlaybackStateCompat.STATE_STOPPED
+ STATE_PAUSED -> PlaybackStateCompat.STATE_PAUSED
+ STATE_PLAYING -> PlaybackStateCompat.STATE_PLAYING
+ else -> {
+ result.error("updateSession-state", "unknown state=$stateString", null)
+ return
+ }
+ }
+
+ var actions = PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SEEK_TO
+ actions = if (state == PlaybackState.STATE_PLAYING) {
+ actions or PlaybackStateCompat.ACTION_PAUSE or PlaybackStateCompat.ACTION_STOP
+ } else {
+ actions or PlaybackStateCompat.ACTION_PLAY
+ }
+ if (canSkipToNext) {
+ actions = actions or PlaybackStateCompat.ACTION_SKIP_TO_NEXT
+ }
+ if (canSkipToPrevious) {
+ actions = actions or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
+ }
+
+ val playbackState = PlaybackStateCompat.Builder()
+ .setState(
+ state,
+ positionMillis,
+ playbackSpeed,
+ System.currentTimeMillis()
+ )
+ .setActions(actions)
+ .build()
+
+ FlutterUtils.runOnUiThread {
+ try {
+ if (session == null) {
+ val mbrIntent = MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_PLAY_PAUSE)
+ val mbrName = ComponentName(context, MediaButtonReceiver::class.java)
+ session = MediaSessionCompat(context, "aves", mbrName, mbrIntent).apply {
+ setCallback(mediaCommandHandler.callback)
+ }
+ }
+ session!!.apply {
+ val metadata = MediaMetadataCompat.Builder()
+ .putString(MediaMetadataCompat.METADATA_KEY_TITLE, title)
+ .putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, title)
+ .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, durationMillis)
+ .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, uri.toString())
+ .build()
+ setMetadata(metadata)
+ setPlaybackState(playbackState)
+ if (!isActive) {
+ isActive = true
+ }
+ }
+
+ val isPlaying = state == PlaybackStateCompat.STATE_PLAYING
+ if (!wasPlaying && isPlaying) {
+ registerNoisyAudioReceiver()
+ } else if (wasPlaying && !isPlaying) {
+ unregisterNoisyAudioReceiver()
+ }
+ wasPlaying = isPlaying
+
+ result.success(null)
+ } catch (e: Exception) {
+ result.error("updateSession-exception", e.message, e.stackTraceToString())
+ }
+ }
+ }
+
+ private fun releaseSession(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ session?.let {
+ it.release()
+ session = null
+ }
+ result.success(null)
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/media_session"
+
+ const val STATE_STOPPED = "stopped"
+ const val STATE_PAUSED = "paused"
+ const val STATE_PLAYING = "playing"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaStoreHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaStoreHandler.kt
new file mode 100644
index 0000000..64b440b
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MediaStoreHandler.kt
@@ -0,0 +1,85 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.Context
+import android.media.MediaScannerConnection
+import android.net.Uri
+import android.os.Build
+import android.provider.MediaStore
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.model.provider.MediaStoreImageProvider
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+
+class MediaStoreHandler(private val context: Context) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "checkObsoleteContentIds" -> ioScope.launch { safe(call, result, ::checkObsoleteContentIds) }
+ "checkObsoletePaths" -> ioScope.launch { safe(call, result, ::checkObsoletePaths) }
+ "getChangedUris" -> ioScope.launch { safe(call, result, ::getChangedUris) }
+ "getGeneration" -> ioScope.launch { safe(call, result, ::getGeneration) }
+ "scanFile" -> ioScope.launch { safe(call, result, ::scanFile) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun checkObsoleteContentIds(call: MethodCall, result: MethodChannel.Result) {
+ val knownContentIds = call.argument<List<Number?>>("knownContentIds")?.map { it?.toLong() }
+ if (knownContentIds == null) {
+ result.error("checkObsoleteContentIds-args", "missing arguments", null)
+ return
+ }
+ result.success(MediaStoreImageProvider().checkObsoleteContentIds(context, knownContentIds))
+ }
+
+ private fun checkObsoletePaths(call: MethodCall, result: MethodChannel.Result) {
+ val knownPathById = call.argument<Map<Number?, String?>>("knownPathById")?.mapKeys { it.key?.toLong() }
+ if (knownPathById == null) {
+ result.error("checkObsoletePaths-args", "missing arguments", null)
+ return
+ }
+ result.success(MediaStoreImageProvider().checkObsoletePaths(context, knownPathById))
+ }
+
+ private fun getChangedUris(call: MethodCall, result: MethodChannel.Result) {
+ val sinceGeneration = call.argument<Int>("sinceGeneration")
+ if (sinceGeneration == null) {
+ result.error("getChangedUris-args", "missing arguments", null)
+ return
+ }
+ val uris = MediaStoreImageProvider().getChangedUris(context, sinceGeneration)
+ result.success(uris)
+ }
+
+ private fun getGeneration(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ val generation = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ try {
+ MediaStore.getGeneration(context, MediaStore.VOLUME_EXTERNAL_PRIMARY)
+ } catch (e: Exception) {
+ // may yield `IllegalArgumentException: Volume external_primary not found`
+ val volumes = MediaStore.getExternalVolumeNames(context).joinToString(", ")
+ result.error("getGeneration-primary", e.message + " (available volumes are [$volumes])", e)
+ return
+ }
+ } else {
+ null
+ }
+ result.success(generation)
+ }
+
+ private fun scanFile(call: MethodCall, result: MethodChannel.Result) {
+ val path = call.argument<String>("path")
+ val mimeType = call.argument<String>("mimeType")
+ MediaScannerConnection.scanFile(context, arrayOf(path), arrayOf(mimeType)) { _, uri: Uri? -> result.success(uri?.toString()) }
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/media_store"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataEditHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataEditHandler.kt
new file mode 100644
index 0000000..470fc20
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataEditHandler.kt
@@ -0,0 +1,206 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.ContextWrapper
+import androidx.core.net.toUri
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.metadata.Mp4TooLargeException
+import deckers.thibault.aves.model.ExifOrientationOp
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.model.provider.ImageProvider.ImageOpCallback
+import deckers.thibault.aves.model.provider.ImageProviderFactory.getProvider
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import java.io.FileNotFoundException
+
+class MetadataEditHandler(private val contextWrapper: ContextWrapper) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "rotate" -> ioScope.launch { safe(call, result, ::rotate) }
+ "flip" -> ioScope.launch { safe(call, result, ::flip) }
+ "editDate" -> ioScope.launch { safe(call, result, ::editDate) }
+ "editMetadata" -> ioScope.launch { safe(call, result, ::editMetadata) }
+ "removeTrailerVideo" -> ioScope.launch { safe(call, result, ::removeTrailerVideo) }
+ "removeTypes" -> ioScope.launch { safe(call, result, ::removeTypes) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun rotate(call: MethodCall, result: MethodChannel.Result) {
+ val clockwise = call.argument<Boolean>("clockwise")
+ if (clockwise == null) {
+ result.error("rotate-args", "missing arguments", null)
+ return
+ }
+
+ val op = if (clockwise) ExifOrientationOp.ROTATE_CW else ExifOrientationOp.ROTATE_CCW
+ editOrientation(call, result, op)
+ }
+
+ private fun flip(call: MethodCall, result: MethodChannel.Result) {
+ editOrientation(call, result, ExifOrientationOp.FLIP)
+ }
+
+ private fun editOrientation(call: MethodCall, result: MethodChannel.Result, op: ExifOrientationOp) {
+ val entryMap = call.argument<FieldMap>("entry")
+ if (entryMap == null) {
+ result.error("editOrientation-args", "missing arguments", null)
+ return
+ }
+
+ val uri = (entryMap["uri"] as String?)?.toUri()
+ val path = entryMap["path"] as String?
+ val mimeType = entryMap["mimeType"] as String?
+ if (uri == null || path == null || mimeType == null) {
+ result.error("editOrientation-args", "failed because entry fields are missing", null)
+ return
+ }
+
+ val provider = getProvider(contextWrapper, uri)
+ if (provider == null) {
+ result.error("editOrientation-provider", "failed to find provider for uri=$uri", null)
+ return
+ }
+
+ val callback = MetadataOpCallback("editOrientation", entryMap, result)
+ provider.editOrientation(contextWrapper, path, uri, mimeType, op, callback)
+ }
+
+ private fun editDate(call: MethodCall, result: MethodChannel.Result) {
+ val dateMillis = call.argument<Number>("dateMillis")?.toLong()
+ val shiftSeconds = call.argument<Number>("shiftSeconds")?.toLong()
+ val fields = call.argument<List<String>>("fields")
+ val entryMap = call.argument<FieldMap>("entry")
+ if (entryMap == null || fields == null) {
+ result.error("editDate-args", "missing arguments", null)
+ return
+ }
+
+ val uri = (entryMap["uri"] as String?)?.toUri()
+ val path = entryMap["path"] as String?
+ val mimeType = entryMap["mimeType"] as String?
+ if (uri == null || path == null || mimeType == null) {
+ result.error("editDate-args", "failed because entry fields are missing", null)
+ return
+ }
+
+ val provider = getProvider(contextWrapper, uri)
+ if (provider == null) {
+ result.error("editDate-provider", "failed to find provider for uri=$uri", null)
+ return
+ }
+
+ val callback = MetadataOpCallback("editDate", entryMap, result)
+ provider.editDate(contextWrapper, path, uri, mimeType, dateMillis, shiftSeconds, fields, callback)
+ }
+
+ private fun editMetadata(call: MethodCall, result: MethodChannel.Result) {
+ val metadata = call.argument<FieldMap>("metadata")
+ val entryMap = call.argument<FieldMap>("entry")
+ val autoCorrectTrailerOffset = call.argument<Boolean>("autoCorrectTrailerOffset")
+ if (entryMap == null || metadata == null || autoCorrectTrailerOffset == null) {
+ result.error("editMetadata-args", "missing arguments", null)
+ return
+ }
+
+ val uri = (entryMap["uri"] as String?)?.toUri()
+ val path = entryMap["path"] as String?
+ val mimeType = entryMap["mimeType"] as String?
+ if (uri == null || path == null || mimeType == null) {
+ result.error("editMetadata-args", "failed because entry fields are missing", null)
+ return
+ }
+
+ val provider = getProvider(contextWrapper, uri)
+ if (provider == null) {
+ result.error("editMetadata-provider", "failed to find provider for uri=$uri", null)
+ return
+ }
+
+ val callback = MetadataOpCallback("editMetadata", entryMap, result)
+ provider.editMetadata(contextWrapper, path, uri, mimeType, metadata, autoCorrectTrailerOffset, callback)
+ }
+
+ private fun removeTrailerVideo(call: MethodCall, result: MethodChannel.Result) {
+ val entryMap = call.argument<FieldMap>("entry")
+ if (entryMap == null) {
+ result.error("removeTrailerVideo-args", "missing arguments", null)
+ return
+ }
+
+ val uri = (entryMap["uri"] as String?)?.toUri()
+ val path = entryMap["path"] as String?
+ val mimeType = entryMap["mimeType"] as String?
+ if (uri == null || path == null || mimeType == null) {
+ result.error("removeTrailerVideo-args", "failed because entry fields are missing", null)
+ return
+ }
+
+ val provider = getProvider(contextWrapper, uri)
+ if (provider == null) {
+ result.error("removeTrailerVideo-provider", "failed to find provider for uri=$uri", null)
+ return
+ }
+
+ val callback = MetadataOpCallback("removeTrailerVideo", entryMap, result)
+ provider.removeTrailerVideo(contextWrapper, path, uri, mimeType, callback)
+ }
+
+ private fun removeTypes(call: MethodCall, result: MethodChannel.Result) {
+ val types = call.argument<List<String>>("types")
+ val entryMap = call.argument<FieldMap>("entry")
+ if (entryMap == null || types == null) {
+ result.error("removeTypes-args", "missing arguments", null)
+ return
+ }
+
+ val uri = (entryMap["uri"] as String?)?.toUri()
+ val path = entryMap["path"] as String?
+ val mimeType = entryMap["mimeType"] as String?
+ if (uri == null || path == null || mimeType == null) {
+ result.error("removeTypes-args", "failed because entry fields are missing", null)
+ return
+ }
+
+ val provider = getProvider(contextWrapper, uri)
+ if (provider == null) {
+ result.error("removeTypes-provider", "failed to find provider for uri=$uri", null)
+ return
+ }
+
+ val callback = MetadataOpCallback("removeTypes", entryMap, result)
+ provider.removeMetadataTypes(contextWrapper, path, uri, mimeType, types.toSet(), callback)
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/metadata_edit"
+ }
+}
+
+private class MetadataOpCallback(
+ private val errorCodeBase: String,
+ private val entryMap: FieldMap,
+ private val result: MethodChannel.Result,
+) : ImageOpCallback {
+ override fun onSuccess(fields: FieldMap) = result.success(fields)
+ override fun onFailure(throwable: Throwable) {
+ val errorCode = if (throwable is Mp4TooLargeException) {
+ if (throwable.type == "moov") {
+ "$errorCodeBase-mp4largemoov"
+ } else {
+ "$errorCodeBase-mp4largeother"
+ }
+ } else if (throwable is FileNotFoundException) {
+ "$errorCodeBase-filenotfound"
+ } else {
+ "$errorCodeBase-failure"
+ }
+ result.error(errorCode, "failed for entry=$entryMap", throwable)
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataFetchHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataFetchHandler.kt
new file mode 100644
index 0000000..e049c3d
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/MetadataFetchHandler.kt
@@ -0,0 +1,1521 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.Context
+import android.media.MediaFormat
+import android.media.MediaMetadataRetriever
+import android.net.Uri
+import android.os.Build
+import android.util.Log
+import androidx.core.net.toUri
+import com.adobe.internal.xmp.XMPException
+import com.adobe.internal.xmp.XMPMeta
+import com.adobe.internal.xmp.XMPMetaFactory
+import com.adobe.internal.xmp.options.SerializeOptions
+import com.adobe.internal.xmp.properties.XMPPropertyInfo
+import com.drew.lang.KeyValuePair
+import com.drew.lang.Rational
+import com.drew.metadata.Tag
+import com.drew.metadata.avi.AviDirectory
+import com.drew.metadata.exif.ExifDirectoryBase
+import com.drew.metadata.exif.ExifIFD0Directory
+import com.drew.metadata.exif.ExifSubIFDDirectory
+import com.drew.metadata.exif.GpsDirectory
+import com.drew.metadata.file.FileTypeDirectory
+import com.drew.metadata.gif.GifAnimationDirectory
+import com.drew.metadata.iptc.IptcDirectory
+import com.drew.metadata.mov.metadata.QuickTimeMetadataDirectory
+import com.drew.metadata.mp4.media.Mp4UuidBoxDirectory
+import com.drew.metadata.png.PngDirectory
+import com.drew.metadata.webp.WebpDirectory
+import com.drew.metadata.xmp.XmpDirectory
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.metadata.ExifGeoTiffTags
+import deckers.thibault.aves.metadata.ExifInterfaceHelper
+import deckers.thibault.aves.metadata.ExifInterfaceHelper.describeAll
+import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeDateMillis
+import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeDouble
+import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeInt
+import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeRational
+import deckers.thibault.aves.metadata.ExifTags
+import deckers.thibault.aves.metadata.GSpherical
+import deckers.thibault.aves.metadata.GeoTiffKeys
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeDateMillis
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeDescription
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeInt
+import deckers.thibault.aves.metadata.Metadata
+import deckers.thibault.aves.metadata.Metadata.DIR_DNG
+import deckers.thibault.aves.metadata.Metadata.DIR_EXIF_GEOTIFF
+import deckers.thibault.aves.metadata.Metadata.DIR_PNG_TEXTUAL_DATA
+import deckers.thibault.aves.metadata.Metadata.getRotationDegreesForExifCode
+import deckers.thibault.aves.metadata.Metadata.isFlippedForExifCode
+import deckers.thibault.aves.metadata.Mp4ParserHelper
+import deckers.thibault.aves.metadata.MultiPage
+import deckers.thibault.aves.metadata.PixyMetaHelper
+import deckers.thibault.aves.metadata.QuickTimeMetadata
+import deckers.thibault.aves.metadata.metadataextractor.Helper
+import deckers.thibault.aves.metadata.metadataextractor.Helper.PNG_ITXT_DIR_NAME
+import deckers.thibault.aves.metadata.metadataextractor.Helper.PNG_LAST_MODIFICATION_TIME_FORMAT
+import deckers.thibault.aves.metadata.metadataextractor.Helper.PNG_TIME_DIR_NAME
+import deckers.thibault.aves.metadata.metadataextractor.Helper.containsGeoTiffTags
+import deckers.thibault.aves.metadata.metadataextractor.Helper.extractGeoKeys
+import deckers.thibault.aves.metadata.metadataextractor.Helper.extractPngProfile
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getDateDigitizedMillis
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getDateModifiedMillis
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getDateOriginalMillis
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeBoolean
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeDateMillis
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeInt
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeRational
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeString
+import deckers.thibault.aves.metadata.metadataextractor.Helper.isPngTextDir
+import deckers.thibault.aves.metadata.metadataextractor.PngActlDirectory
+import deckers.thibault.aves.metadata.metadataextractor.SafeXmpReader
+import deckers.thibault.aves.metadata.metadataextractor.mpf.MpEntry
+import deckers.thibault.aves.metadata.metadataextractor.mpf.MpEntryDirectory
+import deckers.thibault.aves.metadata.xmp.GoogleXMP
+import deckers.thibault.aves.metadata.xmp.XMP
+import deckers.thibault.aves.metadata.xmp.XMP.doesPropExist
+import deckers.thibault.aves.metadata.xmp.XMP.getPropArrayItemValues
+import deckers.thibault.aves.metadata.xmp.XMP.getSafeDateMillis
+import deckers.thibault.aves.metadata.xmp.XMP.getSafeInt
+import deckers.thibault.aves.metadata.xmp.XMP.getSafeLocalizedText
+import deckers.thibault.aves.metadata.xmp.XMP.hasHdrGainMap
+import deckers.thibault.aves.metadata.xmp.XMP.isMotionPhoto
+import deckers.thibault.aves.metadata.xmp.XMP.isPanorama
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.ContextUtils.queryContentPropValue
+import deckers.thibault.aves.utils.HashUtils
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.TIFF_EXTENSION_PATTERN
+import deckers.thibault.aves.utils.MimeTypes.canReadWithExifInterface
+import deckers.thibault.aves.utils.MimeTypes.canReadWithMetadataExtractor
+import deckers.thibault.aves.utils.MimeTypes.isIsoBMFFImage
+import deckers.thibault.aves.utils.MimeTypes.isVideo
+import deckers.thibault.aves.utils.StorageUtils
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import org.json.JSONObject
+import org.mp4parser.boxes.threegpp.ts26244.LocationInformationBox
+import org.mp4parser.tools.Path
+import java.nio.charset.StandardCharsets
+import java.text.DecimalFormat
+import java.text.ParseException
+import java.util.Locale
+import kotlin.math.roundToInt
+import kotlin.math.roundToLong
+import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface
+
+class MetadataFetchHandler(private val context: Context) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "getAllMetadata" -> ioScope.launch { safe(call, result, ::getAllMetadata) }
+ "getCatalogMetadata" -> ioScope.launch { safe(call, result, ::getCatalogMetadata) }
+ "getOverlayMetadata" -> ioScope.launch { safe(call, result, ::getOverlayMetadata) }
+ "getGeoTiffInfo" -> ioScope.launch { safe(call, result, ::getGeoTiffInfo) }
+ "getMultiPageInfo" -> ioScope.launch { safe(call, result, ::getMultiPageInfo) }
+ "getPanoramaInfo" -> ioScope.launch { safe(call, result, ::getPanoramaInfo) }
+ "getIptc" -> ioScope.launch { safe(call, result, ::getIptc) }
+ "getXmp" -> ioScope.launch { safe(call, result, ::getXmp) }
+ "hasContentResolverProp" -> ioScope.launch { safe(call, result, ::hasContentProp) }
+ "getContentResolverProp" -> ioScope.launch { safe(call, result, ::getContentPropValue) }
+ "getDate" -> ioScope.launch { safe(call, result, ::getDate) }
+ "getFields" -> ioScope.launch { safe(call, result, ::getFields) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun getAllMetadata(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ if (mimeType == null || uri == null) {
+ result.error("getAllMetadata-args", "missing arguments", null)
+ return
+ }
+
+ val metadataMap = HashMap<String, MutableMap<String, String>>()
+ var foundExif = false
+ var foundXmp = false
+ var foundMp4Uuid = false
+
+ fun processXmp(xmpMeta: XMPMeta, dirMap: MutableMap<String, String>, allowMultiple: Boolean = false) {
+ if (foundXmp && !allowMultiple) return
+ foundXmp = true
+ try {
+ for (prop in xmpMeta) {
+ if (prop is XMPPropertyInfo) {
+ val path = prop.path
+ if (path?.isNotEmpty() == true) {
+ val value = if (XMP.isDataPath(path)) VALUE_SKIPPED_DATA else prop.value
+ if (value?.isNotEmpty() == true) {
+ dirMap[path] = value
+ }
+ }
+ }
+ }
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to read XMP directory for uri=$uri", e)
+ }
+ // remove this stat as it is not actual XMP data
+ dirMap.remove(XmpDirectory().getTagName(XmpDirectory.TAG_XMP_VALUE_COUNT))
+ if (dirMap.isNotEmpty()) {
+ // add schema prefixes for namespace resolution
+ val prefixes = XMPMetaFactory.getSchemaRegistry().prefixes
+ dirMap["schemaRegistryPrefixes"] = JSONObject(prefixes).toString()
+ }
+ }
+
+ val mp4UuidDirCount = HashMap<String, Int>()
+ fun processMp4Uuid(dir: Mp4UuidBoxDirectory) {
+ var thisDirName: String
+ when (val uuid = dir.getString(Mp4UuidBoxDirectory.TAG_UUID)) {
+ GSpherical.SPHERICAL_VIDEO_V1_UUID -> {
+ val bytes = dir.getByteArray(Mp4UuidBoxDirectory.TAG_USER_DATA)
+ thisDirName = "Spherical Video"
+ metadataMap[thisDirName] = HashMap(GSpherical(bytes).describe())
+ }
+
+ QuickTimeMetadata.PROF_UUID -> {
+ // redundant with info derived on the Dart side
+ }
+
+ QuickTimeMetadata.USMT_UUID -> {
+ val bytes = dir.getByteArray(Mp4UuidBoxDirectory.TAG_USER_DATA)
+ val blocks = QuickTimeMetadata.parseUuidUsmt(bytes)
+ if (blocks.isNotEmpty()) {
+ thisDirName = "QuickTime User Media"
+ val usmt = metadataMap[thisDirName] ?: HashMap()
+ metadataMap[thisDirName] = usmt
+
+ blocks.forEach {
+ var key = it.type
+ var value = it.value
+ val language = it.language
+
+ var i = 0
+ while (usmt.containsKey(key)) {
+ key = it.type + " (${++i})"
+ }
+ if (language != "und") {
+ value += " ($language)"
+ }
+ usmt[key] = value
+ }
+ }
+ }
+
+ else -> {
+ val uuidPart = uuid.substringBefore('-')
+ thisDirName = "${dir.name} $uuidPart"
+
+ val count = mp4UuidDirCount[uuidPart] ?: 0
+ mp4UuidDirCount[uuidPart] = count + 1
+ if (count > 0) {
+ thisDirName += " ($count)"
+ }
+
+ val dirMap = metadataMap[thisDirName] ?: HashMap()
+ metadataMap[thisDirName] = dirMap
+
+ dirMap.putAll(dir.tags.map { Pair(it.tagName, it.description) })
+ }
+ }
+ }
+
+ if (canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ foundExif = metadata.directories.any { it is ExifDirectoryBase && it.tagCount > 0 }
+ foundMp4Uuid = metadata.directories.any { it is Mp4UuidBoxDirectory && it.tagCount > 0 }
+
+ val dirByName = metadata.directories.filter {
+ (it.tagCount > 0 || it.errorCount > 0 || it is MpEntryDirectory)
+ && it !is FileTypeDirectory
+ && it !is AviDirectory
+ }.groupBy { dir -> dir.name }
+
+ for (dirEntry in dirByName) {
+ val baseDirName = dirEntry.key
+
+ // exclude directories known to be redundant with info derived on the Dart side
+ // they are excluded by name instead of runtime type because excluding `Mp4Directory`
+ // would also exclude derived directories, such as `Mp4UuidBoxDirectory`
+ if (allMetadataRedundantDirNames.contains(baseDirName)) continue
+
+ val sameNameDirs = dirEntry.value
+ val sameNameDirCount = sameNameDirs.size
+ for (dirIndex in 0 until sameNameDirCount) {
+ val dir = sameNameDirs[dirIndex]
+
+ // directory name
+ var thisDirName = baseDirName
+ if (sameNameDirCount > 1 && !allMetadataMergeableDirNames.contains(baseDirName)) {
+ // optional count for multiple directories of the same type
+ thisDirName = "$thisDirName[${dirIndex + 1}]"
+ }
+ // optional parent to distinguish child directories of the same type
+ dir.parent?.name?.let { thisDirName = "$it/$thisDirName" }
+
+ var dirMap = metadataMap[thisDirName] ?: HashMap()
+ if (dir !is Mp4UuidBoxDirectory) {
+ metadataMap[thisDirName] = dirMap
+
+ // tags
+ val tags = dir.tags
+ when {
+ dir is ExifDirectoryBase -> {
+ when {
+ dir.containsGeoTiffTags() -> {
+ // split GeoTIFF tags in their own directory
+ val geoTiffDirMap = metadataMap[DIR_EXIF_GEOTIFF] ?: HashMap()
+ metadataMap[DIR_EXIF_GEOTIFF] = geoTiffDirMap
+ val byGeoTiff = tags.groupBy { ExifTags.isGeoTiffTag(it.tagType) }
+ byGeoTiff[true]?.flatMap { tag ->
+ when (tag.tagType) {
+ ExifGeoTiffTags.TAG_GEO_KEY_DIRECTORY -> {
+ val geoTiffTags = (dir as ExifIFD0Directory).extractGeoKeys(dir.getIntArray(tag.tagType))
+ geoTiffTags.map { geoTag ->
+ val name = GeoTiffKeys.getTagName(geoTag.key) ?: "0x${geoTag.key.toString(16)}"
+ val value = geoTag.value
+ val description = if (value is DoubleArray) value.joinToString(" ") { doubleFormat.format(it) } else "$value"
+ Pair(name, description)
+ }
+ }
+ // skip `Geo double/ascii params`, as their content is split and presented through various GeoTIFF keys
+ ExifGeoTiffTags.TAG_GEO_DOUBLE_PARAMS,
+ ExifGeoTiffTags.TAG_GEO_ASCII_PARAMS -> ArrayList()
+
+ else -> listOf(exifTagMapper(tag))
+ }
+ }?.let { geoTiffDirMap.putAll(it) }
+ byGeoTiff[false]?.map { exifTagMapper(it) }?.let { dirMap.putAll(it) }
+ }
+
+ mimeType == MimeTypes.DNG || mimeType == MimeTypes.DNG_ADOBE -> {
+ // split DNG tags in their own directory
+ val dngDirMap = metadataMap[DIR_DNG] ?: HashMap()
+ metadataMap[DIR_DNG] = dngDirMap
+ val byDng = tags.groupBy { ExifTags.isDngTag(it.tagType) }
+ byDng[true]?.map { exifTagMapper(it) }?.let { dngDirMap.putAll(it) }
+ byDng[false]?.map { exifTagMapper(it) }?.let { dirMap.putAll(it) }
+ }
+
+ else -> dirMap.putAll(tags.map { exifTagMapper(it) })
+ }
+ }
+
+ dir.isPngTextDir() -> {
+ metadataMap.remove(thisDirName)
+ dirMap = metadataMap[DIR_PNG_TEXTUAL_DATA] ?: HashMap()
+ metadataMap[DIR_PNG_TEXTUAL_DATA] = dirMap
+
+ for (tag in tags) {
+ val tagType = tag.tagType
+ if (tagType == PngDirectory.TAG_TEXTUAL_DATA) {
+ val pairs = dir.getObject(tagType) as List<*>
+ val textPairs = pairs.map { pair ->
+ val kv = pair as KeyValuePair
+ val key = kv.key
+ // `PNG-iTXt` uses UTF-8, contrary to `PNG-tEXt` and `PNG-zTXt` using Latin-1 / ISO-8859-1
+ val charset = if (baseDirName == PNG_ITXT_DIR_NAME) {
+ StandardCharsets.UTF_8
+ } else {
+ kv.value.charset
+ }
+ val valueString = String(kv.value.bytes, charset)
+ val dirs = extractPngProfile(key, valueString)
+ if (dirs?.any() == true) {
+ dirs.forEach { profileDir ->
+ val profileDirName = "${dir.name}/${profileDir.name}"
+ val profileDirMap = metadataMap[profileDirName] ?: HashMap()
+ metadataMap[profileDirName] = profileDirMap
+ val profileTags = profileDir.tags
+ if (profileDir is ExifDirectoryBase) {
+ profileDirMap.putAll(profileTags.map { exifTagMapper(it) })
+ } else {
+ profileDirMap.putAll(profileTags.map { Pair(it.tagName, it.description) })
+ }
+ }
+ null
+ } else {
+ Pair(key, valueString)
+ }
+ }
+ dirMap.putAll(textPairs.filterNotNull())
+ } else {
+ dirMap[tag.tagName] = tag.description
+ }
+ }
+ }
+
+ dir is MpEntryDirectory -> {
+ dirMap.putAll(dir.describe())
+ }
+
+ else -> dirMap.putAll(tags.map { Pair(it.tagName, it.description) })
+ }
+ }
+
+ if (!isLargeMp4(mimeType, sizeBytes)) {
+ if (dir is Mp4UuidBoxDirectory) {
+ processMp4Uuid(dir)
+ }
+
+ if (dir is XmpDirectory) {
+ processXmp(dir.xmpMeta, dirMap, allowMultiple = true)
+ }
+ }
+
+ // include errors, if any
+ dir.errors.forEachIndexed { i, error ->
+ dirMap["Error[$i]"] = error
+ }
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ if (!foundExif && canReadWithExifInterface(mimeType)) {
+ // fallback to read EXIF via ExifInterface
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val exif = ExifInterface(input)
+ val allTags = describeAll(exif).toMutableMap()
+ if (foundXmp) {
+ // do not overwrite XMP parsed by metadata-extractor
+ // with raw XMP found by ExifInterface
+ allTags.remove(Metadata.DIR_XMP)
+ } else {
+ val xmpTags = allTags[Metadata.DIR_XMP]
+ if (xmpTags != null) {
+ val xmpRaw = xmpTags[ExifInterface.TAG_XMP]
+ if (xmpRaw != null) {
+ val metadata = com.drew.metadata.Metadata()
+ val xmpBytes = xmpRaw.toByteArray(Charsets.UTF_8)
+ SafeXmpReader().extract(xmpBytes, 0, xmpBytes.size, metadata, null)
+ metadata.getFirstDirectoryOfType(XmpDirectory::class.java)?.let { xmpDir ->
+ val dirMap = HashMap<String, String>()
+ processXmp(xmpDir.xmpMeta, dirMap, allowMultiple = true)
+ allTags[Metadata.DIR_XMP] = dirMap
+ }
+ }
+ }
+ }
+ metadataMap.putAll(allTags.mapValues { it.value.toMutableMap() })
+ }
+ } catch (e: Exception) {
+ // ExifInterface initialization can fail with a RuntimeException
+ // caused by an internal MediaMetadataRetriever failure
+ Log.w(LOG_TAG, "failed to get metadata by ExifInterface for uri=$uri", e)
+ }
+ }
+
+ fun fallbackProcessXmp(xmpMeta: XMPMeta) {
+ val thisDirName = XmpDirectory().name
+ val dirMap = metadataMap[thisDirName] ?: HashMap()
+ processXmp(xmpMeta, dirMap)
+ if (dirMap.isNotEmpty()) {
+ metadataMap[thisDirName] = dirMap
+ }
+ }
+
+ XMP.checkIsoBMFFImage(context, mimeType, uri, foundXmp, ::fallbackProcessXmp)
+ // `metadata-extractor` may fail to get UUID boxes for some MP4 files,
+ // so we always check with `mp4parser`, even for smaller files
+ XMP.checkMp4(context, mimeType, uri) { dirs ->
+ for (dir in dirs.filterIsInstance<XmpDirectory>()) {
+ fallbackProcessXmp(dir.xmpMeta)
+ }
+ if (!foundMp4Uuid) {
+ for (dir in dirs.filterIsInstance<Mp4UuidBoxDirectory>()) {
+ processMp4Uuid(dir)
+ }
+ }
+ }
+
+ if (isVideo(mimeType)) {
+ // `metadata-extractor` do not extract custom tags in user data box
+ Mp4ParserHelper.getUserDataBox(context, mimeType, uri)?.let { box ->
+ metadataMap[Metadata.DIR_MP4_USER_DATA] = Mp4ParserHelper.extractBoxFields(box)
+ }
+
+ // this is used as fallback when the video metadata cannot be found on the Dart side
+ // and to identify whether there is an accessible cover image
+ // do not include HEIC here
+ val mediaDir = getAllMetadataByMediaMetadataRetriever(uri)
+ if (mediaDir.isNotEmpty()) {
+ metadataMap[Metadata.DIR_MEDIA] = mediaDir
+ if (mediaDir.containsKey(KEY_HAS_EMBEDDED_PICTURE)) {
+ metadataMap[Metadata.DIR_COVER_ART] = hashMapOf(
+ // dummy entry value
+ "Image" to "data",
+ )
+ }
+ }
+ // Android's `MediaExtractor` and `MediaPlayer` cannot be used for details
+ // about embedded images as they do not list them as separate tracks
+ // and only identify at most one
+ } else if (isIsoBMFFImage(mimeType)) {
+ Mp4ParserHelper.getSamsungSefd(context, uri)?.let { (_, bytes) ->
+ metadataMap[Mp4ParserHelper.SAMSUNG_MAKERNOTE_BOX_TYPE] = hashMapOf(
+ "Size" to bytes.size.toString(),
+ )
+ }
+ }
+
+ if (metadataMap.isNotEmpty()) {
+ result.success(metadataMap)
+ } else {
+ result.error("getAllMetadata-failure", "failed to get metadata for mimeType=$mimeType uri=$uri", null)
+ }
+ }
+
+ private fun getAllMetadataByMediaMetadataRetriever(uri: Uri): MutableMap<String, String> {
+ val dirMap = HashMap<String, String>()
+ val retriever = StorageUtils.openMetadataRetriever(context, uri) ?: return dirMap
+ try {
+ for ((code, name) in MediaMetadataRetrieverHelper.allKeys) {
+ retriever.getSafeDescription(code) { dirMap[name] = it }
+ }
+ if (retriever.embeddedPicture != null) {
+ // additional key for the Dart side to know whether to add a `Cover` section
+ dirMap[KEY_HAS_EMBEDDED_PICTURE] = "yes"
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get video metadata by MediaMetadataRetriever for uri=$uri", e)
+ } finally {
+ // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs
+ retriever.release()
+ }
+ return dirMap
+ }
+
+ // set `KEY_DATE_MILLIS` from these fields (by precedence):
+ // - Exif / DATETIME_ORIGINAL
+ // - Exif / DATETIME
+ // - XMP / xmp:CreateDate
+ // - XMP / photoshop:DateCreated
+ // - PNG / TIME / LAST_MODIFICATION_TIME
+ // - Video / METADATA_KEY_DATE
+ // set `KEY_XMP_TITLE` from these fields (by precedence):
+ // - XMP / dc:title
+ // - IPTC / object-name
+ // set `KEY_XMP_SUBJECTS` from these fields (by precedence):
+ // - XMP / dc:subject
+ // - IPTC / keywords
+ // set `KEY_RATING` from these fields (by precedence):
+ // - XMP / xmp:Rating
+ // - XMP / MicrosoftPhoto:Rating
+ private fun getCatalogMetadata(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val path = call.argument<String>("path")
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ if (mimeType == null || uri == null) {
+ result.error("getCatalogMetadata-args", "missing arguments", null)
+ return
+ }
+
+ val metadataMap = HashMap<String, Any>()
+ getCatalogMetadataByMetadataExtractor(mimeType, uri, path, sizeBytes, metadataMap)
+
+ if (isVideo(mimeType) || isIsoBMFFImage(mimeType)) {
+ getMultimediaCatalogMetadataByMediaMetadataRetriever(mimeType, uri, metadataMap)
+
+ // fallback to MP4 `loci` box for location
+ if (!metadataMap.contains(KEY_LATITUDE) || !metadataMap.contains(KEY_LONGITUDE)) {
+ try {
+ Mp4ParserHelper.getUserDataBox(context, mimeType, uri)?.let { userDataBox ->
+ Path.getPath<LocationInformationBox>(userDataBox, LocationInformationBox.TYPE)?.let { locationBox ->
+ if (!locationBox.isParsed) {
+ locationBox.parseDetails()
+ }
+ metadataMap[KEY_LATITUDE] = locationBox.latitude
+ metadataMap[KEY_LONGITUDE] = locationBox.longitude
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get Location Information box by MP4 parser for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+ }
+
+ if (isIsoBMFFImage(mimeType)) {
+ val flags = (metadataMap[KEY_FLAGS] ?: 0) as Int
+ if ((flags and MASK_IS_MOTION_PHOTO == 0) && MultiPage.isIsoBMFFImageSefdMotionPhoto(context, uri)) {
+ metadataMap[KEY_FLAGS] = flags or MASK_IS_MULTIPAGE or MASK_IS_MOTION_PHOTO
+ }
+ }
+
+ // report success even when empty
+ result.success(metadataMap)
+ }
+
+ private fun getCatalogMetadataByMetadataExtractor(
+ mimeType: String,
+ uri: Uri,
+ path: String?,
+ sizeBytes: Long?,
+ metadataMap: HashMap<String, Any>,
+ ) {
+ var flags = (metadataMap[KEY_FLAGS] ?: 0) as Int
+ var foundExif = false
+ var foundXmp = false
+ var foundMp4Uuid = false
+
+ fun processXmp(xmpMeta: XMPMeta, allowMultiple: Boolean = false) {
+ if (foundXmp && !allowMultiple) return
+ foundXmp = true
+ try {
+ if (xmpMeta.doesPropExist(XMP.DC_SUBJECT_PROP_NAME)) {
+ val values = xmpMeta.getPropArrayItemValues(XMP.DC_SUBJECT_PROP_NAME)
+ metadataMap[KEY_XMP_SUBJECTS] = values.joinToString(XMP_SUBJECTS_SEPARATOR)
+ }
+ xmpMeta.getSafeLocalizedText(XMP.DC_TITLE_PROP_NAME, acceptBlank = false) { metadataMap[KEY_XMP_TITLE] = it }
+ if (!metadataMap.containsKey(KEY_DATE_MILLIS)) {
+ xmpMeta.getSafeDateMillis(XMP.XMP_CREATE_DATE_PROP_NAME) { metadataMap[KEY_DATE_MILLIS] = it }
+ if (!metadataMap.containsKey(KEY_DATE_MILLIS)) {
+ xmpMeta.getSafeDateMillis(XMP.PS_DATE_CREATED_PROP_NAME) { metadataMap[KEY_DATE_MILLIS] = it }
+ }
+ }
+
+ xmpMeta.getSafeInt(XMP.XMP_RATING_PROP_NAME) { metadataMap[KEY_RATING] = it }
+ if (!metadataMap.containsKey(KEY_RATING)) {
+ xmpMeta.getSafeInt(XMP.MS_RATING_PROP_NAME) { percentRating ->
+ // values of 1,25,50,75,99% correspond to 1,2,3,4,5 stars
+ val standardRating = (percentRating / 25f).roundToInt() + 1
+ metadataMap[KEY_RATING] = standardRating
+ }
+ }
+
+ // identification of panorama (aka photo sphere)
+ if (xmpMeta.isPanorama()) {
+ flags = flags or MASK_IS_360
+ }
+
+ // identification of motion photo
+ if (xmpMeta.isMotionPhoto()) {
+ flags = flags or MASK_IS_MULTIPAGE or MASK_IS_MOTION_PHOTO
+ }
+
+ // identification of embedded gain map
+ if (xmpMeta.hasHdrGainMap()) {
+ flags = flags or MASK_IS_HDR
+ }
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to read XMP directory for uri=$uri", e)
+ }
+ }
+
+ fun processMp4Uuid(dir: Mp4UuidBoxDirectory) {
+ // identification of spherical video (aka 360° video)
+ if (dir.getString(Mp4UuidBoxDirectory.TAG_UUID) == GSpherical.SPHERICAL_VIDEO_V1_UUID) {
+ flags = flags or MASK_IS_360
+ }
+ }
+
+ if (canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ foundExif = metadata.directories.any { it is ExifDirectoryBase && it.tagCount > 0 }
+ foundMp4Uuid = metadata.directories.any { it is Mp4UuidBoxDirectory && it.tagCount > 0 }
+
+ // File type
+ for (dir in metadata.getDirectoriesOfType(FileTypeDirectory::class.java)) {
+ // * `metadata-extractor` sometimes detects the wrong MIME type (e.g. `pef` file as `tiff`, `mpeg` as `dvd`, `avif` as `mov`)
+ // * the content resolver / media store sometimes reports the wrong MIME type (e.g. `png` file as `jpeg`, `tiff` as `srw`)
+ // * `context.getContentResolver().getType()` sometimes returns an incorrect value
+ // * `MediaMetadataRetriever.setDataSource()` sometimes fails with `status = 0x80000000`
+ // * file extension is unreliable
+ // In the end, `metadata-extractor` is the most reliable, except for `tiff`/`dvd`/`mov`/`zip` (false positives, false negatives),
+ // in which case we trust the file extension
+ // cf https://github.com/drewnoakes/metadata-extractor/issues/296
+ if (path?.matches(TIFF_EXTENSION_PATTERN) == true) {
+ metadataMap[KEY_MIME_TYPE] = MimeTypes.TIFF
+ } else {
+ dir.getSafeString(FileTypeDirectory.TAG_DETECTED_FILE_MIME_TYPE) {
+ if (it != MimeTypes.TIFF && it != MimeTypes.DVD && it != MimeTypes.MOV && it != MimeTypes.ZIP) {
+ metadataMap[KEY_MIME_TYPE] = it
+ }
+ }
+ }
+ }
+
+ // EXIF
+ for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) {
+ dir.getDateOriginalMillis { metadataMap[KEY_DATE_MILLIS] = it }
+ if (!metadataMap.containsKey(KEY_DATE_MILLIS)) {
+ // fetch date modified from SubIFD directory first, as the sub-second tag is here
+ dir.getDateModifiedMillis { metadataMap[KEY_DATE_MILLIS] = it }
+ }
+ }
+ for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) {
+ if (!metadataMap.containsKey(KEY_DATE_MILLIS)) {
+ // fallback to fetch date modified from IFD0 directory, without the sub-second tag
+ // in case there was no SubIFD directory
+ dir.getSafeDateMillis(ExifIFD0Directory.TAG_DATETIME, null)?.let { metadataMap[KEY_DATE_MILLIS] = it }
+ }
+ dir.getSafeInt(ExifDirectoryBase.TAG_ORIENTATION) {
+ val orientation = it
+ if (isFlippedForExifCode(orientation)) {
+ flags = flags or MASK_IS_FLIPPED
+ }
+ metadataMap[KEY_ROTATION_DEGREES] = getRotationDegreesForExifCode(orientation)
+ }
+ }
+
+ // GPS
+ for (dir in metadata.getDirectoriesOfType(GpsDirectory::class.java)) {
+ val geoLocation = dir.geoLocation
+ if (geoLocation != null) {
+ metadataMap[KEY_LATITUDE] = geoLocation.latitude
+ metadataMap[KEY_LONGITUDE] = geoLocation.longitude
+ }
+ }
+
+ // JPEG Multi-Picture Format
+ if (metadata.getDirectoriesOfType(MpEntryDirectory::class.java).count { !it.entry.isThumbnail } > 1) {
+ flags = flags or MASK_IS_MULTIPAGE
+
+ if (hasAppleHdrGainMap(uri, sizeBytes)) {
+ flags = flags or MASK_IS_HDR
+ }
+ }
+
+ // XMP
+ if (!isLargeMp4(mimeType, sizeBytes)) {
+ metadata.getDirectoriesOfType(XmpDirectory::class.java).map { it.xmpMeta }.forEach {
+ processXmp(it, allowMultiple = true)
+ }
+
+ // XMP fallback to IPTC
+ if (!metadataMap.containsKey(KEY_XMP_TITLE) || !metadataMap.containsKey(KEY_XMP_SUBJECTS)) {
+ for (dir in metadata.getDirectoriesOfType(IptcDirectory::class.java)) {
+ if (!metadataMap.containsKey(KEY_XMP_TITLE)) {
+ dir.getSafeString(IptcDirectory.TAG_OBJECT_NAME, acceptBlank = false) { metadataMap[KEY_XMP_TITLE] = it }
+ }
+ if (!metadataMap.containsKey(KEY_XMP_SUBJECTS)) {
+ dir.keywords?.let { metadataMap[KEY_XMP_SUBJECTS] = it.joinToString(XMP_SUBJECTS_SEPARATOR) }
+ }
+ }
+ }
+ }
+
+ if (!metadataMap.containsKey(KEY_LATITUDE) || !metadataMap.containsKey(KEY_LONGITUDE)) {
+ for (dir in metadata.getDirectoriesOfType(QuickTimeMetadataDirectory::class.java)) {
+ dir.getSafeString(QuickTimeMetadataDirectory.TAG_LOCATION_ISO6709) { locationString ->
+ val matcher = Metadata.VIDEO_LOCATION_PATTERN.matcher(locationString)
+ if (matcher.find() && matcher.groupCount() >= 2) {
+ val latitude = matcher.group(1)?.toDoubleOrNull()
+ val longitude = matcher.group(2)?.toDoubleOrNull()
+ if (latitude != null && longitude != null) {
+ metadataMap[KEY_LATITUDE] = latitude
+ metadataMap[KEY_LONGITUDE] = longitude
+ }
+ }
+ }
+ }
+ }
+
+ when (mimeType) {
+ MimeTypes.PNG -> {
+ // date fallback to PNG time chunk
+ if (!metadataMap.containsKey(KEY_DATE_MILLIS)) {
+ for (dir in metadata.getDirectoriesOfType(PngDirectory::class.java).filter { it.name == PNG_TIME_DIR_NAME }) {
+ dir.getSafeString(PngDirectory.TAG_LAST_MODIFICATION_TIME) {
+ try {
+ PNG_LAST_MODIFICATION_TIME_FORMAT.parse(it)?.let { date ->
+ metadataMap[KEY_DATE_MILLIS] = date.time
+ }
+ } catch (e: ParseException) {
+ Log.w(LOG_TAG, "failed to parse PNG date=$it for uri=$uri", e)
+ }
+ }
+ }
+ }
+
+ // identification of animated PNG
+ if (metadata.containsDirectoryOfType(PngActlDirectory::class.java)) {
+ flags = flags or MASK_IS_ANIMATED
+ }
+ }
+
+ MimeTypes.GIF -> {
+ // identification of animated GIF
+ if (metadata.containsDirectoryOfType(GifAnimationDirectory::class.java)) {
+ flags = flags or MASK_IS_ANIMATED
+ }
+ }
+
+ MimeTypes.WEBP -> {
+ // identification of animated WEBP
+ for (dir in metadata.getDirectoriesOfType(WebpDirectory::class.java)) {
+ dir.getSafeBoolean(WebpDirectory.TAG_IS_ANIMATION) {
+ if (it) flags = flags or MASK_IS_ANIMATED
+ }
+ }
+ }
+
+ MimeTypes.TIFF -> {
+ // identification of GeoTIFF
+ for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) {
+ if (dir.containsGeoTiffTags()) {
+ flags = flags or MASK_IS_GEOTIFF
+ }
+ }
+ }
+ }
+
+ metadata.getDirectoriesOfType(Mp4UuidBoxDirectory::class.java).forEach(::processMp4Uuid)
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ if (!foundExif && canReadWithExifInterface(mimeType)) {
+ // fallback to read EXIF via ExifInterface
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val exif = ExifInterface(input)
+ exif.getSafeDateMillis(ExifInterface.TAG_DATETIME_ORIGINAL, ExifInterface.TAG_SUBSEC_TIME_ORIGINAL) { metadataMap[KEY_DATE_MILLIS] = it }
+ if (!metadataMap.containsKey(KEY_DATE_MILLIS)) {
+ exif.getSafeDateMillis(ExifInterface.TAG_DATETIME, ExifInterface.TAG_SUBSEC_TIME) { metadataMap[KEY_DATE_MILLIS] = it }
+ }
+ exif.getSafeInt(ExifInterface.TAG_ORIENTATION, acceptZero = false) {
+ if (exif.isFlipped) flags = flags or MASK_IS_FLIPPED
+ metadataMap[KEY_ROTATION_DEGREES] = exif.rotationDegrees
+ }
+ val latLong = exif.latLong
+ if (latLong?.size == 2) {
+ metadataMap[KEY_LATITUDE] = latLong[0]
+ metadataMap[KEY_LONGITUDE] = latLong[1]
+ }
+ }
+ } catch (e: Exception) {
+ // ExifInterface initialization can fail with a RuntimeException
+ // caused by an internal MediaMetadataRetriever failure
+ Log.w(LOG_TAG, "failed to get metadata by ExifInterface for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ XMP.checkIsoBMFFImage(context, mimeType, uri, foundXmp, ::processXmp)
+ // `metadata-extractor` may fail to get UUID boxes for some MP4 files,
+ // so we always check with `mp4parser`, even for smaller files
+ XMP.checkMp4(context, mimeType, uri) { dirs ->
+ for (dir in dirs.filterIsInstance<XmpDirectory>()) {
+ processXmp(dir.xmpMeta)
+ }
+ if (!foundMp4Uuid) {
+ for (dir in dirs.filterIsInstance<Mp4UuidBoxDirectory>()) {
+ processMp4Uuid(dir)
+ }
+ }
+ }
+
+ if (mimeType == MimeTypes.TIFF && MultiPage.isMultiPageTiff(context, uri)) flags = flags or MASK_IS_MULTIPAGE
+
+ metadataMap[KEY_FLAGS] = flags
+ }
+
+ private fun hasAppleHdrGainMap(uri: Uri, sizeBytes: Long?): Boolean {
+ val mpEntries = MultiPage.getJpegMpfEntries(context, uri, sizeBytes) ?: return false
+ mpEntries.filter { it.type == MpEntry.TYPE_UNDEFINED }.forEachIndexed { mpIndex, mpEntry ->
+ var dataOffset = mpEntry.dataOffset
+ if (dataOffset > 0) {
+ val baseOffset = MultiPage.getJpegMpfBaseOffset(context, uri, sizeBytes)
+ if (baseOffset != null) {
+ dataOffset += baseOffset
+ }
+ }
+ StorageUtils.openInputStream(context, uri)?.let { input ->
+ input.skip(dataOffset)
+ try {
+ val pageMetadata = Helper.safeRead(input, sizeBytes)
+ if (pageMetadata.getDirectoriesOfType(XmpDirectory::class.java).any { it.xmpMeta.hasHdrGainMap() }) {
+ return true
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for uri=$uri mpIndex=$mpIndex mpEntry=$mpEntry", e)
+ }
+ }
+ }
+ return false
+ }
+
+ private fun getMultimediaCatalogMetadataByMediaMetadataRetriever(
+ mimeType: String,
+ uri: Uri,
+ metadataMap: HashMap<String, Any>,
+ ) {
+ val retriever = StorageUtils.openMetadataRetriever(context, uri) ?: return
+
+ var flags = (metadataMap[KEY_FLAGS] ?: 0) as Int
+ try {
+ retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION) { metadataMap[KEY_ROTATION_DEGREES] = it }
+ if (!metadataMap.containsKey(KEY_DATE_MILLIS)) {
+ retriever.getSafeDateMillis(MediaMetadataRetriever.METADATA_KEY_DATE) { metadataMap[KEY_DATE_MILLIS] = it }
+ }
+
+ if (!metadataMap.containsKey(KEY_LATITUDE) || !metadataMap.containsKey(KEY_LONGITUDE)) {
+ val locationString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_LOCATION)
+ if (locationString != null) {
+ val matcher = Metadata.VIDEO_LOCATION_PATTERN.matcher(locationString)
+ if (matcher.find() && matcher.groupCount() >= 2) {
+ val latitude = matcher.group(1)?.toDoubleOrNull()
+ val longitude = matcher.group(2)?.toDoubleOrNull()
+ if (latitude != null && longitude != null) {
+ metadataMap[KEY_LATITUDE] = latitude
+ metadataMap[KEY_LONGITUDE] = longitude
+ }
+ }
+ }
+ }
+
+ if (isIsoBMFFImage(mimeType)) {
+ retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS) {
+ if (it > 1) flags = flags or MASK_IS_MULTIPAGE
+ }
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_COLOR_TRANSFER) {
+ if (it == MediaFormat.COLOR_TRANSFER_ST2084 || it == MediaFormat.COLOR_TRANSFER_HLG) {
+ flags = flags or MASK_IS_HDR
+ }
+ }
+ }
+
+ metadataMap[KEY_FLAGS] = flags
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get catalog metadata by MediaMetadataRetriever for uri=$uri", e)
+ } finally {
+ // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs
+ retriever.release()
+ }
+ }
+
+ private fun getOverlayMetadata(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ val fields = call.argument<List<String>>("fields")
+ if (mimeType == null || uri == null || fields == null) {
+ result.error("getOverlayMetadata-args", "missing arguments", null)
+ return
+ }
+
+ val metadataMap = HashMap<String, Any>()
+ if (fields.isEmpty() || isVideo(mimeType)) {
+ result.success(metadataMap)
+ return
+ }
+
+ val saveExposureTime = fun(value: Rational) {
+ // `TAG_EXPOSURE_TIME` as a string is sometimes a ratio, sometimes a decimal
+ // so we explicitly request it as a rational (e.g. 1/100, 1/14, 71428571/1000000000, 4000/1000, 2000000000/500000000)
+ // and process it to make sure the numerator is `1` when the ratio value is less than 1
+ val num = value.numerator
+ val denom = value.denominator
+ metadataMap[KEY_EXPOSURE_TIME] = when {
+ num >= denom -> "${value.toSimpleString(true)}″"
+ num != 1L && num != 0L -> Rational(1, (denom / num.toDouble()).roundToLong()).toString()
+ else -> value.toString()
+ }
+ }
+
+ var foundExif = false
+ if (canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) {
+ foundExif = true
+ if (fields.contains(KEY_APERTURE)) {
+ dir.getSafeRational(ExifDirectoryBase.TAG_FNUMBER) { metadataMap[KEY_APERTURE] = it.numerator.toDouble() / it.denominator }
+ }
+ if (fields.contains(KEY_DESCRIPTION)) {
+ getDescriptionByMetadataExtractor(metadata)?.let { metadataMap[KEY_DESCRIPTION] = it }
+ }
+ if (fields.contains(KEY_EXPOSURE_TIME)) {
+ dir.getSafeRational(ExifDirectoryBase.TAG_EXPOSURE_TIME, saveExposureTime)
+ }
+ if (fields.contains(KEY_FOCAL_LENGTH)) {
+ dir.getSafeRational(ExifDirectoryBase.TAG_FOCAL_LENGTH) { metadataMap[KEY_FOCAL_LENGTH] = it.numerator.toDouble() / it.denominator }
+ }
+ if (fields.contains(KEY_ISO)) {
+ dir.getSafeInt(ExifDirectoryBase.TAG_ISO_EQUIVALENT) { metadataMap[KEY_ISO] = it }
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ if (!foundExif && canReadWithExifInterface(mimeType)) {
+ // fallback to read EXIF via ExifInterface
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val exif = ExifInterface(input)
+ if (fields.contains(KEY_APERTURE)) {
+ exif.getSafeDouble(ExifInterface.TAG_F_NUMBER) { metadataMap[KEY_APERTURE] = it }
+ }
+ if (fields.contains(KEY_EXPOSURE_TIME)) {
+ exif.getSafeRational(ExifInterface.TAG_EXPOSURE_TIME, saveExposureTime)
+ }
+ if (fields.contains(KEY_FOCAL_LENGTH)) {
+ exif.getSafeDouble(ExifInterface.TAG_FOCAL_LENGTH) { metadataMap[KEY_FOCAL_LENGTH] = it }
+ }
+ if (fields.contains(KEY_ISO)) {
+ exif.getSafeInt(ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY) { metadataMap[KEY_ISO] = it }
+ }
+ }
+ } catch (e: Exception) {
+ // ExifInterface initialization can fail with a RuntimeException
+ // caused by an internal MediaMetadataRetriever failure
+ Log.w(LOG_TAG, "failed to get metadata by ExifInterface for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ result.success(metadataMap)
+ }
+
+ // returns description from these fields (by precedence):
+ // - XMP / dc:description
+ // - IPTC / caption-abstract
+ // - Exif / UserComment
+ // - Exif / ImageDescription
+ private fun getDescriptionByMetadataExtractor(metadata: com.drew.metadata.Metadata): String? {
+ var description: String? = null
+ for (dir in metadata.getDirectoriesOfType(XmpDirectory::class.java)) {
+ val xmpMeta = dir.xmpMeta
+ try {
+ if (xmpMeta.doesPropExist(XMP.DC_DESCRIPTION_PROP_NAME)) {
+ xmpMeta.getSafeLocalizedText(XMP.DC_DESCRIPTION_PROP_NAME, acceptBlank = false) { description = it }
+ }
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to read XMP directory", e)
+ }
+ }
+ if (description == null) {
+ for (dir in metadata.getDirectoriesOfType(IptcDirectory::class.java)) {
+ dir.getSafeString(IptcDirectory.TAG_CAPTION, acceptBlank = false) { description = it }
+ }
+ }
+ if (description == null) {
+ for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) {
+ // user comment field specifies encoding, unlike other string fields
+ if (dir.containsTag(ExifSubIFDDirectory.TAG_USER_COMMENT)) {
+ val string = dir.getDescription(ExifSubIFDDirectory.TAG_USER_COMMENT)
+ if (string.isNotBlank()) {
+ description = string
+ }
+ }
+ }
+ }
+ if (description == null) {
+ for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) {
+ dir.getSafeString(ExifIFD0Directory.TAG_IMAGE_DESCRIPTION, acceptBlank = false) { description = it }
+ }
+ }
+ return description
+ }
+
+ private fun getGeoTiffInfo(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ if (mimeType == null || uri == null) {
+ result.error("getGeoTiffInfo-args", "missing arguments", null)
+ return
+ }
+
+ if (canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ val fields = HashMap<Int, Any?>()
+ for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) {
+ if (dir.containsGeoTiffTags()) {
+ fields.putAll(dir.tags.map { it.tagType }.filter { ExifTags.isGeoTiffTag(it) }.map {
+ val value = when (it) {
+ ExifGeoTiffTags.TAG_GEO_ASCII_PARAMS -> dir.getString(it)
+ else -> dir.getObject(it)
+ }
+ Pair(it, value)
+ })
+ val geoKeyDirectory = dir.getIntArray(ExifGeoTiffTags.TAG_GEO_KEY_DIRECTORY)
+ fields.putAll((dir as ExifIFD0Directory).extractGeoKeys(geoKeyDirectory))
+ }
+ }
+ result.success(fields)
+ return
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+ result.error("getGeoTiffInfo-empty", "failed to get info for mimeType=$mimeType uri=$uri", null)
+ }
+
+ private fun getMultiPageInfo(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ val isMotionPhoto = call.argument<Boolean>("isMotionPhoto")
+ if (mimeType == null || uri == null || sizeBytes == null || isMotionPhoto == null) {
+ result.error("getMultiPageInfo-args", "missing arguments", null)
+ return
+ }
+
+ val pages: ArrayList<FieldMap>? = if (isMotionPhoto) {
+ MultiPage.getMotionPhotoPages(context, uri, mimeType, sizeBytes)
+ } else {
+ when (mimeType) {
+ MimeTypes.HEIC, MimeTypes.HEIF -> MultiPage.getHeicTracks(context, uri)
+ MimeTypes.JPEG -> MultiPage.getJpegMpfPages(context, uri, sizeBytes)
+ MimeTypes.TIFF -> MultiPage.getTiffPages(context, uri)
+ else -> null
+ }
+ }
+ if (pages?.isEmpty() == true) {
+ result.error("getMultiPageInfo-empty", "failed to get pages for mimeType=$mimeType uri=$uri", null)
+ } else {
+ result.success(pages)
+ }
+ }
+
+ private fun getPanoramaInfo(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ if (mimeType == null || uri == null) {
+ result.error("getPanoramaInfo-args", "missing arguments", null)
+ return
+ }
+
+ val fields: FieldMap = hashMapOf()
+ var foundXmp = false
+
+ fun processXmp(xmpMeta: XMPMeta, allowMultiple: Boolean = false) {
+ if (foundXmp && !allowMultiple) return
+ foundXmp = true
+ fields.putAll(GoogleXMP.getPanoramaInfo(xmpMeta))
+ }
+
+ if (canReadWithMetadataExtractor(mimeType) && !isLargeMp4(mimeType, sizeBytes)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ metadata.getDirectoriesOfType(XmpDirectory::class.java).map { it.xmpMeta }.forEach {
+ processXmp(it, allowMultiple = true)
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ XMP.checkIsoBMFFImage(context, mimeType, uri, foundXmp, ::processXmp)
+ // `metadata-extractor` may fail to get UUID boxes for some MP4 files,
+ // so we always check with `mp4parser`, even for smaller files
+ XMP.checkMp4(context, mimeType, uri) { dirs ->
+ for (dir in dirs.filterIsInstance<XmpDirectory>()) {
+ processXmp(dir.xmpMeta)
+ }
+ }
+
+ if (fields.isEmpty()) {
+ result.error("getPanoramaInfo-empty", "failed to get info for mimeType=$mimeType uri=$uri", null)
+ } else {
+ fields["projectionType"] = fields["projectionType"] ?: GoogleXMP.GPANO_PROJECTION_TYPE_DEFAULT
+ result.success(fields)
+ }
+ }
+
+ private fun getIptc(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ if (mimeType == null || uri == null) {
+ result.error("getIptc-args", "missing arguments", null)
+ return
+ }
+
+ if (MimeTypes.canReadWithPixyMeta(mimeType)) {
+ try {
+ StorageUtils.openInputStream(context, uri)?.use { input ->
+ val iptcDataList = PixyMetaHelper.getIptc(input)
+ result.success(iptcDataList)
+ return
+ }
+ } catch (e: Exception) {
+ result.error("getIptc-exception", "failed to read IPTC for mimeType=$mimeType uri=$uri", e.message)
+ return
+ }
+ }
+
+ result.success(null)
+ }
+
+ // returns XMP components
+ // returns an empty list if there is no XMP
+ private fun getXmp(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ if (mimeType == null || uri == null) {
+ result.error("getXmp-args", "missing arguments", null)
+ return
+ }
+
+ val xmpStrings = mutableListOf<String>()
+ var foundXmp = false
+
+ fun processXmp(xmpMeta: XMPMeta, allowMultiple: Boolean = false) {
+ if (foundXmp && !allowMultiple) return
+ foundXmp = true
+ try {
+ xmpStrings.add(XMPMetaFactory.serializeToString(xmpMeta, xmpSerializeOptions))
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to read XMP directory for uri=$uri", e)
+ }
+ }
+
+ if (canReadWithMetadataExtractor(mimeType) && !isLargeMp4(mimeType, sizeBytes)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ metadata.getDirectoriesOfType(XmpDirectory::class.java).map { it.xmpMeta }.forEach {
+ processXmp(it, allowMultiple = true)
+ }
+ }
+ } catch (e: Exception) {
+ result.error("getXmp-exception", "failed to read XMP for mimeType=$mimeType uri=$uri", e.message)
+ return
+ } catch (e: NoClassDefFoundError) {
+ result.error("getXmp-noclass", "failed to read XMP for mimeType=$mimeType uri=$uri", e.message)
+ return
+ } catch (e: AssertionError) {
+ result.error("getXmp-assert", "failed to read XMP for mimeType=$mimeType uri=$uri", e.message)
+ return
+ }
+ }
+
+ XMP.checkIsoBMFFImage(context, mimeType, uri, foundXmp, ::processXmp)
+ // `metadata-extractor` may fail to get UUID boxes for some MP4 files,
+ // so we always check with `mp4parser`, even for smaller files
+ XMP.checkMp4(context, mimeType, uri) { dirs ->
+ for (dir in dirs.filterIsInstance<XmpDirectory>()) {
+ processXmp(dir.xmpMeta)
+ }
+ }
+
+ result.success(xmpStrings)
+ }
+
+ private fun hasContentProp(call: MethodCall, result: MethodChannel.Result) {
+ val prop = call.argument<String>("prop")
+ if (prop == null) {
+ result.error("hasContentProp-args", "missing arguments", null)
+ return
+ }
+
+ result.success(
+ when (prop) {
+ "owner_package_name" -> Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
+ else -> {
+ result.error("hasContentProp-unknown", "unknown property=$prop", null)
+ return
+ }
+ }
+ )
+ }
+
+ private fun getContentPropValue(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val prop = call.argument<String>("prop")
+ if (mimeType == null || uri == null || prop == null) {
+ result.error("getContentPropValue-args", "missing arguments", null)
+ return
+ }
+
+ try {
+ val value = context.queryContentPropValue(uri, mimeType, prop)
+ result.success(value?.toString())
+ } catch (e: Exception) {
+ result.error("getContentPropValue-query", "failed to query prop for uri=$uri", e.message)
+ }
+ }
+
+ private fun getDate(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ val field = call.argument<String>("field")
+ if (mimeType == null || uri == null || field == null) {
+ result.error("getDate-args", "missing arguments", null)
+ return
+ }
+
+ var dateMillis: Long? = null
+ if (canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ val tag = when (field) {
+ ExifInterface.TAG_DATETIME -> ExifIFD0Directory.TAG_DATETIME
+ ExifInterface.TAG_DATETIME_DIGITIZED -> ExifSubIFDDirectory.TAG_DATETIME_DIGITIZED
+ ExifInterface.TAG_DATETIME_ORIGINAL -> ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL
+ ExifInterface.TAG_GPS_DATESTAMP -> GpsDirectory.TAG_DATE_STAMP
+ else -> {
+ result.error("getDate-field", "unsupported ExifInterface field=$field", null)
+ return
+ }
+ }
+
+ when (tag) {
+ ExifIFD0Directory.TAG_DATETIME -> {
+ for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) {
+ dir.getDateModifiedMillis { dateMillis = it }
+ }
+ if (dateMillis == null) {
+ for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) {
+ dir.getSafeDateMillis(ExifIFD0Directory.TAG_DATETIME, null)?.let { dateMillis = it }
+ }
+ }
+ }
+
+ ExifSubIFDDirectory.TAG_DATETIME_DIGITIZED -> {
+ for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) {
+ dir.getDateDigitizedMillis { dateMillis = it }
+ }
+ }
+
+ ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL -> {
+ for (dir in metadata.getDirectoriesOfType(ExifSubIFDDirectory::class.java)) {
+ dir.getDateOriginalMillis { dateMillis = it }
+ }
+ }
+
+ GpsDirectory.TAG_DATE_STAMP -> {
+ for (dir in metadata.getDirectoriesOfType(GpsDirectory::class.java)) {
+ dir.gpsDate?.let { dateMillis = it.time }
+ }
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ result.success(dateMillis)
+ }
+
+ private fun getFields(call: MethodCall, result: MethodChannel.Result) {
+ val mimeType = call.argument<String>("mimeType")
+ val uri = call.argument<String>("uri")?.toUri()
+ val sizeBytes = call.argument<Number>("sizeBytes")?.toLong()
+ val fields = call.argument<List<String>>("fields")
+ if (mimeType == null || uri == null || fields == null) {
+ result.error("getFields-args", "missing arguments", null)
+ return
+ }
+
+ val metadataMap = HashMap<String, Any?>()
+
+ val hashFields = fields.filter { it.startsWith(HASH_FIELD_PREFIX) }.toSet()
+ metadataMap.putAll(getHashFields(uri, mimeType, sizeBytes, hashFields))
+
+ val exifFields = fields.filterNot { hashFields.contains(it) }.toSet()
+ metadataMap.putAll(getExifFields(uri, mimeType, sizeBytes, exifFields))
+
+ result.success(metadataMap)
+ }
+
+ private fun getHashFields(uri: Uri, mimeType: String, sizeBytes: Long?, fields: Set<String>): FieldMap {
+ val metadataMap = HashMap<String, Any?>()
+ fields.forEach { field ->
+ val function = field.substringAfter(HASH_FIELD_PREFIX).lowercase(Locale.ROOT)
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ metadataMap[field] = HashUtils.getHash(input, function)
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get hash for mimeType=$mimeType uri=$uri function=$function", e)
+ }
+ }
+ return metadataMap
+ }
+
+ private fun getExifFields(uri: Uri, mimeType: String, sizeBytes: Long?, fields: Set<String>): FieldMap {
+ val metadataMap = HashMap<String, Any?>()
+ if (fields.isEmpty() || isVideo(mimeType)) {
+ return metadataMap
+ }
+
+ var foundExif = false
+ if (canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ for (dir in metadata.getDirectoriesOfType(ExifDirectoryBase::class.java)) {
+ foundExif = true
+ val allTags = ExifInterfaceHelper.allTags
+ fields.forEach { tag ->
+ allTags[tag]?.let { mapper ->
+ val tagType = mapper.type
+ dir.getDescription(tagType)?.let { value -> metadataMap[tag] = value }
+ }
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ if (!foundExif && canReadWithExifInterface(mimeType)) {
+ // fallback to read EXIF via ExifInterface
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val exif = ExifInterface(input)
+ fields.forEach { tag ->
+ if (exif.hasAttribute(tag)) {
+ val value = exif.getAttribute(tag)
+ if (value != null) {
+ metadataMap[tag] = value
+ }
+ }
+ }
+ }
+ } catch (e: Exception) {
+ // ExifInterface initialization can fail with a RuntimeException
+ // caused by an internal MediaMetadataRetriever failure
+ Log.w(LOG_TAG, "failed to get metadata by ExifInterface for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ return metadataMap
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<MetadataFetchHandler>()
+ const val CHANNEL = "deckers.thibault/aves/metadata_fetch"
+
+ private val doubleFormat = DecimalFormat("0.###")
+
+ private val allMetadataRedundantDirNames = setOf(
+ "MP4",
+ "MP4 Metadata",
+ "MP4 Sound",
+ "MP4 Video",
+ "QuickTime",
+ "QuickTime Sound",
+ "QuickTime Video",
+ )
+ private val allMetadataMergeableDirNames = setOf(
+ "Exif SubIFD",
+ "GIF Control",
+ "GIF Image",
+ "HEIF",
+ "ICC Profile",
+ "IPTC",
+ "WebP",
+ "XMP",
+ )
+
+ private val xmpSerializeOptions = SerializeOptions().apply {
+ omitPacketWrapper = true // e.g. <?xpacket begin="..." id="W5M0MpCehiHzreSzNTczkc9d"?>...<?xpacket end="r"?>
+ omitXmpMetaElement = false // e.g. <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core Test.SNAPSHOT">...</x:xmpmeta>
+ }
+
+ private fun isLargeMp4(mimeType: String, sizeBytes: Long?) = mimeType == MimeTypes.MP4 && Metadata.isDangerouslyLarge(sizeBytes)
+
+ private fun exifTagMapper(it: Tag): Pair<String, String> {
+ val name = if (it.hasTagName()) {
+ it.tagName
+ } else {
+ ExifTags.getTagName(it.tagType) ?: it.tagName
+ }
+ return Pair(name, it.description)
+ }
+
+ // catalog metadata
+ private const val KEY_MIME_TYPE = "mimeType"
+ private const val KEY_DATE_MILLIS = "dateMillis"
+ private const val KEY_FLAGS = "flags"
+ private const val KEY_ROTATION_DEGREES = "rotationDegrees"
+ private const val KEY_LATITUDE = "latitude"
+ private const val KEY_LONGITUDE = "longitude"
+ private const val KEY_XMP_SUBJECTS = "xmpSubjects"
+ private const val KEY_XMP_TITLE = "xmpTitle"
+ private const val KEY_RATING = "rating"
+
+ private const val MASK_IS_ANIMATED = 1 shl 0
+ private const val MASK_IS_FLIPPED = 1 shl 1
+ private const val MASK_IS_GEOTIFF = 1 shl 2
+ private const val MASK_IS_360 = 1 shl 3
+ private const val MASK_IS_MULTIPAGE = 1 shl 4
+ private const val MASK_IS_MOTION_PHOTO = 1 shl 5
+ private const val MASK_IS_HDR = 1 shl 6 // for images: embedded HDR gainmap, for videos: HDR color transfer
+ private const val XMP_SUBJECTS_SEPARATOR = ";"
+
+ // overlay metadata
+ private const val KEY_APERTURE = "aperture"
+ private const val KEY_DESCRIPTION = "description"
+ private const val KEY_EXPOSURE_TIME = "exposureTime"
+ private const val KEY_FOCAL_LENGTH = "focalLength"
+ private const val KEY_ISO = "iso"
+
+ // additional media key
+ private const val KEY_HAS_EMBEDDED_PICTURE = "Has Embedded Picture"
+
+ private const val HASH_FIELD_PREFIX = "hash"
+ private const val VALUE_SKIPPED_DATA = "[skipped]"
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/SecurityHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/SecurityHandler.kt
new file mode 100644
index 0000000..1263ce7
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/SecurityHandler.kt
@@ -0,0 +1,80 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.Context
+import android.content.SharedPreferences
+import androidx.core.content.edit
+import androidx.security.crypto.EncryptedSharedPreferences
+import androidx.security.crypto.MasterKey
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+
+class SecurityHandler(private val context: Context) : MethodCallHandler {
+ private var sharedPreferences: SharedPreferences? = null
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "writeValue" -> safe(call, result, ::writeValue)
+ "readValue" -> safe(call, result, ::readValue)
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun getStore(): SharedPreferences {
+ if (sharedPreferences == null) {
+ val mainKey = MasterKey.Builder(context)
+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
+ .build()
+ sharedPreferences = EncryptedSharedPreferences.create(
+ context,
+ FILENAME,
+ mainKey,
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
+ )
+ }
+ return sharedPreferences!!
+ }
+
+ private fun writeValue(call: MethodCall, result: MethodChannel.Result) {
+ val key = call.argument<String>("key")
+ val value = call.argument<Any?>("value")
+ if (key == null) {
+ result.error("writeValue-args", "missing arguments", null)
+ return
+ }
+
+ val preferences = getStore()
+ preferences.edit {
+ when (value) {
+ is Boolean -> putBoolean(key, value)
+ is Float -> putFloat(key, value)
+ is Int -> putInt(key, value)
+ is Long -> putLong(key, value)
+ is String -> putString(key, value)
+ null -> remove(key)
+ else -> {
+ result.error("writeValue-type", "unsupported type for value=$value", null)
+ return
+ }
+ }
+ }
+ result.success(true)
+ }
+
+ private fun readValue(call: MethodCall, result: MethodChannel.Result) {
+ val key = call.argument<String>("key")
+ if (key == null) {
+ result.error("readValue-args", "missing arguments", null)
+ return
+ }
+
+ result.success(getStore().all[key])
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/security"
+ const val FILENAME = "secret_shared_prefs"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/StorageHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/StorageHandler.kt
new file mode 100644
index 0000000..6c456fc
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/StorageHandler.kt
@@ -0,0 +1,269 @@
+package deckers.thibault.aves.channel.calls
+
+import android.content.Context
+import android.os.Build
+import android.os.Environment
+import android.os.storage.StorageManager
+import androidx.core.os.EnvironmentCompat
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.PermissionManager
+import deckers.thibault.aves.utils.StorageUtils
+import deckers.thibault.aves.utils.StorageUtils.getFolderSize
+import deckers.thibault.aves.utils.StorageUtils.getPrimaryVolumePath
+import deckers.thibault.aves.utils.StorageUtils.getVolumePaths
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import io.flutter.util.PathUtils
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import java.io.File
+
+class StorageHandler(private val context: Context) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "getDataUsage" -> ioScope.launch { safe(call, result, ::getDataUsage) }
+ "getStorageVolumes" -> ioScope.launch { safe(call, result, ::getStorageVolumes) }
+ "getCacheDirectory" -> ioScope.launch { safe(call, result, ::getCacheDirectory) }
+ "getUntrackedTrashPaths" -> ioScope.launch { safe(call, result, ::getUntrackedTrashPaths) }
+ "getUntrackedVaultPaths" -> ioScope.launch { safe(call, result, ::getUntrackedVaultPaths) }
+ "getVaultRoot" -> ioScope.launch { safe(call, result, ::getVaultRoot) }
+ "getFreeSpace" -> ioScope.launch { safe(call, result, ::getFreeSpace) }
+ "getGrantedDirectories" -> ioScope.launch { safe(call, result, ::getGrantedDirectories) }
+ "getInaccessibleDirectories" -> ioScope.launch { safe(call, result, ::getInaccessibleDirectories) }
+ "getRestrictedDirectories" -> ioScope.launch { safe(call, result, ::getRestrictedDirectories) }
+ "revokeDirectoryAccess" -> safe(call, result, ::revokeDirectoryAccess)
+ "deleteEmptyDirectories" -> ioScope.launch { safe(call, result, ::deleteEmptyDirectories) }
+ "deleteTempDirectory" -> ioScope.launch { safe(call, result, ::deleteTempDirectory) }
+ "deleteExternalCache" -> ioScope.launch { safe(call, result, ::deleteExternalCache) }
+ "canRequestMediaFileBulkAccess" -> safe(call, result, ::canRequestMediaFileBulkAccess)
+ "canInsertMedia" -> safe(call, result, ::canInsertMedia)
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun getDataUsage(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ var internalCache = getFolderSize(context.cacheDir)
+ internalCache += getFolderSize(context.codeCacheDir)
+ val externalCache = context.externalCacheDirs.sumOf(::getFolderSize)
+ val externalFilesDirs = context.getExternalFilesDirs(null)
+
+ val dataDir = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) context.dataDir else File(context.applicationInfo.dataDir)
+
+ val database = getFolderSize(File(dataDir, "databases"))
+ val flutter = getFolderSize(File(PathUtils.getDataDirectory(context)))
+ val vaults = getFolderSize(File(StorageUtils.getVaultRoot(context)))
+ val trash = externalFilesDirs.mapNotNull { StorageUtils.trashDirFor(context, it.path) }.sumOf(::getFolderSize)
+
+ val internalData = getFolderSize(dataDir) - internalCache
+ val externalData = externalFilesDirs.sumOf(::getFolderSize)
+ val miscData = internalData + externalData - (database + flutter + vaults + trash)
+
+ result.success(
+ hashMapOf(
+ "database" to database,
+ "flutter" to flutter,
+ "vaults" to vaults,
+ "trash" to trash,
+ "miscData" to miscData,
+ "internalCache" to internalCache,
+ "externalCache" to externalCache,
+ )
+ )
+ }
+
+ private fun getStorageVolumes(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ val volumes = ArrayList<Map<String, Any>>()
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager
+ if (sm != null) {
+ for (volumePath in getVolumePaths(context)) {
+ try {
+ sm.getStorageVolume(File(volumePath))?.let {
+ volumes.add(
+ hashMapOf(
+ "path" to volumePath,
+ "description" to it.getDescription(context),
+ "isPrimary" to it.isPrimary,
+ "isRemovable" to it.isRemovable,
+ "state" to it.state,
+ )
+ )
+ }
+ } catch (_: Exception) {
+ // ignore
+ }
+ }
+ }
+ } else {
+ val primaryVolumePath = getPrimaryVolumePath(context)
+ for (volumePath in getVolumePaths(context)) {
+ val volumeFile = File(volumePath)
+ try {
+ val isPrimary = volumePath == primaryVolumePath
+ val isRemovable = Environment.isExternalStorageRemovable(volumeFile)
+ volumes.add(
+ hashMapOf(
+ "path" to volumePath,
+ "isPrimary" to isPrimary,
+ "isRemovable" to isRemovable,
+ "state" to EnvironmentCompat.getStorageState(volumeFile)
+ )
+ )
+ } catch (_: Exception) {
+ // ignore
+ }
+ }
+ }
+ result.success(volumes)
+ }
+
+ private fun getCacheDirectory(call: MethodCall, result: MethodChannel.Result) {
+ val external = call.argument<Boolean>("external")
+ if (external == null) {
+ result.error("getCacheDirectory-args", "missing arguments", null)
+ return
+ }
+
+ val dir = (if (external) context.externalCacheDir else context.cacheDir)
+ if (dir == null) {
+ result.error("getCacheDirectory-null", "context cache dir is null", null)
+ return
+ }
+
+ result.success(dir.path)
+ }
+
+
+ private fun getUntrackedTrashPaths(call: MethodCall, result: MethodChannel.Result) {
+ val knownPaths = call.argument<List<String>>("knownPaths")
+ if (knownPaths == null) {
+ result.error("getUntrackedTrashPaths-args", "missing arguments", null)
+ return
+ }
+
+ val trashDirs = context.getExternalFilesDirs(null).filterNotNull().mapNotNull { StorageUtils.trashDirFor(context, it.path) }
+ val trashItemPaths = trashDirs.flatMap { dir -> dir.listFiles()?.filterNotNull()?.mapNotNull { file -> file.path } ?: listOf() }
+ val untrackedPaths = trashItemPaths.filterNot(knownPaths::contains).toList()
+
+ result.success(untrackedPaths)
+ }
+
+ private fun getUntrackedVaultPaths(call: MethodCall, result: MethodChannel.Result) {
+ val vault = call.argument<String>("vault")
+ val knownPaths = call.argument<List<String>>("knownPaths")
+ if (vault == null || knownPaths == null) {
+ result.error("getUntrackedVaultPaths-args", "missing arguments", null)
+ return
+ }
+
+ val vaultDir = File(StorageUtils.getVaultRoot(context), vault)
+ val vaultItemPaths = vaultDir.listFiles()?.mapNotNull { file -> file?.path } ?: listOf()
+ val untrackedPaths = vaultItemPaths.filterNot(knownPaths::contains).toList()
+
+ result.success(untrackedPaths)
+ }
+
+ private fun getVaultRoot(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ result.success(StorageUtils.getVaultRoot(context))
+ }
+
+ private fun getFreeSpace(call: MethodCall, result: MethodChannel.Result) {
+ val path = call.argument<String>("path")
+ if (path == null) {
+ result.error("getFreeSpace-args", "missing arguments", null)
+ return
+ }
+
+ // `StorageStatsManager` `getFreeBytes()` is only available from API 26,
+ // and non-primary volume UUIDs cannot be used with it
+ val file = File(path)
+ try {
+ result.success(file.freeSpace)
+ } catch (e: SecurityException) {
+ result.error("getFreeSpace-security", "failed because of missing access", e.message)
+ }
+ }
+
+ private fun getGrantedDirectories(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ result.success(ArrayList(PermissionManager.getGrantedDirs(context)))
+ }
+
+ private fun getInaccessibleDirectories(call: MethodCall, result: MethodChannel.Result) {
+ val dirPaths = call.argument<List<String>>("dirPaths")
+ if (dirPaths == null) {
+ result.error("getInaccessibleDirectories-args", "missing arguments", null)
+ return
+ }
+
+ result.success(PermissionManager.getInaccessibleDirectories(context, dirPaths))
+ }
+
+ private fun getRestrictedDirectories(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ result.success(PermissionManager.getRestrictedDirectories(context))
+ }
+
+ private fun revokeDirectoryAccess(call: MethodCall, result: MethodChannel.Result) {
+ val path = call.argument<String>("path")
+ if (path == null) {
+ result.error("revokeDirectoryAccess-args", "missing arguments", null)
+ return
+ }
+
+ val success = PermissionManager.revokeDirectoryAccess(context, path)
+ result.success(success)
+ }
+
+ private fun deleteEmptyDirectories(call: MethodCall, result: MethodChannel.Result) {
+ val dirPaths = call.argument<List<String>>("dirPaths")
+ if (dirPaths == null) {
+ result.error("deleteEmptyDirectories-args", "missing arguments", null)
+ return
+ }
+
+ var deleted = 0
+ dirPaths.forEach {
+ try {
+ val dir = File(it)
+ if (dir.isDirectory && dir.listFiles()?.isEmpty() == true && dir.delete()) {
+ deleted++
+ }
+ } catch (_: SecurityException) {
+ // ignore
+ }
+ }
+ result.success(deleted)
+ }
+
+ private fun deleteTempDirectory(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ result.success(StorageUtils.deleteTempDirectory(context))
+ }
+
+ private fun deleteExternalCache(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ context.externalCacheDirs.filter { it.exists() }.forEach { it.deleteRecursively() }
+ result.success(true)
+ }
+
+ private fun canRequestMediaFileBulkAccess(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
+ }
+
+ private fun canInsertMedia(call: MethodCall, result: MethodChannel.Result) {
+ val directories = call.argument<List<FieldMap>>("directories")
+ if (directories == null) {
+ result.error("canInsertMedia-args", "missing arguments", null)
+ return
+ }
+
+ result.success(PermissionManager.canInsertByMediaStore(directories))
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/storage"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/WallpaperHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/WallpaperHandler.kt
new file mode 100644
index 0000000..5b91a63
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/WallpaperHandler.kt
@@ -0,0 +1,58 @@
+package deckers.thibault.aves.channel.calls
+
+import android.app.WallpaperManager
+import android.app.WallpaperManager.FLAG_LOCK
+import android.app.WallpaperManager.FLAG_SYSTEM
+import android.content.ContextWrapper
+import android.os.Build
+import deckers.thibault.aves.channel.calls.Coresult.Companion.safe
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+
+class WallpaperHandler(private val contextWrapper: ContextWrapper) : MethodCallHandler {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "setWallpaper" -> ioScope.launch { safe(call, result, ::setWallpaper) }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun setWallpaper(call: MethodCall, result: MethodChannel.Result) {
+ val bytes = call.argument<ByteArray>("bytes")
+ val home = call.argument<Boolean>("home")
+ val lock = call.argument<Boolean>("lock")
+ if (bytes == null || home == null || lock == null) {
+ result.error("setWallpaper-args", "missing arguments", null)
+ return
+ }
+
+ val manager = WallpaperManager.getInstance(contextWrapper)
+ val supported = Build.VERSION.SDK_INT < Build.VERSION_CODES.M || manager.isWallpaperSupported
+ val allowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.N || manager.isSetWallpaperAllowed
+ if (!supported || !allowed) {
+ result.error("setWallpaper-unsupported", "failed because setting wallpaper is not allowed", null)
+ return
+ }
+
+ bytes.inputStream().use { input ->
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ val flags = (if (home) FLAG_SYSTEM else 0) or (if (lock) FLAG_LOCK else 0)
+ manager.setStream(input, null, true, flags)
+ } else {
+ manager.setStream(input)
+ }
+ }
+ result.success(true)
+ }
+
+ companion object {
+ const val CHANNEL = "deckers.thibault/aves/wallpaper"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ActivityWindowHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ActivityWindowHandler.kt
new file mode 100644
index 0000000..85201c6
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ActivityWindowHandler.kt
@@ -0,0 +1,203 @@
+package deckers.thibault.aves.channel.calls.window
+
+import android.app.Activity
+import android.content.ClipData
+import android.content.Context
+import android.content.pm.ActivityInfo
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Matrix
+import android.graphics.Matrix.ScaleToFit
+import android.graphics.Point
+import android.graphics.RectF
+import android.os.Build
+import android.util.Log
+import android.view.View
+import android.view.WindowManager
+import androidx.core.graphics.createBitmap
+import androidx.core.net.toUri
+import deckers.thibault.aves.channel.calls.AppAdapterHandler.Companion.getShareableUri
+import deckers.thibault.aves.utils.ContextUtils.devicePixelRatio
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.getDisplayCompat
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import java.nio.ByteBuffer
+import kotlin.math.roundToInt
+
+class ActivityWindowHandler(private val activity: Activity) : WindowHandler(activity) {
+ override fun isActivity(call: MethodCall, result: MethodChannel.Result) {
+ result.success(true)
+ }
+
+ private fun setWindowFlag(call: MethodCall, result: MethodChannel.Result, flag: Int) {
+ val on = call.argument<Boolean>("on")
+ if (on == null) {
+ result.error("keepOn-args", "missing arguments", null)
+ return
+ }
+
+ val window = activity.window
+ val old = (window.attributes.flags and flag) != 0
+ if (old != on) {
+ if (on) {
+ window.addFlags(flag)
+ } else {
+ window.clearFlags(flag)
+ }
+ }
+ result.success(null)
+ }
+
+ override fun keepScreenOn(call: MethodCall, result: MethodChannel.Result) {
+ setWindowFlag(call, result, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+
+ override fun secureScreen(call: MethodCall, result: MethodChannel.Result) {
+ setWindowFlag(call, result, WindowManager.LayoutParams.FLAG_SECURE)
+ }
+
+ override fun isInMultiWindowMode(call: MethodCall, result: MethodChannel.Result) {
+ val enabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) activity.isInMultiWindowMode else false
+ result.success(enabled)
+ }
+
+ override fun isInPictureInPictureMode(call: MethodCall, result: MethodChannel.Result) {
+ val enabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) activity.isInPictureInPictureMode else false
+ result.success(enabled)
+ }
+
+ // display orientation in degrees
+ override fun getOrientation(call: MethodCall, result: MethodChannel.Result) {
+ val displayRotation = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ activity.display.rotation
+ } else {
+ val windowService = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
+ @Suppress("deprecation")
+ windowService.defaultDisplay.rotation
+ }
+ result.success(displayRotation * 90)
+ }
+
+ override fun requestOrientation(call: MethodCall, result: MethodChannel.Result) {
+ val orientation = call.argument<Int>("orientation")
+ if (orientation == null) {
+ result.error("requestOrientation-args", "missing arguments", null)
+ return
+ }
+ activity.requestedOrientation = orientation
+ result.success(true)
+ }
+
+ override fun isCutoutAware(call: MethodCall, result: MethodChannel.Result) {
+ result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P)
+ }
+
+ override fun getCutoutInsets(call: MethodCall, result: MethodChannel.Result) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
+ result.error("getCutoutInsets-sdk", "unsupported SDK version=${Build.VERSION.SDK_INT}", null)
+ return
+ }
+
+ val cutout = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ activity.getDisplayCompat()?.cutout
+ } else {
+ activity.window.decorView.rootWindowInsets.displayCutout
+ }
+
+ val density = activity.devicePixelRatio()
+ result.success(
+ hashMapOf(
+ "left" to (cutout?.safeInsetLeft ?: 0) / density,
+ "top" to (cutout?.safeInsetTop ?: 0) / density,
+ "right" to (cutout?.safeInsetRight ?: 0) / density,
+ "bottom" to (cutout?.safeInsetBottom ?: 0) / density,
+ )
+ )
+ }
+
+ override fun supportsWideGamut(call: MethodCall, result: MethodChannel.Result) {
+ result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && activity.resources.configuration.isScreenWideColorGamut)
+ }
+
+ override fun supportsHdr(call: MethodCall, result: MethodChannel.Result) {
+ result.success(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && activity.resources.configuration.isScreenHdr)
+ }
+
+ override fun setColorMode(call: MethodCall, result: MethodChannel.Result) {
+ val wideColorGamut = call.argument<Boolean>("wideColorGamut")
+ val hdr = call.argument<Boolean>("hdr")
+ if (wideColorGamut == null || hdr == null) {
+ result.error("setColorMode-args", "missing arguments", null)
+ return
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ activity.window.colorMode = if (hdr) {
+ ActivityInfo.COLOR_MODE_HDR
+ } else if (wideColorGamut) {
+ ActivityInfo.COLOR_MODE_WIDE_COLOR_GAMUT
+ } else {
+ ActivityInfo.COLOR_MODE_DEFAULT
+ }
+ }
+ result.success(null)
+ }
+
+ override fun startGlobalDrag(call: MethodCall, result: MethodChannel.Result) {
+ val uri = call.argument<String>("uri")?.toUri()
+ val label = call.argument<String>("label")
+ val shadowWidthDip = call.argument<Number>("shadowWidthDip")?.toFloat()
+ val shadowHeightDip = call.argument<Number>("shadowHeightDip")?.toFloat()
+ val shadowBytes = call.argument<ByteArray>("shadowBytes")
+
+ if (uri == null || shadowWidthDip == null || shadowHeightDip == null || shadowBytes == null) {
+ result.error("startGlobalDrag-args", "missing arguments", null)
+ return
+ }
+
+ val clip = ClipData.newUri(activity.contentResolver, label, getShareableUri(activity, uri))
+
+ val density = activity.devicePixelRatio()
+ val widthPx = (shadowWidthDip * density).roundToInt()
+ val heightPx = (shadowHeightDip * density).roundToInt()
+
+ val shadowBuilder: View.DragShadowBuilder = try {
+ val bitmap = createBitmap(widthPx, heightPx, Bitmap.Config.ARGB_8888).also {
+ it.copyPixelsFromBuffer(ByteBuffer.wrap(shadowBytes))
+ }
+
+ val scaleToFit = Matrix()
+ val src = RectF(0f, 0f, bitmap.getWidth().toFloat(), bitmap.getHeight().toFloat())
+ val dst = RectF(0f, 0f, heightPx.toFloat(), heightPx.toFloat())
+ scaleToFit.setRectToRect(src, dst, ScaleToFit.CENTER)
+
+ object : View.DragShadowBuilder() {
+ override fun onProvideShadowMetrics(outShadowSize: Point, outShadowTouchPoint: Point) {
+ outShadowSize.set(widthPx, heightPx)
+ outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2)
+ }
+
+ override fun onDrawShadow(canvas: Canvas) {
+ canvas.drawBitmap(bitmap, scaleToFit, null)
+ }
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to draw widget", e)
+ View.DragShadowBuilder()
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ activity.window.decorView.startDragAndDrop(
+ clip,
+ shadowBuilder,
+ null,
+ View.DRAG_FLAG_GLOBAL or View.DRAG_FLAG_GLOBAL_URI_READ
+ )
+ }
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<ActivityWindowHandler>()
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ServiceWindowHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ServiceWindowHandler.kt
new file mode 100644
index 0000000..a82bb41
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/ServiceWindowHandler.kt
@@ -0,0 +1,59 @@
+package deckers.thibault.aves.channel.calls.window
+
+import android.app.Service
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+
+class ServiceWindowHandler(service: Service) : WindowHandler(service) {
+ override fun isActivity(call: MethodCall, result: MethodChannel.Result) {
+ result.success(false)
+ }
+
+ override fun keepScreenOn(call: MethodCall, result: MethodChannel.Result) {
+ result.success(null)
+ }
+
+ override fun secureScreen(call: MethodCall, result: MethodChannel.Result) {
+ result.success(null)
+ }
+
+ override fun isInMultiWindowMode(call: MethodCall, result: MethodChannel.Result) {
+ result.success(false)
+ }
+
+ override fun isInPictureInPictureMode(call: MethodCall, result: MethodChannel.Result) {
+ result.success(false)
+ }
+
+ override fun getOrientation(call: MethodCall, result: MethodChannel.Result) {
+ result.success(0)
+ }
+
+ override fun requestOrientation(call: MethodCall, result: MethodChannel.Result) {
+ result.success(false)
+ }
+
+ override fun isCutoutAware(call: MethodCall, result: MethodChannel.Result) {
+ result.success(false)
+ }
+
+ override fun getCutoutInsets(call: MethodCall, result: MethodChannel.Result) {
+ result.success(HashMap<String, Any>())
+ }
+
+ override fun supportsWideGamut(call: MethodCall, result: MethodChannel.Result) {
+ result.success(false)
+ }
+
+ override fun supportsHdr(call: MethodCall, result: MethodChannel.Result) {
+ result.success(false)
+ }
+
+ override fun setColorMode(call: MethodCall, result: MethodChannel.Result) {
+ result.success(null)
+ }
+
+ override fun startGlobalDrag(call: MethodCall, result: MethodChannel.Result) {
+ result.success(null)
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/WindowHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/WindowHandler.kt
new file mode 100644
index 0000000..9b7bba8
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/calls/window/WindowHandler.kt
@@ -0,0 +1,72 @@
+package deckers.thibault.aves.channel.calls.window
+
+import android.content.ContextWrapper
+import android.provider.Settings
+import android.util.Log
+import deckers.thibault.aves.channel.calls.Coresult
+import deckers.thibault.aves.utils.LogUtils
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+
+abstract class WindowHandler(private val contextWrapper: ContextWrapper) : MethodChannel.MethodCallHandler {
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "isActivity" -> Coresult.safe(call, result, ::isActivity)
+ "keepScreenOn" -> Coresult.safe(call, result, ::keepScreenOn)
+ "secureScreen" -> Coresult.safe(call, result, ::secureScreen)
+ "isInMultiWindowMode" -> Coresult.safe(call, result, ::isInMultiWindowMode)
+ "isInPictureInPictureMode" -> Coresult.safe(call, result, ::isInPictureInPictureMode)
+ "isRotationLocked" -> Coresult.safe(call, result, ::isRotationLocked)
+ "getOrientation" -> Coresult.safe(call, result, ::getOrientation)
+ "requestOrientation" -> Coresult.safe(call, result, ::requestOrientation)
+ "isCutoutAware" -> Coresult.safe(call, result, ::isCutoutAware)
+ "getCutoutInsets" -> Coresult.safe(call, result, ::getCutoutInsets)
+ "supportsWideGamut" -> Coresult.safe(call, result, ::supportsWideGamut)
+ "supportsHdr" -> Coresult.safe(call, result, ::supportsHdr)
+ "setColorMode" -> Coresult.safe(call, result, ::setColorMode)
+ "startGlobalDrag" -> Coresult.safe(call, result, ::startGlobalDrag)
+ else -> result.notImplemented()
+ }
+ }
+
+ abstract fun isActivity(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun keepScreenOn(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun secureScreen(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun isInMultiWindowMode(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun isInPictureInPictureMode(call: MethodCall, result: MethodChannel.Result)
+
+ private fun isRotationLocked(@Suppress("unused_parameter") call: MethodCall, result: MethodChannel.Result) {
+ var locked = false
+ try {
+ locked = Settings.System.getInt(contextWrapper.contentResolver, Settings.System.ACCELEROMETER_ROTATION) == 0
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get settings with error=${e.message}", null)
+ }
+ result.success(locked)
+ }
+
+ abstract fun getOrientation(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun requestOrientation(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun isCutoutAware(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun getCutoutInsets(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun supportsWideGamut(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun supportsHdr(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun setColorMode(call: MethodCall, result: MethodChannel.Result)
+
+ abstract fun startGlobalDrag(call: MethodCall, result: MethodChannel.Result)
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<WindowHandler>()
+ const val CHANNEL = "deckers.thibault/aves/window"
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/BaseStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/BaseStreamHandler.kt
new file mode 100644
index 0000000..7735b6d
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/BaseStreamHandler.kt
@@ -0,0 +1,108 @@
+package deckers.thibault.aves.channel.streams
+
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import deckers.thibault.aves.utils.MemoryUtils
+import io.flutter.plugin.common.EventChannel
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import java.io.InputStream
+
+abstract class BaseStreamHandler : EventChannel.StreamHandler {
+ val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ // cannot use `lateinit` because we cannot guarantee
+ // its initialization in `onListen` at the right time
+ // e.g. when resuming the app after the activity got destroyed
+ private var eventSink: EventChannel.EventSink? = null
+ private var handler: Handler? = null
+
+ override fun onListen(arguments: Any?, eventSink: EventChannel.EventSink) {
+ this.eventSink = eventSink
+ handler = Handler(Looper.getMainLooper())
+ onCall(arguments)
+ }
+
+ override fun onCancel(arguments: Any?) {
+ // nothing
+ }
+
+ open fun success(event: Any?) {
+ handler?.post {
+ try {
+ eventSink?.success(event)
+ } catch (e: Exception) {
+ Log.w(logTag, "failed to use event sink", e)
+ }
+ }
+ }
+
+ open fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
+ handler?.post {
+ try {
+ eventSink?.error(errorCode, errorMessage, errorDetails)
+ } catch (e: Exception) {
+ Log.w(logTag, "failed to use event sink", e)
+ }
+ }
+ }
+
+ open fun endOfStream() {
+ handler?.post {
+ try {
+ eventSink?.endOfStream()
+ } catch (e: Exception) {
+ Log.w(logTag, "failed to use event sink", e)
+ }
+ }
+ }
+
+ fun streamBytes(inputStream: InputStream): Boolean {
+ val buffer = ByteArray(BUFFER_SIZE)
+ var len: Int
+ while (inputStream.read(buffer).also { len = it } != -1) {
+ // cannot decode image on Flutter side when using `buffer` directly
+ if (MemoryUtils.canAllocate(len)) {
+ success(buffer.copyOf(len))
+ } else {
+ error("streamBytes-memory", "not enough memory to allocate $len bytes", null)
+ return false
+ }
+ }
+ return true
+ }
+
+ fun safe(function: () -> Unit, closeStream: Boolean = true) {
+ try {
+ function()
+ } catch (e: Exception) {
+ error("safe-exception", e.message, e.stackTraceToString())
+ }
+ if (closeStream) {
+ endOfStream()
+ }
+ }
+
+ suspend fun safeSuspend(function: suspend () -> Unit, closeStream: Boolean = true) {
+ try {
+ function()
+ } catch (e: Exception) {
+ error("safeSuspend-exception", e.message, e.stackTraceToString())
+ }
+ if (closeStream) {
+ endOfStream()
+ }
+ }
+
+ abstract val logTag: String
+
+ open fun onCall(args: Any?) {
+ // nothing by default
+ }
+
+ companion object {
+ const val BUFFER_SIZE = 1 shl 18 // 256kB
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ActivityResultStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ActivityResultStreamHandler.kt
new file mode 100644
index 0000000..39d4d53
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ActivityResultStreamHandler.kt
@@ -0,0 +1,278 @@
+package deckers.thibault.aves.channel.streams.darttoplatform
+
+import android.app.Activity
+import android.content.Intent
+import android.net.Uri
+import android.os.Build
+import android.util.Log
+import androidx.core.net.toUri
+import deckers.thibault.aves.MainActivity
+import deckers.thibault.aves.PendingStorageAccessResultHandler
+import deckers.thibault.aves.channel.calls.AppAdapterHandler
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.PermissionManager
+import deckers.thibault.aves.utils.StorageUtils
+import deckers.thibault.aves.utils.StorageUtils.ensureTrailingSeparator
+import kotlinx.coroutines.launch
+
+// starting activity to get a result (e.g. storage access via native dialog)
+// breaks the regular `MethodChannel` so we use a stream channel instead
+class ActivityResultStreamHandler(private val activity: Activity, arguments: Any?) : BaseStreamHandler() {
+ private var op: String? = null
+ private lateinit var args: Map<*, *>
+
+ init {
+ if (arguments is Map<*, *>) {
+ op = arguments["op"] as String?
+ args = arguments
+ }
+ }
+
+ override val logTag = LOG_TAG
+
+ override fun onCall(args: Any?) {
+ // do not automatically close stream when launching activity,
+ // as it will be closed when getting that activity result
+ val closeStream = false
+ when (op) {
+ "requestDirectoryAccess" -> ioScope.launch { safe(::requestDirectoryAccess, closeStream) }
+ "requestMediaFileAccess" -> ioScope.launch { safe(::requestMediaFileAccess, closeStream) }
+ "createFile" -> ioScope.launch { safe(::createFile, closeStream) }
+ "openFile" -> ioScope.launch { safe(::openFile, closeStream) }
+ "copyFile" -> ioScope.launch { safe(::copyFile, closeStream) }
+ "edit" -> safe(::edit, closeStream)
+ "pickCollectionFilters" -> safe(::pickCollectionFilters, closeStream)
+ else -> endOfStream()
+ }
+ }
+
+ override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
+ super.error(errorCode, errorMessage, errorDetails)
+ endOfStream()
+ }
+
+ private fun requestDirectoryAccess() {
+ val path = args["path"] as String?
+ if (path == null) {
+ error("requestDirectoryAccess-args", "missing arguments", null)
+ return
+ }
+
+ PermissionManager.requestDirectoryAccess(activity, ensureTrailingSeparator(path), {
+ success(true)
+ endOfStream()
+ }, {
+ success(false)
+ endOfStream()
+ })
+ }
+
+ private fun requestMediaFileAccess() {
+ val uris = (args["uris"] as List<*>?)?.mapNotNull { if (it is String) it.toUri() else null }
+ val mimeTypes = (args["mimeTypes"] as List<*>?)?.mapNotNull { it as? String }
+ if (uris.isNullOrEmpty() || mimeTypes == null || mimeTypes.size != uris.size) {
+ error("requestMediaFileAccess-args", "missing arguments", null)
+ return
+ }
+
+ if (uris.any { !StorageUtils.isMediaStoreContentUri(it) }) {
+ error("requestMediaFileAccess-nonmediastore", "request is only valid for Media Store content URIs, uris=$uris", null)
+ return
+ }
+
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ error("requestMediaFileAccess-unsupported", "media file bulk access is not allowed before Android 11", null)
+ return
+ }
+
+ try {
+ val granted = PermissionManager.requestMediaFileAccess(activity, uris, mimeTypes)
+ success(granted)
+ endOfStream()
+ } catch (e: Exception) {
+ error("requestMediaFileAccess-request", "failed to request access to ${uris.size} uris=$uris", e.message)
+ }
+ }
+
+ private fun safeStartActivityForStorageAccessResult(intent: Intent, requestCode: Int, onGranted: (uri: Uri) -> Unit, onDenied: () -> Unit) {
+ if (intent.resolveActivity(activity.packageManager) != null) {
+ MainActivity.pendingStorageAccessResultHandlers[requestCode] = PendingStorageAccessResultHandler(null, onGranted, onDenied)
+ if (!safeStartActivityForResult(intent, requestCode)) {
+ MainActivity.notifyError("failed to start activity for intent=$intent extras=${intent.extras}")
+ onDenied()
+ }
+ } else {
+ MainActivity.notifyError("failed to resolve activity for intent=$intent extras=${intent.extras}")
+ onDenied()
+ }
+ }
+
+ private fun createFile() {
+ val name = args["name"] as String?
+ val mimeType = args["mimeType"] as String?
+ val bytes = args["bytes"] as ByteArray?
+ if (name == null || mimeType == null || bytes == null) {
+ error("createFile-args", "missing arguments", null)
+ return
+ }
+
+ fun onGranted(uri: Uri) {
+ ioScope.launch {
+ try {
+ // truncate is necessary when overwriting a longer file
+ activity.contentResolver.openOutputStream(uri, "wt")?.use { output ->
+ output.write(bytes)
+ }
+ success(true)
+ endOfStream()
+ } catch (e: Exception) {
+ error("createFile-write", "failed to write file at uri=$uri", e.message)
+ }
+ }
+ }
+
+ fun onDenied() {
+ success(null)
+ endOfStream()
+ }
+
+ val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
+ addCategory(Intent.CATEGORY_OPENABLE)
+ type = mimeType
+ putExtra(Intent.EXTRA_TITLE, name)
+ }
+ safeStartActivityForStorageAccessResult(intent, MainActivity.CREATE_FILE_REQUEST, ::onGranted, ::onDenied)
+ }
+
+ private fun openFile() {
+ val mimeType = args["mimeType"] as String? // optional
+
+ fun onGranted(uri: Uri) {
+ ioScope.launch {
+ try {
+ activity.contentResolver.openInputStream(uri)?.use(::streamBytes)
+ endOfStream()
+ } catch (e: Exception) {
+ error("openFile-read", "failed to read file at uri=$uri", e.message)
+ }
+ }
+ }
+
+ fun onDenied() {
+ success(ByteArray(0))
+ endOfStream()
+ }
+
+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
+ addCategory(Intent.CATEGORY_OPENABLE)
+ setTypeAndNormalize(mimeType ?: MimeTypes.ANY)
+ }
+ safeStartActivityForStorageAccessResult(intent, MainActivity.OPEN_FILE_REQUEST, ::onGranted, ::onDenied)
+ }
+
+ private fun copyFile() {
+ val name = args["name"] as String?
+ val mimeType = args["mimeType"] as String?
+ val sourceUri = (args["sourceUri"] as String?)?.toUri()
+ if (name == null || mimeType == null || sourceUri == null) {
+ error("copyFile-args", "missing arguments", null)
+ return
+ }
+
+ fun onGranted(uri: Uri) {
+ ioScope.launch {
+ try {
+ StorageUtils.openInputStream(activity, sourceUri)?.use { input ->
+ // truncate is necessary when overwriting a longer file
+ activity.contentResolver.openOutputStream(uri, "wt")?.use { output ->
+ val buffer = ByteArray(BUFFER_SIZE)
+ var len: Int
+ while (input.read(buffer).also { len = it } != -1) {
+ output.write(buffer, 0, len)
+ }
+ }
+ }
+ success(true)
+ endOfStream()
+ } catch (e: Exception) {
+ error("copyFile-write", "failed to copy file from sourceUri=$sourceUri to uri=$uri", e.message)
+ }
+ }
+ }
+
+ fun onDenied() {
+ success(null)
+ endOfStream()
+ }
+
+ val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
+ addCategory(Intent.CATEGORY_OPENABLE)
+ type = mimeType
+ putExtra(Intent.EXTRA_TITLE, name)
+ }
+ safeStartActivityForStorageAccessResult(intent, MainActivity.CREATE_FILE_REQUEST, ::onGranted, ::onDenied)
+ }
+
+ private fun edit() {
+ val uri = args["uri"] as String?
+ val mimeType = args["mimeType"] as String? // optional
+ if (uri == null) {
+ error("edit-args", "missing arguments", null)
+ return
+ }
+
+ val intent = Intent(Intent.ACTION_EDIT)
+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
+ .setDataAndType(AppAdapterHandler.getShareableUri(activity, uri.toUri()), mimeType)
+
+ if (intent.resolveActivity(activity.packageManager) == null) {
+ error("edit-resolve", "cannot resolve activity for this intent for uri=$uri mimeType=$mimeType", null)
+ return
+ }
+
+ MainActivity.pendingEditIntentHandler = { fields ->
+ success(fields)
+ endOfStream()
+ }
+ if (!safeStartActivityForResult(intent, MainActivity.EDIT_REQUEST)) {
+ error("edit-start", "cannot start activity for this intent for uri=$uri mimeType=$mimeType", null)
+ }
+ }
+
+ private fun pickCollectionFilters() {
+ val initialFilters = (args["initialFilters"] as? List<*>)?.mapNotNull { it as? String } ?: listOf()
+ val intent = Intent(MainActivity.INTENT_ACTION_PICK_COLLECTION_FILTERS, null, activity, MainActivity::class.java)
+ .putExtra(MainActivity.EXTRA_KEY_FILTERS_ARRAY, initialFilters.toTypedArray())
+ .putExtra(MainActivity.EXTRA_KEY_FILTERS_STRING, initialFilters.joinToString(MainActivity.EXTRA_STRING_ARRAY_SEPARATOR))
+ MainActivity.pendingCollectionFilterPickHandler = { filters ->
+ success(filters)
+ endOfStream()
+ }
+ activity.startActivityForResult(intent, MainActivity.PICK_COLLECTION_FILTERS_REQUEST)
+ }
+
+ private fun safeStartActivityForResult(intent: Intent, requestCode: Int): Boolean {
+ return try {
+ activity.startActivityForResult(intent, requestCode)
+ true
+ } catch (_: SecurityException) {
+ if (intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0) {
+ // in some environments, providing the write flag yields a `SecurityException`:
+ // "UID XXXX does not have permission to content://XXXX"
+ // so we retry without it
+ Log.i(LOG_TAG, "retry intent=$intent without FLAG_GRANT_WRITE_URI_PERMISSION")
+ intent.flags = intent.flags and Intent.FLAG_GRANT_WRITE_URI_PERMISSION.inv()
+ safeStartActivityForResult(intent, requestCode)
+ } else {
+ false
+ }
+ }
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<ActivityResultStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/activity_result_stream"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageByteStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageByteStreamHandler.kt
new file mode 100644
index 0000000..8633f0c
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageByteStreamHandler.kt
@@ -0,0 +1,277 @@
+package deckers.thibault.aves.channel.streams.darttoplatform
+
+import android.content.Context
+import android.graphics.Rect
+import android.net.Uri
+import androidx.core.net.toUri
+import com.bumptech.glide.Glide
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.decoding.RegionFetcher
+import deckers.thibault.aves.decoding.SvgRegionFetcher
+import deckers.thibault.aves.decoding.ThumbnailFetcher
+import deckers.thibault.aves.decoding.TiffRegionFetcher
+import deckers.thibault.aves.glide.AvesAppGlideModule
+import deckers.thibault.aves.model.EntryFields
+import deckers.thibault.aves.utils.BitmapUtils
+import deckers.thibault.aves.utils.BitmapUtils.applyExifOrientation
+import deckers.thibault.aves.utils.ContextUtils.devicePixelRatio
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.handleEncodedBytesInFlutter
+import deckers.thibault.aves.utils.MimeTypes.isVideo
+import deckers.thibault.aves.utils.MimeTypes.needRotationAfterGlide
+import deckers.thibault.aves.utils.StorageUtils
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import java.io.ByteArrayInputStream
+import java.io.InputStream
+import java.util.Date
+import kotlin.math.roundToInt
+
+class ImageByteStreamHandler(private val context: Context, private val arguments: Any?) : BaseStreamHandler(), ByteSink {
+ private var op: String? = null
+ private var decoded: Boolean = false
+ private val regionFetcher = RegionFetcher(context)
+ private val density = context.devicePixelRatio()
+
+ init {
+ if (arguments is Map<*, *>) {
+ op = arguments["op"] as String?
+ decoded = arguments["decoded"] as Boolean
+ }
+ }
+
+ override val logTag = LOG_TAG
+
+ override fun onCall(args: Any?) {
+ when (op) {
+ "getFullImage" -> ioScope.launch { safeSuspend(::streamFullImage) }
+ "getRegion" -> ioScope.launch { safeSuspend(::streamRegion) }
+ "getThumbnail" -> ioScope.launch { safeSuspend(::streamThumbnail) }
+ else -> endOfStream()
+ }
+ }
+
+ // Supported image formats:
+ // - Flutter (as of v1.20): JPEG, PNG, GIF, Animated GIF, WebP, Animated WebP, BMP, and WBMP
+ // - Android: https://developer.android.com/guide/topics/media/media-formats#image-formats
+ // - Glide: https://github.com/bumptech/glide/blob/master/library/src/main/java/com/bumptech/glide/load/ImageHeaderParser.java
+ private suspend fun streamFullImage() {
+ if (arguments !is Map<*, *>) {
+ return
+ }
+
+ val uri = (arguments["uri"] as String?)?.toUri()
+ val pageId = arguments["pageId"] as Int?
+ val mimeType = arguments["mimeType"] as String?
+ val sizeBytes = (arguments["sizeBytes"] as Number?)?.toLong()
+ val rotationDegrees = arguments["rotationDegrees"] as Int
+ val isFlipped = arguments["isFlipped"] as Boolean
+
+ if (mimeType == null || uri == null) {
+ error("streamImage-args", "missing arguments", null)
+ return
+ }
+
+ if (!decoded && handleEncodedBytesInFlutter(mimeType)) {
+ // the image can be decoded by Flutter codecs,
+ // and there is no need for processing on the platform side
+ // so we stream it without decoding it
+ streamOriginalBytesWithTrailer(uri, mimeType)
+ } else if (isVideo(mimeType)) {
+ streamVideoByGlide(
+ uri = uri,
+ mimeType = mimeType,
+ sizeBytes = sizeBytes,
+ decoded = decoded,
+ )
+ } else {
+ // even if the image could be decoded by Flutter codecs,
+ // it needs to be processed on the platform side
+ // so we decode, process, optionally reencode, then stream it
+ streamImageByGlide(
+ uri = uri,
+ pageId = pageId,
+ mimeType = mimeType,
+ sizeBytes = sizeBytes,
+ rotationDegrees = rotationDegrees,
+ isFlipped = isFlipped,
+ decoded = decoded,
+ )
+ }
+ }
+
+ private fun streamOriginalBytesWithTrailer(uri: Uri, mimeType: String) {
+ try {
+ val sent = StorageUtils.openInputStream(context, uri)?.use(::streamBytes)
+ if (sent ?: false) {
+ success(BitmapUtils.FORMAT_BYTE_ENCODED_AS_BYTES)
+ }
+ } catch (e: Exception) {
+ error("streamImage-image-read-exception", "failed to get image for mimeType=$mimeType uri=$uri", e.stackTraceToString())
+ }
+ }
+
+ private suspend fun streamImageByGlide(
+ uri: Uri,
+ pageId: Int?,
+ mimeType: String,
+ sizeBytes: Long?,
+ rotationDegrees: Int,
+ isFlipped: Boolean,
+ decoded: Boolean,
+ ) {
+ val target = Glide.with(context)
+ .asBitmap()
+ .apply(AvesAppGlideModule.uncachedFullImageOptions)
+ .load(AvesAppGlideModule.getModel(context, uri, mimeType, pageId, sizeBytes))
+ .submit()
+ try {
+ var bitmap = withContext(Dispatchers.IO) { target.get() }
+ if (needRotationAfterGlide(mimeType, pageId)) {
+ bitmap = applyExifOrientation(context, bitmap, rotationDegrees, isFlipped)
+ }
+ if (bitmap != null) {
+ // do not recycle bitmaps fetched from Glide as their lifecycle is unknown
+ val bytes = BitmapUtils.getBytes(bitmap, recycle = false, decoded = decoded, mimeType)
+ streamBytes(ByteArrayInputStream(bytes))
+ } else {
+ error("streamImage-image-decode-null", "failed to get image for mimeType=$mimeType uri=$uri", null)
+ }
+ } catch (e: Exception) {
+ error("streamImage-image-decode-exception", "failed to get image for mimeType=$mimeType uri=$uri", e.stackTraceToString())
+ } finally {
+ Glide.with(context).clear(target)
+ }
+ }
+
+ private suspend fun streamVideoByGlide(uri: Uri, mimeType: String, sizeBytes: Long?, decoded: Boolean) {
+ val target = Glide.with(context)
+ .asBitmap()
+ .apply(AvesAppGlideModule.uncachedFullImageOptions)
+ .load(AvesAppGlideModule.getModel(context, uri, mimeType, null, sizeBytes))
+ .submit()
+ try {
+ val bitmap = withContext(Dispatchers.IO) { target.get() }
+ if (bitmap != null) {
+ // do not recycle bitmaps fetched from Glide as their lifecycle is unknown
+ val bytes = BitmapUtils.getBytes(bitmap, recycle = false, decoded = decoded, mimeType)
+ streamBytes(ByteArrayInputStream(bytes))
+ } else {
+ error("streamImage-video-null", "failed to get image for mimeType=$mimeType uri=$uri", null)
+ }
+ } catch (e: Exception) {
+ error("streamImage-video-exception", "failed to get image for mimeType=$mimeType uri=$uri", e.stackTraceToString())
+ } finally {
+ Glide.with(context).clear(target)
+ }
+ }
+
+ private suspend fun streamRegion() {
+ if (arguments !is Map<*, *>) {
+ return
+ }
+
+ val uri = (arguments["uri"] as String?)?.toUri()
+ val pageId = arguments["pageId"] as Int?
+ val mimeType = arguments["mimeType"] as String?
+ val sizeBytes = (arguments["sizeBytes"] as Number?)?.toLong()
+ val sampleSize = arguments["sampleSize"] as Int?
+ val x = arguments["regionX"] as Int?
+ val y = arguments["regionY"] as Int?
+ val width = arguments["regionWidth"] as Int?
+ val height = arguments["regionHeight"] as Int?
+ val imageWidth = arguments["imageWidth"] as Int?
+ val imageHeight = arguments["imageHeight"] as Int?
+
+ if (uri == null || mimeType == null || sampleSize == null || x == null || y == null || width == null || height == null || imageWidth == null || imageHeight == null) {
+ error("getRegion-args", "missing arguments", null)
+ return
+ }
+
+ val regionRect = Rect(x, y, x + width, y + height)
+ when (mimeType) {
+ MimeTypes.SVG -> SvgRegionFetcher(context).fetch(
+ uri = uri,
+ decoded = decoded,
+ sizeBytes = sizeBytes,
+ scale = sampleSize,
+ regionRect = regionRect,
+ imageWidth = imageWidth,
+ imageHeight = imageHeight,
+ result = this,
+ )
+
+ MimeTypes.TIFF -> TiffRegionFetcher(context).fetch(
+ uri = uri,
+ page = pageId ?: 0,
+ decoded = decoded,
+ sampleSize = sampleSize,
+ regionRect = regionRect,
+ result = this,
+ )
+
+ else -> regionFetcher.fetch(
+ uri = uri,
+ pageId = pageId,
+ decoded = decoded,
+ mimeType = mimeType,
+ sampleSize = sampleSize,
+ regionRect = regionRect,
+ imageWidth = imageWidth,
+ imageHeight = imageHeight,
+ result = this,
+ )
+ }
+ }
+
+ private suspend fun streamThumbnail() {
+ if (arguments !is Map<*, *>) {
+ return
+ }
+
+ val uri = arguments[EntryFields.URI] as String?
+ val pageId = arguments["pageId"] as Int?
+ val mimeType = arguments[EntryFields.MIME_TYPE] as String?
+ val dateModifiedMillis = (arguments[EntryFields.DATE_MODIFIED_MILLIS] as Number?)?.toLong()
+ val rotationDegrees = arguments[EntryFields.ROTATION_DEGREES] as Int?
+ val isFlipped = arguments[EntryFields.IS_FLIPPED] as Boolean?
+ val widthDip = (arguments["widthDip"] as Number?)?.toDouble()
+ val heightDip = (arguments["heightDip"] as Number?)?.toDouble()
+ val defaultSizeDip = (arguments["defaultSizeDip"] as Number?)?.toDouble()
+ val quality = arguments["quality"] as Int?
+
+ if (uri == null || mimeType == null || rotationDegrees == null || isFlipped == null || widthDip == null || heightDip == null || defaultSizeDip == null || quality == null) {
+ error("getThumbnail-args", "missing arguments", null)
+ return
+ }
+
+ // convert DIP to physical pixels here, instead of using `devicePixelRatio` in Flutter
+ ThumbnailFetcher(
+ context = context,
+ uri = uri,
+ pageId = pageId,
+ decoded = decoded,
+ mimeType = mimeType,
+ dateModifiedMillis = dateModifiedMillis ?: (Date().time),
+ rotationDegrees = rotationDegrees,
+ isFlipped = isFlipped,
+ width = (widthDip * density).roundToInt(),
+ height = (heightDip * density).roundToInt(),
+ defaultSize = (defaultSizeDip * density).roundToInt(),
+ quality = quality,
+ result = this,
+ ).fetch()
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<ImageByteStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/media_byte_stream"
+ }
+}
+
+interface ByteSink {
+ fun streamBytes(inputStream: InputStream): Boolean
+ fun error(errorCode: String, errorMessage: String?, errorDetails: Any?)
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageOpStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageOpStreamHandler.kt
new file mode 100644
index 0000000..a8b3543
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/ImageOpStreamHandler.kt
@@ -0,0 +1,221 @@
+package deckers.thibault.aves.channel.streams.darttoplatform
+
+import android.app.Activity
+import android.util.Log
+import androidx.core.net.toUri
+import deckers.thibault.aves.channel.calls.MediaEditHandler.Companion.cancelledOps
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.model.AvesEntry
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.model.NameConflictStrategy
+import deckers.thibault.aves.model.provider.ImageProvider.ImageOpCallback
+import deckers.thibault.aves.model.provider.ImageProviderFactory.getProvider
+import deckers.thibault.aves.model.provider.MediaStoreImageProvider
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.StorageUtils
+import deckers.thibault.aves.utils.StorageUtils.ensureTrailingSeparator
+import kotlinx.coroutines.launch
+
+class ImageOpStreamHandler(private val activity: Activity, private val arguments: Any?) : BaseStreamHandler() {
+ private var op: String? = null
+ private var opId: String? = null
+ private val entryMapList = ArrayList<FieldMap>()
+
+ init {
+ if (arguments is Map<*, *>) {
+ op = arguments["op"] as String?
+ opId = arguments["id"] as String?
+ @Suppress("unchecked_cast")
+ val rawEntries = arguments["entries"] as List<FieldMap>?
+ if (rawEntries != null) {
+ entryMapList.addAll(rawEntries)
+ }
+ }
+ }
+
+ override val logTag = LOG_TAG
+
+ override fun onCall(args: Any?) {
+ when (op) {
+ "delete" -> ioScope.launch { safe(::delete) }
+ "convert" -> ioScope.launch { safeSuspend(::convert) }
+ "move" -> ioScope.launch { safeSuspend(::move) }
+ "rename" -> ioScope.launch { safeSuspend(::rename) }
+ else -> endOfStream()
+ }
+ }
+
+ override fun endOfStream() {
+ cancelledOps.remove(opId)
+ super.endOfStream()
+ }
+
+ private fun isCancelledOp() = cancelledOps.contains(opId)
+
+ private fun delete() {
+ val entries = entryMapList.map(::AvesEntry)
+ for (entry in entries) {
+ val mimeType = entry.mimeType
+ val trashed = entry.trashed
+
+ val uri = entry.uri
+ val path = if (trashed) entry.trashPath else entry.path
+
+ val result: FieldMap = hashMapOf(
+ "uri" to uri.toString(),
+ )
+ if (isCancelledOp()) {
+ result["skipped"] = true
+ } else {
+ result["success"] = false
+ getProvider(activity, uri)?.let { provider ->
+ try {
+ provider.delete(activity, uri, path, mimeType)
+ result["success"] = true
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to delete entry with path=$path", e)
+ }
+ }
+ }
+ success(result)
+ }
+ endOfStream()
+ }
+
+ private suspend fun convert() {
+ if (arguments !is Map<*, *> || entryMapList.isEmpty()) {
+ endOfStream()
+ return
+ }
+
+ var destinationDir = arguments["destinationPath"] as String?
+ val mimeType = arguments["mimeType"] as String?
+ val quality = (arguments["quality"] as Number?)?.toInt()
+ val lengthUnit = arguments["lengthUnit"] as String?
+ val width = (arguments["width"] as Number?)?.toInt()
+ val height = (arguments["height"] as Number?)?.toInt()
+ val writeMetadata = arguments["writeMetadata"] as Boolean?
+ val nameConflictStrategy = NameConflictStrategy.get(arguments["nameConflictStrategy"] as String?)
+ if (destinationDir == null || mimeType == null || quality == null || lengthUnit == null || width == null || height == null || writeMetadata == null || nameConflictStrategy == null) {
+ error("convert-args", "missing arguments", null)
+ return
+ }
+
+ // assume same provider for all entries
+ val firstEntry = entryMapList.first()
+ val provider = (firstEntry["uri"] as String?)?.toUri()?.let { getProvider(activity, it) }
+ if (provider == null) {
+ error("convert-provider", "failed to find provider for entry=$firstEntry", null)
+ return
+ }
+
+ destinationDir = ensureTrailingSeparator(destinationDir)
+ val entries = entryMapList.map(::AvesEntry)
+ provider.convertMultiple(
+ activity = activity,
+ imageExportMimeType = mimeType,
+ targetDir = destinationDir,
+ entries = entries,
+ quality = quality,
+ lengthUnit = lengthUnit,
+ width = width,
+ height = height,
+ writeMetadata = writeMetadata,
+ nameConflictStrategy = nameConflictStrategy,
+ callback = object : ImageOpCallback {
+ override fun onSuccess(fields: FieldMap) = success(fields)
+ override fun onFailure(throwable: Throwable) = error("convert-failure", "failed to convert entries", throwable)
+ },
+ )
+ endOfStream()
+ }
+
+ private suspend fun move() {
+ if (arguments !is Map<*, *>) {
+ endOfStream()
+ return
+ }
+
+ val copy = arguments["copy"] as Boolean?
+ val nameConflictStrategy = NameConflictStrategy.get(arguments["nameConflictStrategy"] as String?)
+ val rawEntryMap = arguments["entriesByDestination"] as Map<*, *>?
+ if (copy == null || nameConflictStrategy == null || rawEntryMap == null || rawEntryMap.isEmpty()) {
+ error("move-args", "missing arguments", null)
+ return
+ }
+
+ val entriesByTargetDir = HashMap<String, List<AvesEntry>>()
+ rawEntryMap.forEach {
+ var destinationDir = it.key as String
+ if (destinationDir != StorageUtils.TRASH_PATH_PLACEHOLDER) {
+ destinationDir = ensureTrailingSeparator(destinationDir)
+ }
+ @Suppress("unchecked_cast")
+ val rawEntries = it.value as List<FieldMap>
+ entriesByTargetDir[destinationDir] = rawEntries.map(::AvesEntry)
+ }
+
+ // always use Media Store (as we move from or to it)
+ val provider = MediaStoreImageProvider()
+
+ provider.moveMultiple(
+ activity = activity,
+ copy = copy,
+ nameConflictStrategy = nameConflictStrategy,
+ entriesByTargetDir = entriesByTargetDir,
+ isCancelledOp = ::isCancelledOp,
+ callback = object : ImageOpCallback {
+ override fun onSuccess(fields: FieldMap) = success(fields)
+ override fun onFailure(throwable: Throwable) = error("move-failure", "failed to move entries", throwable)
+ },
+ )
+ endOfStream()
+ }
+
+ private suspend fun rename() {
+ if (arguments !is Map<*, *>) {
+ endOfStream()
+ return
+ }
+
+ val rawEntryMap = arguments["entriesToNewName"] as Map<*, *>?
+ if (rawEntryMap == null || rawEntryMap.isEmpty()) {
+ error("rename-args", "missing arguments", null)
+ return
+ }
+
+ val entriesToNewName = HashMap<AvesEntry, String>()
+ rawEntryMap.forEach {
+ @Suppress("unchecked_cast")
+ val rawEntry = it.key as FieldMap
+ val newName = it.value as String
+ entriesToNewName[AvesEntry(rawEntry)] = newName
+ }
+
+ val byProvider = entriesToNewName.entries.groupBy { kv -> getProvider(activity, kv.key.uri) }
+ for ((provider, entryList) in byProvider) {
+ if (provider == null) {
+ error("rename-provider", "failed to find provider for entry=${entryList.firstOrNull()}", null)
+ return
+ }
+
+ val entryMap = mapOf(*entryList.map { Pair(it.key, it.value) }.toTypedArray())
+ provider.renameMultiple(
+ activity = activity,
+ entriesToNewName = entryMap,
+ isCancelledOp = ::isCancelledOp,
+ callback = object : ImageOpCallback {
+ override fun onSuccess(fields: FieldMap) = success(fields)
+ override fun onFailure(throwable: Throwable) = error("rename-failure", "failed to rename", throwable.message)
+ },
+ )
+ }
+
+ endOfStream()
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<ImageOpStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/media_op_stream"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/MediaStoreStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/MediaStoreStreamHandler.kt
new file mode 100644
index 0000000..da05c38
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/darttoplatform/MediaStoreStreamHandler.kt
@@ -0,0 +1,36 @@
+package deckers.thibault.aves.channel.streams.darttoplatform
+
+import android.content.Context
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.model.provider.MediaStoreImageProvider
+import deckers.thibault.aves.utils.LogUtils
+import kotlinx.coroutines.launch
+
+class MediaStoreStreamHandler(private val context: Context, arguments: Any?) : BaseStreamHandler() {
+ // knownEntries: map of contentId -> dateModifiedMillis
+ private var knownEntries: Map<Long?, Long?>? = null
+ private var directory: String? = null
+
+ init {
+ if (arguments is Map<*, *>) {
+ knownEntries = (arguments["knownEntries"] as? Map<*, *>?)?.map { (it.key as Number?)?.toLong() to (it.value as Number?)?.toLong() }?.toMap()
+ directory = arguments["directory"] as String?
+ }
+ }
+
+ override val logTag = LOG_TAG
+
+ override fun onCall(args: Any?) {
+ ioScope.launch { safe(::fetchAll) }
+ }
+
+ private fun fetchAll() {
+ MediaStoreImageProvider().fetchAll(context, knownEntries ?: emptyMap(), directory) { success(it) }
+ endOfStream()
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<MediaStoreStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/media_store_stream"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/AnalysisStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/AnalysisStreamHandler.kt
new file mode 100644
index 0000000..92271f4
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/AnalysisStreamHandler.kt
@@ -0,0 +1,15 @@
+package deckers.thibault.aves.channel.streams.platformtodart
+
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.utils.LogUtils
+
+class AnalysisStreamHandler : BaseStreamHandler() {
+ fun notifyCompletion() = success(true)
+
+ override val logTag = LOG_TAG
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<AnalysisStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/analysis_events"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/ErrorStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/ErrorStreamHandler.kt
new file mode 100644
index 0000000..b71b642
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/ErrorStreamHandler.kt
@@ -0,0 +1,15 @@
+package deckers.thibault.aves.channel.streams.platformtodart
+
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.utils.LogUtils
+
+class ErrorStreamHandler : BaseStreamHandler() {
+ fun notifyError(error: String) = success(error)
+
+ override val logTag = LOG_TAG
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<ErrorStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/error"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/IntentStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/IntentStreamHandler.kt
new file mode 100644
index 0000000..badbe20
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/IntentStreamHandler.kt
@@ -0,0 +1,15 @@
+package deckers.thibault.aves.channel.streams.platformtodart
+
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.utils.LogUtils
+
+class IntentStreamHandler : BaseStreamHandler() {
+ fun notifyNewIntent(intentData: MutableMap<String, Any?>?) = success(intentData)
+
+ override val logTag = LOG_TAG
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<IntentStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/new_intent_stream"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaCommandStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaCommandStreamHandler.kt
new file mode 100644
index 0000000..d298464
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaCommandStreamHandler.kt
@@ -0,0 +1,61 @@
+package deckers.thibault.aves.channel.streams.platformtodart
+
+import android.support.v4.media.session.MediaSessionCompat
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.utils.LogUtils
+
+class MediaCommandStreamHandler : BaseStreamHandler() {
+ val callback = object : MediaSessionCompat.Callback() {
+ override fun onPlay() {
+ super.onPlay()
+ success(hashMapOf(KEY_COMMAND to COMMAND_PLAY))
+ }
+
+ override fun onPause() {
+ super.onPause()
+ success(hashMapOf(KEY_COMMAND to COMMAND_PAUSE))
+ }
+
+ override fun onSkipToNext() {
+ super.onSkipToNext()
+ success(hashMapOf(KEY_COMMAND to COMMAND_SKIP_TO_NEXT))
+ }
+
+ override fun onSkipToPrevious() {
+ super.onSkipToPrevious()
+ success(hashMapOf(KEY_COMMAND to COMMAND_SKIP_TO_PREVIOUS))
+ }
+
+ override fun onStop() {
+ super.onStop()
+ success(hashMapOf(KEY_COMMAND to COMMAND_STOP))
+ }
+
+ override fun onSeekTo(pos: Long) {
+ super.onSeekTo(pos)
+ success(
+ hashMapOf(
+ KEY_COMMAND to COMMAND_SEEK,
+ KEY_POSITION to pos,
+ )
+ )
+ }
+ }
+
+ override val logTag = LOG_TAG
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<MediaCommandStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/media_command"
+
+ const val KEY_COMMAND = "command"
+ const val KEY_POSITION = "position"
+
+ const val COMMAND_PLAY = "play"
+ const val COMMAND_PAUSE = "pause"
+ const val COMMAND_SKIP_TO_NEXT = "skip_to_next"
+ const val COMMAND_SKIP_TO_PREVIOUS = "skip_to_previous"
+ const val COMMAND_STOP = "stop"
+ const val COMMAND_SEEK = "seek"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaStoreChangeStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaStoreChangeStreamHandler.kt
new file mode 100644
index 0000000..d666603
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/MediaStoreChangeStreamHandler.kt
@@ -0,0 +1,49 @@
+package deckers.thibault.aves.channel.streams.platformtodart
+
+import android.content.Context
+import android.database.ContentObserver
+import android.net.Uri
+import android.provider.MediaStore
+import android.util.Log
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.utils.LogUtils
+
+class MediaStoreChangeStreamHandler(private val context: Context) : BaseStreamHandler() {
+ private val contentObserver = object : ContentObserver(null) {
+ override fun onChange(selfChange: Boolean) {
+ this.onChange(selfChange, null)
+ }
+
+ override fun onChange(selfChange: Boolean, uri: Uri?) {
+ // warning: querying the content resolver right after a change
+ // sometimes yields obsolete results
+ success(uri?.toString())
+ }
+ }
+
+ init {
+ Log.i(LOG_TAG, "start listening to Media Store")
+ try {
+ context.contentResolver.apply {
+ registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, contentObserver)
+ registerContentObserver(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true, contentObserver)
+ }
+ } catch (e: SecurityException) {
+ // Trying to register an observer may yield a security exception with this message:
+ // "Failed to find provider media for user 0; expected to find a valid ContentProvider for this authority"
+ Log.w(LOG_TAG, "failed to register content observer", e)
+ }
+ }
+
+ fun dispose() {
+ Log.i(LOG_TAG, "stop listening to Media Store")
+ context.contentResolver.unregisterContentObserver(contentObserver)
+ }
+
+ override val logTag = LOG_TAG
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<MediaStoreChangeStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/media_store_change"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/SettingsChangeStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/SettingsChangeStreamHandler.kt
new file mode 100644
index 0000000..c6f8ab2
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/SettingsChangeStreamHandler.kt
@@ -0,0 +1,82 @@
+package deckers.thibault.aves.channel.streams.platformtodart
+
+import android.content.Context
+import android.database.ContentObserver
+import android.net.Uri
+import android.provider.Settings
+import android.util.Log
+import android.view.ViewConfiguration
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.utils.LogUtils
+
+class SettingsChangeStreamHandler(private val context: Context) : BaseStreamHandler() {
+ private val contentObserver = object : ContentObserver(null) {
+ private var accelerometerRotation: Int = 0
+ private var transitionAnimationScale: Float = 1f
+ private var longPressTimeoutMillis: Int = 0
+
+ init {
+ update()
+ }
+
+ override fun onChange(selfChange: Boolean) {
+ this.onChange(selfChange, null)
+ }
+
+ override fun onChange(selfChange: Boolean, uri: Uri?) {
+ if (update()) {
+ success(
+ hashMapOf(
+ Settings.System.ACCELEROMETER_ROTATION to accelerometerRotation,
+ Settings.Global.TRANSITION_ANIMATION_SCALE to transitionAnimationScale,
+ KEY_LONG_PRESS_TIMEOUT_MILLIS to longPressTimeoutMillis,
+ )
+ )
+ }
+ }
+
+ private fun update(): Boolean {
+ var changed = false
+ try {
+ val newAccelerometerRotation = Settings.System.getInt(context.contentResolver, Settings.System.ACCELEROMETER_ROTATION)
+ if (accelerometerRotation != newAccelerometerRotation) {
+ accelerometerRotation = newAccelerometerRotation
+ changed = true
+ }
+ val newTransitionAnimationScale = Settings.Global.getFloat(context.contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE)
+ if (transitionAnimationScale != newTransitionAnimationScale) {
+ transitionAnimationScale = newTransitionAnimationScale
+ changed = true
+ }
+ val newLongPressTimeout = ViewConfiguration.getLongPressTimeout()
+ if (longPressTimeoutMillis != newLongPressTimeout) {
+ longPressTimeoutMillis = newLongPressTimeout
+ changed = true
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get settings with error=${e.message}", null)
+ }
+ return changed
+ }
+ }
+
+ init {
+ Log.i(LOG_TAG, "start listening to system settings")
+ context.contentResolver.registerContentObserver(Settings.System.CONTENT_URI, true, contentObserver)
+ }
+
+ fun dispose() {
+ Log.i(LOG_TAG, "stop listening to system settings")
+ context.contentResolver.unregisterContentObserver(contentObserver)
+ }
+
+ override val logTag = LOG_TAG
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<SettingsChangeStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/settings_change"
+
+ // cf `Settings.Secure.LONG_PRESS_TIMEOUT`
+ const val KEY_LONG_PRESS_TIMEOUT_MILLIS = "long_press_timeout"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/WindowChangeStreamHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/WindowChangeStreamHandler.kt
new file mode 100644
index 0000000..59d62f4
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/channel/streams/platformtodart/WindowChangeStreamHandler.kt
@@ -0,0 +1,15 @@
+package deckers.thibault.aves.channel.streams.platformtodart
+
+import deckers.thibault.aves.channel.streams.BaseStreamHandler
+import deckers.thibault.aves.utils.LogUtils
+
+class WindowChangeStreamHandler : BaseStreamHandler() {
+ fun notifyWindowModeChange() = success(null)
+
+ override val logTag = LOG_TAG
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<ErrorStreamHandler>()
+ const val CHANNEL = "deckers.thibault/aves/window_change"
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/decoding/RegionFetcher.kt b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/RegionFetcher.kt
new file mode 100644
index 0000000..5efbf5d
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/RegionFetcher.kt
@@ -0,0 +1,227 @@
+package deckers.thibault.aves.decoding
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.BitmapRegionDecoder
+import android.graphics.ColorSpace
+import android.graphics.Rect
+import android.net.Uri
+import android.os.Build
+import android.util.Log
+import androidx.core.graphics.createBitmap
+import com.bumptech.glide.Glide
+import deckers.thibault.aves.channel.streams.darttoplatform.ByteSink
+import deckers.thibault.aves.glide.AvesAppGlideModule
+import deckers.thibault.aves.glide.MultiPageImage
+import deckers.thibault.aves.utils.BitmapRegionDecoderCompat
+import deckers.thibault.aves.utils.BitmapUtils
+import deckers.thibault.aves.utils.BitmapUtils.describe
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MathUtils
+import deckers.thibault.aves.utils.MemoryUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.StorageUtils
+import java.io.ByteArrayInputStream
+import java.nio.ByteBuffer
+import java.util.concurrent.locks.ReentrantLock
+import kotlin.concurrent.withLock
+import kotlin.math.max
+import kotlin.math.roundToInt
+
+// As of Android 14 (API 34), `BitmapRegionDecoder` documentation states
+// that "only the JPEG, PNG, WebP and HEIF formats are supported"
+// but in practice it successfully decodes some others.
+class RegionFetcher internal constructor(
+ private val context: Context,
+) {
+ suspend fun fetch(
+ uri: Uri,
+ pageId: Int?,
+ decoded: Boolean,
+ mimeType: String,
+ sampleSize: Int,
+ regionRect: Rect,
+ imageWidth: Int,
+ imageHeight: Int,
+ requestKey: Pair<Uri, Int?> = Pair(uri, pageId),
+ result: ByteSink,
+ ) {
+ if (pageId != null && MultiPageImage.isSupported(mimeType)) {
+ // use export for requested page
+ val exportUri = exportUris.getOrPut(requestKey) { createTemporaryExport(uri, mimeType, pageId) }
+ fetch(
+ uri = exportUri,
+ pageId = null,
+ decoded = decoded,
+ mimeType = EXPORT_MIME_TYPE,
+ sampleSize = sampleSize,
+ regionRect = regionRect,
+ imageWidth = imageWidth,
+ imageHeight = imageHeight,
+ requestKey = requestKey,
+ result = result,
+ )
+ return
+ }
+
+ try {
+ val decoder = getOrCreateDecoder(context, uri, requestKey)
+ if (decoder == null) {
+ result.error("fetch-read-null", "failed to open file for mimeType=$mimeType uri=$uri regionRect=$regionRect", null)
+ return
+ }
+
+ // with raw images, the known image size may not match the decoded image size
+ // so we scale the requested region accordingly
+ var effectiveRect = regionRect
+ var effectiveSampleSize = sampleSize
+
+ if (imageWidth != decoder.width || imageHeight != decoder.height) {
+ val xf = decoder.width.toDouble() / imageWidth
+ val yf = decoder.height.toDouble() / imageHeight
+ effectiveRect = Rect(
+ (regionRect.left * xf).roundToInt(),
+ (regionRect.top * yf).roundToInt(),
+ (regionRect.right * xf).roundToInt(),
+ (regionRect.bottom * yf).roundToInt(),
+ )
+ val factor = MathUtils.highestPowerOf2((1 / max(xf, yf)).roundToInt())
+ if (factor > 1) {
+ effectiveSampleSize = max(1, effectiveSampleSize / factor)
+ }
+ }
+
+ val options = BitmapFactory.Options().apply {
+ inSampleSize = effectiveSampleSize
+ // Specifying preferred config and color space avoids the need for conversion afterwards,
+ // but may prevent decoding (e.g. from RGBA_1010102 to ARGB_8888 on some devices).
+ inPreferredConfig = PREFERRED_CONFIG
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ inPreferredColorSpace = ColorSpace.get(ColorSpace.Named.SRGB)
+ }
+ }
+
+ val pixelCount = effectiveRect.width() * effectiveRect.height() / effectiveSampleSize
+ val targetBitmapSizeBytes = BitmapUtils.getExpectedImageSize(pixelCount.toLong(), options.inPreferredConfig)
+ if (!MemoryUtils.canAllocate(targetBitmapSizeBytes)) {
+ // decoding a region that large would yield an OOM when creating the bitmap
+ result.error("fetch-large-region", "Region too large for uri=$uri regionRect=$regionRect", null)
+ return
+ }
+
+ var bitmap = decoder.decodeRegion(effectiveRect, options)
+ if (bitmap == null) {
+ // retry without specifying config or color space,
+ // falling back to custom byte conversion afterwards
+ options.inPreferredConfig = null
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && options.inPreferredColorSpace != null) {
+ options.inPreferredColorSpace = null
+ }
+ bitmap = decoder.decodeRegion(effectiveRect, options)
+ }
+
+ val bytes = BitmapUtils.getBytes(bitmap, recycle = true, decoded = decoded, mimeType)
+ if (bytes == null) {
+ result.error("fetch-null", "failed to decode region for uri=$uri regionRect=$regionRect", null)
+ } else {
+ result.streamBytes(ByteArrayInputStream(bytes))
+ }
+ } catch (e: Exception) {
+ if (EXPORT_MIME_TYPE != mimeType) {
+ // retry with export on failure,
+ // as some formats are not fully supported by `BitmapRegionDecoder`
+ val exportUri = exportUris.getOrPut(requestKey) { createTemporaryExport(uri, mimeType, pageId) }
+ fetch(
+ uri = exportUri,
+ pageId = null,
+ decoded = decoded,
+ mimeType = EXPORT_MIME_TYPE,
+ sampleSize = sampleSize,
+ regionRect = regionRect,
+ imageWidth = imageWidth,
+ imageHeight = imageHeight,
+ requestKey = requestKey,
+ result = result,
+ )
+ return
+ }
+
+ result.error("fetch-read-exception", "failed to initialize region decoder for uri=$uri regionRect=$regionRect", e.message)
+ }
+ }
+
+ private suspend fun createTemporaryExport(uri: Uri, mimeType: String, pageId: Int?): Uri {
+ val exportFormat = EXPORT_FORMAT
+ Log.d(LOG_TAG, "create export for uri=$uri mimeType=$mimeType pageId=$pageId exportFormat=$exportFormat")
+ val target = Glide.with(context)
+ .asBitmap()
+ .apply(AvesAppGlideModule.uncachedFullImageOptions)
+ .load(AvesAppGlideModule.getModel(context, uri, mimeType, pageId))
+ .submit()
+
+ try {
+ val bitmap = target.get()
+ val tempFile = StorageUtils.createTempFile(context).apply {
+ outputStream().use { output ->
+ val encodedExport = bitmap.compress(exportFormat, 100, output)
+ if (!encodedExport) {
+ Log.w(LOG_TAG, "failed export via encoded bytes for uri=$uri mimeType=$mimeType pageId=$pageId exportFormat=$exportFormat, with bitmap=${bitmap.describe()}")
+
+ val decodedBytes = BitmapUtils.getBytes(bitmap, recycle = false, decoded = true, mimeType)
+ if (decodedBytes != null) {
+ val exportBitmap = createBitmap(bitmap.width, bitmap.height, PREFERRED_CONFIG)
+ exportBitmap.copyPixelsFromBuffer(ByteBuffer.wrap(decodedBytes))
+ val decodedExport = exportBitmap.compress(exportFormat, 100, output)
+ if (!decodedExport) {
+ Log.w(LOG_TAG, "failed to compress exportBitmap=${bitmap.describe()}")
+ }
+ }
+ }
+ }
+ }
+ return Uri.fromFile(tempFile)
+ } finally {
+ Glide.with(context).clear(target)
+ }
+ }
+
+ private data class DecoderRef(
+ val requestKey: Pair<Uri, Int?>,
+ val decoder: BitmapRegionDecoder,
+ )
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<RegionFetcher>()
+ private val PREFERRED_CONFIG = Bitmap.Config.ARGB_8888
+ private const val DECODER_POOL_SIZE = 3
+ private const val EXPORT_MIME_TYPE = MimeTypes.JPEG
+ private val EXPORT_FORMAT = Bitmap.CompressFormat.JPEG
+ private val decoderPool = ArrayList<DecoderRef>()
+ private val exportUris = HashMap<Pair<Uri, Int?>, Uri>()
+
+ private val poolLock = ReentrantLock()
+
+ private fun getOrCreateDecoder(context: Context, uri: Uri, requestKey: Pair<Uri, Int?>): BitmapRegionDecoder? {
+ poolLock.withLock {
+ var decoderRef = decoderPool.firstOrNull { it.requestKey == requestKey }
+ if (decoderRef == null) {
+ val newDecoder = StorageUtils.openInputStream(context, uri)?.use { input ->
+ BitmapRegionDecoderCompat.newInstance(input)
+ }
+ if (newDecoder == null) {
+ return null
+ }
+ decoderRef = DecoderRef(requestKey, newDecoder)
+ } else {
+ decoderPool.remove(decoderRef)
+ }
+ decoderPool.add(0, decoderRef)
+ while (decoderPool.size > DECODER_POOL_SIZE) {
+ decoderPool.removeAt(decoderPool.size - 1)
+ }
+ return decoderRef.decoder
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/decoding/SvgRegionFetcher.kt b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/SvgRegionFetcher.kt
new file mode 100644
index 0000000..8eadcf5
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/SvgRegionFetcher.kt
@@ -0,0 +1,145 @@
+package deckers.thibault.aves.decoding
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Rect
+import android.graphics.RectF
+import android.net.Uri
+import androidx.core.graphics.createBitmap
+import com.caverock.androidsvg.PreserveAspectRatio
+import com.caverock.androidsvg.RenderOptions
+import com.caverock.androidsvg.SVG
+import com.caverock.androidsvg.SVGParseException
+import com.caverock.androidsvg.utils.SVGAndroidRenderer
+import deckers.thibault.aves.channel.streams.darttoplatform.ByteSink
+import deckers.thibault.aves.metadata.SVGParserBufferedInputStream
+import deckers.thibault.aves.metadata.SvgHelper.IMAGE_BASE64_SIZE_DANGER_THRESHOLD
+import deckers.thibault.aves.metadata.SvgHelper.normalizeSize
+import deckers.thibault.aves.utils.BitmapUtils
+import deckers.thibault.aves.utils.MemoryUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.StorageUtils
+import java.io.ByteArrayInputStream
+import java.util.concurrent.locks.ReentrantLock
+import kotlin.concurrent.withLock
+import kotlin.math.ceil
+
+class SvgRegionFetcher internal constructor(
+ private val context: Context,
+) {
+ suspend fun fetch(
+ uri: Uri,
+ decoded: Boolean,
+ sizeBytes: Long?,
+ scale: Int,
+ regionRect: Rect,
+ imageWidth: Int,
+ imageHeight: Int,
+ result: ByteSink,
+ ) {
+ if (!MemoryUtils.canAllocate(sizeBytes)) {
+ // opening an SVG that large would yield an OOM during parsing from `com.caverock.androidsvg.SVGParser`
+ result.error("fetch-read-large-file", "SVG too large at $sizeBytes bytes, for uri=$uri regionRect=$regionRect", null)
+ return
+ }
+
+ try {
+ val svg = getOrCreateDecoder(context, uri)
+ if (svg == null) {
+ result.error("fetch-read-null", "failed to open file for uri=$uri regionRect=$regionRect", null)
+ return
+ }
+
+ // we scale the requested region accordingly to the viewbox size
+ val viewBox = svg.documentViewBox
+ val svgWidth = viewBox.width()
+ val svgHeight = viewBox.height()
+ val xf = imageWidth / scale / ceil(svgWidth)
+ val yf = imageHeight / scale / ceil(svgHeight)
+ // some SVG paths do not respect the rendering viewbox and do not reach its edges
+ // so we render to a slightly larger bitmap, using a slightly larger viewbox,
+ // and crop that bitmap to the target region size
+ val bleedX = xf.toInt()
+ val bleedY = yf.toInt()
+ val effectiveRect = RectF(
+ (regionRect.left - bleedX) / xf,
+ (regionRect.top - bleedY) / yf,
+ (regionRect.right + bleedX) / xf,
+ (regionRect.bottom + bleedY) / yf,
+ )
+ effectiveRect.offset(viewBox.left, viewBox.top)
+
+ val renderOptions = RenderOptions()
+ renderOptions.viewBox(effectiveRect.left, effectiveRect.top, effectiveRect.width(), effectiveRect.height())
+ renderOptions.preserveAspectRatio(PreserveAspectRatio.FULLSCREEN_START)
+
+ val targetBitmapWidth = regionRect.width()
+ val targetBitmapHeight = regionRect.height()
+ val canvasWidth = targetBitmapWidth + bleedX * 2
+ val canvasHeight = targetBitmapHeight + bleedY * 2
+
+ val config = PREFERRED_CONFIG
+ val pixelCount = canvasWidth * canvasHeight
+ val targetBitmapSizeBytes = BitmapUtils.getExpectedImageSize(pixelCount.toLong(), config)
+ if (!MemoryUtils.canAllocate(targetBitmapSizeBytes)) {
+ // decoding a region that large would yield an OOM when creating the bitmap
+ result.error("fetch-large-region", "SVG region too large for uri=$uri regionRect=$regionRect", null)
+ return
+ }
+
+ var bitmap = createBitmap(canvasWidth, canvasHeight, config)
+ val canvas = Canvas(bitmap)
+ SVGAndroidRenderer.setImageBase64StringMaxSize(IMAGE_BASE64_SIZE_DANGER_THRESHOLD)
+ svg.renderToCanvas(canvas, renderOptions)
+
+ bitmap = Bitmap.createBitmap(bitmap, bleedX, bleedY, targetBitmapWidth, targetBitmapHeight)
+ val bytes = BitmapUtils.getBytes(bitmap, recycle = true, decoded = decoded, MimeTypes.SVG)
+ if (bytes == null) {
+ result.error("fetch-null", "failed to decode SVG for uri=$uri regionRect=$regionRect", null)
+ } else {
+ result.streamBytes(ByteArrayInputStream(bytes))
+ }
+ } catch (e: SVGParseException) {
+ result.error("fetch-parse", "failed to parse SVG for uri=$uri regionRect=$regionRect", e.message)
+ } catch (e: Exception) {
+ result.error("fetch-exception", "failed to initialize region decoder for uri=$uri regionRect=$regionRect", e.message)
+ }
+ }
+
+ private data class DecoderRef(
+ val uri: Uri,
+ val decoder: SVG,
+ )
+
+ companion object {
+ private val PREFERRED_CONFIG = Bitmap.Config.ARGB_8888
+ private const val DECODER_POOL_SIZE = 3
+ private val decoderPool = ArrayList<DecoderRef>()
+
+ private val poolLock = ReentrantLock()
+
+ private fun getOrCreateDecoder(context: Context, uri: Uri): SVG? {
+ poolLock.withLock {
+ var decoderRef = decoderPool.firstOrNull { it.uri == uri }
+ if (decoderRef == null) {
+ val newDecoder = StorageUtils.openInputStream(context, uri)?.use { input ->
+ SVG.getFromInputStream(SVGParserBufferedInputStream(input))
+ }
+ if (newDecoder == null) {
+ return null
+ }
+ newDecoder.normalizeSize()
+ decoderRef = DecoderRef(uri, newDecoder)
+ } else {
+ decoderPool.remove(decoderRef)
+ }
+ decoderPool.add(0, decoderRef)
+ while (decoderPool.size > DECODER_POOL_SIZE) {
+ decoderPool.removeAt(decoderPool.size - 1)
+ }
+ return decoderRef.decoder
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/decoding/ThumbnailFetcher.kt b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/ThumbnailFetcher.kt
new file mode 100644
index 0000000..4b46a05
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/ThumbnailFetcher.kt
@@ -0,0 +1,182 @@
+package deckers.thibault.aves.decoding
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.net.Uri
+import android.os.Build
+import android.provider.MediaStore
+import android.util.Log
+import android.util.Size
+import androidx.annotation.RequiresApi
+import androidx.core.graphics.scale
+import androidx.core.net.toUri
+import com.bumptech.glide.Glide
+import com.bumptech.glide.load.DecodeFormat
+import com.bumptech.glide.load.engine.DiskCacheStrategy
+import com.bumptech.glide.request.RequestOptions
+import com.bumptech.glide.signature.ObjectKey
+import deckers.thibault.aves.channel.streams.darttoplatform.ByteSink
+import deckers.thibault.aves.glide.AvesAppGlideModule
+import deckers.thibault.aves.glide.MultiPageImage
+import deckers.thibault.aves.utils.BitmapUtils
+import deckers.thibault.aves.utils.BitmapUtils.applyExifOrientation
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.SVG
+import deckers.thibault.aves.utils.MimeTypes.isVideo
+import deckers.thibault.aves.utils.MimeTypes.needRotationAfterContentResolverThumbnail
+import deckers.thibault.aves.utils.MimeTypes.needRotationAfterGlide
+import deckers.thibault.aves.utils.StorageUtils
+import deckers.thibault.aves.utils.UriUtils.tryParseId
+import java.io.ByteArrayInputStream
+import kotlin.math.min
+import kotlin.math.roundToInt
+
+class ThumbnailFetcher internal constructor(
+ private val context: Context,
+ uri: String,
+ private val pageId: Int?,
+ private val decoded: Boolean,
+ private val mimeType: String,
+ private val dateModifiedMillis: Long,
+ private val rotationDegrees: Int,
+ private val isFlipped: Boolean,
+ width: Int?,
+ height: Int?,
+ private val defaultSize: Int,
+ private val quality: Int,
+ private val result: ByteSink,
+) {
+ private val uri: Uri = uri.toUri()
+ private val width: Int = if (width?.takeIf { it > 0 } != null) width else defaultSize
+ private val height: Int = if (height?.takeIf { it > 0 } != null) height else defaultSize
+ private val svgFetch = mimeType == SVG
+ private val tiffFetch = mimeType == MimeTypes.TIFF
+ private val multiPageFetch = pageId != null && MultiPageImage.isSupported(mimeType)
+ private val customFetch = svgFetch || tiffFetch || multiPageFetch
+
+ suspend fun fetch() {
+ var bitmap: Bitmap? = null
+ var exception: Exception? = null
+
+ try {
+ if (!customFetch && (width == defaultSize || height == defaultSize) && !isFlipped) {
+ // Fetch low quality thumbnails when size is not specified.
+ // As of Android 11, the Media Store content resolver may return a thumbnail
+ // that is automatically rotated according to EXIF orientation, but not flipped,
+ // so we skip this step for flipped entries.
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ bitmap = getByResolver()
+ } else if (StorageUtils.isMediaStoreContentUri(uri)) {
+ bitmap = getByMediaStore()
+ }
+ }
+ } catch (e: Exception) {
+ exception = e
+ }
+
+ // fallback if the native methods failed or for higher quality thumbnails
+ if (bitmap == null) {
+ try {
+ bitmap = getByGlide()
+ } catch (e: Exception) {
+ exception = e
+ }
+ }
+
+ if (bitmap != null) {
+ if (bitmap.width > width && bitmap.height > height) {
+ // rescale when the resulting bitmap is larger than requested
+ val scalingFactor: Double = min(bitmap.width.toDouble() / width, bitmap.height.toDouble() / height)
+ val dstWidth = (bitmap.width / scalingFactor).roundToInt()
+ val dstHeight = (bitmap.height / scalingFactor).roundToInt()
+ Log.d(
+ LOG_TAG, "rescale thumbnail for mimeType=$mimeType uri=$uri width=$width height=$height" +
+ ", with bitmap byteCount=${bitmap.byteCount} size=${bitmap.width}x${bitmap.height}" +
+ ", to target=${dstWidth}x${dstHeight}"
+ )
+ bitmap = bitmap.scale(dstWidth, dstHeight)
+ }
+
+ if (bitmap.byteCount > BITMAP_SIZE_DANGER_THRESHOLD) {
+ result.error(
+ "getThumbnail-large", "thumbnail bitmap dangerously large" +
+ " for mimeType=$mimeType uri=$uri pageId=$pageId width=$width height=$height" +
+ ", with bitmap byteCount=${bitmap.byteCount} size=${bitmap.width}x${bitmap.height} config=${bitmap.config?.name}", null
+ )
+ return
+ }
+ }
+
+ // do not recycle bitmaps fetched from `ContentResolver` or Glide as their lifecycle is unknown
+ val bytes = BitmapUtils.getBytes(bitmap, recycle = false, decoded = decoded, mimeType)
+ if (bytes == null) {
+ var errorDetails: String? = exception?.message
+ if (errorDetails?.isNotEmpty() == true) {
+ errorDetails = errorDetails.split(Regex("\n"), 2).first()
+ }
+ result.error("getThumbnail-null", "failed to get thumbnail for mimeType=$mimeType uri=$uri", errorDetails)
+ } else {
+ result.streamBytes(ByteArrayInputStream(bytes))
+ }
+ }
+
+ @RequiresApi(api = Build.VERSION_CODES.Q)
+ private fun getByResolver(): Bitmap? {
+ val resolver = context.contentResolver
+ var bitmap: Bitmap? = resolver.loadThumbnail(uri, Size(width, height), null)
+ if (needRotationAfterContentResolverThumbnail(mimeType)) {
+ bitmap = applyExifOrientation(context, bitmap, rotationDegrees, isFlipped)
+ }
+ return bitmap
+ }
+
+ private fun getByMediaStore(): Bitmap? {
+ val contentId = uri.tryParseId() ?: return null
+ val resolver = context.contentResolver
+ return if (isVideo(mimeType)) {
+ @Suppress("deprecation")
+ MediaStore.Video.Thumbnails.getThumbnail(resolver, contentId, MediaStore.Video.Thumbnails.MINI_KIND, null)
+ } else {
+ @Suppress("deprecation")
+ var bitmap = MediaStore.Images.Thumbnails.getThumbnail(resolver, contentId, MediaStore.Images.Thumbnails.MINI_KIND, null)
+ // from Android 10 (API 29), returned thumbnail is already rotated according to EXIF orientation
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && bitmap != null) {
+ bitmap = applyExifOrientation(context, bitmap, rotationDegrees, isFlipped)
+ }
+ bitmap
+ }
+ }
+
+ private fun getByGlide(): Bitmap? {
+ // add signature to ignore cache for images which got modified but kept the same URI
+ var options = RequestOptions()
+ .format(if (quality == 100) DecodeFormat.PREFER_ARGB_8888 else DecodeFormat.PREFER_RGB_565)
+ .signature(ObjectKey("$dateModifiedMillis-$rotationDegrees-$isFlipped-$width-$pageId"))
+ .override(width, height)
+ if (isVideo(mimeType)) {
+ options = options.diskCacheStrategy(DiskCacheStrategy.RESOURCE)
+ }
+
+ val target = Glide.with(context)
+ .asBitmap()
+ .apply(options)
+ .load(AvesAppGlideModule.getModel(context, uri, mimeType, pageId))
+ .submit(width, height)
+
+ return try {
+ var bitmap = target.get()
+ if (needRotationAfterGlide(mimeType, pageId)) {
+ bitmap = applyExifOrientation(context, bitmap, rotationDegrees, isFlipped)
+ }
+ bitmap
+ } finally {
+ Glide.with(context).clear(target)
+ }
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<ThumbnailFetcher>()
+ private const val BITMAP_SIZE_DANGER_THRESHOLD = 20 * (1 shl 20) // MB
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/decoding/TiffRegionFetcher.kt b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/TiffRegionFetcher.kt
new file mode 100644
index 0000000..7c58df0
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/decoding/TiffRegionFetcher.kt
@@ -0,0 +1,51 @@
+package deckers.thibault.aves.decoding
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Rect
+import android.net.Uri
+import deckers.thibault.aves.channel.streams.darttoplatform.ByteSink
+import deckers.thibault.aves.glide.TiffFetcher
+import deckers.thibault.aves.utils.BitmapUtils
+import deckers.thibault.aves.utils.MimeTypes
+import org.beyka.tiffbitmapfactory.DecodeArea
+import org.beyka.tiffbitmapfactory.TiffBitmapFactory
+import java.io.ByteArrayInputStream
+
+class TiffRegionFetcher internal constructor(
+ private val context: Context,
+) {
+ suspend fun fetch(
+ uri: Uri,
+ page: Int,
+ decoded: Boolean,
+ sampleSize: Int,
+ regionRect: Rect,
+ result: ByteSink,
+ ) {
+ try {
+ val pfd = context.contentResolver.openFileDescriptor(uri, "r")
+ if (pfd == null) {
+ result.error("fetch-fd", "failed to get file descriptor for uri=$uri", null)
+ return
+ }
+ pfd.use {
+ val fd = pfd.detachFd()
+ val options = TiffFetcher.buildOptions().apply {
+ inDirectoryNumber = page
+ inSampleSize = sampleSize
+ inDecodeArea = DecodeArea(regionRect.left, regionRect.top, regionRect.width(), regionRect.height())
+ }
+ val bitmap: Bitmap? = TiffBitmapFactory.decodeFileDescriptor(fd, options)
+ val bytes = BitmapUtils.getBytes(bitmap, recycle = true, decoded = decoded, MimeTypes.TIFF)
+ if (bytes == null) {
+ result.error("fetch-null", "failed to decode region for uri=$uri page=$page regionRect=$regionRect", null)
+ } else {
+ result.streamBytes(ByteArrayInputStream(bytes))
+ }
+ }
+ } catch (e: Exception) {
+ result.error("fetch-exception", "failed to read from uri=$uri page=$page regionRect=$regionRect", e.message)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/glide/AvesAppGlideModule.kt b/android/app/src/main/kotlin/deckers/thibault/aves/glide/AvesAppGlideModule.kt
new file mode 100644
index 0000000..0b2951a
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/glide/AvesAppGlideModule.kt
@@ -0,0 +1,92 @@
+package deckers.thibault.aves.glide
+
+import android.content.Context
+import android.net.Uri
+import android.text.format.Formatter
+import android.util.Log
+import com.bumptech.glide.Glide
+import com.bumptech.glide.GlideBuilder
+import com.bumptech.glide.Registry
+import com.bumptech.glide.annotation.GlideModule
+import com.bumptech.glide.load.DecodeFormat
+import com.bumptech.glide.load.ImageHeaderParser
+import com.bumptech.glide.load.engine.DiskCacheStrategy
+import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPoolAdapter
+import com.bumptech.glide.load.engine.bitmap_recycle.LruArrayPool
+import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool
+import com.bumptech.glide.load.engine.cache.DiskCache
+import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
+import com.bumptech.glide.load.engine.cache.LruResourceCache
+import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
+import com.bumptech.glide.load.resource.bitmap.ExifInterfaceImageHeaderParser
+import com.bumptech.glide.module.AppGlideModule
+import com.bumptech.glide.request.RequestOptions
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.isVideo
+import deckers.thibault.aves.utils.StorageUtils
+import deckers.thibault.aves.utils.compatRemoveIf
+
+@GlideModule
+class AvesAppGlideModule : AppGlideModule() {
+ override fun applyOptions(context: Context, builder: GlideBuilder) {
+ // hide noisy warning (e.g. for images that can't be decoded)
+ builder.setLogLevel(Log.ERROR)
+
+ // sizing
+ val memorySizeCalculator = MemorySizeCalculator.Builder(context).build()
+ builder.setMemorySizeCalculator(memorySizeCalculator)
+ val size: Int = memorySizeCalculator.bitmapPoolSize
+ if (size > 0) {
+ builder.setBitmapPool(LruBitmapPool(size.toLong()))
+ } else {
+ builder.setBitmapPool(BitmapPoolAdapter())
+ }
+ builder.setArrayPool(LruArrayPool(memorySizeCalculator.arrayPoolSizeInBytes))
+ builder.setMemoryCache(LruResourceCache(memorySizeCalculator.memoryCacheSize.toLong()))
+
+ val diskCacheSize = DiskCache.Factory.DEFAULT_DISK_CACHE_SIZE
+ val internalCacheDiskCacheFactory = InternalCacheDiskCacheFactory(context, DiskCache.Factory.DEFAULT_DISK_CACHE_DIR, diskCacheSize.toLong())
+ builder.setDiskCache(internalCacheDiskCacheFactory)
+
+ fun toMb(bytes: Int) = Formatter.formatFileSize(context, bytes.toLong())
+ Log.d(
+ LOG_TAG, "Glide disk cache size=${toMb(diskCacheSize)}" +
+ ", memory cache size=${toMb(memorySizeCalculator.memoryCacheSize)}" +
+ ", bitmap pool size=${toMb(memorySizeCalculator.bitmapPoolSize)}" +
+ ", array pool size=${toMb(memorySizeCalculator.arrayPoolSizeInBytes)}"
+ )
+ }
+
+ override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
+ // prevent ExifInterface error logs
+ // cf https://github.com/bumptech/glide/issues/3383
+ registry.imageHeaderParsers.compatRemoveIf { parser: ImageHeaderParser? -> parser is ExifInterfaceImageHeaderParser }
+ }
+
+ override fun isManifestParsingEnabled(): Boolean = false
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<AvesAppGlideModule>()
+
+ // request a fresh image with the highest quality format
+ val uncachedFullImageOptions = RequestOptions()
+ .format(DecodeFormat.PREFER_ARGB_8888)
+ .diskCacheStrategy(DiskCacheStrategy.NONE)
+ .skipMemoryCache(true)
+
+ fun getModel(context: Context, uri: Uri, mimeType: String, pageId: Int?, sizeBytes: Long? = null): Any {
+ return if (pageId != null && MultiPageImage.isSupported(mimeType)) {
+ MultiPageImage(context, uri, mimeType, pageId)
+ } else if (mimeType == MimeTypes.TIFF) {
+ TiffImage(context, uri, pageId)
+ } else if (mimeType == MimeTypes.SVG) {
+ SvgImage(context, uri)
+ } else if (isVideo(mimeType)) {
+ VideoThumbnail(context, uri)
+ } else {
+ StorageUtils.getGlideSafeUri(context, uri, mimeType, sizeBytes)
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/glide/MultiPageImageGlideModule.kt b/android/app/src/main/kotlin/deckers/thibault/aves/glide/MultiPageImageGlideModule.kt
new file mode 100644
index 0000000..a87a7c9
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/glide/MultiPageImageGlideModule.kt
@@ -0,0 +1,89 @@
+package deckers.thibault.aves.glide
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.net.Uri
+import android.os.Build
+import com.bumptech.glide.Glide
+import com.bumptech.glide.Priority
+import com.bumptech.glide.Registry
+import com.bumptech.glide.annotation.GlideModule
+import com.bumptech.glide.load.DataSource
+import com.bumptech.glide.load.Options
+import com.bumptech.glide.load.data.DataFetcher
+import com.bumptech.glide.load.data.DataFetcher.DataCallback
+import com.bumptech.glide.load.model.ModelLoader
+import com.bumptech.glide.load.model.ModelLoaderFactory
+import com.bumptech.glide.load.model.MultiModelLoaderFactory
+import com.bumptech.glide.module.LibraryGlideModule
+import com.bumptech.glide.signature.ObjectKey
+import deckers.thibault.aves.metadata.MultiPage
+import deckers.thibault.aves.metadata.MultiTrackMedia
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.isIsoBMFFImage
+
+@GlideModule
+class MultiPageImageGlideModule : LibraryGlideModule() {
+ override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
+ registry.append(MultiPageImage::class.java, Bitmap::class.java, MultiPageThumbnailLoader.Factory())
+ }
+}
+
+class MultiPageImage(val context: Context, val uri: Uri, val mimeType: String, val pageId: Int?) {
+ override fun toString(): String = "MultiPageImage#${hashCode()}{uri=$uri mimeType=$mimeType pageId=$pageId}"
+
+ companion object {
+ fun isSupported(mimeType: String) = isIsoBMFFImage(mimeType) || mimeType == MimeTypes.JPEG
+ }
+}
+
+internal class MultiPageThumbnailLoader : ModelLoader<MultiPageImage, Bitmap> {
+ override fun buildLoadData(model: MultiPageImage, width: Int, height: Int, options: Options): ModelLoader.LoadData<Bitmap> {
+ return ModelLoader.LoadData(ObjectKey(model.uri), MultiPageImageFetcher(model, width, height))
+ }
+
+ override fun handles(model: MultiPageImage): Boolean = true
+
+ internal class Factory : ModelLoaderFactory<MultiPageImage, Bitmap> {
+ override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<MultiPageImage, Bitmap> = MultiPageThumbnailLoader()
+
+ override fun teardown() {}
+ }
+}
+
+internal class MultiPageImageFetcher(val model: MultiPageImage, val width: Int, val height: Int) : DataFetcher<Bitmap> {
+ override fun loadData(priority: Priority, callback: DataCallback<in Bitmap>) {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
+ callback.onLoadFailed(Exception("unsupported Android version"))
+ return
+ }
+
+ val context = model.context
+ val uri = model.uri
+ val mimeType = model.mimeType
+
+ var bitmap: Bitmap? = null
+ if (isIsoBMFFImage(mimeType)) {
+ val trackIndex = model.pageId
+ bitmap = MultiTrackMedia.getImage(context, uri, trackIndex)
+ } else if (mimeType == MimeTypes.JPEG) {
+ val pageIndex = model.pageId ?: 0
+ bitmap = MultiPage.getJpegMpfBitmap(context, uri, pageIndex)
+ }
+
+ if (bitmap == null) {
+ callback.onLoadFailed(Exception("null bitmap"))
+ } else {
+ callback.onDataReady(bitmap)
+ }
+ }
+
+ override fun cleanup() {}
+
+ // cannot cancel
+ override fun cancel() {}
+
+ override fun getDataClass(): Class<Bitmap> = Bitmap::class.java
+
+ override fun getDataSource(): DataSource = DataSource.LOCAL
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/glide/SvgGlideModule.kt b/android/app/src/main/kotlin/deckers/thibault/aves/glide/SvgGlideModule.kt
new file mode 100644
index 0000000..2a43d4b
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/glide/SvgGlideModule.kt
@@ -0,0 +1,102 @@
+package deckers.thibault.aves.glide
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.net.Uri
+import androidx.core.graphics.createBitmap
+import com.bumptech.glide.Glide
+import com.bumptech.glide.Priority
+import com.bumptech.glide.Registry
+import com.bumptech.glide.annotation.GlideModule
+import com.bumptech.glide.load.DataSource
+import com.bumptech.glide.load.Options
+import com.bumptech.glide.load.data.DataFetcher
+import com.bumptech.glide.load.model.ModelLoader
+import com.bumptech.glide.load.model.ModelLoaderFactory
+import com.bumptech.glide.load.model.MultiModelLoaderFactory
+import com.bumptech.glide.module.LibraryGlideModule
+import com.bumptech.glide.signature.ObjectKey
+import com.caverock.androidsvg.SVG
+import com.caverock.androidsvg.SVGParseException
+import com.caverock.androidsvg.utils.SVGAndroidRenderer
+import deckers.thibault.aves.metadata.SVGParserBufferedInputStream
+import deckers.thibault.aves.metadata.SvgHelper.IMAGE_BASE64_SIZE_DANGER_THRESHOLD
+import deckers.thibault.aves.metadata.SvgHelper.normalizeSize
+import deckers.thibault.aves.utils.StorageUtils
+import kotlin.math.ceil
+
+@GlideModule
+class SvgGlideModule : LibraryGlideModule() {
+ override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
+ registry.append(SvgImage::class.java, Bitmap::class.java, SvgLoader.Factory())
+ }
+}
+
+class SvgImage(val context: Context, val uri: Uri)
+
+internal class SvgLoader : ModelLoader<SvgImage, Bitmap> {
+ override fun buildLoadData(model: SvgImage, width: Int, height: Int, options: Options): ModelLoader.LoadData<Bitmap> {
+ return ModelLoader.LoadData(ObjectKey(model.uri), SvgFetcher(model, width, height))
+ }
+
+ override fun handles(model: SvgImage): Boolean = true
+
+ internal class Factory : ModelLoaderFactory<SvgImage, Bitmap> {
+ override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<SvgImage, Bitmap> = SvgLoader()
+
+ override fun teardown() {}
+ }
+}
+
+internal class SvgFetcher(val model: SvgImage, val width: Int, val height: Int) : DataFetcher<Bitmap> {
+ override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in Bitmap>) {
+ val context = model.context
+ val uri = model.uri
+
+ val bitmap: Bitmap? = StorageUtils.openInputStream(context, uri)?.use { input ->
+ try {
+ SVG.getFromInputStream(SVGParserBufferedInputStream(input))?.let { svg ->
+ svg.normalizeSize()
+ val viewBox = svg.documentViewBox
+ val svgWidth = viewBox.width()
+ val svgHeight = viewBox.height()
+
+ val bitmapWidth: Int
+ val bitmapHeight: Int
+ if (width / height.toFloat() > svgWidth / svgHeight) {
+ bitmapWidth = ceil(svgWidth * height / svgHeight).toInt()
+ bitmapHeight = height
+ } else {
+ bitmapWidth = width
+ bitmapHeight = ceil(svgHeight * width / svgWidth).toInt()
+ }
+ val bitmap = createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888)
+
+ val canvas = Canvas(bitmap)
+ SVGAndroidRenderer.setImageBase64StringMaxSize(IMAGE_BASE64_SIZE_DANGER_THRESHOLD)
+ svg.renderToCanvas(canvas)
+ bitmap
+ }
+ } catch (ex: SVGParseException) {
+ callback.onLoadFailed(ex)
+ return
+ }
+ }
+
+ if (bitmap == null) {
+ callback.onLoadFailed(Exception("failed to load SVG for uri=$uri"))
+ } else {
+ callback.onDataReady(bitmap)
+ }
+ }
+
+ override fun cleanup() {}
+
+ // cannot cancel
+ override fun cancel() {}
+
+ override fun getDataClass(): Class<Bitmap> = Bitmap::class.java
+
+ override fun getDataSource(): DataSource = DataSource.LOCAL
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/glide/TiffGlideModule.kt b/android/app/src/main/kotlin/deckers/thibault/aves/glide/TiffGlideModule.kt
new file mode 100644
index 0000000..f0cd864
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/glide/TiffGlideModule.kt
@@ -0,0 +1,127 @@
+package deckers.thibault.aves.glide
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.net.Uri
+import androidx.core.graphics.scale
+import com.bumptech.glide.Glide
+import com.bumptech.glide.Priority
+import com.bumptech.glide.Registry
+import com.bumptech.glide.annotation.GlideModule
+import com.bumptech.glide.load.DataSource
+import com.bumptech.glide.load.Options
+import com.bumptech.glide.load.data.DataFetcher
+import com.bumptech.glide.load.data.DataFetcher.DataCallback
+import com.bumptech.glide.load.model.ModelLoader
+import com.bumptech.glide.load.model.ModelLoaderFactory
+import com.bumptech.glide.load.model.MultiModelLoaderFactory
+import com.bumptech.glide.module.LibraryGlideModule
+import com.bumptech.glide.signature.ObjectKey
+import org.beyka.tiffbitmapfactory.TiffBitmapFactory
+
+@GlideModule
+class TiffGlideModule : LibraryGlideModule() {
+ override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
+ registry.append(TiffImage::class.java, Bitmap::class.java, TiffLoader.Factory())
+ }
+}
+
+class TiffImage(val context: Context, val uri: Uri, val page: Int?)
+
+internal class TiffLoader : ModelLoader<TiffImage, Bitmap> {
+ override fun buildLoadData(model: TiffImage, width: Int, height: Int, options: Options): ModelLoader.LoadData<Bitmap> {
+ return ModelLoader.LoadData(ObjectKey(model.uri), TiffFetcher(model, width, height))
+ }
+
+ override fun handles(model: TiffImage): Boolean = true
+
+ internal class Factory : ModelLoaderFactory<TiffImage, Bitmap> {
+ override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<TiffImage, Bitmap> = TiffLoader()
+
+ override fun teardown() {}
+ }
+}
+
+internal class TiffFetcher(val model: TiffImage, val width: Int, val height: Int) : DataFetcher<Bitmap> {
+ override fun loadData(priority: Priority, callback: DataCallback<in Bitmap>) {
+ val context = model.context
+ val uri = model.uri
+ val page = model.page ?: 0
+
+ var sampleSize = 1
+ val customSize = width > 0 && height > 0
+ if (customSize) {
+ // determine sample size
+ val fd = context.contentResolver.openFileDescriptor(uri, "r")?.detachFd()
+ if (fd == null) {
+ callback.onLoadFailed(Exception("null file descriptor"))
+ return
+ }
+ val options = buildOptions().apply {
+ inJustDecodeBounds = true
+ inDirectoryNumber = page
+ }
+ TiffBitmapFactory.decodeFileDescriptor(fd, options)
+ val imageWidth = options.outWidth
+ val imageHeight = options.outHeight
+ if (imageWidth > width || imageHeight > height) {
+ while (imageHeight / (sampleSize * 2) >= height && imageWidth / (sampleSize * 2) >= width) {
+ sampleSize *= 2
+ }
+ }
+ }
+
+ // decode
+ val fd = context.contentResolver.openFileDescriptor(uri, "r")?.detachFd()
+ if (fd == null) {
+ callback.onLoadFailed(Exception("null file descriptor"))
+ return
+ }
+ val options = buildOptions().apply {
+ inDirectoryNumber = page
+ inSampleSize = sampleSize
+ }
+ try {
+ val bitmap: Bitmap? = TiffBitmapFactory.decodeFileDescriptor(fd, options)
+ // calling `TiffBitmapFactory.closeFd(fd)` after decoding yields a segmentation fault
+
+ if (bitmap == null) {
+ callback.onLoadFailed(Exception("Decoding full TIFF yielded null bitmap"))
+ } else if (customSize) {
+ val dstWidth: Int
+ val dstHeight: Int
+ val aspectRatio = bitmap.width.toFloat() / bitmap.height
+ if (aspectRatio > 1) {
+ dstWidth = (height * aspectRatio).toInt()
+ dstHeight = height
+ } else {
+ dstWidth = width
+ dstHeight = (width / aspectRatio).toInt()
+ }
+ callback.onDataReady(bitmap.scale(dstWidth, dstHeight))
+ } else {
+ callback.onDataReady(bitmap)
+ }
+ } catch (e: Exception) {
+ callback.onLoadFailed(e)
+ }
+ }
+
+ override fun cleanup() {}
+
+ // cannot cancel
+ override fun cancel() {}
+
+ override fun getDataClass(): Class<Bitmap> = Bitmap::class.java
+
+ override fun getDataSource(): DataSource = DataSource.LOCAL
+
+ companion object {
+ fun buildOptions(): TiffBitmapFactory.Options {
+ return TiffBitmapFactory.Options().apply {
+ inThrowException = true
+ inUseOrientationTag = false
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/glide/VideoThumbnailGlideModule.kt b/android/app/src/main/kotlin/deckers/thibault/aves/glide/VideoThumbnailGlideModule.kt
new file mode 100644
index 0000000..f3eef5f
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/glide/VideoThumbnailGlideModule.kt
@@ -0,0 +1,192 @@
+package deckers.thibault.aves.glide
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.media.MediaMetadataRetriever
+import android.net.Uri
+import android.os.Build
+import androidx.annotation.RequiresApi
+import com.bumptech.glide.Glide
+import com.bumptech.glide.Priority
+import com.bumptech.glide.Registry
+import com.bumptech.glide.annotation.GlideModule
+import com.bumptech.glide.load.DataSource
+import com.bumptech.glide.load.Options
+import com.bumptech.glide.load.data.DataFetcher
+import com.bumptech.glide.load.data.DataFetcher.DataCallback
+import com.bumptech.glide.load.model.ModelLoader
+import com.bumptech.glide.load.model.ModelLoaderFactory
+import com.bumptech.glide.load.model.MultiModelLoaderFactory
+import com.bumptech.glide.module.LibraryGlideModule
+import com.bumptech.glide.signature.ObjectKey
+import deckers.thibault.aves.utils.BitmapUtils
+import deckers.thibault.aves.utils.MemoryUtils
+import deckers.thibault.aves.utils.StorageUtils.openMetadataRetriever
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import java.io.ByteArrayInputStream
+import java.io.IOException
+import kotlin.math.min
+import kotlin.math.roundToInt
+
+@GlideModule
+class VideoThumbnailGlideModule : LibraryGlideModule() {
+ override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
+ registry.append(VideoThumbnail::class.java, Bitmap::class.java, VideoThumbnailLoader.Factory())
+ }
+}
+
+class VideoThumbnail(val context: Context, val uri: Uri)
+
+internal class VideoThumbnailLoader : ModelLoader<VideoThumbnail, Bitmap> {
+ override fun buildLoadData(model: VideoThumbnail, width: Int, height: Int, options: Options): ModelLoader.LoadData<Bitmap> {
+ return ModelLoader.LoadData(ObjectKey(model.uri), VideoThumbnailFetcher(model, width, height))
+ }
+
+ override fun handles(model: VideoThumbnail): Boolean = true
+
+ internal class Factory : ModelLoaderFactory<VideoThumbnail, Bitmap> {
+ override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<VideoThumbnail, Bitmap> = VideoThumbnailLoader()
+
+ override fun teardown() {}
+ }
+}
+
+internal class VideoThumbnailFetcher(private val model: VideoThumbnail, val width: Int, val height: Int) : DataFetcher<Bitmap> {
+ private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+
+ override fun loadData(priority: Priority, callback: DataCallback<in Bitmap>) {
+ ioScope.launch {
+ val retriever = openMetadataRetriever(model.context, model.uri)
+ if (retriever == null) {
+ callback.onLoadFailed(Exception("failed to initialize MediaMetadataRetriever for uri=${model.uri}"))
+ } else {
+ try {
+ var bitmap: Bitmap? = null
+
+ retriever.embeddedPicture?.let { bytes ->
+ try {
+ bitmap = BitmapFactory.decodeStream(ByteArrayInputStream(bytes))
+ } catch (_: IOException) {
+ // ignore
+ }
+ }
+
+ if (bitmap == null) {
+ // there is no consistent strategy across devices to match
+ // the thumbnails returned by the content resolver / Media Store
+ // so we derive one in an arbitrary way
+ var timeMillis: Long? = null
+ val durationMillis = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull()
+ if (durationMillis != null) {
+ timeMillis = if (durationMillis < 15000) 0 else min(durationMillis / 2, 15000)
+ }
+ val timeMicros = if (timeMillis != null) timeMillis * 1000 else -1
+ val option = MediaMetadataRetriever.OPTION_CLOSEST_SYNC
+
+ var videoWidth = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toFloatOrNull()
+ var videoHeight = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toFloatOrNull()
+ if (videoWidth == null || videoHeight == null) {
+ throw Exception("failed to get video dimensions")
+ }
+
+ val rotationDegrees = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)?.toIntOrNull() ?: 0
+ val isRotated = rotationDegrees % 180 == 90
+ if (isRotated) {
+ videoWidth = videoHeight.also { videoHeight = videoWidth }
+ }
+
+ var dstWidth = 0
+ var dstHeight = 0
+ if (width > 0 && height > 0) {
+ // cover fit
+ val targetAspectRatio = width / height.toFloat()
+ val videoAspectRatio = videoWidth / videoHeight
+ if (targetAspectRatio > videoAspectRatio) {
+ dstHeight = (width / videoAspectRatio).roundToInt()
+ dstWidth = (dstHeight * videoAspectRatio).roundToInt()
+ } else {
+ dstWidth = (height * videoAspectRatio).roundToInt()
+ dstHeight = (dstWidth / videoAspectRatio).roundToInt()
+ }
+ }
+ if (dstWidth == 0 || dstWidth > videoWidth || dstHeight == 0 || dstHeight > videoHeight) {
+ dstWidth = videoWidth.toInt()
+ dstHeight = videoHeight.toInt()
+ }
+
+ // the returned frame is already rotated according to the video metadata
+ fun getFrameAtTime(timeMicros: Long): Bitmap? {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
+ val pixelCount = dstWidth * dstHeight
+ val targetBitmapSizeBytes = BitmapUtils.getExpectedImageSize(pixelCount.toLong(), getPreferredConfig())
+ if (!MemoryUtils.canAllocate(targetBitmapSizeBytes)) {
+ throw Exception("not enough memory to allocate $targetBitmapSizeBytes bytes for the scaled frame at $dstWidth x $dstHeight")
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ retriever.getScaledFrameAtTime(timeMicros, option, dstWidth, dstHeight, getBitmapParams())
+ } else {
+ retriever.getScaledFrameAtTime(timeMicros, option, dstWidth, dstHeight)
+ }
+ } else {
+ val pixelCount = videoWidth * videoHeight
+ val targetBitmapSizeBytes = BitmapUtils.getExpectedImageSize(pixelCount.toLong(), getPreferredConfig())
+ if (!MemoryUtils.canAllocate(targetBitmapSizeBytes)) {
+ throw Exception("not enough memory to allocate $targetBitmapSizeBytes bytes for the full frame at $videoWidth x $videoHeight")
+ }
+ retriever.getFrameAtTime(timeMicros, option)
+ }
+ }
+
+ bitmap = getFrameAtTime(timeMicros)
+ if (bitmap == null && timeMicros > 0) {
+ // retry to get the first frame instead of an arbitrary one
+ bitmap = getFrameAtTime(0)
+ }
+ }
+
+ if (bitmap == null) {
+ callback.onLoadFailed(Exception("failed to get embedded picture or any frame for uri=${model.uri}"))
+ } else {
+ callback.onDataReady(bitmap)
+ }
+ } catch (e: Exception) {
+ callback.onLoadFailed(e)
+ } finally {
+ // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs
+ retriever.release()
+ }
+ }
+ }
+ }
+
+ @RequiresApi(Build.VERSION_CODES.P)
+ private fun getBitmapParams(): MediaMetadataRetriever.BitmapParams {
+ val params = MediaMetadataRetriever.BitmapParams()
+ params.preferredConfig = this.getPreferredConfig()
+ return params
+ }
+
+ private fun getPreferredConfig(): Bitmap.Config {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ // improved precision with the same memory cost as `ARGB_8888` (4 bytes per pixel)
+ // for wide-gamut and HDR content which does not require alpha blending
+ Bitmap.Config.RGBA_1010102
+ } else {
+ Bitmap.Config.ARGB_8888
+ }
+ }
+
+ // already cleaned up in loadData and ByteArrayInputStream will be GC'd
+ override fun cleanup() {}
+
+ // cannot cancel
+ override fun cancel() {}
+
+ override fun getDataClass(): Class<Bitmap> = Bitmap::class.java
+
+ override fun getDataSource(): DataSource = DataSource.LOCAL
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/DngTags.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/DngTags.kt
new file mode 100644
index 0000000..3137919
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/DngTags.kt
@@ -0,0 +1,229 @@
+package deckers.thibault.aves.metadata
+
+// DNG v1.6.0.0
+// cf https://helpx.adobe.com/content/dam/help/en/photoshop/pdf/dng_spec_1_6_0_0.pdf
+object DngTags {
+ private const val DNG_VERSION = 0xC612
+ private const val DNG_BACKWARD_VERSION = 0xC613
+ private const val UNIQUE_CAMERA_MODEL = 0xC614
+ private const val LOCALIZED_CAMERA_MODEL = 0xC615
+ private const val CFA_PLANE_COLOR = 0xC616
+ private const val CFA_LAYOUT = 0xC617
+ private const val LINEARIZATION_TABLE = 0xC618
+ private const val BLACK_LEVEL_REPEAT_DIM = 0xC619
+ private const val BLACK_LEVEL = 0xC61A
+ private const val BLACK_LEVEL_DELTA_H = 0xC61B
+ private const val BLACK_LEVEL_DELTA_V = 0xC61C
+ private const val WHITE_LEVEL = 0xC61D
+ private const val DEFAULT_SCALE = 0xC61E
+ private const val DEFAULT_CROP_ORIGIN = 0xC61F
+ private const val DEFAULT_CROP_SIZE = 0xC620
+ private const val COLOR_MATRIX_1 = 0xC621
+ private const val COLOR_MATRIX_2 = 0xC622
+ private const val CAMERA_CALIBRATION_1 = 0xC623
+ private const val CAMERA_CALIBRATION_2 = 0xC624
+ private const val REDUCTION_MATRIX_1 = 0xC625
+ private const val REDUCTION_MATRIX_2 = 0xC626
+ private const val ANALOG_BALANCE = 0xC627
+ private const val AS_SHOT_NEUTRAL = 0xC628
+ private const val AS_SHOT_WHITE_XY = 0xC629
+ private const val BASELINE_EXPOSURE = 0xC62A
+ private const val BASELINE_NOISE = 0xC62B
+ private const val BASELINE_SHARPNESS = 0xC62C
+ private const val BAYER_GREEN_SPLIT = 0xC62D
+ private const val LINEAR_RESPONSE_LIMIT = 0xC62E
+ private const val CAMERA_SERIAL_NUMBER = 0xC62F
+ private const val LENS_INFO = 0xC630
+ private const val CHROMA_BLUR_RADIUS = 0xC631
+ private const val ANTI_ALIAS_STRENGTH = 0xC632
+ private const val SHADOW_SCALE = 0xC633
+ private const val DNG_PRIVATE_DATA = 0xC634
+ private const val MAKER_NOTE_SAFETY = 0xC635
+ private const val CALIBRATION_ILLUMINANT_1 = 0xC65A
+ private const val CALIBRATION_ILLUMINANT_2 = 0xC65B
+ private const val BEST_QUALITY_SCALE = 0xC65C
+ private const val RAW_DATA_UNIQUE_ID = 0xC65D
+ private const val ORIGINAL_RAW_FILE_NAME = 0xC68B
+ private const val ORIGINAL_RAW_FILE_DATA = 0xC68C
+ private const val ACTIVE_AREA = 0xC68D
+ private const val MASKED_AREAS = 0xC68E
+ private const val AS_SHOT_ICC_PROFILE = 0xC68F
+ private const val AS_SHOT_PRE_PROFILE_MATRIX = 0xC690
+ private const val CURRENT_ICC_PROFILE = 0xC691
+ private const val CURRENT_PRE_PROFILE_MATRIX = 0xC692
+ private const val COLORIMETRIC_REFERENCE = 0xC6BF
+ private const val CAMERA_CALIBRATION_SIGNATURE = 0xC6F3
+ private const val PROFILE_CALIBRATION_SIGNATURE = 0xC6F4
+ private const val EXTRA_CAMERA_PROFILES = 0xC6F5
+ private const val AS_SHOT_PROFILE_NAME = 0xC6F6
+ private const val NOISE_REDUCTION_APPLIED = 0xC6F7
+ private const val PROFILE_NAME = 0xC6F8
+ private const val PROFILE_HUE_SAT_MAP_DIMS = 0xC6F9
+ private const val PROFILE_HUE_SAT_MAP_DATA_1 = 0xC6FA
+ private const val PROFILE_HUE_SAT_MAP_DATA_2 = 0xC6FB
+ private const val PROFILE_TONE_CURVE = 0xC6FC
+ private const val PROFILE_EMBED_POLICY = 0xC6FD
+ private const val PROFILE_COPYRIGHT = 0xC6FE
+ private const val FORWARD_MATRIX_1 = 0xC714
+ private const val FORWARD_MATRIX_2 = 0xC715
+ private const val PREVIEW_APPLICATION_NAME = 0xC716
+ private const val PREVIEW_APPLICATION_VERSION = 0xC717
+ private const val PREVIEW_SETTINGS_NAME = 0xC718
+ private const val PREVIEW_SETTINGS_DIGEST = 0xC719
+ private const val PREVIEW_COLOR_SPACE = 0xC71A
+ private const val PREVIEW_DATE_TIME = 0xC71B
+ private const val RAW_IMAGE_DIGEST = 0xC71C
+ private const val ORIGINAL_RAW_FILE_DIGEST = 0xC71D
+ private const val SUB_TILE_BLOCK_SIZE = 0xC71E
+ private const val ROW_INTERLEAVE_FACTOR = 0xC71F
+ private const val PROFILE_LOOK_TABLE_DIMS = 0xC725
+ private const val PROFILE_LOOK_TABLE_DATA = 0xC726
+ private const val OPCODE_LIST_1 = 0xC740
+ private const val OPCODE_LIST_2 = 0xC741
+ private const val OPCODE_LIST_3 = 0xC74E
+ private const val NOISE_PROFILE = 0xC761
+ private const val ORIGINAL_DEFAULT_FINAL_SIZE = 0xC791
+ private const val ORIGINAL_BEST_QUALITY_FINAL_SIZE = 0xC792
+ private const val ORIGINAL_DEFAULT_CROP_SIZE = 0xC793
+ private const val PROFILE_HUE_SAT_MAP_ENCODING = 0xC7A3
+ private const val PROFILE_LOOK_TABLE_ENCODING = 0xC7A4
+ private const val BASELINE_EXPOSURE_OFFSET = 0xC7A5
+ private const val DEFAULT_BLACK_RENDER = 0xC7A6
+ private const val NEW_RAW_IMAGE_DIGEST = 0xC7A7
+ private const val RAW_TO_PREVIEW_GAIN = 0xC7A8
+ private const val DEFAULT_USER_CROP = 0xC7B5
+ private const val DEPTH_FORMAT = 0xC7E9
+ private const val DEPTH_NEAR = 0xC7EA
+ private const val DEPTH_FAR = 0xC7EB
+ private const val DEPTH_UNITS = 0xC7EC
+ private const val DEPTH_MEASURE_TYPE = 0xC7ED
+ private const val ENHANCE_PARAMS = 0xC7EE
+ private const val PROFILE_GAIN_TABLE_MAP = 0xCD2D
+ private const val SEMANTIC_NAME = 0xCD2E
+ private const val SEMANTIC_INSTANCE_ID = 0xCD30
+ private const val CALIBRATION_ILLUMINANT_3 = 0xCD31
+ private const val CAMERA_CALIBRATION_3 = 0xCD32
+ private const val COLOR_MATRIX_3 = 0xCD33
+ private const val FORWARD_MATRIX_3 = 0xCD34
+ private const val ILLUMINANT_DATA_1 = 0xCD35
+ private const val ILLUMINANT_DATA_2 = 0xCD36
+ private const val ILLUMINANT_DATA_3 = 0xCD37
+ private const val MASK_SUB_AREA = 0xCD38
+ private const val PROFILE_HUE_SAT_MAP_DATA_3 = 0xCD39
+ private const val REDUCTION_MATRIX_3 = 0xCD3A
+ private const val RGB_TABLES = 0xCD3F
+
+ val tagNameMap = hashMapOf(
+ DNG_VERSION to "DNG Version",
+ DNG_BACKWARD_VERSION to "DNG Backward Version",
+ UNIQUE_CAMERA_MODEL to "Unique Camera Model",
+ LOCALIZED_CAMERA_MODEL to "Localized Camera Model",
+ CFA_PLANE_COLOR to "CFA Plane Color",
+ CFA_LAYOUT to "CFA Layout",
+ LINEARIZATION_TABLE to "Linearization Table",
+ BLACK_LEVEL_REPEAT_DIM to "Black Level Repeat Dim",
+ BLACK_LEVEL to "Black Level",
+ BLACK_LEVEL_DELTA_H to "Black Level Delta H",
+ BLACK_LEVEL_DELTA_V to "Black Level Delta V",
+ WHITE_LEVEL to "White Level",
+ DEFAULT_SCALE to "Default Scale",
+ DEFAULT_CROP_ORIGIN to "Default Crop Origin",
+ DEFAULT_CROP_SIZE to "Default Crop Size",
+ COLOR_MATRIX_1 to "Color Matrix 1",
+ COLOR_MATRIX_2 to "Color Matrix 2",
+ CAMERA_CALIBRATION_1 to "Camera Calibration 1",
+ CAMERA_CALIBRATION_2 to "Camera Calibration 2",
+ REDUCTION_MATRIX_1 to "Reduction Matrix 1",
+ REDUCTION_MATRIX_2 to "Reduction Matrix 2",
+ ANALOG_BALANCE to "Analog Balance",
+ AS_SHOT_NEUTRAL to "As Shot Neutral",
+ AS_SHOT_WHITE_XY to "As Shot White XY",
+ BASELINE_EXPOSURE to "Baseline Exposure",
+ BASELINE_NOISE to "Baseline Noise",
+ BASELINE_SHARPNESS to "Baseline Sharpness",
+ BAYER_GREEN_SPLIT to "Bayer Green Split",
+ LINEAR_RESPONSE_LIMIT to "Linear Response Limit",
+ CAMERA_SERIAL_NUMBER to "Camera Serial Number",
+ LENS_INFO to "Lens Info",
+ CHROMA_BLUR_RADIUS to "Chroma Blur Radius",
+ ANTI_ALIAS_STRENGTH to "Anti Alias Strength",
+ SHADOW_SCALE to "Shadow Scale",
+ DNG_PRIVATE_DATA to "DNG Private Data",
+ MAKER_NOTE_SAFETY to "Maker Note Safety",
+ CALIBRATION_ILLUMINANT_1 to "Calibration Illuminant 1",
+ CALIBRATION_ILLUMINANT_2 to "Calibration Illuminant 2",
+ BEST_QUALITY_SCALE to "Best Quality Scale",
+ RAW_DATA_UNIQUE_ID to "Raw Data Unique ID",
+ ORIGINAL_RAW_FILE_NAME to "Original Raw File Name",
+ ORIGINAL_RAW_FILE_DATA to "Original Raw File Data",
+ ACTIVE_AREA to "Active Area",
+ MASKED_AREAS to "Masked Areas",
+ AS_SHOT_ICC_PROFILE to "As Shot ICC Profile",
+ AS_SHOT_PRE_PROFILE_MATRIX to "As Shot Pre Profile Matrix",
+ CURRENT_ICC_PROFILE to "Current ICC Profile",
+ CURRENT_PRE_PROFILE_MATRIX to "Current Pre Profile Matrix",
+ COLORIMETRIC_REFERENCE to "Colorimetric Reference",
+ CAMERA_CALIBRATION_SIGNATURE to "Camera Calibration Signature",
+ PROFILE_CALIBRATION_SIGNATURE to "Profile Calibration Signature",
+ EXTRA_CAMERA_PROFILES to "Extra Camera Profiles",
+ AS_SHOT_PROFILE_NAME to "As Shot Profile Name",
+ NOISE_REDUCTION_APPLIED to "Noise Reduction Applied",
+ PROFILE_NAME to "Profile Name",
+ PROFILE_HUE_SAT_MAP_DIMS to "Profile Hue Sat Map Dims",
+ PROFILE_HUE_SAT_MAP_DATA_1 to "Profile Hue Sat Map Data 1",
+ PROFILE_HUE_SAT_MAP_DATA_2 to "Profile Hue Sat Map Data 2",
+ PROFILE_TONE_CURVE to "Profile Tone Curve",
+ PROFILE_EMBED_POLICY to "Profile Embed Policy",
+ PROFILE_COPYRIGHT to "Profile Copyright",
+ FORWARD_MATRIX_1 to "Forward Matrix 1",
+ FORWARD_MATRIX_2 to "Forward Matrix 2",
+ PREVIEW_APPLICATION_NAME to "Preview Application Name",
+ PREVIEW_APPLICATION_VERSION to "Preview Application Version",
+ PREVIEW_SETTINGS_NAME to "Preview Settings Name",
+ PREVIEW_SETTINGS_DIGEST to "Preview Settings Digest",
+ PREVIEW_COLOR_SPACE to "Preview Color Space",
+ PREVIEW_DATE_TIME to "Preview Date Time",
+ RAW_IMAGE_DIGEST to "Raw Image Digest",
+ ORIGINAL_RAW_FILE_DIGEST to "Original Raw File Digest",
+ SUB_TILE_BLOCK_SIZE to "Sub Tile Block Size",
+ ROW_INTERLEAVE_FACTOR to "Row Interleave Factor",
+ PROFILE_LOOK_TABLE_DIMS to "Profile Look Table Dims",
+ PROFILE_LOOK_TABLE_DATA to "Profile Look Table Data",
+ OPCODE_LIST_1 to "Opcode List 1",
+ OPCODE_LIST_2 to "Opcode List 2",
+ OPCODE_LIST_3 to "Opcode List 3",
+ NOISE_PROFILE to "Noise Profile",
+ ORIGINAL_DEFAULT_FINAL_SIZE to "Original Default Final Size",
+ ORIGINAL_BEST_QUALITY_FINAL_SIZE to "Original Best Quality Final Size",
+ ORIGINAL_DEFAULT_CROP_SIZE to "Original Default Crop Size",
+ PROFILE_HUE_SAT_MAP_ENCODING to "Profile Hue Sat Map Encoding",
+ PROFILE_LOOK_TABLE_ENCODING to "Profile Look Table Encoding",
+ BASELINE_EXPOSURE_OFFSET to "Baseline Exposure Offset",
+ DEFAULT_BLACK_RENDER to "Default Black Render",
+ NEW_RAW_IMAGE_DIGEST to "New Raw Image Digest",
+ RAW_TO_PREVIEW_GAIN to "Raw To Preview Gain",
+ DEFAULT_USER_CROP to "Default User Crop",
+ DEPTH_FORMAT to "Depth Format",
+ DEPTH_NEAR to "Depth Near",
+ DEPTH_FAR to "Depth Far",
+ DEPTH_UNITS to "Depth Units",
+ DEPTH_MEASURE_TYPE to "Depth Measure Type",
+ ENHANCE_PARAMS to "Enhance Params",
+ PROFILE_GAIN_TABLE_MAP to "Profile Gain Table Map",
+ SEMANTIC_NAME to "Semantic Name",
+ SEMANTIC_INSTANCE_ID to "Semantic Instance ID",
+ CALIBRATION_ILLUMINANT_3 to "Calibration Illuminant 3",
+ CAMERA_CALIBRATION_3 to "Camera Calibration 3",
+ COLOR_MATRIX_3 to "Color Matrix 3",
+ FORWARD_MATRIX_3 to "Forward Matrix 3",
+ ILLUMINANT_DATA_1 to "Illuminant Data 1",
+ ILLUMINANT_DATA_2 to "Illuminant Data 2",
+ ILLUMINANT_DATA_3 to "Illuminant Data 3",
+ MASK_SUB_AREA to "Mask Sub Area",
+ PROFILE_HUE_SAT_MAP_DATA_3 to "Profile Hue Sat Map Data 3",
+ REDUCTION_MATRIX_3 to "Reduction Matrix 3",
+ RGB_TABLES to "RGB Tables",
+ )
+
+ val tags = tagNameMap.keys
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifInterfaceHelper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifInterfaceHelper.kt
new file mode 100644
index 0000000..2f9b652
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifInterfaceHelper.kt
@@ -0,0 +1,420 @@
+package deckers.thibault.aves.metadata
+
+import android.util.Log
+import com.drew.lang.Rational
+import com.drew.metadata.Directory
+import com.drew.metadata.exif.ExifDirectoryBase
+import com.drew.metadata.exif.ExifIFD0Directory
+import com.drew.metadata.exif.ExifThumbnailDirectory
+import com.drew.metadata.exif.GpsDirectory
+import com.drew.metadata.exif.PanasonicRawIFD0Directory
+import com.drew.metadata.exif.makernotes.OlympusCameraSettingsMakernoteDirectory
+import com.drew.metadata.exif.makernotes.OlympusImageProcessingMakernoteDirectory
+import com.drew.metadata.exif.makernotes.OlympusMakernoteDirectory
+import deckers.thibault.aves.utils.LogUtils
+import java.text.ParseException
+import java.text.SimpleDateFormat
+import java.util.Locale
+import kotlin.math.abs
+import kotlin.math.floor
+import kotlin.math.roundToLong
+import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface
+
+object ExifInterfaceHelper {
+ private val LOG_TAG = LogUtils.createTag<ExifInterfaceHelper>()
+ val DATETIME_FORMAT = SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.ROOT)
+ val GPS_DATE_FORMAT = SimpleDateFormat("yyyy:MM:dd", Locale.ROOT)
+ val GPS_TIME_FORMAT = SimpleDateFormat("HH:mm:ss", Locale.ROOT)
+
+ private const val PRECISION_ERROR_TOLERANCE = 1e-10
+
+ // ExifInterface always states it has the following attributes
+ // and returns "0" instead of "null" when they are actually missing
+ private val neverNullTags = listOf(
+ ExifInterface.TAG_IMAGE_LENGTH,
+ ExifInterface.TAG_IMAGE_WIDTH,
+ ExifInterface.TAG_LIGHT_SOURCE,
+ ExifInterface.TAG_ORIENTATION,
+ )
+
+ private fun isNeverNull(tag: String): Boolean = neverNullTags.contains(tag)
+
+ private val baseTags: Map<String, TagMapper?> = mapOf(
+ ExifInterface.TAG_APERTURE_VALUE to TagMapper(ExifDirectoryBase.TAG_APERTURE, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_ARTIST to TagMapper(ExifDirectoryBase.TAG_ARTIST, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_BITS_PER_SAMPLE to TagMapper(ExifDirectoryBase.TAG_BITS_PER_SAMPLE, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_BODY_SERIAL_NUMBER to TagMapper(ExifDirectoryBase.TAG_BODY_SERIAL_NUMBER, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_BRIGHTNESS_VALUE to TagMapper(ExifDirectoryBase.TAG_BRIGHTNESS_VALUE, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_CAMERA_OWNER_NAME to TagMapper(ExifDirectoryBase.TAG_CAMERA_OWNER_NAME, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_CFA_PATTERN to TagMapper(ExifDirectoryBase.TAG_CFA_PATTERN, DirType.EXIF_IFD0, TagFormat.BYTE), // spec format: UNDEFINED, e.g. [Red,Green][Green,Blue]
+ ExifInterface.TAG_COLOR_SPACE to TagMapper(ExifDirectoryBase.TAG_COLOR_SPACE, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_COMPONENTS_CONFIGURATION to TagMapper(ExifDirectoryBase.TAG_COMPONENTS_CONFIGURATION, DirType.EXIF_IFD0, TagFormat.BYTE), // spec format: UNDEFINED, e.g. [Y,Cb,Cr]
+ ExifInterface.TAG_COMPRESSED_BITS_PER_PIXEL to TagMapper(ExifDirectoryBase.TAG_COMPRESSED_AVERAGE_BITS_PER_PIXEL, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_COMPRESSION to TagMapper(ExifDirectoryBase.TAG_COMPRESSION, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_CONTRAST to TagMapper(ExifDirectoryBase.TAG_CONTRAST, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_COPYRIGHT to TagMapper(ExifDirectoryBase.TAG_COPYRIGHT, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_CUSTOM_RENDERED to TagMapper(ExifDirectoryBase.TAG_CUSTOM_RENDERED, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_DATETIME to TagMapper(ExifDirectoryBase.TAG_DATETIME, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_DATETIME_DIGITIZED to TagMapper(ExifDirectoryBase.TAG_DATETIME_DIGITIZED, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_DATETIME_ORIGINAL to TagMapper(ExifDirectoryBase.TAG_DATETIME_ORIGINAL, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION to TagMapper(ExifDirectoryBase.TAG_DEVICE_SETTING_DESCRIPTION, DirType.EXIF_IFD0, TagFormat.UNDEFINED),
+ ExifInterface.TAG_DIGITAL_ZOOM_RATIO to TagMapper(ExifDirectoryBase.TAG_DIGITAL_ZOOM_RATIO, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_EXIF_VERSION to TagMapper(ExifDirectoryBase.TAG_EXIF_VERSION, DirType.EXIF_IFD0, TagFormat.UNDEFINED),
+ ExifInterface.TAG_EXPOSURE_BIAS_VALUE to TagMapper(ExifDirectoryBase.TAG_EXPOSURE_BIAS, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_EXPOSURE_INDEX to TagMapper(ExifDirectoryBase.TAG_EXPOSURE_INDEX, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_EXPOSURE_MODE to TagMapper(ExifDirectoryBase.TAG_EXPOSURE_MODE, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_EXPOSURE_PROGRAM to TagMapper(ExifDirectoryBase.TAG_EXPOSURE_PROGRAM, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_EXPOSURE_TIME to TagMapper(ExifDirectoryBase.TAG_EXPOSURE_TIME, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_FILE_SOURCE to TagMapper(ExifDirectoryBase.TAG_FILE_SOURCE, DirType.EXIF_IFD0, TagFormat.SHORT), // spec format: UNDEFINED
+ ExifInterface.TAG_FLASH to TagMapper(ExifDirectoryBase.TAG_FLASH, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_FLASHPIX_VERSION to TagMapper(ExifDirectoryBase.TAG_FLASHPIX_VERSION, DirType.EXIF_IFD0, TagFormat.UNDEFINED),
+ ExifInterface.TAG_FLASH_ENERGY to TagMapper(ExifDirectoryBase.TAG_FLASH_ENERGY, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_FOCAL_LENGTH to TagMapper(ExifDirectoryBase.TAG_FOCAL_LENGTH, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_FOCAL_LENGTH_IN_35MM_FILM to TagMapper(ExifDirectoryBase.TAG_35MM_FILM_EQUIV_FOCAL_LENGTH, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT to TagMapper(ExifDirectoryBase.TAG_FOCAL_PLANE_RESOLUTION_UNIT, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION to TagMapper(ExifDirectoryBase.TAG_FOCAL_PLANE_X_RESOLUTION, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION to TagMapper(ExifDirectoryBase.TAG_FOCAL_PLANE_Y_RESOLUTION, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_F_NUMBER to TagMapper(ExifDirectoryBase.TAG_FNUMBER, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_GAIN_CONTROL to TagMapper(ExifDirectoryBase.TAG_GAIN_CONTROL, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_GAMMA to TagMapper(ExifDirectoryBase.TAG_GAMMA, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_IMAGE_DESCRIPTION to TagMapper(ExifDirectoryBase.TAG_IMAGE_DESCRIPTION, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_IMAGE_LENGTH to TagMapper(ExifDirectoryBase.TAG_IMAGE_HEIGHT, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_IMAGE_UNIQUE_ID to TagMapper(ExifDirectoryBase.TAG_IMAGE_UNIQUE_ID, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_IMAGE_WIDTH to TagMapper(ExifDirectoryBase.TAG_IMAGE_WIDTH, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_INTEROPERABILITY_INDEX to TagMapper(ExifDirectoryBase.TAG_INTEROP_INDEX, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_ISO_SPEED to TagMapper(ExifDirectoryBase.TAG_ISO_SPEED, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_ISO_SPEED_LATITUDE_YYY to TagMapper(ExifDirectoryBase.TAG_ISO_SPEED_LATITUDE_YYY, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_ISO_SPEED_LATITUDE_ZZZ to TagMapper(ExifDirectoryBase.TAG_ISO_SPEED_LATITUDE_ZZZ, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_LENS_MAKE to TagMapper(ExifDirectoryBase.TAG_LENS_MAKE, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_LENS_MODEL to TagMapper(ExifDirectoryBase.TAG_LENS_MODEL, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_LENS_SERIAL_NUMBER to TagMapper(ExifDirectoryBase.TAG_LENS_SERIAL_NUMBER, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_LENS_SPECIFICATION to TagMapper(ExifDirectoryBase.TAG_LENS_SPECIFICATION, DirType.EXIF_IFD0, TagFormat.RATIONAL_ARRAY),
+ ExifInterface.TAG_LIGHT_SOURCE to TagMapper(ExifDirectoryBase.TAG_WHITE_BALANCE, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_MAKE to TagMapper(ExifDirectoryBase.TAG_MAKE, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_MAKER_NOTE to TagMapper(ExifDirectoryBase.TAG_MAKERNOTE, DirType.EXIF_IFD0, TagFormat.UNDEFINED),
+ ExifInterface.TAG_MAX_APERTURE_VALUE to TagMapper(ExifDirectoryBase.TAG_MAX_APERTURE, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_METERING_MODE to TagMapper(ExifDirectoryBase.TAG_METERING_MODE, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_MODEL to TagMapper(ExifDirectoryBase.TAG_MODEL, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_NEW_SUBFILE_TYPE to TagMapper(ExifDirectoryBase.TAG_NEW_SUBFILE_TYPE, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_OECF to TagMapper(ExifDirectoryBase.TAG_OPTO_ELECTRIC_CONVERSION_FUNCTION, DirType.EXIF_IFD0, TagFormat.UNDEFINED),
+ ExifInterface.TAG_OFFSET_TIME to TagMapper(ExifDirectoryBase.TAG_TIME_ZONE, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_OFFSET_TIME_DIGITIZED to TagMapper(ExifDirectoryBase.TAG_TIME_ZONE_DIGITIZED, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_OFFSET_TIME_ORIGINAL to TagMapper(ExifDirectoryBase.TAG_TIME_ZONE_ORIGINAL, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_ORIENTATION to TagMapper(ExifDirectoryBase.TAG_ORIENTATION, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_PHOTOGRAPHIC_SENSITIVITY to TagMapper(ExifDirectoryBase.TAG_ISO_EQUIVALENT, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_PHOTOMETRIC_INTERPRETATION to TagMapper(ExifDirectoryBase.TAG_PHOTOMETRIC_INTERPRETATION, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_PIXEL_X_DIMENSION to TagMapper(ExifDirectoryBase.TAG_EXIF_IMAGE_WIDTH, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_PIXEL_Y_DIMENSION to TagMapper(ExifDirectoryBase.TAG_EXIF_IMAGE_HEIGHT, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_PLANAR_CONFIGURATION to TagMapper(ExifDirectoryBase.TAG_PLANAR_CONFIGURATION, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_PRIMARY_CHROMATICITIES to TagMapper(ExifDirectoryBase.TAG_PRIMARY_CHROMATICITIES, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_RECOMMENDED_EXPOSURE_INDEX to TagMapper(ExifDirectoryBase.TAG_RECOMMENDED_EXPOSURE_INDEX, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_REFERENCE_BLACK_WHITE to TagMapper(ExifDirectoryBase.TAG_REFERENCE_BLACK_WHITE, DirType.EXIF_IFD0, TagFormat.RATIONAL_ARRAY),
+ ExifInterface.TAG_RELATED_SOUND_FILE to TagMapper(ExifDirectoryBase.TAG_RELATED_SOUND_FILE, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_RESOLUTION_UNIT to TagMapper(ExifDirectoryBase.TAG_RESOLUTION_UNIT, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_ROWS_PER_STRIP to TagMapper(ExifDirectoryBase.TAG_ROWS_PER_STRIP, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_SAMPLES_PER_PIXEL to TagMapper(ExifDirectoryBase.TAG_SAMPLES_PER_PIXEL, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_SATURATION to TagMapper(ExifDirectoryBase.TAG_SATURATION, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_SCENE_CAPTURE_TYPE to TagMapper(ExifDirectoryBase.TAG_SCENE_CAPTURE_TYPE, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_SCENE_TYPE to TagMapper(ExifDirectoryBase.TAG_SCENE_TYPE, DirType.EXIF_IFD0, TagFormat.SHORT), // spec format: UNDEFINED
+ ExifInterface.TAG_SENSING_METHOD to TagMapper(ExifDirectoryBase.TAG_SENSING_METHOD, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_SENSITIVITY_TYPE to TagMapper(ExifDirectoryBase.TAG_SENSITIVITY_TYPE, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_SHARPNESS to TagMapper(ExifDirectoryBase.TAG_SHARPNESS, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_SHUTTER_SPEED_VALUE to TagMapper(ExifDirectoryBase.TAG_SHUTTER_SPEED, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_SOFTWARE to TagMapper(ExifDirectoryBase.TAG_SOFTWARE, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_SPATIAL_FREQUENCY_RESPONSE to TagMapper(ExifDirectoryBase.TAG_SPATIAL_FREQ_RESPONSE, DirType.EXIF_IFD0, TagFormat.UNDEFINED),
+ ExifInterface.TAG_SPECTRAL_SENSITIVITY to TagMapper(ExifDirectoryBase.TAG_SPECTRAL_SENSITIVITY, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_STANDARD_OUTPUT_SENSITIVITY to TagMapper(ExifDirectoryBase.TAG_STANDARD_OUTPUT_SENSITIVITY, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_STRIP_BYTE_COUNTS to TagMapper(ExifDirectoryBase.TAG_STRIP_BYTE_COUNTS, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_STRIP_OFFSETS to TagMapper(ExifDirectoryBase.TAG_STRIP_OFFSETS, DirType.EXIF_IFD0, TagFormat.LONG),
+ ExifInterface.TAG_SUBFILE_TYPE to TagMapper(ExifDirectoryBase.TAG_SUBFILE_TYPE, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_SUBJECT_AREA to TagMapper(ExifDirectoryBase.TAG_SUBJECT_LOCATION_TIFF_EP, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_SUBJECT_DISTANCE to TagMapper(ExifDirectoryBase.TAG_SUBJECT_DISTANCE, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_SUBJECT_DISTANCE_RANGE to TagMapper(ExifDirectoryBase.TAG_SUBJECT_DISTANCE_RANGE, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_SUBJECT_LOCATION to TagMapper(ExifDirectoryBase.TAG_SUBJECT_LOCATION, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_SUBSEC_TIME to TagMapper(ExifDirectoryBase.TAG_SUBSECOND_TIME, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_SUBSEC_TIME_DIGITIZED to TagMapper(ExifDirectoryBase.TAG_SUBSECOND_TIME_DIGITIZED, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_SUBSEC_TIME_ORIGINAL to TagMapper(ExifDirectoryBase.TAG_SUBSECOND_TIME_ORIGINAL, DirType.EXIF_IFD0, TagFormat.ASCII),
+ ExifInterface.TAG_THUMBNAIL_IMAGE_LENGTH to TagMapper(ExifDirectoryBase.TAG_IMAGE_HEIGHT, DirType.EXIF_IFD0, TagFormat.LONG), // IFD_THUMBNAIL_TAGS 0x0101
+ ExifInterface.TAG_THUMBNAIL_IMAGE_WIDTH to TagMapper(ExifDirectoryBase.TAG_IMAGE_WIDTH, DirType.EXIF_IFD0, TagFormat.LONG), // IFD_THUMBNAIL_TAGS 0x0100
+ ExifInterface.TAG_TRANSFER_FUNCTION to TagMapper(ExifDirectoryBase.TAG_TRANSFER_FUNCTION, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_USER_COMMENT to TagMapper(ExifDirectoryBase.TAG_USER_COMMENT, DirType.EXIF_IFD0, TagFormat.COMMENT),
+ ExifInterface.TAG_WHITE_BALANCE to TagMapper(ExifDirectoryBase.TAG_WHITE_BALANCE, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_WHITE_POINT to TagMapper(ExifDirectoryBase.TAG_WHITE_POINT, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_X_RESOLUTION to TagMapper(ExifDirectoryBase.TAG_X_RESOLUTION, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_Y_CB_CR_COEFFICIENTS to TagMapper(ExifDirectoryBase.TAG_YCBCR_COEFFICIENTS, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ ExifInterface.TAG_Y_CB_CR_POSITIONING to TagMapper(ExifDirectoryBase.TAG_YCBCR_POSITIONING, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_Y_CB_CR_SUB_SAMPLING to TagMapper(ExifDirectoryBase.TAG_YCBCR_SUBSAMPLING, DirType.EXIF_IFD0, TagFormat.SHORT),
+ ExifInterface.TAG_Y_RESOLUTION to TagMapper(ExifDirectoryBase.TAG_Y_RESOLUTION, DirType.EXIF_IFD0, TagFormat.RATIONAL),
+ )
+
+ private val thumbnailTags: Map<String, TagMapper?> = mapOf(
+ ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT to TagMapper(ExifThumbnailDirectory.TAG_THUMBNAIL_OFFSET, DirType.EXIF_THUMBNAIL, TagFormat.LONG), // IFD_TIFF_TAGS or IFD_THUMBNAIL_TAGS 0x0201
+ ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH to TagMapper(ExifThumbnailDirectory.TAG_THUMBNAIL_LENGTH, DirType.EXIF_THUMBNAIL, TagFormat.LONG), // IFD_TIFF_TAGS or IFD_THUMBNAIL_TAGS 0x0202
+ )
+
+ private val gpsTags: Map<String, TagMapper?> = mapOf(
+ ExifInterface.TAG_GPS_ALTITUDE to TagMapper(GpsDirectory.TAG_ALTITUDE, DirType.GPS, TagFormat.RATIONAL),
+ ExifInterface.TAG_GPS_ALTITUDE_REF to TagMapper(GpsDirectory.TAG_ALTITUDE_REF, DirType.GPS, TagFormat.BYTE),
+ ExifInterface.TAG_GPS_AREA_INFORMATION to TagMapper(GpsDirectory.TAG_AREA_INFORMATION, DirType.GPS, TagFormat.COMMENT),
+ ExifInterface.TAG_GPS_DATESTAMP to TagMapper(GpsDirectory.TAG_DATE_STAMP, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_DEST_BEARING to TagMapper(GpsDirectory.TAG_DEST_BEARING, DirType.GPS, TagFormat.RATIONAL),
+ ExifInterface.TAG_GPS_DEST_BEARING_REF to TagMapper(GpsDirectory.TAG_DEST_BEARING_REF, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_DEST_DISTANCE to TagMapper(GpsDirectory.TAG_DEST_DISTANCE, DirType.GPS, TagFormat.RATIONAL),
+ ExifInterface.TAG_GPS_DEST_DISTANCE_REF to TagMapper(GpsDirectory.TAG_DEST_DISTANCE_REF, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_DEST_LATITUDE to TagMapper(GpsDirectory.TAG_DEST_LATITUDE, DirType.GPS, TagFormat.RATIONAL_ARRAY),
+ ExifInterface.TAG_GPS_DEST_LATITUDE_REF to TagMapper(GpsDirectory.TAG_DEST_LATITUDE_REF, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_DEST_LONGITUDE to TagMapper(GpsDirectory.TAG_DEST_LONGITUDE, DirType.GPS, TagFormat.RATIONAL_ARRAY),
+ ExifInterface.TAG_GPS_DEST_LONGITUDE_REF to TagMapper(GpsDirectory.TAG_DEST_LONGITUDE_REF, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_DIFFERENTIAL to TagMapper(GpsDirectory.TAG_DIFFERENTIAL, DirType.GPS, TagFormat.SHORT),
+ ExifInterface.TAG_GPS_DOP to TagMapper(GpsDirectory.TAG_DOP, DirType.GPS, TagFormat.RATIONAL),
+ ExifInterface.TAG_GPS_H_POSITIONING_ERROR to TagMapper(GpsDirectory.TAG_H_POSITIONING_ERROR, DirType.GPS, TagFormat.RATIONAL),
+ ExifInterface.TAG_GPS_IMG_DIRECTION to TagMapper(GpsDirectory.TAG_IMG_DIRECTION, DirType.GPS, TagFormat.RATIONAL),
+ ExifInterface.TAG_GPS_IMG_DIRECTION_REF to TagMapper(GpsDirectory.TAG_IMG_DIRECTION_REF, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_LATITUDE to TagMapper(GpsDirectory.TAG_LATITUDE, DirType.GPS, TagFormat.RATIONAL_ARRAY),
+ ExifInterface.TAG_GPS_LATITUDE_REF to TagMapper(GpsDirectory.TAG_LATITUDE_REF, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_LONGITUDE to TagMapper(GpsDirectory.TAG_LONGITUDE, DirType.GPS, TagFormat.RATIONAL_ARRAY),
+ ExifInterface.TAG_GPS_LONGITUDE_REF to TagMapper(GpsDirectory.TAG_LONGITUDE_REF, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_MAP_DATUM to TagMapper(GpsDirectory.TAG_MAP_DATUM, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_MEASURE_MODE to TagMapper(GpsDirectory.TAG_MEASURE_MODE, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_PROCESSING_METHOD to TagMapper(GpsDirectory.TAG_PROCESSING_METHOD, DirType.GPS, TagFormat.COMMENT),
+ ExifInterface.TAG_GPS_SATELLITES to TagMapper(GpsDirectory.TAG_SATELLITES, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_SPEED to TagMapper(GpsDirectory.TAG_SPEED, DirType.GPS, TagFormat.RATIONAL),
+ ExifInterface.TAG_GPS_SPEED_REF to TagMapper(GpsDirectory.TAG_SPEED_REF, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_STATUS to TagMapper(GpsDirectory.TAG_STATUS, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_TIMESTAMP to TagMapper(GpsDirectory.TAG_TIME_STAMP, DirType.GPS, TagFormat.RATIONAL_ARRAY),
+ ExifInterface.TAG_GPS_TRACK to TagMapper(GpsDirectory.TAG_TRACK, DirType.GPS, TagFormat.RATIONAL),
+ ExifInterface.TAG_GPS_TRACK_REF to TagMapper(GpsDirectory.TAG_TRACK_REF, DirType.GPS, TagFormat.ASCII),
+ ExifInterface.TAG_GPS_VERSION_ID to TagMapper(GpsDirectory.TAG_VERSION_ID, DirType.GPS, TagFormat.BYTE),
+ )
+
+ private val xmpTags: Map<String, TagMapper?> = mapOf(
+ ExifInterface.TAG_XMP to null, // IFD_TIFF_TAGS 0x02BC
+ )
+
+ private val rawTags: Map<String, TagMapper?> = mapOf(
+ // DNG
+ ExifInterface.TAG_DEFAULT_CROP_SIZE to null, // IFD_EXIF_TAGS 0xC620
+ ExifInterface.TAG_DNG_VERSION to null, // IFD_EXIF_TAGS 0xC612
+ // ORF
+ ExifInterface.TAG_ORF_ASPECT_FRAME to TagMapper(OlympusImageProcessingMakernoteDirectory.TagAspectFrame, DirType.OIPM, TagFormat.LONG), // ORF_IMAGE_PROCESSING_TAGS 0x1113
+ ExifInterface.TAG_ORF_PREVIEW_IMAGE_LENGTH to TagMapper(OlympusCameraSettingsMakernoteDirectory.TagPreviewImageLength, DirType.OCSM, TagFormat.LONG), // ORF_CAMERA_SETTINGS_TAGS 0x0102
+ ExifInterface.TAG_ORF_PREVIEW_IMAGE_START to TagMapper(OlympusCameraSettingsMakernoteDirectory.TagPreviewImageStart, DirType.OCSM, TagFormat.LONG), // ORF_CAMERA_SETTINGS_TAGS 0x0101
+ ExifInterface.TAG_ORF_THUMBNAIL_IMAGE to TagMapper(OlympusMakernoteDirectory.TAG_THUMBNAIL_IMAGE, DirType.OM, TagFormat.UNDEFINED), // ORF_MAKER_NOTE_TAGS 0x0100
+ // RW2
+ ExifInterface.TAG_RW2_ISO to TagMapper(PanasonicRawIFD0Directory.TagIso, DirType.PRIFD0, TagFormat.LONG), // IFD_TIFF_TAGS 0x0017
+ ExifInterface.TAG_RW2_JPG_FROM_RAW to TagMapper(PanasonicRawIFD0Directory.TagJpgFromRaw, DirType.PRIFD0, TagFormat.UNDEFINED), // IFD_TIFF_TAGS 0x002E
+ ExifInterface.TAG_RW2_SENSOR_BOTTOM_BORDER to TagMapper(PanasonicRawIFD0Directory.TagSensorBottomBorder, DirType.PRIFD0, TagFormat.LONG), // IFD_TIFF_TAGS 0x0006
+ ExifInterface.TAG_RW2_SENSOR_LEFT_BORDER to TagMapper(PanasonicRawIFD0Directory.TagSensorLeftBorder, DirType.PRIFD0, TagFormat.LONG), // IFD_TIFF_TAGS 0x0005
+ ExifInterface.TAG_RW2_SENSOR_RIGHT_BORDER to TagMapper(PanasonicRawIFD0Directory.TagSensorRightBorder, DirType.PRIFD0, TagFormat.LONG), // IFD_TIFF_TAGS 0x0007
+ ExifInterface.TAG_RW2_SENSOR_TOP_BORDER to TagMapper(PanasonicRawIFD0Directory.TagSensorTopBorder, DirType.PRIFD0, TagFormat.LONG), // IFD_TIFF_TAGS 0x0004
+ )
+
+ // list of known ExifInterface tags (as of androidx.exifinterface:exifinterface:1.3.0)
+ // mapped to metadata-extractor tags (as of v2.14.0)
+ val allTags: Map<String, TagMapper?> = hashMapOf<String, TagMapper?>(
+ ).apply {
+ putAll(baseTags)
+ putAll(thumbnailTags)
+ putAll(gpsTags)
+ putAll(xmpTags)
+ putAll(rawTags)
+ }
+
+ fun describeAll(exif: ExifInterface): Map<String, Map<String, String>> {
+ // initialize metadata-extractor directories that we will fill
+ // by tags converted from the ExifInterface attributes
+ // so that we can rely on metadata-extractor descriptions
+ val dirs = DirType.entries.associateWith { it.createDirectory() }
+
+ // exclude Exif directory when it only includes image size
+ val isUselessExif = fun(it: Map<String, String>): Boolean {
+ return it.size == 2 && it.containsKey("Image Height") && it.containsKey("Image Width")
+ }
+
+ return HashMap<String, Map<String, String>>().apply {
+ put("Exif", describeDir(exif, dirs, baseTags).takeUnless(isUselessExif) ?: hashMapOf())
+ put("Exif Thumbnail", describeDir(exif, dirs, thumbnailTags))
+ put(Metadata.DIR_GPS, describeDir(exif, dirs, gpsTags))
+ put(Metadata.DIR_XMP, describeDir(exif, dirs, xmpTags))
+ put("Exif Raw", describeDir(exif, dirs, rawTags))
+ }.filterValues { it.isNotEmpty() }
+ }
+
+ private fun describeDir(exif: ExifInterface, metadataExtractorDirs: Map<DirType, Directory>, tags: Map<String, TagMapper?>): Map<String, String> {
+ val dirMap = HashMap<String, String>()
+
+ fillMetadataExtractorDir(exif, metadataExtractorDirs, tags)
+
+ for ((exifInterfaceTag, mapper) in tags) {
+ if (exif.hasAttribute(exifInterfaceTag)) {
+ val value: String? = exif.getAttribute(exifInterfaceTag)
+ if (value != null && !(value == "0" && isNeverNull(exifInterfaceTag))) {
+ if (mapper != null) {
+ val dir = metadataExtractorDirs[mapper.dirType] ?: error("Directory type ${mapper.dirType} does not have a matching Directory instance")
+ val type = mapper.type
+ val tagName = dir.getTagName(type)
+
+ val description: String? = dir.getDescription(type)
+ if (description != null) {
+ dirMap[tagName] = description
+ } else {
+ Log.w(LOG_TAG, "failed to get description for tag=$exifInterfaceTag value=$value")
+ dirMap[tagName] = value
+ }
+ } else {
+ dirMap[exifInterfaceTag] = value
+ }
+ }
+ }
+ }
+ return dirMap
+ }
+
+ private fun fillMetadataExtractorDir(exif: ExifInterface, metadataExtractorDirs: Map<DirType, Directory>, tags: Map<String, TagMapper?>) {
+ for ((exifInterfaceTag, mapper) in tags) {
+ if (exif.hasAttribute(exifInterfaceTag) && mapper != null) {
+ val value: String? = exif.getAttribute(exifInterfaceTag)
+ if (value != null && (value != "0" || !neverNullTags.contains(exifInterfaceTag))) {
+ val obj: Any? = when (mapper.format) {
+ TagFormat.ASCII, TagFormat.COMMENT, TagFormat.UNDEFINED -> value
+ TagFormat.BYTE -> exif.getAttributeBytes(exifInterfaceTag)
+ TagFormat.SHORT -> value.toShortOrNull()
+ TagFormat.LONG -> value.toLongOrNull()
+ TagFormat.RATIONAL -> toRational(value)
+ TagFormat.RATIONAL_ARRAY -> toRationalArray(value)
+ null -> null
+ }
+ if (obj != null) {
+ val dir = metadataExtractorDirs[mapper.dirType] ?: error("Directory type ${mapper.dirType} does not have a matching Directory instance")
+ dir.setObject(mapper.type, obj)
+ }
+ }
+ }
+ }
+ }
+
+ private fun toRational(s: String?): Rational? {
+ s ?: return null
+
+ // e.g. "12345/100" to Rational(12345, 100)
+ val parts = s.split("/")
+ if (parts.size == 2) {
+ val numerator = parts[0].toLongOrNull() ?: return null
+ val denominator = parts[1].toLongOrNull() ?: return null
+ return Rational(numerator, denominator)
+ }
+
+ var d = s.toDoubleOrNull() ?: return null
+ if (d == 0.0) return Rational(0, 1)
+
+ // e.g. "0.02564102564102564" to Rational(1, 39)
+ if (d < 1) {
+ val numerator = 1L
+ val f = numerator / d
+ val denominator = f.roundToLong()
+ if (abs(f - denominator) < PRECISION_ERROR_TOLERANCE) {
+ return Rational(numerator, denominator)
+ }
+ }
+
+ // e.g. "123.45" to Rational(12345, 100)
+ var denominator: Long = 1
+ while (d != floor(d)) {
+ denominator *= 10
+ d *= 10
+ if (denominator > 10000000000) {
+ // let's not get irrational
+ return null
+ }
+ }
+ val numerator: Long = d.roundToLong()
+ return Rational(numerator, denominator)
+ }
+
+ private fun toRationalArray(s: String?): Array<Rational>? {
+ s ?: return null
+ val list = s.split(",").mapNotNull { toRational(it) }
+ if (list.isEmpty()) return null
+ return list.toTypedArray()
+ }
+
+ // extensions
+
+ fun ExifInterface.getSafeInt(tag: String, acceptZero: Boolean = true, save: (value: Int) -> Unit) {
+ if (this.hasAttribute(tag)) {
+ val value = this.getAttributeInt(tag, 0)
+ if (acceptZero || value != 0) {
+ save(value)
+ }
+ }
+ }
+
+ fun ExifInterface.getSafeDouble(tag: String, save: (value: Double) -> Unit) {
+ if (this.hasAttribute(tag)) {
+ val value = this.getAttributeDouble(tag, Double.NaN)
+ if (!value.isNaN()) {
+ save(value)
+ }
+ }
+ }
+
+ fun ExifInterface.getSafeRational(tag: String, save: (value: Rational) -> Unit) {
+ if (this.hasAttribute(tag)) {
+ val value = toRational(this.getAttribute(tag))
+ if (value != null) {
+ save(value)
+ }
+ }
+ }
+
+ fun ExifInterface.getSafeDateMillis(tag: String, subSecTag: String?, save: (value: Long) -> Unit) {
+ if (this.hasAttribute(tag)) {
+ val dateString = this.getAttribute(tag)
+ if (dateString != null) {
+ try {
+ DATETIME_FORMAT.parse(dateString)?.let { date ->
+ var dateMillis = date.time
+ if (subSecTag != null && this.hasAttribute(subSecTag)) {
+ dateMillis += Metadata.parseSubSecond(this.getAttribute(subSecTag))
+ }
+ save(dateMillis)
+ }
+ } catch (e: ParseException) {
+ Log.w(LOG_TAG, "failed to parse date=$dateString", e)
+ }
+ }
+ }
+ }
+}
+
+enum class DirType {
+ EXIF_IFD0 {
+ override fun createDirectory() = ExifIFD0Directory()
+ },
+ EXIF_THUMBNAIL {
+ override fun createDirectory() = ExifThumbnailDirectory(0)
+ },
+ GPS {
+ override fun createDirectory() = GpsDirectory()
+ },
+ OIPM {
+ override fun createDirectory() = OlympusImageProcessingMakernoteDirectory()
+ },
+ OCSM {
+ override fun createDirectory() = OlympusCameraSettingsMakernoteDirectory()
+ },
+ OM {
+ override fun createDirectory() = OlympusMakernoteDirectory()
+ },
+ PRIFD0 {
+ override fun createDirectory() = PanasonicRawIFD0Directory()
+ };
+
+ abstract fun createDirectory(): Directory
+}
+
+enum class TagFormat {
+ ASCII, COMMENT, BYTE, SHORT, LONG, RATIONAL, RATIONAL_ARRAY, UNDEFINED
+}
+
+data class TagMapper(val type: Int, val dirType: DirType, val format: TagFormat?)
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifTags.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifTags.kt
new file mode 100644
index 0000000..723bac0
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/ExifTags.kt
@@ -0,0 +1,61 @@
+package deckers.thibault.aves.metadata
+
+/*
+Exif tags missing from `metadata-extractor`
+
+Photoshop
+https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/
+https://www.adobe.io/content/dam/udp/en/open/standards/tiff/TIFFphotoshop.pdf
+ */
+object ExifTags {
+ private const val PROCESSING_SOFTWARE = 0x000b
+ private const val X_POSITION = 0x011e
+ private const val Y_POSITION = 0x011f
+ private const val T4_OPTIONS = 0x0124
+ private const val T6_OPTIONS = 0x0125
+ private const val COLOR_MAP = 0x0140
+ private const val EXTRA_SAMPLES = 0x0152
+ private const val SAMPLE_FORMAT = 0x0153
+ private const val SMIN_SAMPLE_VALUE = 0x0154
+ private const val SMAX_SAMPLE_VALUE = 0x0155
+ private const val SONY_RAW_FILE_TYPE = 0x7000
+ private const val SONY_TONE_CURVE = 0x7010
+ private const val MATTEING = 0x80e3
+
+ // sensing method (0x9217) redundant with sensing method (0xA217)
+ private const val SENSING_METHOD = 0x9217
+ private const val IMAGE_SOURCE_DATA = 0x935c
+ private const val GDAL_METADATA = 0xa480
+ private const val GDAL_NO_DATA = 0xa481
+
+ private val tagNameMap = hashMapOf(
+ PROCESSING_SOFTWARE to "Processing Software",
+ X_POSITION to "X Position",
+ Y_POSITION to "Y Position",
+ T4_OPTIONS to "T4 Options",
+ T6_OPTIONS to "T6 Options",
+ COLOR_MAP to "Color Map",
+ EXTRA_SAMPLES to "Extra Samples",
+ SAMPLE_FORMAT to "Sample Format",
+ SMIN_SAMPLE_VALUE to "S Min Sample Value",
+ SMAX_SAMPLE_VALUE to "S Max Sample Value",
+ SONY_RAW_FILE_TYPE to "Sony Raw File Type",
+ SONY_TONE_CURVE to "Sony Tone Curve",
+ MATTEING to "Matteing",
+ SENSING_METHOD to "Sensing Method (0x9217)",
+ IMAGE_SOURCE_DATA to "Image Source Data",
+ GDAL_METADATA to "GDAL Metadata",
+ GDAL_NO_DATA to "GDAL No Data",
+ ).apply {
+ putAll(DngTags.tagNameMap)
+ putAll(ExifGeoTiffTags.tagNameMap)
+ }
+
+ fun isDngTag(tag: Int) = DngTags.tags.contains(tag)
+
+ fun isGeoTiffTag(tag: Int) = ExifGeoTiffTags.tags.contains(tag)
+
+ fun getTagName(tag: Int): String? {
+ return tagNameMap[tag]
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/GeoTiffTags.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/GeoTiffTags.kt
new file mode 100644
index 0000000..e31cca4
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/GeoTiffTags.kt
@@ -0,0 +1,116 @@
+package deckers.thibault.aves.metadata
+
+object GeoTiffKeys {
+ // not a standard tag
+ const val GEOTIFF_VERSION = 0
+
+ private const val MODEL_TYPE = 0x0400
+ private const val RASTER_TYPE = 0x0401
+ private const val CITATION = 0x0402
+ private const val GEOG_TYPE = 0x0800
+ private const val GEOG_CITATION = 0x0801
+ private const val GEOG_GEODETIC_DATUM = 0x0802
+ private const val GEOG_LINEAR_UNITS = 0x0804
+ private const val GEOG_ANGULAR_UNITS = 0x0806
+ private const val GEOG_ELLIPSOID = 0x0808
+ private const val GEOG_SEMI_MAJOR_AXIS = 0x0809
+ private const val GEOG_SEMI_MINOR_AXIS = 0x080a
+ private const val GEOG_INV_FLATTENING = 0x080b
+ private const val PROJ_CS_TYPE = 0x0c00
+ private const val PROJ_CS_CITATION = 0x0c01
+ private const val PROJECTION = 0x0c02
+ private const val PROJ_COORD_TRANS = 0x0c03
+ private const val PROJ_LINEAR_UNITS = 0x0c04
+ private const val PROJ_STD_PARALLEL_1 = 0x0c06
+ private const val PROJ_STD_PARALLEL_2 = 0x0c07
+ private const val PROJ_NAT_ORIGIN_LONG = 0x0c08
+ private const val PROJ_NAT_ORIGIN_LAT = 0x0c09
+ private const val PROJ_FALSE_EASTING = 0x0c0a
+ private const val PROJ_FALSE_NORTHING = 0x0c0b
+ private const val PROJ_SCALE_AT_NAT_ORIGIN = 0x0c14
+ private const val PROJ_AZIMUTH_ANGLE = 0x0c16
+ private const val VERTICAL_UNITS = 0x1003
+
+ private val tagNameMap = hashMapOf(
+ GEOTIFF_VERSION to "GeoTIFF Version",
+ MODEL_TYPE to "Model Type",
+ RASTER_TYPE to "Raster Type",
+ CITATION to "Citation",
+ GEOG_TYPE to "Geographic Type",
+ GEOG_CITATION to "Geographic Citation",
+ GEOG_GEODETIC_DATUM to "Geographic Geodetic Datum",
+ GEOG_LINEAR_UNITS to "Geographic Linear Units",
+ GEOG_ANGULAR_UNITS to "Geographic Angular Units",
+ GEOG_ELLIPSOID to "Geographic Ellipsoid",
+ GEOG_SEMI_MAJOR_AXIS to "Semi-major axis",
+ GEOG_SEMI_MINOR_AXIS to "Semi-minor axis",
+ GEOG_INV_FLATTENING to "Inv. Flattening",
+ PROJ_CS_TYPE to "Projected Coordinate System Type",
+ PROJ_CS_CITATION to "Projected Coordinate System Citation",
+ PROJECTION to "Projection",
+ PROJ_COORD_TRANS to "Projected Coordinate Transform",
+ PROJ_LINEAR_UNITS to "Projection Linear Units",
+ PROJ_STD_PARALLEL_1 to "Projection Standard Parallel 1",
+ PROJ_STD_PARALLEL_2 to "Projection Standard Parallel 2",
+ PROJ_NAT_ORIGIN_LONG to "Projection Natural Origin Longitude",
+ PROJ_NAT_ORIGIN_LAT to "Projection Natural Origin Latitude",
+ PROJ_FALSE_EASTING to "Projection False Easting",
+ PROJ_FALSE_NORTHING to "Projection False Northing",
+ PROJ_SCALE_AT_NAT_ORIGIN to "Projection Scale at Natural Origin",
+ PROJ_AZIMUTH_ANGLE to "Projection Azimuth Angle",
+ VERTICAL_UNITS to "Vertical Units",
+ )
+
+ fun getTagName(tag: Int): String? {
+ return tagNameMap[tag]
+ }
+}
+
+object ExifGeoTiffTags {
+ // ModelPixelScaleTag (optional)
+ // Tag = 33550 (830E.H)
+ // Type = DOUBLE
+ // Count = 3
+ const val TAG_MODEL_PIXEL_SCALE = 0x830e
+
+ // ModelTiePointTag (conditional)
+ // Tag = 33922 (8482.H)
+ // Type = DOUBLE
+ // Count = 6*K, K = number of tie points
+ const val TAG_MODEL_TIE_POINT = 0x8482
+
+ // ModelTransformationTag (conditional)
+ // Tag = 34264 (85D8.H)
+ // Type = DOUBLE
+ // Count = 16
+ const val TAG_MODEL_TRANSFORMATION = 0x85d8
+
+ // GeoKeyDirectoryTag (mandatory)
+ // Tag = 34735 (87AF.H)
+ // Type = UNSIGNED SHORT
+ // Count = variable, >= 4
+ const val TAG_GEO_KEY_DIRECTORY = 0x87af
+
+ // GeoDoubleParamsTag (optional)
+ // Tag = 34736 (87BO.H)
+ // Type = DOUBLE
+ // Count = variable
+ const val TAG_GEO_DOUBLE_PARAMS = 0x87b0
+
+ // GeoAsciiParamsTag (optional)
+ // Tag = 34737 (87B1.H)
+ // Type = ASCII
+ // Count = variable
+ const val TAG_GEO_ASCII_PARAMS = 0x87b1
+
+ val tagNameMap = hashMapOf(
+ TAG_GEO_ASCII_PARAMS to "Geo Ascii Params",
+ TAG_GEO_DOUBLE_PARAMS to "Geo Double Params",
+ TAG_GEO_KEY_DIRECTORY to "Geo Key Directory",
+ TAG_MODEL_PIXEL_SCALE to "Model Pixel Scale",
+ TAG_MODEL_TIE_POINT to "Model Tie Points",
+ TAG_MODEL_TRANSFORMATION to "Model Transformation",
+ )
+
+ val tags = tagNameMap.keys
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MediaMetadataRetrieverHelper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MediaMetadataRetrieverHelper.kt
new file mode 100644
index 0000000..fd840b9
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MediaMetadataRetrieverHelper.kt
@@ -0,0 +1,187 @@
+package deckers.thibault.aves.metadata
+
+import android.media.MediaFormat
+import android.media.MediaMetadataRetriever
+import android.os.Build
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.TimeZone
+
+object MediaMetadataRetrieverHelper {
+ val allKeys = hashMapOf(
+ MediaMetadataRetriever.METADATA_KEY_ALBUM to "Album",
+ MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST to "Album Artist",
+ MediaMetadataRetriever.METADATA_KEY_ARTIST to "Artist",
+ MediaMetadataRetriever.METADATA_KEY_AUTHOR to "Author",
+ MediaMetadataRetriever.METADATA_KEY_BITRATE to "Bitrate",
+ MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER to "CD Track Number",
+ MediaMetadataRetriever.METADATA_KEY_COMPILATION to "Compilation",
+ MediaMetadataRetriever.METADATA_KEY_COMPOSER to "Composer",
+ MediaMetadataRetriever.METADATA_KEY_DATE to "Date",
+ MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER to "Disc Number",
+ MediaMetadataRetriever.METADATA_KEY_DURATION to "Duration",
+ MediaMetadataRetriever.METADATA_KEY_GENRE to "Genre",
+ MediaMetadataRetriever.METADATA_KEY_HAS_AUDIO to "Has Audio",
+ MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO to "Has Video",
+ MediaMetadataRetriever.METADATA_KEY_LOCATION to "Location",
+ MediaMetadataRetriever.METADATA_KEY_MIMETYPE to "MIME Type",
+ MediaMetadataRetriever.METADATA_KEY_NUM_TRACKS to "Number of Tracks",
+ MediaMetadataRetriever.METADATA_KEY_TITLE to "Title",
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT to "Video Height",
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH to "Video Width",
+ MediaMetadataRetriever.METADATA_KEY_WRITER to "Writer",
+ MediaMetadataRetriever.METADATA_KEY_YEAR to "Year",
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION to "Video Rotation",
+ ).apply {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ put(MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE, "Capture Framerate")
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
+ putAll(
+ hashMapOf(
+ MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE to "Has Image",
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_COUNT to "Image Count",
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_HEIGHT to "Image Height",
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_PRIMARY to "Image Primary",
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_ROTATION to "Image Rotation",
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_WIDTH to "Image Width",
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_FRAME_COUNT to "Video Frame Count",
+ )
+ )
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ putAll(
+ hashMapOf(
+ MediaMetadataRetriever.METADATA_KEY_EXIF_LENGTH to "Exif Length",
+ MediaMetadataRetriever.METADATA_KEY_EXIF_OFFSET to "Exif Offset",
+ )
+ )
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ putAll(
+ hashMapOf(
+ MediaMetadataRetriever.METADATA_KEY_COLOR_RANGE to "Color Range",
+ MediaMetadataRetriever.METADATA_KEY_COLOR_STANDARD to "Color Standard",
+ MediaMetadataRetriever.METADATA_KEY_COLOR_TRANSFER to "Color Transfer",
+ )
+ )
+ }
+ }
+
+ private val durationFormat = SimpleDateFormat("HH:mm:ss.SSS", Locale.ROOT).apply { timeZone = TimeZone.getTimeZone("UTC") }
+
+ // extensions
+
+ fun MediaMetadataRetriever.getSafeString(tag: Int, save: (value: String) -> Unit) {
+ val value = this.extractMetadata(tag)
+ if (value != null) save(value)
+ }
+
+ fun MediaMetadataRetriever.getSafeInt(tag: Int, save: (value: Int) -> Unit) {
+ val value = this.extractMetadata(tag)?.toIntOrNull()
+ if (value != null) save(value)
+ }
+
+ fun MediaMetadataRetriever.getSafeLong(tag: Int, save: (value: Long) -> Unit) {
+ val value = this.extractMetadata(tag)?.toLongOrNull()
+ if (value != null) save(value)
+ }
+
+ fun MediaMetadataRetriever.getSafeDateMillis(tag: Int, save: (value: Long) -> Unit) {
+ val dateString = this.extractMetadata(tag)
+ val dateMillis = Metadata.parseVideoMetadataDate(dateString)
+ // some entries have an invalid default date (19040101T000000.000Z) that is before Epoch time
+ if (dateMillis > 0) save(dateMillis)
+ }
+
+ private fun formatBitrate(size: Long): String {
+ val divider = 1000
+ val symbol = "bit/s"
+
+ if (size < divider) return "$size $symbol"
+ if (size < divider * divider) return "${String.format(Locale.getDefault(), "%.2f", size.toDouble() / divider)} K$symbol"
+ return "${String.format(Locale.getDefault(), "%.2f", size.toDouble() / divider / divider)} M$symbol"
+ }
+
+ fun MediaMetadataRetriever.getSafeDescription(tag: Int, save: (value: String) -> Unit) {
+ val value = this.extractMetadata(tag)
+ if (value != null) {
+ when (tag) {
+ // format
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_ROTATION,
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION -> "$value°"
+
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_HEIGHT, MediaMetadataRetriever.METADATA_KEY_IMAGE_WIDTH,
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT, MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH -> "$value pixels"
+
+ MediaMetadataRetriever.METADATA_KEY_BITRATE -> {
+ val bitrate = value.toLongOrNull() ?: 0
+ if (bitrate > 0) formatBitrate(bitrate) else null
+ }
+
+ MediaMetadataRetriever.METADATA_KEY_CAPTURE_FRAMERATE -> {
+ val framerate = value.toDoubleOrNull() ?: 0.0
+ if (framerate > 0.0) "$framerate" else null
+ }
+
+ MediaMetadataRetriever.METADATA_KEY_DURATION -> {
+ val dateMillis = value.toLongOrNull() ?: 0
+ if (dateMillis > 0) durationFormat.format(Date(dateMillis)) else null
+ }
+
+ MediaMetadataRetriever.METADATA_KEY_COLOR_RANGE -> {
+ when (value.toIntOrNull()) {
+ MediaFormat.COLOR_RANGE_FULL -> "Full"
+ MediaFormat.COLOR_RANGE_LIMITED -> "Limited"
+ else -> value
+ }
+ }
+
+ MediaMetadataRetriever.METADATA_KEY_COLOR_STANDARD -> {
+ when (value.toIntOrNull()) {
+ MediaFormat.COLOR_STANDARD_BT709 -> "BT.709"
+ MediaFormat.COLOR_STANDARD_BT601_PAL -> "BT.601 625 (PAL)"
+ MediaFormat.COLOR_STANDARD_BT601_NTSC -> "BT.601 525 (NTSC)"
+ MediaFormat.COLOR_STANDARD_BT2020 -> "BT.2020"
+ else -> value
+ }
+ }
+
+ MediaMetadataRetriever.METADATA_KEY_COLOR_TRANSFER -> {
+ when (value.toIntOrNull()) {
+ MediaFormat.COLOR_TRANSFER_LINEAR -> "Linear"
+ MediaFormat.COLOR_TRANSFER_SDR_VIDEO -> "SMPTE 170M"
+ MediaFormat.COLOR_TRANSFER_ST2084 -> "SMPTE ST 2084"
+ MediaFormat.COLOR_TRANSFER_HLG -> "ARIB STD-B67 (HLG)"
+ else -> value
+ }
+ }
+ // hide default or invalid values
+ MediaMetadataRetriever.METADATA_KEY_COMPILATION,
+ MediaMetadataRetriever.METADATA_KEY_DISC_NUMBER,
+ MediaMetadataRetriever.METADATA_KEY_YEAR -> if (value != "0") value else null
+
+ MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER -> if (value != "0/0") value else null
+ MediaMetadataRetriever.METADATA_KEY_DATE -> {
+ val dateMillis = Metadata.parseVideoMetadataDate(value)
+ // some entries have an invalid default date (19040101T000000.000Z) that is before Epoch time
+ if (dateMillis > 0) value else null
+ }
+ // hide
+ MediaMetadataRetriever.METADATA_KEY_LOCATION,
+ MediaMetadataRetriever.METADATA_KEY_MIMETYPE -> null
+ // as is
+ else -> value
+ }?.let { save(it) }
+ }
+ }
+
+ fun MediaFormat.getSafeInt(key: String, save: (value: Int) -> Unit) {
+ if (this.containsKey(key)) save(this.getInteger(key))
+ }
+
+ fun MediaFormat.getSafeLong(key: String, save: (value: Long) -> Unit) {
+ if (this.containsKey(key)) save(this.getLong(key))
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Metadata.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Metadata.kt
new file mode 100644
index 0000000..0d1dbff
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Metadata.kt
@@ -0,0 +1,186 @@
+package deckers.thibault.aves.metadata
+
+import android.content.Context
+import android.net.Uri
+import android.util.Log
+import deckers.thibault.aves.utils.FileUtils.transferFrom
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.StorageUtils
+import java.io.File
+import java.io.InputStream
+import java.text.ParseException
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.TimeZone
+import java.util.regex.Pattern
+import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface
+
+object Metadata {
+ private val LOG_TAG = LogUtils.createTag<Metadata>()
+
+ const val IPTC_MARKER_BYTE: Byte = 0x1c
+
+ // Pattern to extract latitude & longitude from a video location tag (cf ISO 6709)
+ // Examples:
+ // "+37.5090+127.0243/" (Samsung)
+ // "+51.3328-000.7053+113.474/" (Apple)
+ val VIDEO_LOCATION_PATTERN: Pattern = Pattern.compile("([+-][.0-9]+)([+-][.0-9]+).*")
+
+ private val VIDEO_DATE_SUBSECOND_PATTERN = Pattern.compile("(\\d{6})(\\.\\d+)")
+ private val VIDEO_TIME_ZONE_PATTERN = Pattern.compile("(Z|[+-]\\d{4})$")
+
+ // directory names, as shown when listing all metadata
+ const val DIR_GPS = "GPS" // from metadata-extractor
+ const val DIR_XMP = "XMP" // from metadata-extractor
+ const val DIR_MEDIA = "Media" // custom
+ const val DIR_COVER_ART = "Cover" // custom
+ const val DIR_DNG = "DNG" // custom
+ const val DIR_EXIF_GEOTIFF = "GeoTIFF" // custom
+ const val DIR_PNG_TEXTUAL_DATA = "PNG Textual Data" // custom
+ const val DIR_MP4_USER_DATA = "User Data" // custom
+
+ // types of metadata
+ const val TYPE_COMMENT = "comment"
+ const val TYPE_EXIF = "exif"
+ const val TYPE_ICC_PROFILE = "icc_profile"
+ const val TYPE_IPTC = "iptc"
+ const val TYPE_JFIF = "jfif"
+ const val TYPE_JPEG_ADOBE = "jpeg_adobe"
+ const val TYPE_JPEG_DUCKY = "jpeg_ducky"
+ const val TYPE_MP4 = "mp4"
+ const val TYPE_PHOTOSHOP_IRB = "photoshop_irb"
+ const val TYPE_XMP = "xmp"
+
+ // interpret EXIF code to angle (0, 90, 180 or 270 degrees)
+ fun getRotationDegreesForExifCode(exifOrientation: Int): Int = when (exifOrientation) {
+ ExifInterface.ORIENTATION_ROTATE_90, ExifInterface.ORIENTATION_TRANSVERSE -> 90
+ ExifInterface.ORIENTATION_ROTATE_180, ExifInterface.ORIENTATION_FLIP_VERTICAL -> 180
+ ExifInterface.ORIENTATION_ROTATE_270, ExifInterface.ORIENTATION_TRANSPOSE -> 270
+ else -> 0
+ }
+
+ // interpret EXIF code to whether the image is flipped
+ fun isFlippedForExifCode(exifOrientation: Int): Boolean = when (exifOrientation) {
+ ExifInterface.ORIENTATION_FLIP_HORIZONTAL, ExifInterface.ORIENTATION_TRANSVERSE, ExifInterface.ORIENTATION_FLIP_VERTICAL, ExifInterface.ORIENTATION_TRANSPOSE -> true
+ else -> false
+ }
+
+ fun getExifCode(rotationDegrees: Int, isFlipped: Boolean): Int {
+ return when (rotationDegrees) {
+ 90 -> if (isFlipped) ExifInterface.ORIENTATION_TRANSVERSE else ExifInterface.ORIENTATION_ROTATE_90
+ 180 -> if (isFlipped) ExifInterface.ORIENTATION_FLIP_VERTICAL else ExifInterface.ORIENTATION_ROTATE_180
+ 270 -> if (isFlipped) ExifInterface.ORIENTATION_TRANSPOSE else ExifInterface.ORIENTATION_ROTATE_270
+ else -> if (isFlipped) ExifInterface.ORIENTATION_FLIP_HORIZONTAL else ExifInterface.ORIENTATION_NORMAL
+ }
+ }
+
+ fun parseSubSecond(subSecond: String?): Int {
+ if (subSecond != null) {
+ try {
+ val millis = (".$subSecond".toDouble() * 1000).toInt()
+ if (millis in 0..999) {
+ return millis
+ }
+ } catch (_: NumberFormatException) {
+ // ignore
+ }
+ }
+ return 0
+ }
+
+ // not sure which standards are used for the different video formats,
+ // but looks like some form of ISO 8601 `basic format`:
+ // yyyyMMddTHHmmss(.sss)?(Z|+/-hhmm)?
+ fun parseVideoMetadataDate(metadataDate: String?): Long {
+ var dateString = metadataDate ?: return 0
+
+ // optional sub-second
+ var subSecond: String? = null
+ val subSecondMatcher = VIDEO_DATE_SUBSECOND_PATTERN.matcher(dateString)
+ if (subSecondMatcher.find()) {
+ subSecond = subSecondMatcher.group(2)?.substring(1)
+ dateString = subSecondMatcher.replaceAll("$1")
+ }
+
+ // optional time zone
+ var timeZone: TimeZone? = null
+ val timeZoneMatcher = VIDEO_TIME_ZONE_PATTERN.matcher(dateString)
+ if (timeZoneMatcher.find()) {
+ timeZone = TimeZone.getTimeZone("GMT${timeZoneMatcher.group().replace("Z", "")}")
+ dateString = timeZoneMatcher.replaceAll("")
+ }
+
+ val date: Date = try {
+ val parser = SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ROOT)
+ parser.timeZone = timeZone ?: TimeZone.getTimeZone("GMT")
+ parser.parse(dateString)
+ } catch (_: ParseException) {
+ // ignore
+ null
+ } ?: return 0
+
+ return date.time + parseSubSecond(subSecond)
+ }
+
+ // Opening some large files yields an OOM (both with `metadata-extractor` v2.15.0 and `ExifInterface` v1.3.1),
+ // so we define an arbitrary threshold to avoid a crash on launch.
+ // It is not clear whether it is because of the file itself or its metadata.
+ private const val FILE_SIZE_MAX = 100 * (1 shl 20) // MB
+
+ fun isDangerouslyLarge(sizeBytes: Long?) = sizeBytes == null || sizeBytes > FILE_SIZE_MAX
+
+ // we try and read metadata from large files by copying an arbitrary amount from its beginning
+ // to a temporary file, and reusing that preview file for all metadata reading purposes
+ private const val PREVIEW_SIZE: Long = 5 * (1 shl 20) // MB
+
+ private val previewFiles = HashMap<Uri, File>()
+
+ private fun getSafeUri(context: Context, uri: Uri, mimeType: String?, sizeBytes: Long?): Uri {
+ // formats known to yield OOM for large files
+ return when (mimeType) {
+ // formats known to yield OOM for large files
+ MimeTypes.DNG,
+ MimeTypes.DNG_ADOBE,
+ MimeTypes.HEIC,
+ MimeTypes.HEIF,
+ MimeTypes.MP4,
+ MimeTypes.PSD_VND,
+ MimeTypes.PSD_X,
+ MimeTypes.TIFF,
+ null ->
+ if (isDangerouslyLarge(sizeBytes)) {
+ Log.d(LOG_TAG, "Dangerously large file with uri=$uri, mimeType=$mimeType, size=$sizeBytes")
+ // make a preview from the beginning of the file,
+ // hoping the metadata is accessible in the copied chunk
+ var previewFile = previewFiles[uri]
+ if (previewFile == null) {
+ previewFile = createPreviewFile(context, uri)
+ previewFiles[uri] = previewFile
+ }
+ Uri.fromFile(previewFile)
+ } else {
+ // small enough to be safe as it is
+ uri
+ }
+
+ else ->
+ // *probably* safe
+ uri
+ }
+ }
+
+ fun createPreviewFile(context: Context, uri: Uri): File {
+ val size = PREVIEW_SIZE
+ Log.d(LOG_TAG, "create preview of size=$size for uri=$uri")
+ return StorageUtils.createTempFile(context).apply {
+ transferFrom(StorageUtils.openInputStream(context, uri), size)
+ }
+ }
+
+ fun openSafeInputStream(context: Context, uri: Uri, mimeType: String?, sizeBytes: Long?): InputStream? {
+ val safeUri = getSafeUri(context, uri, mimeType, sizeBytes)
+ return StorageUtils.openInputStream(context, safeUri)
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Mp4ParserHelper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Mp4ParserHelper.kt
new file mode 100644
index 0000000..42c1187
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/Mp4ParserHelper.kt
@@ -0,0 +1,436 @@
+package deckers.thibault.aves.metadata
+
+import android.content.Context
+import android.net.Uri
+import android.util.Log
+import deckers.thibault.aves.metadata.xmp.XMP
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.StorageUtils
+import deckers.thibault.aves.utils.toByteArray
+import deckers.thibault.aves.utils.toHex
+import org.mp4parser.BasicContainer
+import org.mp4parser.Box
+import org.mp4parser.Container
+import org.mp4parser.IsoFile
+import org.mp4parser.PropertyBoxParserImpl
+import org.mp4parser.boxes.UnknownBox
+import org.mp4parser.boxes.UserBox
+import org.mp4parser.boxes.apple.AppleCoverBox
+import org.mp4parser.boxes.apple.AppleGPSCoordinatesBox
+import org.mp4parser.boxes.apple.AppleItemListBox
+import org.mp4parser.boxes.apple.AppleVariableSignedIntegerBox
+import org.mp4parser.boxes.apple.Utf8AppleDataBox
+import org.mp4parser.boxes.iso14496.part12.FreeBox
+import org.mp4parser.boxes.iso14496.part12.HandlerBox
+import org.mp4parser.boxes.iso14496.part12.MediaDataBox
+import org.mp4parser.boxes.iso14496.part12.MetaBox
+import org.mp4parser.boxes.iso14496.part12.MovieBox
+import org.mp4parser.boxes.iso14496.part12.MovieFragmentBox
+import org.mp4parser.boxes.iso14496.part12.SampleTableBox
+import org.mp4parser.boxes.iso14496.part12.SegmentIndexBox
+import org.mp4parser.boxes.iso14496.part12.TrackHeaderBox
+import org.mp4parser.boxes.iso14496.part12.UserDataBox
+import org.mp4parser.boxes.threegpp.ts26244.AuthorBox
+import org.mp4parser.boxes.threegpp.ts26244.LocationInformationBox
+import org.mp4parser.support.AbstractBox
+import org.mp4parser.support.Matrix
+import org.mp4parser.tools.Path
+import java.io.ByteArrayOutputStream
+import java.io.FileInputStream
+import java.nio.channels.Channels
+
+object Mp4ParserHelper {
+ private val LOG_TAG = LogUtils.createTag<Mp4ParserHelper>()
+
+ // arbitrary size to detect boxes that may yield an OOM
+ private const val BOX_SIZE_DANGER_THRESHOLD = 3 * (1 shl 20) // MB
+
+ const val SAMSUNG_MAKERNOTE_BOX_TYPE = "sefd"
+ const val SEFD_MOTION_PHOTO_NAME = "MotionPhoto_Data"
+
+ private val largerTypeWhitelist = listOf(
+ // HEIC motion photo may contain Samsung maker notes in `sefd` box,
+ // including a video larger than the danger threshold
+ SAMSUNG_MAKERNOTE_BOX_TYPE,
+ )
+
+ fun computeEdits(context: Context, uri: Uri, modifier: (isoFile: IsoFile) -> Unit): List<Pair<Long, ByteArray>> {
+ // we can skip uninteresting boxes with a seekable data source
+ val pfd = StorageUtils.openInputFileDescriptor(context, uri) ?: throw Exception("failed to open file descriptor for uri=$uri")
+ pfd.use {
+ FileInputStream(it.fileDescriptor).use { stream ->
+ stream.channel.use { channel ->
+ val boxParser = PropertyBoxParserImpl().apply {
+ // do not skip anything inside `MovieBox` as it will be parsed and rewritten for editing
+ // do not skip weird boxes (like trailing "0000" box), to fail fast if it is large
+ val skippedTypes = listOf(
+ // parsing `MediaDataBox` can take a long time
+ MediaDataBox.TYPE,
+ )
+ setBoxSkipper { type, size ->
+ if (skippedTypes.contains(type)) return@setBoxSkipper true
+ if (size > BOX_SIZE_DANGER_THRESHOLD) throw Mp4TooLargeException(type, "box (type=$type size=$size) is too large")
+ false
+ }
+ }
+ // creating `IsoFile` with a `File` or a `File.inputStream()` yields `No such device`
+ IsoFile(channel, boxParser).use { isoFile ->
+ val fragmented = isoFile.boxes.any { box -> box is MovieFragmentBox || box is SegmentIndexBox }
+ if (fragmented) throw Exception("editing fragmented movies is not supported")
+
+ val lastContentBox = isoFile.boxes.reversed().firstOrNull { box ->
+ when {
+ box == isoFile.movieBox -> false
+ testXmpBox(box) -> false
+ box is FreeBox -> false
+ else -> true
+ }
+ }
+ lastContentBox ?: throw Exception("failed to find last content box")
+ val oldFileSize = isoFile.size
+ var appendOffset = (isoFile.getBoxOffset { box -> box == lastContentBox })!! + lastContentBox.size
+
+ val edits = arrayListOf<Pair<Long, ByteArray>>()
+ fun addFreeBoxEdit(offset: Long, size: Long): Boolean {
+ val boxSize = size.toInt() - 8
+ if (boxSize > BOX_SIZE_DANGER_THRESHOLD) throw Exception("dangerous free box replacement for size=$boxSize")
+ return edits.add(Pair(offset, FreeBox(boxSize).toBytes()))
+ }
+
+ // replace existing movie box by a free box
+ isoFile.getBoxOffset { box -> box.type == MovieBox.TYPE }?.let { offset ->
+ addFreeBoxEdit(offset, isoFile.movieBox.size)
+ }
+
+ // replace existing XMP box by a free box
+ isoFile.getBoxOffset { box -> testXmpBox(box) }?.let { offset ->
+ addFreeBoxEdit(offset, isoFile.xmpBox!!.size)
+ }
+
+ modifier(isoFile)
+
+ // write edited movie box
+ val movieBoxBytes = isoFile.movieBox.toBytes()
+ edits.removeAll { (offset, _) -> offset == appendOffset }
+ edits.add(Pair(appendOffset, movieBoxBytes))
+ appendOffset += movieBoxBytes.size
+
+ // write edited XMP box
+ isoFile.xmpBox?.let { box ->
+ edits.removeAll { (offset, _) -> offset == appendOffset }
+ edits.add(Pair(appendOffset, box.toBytes()))
+ appendOffset += box.size
+ }
+
+ // write trailing free box instead of truncating
+ val trailing = oldFileSize - appendOffset
+ if (trailing > 0) {
+ addFreeBoxEdit(appendOffset, trailing)
+ }
+ return edits
+ }
+ }
+ }
+ }
+ }
+
+ // according to XMP Specification Part 3 - Storage in Files,
+ // XMP is embedded in MPEG-4 files using a top-level UUID box
+ private fun testXmpBox(box: Box): Boolean {
+ if (box is UserBox) {
+ if (!box.isParsed) {
+ box.parseDetails()
+ }
+ return box.userType.contentEquals(XMP.mp4Uuid)
+ }
+ return false
+ }
+
+ // returns the offset and data of the Samsung maker notes box
+ fun getSamsungSefd(context: Context, uri: Uri): Pair<Long, ByteArray>? {
+ try {
+ // we can skip uninteresting boxes with a seekable data source
+ val pfd = StorageUtils.openInputFileDescriptor(context, uri) ?: throw Exception("failed to open file descriptor for uri=$uri")
+ pfd.use {
+ FileInputStream(it.fileDescriptor).use { stream ->
+ stream.channel.use { channel ->
+ IsoFile(channel, metadataBoxParser()).use { isoFile ->
+ var offset = 0L
+ for (box in isoFile.boxes) {
+ if (box is UnknownBox && box.type == SAMSUNG_MAKERNOTE_BOX_TYPE) {
+ if (!box.isParsed) {
+ box.parseDetails()
+ }
+ return Pair(offset + 8, box.data.toByteArray()) // skip 8 bytes for box header
+ }
+ offset += box.size
+ }
+ }
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read sefd box", e)
+ }
+ return null
+ }
+
+ // extensions
+
+ fun IsoFile.updateLocation(locationIso6709: String?) {
+ // Apple GPS Coordinates Box can be in various locations:
+ // - moov[0]/udta[0]/©xyz
+ // - moov[0]/meta[0]/ilst/©xyz
+ // - others?
+ removeBoxes(AppleGPSCoordinatesBox::class.java, true)
+
+ locationIso6709 ?: return
+
+ var userDataBox = Path.getPath<UserDataBox>(movieBox, UserDataBox.TYPE)
+ if (userDataBox == null) {
+ userDataBox = UserDataBox()
+ movieBox.addBox(userDataBox)
+ }
+
+ userDataBox.addBox(AppleGPSCoordinatesBox().apply {
+ value = locationIso6709
+ })
+ }
+
+ fun IsoFile.updateRotation(degrees: Int): Boolean {
+ val matrix: Matrix = when (degrees) {
+ 0 -> Matrix.ROTATE_0
+ 90 -> Matrix.ROTATE_90
+ 180 -> Matrix.ROTATE_180
+ 270 -> Matrix.ROTATE_270
+ else -> throw Exception("failed because of invalid rotation degrees=$degrees")
+ }
+
+ var success = false
+ movieBox.getBoxes(TrackHeaderBox::class.java, true).filter { tkhd ->
+ if (!tkhd.isParsed) {
+ tkhd.parseDetails()
+ }
+ tkhd.width > 0 && tkhd.height > 0
+ }.forEach { tkhd ->
+ if (!setOf(Matrix.ROTATE_0, Matrix.ROTATE_90, Matrix.ROTATE_180, Matrix.ROTATE_270).contains(tkhd.matrix)) {
+ throw Exception("failed because existing matrix is not a simple rotation matrix")
+ }
+ tkhd.matrix = matrix
+ success = true
+ }
+ return success
+ }
+
+ fun IsoFile.updateXmp(xmp: String?) {
+ val xmpBox = xmpBox
+ if (xmp != null) {
+ val xmpData = xmp.toByteArray(Charsets.UTF_8)
+ if (xmpBox == null) {
+ addBox(UserBox(XMP.mp4Uuid).apply {
+ data = xmpData
+ })
+ } else {
+ xmpBox.data = xmpData
+ }
+ } else if (xmpBox != null) {
+ removeBox(xmpBox)
+ }
+ }
+
+ private fun IsoFile.getBoxOffset(test: (box: Box) -> Boolean): Long? {
+ var offset = 0L
+ for (box in boxes) {
+ if (test(box)) {
+ return offset
+ }
+ offset += box.size
+ }
+ return null
+ }
+
+ private val IsoFile.xmpBox: UserBox?
+ get() = boxes.firstOrNull { testXmpBox(it) } as UserBox?
+
+ fun <T : Box> Container.processBoxes(clazz: Class<T>, recursive: Boolean, apply: (box: T, parent: Container) -> Unit) {
+ // use a copy, in case box processing removes boxes
+ for (box in ArrayList(boxes)) {
+ if (clazz.isInstance(box)) {
+ @Suppress("unchecked_cast")
+ apply(box as T, this)
+ }
+ if (recursive && box is Container) {
+ box.processBoxes(clazz, true, apply)
+ }
+ }
+ }
+
+ private fun <T : Box> Container.removeBoxes(clazz: Class<T>, recursive: Boolean) {
+ processBoxes(clazz, recursive) { box, parent -> parent.removeBox(box) }
+ }
+
+ private fun Container.removeBox(box: Box) {
+ boxes = boxes.apply { remove(box) }
+ }
+
+ fun Container.dumpBoxes(sb: StringBuilder, indent: Int = 0) {
+ for (box in boxes) {
+ val boxType = box.type
+ try {
+ if (box is AbstractBox && !box.isParsed) {
+ box.parseDetails()
+ }
+ when (box) {
+ is BasicContainer -> {
+ sb.appendLine("${"\t".repeat(indent)}[$boxType] ${box.javaClass.simpleName}")
+ box.dumpBoxes(sb, indent + 1)
+ }
+
+ is UserBox -> sb.appendLine("${"\t".repeat(indent)}[$boxType] userType=${box.userType.toHex()} $box")
+ else -> sb.appendLine("${"\t".repeat(indent)}[$boxType] $box")
+ }
+ } catch (e: Exception) {
+ sb.appendLine("${"\t".repeat(indent)}failed to access box type=$boxType exception=${e.message}")
+ }
+ }
+ }
+
+ fun Box.toBytes(): ByteArray {
+ if (size > BOX_SIZE_DANGER_THRESHOLD) throw Mp4TooLargeException(type, "box (type=$type size=$size) is too large")
+ val stream = ByteArrayOutputStream(size.toInt())
+ Channels.newChannel(stream).use { getBox(it) }
+ return stream.toByteArray()
+ }
+
+ fun metadataBoxParser() = PropertyBoxParserImpl().apply {
+ val skippedTypes = listOf(
+ // parsing `MediaDataBox` can take a long time
+ MediaDataBox.TYPE,
+ // parsing `SampleTableBox` or `FreeBox` may yield OOM
+ SampleTableBox.TYPE, FreeBox.TYPE,
+ // some files are padded with `0` but the parser does not stop, reads type "0000",
+ // then a large size from following "0000", which may yield OOM
+ "0000",
+ )
+ setBoxSkipper { type, size ->
+ if (skippedTypes.contains(type)) return@setBoxSkipper true
+ if (size > BOX_SIZE_DANGER_THRESHOLD && !largerTypeWhitelist.contains(type)) throw Mp4TooLargeException(type, "box (type=$type size=$size) is too large")
+ false
+ }
+ }
+
+ fun getUserDataBox(
+ context: Context,
+ mimeType: String,
+ uri: Uri,
+ ): UserDataBox? {
+ if (mimeType != MimeTypes.MP4) return null
+
+ try {
+ // we can skip uninteresting boxes with a seekable data source
+ val pfd = StorageUtils.openInputFileDescriptor(context, uri) ?: throw Exception("failed to open file descriptor for uri=$uri")
+ pfd.use {
+ FileInputStream(it.fileDescriptor).use { stream ->
+ stream.channel.use { channel ->
+ // creating `IsoFile` with a `File` or a `File.inputStream()` yields `No such device`
+ IsoFile(channel, metadataBoxParser()).use { isoFile ->
+ return Path.getPath(isoFile.movieBox, UserDataBox.TYPE)
+ }
+ }
+ }
+ }
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to parse MP4 for mimeType=$mimeType uri=$uri", e)
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get User Data box by MP4 parser for mimeType=$mimeType uri=$uri", e)
+ }
+ return null
+ }
+
+ fun extractBoxFields(container: Container): HashMap<String, String> {
+ val fields = HashMap<String, String>()
+ for (box in container.boxes) {
+ if (box is AbstractBox && !box.isParsed) {
+ box.parseDetails()
+ }
+ val type = box.type
+ val key = boxTypeMetadataKey(type)
+ when (box) {
+ is AuthorBox -> fields[key] = box.author
+ is AppleCoverBox -> fields[key] = "[${box.coverData.size} bytes]"
+ is AppleGPSCoordinatesBox -> fields[key] = box.value
+ is AppleItemListBox -> fields.putAll(extractBoxFields(box))
+ is AppleVariableSignedIntegerBox -> fields[key] = box.value.toString()
+ is HandlerBox -> {}
+ is LocationInformationBox -> {
+ hashMapOf<String, String>(
+ "Language" to box.language,
+ "Name" to box.name,
+ "Role" to box.role.toString(),
+ "Longitude" to box.longitude.toString(),
+ "Latitude" to box.latitude.toString(),
+ "Altitude" to box.altitude.toString(),
+ "Astronomical Body" to box.astronomicalBody,
+ "Additional Notes" to box.additionalNotes,
+ ).forEach { (k, v) -> fields["$key/$k"] = v }
+ }
+
+ is MetaBox -> {
+ val handlerBox = Path.getPath<HandlerBox>(box, HandlerBox.TYPE).apply { parseDetails() }
+ when (val handlerType = handlerBox?.handlerType ?: MetaBox.TYPE) {
+ "mdir" -> fields.putAll(extractBoxFields(box))
+ else -> fields.putAll(extractBoxFields(box).map { Pair("$handlerType/${it.key}", it.value) }.toMap())
+ }
+ }
+
+ is UnknownBox -> {
+ val byteBuffer = box.data
+ val remaining = byteBuffer.remaining()
+ if (remaining > 512) {
+ fields[key] = "[$remaining bytes]"
+ } else {
+ val bytes = byteBuffer.toByteArray()
+ when (type) {
+ "SDLN",
+ "smrd" -> fields[key] = String(bytes)
+
+ else -> fields[key] = "0x${bytes.toHex()}"
+ }
+ }
+ }
+
+ is Utf8AppleDataBox -> fields[key] = box.value
+
+ else -> fields[key] = box.toString()
+ }
+ }
+ return fields
+ }
+
+ // cf https://exiftool.org/TagNames/QuickTime.html
+ private fun boxTypeMetadataKey(type: String) = when (type) {
+ "auth" -> "Author"
+ "catg" -> "Category"
+ "covr" -> "Cover Art"
+ "keyw" -> "Keyword"
+ "loci" -> "Location"
+ "mcvr" -> "Preview Image"
+ "pcst" -> "Podcast"
+ "SDLN" -> "Play Mode"
+ "stik" -> "Media Type"
+ "©alb" -> "Album"
+ "©ART" -> "Artist"
+ "©aut" -> "Author"
+ "©cmt" -> "Comment"
+ "©day" -> "Year"
+ "©des" -> "Description"
+ "©gen" -> "Genre"
+ "©nam" -> "Title"
+ "©too" -> "Encoder"
+ "©xyz" -> "GPS Coordinates"
+ else -> type
+ }
+}
+
+class Mp4TooLargeException(val type: String, message: String) : RuntimeException(message)
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiPage.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiPage.kt
new file mode 100644
index 0000000..948b2ae
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiPage.kt
@@ -0,0 +1,451 @@
+package deckers.thibault.aves.metadata
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.media.MediaExtractor
+import android.media.MediaFormat
+import android.net.Uri
+import android.os.Build
+import android.os.ParcelFileDescriptor
+import android.util.Log
+import com.adobe.internal.xmp.XMPMeta
+import com.drew.imaging.jpeg.JpegSegmentType
+import com.drew.metadata.exif.ExifDirectoryBase
+import com.drew.metadata.exif.ExifIFD0Directory
+import com.drew.metadata.xmp.XmpDirectory
+import deckers.thibault.aves.glide.TiffFetcher
+import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeInt
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeInt
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeLong
+import deckers.thibault.aves.metadata.metadataextractor.Helper
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeInt
+import deckers.thibault.aves.metadata.metadataextractor.mpf.MpEntry
+import deckers.thibault.aves.metadata.metadataextractor.mpf.MpEntryDirectory
+import deckers.thibault.aves.metadata.xmp.GoogleXMP
+import deckers.thibault.aves.metadata.xmp.XMP
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MemoryUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.canReadWithMetadataExtractor
+import deckers.thibault.aves.utils.MimeTypes.isHeic
+import deckers.thibault.aves.utils.MimeTypes.isIsoBMFFImage
+import deckers.thibault.aves.utils.StorageUtils
+import deckers.thibault.aves.utils.indexOfBytes
+import org.beyka.tiffbitmapfactory.TiffBitmapFactory
+import java.io.DataInputStream
+import java.io.EOFException
+import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface
+
+object MultiPage {
+ private val LOG_TAG = LogUtils.createTag<MultiPage>()
+
+ // TODO TLAD more generic support, (e.g. 0x00000014 + `ftyp` + `qt `)
+ // atom length (variable, e.g. `0x00000018`) + atom type (`ftyp`) + type (variable, e.g. `mp42`, `qt`)
+ private val heicMotionPhotoVideoStartIndicator = byteArrayOf(0x00, 0x00, 0x00, 0x18) + "ftypmp42".toByteArray()
+
+ // page info
+ private const val KEY_MIME_TYPE = "mimeType"
+ private const val KEY_HEIGHT = "height"
+ private const val KEY_WIDTH = "width"
+ private const val KEY_PAGE = "page"
+ private const val KEY_IS_DEFAULT = "isDefault"
+ private const val KEY_DURATION = "durationMillis"
+ private const val KEY_ROTATION_DEGREES = "rotationDegrees"
+
+ fun getHeicTracks(context: Context, uri: Uri): ArrayList<FieldMap> {
+ val tracks = ArrayList<FieldMap>()
+ val extractor = MediaExtractor()
+ extractor.setDataSource(context, uri, null)
+ for (pageIndex in 0 until extractor.trackCount) {
+ try {
+ val format = extractor.getTrackFormat(pageIndex)
+ format.getString(MediaFormat.KEY_MIME)?.let { mime ->
+ val trackMime = if (mime == MediaFormat.MIMETYPE_IMAGE_ANDROID_HEIC) MimeTypes.HEIC else mime
+ val track: FieldMap = hashMapOf(
+ KEY_PAGE to pageIndex,
+ KEY_MIME_TYPE to trackMime,
+ )
+
+ // do not use `MediaFormat.KEY_TRACK_ID` as it is actually not unique between tracks
+ // e.g. there could be both a video track and an image track with KEY_TRACK_ID == 1
+
+ format.getSafeInt(MediaFormat.KEY_WIDTH) { track[KEY_WIDTH] = it }
+ format.getSafeInt(MediaFormat.KEY_HEIGHT) { track[KEY_HEIGHT] = it }
+ format.getSafeInt(MediaFormat.KEY_IS_DEFAULT) { track[KEY_IS_DEFAULT] = it != 0 }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ format.getSafeInt(MediaFormat.KEY_ROTATION) { track[KEY_ROTATION_DEGREES] = it }
+ }
+ if (MimeTypes.isVideo(trackMime)) {
+ format.getSafeLong(MediaFormat.KEY_DURATION) { track[KEY_DURATION] = it / 1000 }
+ }
+ tracks.add(track)
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get HEIC track information for uri=$uri, pageIndex=$pageIndex", e)
+ }
+ }
+ extractor.release()
+ return tracks
+ }
+
+ fun isIsoBMFFImageSefdMotionPhoto(context: Context, uri: Uri): Boolean {
+ return getIsoBMFFImageSefdMotionPhotoVideoSizing(context, uri) != null
+ }
+
+ private fun getIsoBMFFImageSefdMotionPhotoVideoSizing(context: Context, uri: Uri): Pair<Long, Long>? {
+ Mp4ParserHelper.getSamsungSefd(context, uri)?.let { (sefdOffset, sefdBytes) ->
+ // we could properly parse each tag until we find the "embedded video" tag (0x0a30)
+ // but it seems that decoding the SEFT trailer is necessary for this,
+ // so we simply search for the "MotionPhoto_Data" sequence instead
+ val name = Mp4ParserHelper.SEFD_MOTION_PHOTO_NAME
+ val index = sefdBytes.indexOfBytes(name.toByteArray(Charsets.UTF_8))
+ if (index != -1) {
+ val videoOffset = sefdOffset + index + name.length
+ val videoSize = sefdBytes.size - (videoOffset - sefdOffset)
+ return Pair(videoOffset, videoSize)
+ }
+ }
+ return null
+ }
+
+ private fun getJpegMpfPrimaryRotation(context: Context, uri: Uri, sizeBytes: Long): Int {
+ val mimeType = MimeTypes.JPEG
+ var rotationDegrees = 0
+
+ var foundExif = false
+ if (canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ foundExif = metadata.directories.any { it is ExifDirectoryBase && it.tagCount > 0 }
+ for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) {
+ dir.getSafeInt(ExifDirectoryBase.TAG_ORIENTATION) {
+ rotationDegrees = Metadata.getRotationDegreesForExifCode(it)
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ if (!foundExif) {
+ // fallback to read EXIF via ExifInterface
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val exif = ExifInterface(input)
+ exif.getSafeInt(ExifInterface.TAG_ORIENTATION, acceptZero = false) {
+ rotationDegrees = exif.rotationDegrees
+ }
+ }
+ } catch (e: Exception) {
+ // ExifInterface initialization can fail with a RuntimeException
+ // caused by an internal MediaMetadataRetriever failure
+ Log.w(LOG_TAG, "failed to get metadata by ExifInterface for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ return rotationDegrees
+ }
+
+ // starts after `[APP2 marker (1 byte)] [segment size (2 bytes)] [MPF marker (4 bytes)]`
+ fun getJpegMpfBaseOffset(context: Context, uri: Uri, sizeBytes: Long?): Int? {
+ val mimeType = MimeTypes.JPEG
+ val endMarker = 0xFF
+ val app2Marker = JpegSegmentType.APP2.byteValue
+ val mpfMarker = "MPF".toByteArray() + 0x00
+
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ var offset = 0
+ val marker = ByteArray(4)
+ while (true) {
+ // look for APP2 marker (0xFFE2)
+ var found = false
+ while (!found) {
+ var i = input.read()
+ if (i == -1) throw EOFException()
+ offset++
+ if (i == endMarker) {
+ i = input.read()
+ if (i == -1) throw EOFException()
+ offset++
+ found = i.toByte() == app2Marker
+ }
+ }
+ // skip 2 bytes for segment size
+ input.skip(2)
+ offset += 2
+ input.read(marker, 0, marker.size)
+ offset += 4
+ if (marker.contentEquals(mpfMarker)) {
+ return offset
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get MPF base offset from uri=$uri", e)
+ }
+ return null
+ }
+
+ fun getJpegMpfEntries(context: Context, uri: Uri, sizeBytes: Long?): List<MpEntry>? {
+ val mimeType = MimeTypes.JPEG
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ return metadata.getDirectoriesOfType(MpEntryDirectory::class.java).map { it.entry }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to find MPF entries", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to find MPF entries", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to find MPF entries", e)
+ }
+ return null
+ }
+
+ fun getJpegMpfPages(context: Context, uri: Uri, sizeBytes: Long): ArrayList<FieldMap> {
+ val primaryRotation = getJpegMpfPrimaryRotation(context, uri, sizeBytes)
+
+ val pages = ArrayList<FieldMap>()
+ val baseOffset = getJpegMpfBaseOffset(context, uri, sizeBytes)
+ val mpEntries = getJpegMpfEntries(context, uri, sizeBytes)
+ if (mpEntries != null && baseOffset != null) {
+ for ((pageIndex, mpEntry) in mpEntries.withIndex()) {
+ mpEntry.mimeType?.let { embedMimeType ->
+ val page = hashMapOf<String, Any?>(
+ KEY_PAGE to pageIndex,
+ KEY_MIME_TYPE to embedMimeType,
+ KEY_IS_DEFAULT to (pageIndex == 0),
+ KEY_ROTATION_DEGREES to primaryRotation,
+ )
+
+ var dataOffset = mpEntry.dataOffset
+ if (dataOffset > 0) {
+ dataOffset += baseOffset
+ }
+ StorageUtils.openInputStream(context, uri)?.let { input ->
+ input.skip(dataOffset)
+ val options = BitmapFactory.Options().apply {
+ inJustDecodeBounds = true
+ }
+ BitmapFactory.decodeStream(input, null, options)
+ options.outWidth.takeIf { it >= 0 }?.let { page[KEY_WIDTH] = it }
+ options.outHeight.takeIf { it >= 0 }?.let { page[KEY_HEIGHT] = it }
+
+ pages.add(page)
+ }
+ }
+ }
+ }
+
+ return pages
+ }
+
+ fun getJpegMpfBitmap(context: Context, uri: Uri, pageIndex: Int): Bitmap? {
+ val mpEntries = getJpegMpfEntries(context, uri, null)
+ if (mpEntries != null && pageIndex < mpEntries.size) {
+ val mpEntry = mpEntries[pageIndex]
+ var dataOffset = mpEntry.dataOffset
+ if (dataOffset > 0) {
+ val baseOffset = getJpegMpfBaseOffset(context, uri, null)
+ if (baseOffset != null) {
+ dataOffset += baseOffset
+ }
+ }
+ StorageUtils.openInputStream(context, uri)?.let { input ->
+ input.skip(dataOffset)
+ return BitmapFactory.decodeStream(input)
+ }
+ }
+ return null
+ }
+
+ fun getMotionPhotoPages(context: Context, uri: Uri, mimeType: String, sizeBytes: Long): ArrayList<FieldMap> {
+ val pages = ArrayList<FieldMap>()
+ getMotionPhotoVideoInfo(context, uri, mimeType, sizeBytes)?.let { videoInfo ->
+ // set the original image as the first and default track
+ var pageIndex = 0
+ pages.add(
+ hashMapOf(
+ KEY_PAGE to pageIndex++,
+ KEY_MIME_TYPE to mimeType,
+ KEY_IS_DEFAULT to true,
+ )
+ )
+ // add video tracks from the appended video
+ videoInfo.getString(MediaFormat.KEY_MIME)?.let { mime ->
+ if (MimeTypes.isVideo(mime)) {
+ val page: FieldMap = hashMapOf(
+ KEY_PAGE to pageIndex++,
+ KEY_MIME_TYPE to MimeTypes.MP4,
+ KEY_IS_DEFAULT to false,
+ )
+ videoInfo.getSafeInt(MediaFormat.KEY_WIDTH) { page[KEY_WIDTH] = it }
+ videoInfo.getSafeInt(MediaFormat.KEY_HEIGHT) { page[KEY_HEIGHT] = it }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ videoInfo.getSafeInt(MediaFormat.KEY_ROTATION) { page[KEY_ROTATION_DEGREES] = it }
+ }
+ videoInfo.getSafeLong(MediaFormat.KEY_DURATION) { page[KEY_DURATION] = it / 1000 }
+ pages.add(page)
+ }
+ }
+ }
+ return pages
+ }
+
+ fun getTrailerVideoSize(context: Context, uri: Uri, mimeType: String, sizeBytes: Long): Long? {
+ if (isHeic(mimeType)) {
+ // XMP in HEIC motion photos (as taken with a Samsung Camera v12.0.01.50) indicates an `Item:Length` of 68 bytes for the video.
+ // This item does not contain the video itself, but only some kind of metadata (no doc, no spec),
+ // so we ignore the `Item:Length` and look instead for the MP4 marker bytes indicating the start of the video.
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ if (MemoryUtils.canAllocate(sizeBytes)) {
+ val bytes = ByteArray(sizeBytes.toInt())
+ DataInputStream(input).use {
+ it.readFully(bytes)
+ }
+ val index = bytes.indexOfBytes(heicMotionPhotoVideoStartIndicator)
+ if (index != -1) {
+ return sizeBytes - index
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get motion photo offset from uri=$uri", e)
+ }
+ }
+
+ var offsetFromEnd: Long? = null
+ var foundXmp = false
+
+ fun processXmp(xmpMeta: XMPMeta) {
+ offsetFromEnd = offsetFromEnd ?: GoogleXMP.getTrailingVideoOffsetFromEnd(xmpMeta)
+ }
+
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+ foundXmp = metadata.directories.any { it is XmpDirectory && it.tagCount > 0 }
+ metadata.getDirectoriesOfType(XmpDirectory::class.java).map { it.xmpMeta }.forEach(::processXmp)
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get motion photo offset from uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to get motion photo offset from uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to get motion photo offset from uri=$uri", e)
+ }
+
+ XMP.checkIsoBMFFImage(context, mimeType, uri, foundXmp, ::processXmp)
+
+ return offsetFromEnd
+ }
+
+ private fun getMotionPhotoVideoInfo(context: Context, uri: Uri, mimeType: String, sizeBytes: Long): MediaFormat? {
+ getMotionPhotoVideoSizing(context, uri, mimeType, sizeBytes)?.let { (videoOffset, videoSize) ->
+ return getEmbedVideoInfo(context, uri, videoOffset, videoSize)
+ }
+ return null
+ }
+
+ fun getTrailerVideoInfo(context: Context, uri: Uri, fileSize: Long, videoSize: Long): MediaFormat? {
+ return getEmbedVideoInfo(context, uri, videoOffset = fileSize - videoSize, videoSize = videoSize)
+ }
+
+ private fun getEmbedVideoInfo(context: Context, uri: Uri, videoOffset: Long, videoSize: Long): MediaFormat? {
+ val extractor = MediaExtractor()
+ var pfd: ParcelFileDescriptor? = null
+ try {
+ pfd = context.contentResolver.openFileDescriptor(uri, "r")
+ pfd?.fileDescriptor?.let { fd ->
+ extractor.setDataSource(fd, videoOffset, videoSize)
+ // video track may be after an audio track
+ for (trackIndex in 0 until extractor.trackCount) {
+ try {
+ val format = extractor.getTrackFormat(trackIndex)
+ format.getString(MediaFormat.KEY_MIME)?.let {
+ if (MimeTypes.isVideo(it)) {
+ return format
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get track information for uri=$uri, track num=$trackIndex", e)
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to open motion photo for uri=$uri", e)
+ } finally {
+ extractor.release()
+ pfd?.close()
+ }
+ return null
+ }
+
+ fun getMotionPhotoVideoSizing(context: Context, uri: Uri, mimeType: String, sizeBytes: Long): Pair<Long, Long>? {
+ // default to trailer videos
+ getTrailerVideoSize(context, uri, mimeType, sizeBytes)?.let { videoSize ->
+ val videoOffset = sizeBytes - videoSize
+ return Pair(videoOffset, videoSize)
+ }
+
+ if (isIsoBMFFImage(mimeType)) {
+ // fallback to video within Samsung SEFD box
+ return getIsoBMFFImageSefdMotionPhotoVideoSizing(context, uri)
+ }
+
+ return null
+ }
+
+ fun getTiffPages(context: Context, uri: Uri): ArrayList<FieldMap> {
+ fun toMap(pageIndex: Int, options: TiffBitmapFactory.Options): FieldMap {
+ return hashMapOf(
+ KEY_PAGE to pageIndex,
+ KEY_MIME_TYPE to MimeTypes.TIFF,
+ KEY_WIDTH to options.outWidth,
+ KEY_HEIGHT to options.outHeight,
+ )
+ }
+
+ val pages = ArrayList<FieldMap>()
+ getTiffPageInfo(context, uri, 0)?.let { first ->
+ pages.add(toMap(0, first))
+ val pageCount = first.outDirectoryCount
+ for (pageIndex in 1 until pageCount) {
+ getTiffPageInfo(context, uri, pageIndex)?.let { pages.add(toMap(pageIndex, it)) }
+ }
+ }
+ return pages
+ }
+
+ fun isMultiPageTiff(context: Context, uri: Uri) = (getTiffPageInfo(context, uri, 0)?.outDirectoryCount ?: 1) > 1
+
+ private fun getTiffPageInfo(context: Context, uri: Uri, page: Int): TiffBitmapFactory.Options? {
+ try {
+ val fd = context.contentResolver.openFileDescriptor(uri, "r")?.detachFd()
+ if (fd == null) {
+ Log.w(LOG_TAG, "failed to get TIFF file descriptor for uri=$uri")
+ return null
+ }
+ val options = TiffFetcher.buildOptions().apply {
+ inJustDecodeBounds = true
+ inDirectoryNumber = page
+ }
+ TiffBitmapFactory.decodeFileDescriptor(fd, options)
+ return options
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get TIFF page info for uri=$uri page=$page", e)
+ }
+ return null
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiTrackMedia.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiTrackMedia.kt
new file mode 100644
index 0000000..d73bbe8
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/MultiTrackMedia.kt
@@ -0,0 +1,59 @@
+package deckers.thibault.aves.metadata
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.media.MediaExtractor
+import android.media.MediaFormat
+import android.net.Uri
+import android.os.Build
+import android.util.Log
+import androidx.annotation.RequiresApi
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.StorageUtils
+
+object MultiTrackMedia {
+ private val LOG_TAG = LogUtils.createTag<MultiTrackMedia>()
+
+ @RequiresApi(Build.VERSION_CODES.P)
+ fun getImage(context: Context, uri: Uri, trackIndex: Int?): Bitmap? {
+ val retriever = StorageUtils.openMetadataRetriever(context, uri) ?: return null
+ try {
+ return if (trackIndex != null) {
+ val imageIndex = trackIndexToImageIndex(context, uri, trackIndex) ?: return null
+ retriever.getImageAtIndex(imageIndex)
+ } else {
+ retriever.primaryImage
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to extract image from uri=$uri trackIndex=$trackIndex", e)
+ } finally {
+ // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs
+ retriever.release()
+ }
+ return null
+ }
+
+ private fun trackIndexToImageIndex(context: Context, uri: Uri, trackIndex: Int): Int? {
+ val extractor = MediaExtractor()
+ try {
+ extractor.setDataSource(context, uri, null)
+ val trackCount = extractor.trackCount
+ var imageIndex = 0
+ for (i in 0 until trackCount) {
+ val trackFormat = extractor.getTrackFormat(i)
+ if (trackIndex == i) {
+ return imageIndex
+ }
+ if (MimeTypes.isImage(trackFormat.getString(MediaFormat.KEY_MIME))) {
+ imageIndex++
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get image index for uri=$uri, trackIndex=$trackIndex", e)
+ } finally {
+ extractor.release()
+ }
+ return null
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/PixyMetaHelper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/PixyMetaHelper.kt
new file mode 100644
index 0000000..2f3b17a
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/PixyMetaHelper.kt
@@ -0,0 +1,172 @@
+package deckers.thibault.aves.metadata
+
+import android.content.Context
+import android.net.Uri
+import deckers.thibault.aves.metadata.Metadata.TYPE_COMMENT
+import deckers.thibault.aves.metadata.Metadata.TYPE_EXIF
+import deckers.thibault.aves.metadata.Metadata.TYPE_ICC_PROFILE
+import deckers.thibault.aves.metadata.Metadata.TYPE_IPTC
+import deckers.thibault.aves.metadata.Metadata.TYPE_JFIF
+import deckers.thibault.aves.metadata.Metadata.TYPE_JPEG_ADOBE
+import deckers.thibault.aves.metadata.Metadata.TYPE_JPEG_DUCKY
+import deckers.thibault.aves.metadata.Metadata.TYPE_PHOTOSHOP_IRB
+import deckers.thibault.aves.metadata.Metadata.TYPE_XMP
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.StorageUtils
+import pixy.meta.meta.Metadata
+import pixy.meta.meta.MetadataEntry
+import pixy.meta.meta.MetadataType
+import pixy.meta.meta.iptc.IPTC
+import pixy.meta.meta.iptc.IPTCDataSet
+import pixy.meta.meta.iptc.IPTCRecord
+import pixy.meta.meta.jpeg.JPGMeta
+import pixy.meta.meta.xmp.XMP
+import pixy.meta.string.XMLUtils
+import java.io.File
+import java.io.InputStream
+import java.io.OutputStream
+
+object PixyMetaHelper {
+ fun describe(input: InputStream): HashMap<String, String> {
+ val metadataMap = HashMap<String, String>()
+
+ fun fetch(parents: String, entries: Iterable<MetadataEntry>) {
+ for (entry in entries) {
+ metadataMap["$parents ${entry.key}"] = entry.value
+ if (entry.isMetadataEntryGroup) {
+ fetch("$parents ${entry.key} /", entry.metadataEntries)
+ }
+ }
+ }
+
+ val metadataByType = Metadata.readMetadata(input)
+ for ((type, metadata) in metadataByType.entries) {
+ if (type == MetadataType.XMP) {
+ val xmp = metadataByType[MetadataType.XMP] as XMP?
+ if (xmp != null) {
+ metadataMap["XMP"] = xmp.xmpDocString()
+ if (xmp.hasExtendedXmp()) {
+ metadataMap["XMP extended"] = xmp.extendedXmpDocString()
+ }
+ }
+ } else {
+ fetch("$type /", metadata)
+ }
+ }
+
+ return metadataMap
+ }
+
+ fun getIptc(input: InputStream): List<FieldMap>? {
+ val iptc = Metadata.readMetadata(input)[MetadataType.IPTC] as IPTC? ?: return null
+
+ val iptcDataList = ArrayList<FieldMap>()
+ iptc.dataSets.forEach { dataSetEntry ->
+ val tag = dataSetEntry.key
+ val dataSets = dataSetEntry.value
+ iptcDataList.add(
+ hashMapOf(
+ "record" to tag.recordNumber,
+ "tag" to tag.tag,
+ "values" to dataSets.map { it.data }.toMutableList(),
+ )
+ )
+ }
+ return iptcDataList
+ }
+
+ fun setIptc(
+ input: InputStream,
+ output: OutputStream,
+ iptcDataList: List<FieldMap>?,
+ ) {
+ val iptc: List<IPTCDataSet> = iptcDataList?.flatMap {
+ val record = it["record"] as Int
+ val tag = it["tag"] as Int
+ val values = it["values"] as List<*>
+ values.map { data -> IPTCDataSet(IPTCRecord.fromRecordNumber(record), tag, data as ByteArray) }
+ } ?: ArrayList()
+ Metadata.insertIPTC(input, output, iptc)
+ }
+
+ fun getXmp(input: InputStream): XMP? = Metadata.readMetadata(input)[MetadataType.XMP] as XMP?
+
+ // PixyMeta may fail with just a log, and write nothing to the output
+ fun setXmp(
+ input: InputStream,
+ output: OutputStream,
+ xmpString: String?,
+ extendedXmpString: String?
+ ) {
+ if (extendedXmpString != null) {
+ JPGMeta.insertXMP(input, output, xmpString, extendedXmpString)
+ } else {
+ Metadata.insertXMP(input, output, xmpString)
+ }
+ }
+
+ fun XMP.xmpDocString(): String = XMLUtils.serializeToString(xmpDocument)
+
+ fun XMP.extendedXmpDocString(): String = XMLUtils.serializeToString(extendedXmpDocument)
+
+ fun copyIptcXmp(
+ context: Context,
+ sourceMimeType: String,
+ sourceUri: Uri,
+ targetMimeType: String,
+ targetUri: Uri,
+ editableFile: File,
+ ) {
+ var pixyIptc: IPTC? = null
+ var pixyXmp: XMP? = null
+ if (MimeTypes.canReadWithPixyMeta(sourceMimeType)) {
+ StorageUtils.openInputStream(context, sourceUri)?.use { input ->
+ val metadata = Metadata.readMetadata(input)
+ if (MimeTypes.canEditIptc(targetMimeType)) {
+ pixyIptc = metadata[MetadataType.IPTC] as IPTC?
+ }
+ if (MimeTypes.canEditXmp(targetMimeType)) {
+ pixyXmp = metadata[MetadataType.XMP] as XMP?
+ }
+ }
+ }
+ if (pixyIptc != null || pixyXmp != null) {
+ editableFile.outputStream().use { output ->
+ if (pixyIptc != null) {
+ // reopen input to read from start
+ StorageUtils.openInputStream(context, targetUri)?.use { input ->
+ val iptcs = pixyIptc!!.dataSets.flatMap { it.value }
+ Metadata.insertIPTC(input, output, iptcs)
+ }
+ }
+ if (pixyXmp != null) {
+ // reopen input to read from start
+ StorageUtils.openInputStream(context, targetUri)?.use { input ->
+ val xmpString = pixyXmp!!.xmpDocString()
+ val extendedXmp = if (pixyXmp!!.hasExtendedXmp()) pixyXmp!!.extendedXmpDocString() else null
+ setXmp(input, output, xmpString, if (targetMimeType == MimeTypes.JPEG) extendedXmp else null)
+ }
+ }
+ }
+ }
+ }
+
+ fun removeMetadata(input: InputStream, output: OutputStream, metadataTypes: Set<String>) {
+ val types = metadataTypes.map(::toMetadataType).toTypedArray()
+ Metadata.removeMetadata(input, output, *types)
+ }
+
+ private fun toMetadataType(typeString: String): MetadataType? = when (typeString) {
+ TYPE_COMMENT -> MetadataType.COMMENT
+ TYPE_EXIF -> MetadataType.EXIF
+ TYPE_ICC_PROFILE -> MetadataType.ICC_PROFILE
+ TYPE_IPTC -> MetadataType.IPTC
+ TYPE_JFIF -> MetadataType.JPG_JFIF
+ TYPE_JPEG_ADOBE -> MetadataType.JPG_ADOBE
+ TYPE_JPEG_DUCKY -> MetadataType.JPG_DUCKY
+ TYPE_PHOTOSHOP_IRB -> MetadataType.PHOTOSHOP_IRB
+ TYPE_XMP -> MetadataType.XMP
+ else -> null
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/QuickTimeMetadata.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/QuickTimeMetadata.kt
new file mode 100644
index 0000000..e9b2206
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/QuickTimeMetadata.kt
@@ -0,0 +1,99 @@
+package deckers.thibault.aves.metadata
+
+import deckers.thibault.aves.utils.toHex
+import java.math.BigInteger
+import java.nio.charset.Charset
+
+class QuickTimeMetadataBlock(val type: String, val value: String, val language: String)
+
+object QuickTimeMetadata {
+ // QuickTime Profile Tags
+ // cf https://exiftool.org/TagNames/QuickTime.html#Profile
+ const val PROF_UUID = "50524f46-21d2-4fce-bb88-695cfac9c740"
+
+ // QuickTime UserMedia Tags
+ // cf https://exiftool.org/TagNames/QuickTime.html#UserMedia
+ const val USMT_UUID = "55534d54-21d2-4fce-bb88-695cfac9c740"
+
+ private const val METADATA_BOX_ID = "MTDT"
+
+ fun parseUuidUsmt(data: ByteArray): List<QuickTimeMetadataBlock> {
+ val blocks = ArrayList<QuickTimeMetadataBlock>()
+ val boxHeader = BoxHeader(data)
+ if (boxHeader.boxType == METADATA_BOX_ID) {
+ blocks.addAll(parseQuicktimeMtdtBox(boxHeader, data))
+ }
+ return blocks
+ }
+
+ private fun parseQuicktimeMtdtBox(boxHeader: BoxHeader, data: ByteArray): List<QuickTimeMetadataBlock> {
+ val blocks = ArrayList<QuickTimeMetadataBlock>()
+ var bytes = data
+ val blockCount = BigInteger(bytes.copyOfRange(8, 10)).toInt()
+ bytes = bytes.copyOfRange(10, boxHeader.boxDataSize)
+
+ for (i in 0 until blockCount) {
+ val blockSize = BigInteger(bytes.copyOfRange(0, 2)).toInt()
+ val blockType = BigInteger(bytes.copyOfRange(2, 6)).toInt()
+ val language = parseLanguage(bytes.copyOfRange(6, 8))
+ val encoding = BigInteger(bytes.copyOfRange(8, 10)).toInt()
+ val payload = bytes.copyOfRange(10, blockSize)
+
+ val payloadString = when (encoding) {
+ // 0x00: short array
+ 0x00 -> {
+ payload
+ .asList()
+ .chunked(2)
+ .map { (h, l) -> ((h.toInt() shl 8) + l.toInt()).toShort() }
+ .joinToString()
+ }
+ // 0x01: string
+ 0x01 -> String(payload, Charset.forName("UTF-16BE")).trim()
+ // 0x101: artwork/icon
+ else -> "0x${payload.toHex()}"
+ }
+
+ val blockTypeString = when (blockType) {
+ 0x01 -> "Title"
+ 0x03 -> "Creation Time"
+ 0x04 -> "Software"
+ 0x0A -> "Track property"
+ 0x0B -> "Time zone"
+ 0x0C -> "Modification Time"
+ else -> "0x${blockType.toByte().toHex()}"
+ }
+
+ blocks.add(
+ QuickTimeMetadataBlock(
+ type = blockTypeString,
+ value = payloadString,
+ language = language,
+ )
+ )
+ bytes = bytes.copyOfRange(blockSize, bytes.size)
+ }
+
+ return blocks
+ }
+
+ // ISO 639 language code written as 3 groups of 5 bits for each letter (ascii code - 0x60)
+ // e.g. 0x55c4 -> 10101 01110 00100 -> 21 14 4 -> "und"
+ private fun parseLanguage(bytes: ByteArray): String {
+ val i = BigInteger(bytes).toInt()
+ val c1 = Character.toChars((i shr 10 and 0x1F) + 0x60)[0]
+ val c2 = Character.toChars((i shr 5 and 0x1F) + 0x60)[0]
+ val c3 = Character.toChars((i and 0x1F) + 0x60)[0]
+ return "$c1$c2$c3"
+ }
+}
+
+class BoxHeader(bytes: ByteArray) {
+ var boxDataSize: Int = 0
+ var boxType: String
+
+ init {
+ boxDataSize = BigInteger(bytes.copyOfRange(0, 4)).toInt()
+ boxType = String(bytes.copyOfRange(4, 8))
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SphericalVideo.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SphericalVideo.kt
new file mode 100644
index 0000000..783e4b2
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SphericalVideo.kt
@@ -0,0 +1,109 @@
+package deckers.thibault.aves.metadata
+
+import android.util.Log
+import android.util.Xml
+import deckers.thibault.aves.utils.LogUtils
+import org.xmlpull.v1.XmlPullParser
+import java.io.ByteArrayInputStream
+
+// `xmlBytes`: bytes representing the XML embedded in a MP4 `uuid` box, according to Spherical Video V1 spec
+class GSpherical(xmlBytes: ByteArray) {
+ private var spherical: Boolean = false
+ private var stitched: Boolean = false
+ private var stitchingSoftware: String = ""
+ private var projectionType: String = ""
+ private var stereoMode: String? = null
+ private var sourceCount: Int? = null
+ private var initialViewHeadingDegrees: Int? = null
+ private var initialViewPitchDegrees: Int? = null
+ private var initialViewRollDegrees: Int? = null
+ private var timestamp: Int? = null
+ private var fullPanoWidthPixels: Int? = null
+ private var fullPanoHeightPixels: Int? = null
+ private var croppedAreaImageWidthPixels: Int? = null
+ private var croppedAreaImageHeightPixels: Int? = null
+ private var croppedAreaLeftPixels: Int? = null
+ private var croppedAreaTopPixels: Int? = null
+
+ init {
+ try {
+ ByteArrayInputStream(xmlBytes).use {
+ val parser = Xml.newPullParser().apply {
+ setInput(it, null)
+ nextTag()
+ require(XmlPullParser.START_TAG, RDF_NS, "SphericalVideo")
+ }
+ while (parser.next() != XmlPullParser.END_TAG) {
+ if (parser.eventType != XmlPullParser.START_TAG) continue
+ if (parser.namespace == GSPHERICAL_NS) {
+ when (val tag = parser.name) {
+ "Spherical" -> spherical = readTag(parser, tag) == "true"
+ "Stitched" -> stitched = readTag(parser, tag) == "true"
+ "StitchingSoftware" -> stitchingSoftware = readTag(parser, tag)
+ "ProjectionType" -> projectionType = readTag(parser, tag)
+ "StereoMode" -> stereoMode = readTag(parser, tag)
+ "SourceCount" -> sourceCount = readTag(parser, tag).toInt()
+ "InitialViewHeadingDegrees" -> initialViewHeadingDegrees = readTag(parser, tag).toInt()
+ "InitialViewPitchDegrees" -> initialViewPitchDegrees = readTag(parser, tag).toInt()
+ "InitialViewRollDegrees" -> initialViewRollDegrees = readTag(parser, tag).toInt()
+ "Timestamp" -> timestamp = readTag(parser, tag).toInt()
+ "FullPanoWidthPixels" -> fullPanoWidthPixels = readTag(parser, tag).toInt()
+ "FullPanoHeightPixels" -> fullPanoHeightPixels = readTag(parser, tag).toInt()
+ "CroppedAreaImageWidthPixels" -> croppedAreaImageWidthPixels = readTag(parser, tag).toInt()
+ "CroppedAreaImageHeightPixels" -> croppedAreaImageHeightPixels = readTag(parser, tag).toInt()
+ "CroppedAreaLeftPixels" -> croppedAreaLeftPixels = readTag(parser, tag).toInt()
+ "CroppedAreaTopPixels" -> croppedAreaTopPixels = readTag(parser, tag).toInt()
+ }
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to parse XML", e)
+ }
+ }
+
+ fun describe(): Map<String, String> = hashMapOf(
+ "Spherical" to spherical.toString(),
+ "Stitched" to stitched.toString(),
+ "Stitching Software" to stitchingSoftware,
+ "Projection Type" to projectionType,
+ "Stereo Mode" to stereoMode,
+ "Source Count" to sourceCount?.toString(),
+ "Initial View Heading Degrees" to initialViewHeadingDegrees?.toString(),
+ "Initial View Pitch Degrees" to initialViewPitchDegrees?.toString(),
+ "Initial View Roll Degrees" to initialViewRollDegrees?.toString(),
+ "Timestamp" to timestamp?.toString(),
+ "Full Panorama Width Pixels" to fullPanoWidthPixels?.toString(),
+ "Full Panorama Height Pixels" to fullPanoHeightPixels?.toString(),
+ "Cropped Area Image Width Pixels" to croppedAreaImageWidthPixels?.toString(),
+ "Cropped Area Image Height Pixels" to croppedAreaImageHeightPixels?.toString(),
+ "Cropped Area Left Pixels" to croppedAreaLeftPixels?.toString(),
+ "Cropped Area Top Pixels" to croppedAreaTopPixels?.toString(),
+ ).filterValues { it != null }.mapValues { it.value as String }
+
+ companion object SphericalVideo {
+ private val LOG_TAG = LogUtils.createTag<SphericalVideo>()
+
+ // cf https://github.com/google/spatial-media
+ const val SPHERICAL_VIDEO_V1_UUID = "ffcc8263-f855-4a93-8814-587a02521fdd"
+
+ const val RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+ const val GSPHERICAL_NS = "http://ns.google.com/videos/1.0/spherical/"
+
+ private fun readText(parser: XmlPullParser): String {
+ var text = ""
+ if (parser.next() == XmlPullParser.TEXT) {
+ text = parser.text
+ parser.nextTag()
+ }
+ return text
+ }
+
+ private fun readTag(parser: XmlPullParser, tag: String): String {
+ parser.require(XmlPullParser.START_TAG, GSPHERICAL_NS, tag)
+ val text = readText(parser)
+ parser.require(XmlPullParser.END_TAG, GSPHERICAL_NS, tag)
+ return text
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SvgHelper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SvgHelper.kt
new file mode 100644
index 0000000..a170e4e
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/SvgHelper.kt
@@ -0,0 +1,33 @@
+package deckers.thibault.aves.metadata
+
+import com.caverock.androidsvg.SVG
+import java.io.BufferedInputStream
+import java.io.InputStream
+import kotlin.math.max
+
+object SvgHelper {
+ const val IMAGE_BASE64_SIZE_DANGER_THRESHOLD: Long = 5 * (1 shl 20) // MB
+
+ fun SVG.normalizeSize() {
+ if (documentViewBox == null) {
+ setDocumentViewBox(0f, 0f, documentWidth, documentHeight)
+ }
+ setDocumentWidth("100%")
+ setDocumentHeight("100%")
+ }
+}
+
+// As of AndroidSVG v1.4, SVGParser.ENTITY_WATCH_BUFFER_SIZE is set at 4096.
+// This constant is not configurable and used for the internal buffer mark read limit.
+// Parsing will fail if the SVG header is larger than this value.
+// So we define and apply a minimum read limit.
+class SVGParserBufferedInputStream(input: InputStream) : BufferedInputStream(input) {
+ @Synchronized
+ override fun mark(readlimit: Int) {
+ super.mark(max(MINIMUM_READ_LIMIT, readlimit))
+ }
+
+ companion object {
+ private const val MINIMUM_READ_LIMIT = 1 shl 14 // 16kB
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/Helper.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/Helper.kt
new file mode 100644
index 0000000..748cba1
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/Helper.kt
@@ -0,0 +1,403 @@
+package deckers.thibault.aves.metadata.metadataextractor
+
+import android.util.Log
+import com.drew.imaging.FileType
+import com.drew.imaging.FileTypeDetector
+import com.drew.imaging.ImageMetadataReader
+import com.drew.imaging.ImageProcessingException
+import com.drew.imaging.jpeg.JpegMetadataReader
+import com.drew.imaging.jpeg.JpegSegmentMetadataReader
+import com.drew.imaging.mp4.Mp4Reader
+import com.drew.imaging.tiff.TiffProcessingException
+import com.drew.imaging.tiff.TiffReader
+import com.drew.lang.ByteArrayReader
+import com.drew.lang.RandomAccessStreamReader
+import com.drew.lang.Rational
+import com.drew.lang.SequentialByteArrayReader
+import com.drew.metadata.Directory
+import com.drew.metadata.StringValue
+import com.drew.metadata.exif.ExifDirectoryBase
+import com.drew.metadata.exif.ExifIFD0Directory
+import com.drew.metadata.exif.ExifReader
+import com.drew.metadata.exif.ExifSubIFDDirectory
+import com.drew.metadata.file.FileTypeDirectory
+import com.drew.metadata.iptc.IptcReader
+import com.drew.metadata.png.PngDirectory
+import com.drew.metadata.xmp.XmpReader
+import deckers.thibault.aves.metadata.ExifGeoTiffTags
+import deckers.thibault.aves.metadata.GeoTiffKeys
+import deckers.thibault.aves.metadata.Metadata
+import deckers.thibault.aves.metadata.metadataextractor.mpf.MpfReader
+import deckers.thibault.aves.utils.LogUtils
+import java.io.BufferedInputStream
+import java.io.IOException
+import java.io.InputStream
+import java.text.ParseException
+import java.text.SimpleDateFormat
+import java.util.Calendar
+import java.util.Date
+import java.util.GregorianCalendar
+import java.util.Locale
+import java.util.TimeZone
+import java.util.regex.Pattern
+
+object Helper {
+ private val LOG_TAG = LogUtils.createTag<Helper>()
+
+ const val PNG_ITXT_DIR_NAME = "PNG-iTXt"
+ private const val PNG_TEXT_DIR_NAME = "PNG-tEXt"
+ const val PNG_TIME_DIR_NAME = "PNG-tIME"
+ private const val PNG_ZTXT_DIR_NAME = "PNG-zTXt"
+ private const val PNG_RAW_PROFILE_EXIF = "Raw profile type exif"
+ private const val PNG_RAW_PROFILE_IPTC = "Raw profile type iptc"
+
+ val PNG_LAST_MODIFICATION_TIME_FORMAT = SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.ROOT)
+
+ // Pattern to extract profile name, length, and text data
+ // of raw profiles (EXIF, IPTC, etc.) in PNG `zTXt` chunks
+ // e.g. "iptc [...] 114 [...] 3842494d040400[...]"
+ // e.g. "exif [...] 134 [...] 4578696600004949[...]"
+ private val PNG_RAW_PROFILE_PATTERN = Regex("^\\n(.*?)\\n\\s*(\\d+)\\n(.*)", RegexOption.DOT_MATCHES_ALL)
+
+ fun readMimeType(input: InputStream): String? {
+ val bufferedInputStream = if (input is BufferedInputStream) input else BufferedInputStream(input)
+ return FileTypeDetector.detectFileType(bufferedInputStream).mimeType
+ }
+
+ @Throws(IOException::class, ImageProcessingException::class)
+ fun safeRead(input: InputStream, @Suppress("unused_parameter") sizeBytes: Long?): com.drew.metadata.Metadata {
+ val inputStream = if (input is BufferedInputStream) input else BufferedInputStream(input)
+ val fileType = FileTypeDetector.detectFileType(inputStream)
+
+ // Providing the stream length is risky, as it may crash if it is incorrect.
+ // Not providing the stream length is also risky, as it may lead to OOM
+ // when `RandomAccessStreamReader` reads the entire stream to validate offsets.
+ val undefinedStreamLength = -1L
+
+ val metadata = when (fileType) {
+ FileType.Jpeg -> safeReadJpeg(inputStream)
+ FileType.Mp4 -> safeReadMp4(inputStream)
+ FileType.Png -> safeReadPng(inputStream)
+ FileType.Psd -> safeReadPsd(inputStream)
+ FileType.Tiff,
+ FileType.Arw,
+ FileType.Cr2,
+ FileType.Nef,
+ FileType.Orf,
+ FileType.Rw2 -> safeReadTiff(inputStream, undefinedStreamLength)
+
+ else -> ImageMetadataReader.readMetadata(inputStream, undefinedStreamLength, fileType)
+ }
+
+ metadata.addDirectory(FileTypeDirectory(fileType))
+ return metadata
+ }
+
+ // Some JPEG, TIFF, MP4 (and other types?) contain XMP with a preposterous number of `DocumentAncestors`.
+ // This bloated XMP is unsafely loaded in memory by Adobe's `XMPMetaParser.parseInputSource`
+ // which easily yields OOM on Android, so we try to detect and strip extended XMP with a modified XMP reader.
+ private fun safeReadJpeg(input: InputStream): com.drew.metadata.Metadata {
+ val readers = ArrayList<JpegSegmentMetadataReader>().apply {
+ addAll(JpegMetadataReader.ALL_READERS.filter { it !is XmpReader })
+ add(SafeXmpReader())
+ add(MpfReader())
+ }
+
+ val metadata = com.drew.metadata.Metadata()
+ JpegMetadataReader.process(metadata, input, readers)
+ return metadata
+ }
+
+ private fun safeReadPng(input: InputStream): com.drew.metadata.Metadata {
+ return SafePngMetadataReader.readMetadata(input)
+ }
+
+ private fun safeReadPsd(input: InputStream): com.drew.metadata.Metadata {
+ return SafePsdMetadataReader.readMetadata(input)
+ }
+
+ @Throws(IOException::class, TiffProcessingException::class)
+ fun safeReadTiff(input: InputStream, streamLength: Long): com.drew.metadata.Metadata {
+ val reader = RandomAccessStreamReader(input, RandomAccessStreamReader.DEFAULT_CHUNK_LENGTH, streamLength)
+ val metadata = com.drew.metadata.Metadata()
+ val handler = SafeExifTiffHandler(metadata, null, 0)
+ TiffReader().processTiff(reader, handler, 0)
+ return metadata
+ }
+
+ private fun safeReadMp4(input: InputStream): com.drew.metadata.Metadata {
+ val metadata = com.drew.metadata.Metadata()
+ Mp4Reader.extract(input, SafeMp4BoxHandler(metadata))
+ return metadata
+ }
+
+ // extensions
+
+ fun Directory.getSafeString(tag: Int, acceptBlank: Boolean = true, save: (value: String) -> Unit) {
+ if (this.containsTag(tag)) {
+ val string = this.getString(tag)
+ if (acceptBlank || string.isNotBlank()) {
+ save(string)
+ }
+ }
+ }
+
+ fun Directory.getSafeBoolean(tag: Int, save: (value: Boolean) -> Unit) {
+ if (this.containsTag(tag)) save(this.getBoolean(tag))
+ }
+
+ fun Directory.getSafeInt(tag: Int, save: (value: Int) -> Unit) {
+ if (this.containsTag(tag)) save(this.getInt(tag))
+ }
+
+ fun Directory.getSafeLong(tag: Int, save: (value: Long) -> Unit) {
+ if (this.containsTag(tag)) save(this.getLong(tag))
+ }
+
+ fun Directory.getSafeRational(tag: Int, save: (value: Rational) -> Unit) {
+ if (this.containsTag(tag)) save(this.getRational(tag))
+ }
+
+ fun Directory.getSafeDateMillis(tag: Int, subSecond: String?): Long? {
+ if (this.containsTag(tag)) {
+ val date = this.getDatePlus(tag, subSecond, TimeZone.getDefault())
+ if (date != null) return date.time
+ }
+ return null
+ }
+
+ // This seems to cover all known Exif and Xmp date strings
+ // Note that " : : : : " is a valid date string according to the Exif spec (which means 'unknown date'): http://www.awaresystems.be/imaging/tiff/tifftags/privateifd/exif/datetimeoriginal.html
+ private val dateFormats = arrayOf(
+ "yyyy:MM:dd HH:mm:ss",
+ "yyyy:MM:dd HH:mm",
+ "yyyy-MM-dd HH:mm:ss",
+ "yyyy-MM-dd HH:mm",
+ "yyyy.MM.dd HH:mm:ss",
+ "yyyy.MM.dd HH:mm",
+ "yyyy-MM-dd'T'HH:mm:ss",
+ "yyyy-MM-dd'T'HH:mm",
+ "yyyy-MM-dd",
+ "yyyy-MM",
+ "yyyyMMdd", // as used in IPTC data
+ "yyyy"
+ ).map { SimpleDateFormat(it, Locale.ROOT) }.toTypedArray()
+ private val subsecondPattern = Pattern.compile("(\\d\\d:\\d\\d:\\d\\d)(\\.\\d+)")
+ private val timeZonePattern = Pattern.compile("(Z|[+-]\\d\\d:\\d\\d|[+-]\\d\\d\\d\\d)$")
+ private val calendar: Calendar = GregorianCalendar()
+ private const val PARSED_DATE_YEAR_MAX = 10000
+
+ // adapted from `metadata-extractor` v2.18.0 `Directory.getDate()`
+ // to also parse dates written as timestamps
+ private fun Directory.getDatePlus(tagType: Int, subSecond: String?, timeZone: TimeZone?): Date? {
+ var effectiveSubSecond = subSecond
+ var effectiveTimeZone = timeZone
+ val o = this.getObject(tagType)
+ if (o is Date) return o
+
+ var date: Date? = null
+ if (o is String || o is StringValue) {
+ var dateString = o.toString()
+
+ // if the date string has subsecond information, it supersedes the subsecond parameter
+ val subsecondMatcher = subsecondPattern.matcher(dateString)
+ if (subsecondMatcher.find()) {
+ effectiveSubSecond = subsecondMatcher.group(2)?.substring(1)
+ dateString = subsecondMatcher.replaceAll("$1")
+ }
+
+ // if the date string has time zone information, it supersedes the timeZone parameter
+ val timeZoneMatcher = timeZonePattern.matcher(dateString)
+ if (timeZoneMatcher.find()) {
+ effectiveTimeZone = TimeZone.getTimeZone("GMT" + timeZoneMatcher.group().replace("Z".toRegex(), ""))
+ dateString = timeZoneMatcher.replaceAll("")
+ }
+ for (dateFormat in dateFormats) {
+ try {
+ dateFormat.timeZone = effectiveTimeZone ?: TimeZone.getTimeZone("GMT") // don't interpret zone time
+ val parsed = dateFormat.parse(dateString)
+ if (parsed != null) {
+ calendar.time = parsed
+ if (calendar.get(Calendar.YEAR) < PARSED_DATE_YEAR_MAX) {
+ date = parsed
+ break
+ }
+ }
+ } catch (_: ParseException) {
+ // simply try the next pattern
+ }
+ }
+ if (date == null) {
+ val dateLong = dateString.toLongOrNull()
+ if (dateLong != null) {
+ val epochTimeMillis = when (dateLong) {
+ in 0..99999999999 -> dateLong * 1000 // seconds
+ in 100000000000..99999999999999 -> dateLong // millis
+ in 100000000000000..9999999999999999 -> dateLong / 1000 // micros
+ else -> dateLong / 1000000 // nanos
+ }
+ date = Date(epochTimeMillis)
+ }
+ }
+ }
+ if (date == null) return null
+
+ if (effectiveSubSecond != null) {
+ try {
+ val millisecond = (".$effectiveSubSecond".toDouble() * 1000).toInt()
+ if (millisecond in 0..999) {
+ val calendar = Calendar.getInstance()
+ calendar.time = date
+ calendar[Calendar.MILLISECOND] = millisecond
+ return calendar.time
+ }
+ } catch (_: NumberFormatException) {
+ // ignore
+ }
+ }
+ return date
+ }
+
+ // time tag and sub-second tag are *not* in the same directory
+ fun ExifSubIFDDirectory.getDateModifiedMillis(save: (value: Long) -> Unit) {
+ val parent = parent
+ if (parent is ExifIFD0Directory) {
+ val subSecond = getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME)
+ val dateMillis = parent.getSafeDateMillis(ExifIFD0Directory.TAG_DATETIME, subSecond)
+ if (dateMillis != null) save(dateMillis)
+ }
+ }
+
+ fun ExifSubIFDDirectory.getDateDigitizedMillis(save: (value: Long) -> Unit) {
+ val subSecond = getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME_DIGITIZED)
+ val dateMillis = this.getSafeDateMillis(ExifSubIFDDirectory.TAG_DATETIME_DIGITIZED, subSecond)
+ if (dateMillis != null) save(dateMillis)
+ }
+
+ fun ExifSubIFDDirectory.getDateOriginalMillis(save: (value: Long) -> Unit) {
+ val subSecond = getString(ExifSubIFDDirectory.TAG_SUBSECOND_TIME_ORIGINAL)
+ val dateMillis = this.getSafeDateMillis(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL, subSecond)
+ if (dateMillis != null) save(dateMillis)
+ }
+
+ // geotiff
+
+ /*
+ cf http://docs.opengeospatial.org/is/19-008r4/19-008r4.html#_underlying_tiff_requirements
+ - One of ModelTiepointTag or ModelTransformationTag SHALL be included in an Image File Directory (IFD)
+ - If the ModelTransformationTag is included in an IFD, then a ModelPixelScaleTag SHALL NOT be included
+ - If the ModelPixelScaleTag is included in an IFD, then a ModelTiepointTag SHALL also be included.
+ */
+ fun ExifDirectoryBase.containsGeoTiffTags(): Boolean {
+ if (!this.containsTag(ExifGeoTiffTags.TAG_GEO_KEY_DIRECTORY)) return false
+
+ val modelTiePoints = this.containsTag(ExifGeoTiffTags.TAG_MODEL_TIE_POINT)
+ val modelTransformation = this.containsTag(ExifGeoTiffTags.TAG_MODEL_TRANSFORMATION)
+ if (!modelTiePoints && !modelTransformation) return false
+
+ val modelPixelScale = this.containsTag(ExifGeoTiffTags.TAG_MODEL_PIXEL_SCALE)
+ return !((modelTransformation && modelPixelScale) || (modelPixelScale && !modelTiePoints))
+ }
+
+ // TODO TLAD use `GeoTiffDirectory` from the Java version of `metadata-extractor` when available
+ // adapted from https://github.com/drewnoakes/metadata-extractor-dotnet/blob/master/MetadataExtractor/Formats/Exif/ExifTiffHandler.cs
+ fun ExifIFD0Directory.extractGeoKeys(geoKeys: IntArray): HashMap<Int, Any?> {
+ val fields = HashMap<Int, Any?>()
+ if (geoKeys.size < 4) return fields
+
+ var i = 0
+ val directoryVersion = geoKeys[i++]
+ val revision = geoKeys[i++]
+ val minorRevision = geoKeys[i++]
+ val numberOfKeys = geoKeys[i++]
+
+ fields[GeoTiffKeys.GEOTIFF_VERSION] = "$directoryVersion.$revision.$minorRevision"
+
+ (0 until numberOfKeys).forEach { j ->
+ val keyId = geoKeys[i++]
+ val tiffTagLocation = geoKeys[i++]
+ val valueCount = geoKeys[i++]
+ val valueOffset = geoKeys[i++]
+
+ try {
+ if (tiffTagLocation == 0) {
+ fields[keyId] = valueOffset
+ } else {
+ val sourceValue = getObject(tiffTagLocation)
+ if (sourceValue is StringValue) {
+ if (valueOffset + valueCount <= sourceValue.bytes.size) {
+ fields[keyId] = String(sourceValue.bytes, valueOffset, valueCount).trimEnd('|')
+ } else {
+ Log.w(LOG_TAG, "GeoTIFF key $keyId with offset $valueOffset and count $valueCount extends beyond length of source value (${sourceValue.bytes.size})")
+ }
+ } else if (sourceValue.javaClass.isArray) {
+ val sourceArray = sourceValue as DoubleArray
+ if (valueOffset + valueCount <= sourceArray.size) {
+ fields[keyId] = sourceArray.copyOfRange(valueOffset, valueOffset + valueCount)
+ } else {
+ Log.w(LOG_TAG, "GeoTIFF key $keyId with offset $valueOffset and count $valueCount extends beyond length of source value (${sourceArray.size})")
+ }
+ } else {
+ Log.w(LOG_TAG, "GeoTIFF key $keyId references tag $tiffTagLocation which has unsupported type of ${sourceValue?.javaClass}")
+ }
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to extract GeoTiff fields from keys", e)
+ }
+ }
+
+ return fields
+ }
+
+ // PNG
+
+ fun Directory.isPngTextDir(): Boolean = this is PngDirectory && setOf(PNG_ITXT_DIR_NAME, PNG_TEXT_DIR_NAME, PNG_ZTXT_DIR_NAME).contains(this.name)
+
+ fun extractPngProfile(key: String, valueString: String): Iterable<Directory>? {
+ if (key == PNG_RAW_PROFILE_EXIF || key == PNG_RAW_PROFILE_IPTC) {
+ val match = PNG_RAW_PROFILE_PATTERN.matchEntire(valueString)
+ if (match != null) {
+ val dataString = match.groupValues[3]
+ val hexString = dataString.replace(Regex("[\\r\\n]"), "")
+ val dataBytes = hexString.decodeHex()
+ if (dataBytes != null) {
+ val metadata = com.drew.metadata.Metadata()
+ when (key) {
+ PNG_RAW_PROFILE_EXIF -> {
+ if (ExifReader.startsWithJpegExifPreamble(dataBytes)) {
+ ExifReader().extract(ByteArrayReader(dataBytes), metadata, ExifReader.JPEG_SEGMENT_PREAMBLE.length)
+ }
+ }
+
+ PNG_RAW_PROFILE_IPTC -> {
+ val start = dataBytes.indexOf(Metadata.IPTC_MARKER_BYTE)
+ if (start != -1) {
+ val segmentBytes = dataBytes.copyOfRange(fromIndex = start, toIndex = dataBytes.size)
+ IptcReader().extract(SequentialByteArrayReader(segmentBytes), metadata, segmentBytes.size.toLong())
+ }
+ }
+ }
+ return metadata.directories
+ }
+ }
+ }
+ return null
+ }
+
+ // convenience methods
+
+ private fun String.decodeHex(): ByteArray? {
+ if (length % 2 != 0) return null
+
+ try {
+ val byteIterator = chunkedSequence(2)
+ .map { it.toInt(16).toByte() }
+ .iterator()
+
+ return ByteArray(length / 2) { byteIterator.next() }
+ } catch (e: NumberFormatException) {
+ Log.w(LOG_TAG, "failed to decode hex string=$this", e)
+ }
+ return null
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/PngActlDirectory.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/PngActlDirectory.kt
new file mode 100644
index 0000000..9313882
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/PngActlDirectory.kt
@@ -0,0 +1,22 @@
+package deckers.thibault.aves.metadata.metadataextractor
+import com.drew.imaging.png.PngChunkType
+import com.drew.metadata.png.PngDirectory
+
+class PngActlDirectory : PngDirectory(chunkType) {
+ override fun getTagNameMap(): HashMap<Int, String> {
+ return tagNames
+ }
+
+ companion object {
+ val chunkType = PngChunkType("acTL")
+
+ // tags should be distinct from those already defined in `PngDirectory`
+ const val TAG_NUM_FRAMES = 101
+ const val TAG_NUM_PLAYS = 102
+
+ private val tagNames = hashMapOf(
+ TAG_NUM_FRAMES to "Number Of Frames",
+ TAG_NUM_PLAYS to "Number Of Plays",
+ )
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeExifTiffHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeExifTiffHandler.kt
new file mode 100644
index 0000000..39a4c49
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeExifTiffHandler.kt
@@ -0,0 +1,28 @@
+package deckers.thibault.aves.metadata.metadataextractor
+
+import com.drew.lang.RandomAccessReader
+import com.drew.metadata.Directory
+import com.drew.metadata.Metadata
+import com.drew.metadata.exif.ExifIFD0Directory
+import com.drew.metadata.exif.ExifSubIFDDirectory
+import com.drew.metadata.exif.ExifTiffHandler
+import java.io.IOException
+
+class SafeExifTiffHandler(metadata: Metadata, parentDirectory: Directory?, exifStartOffset: Int) : ExifTiffHandler(metadata, parentDirectory, exifStartOffset) {
+ @Throws(IOException::class)
+ override fun customProcessTag(
+ tagOffset: Int,
+ processedIfdOffsets: MutableSet<Int>?,
+ tiffHeaderOffset: Int,
+ reader: RandomAccessReader?,
+ tagId: Int,
+ byteCount: Int,
+ ): Boolean {
+ if (tagId == ExifSubIFDDirectory.TAG_APPLICATION_NOTES && (_currentDirectory is ExifIFD0Directory || _currentDirectory is ExifSubIFDDirectory)) {
+ SafeXmpReader().extract(reader!!.getNullTerminatedBytes(tagOffset, byteCount), _metadata, _currentDirectory)
+ return true
+ }
+
+ return super.customProcessTag(tagOffset, processedIfdOffsets, tiffHeaderOffset, reader, tagId, byteCount)
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4BoxHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4BoxHandler.kt
new file mode 100644
index 0000000..b4e8377
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4BoxHandler.kt
@@ -0,0 +1,20 @@
+package deckers.thibault.aves.metadata.metadataextractor
+
+import com.drew.imaging.mp4.Mp4Handler
+import com.drew.metadata.Metadata
+import com.drew.metadata.mp4.Mp4BoxHandler
+import com.drew.metadata.mp4.Mp4BoxTypes
+import com.drew.metadata.mp4.Mp4Context
+import java.io.IOException
+
+class SafeMp4BoxHandler(metadata: Metadata) : Mp4BoxHandler(metadata) {
+ @Throws(IOException::class)
+ override fun processBox(type: String, payload: ByteArray?, boxSize: Long, context: Mp4Context?): Mp4Handler<*>? {
+ if (payload != null && type == Mp4BoxTypes.BOX_USER_DEFINED) {
+ val userBoxHandler = SafeMp4UuidBoxHandler(metadata)
+ userBoxHandler.processBox(type, payload, boxSize, context)
+ return this
+ }
+ return super.processBox(type, payload, boxSize, context)
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4UuidBoxHandler.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4UuidBoxHandler.kt
new file mode 100644
index 0000000..147f67f
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeMp4UuidBoxHandler.kt
@@ -0,0 +1,20 @@
+package deckers.thibault.aves.metadata.metadataextractor
+
+import com.drew.imaging.mp4.Mp4Handler
+import com.drew.metadata.Metadata
+import com.drew.metadata.mp4.Mp4Context
+import com.drew.metadata.mp4.media.Mp4UuidBoxHandler
+import deckers.thibault.aves.metadata.xmp.XMP
+
+class SafeMp4UuidBoxHandler(metadata: Metadata) : Mp4UuidBoxHandler(metadata) {
+ override fun processBox(type: String?, payload: ByteArray?, boxSize: Long, context: Mp4Context?): Mp4Handler<*> {
+ if (payload != null && payload.size >= 16) {
+ val payloadUuid = payload.copyOfRange(0, 16)
+ if (payloadUuid.contentEquals(XMP.mp4Uuid)) {
+ SafeXmpReader().extract(payload, 16, payload.size - 16, metadata, directory)
+ return this
+ }
+ }
+ return super.processBox(type, payload, boxSize, context)
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePhotoshopReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePhotoshopReader.kt
new file mode 100644
index 0000000..d312569
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePhotoshopReader.kt
@@ -0,0 +1,116 @@
+package deckers.thibault.aves.metadata.metadataextractor
+
+import com.drew.imaging.ImageProcessingException
+import com.drew.lang.ByteArrayReader
+import com.drew.lang.SequentialByteArrayReader
+import com.drew.lang.SequentialReader
+import com.drew.metadata.Directory
+import com.drew.metadata.Metadata
+import com.drew.metadata.exif.ExifReader
+import com.drew.metadata.icc.IccReader
+import com.drew.metadata.iptc.IptcReader
+import com.drew.metadata.photoshop.PhotoshopDirectory
+import com.drew.metadata.photoshop.PhotoshopReader
+import java.util.Arrays
+
+// adapted from `PhotoshopReader` to prevent OOM from reading large XMP
+// as of `metadata-extractor` v2.18.0, there is no way to customize the Photoshop reader
+// without copying the whole `extract` function
+class SafePhotoshopReader : PhotoshopReader() {
+ override fun extract(reader: SequentialReader, length: Int, metadata: Metadata, parentDirectory: Directory?) {
+ val directory = PhotoshopDirectory()
+ metadata.addDirectory(directory)
+
+ if (parentDirectory != null) {
+ directory.parent = parentDirectory
+ }
+
+ // Data contains a sequence of Image Resource Blocks (IRBs):
+ //
+ // 4 bytes - Signature; mostly "8BIM" but "PHUT", "AgHg" and "DCSR" are also found
+ // 2 bytes - Resource identifier
+ // String - Pascal string, padded to make length even
+ // 4 bytes - Size of resource data which follows
+ // Data - The resource data, padded to make size even
+ //
+ // http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#50577409_pgfId-1037504
+
+ var pos = 0
+ var clippingPathCount = 0
+ while (pos < length) {
+ try {
+ // 4 bytes for the signature ("8BIM", "PHUT", etc.)
+ val signature = reader.getString(4)
+ pos += 4
+
+ // 2 bytes for the resource identifier (tag type).
+ val tagType = reader.uInt16 // segment type
+ pos += 2
+
+ // A variable number of bytes holding a pascal string (two leading bytes for length).
+ var descriptionLength = reader.uInt8.toInt()
+ pos += 1
+ // Some basic bounds checking
+ if (descriptionLength < 0 || descriptionLength + pos > length) {
+ throw ImageProcessingException("Invalid string length")
+ }
+
+ // Get name (important for paths)
+ val description = StringBuilder()
+ descriptionLength += pos
+ // Loop through each byte and append to string
+ while (pos < descriptionLength) {
+ description.append(Char(reader.uInt8.toUShort()))
+ pos++
+ }
+
+ // The number of bytes is padded with a trailing zero, if needed, to make the size even.
+ if (pos % 2 != 0) {
+ reader.skip(1)
+ pos++
+ }
+
+ // 4 bytes for the size of the resource data that follows.
+ val byteCount = reader.int32
+ pos += 4
+ // The resource data.
+ var tagBytes = reader.getBytes(byteCount)
+ pos += byteCount
+ // The number of bytes is padded with a trailing zero, if needed, to make the size even.
+ if (pos % 2 != 0) {
+ reader.skip(1)
+ pos++
+ }
+
+ if (signature == "8BIM") {
+ when (tagType) {
+ PhotoshopDirectory.TAG_IPTC -> IptcReader().extract(SequentialByteArrayReader(tagBytes), metadata, tagBytes.size.toLong(), directory)
+ PhotoshopDirectory.TAG_ICC_PROFILE_BYTES -> IccReader().extract(ByteArrayReader(tagBytes), metadata, directory)
+ PhotoshopDirectory.TAG_EXIF_DATA_1,
+ PhotoshopDirectory.TAG_EXIF_DATA_3 -> ExifReader().extract(ByteArrayReader(tagBytes), metadata, 0, directory)
+
+ PhotoshopDirectory.TAG_XMP_DATA -> SafeXmpReader().extract(tagBytes, metadata, directory)
+ in 0x07D0..0x0BB6 -> {
+ clippingPathCount++
+ tagBytes = Arrays.copyOf(tagBytes, tagBytes.size + description.length + 1)
+ // Append description(name) to end of byte array with 1 byte before the description representing the length
+ for (i in tagBytes.size - description.length - 1 until tagBytes.size) {
+ if (i % (tagBytes.size - description.length - 1 + description.length) == 0) tagBytes[i] = description.length.toByte() else tagBytes[i] = description[i - (tagBytes.size - description.length - 1)].code.toByte()
+ }
+// PhotoshopDirectory._tagNameMap[0x07CF + clippingPathCount] = "Path Info $clippingPathCount"
+ directory.setByteArray(0x07CF + clippingPathCount, tagBytes)
+ }
+
+ else -> directory.setByteArray(tagType, tagBytes)
+ }
+// if (tagType in 0x0fa0..0x1387) {
+// PhotoshopDirectory._tagNameMap[tagType] = String.format("Plug-in %d Data", tagType - 0x0fa0 + 1)
+// }
+ }
+ } catch (ex: Exception) {
+ directory.addError(ex.message)
+ return
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePngMetadataReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePngMetadataReader.kt
new file mode 100644
index 0000000..719f08a
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePngMetadataReader.kt
@@ -0,0 +1,335 @@
+package deckers.thibault.aves.metadata.metadataextractor
+
+import android.util.Log
+import com.drew.imaging.png.PngChromaticities
+import com.drew.imaging.png.PngChunk
+import com.drew.imaging.png.PngChunkReader
+import com.drew.imaging.png.PngChunkType
+import com.drew.imaging.png.PngHeader
+import com.drew.imaging.png.PngProcessingException
+import com.drew.imaging.tiff.TiffProcessingException
+import com.drew.imaging.tiff.TiffReader
+import com.drew.lang.ByteArrayReader
+import com.drew.lang.ByteConvert
+import com.drew.lang.Charsets
+import com.drew.lang.DateUtil
+import com.drew.lang.KeyValuePair
+import com.drew.lang.RandomAccessStreamReader
+import com.drew.lang.SequentialByteArrayReader
+import com.drew.lang.SequentialReader
+import com.drew.lang.StreamReader
+import com.drew.lang.StreamUtil
+import com.drew.metadata.ErrorDirectory
+import com.drew.metadata.Metadata
+import com.drew.metadata.StringValue
+import com.drew.metadata.exif.ExifTiffHandler
+import com.drew.metadata.icc.IccReader
+import com.drew.metadata.png.PngChromaticitiesDirectory
+import com.drew.metadata.png.PngDirectory
+import com.drew.metadata.xmp.XmpReader
+import deckers.thibault.aves.utils.LogUtils
+import java.io.ByteArrayInputStream
+import java.io.IOException
+import java.io.InputStream
+import java.util.Locale
+import java.util.zip.InflaterInputStream
+import java.util.zip.ZipException
+
+// adapted from `PngMetadataReader` to:
+// - prevent OOM from reading large chunks. As of `metadata-extractor` v2.18.0, there is no way to customize the reader
+// without copying `desiredChunkTypes` and the whole `processChunk` function.
+// - parse `acTL` chunk to identify animated PNGs.
+object SafePngMetadataReader {
+ private val LOG_TAG = LogUtils.createTag<SafePngMetadataReader>()
+
+ // arbitrary size to detect chunks that may yield an OOM
+ private const val CHUNK_SIZE_DANGER_THRESHOLD = SafeXmpReader.SEGMENT_TYPE_SIZE_DANGER_THRESHOLD
+
+ private val latin1Encoding = Charsets.ISO_8859_1
+ private val utf8Encoding = Charsets.UTF_8
+ private val desiredChunkTypes: Set<PngChunkType> = hashSetOf(
+ PngChunkType.IHDR,
+ PngChunkType.PLTE,
+ PngChunkType.tRNS,
+ PngChunkType.cHRM,
+ PngChunkType.sRGB,
+ PngChunkType.gAMA,
+ PngChunkType.iCCP,
+ PngChunkType.bKGD,
+ PngChunkType.tEXt,
+ PngChunkType.zTXt,
+ PngChunkType.iTXt,
+ PngChunkType.tIME,
+ PngChunkType.pHYs,
+ PngChunkType.sBIT,
+ PngChunkType.eXIf,
+ PngActlDirectory.chunkType,
+ )
+
+ @Throws(IOException::class, PngProcessingException::class)
+ fun readMetadata(inputStream: InputStream): Metadata {
+ val chunks = PngChunkReader().extract(StreamReader(inputStream), desiredChunkTypes)
+ val metadata = Metadata()
+ for (chunk in chunks) {
+ try {
+ processChunk(metadata, chunk)
+ } catch (e: Exception) {
+ metadata.addDirectory(ErrorDirectory("Exception reading PNG chunk: " + e.message))
+ }
+ }
+ return metadata
+ }
+
+ @Throws(PngProcessingException::class, IOException::class)
+ private fun processChunk(metadata: Metadata, chunk: PngChunk) {
+ val chunkType = chunk.type
+ val bytes = chunk.bytes
+
+ // TLAD insert start
+ if (bytes.size > CHUNK_SIZE_DANGER_THRESHOLD) {
+ Log.w(LOG_TAG, "PNG chunk $chunkType is too large, with a size of ${bytes.size} B")
+ return
+ }
+ // TLAD insert end
+
+ if (chunkType == PngChunkType.IHDR) {
+ val header = PngHeader(bytes)
+ val directory = PngDirectory(PngChunkType.IHDR)
+ directory.setInt(PngDirectory.TAG_IMAGE_WIDTH, header.imageWidth)
+ directory.setInt(PngDirectory.TAG_IMAGE_HEIGHT, header.imageHeight)
+ directory.setInt(PngDirectory.TAG_BITS_PER_SAMPLE, header.bitsPerSample.toInt())
+ directory.setInt(PngDirectory.TAG_COLOR_TYPE, header.colorType.numericValue)
+ directory.setInt(PngDirectory.TAG_COMPRESSION_TYPE, header.compressionType.toInt() and 0xFF) // make sure it's unsigned
+ directory.setInt(PngDirectory.TAG_FILTER_METHOD, header.filterMethod.toInt())
+ directory.setInt(PngDirectory.TAG_INTERLACE_METHOD, header.interlaceMethod.toInt())
+ metadata.addDirectory(directory)
+ // TLAD insert start
+ } else if (chunkType == PngActlDirectory.chunkType) {
+ if (bytes.size != 8) {
+ throw PngProcessingException("Invalid number of bytes")
+ }
+ val reader = SequentialByteArrayReader(bytes)
+ try {
+ metadata.addDirectory(PngActlDirectory().apply {
+ setInt(PngActlDirectory.TAG_NUM_FRAMES, reader.int32)
+ setInt(PngActlDirectory.TAG_NUM_PLAYS, reader.int32)
+ })
+ } catch (ex: IOException) {
+ throw PngProcessingException(ex)
+ }
+ // TLAD insert end
+ } else if (chunkType == PngChunkType.PLTE) {
+ val directory = PngDirectory(PngChunkType.PLTE)
+ directory.setInt(PngDirectory.TAG_PALETTE_SIZE, bytes.size / 3)
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.tRNS) {
+ val directory = PngDirectory(PngChunkType.tRNS)
+ directory.setInt(PngDirectory.TAG_PALETTE_HAS_TRANSPARENCY, 1)
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.sRGB) {
+ val srgbRenderingIntent = bytes[0].toInt()
+ val directory = PngDirectory(PngChunkType.sRGB)
+ directory.setInt(PngDirectory.TAG_SRGB_RENDERING_INTENT, srgbRenderingIntent)
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.cHRM) {
+ val chromaticities = PngChromaticities(bytes)
+ val directory = PngChromaticitiesDirectory()
+ directory.setInt(PngChromaticitiesDirectory.TAG_WHITE_POINT_X, chromaticities.whitePointX)
+ directory.setInt(PngChromaticitiesDirectory.TAG_WHITE_POINT_Y, chromaticities.whitePointY)
+ directory.setInt(PngChromaticitiesDirectory.TAG_RED_X, chromaticities.redX)
+ directory.setInt(PngChromaticitiesDirectory.TAG_RED_Y, chromaticities.redY)
+ directory.setInt(PngChromaticitiesDirectory.TAG_GREEN_X, chromaticities.greenX)
+ directory.setInt(PngChromaticitiesDirectory.TAG_GREEN_Y, chromaticities.greenY)
+ directory.setInt(PngChromaticitiesDirectory.TAG_BLUE_X, chromaticities.blueX)
+ directory.setInt(PngChromaticitiesDirectory.TAG_BLUE_Y, chromaticities.blueY)
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.gAMA) {
+ val gammaInt = ByteConvert.toInt32BigEndian(bytes)
+ SequentialByteArrayReader(bytes).int32
+ val directory = PngDirectory(PngChunkType.gAMA)
+ directory.setDouble(PngDirectory.TAG_GAMMA, gammaInt / 100000.0)
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.iCCP) {
+ val reader: SequentialReader = SequentialByteArrayReader(bytes)
+
+ // Profile Name is 1-79 bytes, followed by the 1 byte null character
+ val profileNameBytes = reader.getNullTerminatedBytes(79 + 1)
+ val directory = PngDirectory(PngChunkType.iCCP)
+ directory.setStringValue(PngDirectory.TAG_ICC_PROFILE_NAME, StringValue(profileNameBytes, latin1Encoding))
+ val compressionMethod = reader.int8
+ // Only compression method allowed by the spec is zero: deflate
+ if (compressionMethod.toInt() == 0) {
+ // bytes left for compressed text is:
+ // total bytes length - (profileNameBytes length + null byte + compression method byte)
+ val bytesLeft = bytes.size - (profileNameBytes.size + 1 + 1)
+ val compressedProfile = reader.getBytes(bytesLeft)
+ try {
+ val inflateStream = InflaterInputStream(ByteArrayInputStream(compressedProfile))
+ IccReader().extract(RandomAccessStreamReader(inflateStream), metadata, directory)
+ inflateStream.close()
+ } catch (zex: ZipException) {
+ directory.addError(String.format("Exception decompressing PNG iCCP chunk : %s", zex.message))
+ metadata.addDirectory(directory)
+ }
+ } else {
+ directory.addError("Invalid compression method value")
+ }
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.bKGD) {
+ val directory = PngDirectory(PngChunkType.bKGD)
+ directory.setByteArray(PngDirectory.TAG_BACKGROUND_COLOR, bytes)
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.tEXt) {
+ val reader: SequentialReader = SequentialByteArrayReader(bytes)
+
+ // Keyword is 1-79 bytes, followed by the 1 byte null character
+ val keywordsv = reader.getNullTerminatedStringValue(79 + 1, latin1Encoding)
+ val keyword = keywordsv.toString()
+
+ // bytes left for text is:
+ // total bytes length - (Keyword length + null byte)
+ val bytesLeft = bytes.size - (keywordsv.bytes.size + 1)
+ val value = reader.getNullTerminatedStringValue(bytesLeft, latin1Encoding)
+ val textPairs: MutableList<KeyValuePair> = ArrayList()
+ textPairs.add(KeyValuePair(keyword, value))
+ val directory = PngDirectory(PngChunkType.tEXt)
+ directory.setObject(PngDirectory.TAG_TEXTUAL_DATA, textPairs)
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.zTXt) {
+ val reader: SequentialReader = SequentialByteArrayReader(bytes)
+
+ // Keyword is 1-79 bytes, followed by the 1 byte null character
+ val keywordsv = reader.getNullTerminatedStringValue(79 + 1, latin1Encoding)
+ val keyword = keywordsv.toString()
+ val compressionMethod = reader.int8
+
+ // bytes left for compressed text is:
+ // total bytes length - (Keyword length + null byte + compression method byte)
+ val bytesLeft = bytes.size - (keywordsv.bytes.size + 1 + 1)
+ var textBytes: ByteArray? = null
+ if (compressionMethod.toInt() == 0) {
+ try {
+ textBytes = StreamUtil.readAllBytes(InflaterInputStream(ByteArrayInputStream(bytes, bytes.size - bytesLeft, bytesLeft)))
+ } catch (zex: ZipException) {
+ val directory = PngDirectory(PngChunkType.zTXt)
+ directory.addError(String.format("Exception decompressing PNG zTXt chunk with keyword \"%s\": %s", keyword, zex.message))
+ metadata.addDirectory(directory)
+ }
+ } else {
+ val directory = PngDirectory(PngChunkType.zTXt)
+ directory.addError("Invalid compression method value")
+ metadata.addDirectory(directory)
+ }
+ if (textBytes != null) {
+ if (keyword == "XML:com.adobe.xmp") {
+ // NOTE in testing images, the XMP has parsed successfully, but we are not extracting tags from it as necessary
+ XmpReader().extract(textBytes, metadata)
+ } else {
+ val textPairs: MutableList<KeyValuePair> = ArrayList()
+ textPairs.add(KeyValuePair(keyword, StringValue(textBytes, latin1Encoding)))
+ val directory = PngDirectory(PngChunkType.zTXt)
+ directory.setObject(PngDirectory.TAG_TEXTUAL_DATA, textPairs)
+ metadata.addDirectory(directory)
+ }
+ }
+ } else if (chunkType == PngChunkType.iTXt) {
+ val reader: SequentialReader = SequentialByteArrayReader(bytes)
+
+ // Keyword is 1-79 bytes, followed by the 1 byte null character
+ val keywordsv = reader.getNullTerminatedStringValue(79 + 1, utf8Encoding)
+ val keyword = keywordsv.toString()
+ val compressionFlag = reader.int8
+ val compressionMethod = reader.int8
+ // TODO we currently ignore languageTagBytes and translatedKeywordBytes
+ val languageTagBytes = reader.getNullTerminatedBytes(bytes.size)
+ val translatedKeywordBytes = reader.getNullTerminatedBytes(bytes.size)
+
+ // bytes left for compressed text is:
+ // total bytes length - (Keyword length + null byte + comp flag byte + comp method byte + lang length + null byte + translated length + null byte)
+ val bytesLeft = bytes.size - (keywordsv.bytes.size + 1 + 1 + 1 + languageTagBytes.size + 1 + translatedKeywordBytes.size + 1)
+ var textBytes: ByteArray? = null
+ if (compressionFlag.toInt() == 0) {
+ textBytes = reader.getNullTerminatedBytes(bytesLeft)
+ } else if (compressionFlag.toInt() == 1) {
+ if (compressionMethod.toInt() == 0) {
+ try {
+ textBytes = StreamUtil.readAllBytes(InflaterInputStream(ByteArrayInputStream(bytes, bytes.size - bytesLeft, bytesLeft)))
+ } catch (zex: ZipException) {
+ val directory = PngDirectory(PngChunkType.iTXt)
+ directory.addError(String.format("Exception decompressing PNG iTXt chunk with keyword \"%s\": %s", keyword, zex.message))
+ metadata.addDirectory(directory)
+ }
+ } else {
+ val directory = PngDirectory(PngChunkType.iTXt)
+ directory.addError("Invalid compression method value")
+ metadata.addDirectory(directory)
+ }
+ } else {
+ val directory = PngDirectory(PngChunkType.iTXt)
+ directory.addError("Invalid compression flag value")
+ metadata.addDirectory(directory)
+ }
+ if (textBytes != null) {
+ if (keyword == "XML:com.adobe.xmp") {
+ // NOTE in testing images, the XMP has parsed successfully, but we are not extracting tags from it as necessary
+ XmpReader().extract(textBytes, metadata)
+ } else {
+ val textPairs: MutableList<KeyValuePair> = ArrayList()
+ textPairs.add(KeyValuePair(keyword, StringValue(textBytes, utf8Encoding)))
+ val directory = PngDirectory(PngChunkType.iTXt)
+ directory.setObject(PngDirectory.TAG_TEXTUAL_DATA, textPairs)
+ metadata.addDirectory(directory)
+ }
+ }
+ } else if (chunkType == PngChunkType.tIME) {
+ val reader = SequentialByteArrayReader(bytes)
+ val year = reader.uInt16
+ val month = reader.uInt8.toInt()
+ val day = reader.uInt8.toInt()
+ val hour = reader.uInt8.toInt()
+ val minute = reader.uInt8.toInt()
+ val second = reader.uInt8.toInt()
+ val directory = PngDirectory(PngChunkType.tIME)
+ if (DateUtil.isValidDate(year, month - 1, day) && DateUtil.isValidTime(hour, minute, second)) {
+ val dateString = String.format(Locale.ROOT, "%04d:%02d:%02d %02d:%02d:%02d", year, month, day, hour, minute, second)
+ directory.setString(PngDirectory.TAG_LAST_MODIFICATION_TIME, dateString)
+ } else {
+ directory.addError(
+ String.format(
+ Locale.ROOT,
+ "PNG tIME data describes an invalid date/time: year=%d month=%d day=%d hour=%d minute=%d second=%d",
+ year, month, day, hour, minute, second
+ )
+ )
+ }
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.pHYs) {
+ val reader = SequentialByteArrayReader(bytes)
+ val pixelsPerUnitX = reader.int32
+ val pixelsPerUnitY = reader.int32
+ val unitSpecifier = reader.int8
+ val directory = PngDirectory(PngChunkType.pHYs)
+ directory.setInt(PngDirectory.TAG_PIXELS_PER_UNIT_X, pixelsPerUnitX)
+ directory.setInt(PngDirectory.TAG_PIXELS_PER_UNIT_Y, pixelsPerUnitY)
+ directory.setInt(PngDirectory.TAG_UNIT_SPECIFIER, unitSpecifier.toInt())
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.sBIT) {
+ val directory = PngDirectory(PngChunkType.sBIT)
+ directory.setByteArray(PngDirectory.TAG_SIGNIFICANT_BITS, bytes)
+ metadata.addDirectory(directory)
+ } else if (chunkType == PngChunkType.eXIf) {
+ try {
+ val handler = ExifTiffHandler(metadata, null, 0)
+ TiffReader().processTiff(ByteArrayReader(bytes), handler, 0)
+ } catch (ex: TiffProcessingException) {
+ val directory = PngDirectory(PngChunkType.eXIf)
+ directory.addError(ex.message)
+ metadata.addDirectory(directory)
+ } catch (ex: IOException) {
+ val directory = PngDirectory(PngChunkType.eXIf)
+ directory.addError(ex.message)
+ metadata.addDirectory(directory)
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdMetadataReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdMetadataReader.kt
new file mode 100644
index 0000000..6f93a23
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdMetadataReader.kt
@@ -0,0 +1,13 @@
+package deckers.thibault.aves.metadata.metadataextractor
+
+import com.drew.lang.StreamReader
+import com.drew.metadata.Metadata
+import java.io.InputStream
+
+object SafePsdMetadataReader {
+ fun readMetadata(inputStream: InputStream): Metadata {
+ val metadata = Metadata()
+ SafePsdReader().extract(StreamReader(inputStream), metadata)
+ return metadata
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdReader.kt
new file mode 100644
index 0000000..3ca23f6
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafePsdReader.kt
@@ -0,0 +1,93 @@
+package deckers.thibault.aves.metadata.metadataextractor
+
+import com.drew.lang.SequentialReader
+import com.drew.metadata.Metadata
+import com.drew.metadata.photoshop.PsdHeaderDirectory
+import java.io.IOException
+
+// adapted from `PsdReader` to prevent OOM from reading large XMP
+// as of `metadata-extractor` v2.18.0, there is no way to customize the Photoshop reader
+// without copying the whole `extract` function
+class SafePsdReader {
+ fun extract(reader: SequentialReader, metadata: Metadata) {
+ val directory = PsdHeaderDirectory()
+ metadata.addDirectory(directory)
+
+ // FILE HEADER SECTION
+
+ try {
+ val signature = reader.int32
+ if (signature != 0x38425053) // "8BPS"
+ {
+ directory.addError("Invalid PSD file signature")
+ return
+ }
+
+ val version = reader.uInt16
+ if (version != 1 && version != 2) {
+ directory.addError("Invalid PSD file version (must be 1 or 2)")
+ return
+ }
+
+ // 6 reserved bytes are skipped here. They should be zero.
+ reader.skip(6)
+
+ val channelCount = reader.uInt16
+ directory.setInt(PsdHeaderDirectory.TAG_CHANNEL_COUNT, channelCount)
+
+ // even though this is probably an unsigned int, the max height in practice is 300,000
+ val imageHeight = reader.int32
+ directory.setInt(PsdHeaderDirectory.TAG_IMAGE_HEIGHT, imageHeight)
+
+ // even though this is probably an unsigned int, the max width in practice is 300,000
+ val imageWidth = reader.int32
+ directory.setInt(PsdHeaderDirectory.TAG_IMAGE_WIDTH, imageWidth)
+
+ val bitsPerChannel = reader.uInt16
+ directory.setInt(PsdHeaderDirectory.TAG_BITS_PER_CHANNEL, bitsPerChannel)
+
+ val colorMode = reader.uInt16
+ directory.setInt(PsdHeaderDirectory.TAG_COLOR_MODE, colorMode)
+ } catch (_: IOException) {
+ directory.addError("Unable to read PSD header")
+ return
+ }
+
+ // COLOR MODE DATA SECTION
+
+ try {
+ val sectionLength = reader.uInt32
+
+ /*
+ * Only indexed color and duotone (see the mode field in the File header section) have color mode data.
+ * For all other modes, this section is just the 4-byte length field, which is set to zero.
+ *
+ * Indexed color images: length is 768; color data contains the color table for the image,
+ * in non-interleaved order.
+ * Duotone images: color data contains the duotone specification (the format of which is not documented).
+ * Other applications that read Photoshop files can treat a duotone image as a gray image,
+ * and just preserve the contents of the duotone information when reading and writing the
+ * file.
+ */
+ reader.skip(sectionLength)
+ } catch (_: IOException) {
+ return
+ }
+
+ // IMAGE RESOURCES SECTION
+
+ try {
+ val sectionLength = reader.uInt32
+
+ assert(sectionLength <= Int.MAX_VALUE)
+
+ SafePhotoshopReader().extract(reader, sectionLength.toInt(), metadata)
+ } catch (_: IOException) {
+ // ignore
+ }
+
+ // LAYER AND MASK INFORMATION SECTION (skipped)
+
+ // IMAGE DATA SECTION (skipped)
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeXmpReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeXmpReader.kt
new file mode 100644
index 0000000..603e3ed
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/SafeXmpReader.kt
@@ -0,0 +1,179 @@
+package deckers.thibault.aves.metadata.metadataextractor
+
+import android.util.Log
+import com.adobe.internal.xmp.XMPException
+import com.adobe.internal.xmp.XMPMeta
+import com.adobe.internal.xmp.XMPMetaFactory
+import com.adobe.internal.xmp.impl.ByteBuffer
+import com.adobe.internal.xmp.options.ParseOptions
+import com.adobe.internal.xmp.properties.XMPPropertyInfo
+import com.drew.imaging.jpeg.JpegSegmentType
+import com.drew.lang.SequentialByteArrayReader
+import com.drew.lang.SequentialReader
+import com.drew.metadata.Directory
+import com.drew.metadata.Metadata
+import com.drew.metadata.xmp.XmpDirectory
+import com.drew.metadata.xmp.XmpReader
+import deckers.thibault.aves.utils.LogUtils
+import java.io.IOException
+import java.util.Locale
+
+class SafeXmpReader : XmpReader() {
+ // adapted from `XmpReader` to detect and skip large extended XMP
+ override fun readJpegSegments(segments: Iterable<ByteArray>, metadata: Metadata, segmentType: JpegSegmentType) {
+ val preambleLength = XMP_JPEG_PREAMBLE.length
+ val extensionPreambleLength = XMP_EXTENSION_JPEG_PREAMBLE.length
+ var extendedXMPGUID: String? = null
+ var extendedXMPBuffer: ByteArray? = null
+ var loggedDanger = false
+
+ for (segmentBytes in segments) {
+ if (segmentBytes.size >= preambleLength) {
+ if (XMP_JPEG_PREAMBLE.equals(String(segmentBytes, 0, preambleLength), ignoreCase = true) ||
+ "XMP".equals(String(segmentBytes, 0, 3), ignoreCase = true)
+ ) {
+ val xmlBytes = ByteArray(segmentBytes.size - preambleLength)
+ System.arraycopy(segmentBytes, preambleLength, xmlBytes, 0, xmlBytes.size)
+ extract(xmlBytes, metadata)
+ extendedXMPGUID = getExtendedXMPGUID(metadata)
+ continue
+ }
+ }
+ if (extendedXMPGUID != null && segmentBytes.size >= extensionPreambleLength &&
+ XMP_EXTENSION_JPEG_PREAMBLE.equals(String(segmentBytes, 0, extensionPreambleLength), ignoreCase = true)
+ ) {
+ extendedXMPBuffer = processExtendedXMPChunk(metadata, segmentBytes, extendedXMPGUID, extendedXMPBuffer) { fullLength ->
+ if (!loggedDanger) {
+ logError(metadata, fullLength)
+ loggedDanger = true
+ }
+ }
+ }
+ }
+
+ extendedXMPBuffer?.let { xmpBytes ->
+ val totalSize = xmpBytes.size
+ if (totalSize > SEGMENT_TYPE_SIZE_DANGER_THRESHOLD) {
+ logError(metadata, totalSize)
+ } else {
+ extract(xmpBytes, metadata)
+ }
+ }
+ }
+
+ // adapted from `XmpReader` to provide different parsing options
+ // and to detect large XMP when extracted directly (e.g. from Photoshop reader)
+ override fun extract(xmpBytes: ByteArray, offset: Int, length: Int, metadata: Metadata, parentDirectory: Directory?) {
+ val totalSize = xmpBytes.size
+ if (totalSize > SEGMENT_TYPE_SIZE_DANGER_THRESHOLD) {
+ logError(metadata, totalSize)
+ return
+ }
+
+ val directory = XmpDirectory()
+ if (parentDirectory != null) directory.parent = parentDirectory
+
+ try {
+ val xmpMeta: XMPMeta = if (offset == 0 && length == totalSize) {
+ XMPMetaFactory.parseFromBuffer(xmpBytes, PARSE_OPTIONS)
+ } else {
+ val buffer = ByteBuffer(xmpBytes, offset, length)
+ XMPMetaFactory.parse(buffer.byteStream, PARSE_OPTIONS)
+ }
+ directory.xmpMeta = xmpMeta
+ } catch (e: XMPException) {
+ directory.addError("Error processing XMP data: " + e.message)
+ }
+ if (!directory.isEmpty) metadata.addDirectory(directory)
+ }
+
+ // adapted from `XmpReader` because original is private
+ private fun getExtendedXMPGUID(metadata: Metadata): String? {
+ val xmpDirectories = metadata.getDirectoriesOfType(XmpDirectory::class.java)
+ for (directory in xmpDirectories) {
+ val xmpMeta = directory.xmpMeta
+ try {
+ val itr = xmpMeta.iterator(SCHEMA_XMP_NOTES, null, null) ?: continue
+ while (itr.hasNext()) {
+ val pi = itr.next() as XMPPropertyInfo?
+ if (ATTRIBUTE_EXTENDED_XMP == pi!!.path) {
+ return pi.value
+ }
+ }
+ } catch (e: XMPException) {
+ // Fail silently here: we had a reading issue, not a decoding issue.
+ }
+ }
+ return null
+ }
+
+ // adapted from `XmpReader` to prevent large allocation
+ private fun processExtendedXMPChunk(metadata: Metadata, segmentBytes: ByteArray, extendedXMPGUID: String, extendedXMPBufferIn: ByteArray?, onDangerSize: (fullLength: Int) -> Unit): ByteArray? {
+ var extendedXMPBuffer: ByteArray? = extendedXMPBufferIn
+ val extensionPreambleLength = XMP_EXTENSION_JPEG_PREAMBLE.length
+ val segmentLength = segmentBytes.size
+ val totalOffset = extensionPreambleLength + EXTENDED_XMP_GUID_LENGTH + EXTENDED_XMP_INT_LENGTH + EXTENDED_XMP_INT_LENGTH
+ if (segmentLength >= totalOffset) {
+ try {
+ val reader: SequentialReader = SequentialByteArrayReader(segmentBytes)
+ reader.skip(extensionPreambleLength.toLong())
+ val segmentGUID = reader.getString(EXTENDED_XMP_GUID_LENGTH)
+ if (extendedXMPGUID == segmentGUID) {
+ val fullLength = reader.uInt32.toInt()
+ val chunkOffset = reader.uInt32.toInt()
+ if (extendedXMPBuffer == null) {
+ // TLAD insert start
+ if (fullLength > SEGMENT_TYPE_SIZE_DANGER_THRESHOLD) {
+ onDangerSize(fullLength)
+ return null
+ }
+ // TLAD insert end
+ extendedXMPBuffer = ByteArray(fullLength)
+ }
+ if (extendedXMPBuffer.size == fullLength) {
+ System.arraycopy(segmentBytes, totalOffset, extendedXMPBuffer, chunkOffset, segmentLength - totalOffset)
+ } else {
+ val directory = XmpDirectory()
+ directory.addError(String.format(Locale.ROOT, "Inconsistent length for the Extended XMP buffer: %d instead of %d", fullLength, extendedXMPBuffer.size))
+ metadata.addDirectory(directory)
+ }
+ }
+ } catch (ex: IOException) {
+ val directory = XmpDirectory()
+ directory.addError(ex.message)
+ metadata.addDirectory(directory)
+ }
+ }
+ return extendedXMPBuffer
+ }
+
+ private fun logError(metadata: Metadata, size: Int) {
+ val error = "Extended XMP is too large, with a size of $size B"
+ Log.w(LOG_TAG, error)
+ metadata.addDirectory(XmpDirectory().apply {
+ addError(error)
+ })
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<SafeXmpReader>()
+
+ // arbitrary size to detect extended XMP that may yield an OOM
+ const val SEGMENT_TYPE_SIZE_DANGER_THRESHOLD = 3 * (1 shl 20) // MB
+
+ // tighter node limits for faster loading
+ val PARSE_OPTIONS: ParseOptions = ParseOptions().setXMPNodesToLimit(
+ mapOf(
+ "photoshop:DocumentAncestors" to 200,
+ "xmpMM:History" to 200,
+ )
+ )
+
+ private const val XMP_JPEG_PREAMBLE = "http://ns.adobe.com/xap/1.0/\u0000"
+ private const val XMP_EXTENSION_JPEG_PREAMBLE = "http://ns.adobe.com/xmp/extension/\u0000"
+ private const val SCHEMA_XMP_NOTES = "http://ns.adobe.com/xmp/note/"
+ private const val ATTRIBUTE_EXTENDED_XMP = "xmpNote:HasExtendedXMP"
+ private const val EXTENDED_XMP_GUID_LENGTH = 32
+ private const val EXTENDED_XMP_INT_LENGTH = 4
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntry.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntry.kt
new file mode 100644
index 0000000..c99adc7
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntry.kt
@@ -0,0 +1,37 @@
+package deckers.thibault.aves.metadata.metadataextractor.mpf
+
+import deckers.thibault.aves.utils.MimeTypes
+
+class MpEntry(val flags: Int, val format: Int, val type: Int, val size: Long, val dataOffset: Long, val dep1: Short, val dep2: Short) {
+ val mimeType: String?
+ get() = getMimeType(format)
+
+ val isThumbnail: Boolean
+ get() = when (type) {
+ TYPE_THUMBNAIL_VGA, TYPE_THUMBNAIL_FULL_HD -> true
+ else -> false
+ }
+
+ override fun toString(): String = "MpEntry#${hashCode()}{flags=$flags format=$format type=$type size=$size dataOffset=$dataOffset dep1=$dep1 dep2=$dep2}"
+
+ companion object {
+ const val FLAG_REPRESENTATIVE = 1 shl 2
+ const val FLAG_DEPENDENT_CHILD = 1 shl 3
+ const val FLAG_DEPENDENT_PARENT = 1 shl 4
+
+ const val TYPE_PRIMARY = 0x030000
+ const val TYPE_THUMBNAIL_VGA = 0x010001
+ const val TYPE_THUMBNAIL_FULL_HD = 0x010002
+ const val TYPE_PANORAMA = 0x020001
+ const val TYPE_DISPARITY = 0x020002
+ const val TYPE_MULTI_ANGLE = 0x020003
+ const val TYPE_UNDEFINED = 0x000000
+
+ fun getMimeType(format: Int): String? {
+ return when (format) {
+ 0 -> MimeTypes.JPEG
+ else -> null
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntryDirectory.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntryDirectory.kt
new file mode 100644
index 0000000..7dba552
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpEntryDirectory.kt
@@ -0,0 +1,64 @@
+package deckers.thibault.aves.metadata.metadataextractor.mpf
+
+import com.drew.metadata.Directory
+import com.drew.metadata.TagDescriptor
+
+class MpEntryDirectory(val id: Int, val entry: MpEntry) : Directory() {
+ private val descriptor = MpEntryDescriptor(this)
+
+ init {
+ setDescriptor(descriptor)
+ }
+
+ fun describe(): Map<String, String> {
+ return HashMap<String, String>().apply {
+ put("Flags", descriptor.getFlagsDescription(entry.flags))
+ put("Format", descriptor.getFormatDescription(entry.format))
+ put("Type", descriptor.getTypeDescription(entry.type))
+ put("Size", "${entry.size} bytes")
+ put("Offset", "${entry.dataOffset} bytes")
+ put("Dependent Image 1 Entry Number", "${entry.dep1}")
+ put("Dependent Image 2 Entry Number", "${entry.dep2}")
+ }
+ }
+
+ override fun getName(): String {
+ return "MPF Image #$id"
+ }
+
+ override fun getTagNameMap(): HashMap<Int, String> {
+ return _tagNameMap
+ }
+
+ companion object {
+ private val _tagNameMap = HashMap<Int, String>()
+ }
+}
+
+class MpEntryDescriptor(directory: MpEntryDirectory?) : TagDescriptor<MpEntryDirectory>(directory) {
+ fun getFlagsDescription(flags: Int): String {
+ val flagStrings = ArrayList<String>().apply {
+ if (flags and MpEntry.FLAG_REPRESENTATIVE != 0) add("representative image")
+ if (flags and MpEntry.FLAG_DEPENDENT_CHILD != 0) add("dependent child image")
+ if (flags and MpEntry.FLAG_DEPENDENT_PARENT != 0) add("dependent parent image")
+ }
+ return if (flagStrings.isEmpty()) "none" else flagStrings.joinToString(", ")
+ }
+
+ fun getFormatDescription(format: Int): String {
+ return MpEntry.getMimeType(format) ?: "Unknown ($format)"
+ }
+
+ fun getTypeDescription(type: Int): String {
+ return when (type) {
+ MpEntry.TYPE_PRIMARY -> "Baseline MP Primary Image"
+ MpEntry.TYPE_THUMBNAIL_VGA -> "Large Thumbnail (VGA equivalent)"
+ MpEntry.TYPE_THUMBNAIL_FULL_HD -> "Large Thumbnail (full HD equivalent)"
+ MpEntry.TYPE_PANORAMA -> "Multi-frame Panorama"
+ MpEntry.TYPE_DISPARITY -> "Multi-frame Disparity"
+ MpEntry.TYPE_MULTI_ANGLE -> "Multi-angle"
+ MpEntry.TYPE_UNDEFINED -> "Undefined"
+ else -> "Unknown ($type)"
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfDirectory.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfDirectory.kt
new file mode 100644
index 0000000..c0ea08c
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfDirectory.kt
@@ -0,0 +1,36 @@
+package deckers.thibault.aves.metadata.metadataextractor.mpf
+
+import com.drew.metadata.Directory
+import com.drew.metadata.TagDescriptor
+
+class MpfDirectory : Directory() {
+ init {
+ setDescriptor(MpfDescriptor(this))
+ }
+
+ override fun getName(): String {
+ return "MPF"
+ }
+
+ override fun getTagNameMap(): HashMap<Int, String> {
+ return _tagNameMap
+ }
+
+ companion object {
+ const val TAG_MPF_VERSION = 0xb000
+ const val TAG_NUMBER_OF_IMAGES = 0xb001
+ const val TAG_MP_ENTRY = 0xb002
+ private const val TAG_IMAGE_UID_LIST = 0xb003
+ private const val TAG_TOTAL_FRAMES = 0xb004
+
+ private val _tagNameMap = HashMap<Int, String>().apply {
+ put(TAG_MPF_VERSION, "MPF Version")
+ put(TAG_NUMBER_OF_IMAGES, "Number Of Images")
+ put(TAG_MP_ENTRY, "MP Entry")
+ put(TAG_IMAGE_UID_LIST, "Image UID List")
+ put(TAG_TOTAL_FRAMES, "Total Frames")
+ }
+ }
+}
+
+class MpfDescriptor(directory: MpfDirectory?) : TagDescriptor<MpfDirectory>(directory) \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfReader.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfReader.kt
new file mode 100644
index 0000000..423ff56
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/metadataextractor/mpf/MpfReader.kt
@@ -0,0 +1,95 @@
+package deckers.thibault.aves.metadata.metadataextractor.mpf
+
+import android.util.Log
+import com.drew.imaging.jpeg.JpegSegmentMetadataReader
+import com.drew.imaging.jpeg.JpegSegmentType
+import com.drew.lang.ByteArrayReader
+import com.drew.lang.RandomAccessReader
+import com.drew.metadata.Metadata
+import com.drew.metadata.MetadataReader
+import deckers.thibault.aves.utils.LogUtils
+
+class MpfReader : JpegSegmentMetadataReader, MetadataReader {
+ override fun getSegmentTypes(): Iterable<JpegSegmentType> {
+ return listOf(JpegSegmentType.APP2)
+ }
+
+ override fun readJpegSegments(segments: Iterable<ByteArray>, metadata: Metadata, segmentType: JpegSegmentType) {
+ for (segmentBytes in segments) {
+ // Skip segments not starting with the required header
+ if (segmentBytes.size >= PREAMBLE.length && PREAMBLE == String(segmentBytes, 0, PREAMBLE.length)) {
+ extract(ByteArrayReader(segmentBytes), metadata)
+ }
+ }
+ }
+
+ override fun extract(reader: RandomAccessReader, metadata: Metadata) {
+ val directory = MpfDirectory()
+ metadata.addDirectory(directory)
+
+ val baseOffset = 4
+
+ // MP Format Identifier (4Byte)
+ // MP header
+ // - MP Endian (4Byte)
+ val byteOrderIdentifier = reader.getInt16(baseOffset)
+ if (byteOrderIdentifier.toInt() == 0x4d4d) { // "MM"
+ reader.isMotorolaByteOrder = true
+ } else if (byteOrderIdentifier.toInt() == 0x4949) { // "II"
+ reader.isMotorolaByteOrder = false
+ }
+ // - Offset to First IFD (4Byte)
+ val firstIfdOffset = reader.getInt32(baseOffset + 4)
+
+ // [in primary image only] MP Index IFD:
+ // - Count (2Byte)
+ var offset = baseOffset + firstIfdOffset
+ val tagCount = reader.getInt16(offset)
+ offset += 2
+ // - MP Index Fields (Overall Structure Info.)
+ var imageCount = 0
+ for (tag in 0..<tagCount) {
+ when (val tagId = reader.getUInt16(offset)) {
+ MpfDirectory.TAG_MPF_VERSION -> directory.setString(tagId, reader.getString(offset + 8, 4, Charsets.US_ASCII))
+ MpfDirectory.TAG_NUMBER_OF_IMAGES -> {
+ imageCount = reader.getInt32(offset + 8)
+ directory.setInt(tagId, imageCount)
+ }
+
+ MpfDirectory.TAG_MP_ENTRY -> {
+ var mpEntryOffset = baseOffset + reader.getInt32(offset + 8)
+ for (index in 0..<imageCount) {
+ // individual image
+ val attribute = reader.getUInt32(mpEntryOffset)
+ val flags = (attribute shr 27 and 0x1f).toInt()
+ val format = (attribute shr 24 and 0x7).toInt()
+ val type = (attribute and 0xffffff).toInt()
+ val size = reader.getUInt32(mpEntryOffset + 4)
+ val dataOffset = reader.getUInt32(mpEntryOffset + 8)
+ val dep1 = reader.getInt16(mpEntryOffset + 12)
+ val dep2 = reader.getInt16(mpEntryOffset + 14)
+ metadata.addDirectory(MpEntryDirectory(index + 1, MpEntry(flags, format, type, size, dataOffset, dep1, dep2)))
+ mpEntryOffset += 16
+ }
+ }
+
+ else -> Log.d(LOG_TAG, "unknown tag=$tagId")
+ }
+ offset += 12
+ }
+
+ // - Offset of Next IFD (4Byte)
+ // Value (MP Index IFD)
+
+ // [in primary & other images] MP Attributes IFD:
+ // - Count (2Byte)
+ // - MP Attribute Fields (Details of Specific Image Usage)
+ // - Offset of Next IFD
+ // Value (MP Attribute IFD)
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<MpfReader>()
+ private const val PREAMBLE = "MPF"
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleDeviceContainer.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleDeviceContainer.kt
new file mode 100644
index 0000000..41d27f9
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleDeviceContainer.kt
@@ -0,0 +1,85 @@
+package deckers.thibault.aves.metadata.xmp
+
+import android.content.Context
+import android.net.Uri
+import com.adobe.internal.xmp.XMPMeta
+import deckers.thibault.aves.metadata.Metadata
+import deckers.thibault.aves.metadata.xmp.XMP.countPropPathArrayItems
+import deckers.thibault.aves.metadata.xmp.XMP.getSafeStructField
+import deckers.thibault.aves.utils.indexOfBytes
+import java.io.DataInputStream
+
+class GoogleDeviceContainer {
+ private val jfifSignature = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte(), 0xE0.toByte(), 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01)
+
+ private val items: MutableList<GoogleDeviceContainerItem> = ArrayList()
+ private val offsets: MutableList<Int> = ArrayList()
+
+ fun findItems(xmpMeta: XMPMeta) {
+ val containerDirectoryPath = listOf(GoogleXMP.GDEVICE_CONTAINER_PROP_NAME, GoogleXMP.GDEVICE_CONTAINER_DIRECTORY_PROP_NAME)
+ val count = xmpMeta.countPropPathArrayItems(containerDirectoryPath)
+ for (i in 1 until count + 1) {
+ val mimeType = xmpMeta.getSafeStructField(containerDirectoryPath + listOf(i, GoogleXMP.GDEVICE_CONTAINER_ITEM_MIME_PROP_NAME))?.value
+ val length = xmpMeta.getSafeStructField(containerDirectoryPath + listOf(i, GoogleXMP.GDEVICE_CONTAINER_ITEM_LENGTH_PROP_NAME))?.value?.toLongOrNull()
+ val dataUri = xmpMeta.getSafeStructField(containerDirectoryPath + listOf(i, GoogleXMP.GDEVICE_CONTAINER_ITEM_DATA_URI_PROP_NAME))?.value
+ if (mimeType != null && length != null && dataUri != null) {
+ items.add(
+ GoogleDeviceContainerItem(
+ mimeType = mimeType,
+ length = length,
+ dataUri = dataUri,
+ )
+ )
+ } else throw Exception("failed to extract Google device container item at index=$i with mimeType=$mimeType, length=$length, dataUri=$dataUri")
+ }
+ }
+
+ fun findOffsets(context: Context, uri: Uri, mimeType: String, sizeBytes: Long) {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ val bytes = ByteArray(sizeBytes.toInt())
+ DataInputStream(input).use {
+ it.readFully(bytes)
+ }
+
+ var start = 0
+ while (start < sizeBytes) {
+ val offset = bytes.indexOfBytes(jfifSignature, start)
+ if (offset != -1 && offset >= start) {
+ start = offset + jfifSignature.size
+ offsets.add(offset)
+ } else {
+ start = sizeBytes.toInt()
+ }
+ }
+ }
+
+ // fix first offset as it may refer to included thumbnail instead of primary image
+ while (offsets.size < items.size) {
+ offsets.add(0, 0)
+ }
+ offsets[0] = 0
+ }
+
+ fun itemIndex(dataUri: String) = items.indexOfFirst { it.dataUri == dataUri }
+
+ private fun item(index: Int): GoogleDeviceContainerItem? {
+ return if (0 <= index && index < items.size) {
+ items[index]
+ } else null
+ }
+
+ fun itemStartOffset(index: Int): Long? {
+ return if (0 <= index && index < offsets.size) {
+ offsets[index].toLong()
+ } else null
+ }
+
+ fun itemLength(index: Int): Long? {
+ val lengthByMeta = item(index)?.length ?: return null
+ return if (lengthByMeta != 0L) lengthByMeta else itemStartOffset(index + 1)
+ }
+
+ fun itemMimeType(index: Int) = item(index)?.mimeType
+}
+
+class GoogleDeviceContainerItem(val mimeType: String, val length: Long, val dataUri: String)
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleXMP.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleXMP.kt
new file mode 100644
index 0000000..f5f42d3
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/GoogleXMP.kt
@@ -0,0 +1,205 @@
+package deckers.thibault.aves.metadata.xmp
+
+import android.util.Log
+import com.adobe.internal.xmp.XMPError
+import com.adobe.internal.xmp.XMPException
+import com.adobe.internal.xmp.XMPMeta
+import deckers.thibault.aves.metadata.xmp.XMP.countPropArrayItems
+import deckers.thibault.aves.metadata.xmp.XMP.doesPropExist
+import deckers.thibault.aves.metadata.xmp.XMP.doesPropPathExist
+import deckers.thibault.aves.metadata.xmp.XMP.getSafeInt
+import deckers.thibault.aves.metadata.xmp.XMP.getSafeLong
+import deckers.thibault.aves.metadata.xmp.XMP.getSafeString
+import deckers.thibault.aves.metadata.xmp.XMP.getSafeStructField
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+
+object GoogleXMP {
+ private val LOG_TAG = LogUtils.createTag<GoogleXMP>()
+
+ // namespaces
+ private const val GAUDIO_NS_URI = "http://ns.google.com/photos/1.0/audio/"
+ private const val GCAMERA_NS_URI = "http://ns.google.com/photos/1.0/camera/"
+ private const val GCONTAINER_NS_URI = "http://ns.google.com/photos/1.0/container/"
+ private const val GCONTAINER_ITEM_NS_URI = "http://ns.google.com/photos/1.0/container/item/"
+ private const val GDEPTH_NS_URI = "http://ns.google.com/photos/1.0/depthmap/"
+ private const val GDEVICE_NS_URI = "http://ns.google.com/photos/dd/1.0/device/"
+ private const val GDEVICE_CONTAINER_NS_URI = "http://ns.google.com/photos/dd/1.0/container/"
+ private const val GDEVICE_ITEM_NS_URI = "http://ns.google.com/photos/dd/1.0/item/"
+ private const val GIMAGE_NS_URI = "http://ns.google.com/photos/1.0/image/"
+ private const val GPANO_NS_URI = "http://ns.google.com/photos/1.0/panorama/"
+
+ // embedded media data properties
+ // cf https://developers.google.com/depthmap-metadata
+ // cf https://developers.google.com/vr/reference/cardboard-camera-vr-photo-format
+ private val knownDataProps = listOf(
+ XMPPropName(GAUDIO_NS_URI, "Data"),
+ XMPPropName(GCAMERA_NS_URI, "RelitInputImageData"),
+ XMPPropName(GIMAGE_NS_URI, "Data"),
+ XMPPropName(GDEPTH_NS_URI, "Data"),
+ XMPPropName(GDEPTH_NS_URI, "Confidence"),
+ )
+
+
+ fun isDataPath(path: String) = knownDataProps.map { it.toString() }.any { path == it }
+
+ // google portrait
+
+ val GDEVICE_CONTAINER_PROP_NAME = XMPPropName(GDEVICE_NS_URI, "Container")
+ val GDEVICE_CONTAINER_DIRECTORY_PROP_NAME = XMPPropName(GDEVICE_CONTAINER_NS_URI, "Directory")
+ val GDEVICE_CONTAINER_ITEM_DATA_URI_PROP_NAME = XMPPropName(GDEVICE_ITEM_NS_URI, "DataURI")
+ val GDEVICE_CONTAINER_ITEM_LENGTH_PROP_NAME = XMPPropName(GDEVICE_ITEM_NS_URI, "Length")
+ val GDEVICE_CONTAINER_ITEM_MIME_PROP_NAME = XMPPropName(GDEVICE_ITEM_NS_URI, "Mime")
+
+ // container
+
+ private val GCAMERA_VIDEO_OFFSET_PROP_NAME = XMPPropName(GCAMERA_NS_URI, "MicroVideoOffset")
+ private val GCONTAINER_DIRECTORY_PROP_NAME = XMPPropName(GCONTAINER_NS_URI, "Directory")
+ private val GCONTAINER_ITEM_PROP_NAME = XMPPropName(GCONTAINER_NS_URI, "Item")
+ private val GCONTAINER_ITEM_LENGTH_PROP_NAME = XMPPropName(GCONTAINER_ITEM_NS_URI, "Length")
+ private val GCONTAINER_ITEM_MIME_PROP_NAME = XMPPropName(GCONTAINER_ITEM_NS_URI, "Mime")
+ private val GCONTAINER_ITEM_SEMANTIC_PROP_NAME = XMPPropName(GCONTAINER_ITEM_NS_URI, "Semantic")
+
+ private const val ITEM_SEMANTIC_GAIN_MAP = "GainMap"
+
+ // panorama
+ // cf https://developers.google.com/streetview/spherical-metadata
+
+ private val GPANO_CROPPED_AREA_HEIGHT_PROP_NAME = XMPPropName(GPANO_NS_URI, "CroppedAreaImageHeightPixels")
+ private val GPANO_CROPPED_AREA_WIDTH_PROP_NAME = XMPPropName(GPANO_NS_URI, "CroppedAreaImageWidthPixels")
+ private val GPANO_CROPPED_AREA_LEFT_PROP_NAME = XMPPropName(GPANO_NS_URI, "CroppedAreaLeftPixels")
+ private val GPANO_CROPPED_AREA_TOP_PROP_NAME = XMPPropName(GPANO_NS_URI, "CroppedAreaTopPixels")
+ private val GPANO_FULL_PANO_HEIGHT_PROP_NAME = XMPPropName(GPANO_NS_URI, "FullPanoHeightPixels")
+ private val GPANO_FULL_PANO_WIDTH_PROP_NAME = XMPPropName(GPANO_NS_URI, "FullPanoWidthPixels")
+ private val GPANO_PROJECTION_TYPE_PROP_NAME = XMPPropName(GPANO_NS_URI, "ProjectionType")
+ const val GPANO_PROJECTION_TYPE_DEFAULT = "equirectangular"
+
+ // `GPano:ProjectionType` is required by spec but it is sometimes missing, assuming default
+ // `GPano:FullPanoHeightPixels` is required by spec but it is sometimes missing (e.g. Samsung Camera app panorama mode)
+ private val gpanoRequiredProps = listOf(
+ GPANO_CROPPED_AREA_HEIGHT_PROP_NAME,
+ GPANO_CROPPED_AREA_WIDTH_PROP_NAME,
+ GPANO_CROPPED_AREA_LEFT_PROP_NAME,
+ GPANO_CROPPED_AREA_TOP_PROP_NAME,
+ GPANO_FULL_PANO_WIDTH_PROP_NAME,
+ )
+
+ fun isUltraHdPhoto(meta: XMPMeta): Boolean {
+ if (meta.doesPropExist(GCONTAINER_DIRECTORY_PROP_NAME)) {
+ val count = meta.countPropArrayItems(GCONTAINER_DIRECTORY_PROP_NAME)
+ for (i in 1 until count + 1) {
+ val semantic = meta.getSafeStructField(listOf(GCONTAINER_DIRECTORY_PROP_NAME, i, GCONTAINER_ITEM_PROP_NAME, GCONTAINER_ITEM_SEMANTIC_PROP_NAME))?.value
+ if (semantic == ITEM_SEMANTIC_GAIN_MAP) {
+ return true
+ }
+ }
+ }
+ return false
+ }
+
+ fun isMotionPhoto(meta: XMPMeta): Boolean {
+ try {
+ // GCamera motion photo
+ if (meta.doesPropExist(GCAMERA_VIDEO_OFFSET_PROP_NAME)) return true
+
+ // Container motion photo
+ if (meta.doesPropExist(GCONTAINER_DIRECTORY_PROP_NAME)) {
+ val count = meta.countPropArrayItems(GCONTAINER_DIRECTORY_PROP_NAME)
+ var hasImage = false
+ var hasVideo = false
+ for (i in 1 until count + 1) {
+ val mime = getContainerItemAttribute(meta, i, GCONTAINER_ITEM_MIME_PROP_NAME)
+ val length = getContainerItemAttribute(meta, i, GCONTAINER_ITEM_LENGTH_PROP_NAME)
+ // `length` is not always provided for the image item
+ hasImage = hasImage || MimeTypes.isImage(mime)
+ hasVideo = hasVideo || (MimeTypes.isVideo(mime) && length != null)
+ }
+ if (hasImage && hasVideo) return true
+ }
+
+ return false
+ } catch (e: XMPException) {
+ if (e.errorCode != XMPError.BADSCHEMA) {
+ // `BADSCHEMA` code is reported when we check a property
+ // from a non standard namespace, and that namespace is not declared in the XMP
+ Log.w(LOG_TAG, "failed to check Google motion photo props from XMP", e)
+ }
+ }
+ return false
+ }
+
+ private fun getContainerItemAttribute(meta: XMPMeta, i: Int, attribute: XMPPropName): String? {
+ // variant of `Container:Item` with `<rdf:li rdf:parseType="Resource">`
+ val mime = meta.getSafeStructField(listOf(GCONTAINER_DIRECTORY_PROP_NAME, i, GCONTAINER_ITEM_PROP_NAME, attribute))?.value
+ // variant of `Container:Item` with `<rdf:li>`
+ return mime ?: meta.getSafeStructField(listOf(GCONTAINER_DIRECTORY_PROP_NAME, i, attribute))?.value
+ }
+
+ fun isPanorama(meta: XMPMeta): Boolean {
+ try {
+ if (gpanoRequiredProps.all { meta.doesPropExist(it) }) return true
+ } catch (e: XMPException) {
+ if (e.errorCode != XMPError.BADSCHEMA) {
+ // `BADSCHEMA` code is reported when we check a property
+ // from a non standard namespace, and that namespace is not declared in the XMP
+ Log.w(LOG_TAG, "failed to check Google panorama props from XMP", e)
+ }
+ }
+ return false
+ }
+
+ fun getPanoramaInfo(meta: XMPMeta): FieldMap {
+ val fields: FieldMap = hashMapOf()
+ try {
+ meta.getSafeInt(GPANO_CROPPED_AREA_LEFT_PROP_NAME) { fields["croppedAreaLeft"] = it }
+ meta.getSafeInt(GPANO_CROPPED_AREA_TOP_PROP_NAME) { fields["croppedAreaTop"] = it }
+ meta.getSafeInt(GPANO_CROPPED_AREA_WIDTH_PROP_NAME) { fields["croppedAreaWidth"] = it }
+ meta.getSafeInt(GPANO_CROPPED_AREA_HEIGHT_PROP_NAME) { fields["croppedAreaHeight"] = it }
+ meta.getSafeInt(GPANO_FULL_PANO_WIDTH_PROP_NAME) { fields["fullPanoWidth"] = it }
+ meta.getSafeInt(GPANO_FULL_PANO_HEIGHT_PROP_NAME) { fields["fullPanoHeight"] = it }
+ meta.getSafeString(GPANO_PROJECTION_TYPE_PROP_NAME) { fields["projectionType"] = it }
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to read XMP directory", e)
+ }
+ return fields
+ }
+
+ fun getTrailingVideoOffsetFromEnd(meta: XMPMeta): Long? {
+ var offsetFromEnd: Long? = null
+ if (meta.doesPropExist(GCAMERA_VIDEO_OFFSET_PROP_NAME)) {
+ // `GCamera` motion photo
+ meta.getSafeLong(GCAMERA_VIDEO_OFFSET_PROP_NAME) { offsetFromEnd = it }
+ } else if (meta.doesPropExist(GCONTAINER_DIRECTORY_PROP_NAME)) {
+ // `Container` motion photo
+ val count = meta.countPropArrayItems(GCONTAINER_DIRECTORY_PROP_NAME)
+ for (i in 1 until count + 1) {
+ val mime = getContainerItemAttribute(meta, i, GCONTAINER_ITEM_MIME_PROP_NAME)
+ if (MimeTypes.isVideo(mime)) {
+ getContainerItemAttribute(meta, i, GCONTAINER_ITEM_LENGTH_PROP_NAME)?.let { offsetFromEnd = it.toLong() }
+ }
+ }
+ }
+ return offsetFromEnd
+ }
+
+ fun updateTrailingVideoOffset(xmp: String, oldOffset: Number, newOffset: Number): String {
+ return xmp.replace(
+ // GCamera motion photo
+ "${GCAMERA_VIDEO_OFFSET_PROP_NAME}=\"$oldOffset\"",
+ "${GCAMERA_VIDEO_OFFSET_PROP_NAME}=\"$newOffset\"",
+ ).replace(
+ // Container motion photo
+ "${GCONTAINER_ITEM_LENGTH_PROP_NAME}=\"$oldOffset\"",
+ "${GCONTAINER_ITEM_LENGTH_PROP_NAME}=\"$newOffset\"",
+ )
+ }
+
+ fun getDeviceContainer(meta: XMPMeta): GoogleDeviceContainer? {
+ return if (meta.doesPropPathExist(listOf(GDEVICE_CONTAINER_PROP_NAME, GDEVICE_CONTAINER_DIRECTORY_PROP_NAME))) {
+ GoogleDeviceContainer().apply { findItems(meta) }
+ } else {
+ null
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/XMP.kt b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/XMP.kt
new file mode 100644
index 0000000..20e6a7a
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/metadata/xmp/XMP.kt
@@ -0,0 +1,317 @@
+package deckers.thibault.aves.metadata.xmp
+
+import android.content.Context
+import android.net.Uri
+import android.os.Build
+import android.provider.MediaStore
+import android.util.Log
+import com.adobe.internal.xmp.XMPError
+import com.adobe.internal.xmp.XMPException
+import com.adobe.internal.xmp.XMPMeta
+import com.adobe.internal.xmp.XMPMetaFactory
+import com.adobe.internal.xmp.properties.XMPProperty
+import com.drew.metadata.Directory
+import deckers.thibault.aves.metadata.Mp4ParserHelper
+import deckers.thibault.aves.metadata.Mp4ParserHelper.processBoxes
+import deckers.thibault.aves.metadata.Mp4ParserHelper.toBytes
+import deckers.thibault.aves.metadata.metadataextractor.SafeMp4UuidBoxHandler
+import deckers.thibault.aves.metadata.metadataextractor.SafeXmpReader
+import deckers.thibault.aves.utils.ContextUtils.queryContentPropValue
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MemoryUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.isIsoBMFFImage
+import deckers.thibault.aves.utils.StorageUtils
+import org.mp4parser.IsoFile
+import org.mp4parser.boxes.UserBox
+import java.io.FileInputStream
+import java.util.TimeZone
+
+object XMP {
+ private val LOG_TAG = LogUtils.createTag<XMP>()
+
+ // BE7ACFCB 97A942E8 9C719994 91E3AFAC / BE7ACFCB-97A9-42E8-9C71-999491E3AFAC
+ val mp4Uuid = byteArrayOf(0xbe.toByte(), 0x7a, 0xcf.toByte(), 0xcb.toByte(), 0x97.toByte(), 0xa9.toByte(), 0x42, 0xe8.toByte(), 0x9c.toByte(), 0x71, 0x99.toByte(), 0x94.toByte(), 0x91.toByte(), 0xe3.toByte(), 0xaf.toByte(), 0xac.toByte())
+
+ // standard namespaces
+ // cf com.adobe.internal.xmp.XMPConst
+ private const val DC_NS_URI = "http://purl.org/dc/elements/1.1/"
+ private const val MICROSOFTPHOTO_NS_URI = "http://ns.microsoft.com/photo/1.0/"
+ private const val PHOTOSHOP_NS_URI = "http://ns.adobe.com/photoshop/1.0/"
+ private const val XMP_NS_URI = "http://ns.adobe.com/xap/1.0/"
+
+ // other namespaces
+ private const val APPLE_HDRGM_NS_URI = "http://ns.apple.com/HDRGainMap/1.0/"
+ private const val HDRGM_NS_URI = "http://ns.adobe.com/hdr-gain-map/1.0/"
+ private const val PMTM_NS_URI = "http://www.hdrsoft.com/photomatix_settings01"
+
+ val DC_SUBJECT_PROP_NAME = XMPPropName(DC_NS_URI, "subject")
+ val DC_DESCRIPTION_PROP_NAME = XMPPropName(DC_NS_URI, "description")
+ val DC_TITLE_PROP_NAME = XMPPropName(DC_NS_URI, "title")
+ val MS_RATING_PROP_NAME = XMPPropName(MICROSOFTPHOTO_NS_URI, "Rating")
+ val PS_DATE_CREATED_PROP_NAME = XMPPropName(PHOTOSHOP_NS_URI, "DateCreated")
+ val XMP_CREATE_DATE_PROP_NAME = XMPPropName(XMP_NS_URI, "CreateDate")
+ val XMP_RATING_PROP_NAME = XMPPropName(XMP_NS_URI, "Rating")
+
+ private const val GENERIC_LANG = ""
+ private const val SPECIFIC_LANG = "en-US"
+
+ fun isDataPath(path: String) = GoogleXMP.isDataPath(path)
+
+ // HDR gain map
+
+ private val HDRGM_VERSION_PROP_NAME = XMPPropName(HDRGM_NS_URI, "Version")
+ private val APPLE_HDRGM_VERSION_PROP_NAME = XMPPropName(APPLE_HDRGM_NS_URI, "HDRGainMapVersion")
+
+ // panorama
+
+ private val PMTM_IS_PANO360_PROP_NAME = XMPPropName(PMTM_NS_URI, "IsPano360")
+
+ // as of `metadata-extractor` v2.18.0, XMP is not discovered in AVIF/HEIC images,
+ // so we fall back to the native content resolver, if possible
+ fun checkIsoBMFFImage(
+ context: Context,
+ mimeType: String,
+ uri: Uri,
+ foundXmp: Boolean,
+ processXmp: (xmpMeta: XMPMeta) -> Unit,
+ ) {
+ if (!foundXmp && isIsoBMFFImage(mimeType) && StorageUtils.isMediaStoreContentUri(uri) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ try {
+ val xmpBytes = context.queryContentPropValue(uri, mimeType, MediaStore.MediaColumns.XMP)
+ if (xmpBytes is ByteArray && xmpBytes.isNotEmpty()) {
+ val xmpMeta = XMPMetaFactory.parseFromBuffer(xmpBytes, SafeXmpReader.PARSE_OPTIONS)
+ processXmp(xmpMeta)
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get XMP by content resolver for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+ }
+
+ // as of `metadata-extractor` v2.18.0, processing large MP4 files may crash,
+ // so we fall back to parsing with `mp4parser`
+ fun checkMp4(
+ context: Context,
+ mimeType: String,
+ uri: Uri,
+ processDirs: (dirs: List<Directory>) -> Unit,
+ ) {
+ if (mimeType != MimeTypes.MP4) return
+ try {
+ // we can skip uninteresting boxes with a seekable data source
+ val pfd = StorageUtils.openInputFileDescriptor(context, uri) ?: throw Exception("failed to open file descriptor for uri=$uri")
+ pfd.use {
+ FileInputStream(it.fileDescriptor).use { stream ->
+ stream.channel.use { channel ->
+ // creating `IsoFile` with a `File` or a `File.inputStream()` yields `No such device`
+ IsoFile(channel, Mp4ParserHelper.metadataBoxParser()).use { isoFile ->
+ isoFile.processBoxes(UserBox::class.java, true) { box, _ ->
+ val boxSize = box.size
+ if (MemoryUtils.canAllocate(boxSize)) {
+ val bytes = box.toBytes()
+ val payload = bytes.copyOfRange(8, bytes.size)
+
+ val metadata = com.drew.metadata.Metadata()
+ SafeMp4UuidBoxHandler(metadata).processBox("", payload, -1, null)
+ processDirs(metadata.directories.filter { dir -> dir.tagCount > 0 }.toList())
+ } else {
+ Log.w(LOG_TAG, "MP4 box too large at $boxSize bytes, for mimeType=$mimeType uri=$uri")
+ }
+ }
+ }
+ }
+ }
+ }
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to parse MP4 for mimeType=$mimeType uri=$uri", e)
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get XMP by MP4 parser for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+
+ // extensions
+
+ fun XMPMeta.hasHdrGainMap(): Boolean {
+ try {
+ // standard HDR gain map
+ if (doesPropExist(HDRGM_VERSION_PROP_NAME)) return true
+
+ // `Ultra HDR`
+ if (GoogleXMP.isUltraHdPhoto(this)) return true
+
+ // Apple HDR gain map
+ if (doesPropExist(APPLE_HDRGM_VERSION_PROP_NAME)) return true
+
+ return false
+ } catch (e: XMPException) {
+ if (e.errorCode != XMPError.BADSCHEMA) {
+ // `BADSCHEMA` code is reported when we check a property
+ // from a non standard namespace, and that namespace is not declared in the XMP
+ Log.w(LOG_TAG, "failed to check HDR props from XMP", e)
+ }
+ }
+ return false
+ }
+
+ fun XMPMeta.isMotionPhoto() = GoogleXMP.isMotionPhoto(this)
+
+ fun XMPMeta.isPanorama(): Boolean {
+ // Google
+ if (GoogleXMP.isPanorama(this)) return true
+
+ // Photomatix
+ try {
+ if (getPropertyString(PMTM_IS_PANO360_PROP_NAME.nsUri, PMTM_IS_PANO360_PROP_NAME.toString()) == "Yes") return true
+ } catch (e: XMPException) {
+ if (e.errorCode != XMPError.BADSCHEMA) {
+ // `BADSCHEMA` code is reported when we check a property
+ // from a non standard namespace, and that namespace is not declared in the XMP
+ Log.w(LOG_TAG, "failed to check Photomatix panorama props from XMP", e)
+ }
+ }
+
+ return false
+ }
+
+ fun XMPMeta.doesPropExist(prop: XMPPropName): Boolean {
+ return doesPropertyExist(prop.nsUri, prop.toString())
+ }
+
+ fun XMPMeta.doesPropPathExist(props: List<XMPPropName>): Boolean {
+ return doesPropertyExist(props.first().nsUri, props.joinToString("/"))
+ }
+
+ fun XMPMeta.countPropArrayItems(prop: XMPPropName): Int {
+ return countArrayItems(prop.nsUri, prop.toString())
+ }
+
+ fun XMPMeta.countPropPathArrayItems(props: List<XMPPropName>): Int {
+ return countArrayItems(props.first().nsUri, props.joinToString("/"))
+ }
+
+ fun XMPMeta.getPropArrayItemValues(prop: XMPPropName): List<String> {
+ val schema = prop.nsUri
+ val propName = prop.toString()
+ val count = countArrayItems(schema, propName)
+ return (1 until count + 1).map { getArrayItem(schema, propName, it).value }
+ }
+
+ fun XMPMeta.getSafeInt(prop: XMPPropName, save: (value: Int) -> Unit) {
+ val schema = prop.nsUri
+ val propName = prop.toString()
+ try {
+ if (doesPropertyExist(schema, propName)) {
+ val item = getPropertyInteger(schema, propName)
+ // double check retrieved items as the property sometimes is reported to exist but it is actually null
+ if (item != null) {
+ save(item)
+ }
+ }
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to get int for XMP schema=$schema, propName=$propName", e)
+ }
+ }
+
+ fun XMPMeta.getSafeLong(prop: XMPPropName, save: (value: Long) -> Unit) {
+ val schema = prop.nsUri
+ val propName = prop.toString()
+ try {
+ if (doesPropertyExist(schema, propName)) {
+ val item = getPropertyLong(schema, propName)
+ // double check retrieved items as the property sometimes is reported to exist but it is actually null
+ if (item != null) {
+ save(item)
+ }
+ }
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to get long for XMP schema=$schema, propName=$propName", e)
+ }
+ }
+
+ fun XMPMeta.getSafeString(prop: XMPPropName, save: (value: String) -> Unit) {
+ val schema = prop.nsUri
+ val propName = prop.toString()
+ try {
+ if (doesPropertyExist(schema, propName)) {
+ val item = getPropertyString(schema, propName)
+ // double check retrieved items as the property sometimes is reported to exist but it is actually null
+ if (item != null) {
+ save(item)
+ }
+ }
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to get int for XMP schema=$schema, propName=$propName", e)
+ }
+ }
+
+ fun XMPMeta.getSafeLocalizedText(prop: XMPPropName, acceptBlank: Boolean = true, save: (value: String) -> Unit) {
+ val schema = prop.nsUri
+ val propName = prop.toString()
+ try {
+ if (doesPropertyExist(schema, propName)) {
+ val item = getLocalizedText(schema, propName, GENERIC_LANG, SPECIFIC_LANG)
+ // double check retrieved items as the property sometimes is reported to exist but it is actually null
+ if (item != null && (acceptBlank || item.value.isNotBlank())) {
+ save(item.value)
+ }
+ }
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to get text for XMP schema=$schema, propName=$propName", e)
+ }
+ }
+
+ fun XMPMeta.getSafeDateMillis(prop: XMPPropName, save: (value: Long) -> Unit) {
+ val schema = prop.nsUri
+ val propName = prop.toString()
+ try {
+ if (doesPropertyExist(schema, propName)) {
+ val item = getPropertyDate(schema, propName)
+ // double check retrieved items as the property sometimes is reported to exist but it is actually null
+ if (item != null) {
+ // strip time zone from XMP dates so that we show date/times as local ones
+ // this aligns with Exif date/times, which are specified without time zones
+ item.timeZone = TimeZone.getDefault()
+ save(item.calendar.timeInMillis)
+ }
+ }
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to get date for XMP schema=$schema, propName=$propName", e)
+ }
+ }
+
+ // e.g. path 'Container:Directory[42]/Container:Item/Item:Mime' matches:
+ // - structNs: "http://ns.google.com/photos/1.0/container/"
+ // - structName: "Container:Directory[42]/Container:Item"
+ // - fieldNs: "http://ns.google.com/photos/1.0/container/item/"
+ // - fieldName: "Item:Mime"
+ fun XMPMeta.getSafeStructField(props: List<Any>): XMPProperty? {
+ if (props.size >= 2) {
+ val structFirst = props.first()
+ val field = props.last()
+ if (structFirst is XMPPropName && field is XMPPropName) {
+ val structName = props.take(props.size - 1).mapIndexed { index, prop ->
+ when (prop) {
+ is XMPPropName -> "${if (index == 0) "" else "/"}$prop"
+ is Int -> "[$prop]"
+ else -> null
+ }
+ }.filterNotNull().joinToString("")
+ val fieldName = field.toString()
+
+ try {
+ return getStructField(structFirst.nsUri, structName, field.nsUri, fieldName)
+ } catch (e: XMPException) {
+ Log.w(LOG_TAG, "failed to get XMP struct field for props=$props", e)
+ }
+ }
+ }
+ return null
+ }
+}
+
+class XMPPropName(val nsUri: String, private val prop: String) {
+ private fun resolve(): String = "${XMPMetaFactory.getSchemaRegistry().getNamespacePrefix(nsUri)}$prop"
+
+ override fun toString(): String = resolve()
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/AvesEntry.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/AvesEntry.kt
new file mode 100644
index 0000000..00017e8
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/AvesEntry.kt
@@ -0,0 +1,37 @@
+package deckers.thibault.aves.model
+
+import android.net.Uri
+import androidx.core.net.toUri
+
+class AvesEntry(map: FieldMap) {
+ val uri: Uri = (map[EntryFields.URI] as String).toUri() // content or file URI
+ val path = map[EntryFields.PATH] as String? // best effort to get local path
+ val pageId = map[EntryFields.PAGE_ID] as Int? // null means the main entry
+ val mimeType = map[EntryFields.MIME_TYPE] as String
+ val width = map[EntryFields.WIDTH] as Int
+ val height = map[EntryFields.HEIGHT] as Int
+ val rotationDegrees = map[EntryFields.ROTATION_DEGREES] as Int
+ val isFlipped = map[EntryFields.IS_FLIPPED] as Boolean
+ val sizeBytes = toLong(map[EntryFields.SIZE_BYTES])
+ val trashed = map[EntryFields.TRASHED] as Boolean
+ val trashPath = map[EntryFields.TRASH_PATH] as String?
+
+ private val isRotated: Boolean
+ get() = rotationDegrees % 180 == 90
+
+ val displayWidth: Int
+ get() = if (isRotated) height else width
+
+ val displayHeight: Int
+ get() = if (isRotated) width else height
+
+ override fun toString(): String = "AvesEntry#${hashCode()}{uri=$uri path=$path pageId=$pageId mimeType=$mimeType width=$width height=$height rotationDegrees=$rotationDegrees isFlipped=$isFlipped sizeBytes=$sizeBytes trashed=$trashed trashPath=$trashPath}"
+
+ companion object {
+ // convenience method
+ private fun toLong(o: Any?): Long? = when (o) {
+ is Int -> o.toLong()
+ else -> o as? Long
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/EntryFields.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/EntryFields.kt
new file mode 100644
index 0000000..1dab12b
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/EntryFields.kt
@@ -0,0 +1,29 @@
+package deckers.thibault.aves.model
+
+// entry fields exported and imported from/to the platform side
+// should match `EntryFields` on Dart side
+object EntryFields {
+ const val ORIGIN = "origin" // int
+ const val URI = "uri" // string
+ const val CONTENT_ID = "contentId" // long
+ const val PATH = "path" // string
+ const val PAGE_ID = "pageId" // int
+ const val SOURCE_MIME_TYPE = "sourceMimeType" // string
+ const val MIME_TYPE = "mimeType" // string
+
+ const val WIDTH = "width" // int
+ const val HEIGHT = "height" // int
+ const val SOURCE_ROTATION_DEGREES = "sourceRotationDegrees" // int
+ const val ROTATION_DEGREES = "rotationDegrees" // int
+ const val IS_FLIPPED = "isFlipped" // boolean
+
+ const val DATE_ADDED_SECS = "dateAddedSecs" // long
+ const val DATE_MODIFIED_MILLIS = "dateModifiedMillis" // long
+ const val SOURCE_DATE_TAKEN_MILLIS = "sourceDateTakenMillis" // long
+ const val DURATION_MILLIS = "durationMillis" // long
+
+ const val SIZE_BYTES = "sizeBytes" // long
+ const val TRASHED = "trashed" // boolean
+ const val TRASH_PATH = "trashPath" // string
+ const val TITLE = "title" // string
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/ExifOrientationOp.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/ExifOrientationOp.kt
new file mode 100644
index 0000000..7b7737c
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/ExifOrientationOp.kt
@@ -0,0 +1,5 @@
+package deckers.thibault.aves.model
+
+enum class ExifOrientationOp {
+ ROTATE_CW, ROTATE_CCW, FLIP
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/FieldMap.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/FieldMap.kt
new file mode 100644
index 0000000..78592a2
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/FieldMap.kt
@@ -0,0 +1,3 @@
+package deckers.thibault.aves.model
+
+typealias FieldMap = MutableMap<String, Any?>
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/NameConflictStrategy.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/NameConflictStrategy.kt
new file mode 100644
index 0000000..21f59a7
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/NameConflictStrategy.kt
@@ -0,0 +1,16 @@
+package deckers.thibault.aves.model
+
+import java.io.File
+
+enum class NameConflictStrategy {
+ RENAME, REPLACE, SKIP;
+
+ companion object {
+ fun get(name: String?): NameConflictStrategy? {
+ name ?: return null
+ return valueOf(name.uppercase())
+ }
+ }
+}
+
+class NameConflictResolution(var nameWithoutExtension: String?, var replacementFile: File?) \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/SourceEntry.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/SourceEntry.kt
new file mode 100644
index 0000000..39fccd8
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/SourceEntry.kt
@@ -0,0 +1,280 @@
+package deckers.thibault.aves.model
+
+import android.content.ContentResolver
+import android.content.Context
+import android.graphics.BitmapFactory
+import android.media.MediaMetadataRetriever
+import android.net.Uri
+import androidx.core.net.toUri
+import com.drew.metadata.avi.AviDirectory
+import com.drew.metadata.exif.ExifIFD0Directory
+import com.drew.metadata.jpeg.JpegDirectory
+import com.drew.metadata.mp4.Mp4Directory
+import com.drew.metadata.mp4.media.Mp4VideoDirectory
+import com.drew.metadata.photoshop.PsdHeaderDirectory
+import deckers.thibault.aves.glide.TiffFetcher
+import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeDateMillis
+import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeInt
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeDateMillis
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeInt
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeLong
+import deckers.thibault.aves.metadata.MediaMetadataRetrieverHelper.getSafeString
+import deckers.thibault.aves.metadata.Metadata
+import deckers.thibault.aves.metadata.Metadata.getRotationDegreesForExifCode
+import deckers.thibault.aves.metadata.metadataextractor.Helper
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeDateMillis
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeInt
+import deckers.thibault.aves.metadata.metadataextractor.Helper.getSafeLong
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.StorageUtils
+import deckers.thibault.aves.utils.UriUtils.tryParseId
+import org.beyka.tiffbitmapfactory.TiffBitmapFactory
+import java.io.IOException
+import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface
+
+class SourceEntry {
+ private val origin: Int
+ val uri: Uri // content or file URI
+ var path: String? = null // best effort to get local path
+ private val sourceMimeType: String
+ private var title: String? = null
+ var width: Int? = null
+ var height: Int? = null
+ private var sourceRotationDegrees: Int? = null
+ private var sizeBytes: Long? = null
+ private var dateAddedSecs: Long? = null
+ private var dateModifiedMillis: Long? = null
+ private var sourceDateTakenMillis: Long? = null
+ private var durationMillis: Long? = null
+
+ private var foundExif: Boolean = false
+
+ constructor(origin: Int, uri: Uri, sourceMimeType: String) {
+ this.origin = origin
+ this.uri = uri
+ this.sourceMimeType = sourceMimeType
+ }
+
+ constructor(map: FieldMap) {
+ origin = map[EntryFields.ORIGIN] as Int
+ uri = (map[EntryFields.URI] as String).toUri()
+ path = map[EntryFields.PATH] as String?
+ sourceMimeType = map[EntryFields.SOURCE_MIME_TYPE] as String
+ width = map[EntryFields.WIDTH] as Int?
+ height = map[EntryFields.HEIGHT] as Int?
+ sourceRotationDegrees = map[EntryFields.SOURCE_ROTATION_DEGREES] as Int?
+ sizeBytes = toLong(map[EntryFields.SIZE_BYTES])
+ title = map[EntryFields.TITLE] as String?
+ dateAddedSecs = toLong(map[EntryFields.DATE_ADDED_SECS])
+ dateModifiedMillis = toLong(map[EntryFields.DATE_MODIFIED_MILLIS])
+ sourceDateTakenMillis = toLong(map[EntryFields.SOURCE_DATE_TAKEN_MILLIS])
+ durationMillis = toLong(map[EntryFields.DURATION_MILLIS])
+ }
+
+ fun initFromFile(path: String, title: String, sizeBytes: Long, dateModifiedMillis: Long) {
+ this.path = path
+ this.title = title
+ this.sizeBytes = sizeBytes
+ this.dateModifiedMillis = dateModifiedMillis
+ }
+
+ fun toMap(): FieldMap {
+ return hashMapOf(
+ EntryFields.ORIGIN to origin,
+ EntryFields.URI to uri.toString(),
+ EntryFields.PATH to path,
+ EntryFields.SOURCE_MIME_TYPE to sourceMimeType,
+ EntryFields.WIDTH to width,
+ EntryFields.HEIGHT to height,
+ EntryFields.SOURCE_ROTATION_DEGREES to (sourceRotationDegrees ?: 0),
+ EntryFields.SIZE_BYTES to sizeBytes,
+ EntryFields.TITLE to title,
+ EntryFields.DATE_ADDED_SECS to dateAddedSecs,
+ EntryFields.DATE_MODIFIED_MILLIS to dateModifiedMillis,
+ EntryFields.SOURCE_DATE_TAKEN_MILLIS to sourceDateTakenMillis,
+ EntryFields.DURATION_MILLIS to durationMillis,
+ // only for map export
+ EntryFields.CONTENT_ID to contentId,
+ )
+ }
+
+ // ignore when the ID is not a number
+ // e.g. content://com.sec.android.app.myfiles.FileProvider/device_storage/20200109_162621.jpg
+ private val contentId: Long?
+ get() = if (uri.scheme == ContentResolver.SCHEME_CONTENT) uri.tryParseId() else null
+
+ val isSized: Boolean
+ get() = (width ?: 0) > 0 && (height ?: 0) > 0
+
+ private val hasDuration: Boolean
+ get() = (durationMillis ?: 0) > 0
+
+ val isVideo: Boolean
+ get() = MimeTypes.isVideo(sourceMimeType)
+
+ val isSvg: Boolean
+ get() = sourceMimeType == MimeTypes.SVG
+
+ // metadata retrieval
+ // expects entry with: uri, mimeType
+ // finds: width, height, orientation/rotation, date, title, duration
+ fun fillPreCatalogMetadata(context: Context): SourceEntry {
+ if (isSvg) return this
+ if (isVideo) {
+ fillVideoByMediaMetadataRetriever(context)
+ if (isSized && hasDuration) return this
+ fillByMetadataExtractor(context)
+ } else {
+ fillByMetadataExtractor(context)
+ if (isSized && foundExif) return this
+ fillByExifInterface(context)
+ }
+ if (!isSized) {
+ when (sourceMimeType) {
+ MimeTypes.TIFF -> fillByTiffDecode(context)
+ else -> fillByBitmapDecode(context)
+ }
+ }
+ return this
+ }
+
+ // finds: width, height, orientation, date, duration, title
+ private fun fillVideoByMediaMetadataRetriever(context: Context) {
+ val retriever = StorageUtils.openMetadataRetriever(context, uri) ?: return
+ try {
+ retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH) { width = it }
+ retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT) { height = it }
+ retriever.getSafeLong(MediaMetadataRetriever.METADATA_KEY_DURATION) { durationMillis = it }
+ retriever.getSafeDateMillis(MediaMetadataRetriever.METADATA_KEY_DATE) { sourceDateTakenMillis = it }
+ retriever.getSafeString(MediaMetadataRetriever.METADATA_KEY_TITLE) { title = it }
+ retriever.getSafeInt(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION) { sourceRotationDegrees = it }
+ } catch (_: Exception) {
+ // ignore
+ } finally {
+ // cannot rely on `MediaMetadataRetriever` being `AutoCloseable` on older APIs
+ retriever.release()
+ }
+ }
+
+ // finds: width, height, orientation, date, duration
+ private fun fillByMetadataExtractor(context: Context) {
+ // skip raw images because `metadata-extractor` reports the decoded dimensions instead of the raw dimensions
+ if (!MimeTypes.canReadWithMetadataExtractor(sourceMimeType)
+ || MimeTypes.isRaw(sourceMimeType)
+ ) return
+
+ try {
+ Metadata.openSafeInputStream(context, uri, sourceMimeType, sizeBytes)?.use { input ->
+ val metadata = Helper.safeRead(input, sizeBytes)
+
+ // do not switch on specific MIME types, as the reported MIME type could be wrong
+ // (e.g. PNG registered as JPG)
+ if (isVideo) {
+ for (dir in metadata.getDirectoriesOfType(AviDirectory::class.java)) {
+ dir.getSafeInt(AviDirectory.TAG_WIDTH) { width = it }
+ dir.getSafeInt(AviDirectory.TAG_HEIGHT) { height = it }
+ dir.getSafeLong(AviDirectory.TAG_DURATION) { durationMillis = it }
+ }
+ for (dir in metadata.getDirectoriesOfType(Mp4VideoDirectory::class.java)) {
+ dir.getSafeInt(Mp4VideoDirectory.TAG_WIDTH) { width = it }
+ dir.getSafeInt(Mp4VideoDirectory.TAG_HEIGHT) { height = it }
+ }
+ for (dir in metadata.getDirectoriesOfType(Mp4Directory::class.java)) {
+ dir.getSafeInt(Mp4Directory.TAG_ROTATION) { sourceRotationDegrees = it }
+ dir.getSafeLong(Mp4Directory.TAG_DURATION) { durationMillis = it }
+ }
+ } else {
+ for (dir in metadata.getDirectoriesOfType(ExifIFD0Directory::class.java)) {
+ foundExif = true
+ dir.getSafeInt(ExifIFD0Directory.TAG_IMAGE_WIDTH) { width = it }
+ dir.getSafeInt(ExifIFD0Directory.TAG_IMAGE_HEIGHT) { height = it }
+ dir.getSafeInt(ExifIFD0Directory.TAG_ORIENTATION) { sourceRotationDegrees = getRotationDegreesForExifCode(it) }
+ dir.getSafeDateMillis(ExifIFD0Directory.TAG_DATETIME, null)?.let { sourceDateTakenMillis = it }
+ }
+
+ // dimensions reported in EXIF do not always match the image
+ // so we fetch them from the format directory if available
+ for (dir in metadata.getDirectoriesOfType(JpegDirectory::class.java)) {
+ dir.getSafeInt(JpegDirectory.TAG_IMAGE_WIDTH) { width = it }
+ dir.getSafeInt(JpegDirectory.TAG_IMAGE_HEIGHT) { height = it }
+ }
+ for (dir in metadata.getDirectoriesOfType(PsdHeaderDirectory::class.java)) {
+ dir.getSafeInt(PsdHeaderDirectory.TAG_IMAGE_WIDTH) { width = it }
+ dir.getSafeInt(PsdHeaderDirectory.TAG_IMAGE_HEIGHT) { height = it }
+ }
+ }
+ }
+ } catch (_: Exception) {
+ // ignore
+ } catch (_: NoClassDefFoundError) {
+ // ignore
+ } catch (_: AssertionError) {
+ // ignore
+ }
+ }
+
+ // finds: width, height, orientation, date
+ private fun fillByExifInterface(context: Context) {
+ if (!MimeTypes.canReadWithExifInterface(sourceMimeType)) return
+
+ try {
+ Metadata.openSafeInputStream(context, uri, sourceMimeType, sizeBytes)?.use { input ->
+ val exif = ExifInterface(input)
+ foundExif = true
+ exif.getSafeInt(ExifInterface.TAG_IMAGE_WIDTH, acceptZero = false) { width = it }
+ exif.getSafeInt(ExifInterface.TAG_IMAGE_LENGTH, acceptZero = false) { height = it }
+ exif.getSafeInt(ExifInterface.TAG_ORIENTATION, acceptZero = false) { sourceRotationDegrees = exif.rotationDegrees }
+ exif.getSafeDateMillis(ExifInterface.TAG_DATETIME, ExifInterface.TAG_SUBSEC_TIME) { sourceDateTakenMillis = it }
+ }
+ } catch (_: Exception) {
+ // ExifInterface initialization can fail with a RuntimeException
+ // caused by an internal MediaMetadataRetriever failure
+ }
+ }
+
+ // finds: width, height
+ private fun fillByBitmapDecode(context: Context) {
+ try {
+ StorageUtils.openInputStream(context, uri)?.use { input ->
+ val options = BitmapFactory.Options().apply {
+ inJustDecodeBounds = true
+ }
+ BitmapFactory.decodeStream(input, null, options)
+ width = options.outWidth
+ height = options.outHeight
+ }
+ } catch (_: IOException) {
+ // ignore
+ }
+ }
+
+ private fun fillByTiffDecode(context: Context) {
+ try {
+ context.contentResolver.openFileDescriptor(uri, "r")?.use { pfd ->
+ val fd = pfd.detachFd()
+ val options = TiffFetcher.buildOptions().apply {
+ inJustDecodeBounds = true
+ }
+ TiffBitmapFactory.decodeFileDescriptor(fd, options)
+ width = options.outWidth
+ height = options.outHeight
+ }
+ } catch (_: Exception) {
+ // ignore
+ }
+ }
+
+ companion object {
+ // convenience method
+ private fun toLong(o: Any?): Long? = when (o) {
+ is Int -> o.toLong()
+ else -> o as? Long
+ }
+
+ // should match `EntryOrigins` on the Dart side
+ const val ORIGIN_MEDIA_STORE_CONTENT = 0
+ const val ORIGIN_UNKNOWN_CONTENT = 1
+ const val ORIGIN_FILE = 2
+ const val ORIGIN_VAULT = 3
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/AvesEmbeddedMediaProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/AvesEmbeddedMediaProvider.kt
new file mode 100644
index 0000000..49f0a88
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/AvesEmbeddedMediaProvider.kt
@@ -0,0 +1,18 @@
+package deckers.thibault.aves.model.provider
+
+import android.content.ContentResolver
+import android.content.Context
+import android.net.Uri
+import java.util.Locale
+
+class AvesEmbeddedMediaProvider : UnknownContentProvider() {
+ override val reliableProviderMimeType: Boolean
+ get() = true
+
+ companion object {
+ fun provides(context: Context, uri: Uri): Boolean {
+ if (uri.scheme?.lowercase(Locale.ROOT) != ContentResolver.SCHEME_CONTENT) return false
+ return uri.authority == "${context.applicationContext.packageName}.file_provider"
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/FileImageProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/FileImageProvider.kt
new file mode 100644
index 0000000..ce9dabf
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/FileImageProvider.kt
@@ -0,0 +1,126 @@
+package deckers.thibault.aves.model.provider
+
+import android.app.Activity
+import android.content.Context
+import android.content.ContextWrapper
+import android.net.Uri
+import android.util.Log
+import android.webkit.MimeTypeMap
+import deckers.thibault.aves.model.EntryFields
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.model.SourceEntry
+import deckers.thibault.aves.utils.LogUtils
+import java.io.File
+
+internal class FileImageProvider : ImageProvider() {
+ override fun fetchSingle(context: Context, uri: Uri, sourceMimeType: String?, allowUnsized: Boolean, callback: ImageOpCallback) {
+ var mimeType = sourceMimeType
+ val path = uri.path
+
+ if (mimeType == null) {
+ // try to guess by file extension
+ var extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
+ if (extension.isEmpty() && path != null) {
+ val lastDotIndex = path.lastIndexOf('.')
+ if (lastDotIndex >= 0) {
+ extension = path.substring(lastDotIndex + 1)
+ }
+ }
+ if (extension.isNotEmpty()) {
+ mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
+ }
+ }
+
+ if (mimeType == null) {
+ // try to guess by file preview read
+ var sizeBytes: Long? = null
+ try {
+ path?.let { sizeBytes = File(it).length() }
+ } catch (e: SecurityException) {
+ callback.onFailure(e)
+ return
+ }
+ mimeType = detectMimeType(context, uri, mimeType = null, sizeBytes)
+ }
+
+ if (mimeType == null) {
+ callback.onFailure(Exception("MIME type was not provided and cannot be guessed from extension or preview of uri=$uri"))
+ return
+ }
+
+ val entry = SourceEntry(SourceEntry.ORIGIN_FILE, uri, mimeType)
+
+ if (path != null) {
+ try {
+ val file = File(path)
+ if (file.exists()) {
+ entry.initFromFile(
+ path = path,
+ title = file.name,
+ sizeBytes = file.length(),
+ dateModifiedMillis = file.lastModified(),
+ )
+ }
+ } catch (e: SecurityException) {
+ callback.onFailure(e)
+ return
+ }
+ }
+ entry.fillPreCatalogMetadata(context)
+
+ if (allowUnsized || entry.isSized || entry.isSvg || entry.isVideo) {
+ callback.onSuccess(entry.toMap())
+ } else {
+ callback.onFailure(Exception("entry has no size"))
+ }
+ }
+
+ override fun delete(contextWrapper: ContextWrapper, uri: Uri, path: String?, mimeType: String) {
+ path ?: throw Exception("failed to delete file because path is null")
+
+ val file = File(path)
+ if (file.exists()) {
+ Log.d(LOG_TAG, "delete file at path=$path")
+ if (!file.delete()) {
+ throw Exception("failed to delete entry with uri=$uri path=$path")
+ }
+ }
+ }
+
+ override suspend fun renameSingle(
+ activity: Activity,
+ mimeType: String,
+ oldMediaUri: Uri,
+ oldPath: String,
+ newFile: File,
+ ): FieldMap {
+ Log.d(LOG_TAG, "rename file at path=$oldPath")
+ val renamed = File(oldPath).renameTo(newFile)
+ if (!renamed) {
+ throw Exception("failed to rename file at path=$oldPath")
+ }
+
+ return hashMapOf(
+ EntryFields.URI to Uri.fromFile(newFile).toString(),
+ EntryFields.PATH to newFile.path,
+ EntryFields.DATE_MODIFIED_MILLIS to newFile.lastModified(),
+ )
+ }
+
+ override fun scanPostMetadataEdit(context: Context, path: String, uri: Uri, mimeType: String, newFields: FieldMap, callback: ImageOpCallback) {
+ try {
+ val file = File(path)
+ if (file.exists()) {
+ newFields[EntryFields.DATE_MODIFIED_MILLIS] = file.lastModified()
+ newFields[EntryFields.SIZE_BYTES] = file.length()
+ }
+ callback.onSuccess(newFields)
+ } catch (e: SecurityException) {
+ callback.onFailure(e)
+ }
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<MediaStoreImageProvider>()
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProvider.kt
new file mode 100644
index 0000000..284238f
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProvider.kt
@@ -0,0 +1,1443 @@
+package deckers.thibault.aves.model.provider
+
+import android.app.Activity
+import android.content.Context
+import android.content.ContextWrapper
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.graphics.Bitmap
+import android.graphics.ImageDecoder
+import android.net.Uri
+import android.os.Binder
+import android.os.Build
+import android.util.Log
+import androidx.core.net.toUri
+import com.bumptech.glide.Glide
+import com.bumptech.glide.request.FutureTarget
+import com.commonsware.cwac.document.DocumentFileCompat
+import deckers.thibault.aves.glide.AvesAppGlideModule
+import deckers.thibault.aves.metadata.ExifInterfaceHelper
+import deckers.thibault.aves.metadata.ExifInterfaceHelper.getSafeDateMillis
+import deckers.thibault.aves.metadata.Metadata
+import deckers.thibault.aves.metadata.Metadata.TYPE_EXIF
+import deckers.thibault.aves.metadata.Metadata.TYPE_IPTC
+import deckers.thibault.aves.metadata.Metadata.TYPE_MP4
+import deckers.thibault.aves.metadata.Metadata.TYPE_XMP
+import deckers.thibault.aves.metadata.Mp4ParserHelper
+import deckers.thibault.aves.metadata.Mp4ParserHelper.updateLocation
+import deckers.thibault.aves.metadata.Mp4ParserHelper.updateRotation
+import deckers.thibault.aves.metadata.Mp4ParserHelper.updateXmp
+import deckers.thibault.aves.metadata.MultiPage
+import deckers.thibault.aves.metadata.PixyMetaHelper
+import deckers.thibault.aves.metadata.PixyMetaHelper.extendedXmpDocString
+import deckers.thibault.aves.metadata.PixyMetaHelper.xmpDocString
+import deckers.thibault.aves.metadata.metadataextractor.Helper
+import deckers.thibault.aves.metadata.xmp.GoogleXMP
+import deckers.thibault.aves.model.AvesEntry
+import deckers.thibault.aves.model.EntryFields
+import deckers.thibault.aves.model.ExifOrientationOp
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.model.NameConflictResolution
+import deckers.thibault.aves.model.NameConflictStrategy
+import deckers.thibault.aves.model.SourceEntry
+import deckers.thibault.aves.utils.BitmapUtils
+import deckers.thibault.aves.utils.BmpWriter
+import deckers.thibault.aves.utils.FileUtils.transferFrom
+import deckers.thibault.aves.utils.FileUtils.transferTo
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.canEditExif
+import deckers.thibault.aves.utils.MimeTypes.canEditIptc
+import deckers.thibault.aves.utils.MimeTypes.canEditXmp
+import deckers.thibault.aves.utils.MimeTypes.canReadWithExifInterface
+import deckers.thibault.aves.utils.MimeTypes.canRemoveMetadata
+import deckers.thibault.aves.utils.MimeTypes.extensionFor
+import deckers.thibault.aves.utils.MimeTypes.isVideo
+import deckers.thibault.aves.utils.StorageUtils
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.io.ByteArrayInputStream
+import java.io.File
+import java.io.FileOutputStream
+import java.io.IOException
+import java.io.OutputStream
+import java.nio.channels.Channels
+import java.util.Date
+import java.util.TimeZone
+import kotlin.math.absoluteValue
+import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface
+
+abstract class ImageProvider {
+ open fun fetchSingle(context: Context, uri: Uri, sourceMimeType: String?, allowUnsized: Boolean, callback: ImageOpCallback) {
+ callback.onFailure(UnsupportedOperationException("`fetchSingle` is not supported by this image provider"))
+ }
+
+ suspend fun scanNewPath(context: Context, path: String, mimeType: String): FieldMap {
+ return if (StorageUtils.isInVault(context, path)) {
+ val uri = Uri.fromFile(File(path))
+ hashMapOf(
+ EntryFields.ORIGIN to SourceEntry.ORIGIN_VAULT,
+ EntryFields.URI to uri.toString(),
+ EntryFields.CONTENT_ID to null,
+ EntryFields.PATH to path,
+ )
+ } else {
+ MediaStoreImageProvider().scanNewPathByMediaStore(context, path, mimeType)
+ }
+ }
+
+ private fun deletePath(contextWrapper: ContextWrapper, path: String, mimeType: String) {
+ if (StorageUtils.isInVault(contextWrapper, path)) {
+ FileImageProvider().apply {
+ val uri = Uri.fromFile(File(path))
+ delete(contextWrapper, uri, path, mimeType)
+ }
+ } else {
+ MediaStoreImageProvider().apply {
+ val uri = getContentUriForPath(contextWrapper, path)
+ uri ?: throw Exception("failed to find content URI for path=$path")
+ delete(contextWrapper, uri, path, mimeType)
+ }
+ }
+ }
+
+ open fun delete(contextWrapper: ContextWrapper, uri: Uri, path: String?, mimeType: String) {
+ throw UnsupportedOperationException("`delete` is not supported by this image provider")
+ }
+
+ open suspend fun moveMultiple(
+ activity: Activity,
+ copy: Boolean,
+ nameConflictStrategy: NameConflictStrategy,
+ entriesByTargetDir: Map<String, List<AvesEntry>>,
+ isCancelledOp: CancelCheck,
+ callback: ImageOpCallback,
+ ) {
+ callback.onFailure(UnsupportedOperationException("`moveMultiple` is not supported by this image provider"))
+ }
+
+ suspend fun renameMultiple(
+ activity: Activity,
+ entriesToNewName: Map<AvesEntry, String>,
+ isCancelledOp: CancelCheck,
+ callback: ImageOpCallback,
+ ) {
+ for (kv in entriesToNewName) {
+ val entry = kv.key
+ val desiredName = kv.value
+
+ val sourceUri = entry.uri
+ val sourcePath = entry.path
+ val mimeType = entry.mimeType
+
+ val result: FieldMap = hashMapOf(
+ "uri" to sourceUri.toString(),
+ "success" to false,
+ )
+
+ if (sourcePath != null) {
+ try {
+ var newFields: FieldMap = skippedFieldMap
+ if (!isCancelledOp()) {
+ val desiredNameWithoutExtension = desiredName.substringBeforeLast(".")
+
+ val oldFile = File(sourcePath)
+ if (oldFile.nameWithoutExtension != desiredNameWithoutExtension) {
+ val defaultExtension = oldFile.extension
+ oldFile.parent?.let { dir ->
+ val resolution = resolveTargetFileNameWithoutExtension(
+ contextWrapper = activity,
+ dir = dir,
+ desiredNameWithoutExtension = desiredNameWithoutExtension,
+ mimeType = mimeType,
+ defaultExtension = defaultExtension,
+ conflictStrategy = NameConflictStrategy.RENAME,
+ )
+ resolution.nameWithoutExtension?.let { targetNameWithoutExtension ->
+ val targetFileName = "$targetNameWithoutExtension${extensionFor(mimeType, defaultExtension)}"
+ val newFile = File(dir, targetFileName)
+ if (oldFile != newFile) {
+ newFields = renameSingle(
+ activity = activity,
+ mimeType = mimeType,
+ oldMediaUri = sourceUri,
+ oldPath = sourcePath,
+ newFile = newFile,
+ )
+ }
+ }
+ }
+ }
+ }
+ result["newFields"] = newFields
+ result["success"] = true
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to rename to newFileName=$desiredName entry with sourcePath=$sourcePath", e)
+ }
+ }
+ callback.onSuccess(result)
+ }
+ }
+
+ open suspend fun renameSingle(
+ activity: Activity,
+ mimeType: String,
+ oldMediaUri: Uri,
+ oldPath: String,
+ newFile: File,
+ ): FieldMap {
+ throw UnsupportedOperationException("`renameSingle` is not supported by this image provider")
+ }
+
+ open fun scanPostMetadataEdit(context: Context, path: String, uri: Uri, mimeType: String, newFields: FieldMap, callback: ImageOpCallback) {
+ throw UnsupportedOperationException("`scanPostMetadataEdit` is not supported by this image provider")
+ }
+
+ suspend fun convertMultiple(
+ activity: Activity,
+ imageExportMimeType: String,
+ targetDir: String,
+ entries: List<AvesEntry>,
+ quality: Int,
+ lengthUnit: String,
+ width: Int,
+ height: Int,
+ writeMetadata: Boolean,
+ nameConflictStrategy: NameConflictStrategy,
+ callback: ImageOpCallback,
+ ) {
+ if (!supportedExportMimeTypes.contains(imageExportMimeType)) {
+ callback.onFailure(Exception("unsupported export MIME type=$imageExportMimeType"))
+ return
+ }
+
+ val targetDirDocFile = StorageUtils.createDirectoryDocIfAbsent(activity, targetDir)
+ if (!File(targetDir).exists()) {
+ callback.onFailure(Exception("failed to create directory at path=$targetDir"))
+ return
+ }
+
+ for (entry in entries) {
+ val sourceUri = entry.uri
+ val sourcePath = entry.path
+ val pageId = entry.pageId
+
+ val result: FieldMap = hashMapOf(
+ "uri" to sourceUri.toString(),
+ "pageId" to pageId,
+ "success" to false,
+ )
+
+ val sourceMimeType = entry.mimeType
+ val exportMimeType = if (isVideo(sourceMimeType)) sourceMimeType else imageExportMimeType
+ try {
+ val newFields = convertSingle(
+ activity = activity,
+ sourceEntry = entry,
+ targetDir = targetDir,
+ targetDirDocFile = targetDirDocFile,
+ quality = quality,
+ lengthUnit = lengthUnit,
+ width = width,
+ height = height,
+ writeMetadata = writeMetadata,
+ nameConflictStrategy = nameConflictStrategy,
+ exportMimeType = exportMimeType,
+ )
+ result["newFields"] = newFields
+ result["success"] = true
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to convert to targetDir=$targetDir entry with sourcePath=$sourcePath pageId=$pageId", e)
+ }
+ callback.onSuccess(result)
+ }
+ }
+
+ private suspend fun convertSingle(
+ activity: Activity,
+ sourceEntry: AvesEntry,
+ targetDir: String,
+ targetDirDocFile: DocumentFileCompat?,
+ quality: Int,
+ lengthUnit: String,
+ width: Int,
+ height: Int,
+ writeMetadata: Boolean,
+ nameConflictStrategy: NameConflictStrategy,
+ exportMimeType: String,
+ ): FieldMap {
+ val sourceMimeType = sourceEntry.mimeType
+ var sourceUri = sourceEntry.uri
+ val pageId = sourceEntry.pageId
+
+ var desiredNameWithoutExtension = if (sourceEntry.path != null) {
+ val sourceFileName = File(sourceEntry.path).name
+ sourceFileName.substringBeforeLast(".")
+ } else {
+ sourceUri.lastPathSegment!!
+ }
+ if (pageId != null) {
+ val page = if (sourceMimeType == MimeTypes.TIFF) pageId + 1 else pageId
+ desiredNameWithoutExtension += "_${page.toString().padStart(3, '0')}"
+ }
+
+ // there is no benefit providing input extension
+ // for known output MIME type
+ val defaultExtension = null
+
+ val resolution = resolveTargetFileNameWithoutExtension(
+ contextWrapper = activity,
+ dir = targetDir,
+ desiredNameWithoutExtension = desiredNameWithoutExtension,
+ mimeType = exportMimeType,
+ defaultExtension = defaultExtension,
+ conflictStrategy = nameConflictStrategy,
+ )
+ val targetNameWithoutExtension = resolution.nameWithoutExtension ?: return skippedFieldMap
+ resolution.replacementFile?.let { file ->
+ sourceUri = Uri.fromFile(file)
+ }
+
+ val targetMimeType: String
+ val write: (OutputStream) -> Unit
+ var target: FutureTarget<Bitmap>? = null
+ try {
+ if (isVideo(sourceMimeType)) {
+ targetMimeType = sourceMimeType
+ write = { output ->
+ val sourceDocFile = DocumentFileCompat.fromSingleUri(activity, sourceUri)
+ sourceDocFile.copyTo(output)
+ }
+ } else {
+ var targetWidthPx: Int
+ var targetHeightPx: Int
+ when (lengthUnit) {
+ LENGTH_UNIT_PERCENT -> {
+ targetWidthPx = sourceEntry.displayWidth * width / 100
+ targetHeightPx = sourceEntry.displayHeight * height / 100
+ }
+
+ else -> {
+ targetWidthPx = width
+ targetHeightPx = height
+ }
+ }
+
+ val rotationDegrees = sourceEntry.rotationDegrees
+ val needRotationAfterGlide = MimeTypes.needRotationAfterGlide(sourceMimeType, pageId)
+ if (rotationDegrees != 0 && needRotationAfterGlide) {
+ targetWidthPx = targetHeightPx.also { targetHeightPx = targetWidthPx }
+ }
+
+ target = Glide.with(activity.applicationContext)
+ .asBitmap()
+ .apply(AvesAppGlideModule.uncachedFullImageOptions)
+ .load(AvesAppGlideModule.getModel(activity, sourceUri, sourceMimeType, pageId, sourceEntry.sizeBytes))
+ .submit(targetWidthPx, targetHeightPx)
+
+ var bitmap = withContext(Dispatchers.IO) { target.get() }
+ if (needRotationAfterGlide) {
+ bitmap = BitmapUtils.applyExifOrientation(activity, bitmap, rotationDegrees, sourceEntry.isFlipped)
+ }
+ bitmap ?: throw Exception("failed to get image for mimeType=$sourceMimeType uri=$sourceUri page=$pageId")
+
+ targetMimeType = exportMimeType
+ write = { output ->
+ if (exportMimeType == MimeTypes.BMP) {
+ BmpWriter.writeRGB24(bitmap, output)
+ } else {
+ val format = when (exportMimeType) {
+ MimeTypes.JPEG -> Bitmap.CompressFormat.JPEG
+ MimeTypes.PNG -> Bitmap.CompressFormat.PNG
+ MimeTypes.WEBP -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ if (quality == 100) {
+ Bitmap.CompressFormat.WEBP_LOSSLESS
+ } else {
+ Bitmap.CompressFormat.WEBP_LOSSY
+ }
+ } else {
+ @Suppress("deprecation")
+ Bitmap.CompressFormat.WEBP
+ }
+
+ else -> throw Exception("unsupported export MIME type=$exportMimeType")
+ }
+ bitmap.compress(format, quality, output)
+ }
+ }
+ }
+
+ val targetPath = MediaStoreImageProvider().createSingle(
+ activity = activity,
+ mimeType = targetMimeType,
+ targetDir = targetDir,
+ targetDirDocFile = targetDirDocFile,
+ targetNameWithoutExtension = targetNameWithoutExtension,
+ defaultExtension = defaultExtension,
+ write = write,
+ )
+
+ val newFields = scanNewPath(activity, targetPath, exportMimeType)
+ val targetUri = (newFields[EntryFields.URI] as String).toUri()
+ if (writeMetadata) {
+ copyMetadata(
+ context = activity,
+ sourceMimeType = sourceMimeType,
+ sourceUri = sourceUri,
+ targetMimeType = targetMimeType,
+ targetUri = targetUri,
+ targetPath = targetPath,
+ )
+ }
+
+ return newFields
+ } finally {
+ // clearing Glide target should happen after effectively writing the bitmap
+ Glide.with(activity.applicationContext).clear(target)
+
+ resolution.replacementFile?.delete()
+ }
+ }
+
+ private fun copyMetadata(
+ context: Context,
+ sourceMimeType: String,
+ sourceUri: Uri,
+ targetMimeType: String,
+ targetUri: Uri,
+ targetPath: String,
+ ) {
+ val editableFile = StorageUtils.createTempFile(context).apply {
+ // copy original file to a temporary file for editing
+ val inputStream = StorageUtils.openInputStream(context, targetUri)
+ transferFrom(inputStream, File(targetPath).length())
+ }
+
+ // copy IPTC / XMP via PixyMeta
+ PixyMetaHelper.copyIptcXmp(context, sourceMimeType, sourceUri, targetMimeType, targetUri, editableFile)
+
+ // copy Exif via ExifInterface
+
+ val exif = HashMap<String, String?>()
+ val skippedTags = listOf(
+ ExifInterface.TAG_IMAGE_LENGTH,
+ ExifInterface.TAG_IMAGE_WIDTH,
+ ExifInterface.TAG_ORIENTATION,
+ // Thumbnail Offset / Length
+ ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT,
+ ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH,
+ // Exif Image Width / Height
+ ExifInterface.TAG_PIXEL_X_DIMENSION,
+ ExifInterface.TAG_PIXEL_Y_DIMENSION,
+ )
+ if (canReadWithExifInterface(sourceMimeType) && canEditExif(targetMimeType)) {
+ StorageUtils.openInputStream(context, sourceUri)?.use { input ->
+ ExifInterface(input).apply {
+ ExifInterfaceHelper.allTags.keys.filterNot { skippedTags.contains(it) }.filter { hasAttribute(it) }.forEach { tag ->
+ exif[tag] = getAttribute(tag)
+ }
+ }
+ }
+ }
+ if (exif.isNotEmpty()) {
+ ExifInterface(editableFile).apply {
+ exif.entries.forEach { (tag, value) ->
+ setAttribute(tag, value)
+ }
+ saveAttributes()
+ }
+ }
+
+ // copy the edited temporary file back to the original
+ editableFile.transferTo(outputStream(context, targetMimeType, targetUri, targetPath))
+ editableFile.delete()
+ }
+
+ suspend fun captureFrame(
+ contextWrapper: ContextWrapper,
+ desiredNameWithoutExtension: String,
+ exifFields: FieldMap,
+ bytes: ByteArray,
+ targetDir: String,
+ nameConflictStrategy: NameConflictStrategy,
+ callback: ImageOpCallback,
+ ) {
+ val targetDirDocFile = StorageUtils.createDirectoryDocIfAbsent(contextWrapper, targetDir)
+ if (!File(targetDir).exists()) {
+ callback.onFailure(Exception("failed to create directory at path=$targetDir"))
+ return
+ }
+
+ // TODO TLAD [storage] allow inserting by Media Store
+ if (targetDirDocFile == null) {
+ callback.onFailure(Exception("failed to get tree doc for directory at path=$targetDir"))
+ return
+ }
+
+ val captureMimeType = MimeTypes.JPEG
+ val resolution = try {
+ resolveTargetFileNameWithoutExtension(
+ contextWrapper = contextWrapper,
+ dir = targetDir,
+ desiredNameWithoutExtension = desiredNameWithoutExtension,
+ mimeType = captureMimeType,
+ defaultExtension = null,
+ conflictStrategy = nameConflictStrategy,
+ )
+ } catch (e: Exception) {
+ callback.onFailure(e)
+ return
+ }
+
+ val targetNameWithoutExtension = resolution.nameWithoutExtension
+ if (targetNameWithoutExtension == null) {
+ // skip it
+ callback.onSuccess(skippedFieldMap)
+ return
+ }
+
+ // the file created from a `TreeDocumentFile` is also a `TreeDocumentFile`
+ // but in order to open an output stream to it, we need to use a `SingleDocumentFile`
+ // through a document URI, not a tree URI
+ // note that `DocumentFile.getParentFile()` returns null if we did not pick a tree first
+ val targetTreeFile = targetDirDocFile.createFile(captureMimeType, targetNameWithoutExtension)
+ val targetDocFile = DocumentFileCompat.fromSingleUri(contextWrapper, targetTreeFile.uri)
+
+ try {
+ if (exifFields.isEmpty()) {
+ targetDocFile.openOutputStream().use { output ->
+ output.write(bytes)
+ }
+ } else {
+ val editableFile = withContext(Dispatchers.IO) { StorageUtils.createTempFile(contextWrapper) }.apply {
+ transferFrom(ByteArrayInputStream(bytes), bytes.size.toLong())
+ }
+
+ val exif = ExifInterface(editableFile)
+
+ val rotationDegrees = exifFields["rotationDegrees"] as Int?
+ if (rotationDegrees != null) {
+ // when the orientation is not defined, it returns `undefined (0)` instead of the orientation default value `normal (1)`
+ // in that case we explicitly set it to `normal` first
+ // because ExifInterface fails to rotate an image with undefined orientation
+ // as of androidx.exifinterface:exifinterface:1.3.0
+ val currentOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
+ if (currentOrientation == ExifInterface.ORIENTATION_UNDEFINED) {
+ exif.setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL.toString())
+ }
+ exif.rotate(rotationDegrees)
+ }
+
+ val dateTimeMillis = (exifFields["dateTimeMillis"] as Number?)?.toLong()
+ if (dateTimeMillis != null) {
+ val dateString = ExifInterfaceHelper.DATETIME_FORMAT.format(Date(dateTimeMillis))
+ exif.setAttribute(ExifInterface.TAG_DATETIME, dateString)
+ exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, dateString)
+
+ val timeZoneString = getTimeZoneString(TimeZone.getDefault(), dateTimeMillis)
+ exif.setAttribute(ExifInterface.TAG_OFFSET_TIME, timeZoneString)
+ exif.setAttribute(ExifInterface.TAG_OFFSET_TIME_ORIGINAL, timeZoneString)
+
+ val sub = dateTimeMillis % 1000
+ if (sub > 0) {
+ val subString = sub.toString()
+ exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME, subString)
+ exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, subString)
+ }
+ }
+
+ val latitude = (exifFields["latitude"] as Number?)?.toDouble()
+ val longitude = (exifFields["longitude"] as Number?)?.toDouble()
+ if (latitude != null && longitude != null) {
+ exif.setLatLong(latitude, longitude)
+ }
+
+ exif.saveAttributes()
+
+ // copy the edited temporary file back to the original
+ DocumentFileCompat.fromFile(editableFile).copyTo(targetDocFile)
+ editableFile.delete()
+ }
+
+ val fileName = targetDocFile.name
+ val targetFullPath = targetDir + fileName
+ val newFields = scanNewPath(contextWrapper, targetFullPath, captureMimeType)
+ callback.onSuccess(newFields)
+ } catch (e: Exception) {
+ callback.onFailure(e)
+ }
+ }
+
+ fun createTimeStampFileName() = Date().time.toString()
+
+ private fun sanitizeDesiredFileName(desiredName: String): String {
+ var name = desiredName
+ // prevent creating hidden files
+ while (name.isNotEmpty() && name.startsWith(".")) {
+ name = name.substring(1)
+ }
+ if (name.isEmpty()) {
+ name = createTimeStampFileName()
+ }
+ return name
+ }
+
+ // returns available name to use, or `null` to skip it
+ fun resolveTargetFileNameWithoutExtension(
+ contextWrapper: ContextWrapper,
+ dir: String,
+ desiredNameWithoutExtension: String,
+ mimeType: String,
+ defaultExtension: String?,
+ conflictStrategy: NameConflictStrategy,
+ ): NameConflictResolution {
+ val sanitizedNameWithoutExtension = sanitizeDesiredFileName(desiredNameWithoutExtension)
+ var resolvedName: String? = sanitizedNameWithoutExtension
+ var replacementFile: File? = null
+
+ val extension = extensionFor(mimeType, defaultExtension)
+ val targetFile = File(dir, "$sanitizedNameWithoutExtension$extension")
+ when (conflictStrategy) {
+ NameConflictStrategy.RENAME -> {
+ var nameWithoutExtension = sanitizedNameWithoutExtension
+ var i = 0
+ while (File(dir, "$nameWithoutExtension$extension").exists()) {
+ i++
+ nameWithoutExtension = "$sanitizedNameWithoutExtension ($i)"
+ }
+ resolvedName = nameWithoutExtension
+ }
+
+ NameConflictStrategy.REPLACE -> {
+ if (targetFile.exists()) {
+ // move replaced file to temp storage
+ // so that it can be used as a source for conversion or metadata copy
+ replacementFile = StorageUtils.createTempFile(contextWrapper).apply {
+ targetFile.transferTo(outputStream())
+ }
+ deletePath(contextWrapper, targetFile.path, mimeType)
+ }
+ }
+
+ NameConflictStrategy.SKIP -> {
+ if (targetFile.exists()) {
+ resolvedName = null
+ }
+ }
+ }
+
+ return NameConflictResolution(resolvedName, replacementFile)
+ }
+
+ // cf `MetadataFetchHandler.getCatalogMetadataByMetadataExtractor()` for a more thorough check
+ fun detectMimeType(context: Context, uri: Uri, mimeType: String?, sizeBytes: Long?): String? {
+ var detectedMimeType: String? = null
+ if (MimeTypes.canReadWithMetadataExtractor(mimeType)) {
+ try {
+ Metadata.openSafeInputStream(context, uri, mimeType, sizeBytes)?.use { input ->
+ detectedMimeType = Helper.readMimeType(input)
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to read metadata by metadata-extractor for mimeType=$mimeType uri=$uri", e)
+ }
+ }
+ return detectedMimeType
+ }
+
+ private fun editExif(
+ context: Context,
+ path: String,
+ uri: Uri,
+ mimeType: String,
+ callback: ImageOpCallback,
+ autoCorrectTrailerOffset: Boolean = true,
+ trailerDiff: Int = 0,
+ edit: (exif: ExifInterface) -> Unit,
+ ): Boolean {
+ if (!canEditExif(mimeType)) {
+ callback.onFailure(UnsupportedOperationException("unsupported mimeType=$mimeType"))
+ return false
+ }
+
+ val originalFileSize = File(path).length()
+ var trailerVideoBytes: ByteArray? = null
+ val editableFile = StorageUtils.createTempFile(context).apply {
+ val trailerVideoSize = MultiPage.getTrailerVideoSize(context, uri, mimeType, originalFileSize)?.let { it + trailerDiff }
+ val isTrailerVideoValid = trailerVideoSize != null && MultiPage.getTrailerVideoInfo(context, uri, originalFileSize, trailerVideoSize) != null
+ try {
+ if (trailerVideoSize != null && isTrailerVideoValid) {
+ // handle motion photo and embedded video separately
+ val imageSize = (originalFileSize - trailerVideoSize).toInt()
+ val videoByteSize = trailerVideoSize.toInt()
+ trailerVideoBytes = ByteArray(videoByteSize)
+
+ StorageUtils.openInputStream(context, uri)?.let { input ->
+ val imageBytes = ByteArray(imageSize)
+ input.read(imageBytes, 0, imageSize)
+ input.read(trailerVideoBytes, 0, videoByteSize)
+
+ // copy only the image to a temporary file for editing
+ // video will be appended after metadata modification
+ transferFrom(ByteArrayInputStream(imageBytes), imageBytes.size.toLong())
+ }
+ } else {
+ // copy original file to a temporary file for editing
+ val inputStream = StorageUtils.openInputStream(context, uri)
+ transferFrom(inputStream, originalFileSize)
+ }
+ } catch (e: Exception) {
+ callback.onFailure(e)
+ return false
+ }
+ }
+
+ try {
+ edit(ExifInterface(editableFile))
+
+ val editableFileSizeBytes = editableFile.length()
+ if (editableFileSizeBytes == 0L) {
+ callback.onFailure(Exception("editing Exif yielded an empty file"))
+ return false
+ }
+
+ val editedMimeType = detectMimeType(context, Uri.fromFile(editableFile), mimeType, editableFileSizeBytes)
+ if (editedMimeType != mimeType) {
+ throw Exception("editing Exif changes mimeType=$mimeType -> $editedMimeType for uri=$uri path=$path")
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
+ // editing may corrupt the file for various reasons,
+ // so we check whether decoding it throws an exception
+ ImageDecoder.decodeBitmap(ImageDecoder.createSource(editableFile))
+ }
+
+ if (trailerVideoBytes != null) {
+ // append trailer video, if any
+ editableFile.appendBytes(trailerVideoBytes)
+ }
+
+ // copy the edited temporary file back to the original
+ editableFile.transferTo(outputStream(context, mimeType, uri, path))
+
+ if (autoCorrectTrailerOffset && !checkTrailerOffset(context, path, uri, mimeType, trailerVideoBytes?.size, editableFile, callback)) {
+ return false
+ }
+ editableFile.delete()
+ } catch (e: IOException) {
+ callback.onFailure(e)
+ return false
+ }
+
+ return true
+ }
+
+ private fun editIptc(
+ context: Context,
+ path: String,
+ uri: Uri,
+ mimeType: String,
+ callback: ImageOpCallback,
+ autoCorrectTrailerOffset: Boolean = true,
+ trailerDiff: Int = 0,
+ iptc: List<FieldMap>?,
+ ): Boolean {
+ if (!canEditIptc(mimeType)) {
+ callback.onFailure(UnsupportedOperationException("unsupported mimeType=$mimeType"))
+ return false
+ }
+
+ val originalFileSize = File(path).length()
+ var trailerVideoBytes: ByteArray? = null
+ val editableFile = StorageUtils.createTempFile(context).apply {
+ val trailerVideoSize = MultiPage.getTrailerVideoSize(context, uri, mimeType, originalFileSize)?.let { it + trailerDiff }
+ val isTrailerVideoValid = trailerVideoSize != null && MultiPage.getTrailerVideoInfo(context, uri, originalFileSize, trailerVideoSize) != null
+ try {
+ if (trailerVideoSize != null && isTrailerVideoValid) {
+ // handle motion photo and embedded video separately
+ val imageSize = (originalFileSize - trailerVideoSize).toInt()
+ val videoByteSize = trailerVideoSize.toInt()
+ trailerVideoBytes = ByteArray(videoByteSize)
+
+ StorageUtils.openInputStream(context, uri)?.let { input ->
+ val imageBytes = ByteArray(imageSize)
+ input.read(imageBytes, 0, imageSize)
+ input.read(trailerVideoBytes, 0, videoByteSize)
+
+ // copy only the image to a temporary file for editing
+ // video will be appended after metadata modification
+ transferFrom(ByteArrayInputStream(imageBytes), imageBytes.size.toLong())
+ }
+ } else {
+ // copy original file to a temporary file for editing
+ val inputStream = StorageUtils.openInputStream(context, uri)
+ transferFrom(inputStream, originalFileSize)
+ }
+ } catch (e: Exception) {
+ callback.onFailure(e)
+ return false
+ }
+ }
+
+ try {
+ editableFile.outputStream().use { output ->
+ // reopen input to read from start
+ StorageUtils.openInputStream(context, uri)?.use { input ->
+ when {
+ iptc != null ->
+ PixyMetaHelper.setIptc(input, output, iptc)
+
+ canRemoveMetadata(mimeType) ->
+ PixyMetaHelper.removeMetadata(input, output, setOf(TYPE_IPTC))
+
+ else -> {
+ Log.w(LOG_TAG, "setting empty IPTC for mimeType=$mimeType")
+ PixyMetaHelper.setIptc(input, output, null)
+ }
+ }
+ }
+ }
+
+ if (editableFile.length() == 0L) {
+ callback.onFailure(Exception("editing IPTC yielded an empty file"))
+ return false
+ }
+
+ if (trailerVideoBytes != null) {
+ // append trailer video, if any
+ editableFile.appendBytes(trailerVideoBytes)
+ }
+
+ // copy the edited temporary file back to the original
+ editableFile.transferTo(outputStream(context, mimeType, uri, path))
+
+ if (autoCorrectTrailerOffset && !checkTrailerOffset(context, path, uri, mimeType, trailerVideoBytes?.size, editableFile, callback)) {
+ return false
+ }
+ editableFile.delete()
+ } catch (e: IOException) {
+ callback.onFailure(e)
+ return false
+ }
+
+ return true
+ }
+
+ private fun editMp4Metadata(
+ context: Context,
+ path: String,
+ uri: Uri,
+ mimeType: String,
+ callback: ImageOpCallback,
+ fieldsToEdit: Map<*, *>,
+ newFields: FieldMap? = null,
+ ): Boolean {
+ if (mimeType != MimeTypes.MP4) {
+ callback.onFailure(UnsupportedOperationException("unsupported mimeType=$mimeType"))
+ return false
+ }
+
+ try {
+ val edits = Mp4ParserHelper.computeEdits(context, uri) { isoFile ->
+ fieldsToEdit.forEach { kv ->
+ val tag = kv.key as String
+ val value = kv.value as String?
+ when (tag) {
+ "gpsCoordinates" -> isoFile.updateLocation(value)
+ "rotationDegrees" -> {
+ val degrees = value?.toIntOrNull() ?: throw Exception("failed because of invalid rotation=$value")
+ if (isoFile.updateRotation(degrees) && newFields != null) {
+ newFields["rotationDegrees"] = degrees
+ }
+ }
+
+ "xmp" -> isoFile.updateXmp(value)
+ }
+ }
+ }
+
+ val pfd = StorageUtils.openOutputFileDescriptor(
+ context = context,
+ mimeType = mimeType,
+ uri = uri,
+ path = path,
+ // do not truncate with "t"
+ // "w" is enough on API 29+, but it will yield an empty file on API <29
+ // so "r" is necessary for backward compatibility
+ mode = "rw",
+ ) ?: throw Exception("failed to open file descriptor for uri=$uri path=$path")
+ pfd.use {
+ FileOutputStream(it.fileDescriptor).use { outputStream ->
+ outputStream.channel.use { outputChannel ->
+ edits.forEach { (offset, bytes) ->
+ bytes.inputStream().use { inputStream ->
+ Channels.newChannel(inputStream).use { inputChannel ->
+ outputChannel.transferFrom(inputChannel, offset, bytes.size.toLong())
+ }
+ }
+ }
+ }
+ }
+ }
+ } catch (e: NoClassDefFoundError) {
+ callback.onFailure(e)
+ return false
+ } catch (e: Exception) {
+ callback.onFailure(e)
+ return false
+ }
+
+ return true
+ }
+
+ // provide `editCoreXmp` to modify existing core XMP,
+ // or provide `coreXmp` and `extendedXmp` to set them
+ private fun editXmp(
+ context: Context,
+ path: String,
+ uri: Uri,
+ mimeType: String,
+ callback: ImageOpCallback,
+ autoCorrectTrailerOffset: Boolean = true,
+ trailerDiff: Int = 0,
+ coreXmp: String? = null,
+ extendedXmp: String? = null,
+ editCoreXmp: ((xmp: String) -> String)? = null,
+ ): Boolean {
+ if (!canEditXmp(mimeType)) {
+ callback.onFailure(UnsupportedOperationException("unsupported mimeType=$mimeType"))
+ return false
+ }
+
+ if (mimeType == MimeTypes.MP4) {
+ return editMp4Metadata(
+ context = context,
+ path = path,
+ uri = uri,
+ mimeType = mimeType,
+ callback = callback,
+ fieldsToEdit = mapOf("xmp" to coreXmp),
+ )
+ }
+
+ val originalFileSize = File(path).length()
+ val trailerVideoSize = MultiPage.getTrailerVideoSize(context, uri, mimeType, originalFileSize)?.let { it.toInt() + trailerDiff }
+ val editableFile = StorageUtils.createTempFile(context).apply {
+ try {
+ editXmpWithPixy(
+ context = context,
+ uri = uri,
+ mimeType = mimeType,
+ coreXmp = coreXmp,
+ extendedXmp = extendedXmp,
+ editCoreXmp = editCoreXmp,
+ editableFile = this
+ )
+ } catch (e: Exception) {
+ callback.onFailure(e)
+ return false
+ }
+ }
+
+ if (editableFile.length() == 0L) {
+ callback.onFailure(Exception("editing XMP yielded an empty file"))
+ return false
+ }
+
+ try {
+ // copy the edited temporary file back to the original
+ editableFile.transferTo(outputStream(context, mimeType, uri, path))
+
+ if (autoCorrectTrailerOffset && !checkTrailerOffset(context, path, uri, mimeType, trailerVideoSize, editableFile, callback)) {
+ return false
+ }
+ editableFile.delete()
+ } catch (e: IOException) {
+ callback.onFailure(e)
+ return false
+ }
+
+ return true
+ }
+
+ private fun editXmpWithPixy(
+ context: Context,
+ uri: Uri,
+ mimeType: String,
+ coreXmp: String?,
+ extendedXmp: String?,
+ editCoreXmp: ((xmp: String) -> String)?,
+ editableFile: File
+ ) {
+ var editedXmpString = coreXmp
+ var editedExtendedXmp = extendedXmp
+ if (editCoreXmp != null) {
+ val pixyXmp = StorageUtils.openInputStream(context, uri)?.use { input -> PixyMetaHelper.getXmp(input) }
+ if (pixyXmp != null) {
+ editedXmpString = editCoreXmp(pixyXmp.xmpDocString())
+ if (pixyXmp.hasExtendedXmp()) {
+ editedExtendedXmp = pixyXmp.extendedXmpDocString()
+ }
+ }
+ }
+
+ editableFile.outputStream().use { output ->
+ // reopen input to read from start
+ StorageUtils.openInputStream(context, uri)?.use { input ->
+ if (editedXmpString != null) {
+ if (editedExtendedXmp != null && mimeType != MimeTypes.JPEG) {
+ Log.w(LOG_TAG, "extended XMP is not supported by mimeType=$mimeType")
+ PixyMetaHelper.setXmp(input, output, editedXmpString, null)
+ } else {
+ PixyMetaHelper.setXmp(input, output, editedXmpString, editedExtendedXmp)
+ }
+ } else if (canRemoveMetadata(mimeType)) {
+ PixyMetaHelper.removeMetadata(input, output, setOf(TYPE_XMP))
+ } else {
+ Log.w(LOG_TAG, "setting empty XMP for mimeType=$mimeType")
+ PixyMetaHelper.setXmp(input, output, null, null)
+ }
+ }
+ }
+ }
+
+ // A few bytes are sometimes appended when writing to a document output stream.
+ // In that case, we need to adjust the trailer video offset accordingly and rewrite the file.
+ // returns whether the file at `path` is fine
+ private fun checkTrailerOffset(
+ context: Context,
+ path: String,
+ uri: Uri,
+ mimeType: String,
+ trailerOffset: Number?,
+ editedFile: File,
+ callback: ImageOpCallback,
+ ): Boolean {
+ if (trailerOffset == null) return true
+
+ val expectedLength = editedFile.length()
+ val actualLength = File(path).length()
+ val diff = (actualLength - expectedLength).toInt()
+ if (diff == 0) return true
+
+ Log.w(
+ LOG_TAG, "Edited file length=$expectedLength does not match final document file length=$actualLength. " +
+ "We need to edit XMP to adjust trailer video offset by $diff bytes."
+ )
+ val newTrailerOffset = trailerOffset.toLong() + diff
+ return editXmp(context, path, uri, mimeType, callback, trailerDiff = diff, editCoreXmp = { xmp ->
+ GoogleXMP.updateTrailingVideoOffset(xmp, trailerOffset, newTrailerOffset)
+ })
+ }
+
+ fun editOrientation(
+ context: Context,
+ path: String,
+ uri: Uri,
+ mimeType: String,
+ op: ExifOrientationOp,
+ callback: ImageOpCallback,
+ ) {
+ val newFields: FieldMap = hashMapOf()
+
+ val success = editExif(context, path, uri, mimeType, callback) { exif ->
+ // when the orientation is not defined, it returns `undefined (0)` instead of the orientation default value `normal (1)`
+ // in that case we explicitly set it to `normal` first
+ // because ExifInterface fails to rotate an image with undefined orientation
+ // as of androidx.exifinterface:exifinterface:1.3.0
+ val currentOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
+ if (currentOrientation == ExifInterface.ORIENTATION_UNDEFINED) {
+ exif.setAttribute(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL.toString())
+ }
+ when (op) {
+ ExifOrientationOp.ROTATE_CW -> exif.rotate(90)
+ ExifOrientationOp.ROTATE_CCW -> exif.rotate(-90)
+ ExifOrientationOp.FLIP -> exif.flipHorizontally()
+ }
+ exif.saveAttributes()
+ newFields["rotationDegrees"] = exif.rotationDegrees
+ newFields["isFlipped"] = exif.isFlipped
+ }
+
+ if (success) {
+ scanPostMetadataEdit(context, path, uri, mimeType, newFields, callback)
+ }
+ }
+
+ fun editDate(
+ context: Context,
+ path: String,
+ uri: Uri,
+ mimeType: String,
+ dateMillis: Long?,
+ shiftSeconds: Long?,
+ fields: List<String>,
+ callback: ImageOpCallback,
+ ) {
+ val success = editExif(context, path, uri, mimeType, callback) { exif ->
+ when {
+ dateMillis != null -> {
+ // set
+ val date = Date(dateMillis)
+ val dateString = ExifInterfaceHelper.DATETIME_FORMAT.format(date)
+ val subSec = dateMillis % 1000
+ val subSecString = if (subSec > 0) subSec.toString().padStart(3, '0') else null
+
+ if (fields.contains(ExifInterface.TAG_DATETIME)) {
+ exif.setAttribute(ExifInterface.TAG_DATETIME, dateString)
+ exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME, subSecString)
+ }
+ if (fields.contains(ExifInterface.TAG_DATETIME_ORIGINAL)) {
+ exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, dateString)
+ exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, subSecString)
+ }
+ if (fields.contains(ExifInterface.TAG_DATETIME_DIGITIZED)) {
+ exif.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, dateString)
+ exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME_DIGITIZED, subSecString)
+ }
+ if (fields.contains(ExifInterface.TAG_GPS_DATESTAMP)) {
+ exif.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, ExifInterfaceHelper.GPS_DATE_FORMAT.format(date))
+ exif.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, ExifInterfaceHelper.GPS_TIME_FORMAT.format(date))
+ }
+ }
+
+ shiftSeconds != null -> {
+ // shift
+ val shiftMillis = shiftSeconds * 1000
+ listOf(
+ ExifInterface.TAG_DATETIME,
+ ExifInterface.TAG_DATETIME_ORIGINAL,
+ ExifInterface.TAG_DATETIME_DIGITIZED,
+ ).forEach { field ->
+ if (fields.contains(field)) {
+ val subSecTag = when (field) {
+ ExifInterface.TAG_DATETIME -> ExifInterface.TAG_SUBSEC_TIME
+ ExifInterface.TAG_DATETIME_DIGITIZED -> ExifInterface.TAG_SUBSEC_TIME_DIGITIZED
+ ExifInterface.TAG_DATETIME_ORIGINAL -> ExifInterface.TAG_SUBSEC_TIME_ORIGINAL
+ else -> null
+ }
+ exif.getSafeDateMillis(field, subSecTag) { date ->
+ exif.setAttribute(field, ExifInterfaceHelper.DATETIME_FORMAT.format(date + shiftMillis))
+ }
+ }
+ }
+ if (fields.contains(ExifInterface.TAG_GPS_DATESTAMP)) {
+ exif.gpsDateTime?.let { date ->
+ val shifted = date + shiftMillis - TimeZone.getDefault().rawOffset
+ exif.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, ExifInterfaceHelper.GPS_DATE_FORMAT.format(shifted))
+ exif.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, ExifInterfaceHelper.GPS_TIME_FORMAT.format(shifted))
+ }
+ }
+ }
+
+ else -> {
+ // clear
+ if (fields.contains(ExifInterface.TAG_DATETIME)) {
+ exif.setAttribute(ExifInterface.TAG_DATETIME, null)
+ exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME, null)
+ exif.setAttribute(ExifInterface.TAG_OFFSET_TIME, null)
+ }
+ if (fields.contains(ExifInterface.TAG_DATETIME_ORIGINAL)) {
+ exif.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, null)
+ exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME_ORIGINAL, null)
+ exif.setAttribute(ExifInterface.TAG_OFFSET_TIME_ORIGINAL, null)
+ }
+ if (fields.contains(ExifInterface.TAG_DATETIME_DIGITIZED)) {
+ exif.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, null)
+ exif.setAttribute(ExifInterface.TAG_SUBSEC_TIME_DIGITIZED, null)
+ exif.setAttribute(ExifInterface.TAG_OFFSET_TIME_DIGITIZED, null)
+ }
+ if (fields.contains(ExifInterface.TAG_GPS_DATESTAMP)) {
+ exif.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, null)
+ exif.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, null)
+ }
+ }
+ }
+ exif.saveAttributes()
+ }
+
+ if (success) {
+ scanPostMetadataEdit(context, path, uri, mimeType, HashMap(), callback)
+ }
+ }
+
+ fun editMetadata(
+ context: Context,
+ path: String,
+ uri: Uri,
+ mimeType: String,
+ modifier: FieldMap,
+ autoCorrectTrailerOffset: Boolean,
+ callback: ImageOpCallback,
+ ) {
+ val newFields: FieldMap = hashMapOf()
+ if (modifier.containsKey(TYPE_EXIF)) {
+ val fields = modifier[TYPE_EXIF] as Map<*, *>?
+ if (fields != null && fields.isNotEmpty()) {
+ if (!editExif(
+ context = context,
+ path = path,
+ uri = uri,
+ mimeType = mimeType,
+ callback = callback,
+ autoCorrectTrailerOffset = autoCorrectTrailerOffset,
+ ) { exif ->
+ var setLocation = false
+ fields.forEach { kv ->
+ val tag = kv.key as String?
+ if (tag != null) {
+ val value = kv.value
+ if (value == null) {
+ // remove attribute
+ exif.setAttribute(tag, null)
+ } else {
+ when (tag) {
+ ExifInterface.TAG_GPS_LATITUDE,
+ ExifInterface.TAG_GPS_LATITUDE_REF,
+ ExifInterface.TAG_GPS_LONGITUDE,
+ ExifInterface.TAG_GPS_LONGITUDE_REF -> {
+ setLocation = true
+ }
+
+ else -> {
+ if (value is String) {
+ exif.setAttribute(tag, value)
+ } else {
+ Log.w(LOG_TAG, "failed to set Exif attribute $tag because value=$value is not a string")
+ }
+ }
+ }
+ }
+ }
+ }
+ if (setLocation) {
+ val latAbs = (fields[ExifInterface.TAG_GPS_LATITUDE] as Number?)?.toDouble()
+ val latRef = fields[ExifInterface.TAG_GPS_LATITUDE_REF] as String?
+ val lngAbs = (fields[ExifInterface.TAG_GPS_LONGITUDE] as Number?)?.toDouble()
+ val lngRef = fields[ExifInterface.TAG_GPS_LONGITUDE_REF] as String?
+ if (latAbs != null && latRef != null && lngAbs != null && lngRef != null) {
+ val latitude = if (latRef == ExifInterface.LATITUDE_SOUTH) -latAbs else latAbs
+ val longitude = if (lngRef == ExifInterface.LONGITUDE_WEST) -lngAbs else lngAbs
+ exif.setLatLong(latitude, longitude)
+ } else {
+ Log.w(LOG_TAG, "failed to set Exif location with latAbs=$latAbs, latRef=$latRef, lngAbs=$lngAbs, lngRef=$lngRef")
+ }
+ }
+ exif.saveAttributes()
+ }
+ ) return
+ }
+ }
+
+ if (modifier.containsKey(TYPE_IPTC)) {
+ val iptc = (modifier[TYPE_IPTC] as List<*>?)?.filterIsInstance<FieldMap>()
+ if (!editIptc(
+ context = context,
+ path = path,
+ uri = uri,
+ mimeType = mimeType,
+ callback = callback,
+ autoCorrectTrailerOffset = autoCorrectTrailerOffset,
+ iptc = iptc,
+ )
+ ) return
+ }
+
+ if (modifier.containsKey(TYPE_MP4)) {
+ val fieldsToEdit = modifier[TYPE_MP4] as Map<*, *>?
+ if (fieldsToEdit != null && fieldsToEdit.isNotEmpty()) {
+ if (!editMp4Metadata(
+ context = context,
+ path = path,
+ uri = uri,
+ mimeType = mimeType,
+ callback = callback,
+ fieldsToEdit = fieldsToEdit,
+ newFields = newFields,
+ )
+ ) return
+ }
+ }
+
+ if (modifier.containsKey(TYPE_XMP)) {
+ val xmp = modifier[TYPE_XMP] as Map<*, *>?
+ if (xmp != null) {
+ val coreXmp = xmp["xmp"] as String?
+ val extendedXmp = xmp["extendedXmp"] as String?
+ if (!editXmp(
+ context = context,
+ path = path,
+ uri = uri,
+ mimeType = mimeType,
+ callback = callback,
+ autoCorrectTrailerOffset = autoCorrectTrailerOffset,
+ coreXmp = coreXmp,
+ extendedXmp = extendedXmp,
+ )
+ ) return
+ }
+ }
+
+ scanPostMetadataEdit(context, path, uri, mimeType, newFields, callback)
+ }
+
+ fun removeTrailerVideo(
+ context: Context,
+ path: String,
+ uri: Uri,
+ mimeType: String,
+ callback: ImageOpCallback,
+ ) {
+ val originalFileSize = File(path).length()
+ val trailerVideoSize = MultiPage.getTrailerVideoSize(context, uri, mimeType, originalFileSize)
+ if (trailerVideoSize == null) {
+ callback.onFailure(Exception("failed to get trailer video size"))
+ return
+ }
+
+ val isTrailerVideoValid = MultiPage.getTrailerVideoInfo(context, uri, fileSize = originalFileSize, videoSize = trailerVideoSize) != null
+ if (!isTrailerVideoValid) {
+ callback.onFailure(Exception("failed to open trailer video with size=$trailerVideoSize"))
+ return
+ }
+
+ val editableFile = StorageUtils.createTempFile(context).apply {
+ try {
+ val inputStream = StorageUtils.openInputStream(context, uri)
+ // partial copy
+ transferFrom(inputStream, originalFileSize - trailerVideoSize)
+ } catch (e: Exception) {
+ Log.d(LOG_TAG, "failed to remove trailer video", e)
+ callback.onFailure(e)
+ return
+ }
+ }
+
+ try {
+ // copy the edited temporary file back to the original
+ editableFile.transferTo(outputStream(context, mimeType, uri, path))
+ editableFile.delete()
+ } catch (e: IOException) {
+ callback.onFailure(e)
+ return
+ }
+
+ val newFields: FieldMap = hashMapOf()
+ scanPostMetadataEdit(context, path, uri, mimeType, newFields, callback)
+ }
+
+ fun removeMetadataTypes(
+ context: Context,
+ path: String,
+ uri: Uri,
+ mimeType: String,
+ types: Set<String>,
+ callback: ImageOpCallback,
+ ) {
+ if (!canRemoveMetadata(mimeType)) {
+ callback.onFailure(UnsupportedOperationException("unsupported mimeType=$mimeType"))
+ return
+ }
+
+ val originalFileSize = File(path).length()
+ val trailerVideoSize = MultiPage.getTrailerVideoSize(context, uri, mimeType, originalFileSize)
+ val isTrailerVideoValid = trailerVideoSize != null && MultiPage.getTrailerVideoInfo(context, uri, originalFileSize, trailerVideoSize) != null
+ val editableFile = StorageUtils.createTempFile(context).apply {
+ try {
+ outputStream().use { output ->
+ // reopen input to read from start
+ StorageUtils.openInputStream(context, uri)?.use { input ->
+ PixyMetaHelper.removeMetadata(input, output, types)
+ }
+ }
+ } catch (e: Exception) {
+ Log.d(LOG_TAG, "failed to remove metadata", e)
+ callback.onFailure(e)
+ return
+ }
+ }
+
+ if (editableFile.length() == 0L) {
+ callback.onFailure(Exception("removing metadata yielded an empty file"))
+ return
+ }
+
+ try {
+ // copy the edited temporary file back to the original
+ editableFile.transferTo(outputStream(context, mimeType, uri, path))
+
+ if (!types.contains(TYPE_XMP) && isTrailerVideoValid && !checkTrailerOffset(context, path, uri, mimeType, trailerVideoSize, editableFile, callback)) {
+ return
+ }
+ editableFile.delete()
+ } catch (e: IOException) {
+ callback.onFailure(e)
+ return
+ }
+
+ val newFields: FieldMap = hashMapOf()
+ scanPostMetadataEdit(context, path, uri, mimeType, newFields, callback)
+ }
+
+ private fun outputStream(
+ context: Context,
+ mimeType: String,
+ uri: Uri,
+ path: String
+ ): OutputStream {
+ // truncate is necessary when overwriting a longer file
+ val mode = "wt"
+ return if (isMediaUriPermissionGranted(context, uri, mimeType)) {
+ StorageUtils.openOutputStream(context, mimeType, uri, mode) ?: throw Exception("failed to open output stream for uri=$uri")
+ } else {
+ val documentUri = StorageUtils.getDocumentFile(context, path, uri)?.uri ?: throw Exception("failed to get document file for path=$path, uri=$uri")
+ context.contentResolver.openOutputStream(documentUri, mode) ?: throw Exception("failed to open output stream from documentUri=$documentUri for path=$path, uri=$uri")
+ }
+ }
+
+ interface ImageOpCallback {
+ fun onSuccess(fields: FieldMap)
+ fun onFailure(throwable: Throwable)
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<ImageProvider>()
+
+ private const val LENGTH_UNIT_PERCENT = "percent"
+
+ val supportedExportMimeTypes = listOf(MimeTypes.BMP, MimeTypes.JPEG, MimeTypes.PNG, MimeTypes.WEBP)
+
+ // used when skipping a move/creation op because the target file already exists
+ val skippedFieldMap: HashMap<String, Any?> = hashMapOf("skipped" to true)
+
+ // used when deleting instead of moving to bin because the target file no longer exists
+ val deletedFieldMap: HashMap<String, Any?> = hashMapOf("deleted" to true)
+
+ fun isMediaUriPermissionGranted(context: Context, uri: Uri, mimeType: String): Boolean {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ val safeUri = StorageUtils.getMediaStoreScopedStorageSafeUri(uri, mimeType)
+
+ val pid = Binder.getCallingPid()
+ val uid = Binder.getCallingUid()
+ val flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION
+ context.checkUriPermission(safeUri, pid, uid, flags) == PackageManager.PERMISSION_GRANTED
+ } else {
+ false
+ }
+ }
+
+ fun getTimeZoneString(timeZone: TimeZone, dateTimeMillis: Long): String {
+ val offset = timeZone.getOffset(dateTimeMillis)
+ val offsetInMinutes = offset.absoluteValue / 60000
+ val offsetSign = if (offset < 0) "-" else "+"
+ val offsetHours = "${offsetInMinutes / 60}".padStart(2, '0')
+ val offsetMinutes = "${offsetInMinutes % 60}".padStart(2, '0')
+ return "$offsetSign$offsetHours:$offsetMinutes"
+ }
+ }
+}
+
+typealias CancelCheck = () -> Boolean
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProviderFactory.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProviderFactory.kt
new file mode 100644
index 0000000..1807206
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/ImageProviderFactory.kt
@@ -0,0 +1,26 @@
+package deckers.thibault.aves.model.provider
+
+import android.content.ContentResolver
+import android.content.Context
+import android.net.Uri
+import deckers.thibault.aves.utils.StorageUtils
+import java.util.Locale
+
+object ImageProviderFactory {
+ fun getProvider(context: Context, uri: Uri): ImageProvider? {
+ return when (uri.scheme?.lowercase(Locale.ROOT)) {
+ ContentResolver.SCHEME_CONTENT -> {
+ if (StorageUtils.isMediaStoreContentUri(uri)) {
+ MediaStoreImageProvider()
+ } else if (AvesEmbeddedMediaProvider.provides(context, uri)) {
+ AvesEmbeddedMediaProvider()
+ } else {
+ UnknownContentProvider()
+ }
+ }
+
+ ContentResolver.SCHEME_FILE -> FileImageProvider()
+ else -> null
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/MediaStoreImageProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/MediaStoreImageProvider.kt
new file mode 100644
index 0000000..a9e19a8
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/MediaStoreImageProvider.kt
@@ -0,0 +1,1079 @@
+package deckers.thibault.aves.model.provider
+
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.app.RecoverableSecurityException
+import android.content.ContentResolver
+import android.content.ContentUris
+import android.content.ContentValues
+import android.content.Context
+import android.content.ContextWrapper
+import android.graphics.BitmapFactory
+import android.media.MediaScannerConnection
+import android.net.Uri
+import android.os.Build
+import android.os.Environment
+import android.provider.MediaStore
+import android.util.Log
+import androidx.annotation.RequiresApi
+import com.commonsware.cwac.document.DocumentFileCompat
+import deckers.thibault.aves.MainActivity
+import deckers.thibault.aves.MainActivity.Companion.DELETE_SINGLE_PERMISSION_REQUEST
+import deckers.thibault.aves.model.AvesEntry
+import deckers.thibault.aves.model.EntryFields
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.model.NameConflictStrategy
+import deckers.thibault.aves.model.SourceEntry
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.MimeTypes.extensionFor
+import deckers.thibault.aves.utils.MimeTypes.isHeic
+import deckers.thibault.aves.utils.MimeTypes.isImage
+import deckers.thibault.aves.utils.MimeTypes.isVideo
+import deckers.thibault.aves.utils.StorageUtils
+import deckers.thibault.aves.utils.StorageUtils.PathSegments
+import deckers.thibault.aves.utils.StorageUtils.ensureTrailingSeparator
+import deckers.thibault.aves.utils.StorageUtils.removeTrailingSeparator
+import deckers.thibault.aves.utils.UriUtils.tryParseId
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.runBlocking
+import java.io.File
+import java.io.FileOutputStream
+import java.io.IOException
+import java.io.OutputStream
+import java.io.SyncFailedException
+import java.util.Locale
+import java.util.concurrent.CompletableFuture
+import kotlin.coroutines.Continuation
+import kotlin.coroutines.resume
+import kotlin.coroutines.resumeWithException
+import kotlin.coroutines.suspendCoroutine
+
+class MediaStoreImageProvider : ImageProvider() {
+ fun fetchAll(
+ context: Context,
+ knownEntries: Map<Long?, Long?>,
+ directory: String?,
+ handleNewEntry: NewEntryHandler,
+ ) {
+ Log.d(LOG_TAG, "fetching all media store items for ${knownEntries.size} known entries, directory=$directory")
+ val isModified = fun(contentId: Long, dateModifiedMillis: Long): Boolean {
+ val knownDate = knownEntries[contentId]
+ return knownDate == null || knownDate < dateModifiedMillis
+ }
+ val handleNew: NewEntryHandler
+ var selection: String? = null
+ var selectionArgs: Array<String>? = null
+ if (directory != null) {
+ val relativePathDirectory = ensureTrailingSeparator(directory)
+ val relativePath = PathSegments(context, relativePathDirectory).relativeDir
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && relativePath != null) {
+ selection = "${MediaStore.MediaColumns.RELATIVE_PATH} = ? AND ${MediaStore.MediaColumns.DATA} LIKE ?"
+ selectionArgs = arrayOf(relativePath, "$relativePathDirectory%")
+ } else {
+ selection = "${MediaStore.MediaColumns.DATA} LIKE ?"
+ selectionArgs = arrayOf("$relativePathDirectory%")
+ }
+
+ val parentCheckDirectory = removeTrailingSeparator(directory)
+ handleNew = { entry ->
+ // skip entries in subfolders
+ val path = entry[EntryFields.PATH] as String?
+ if (path != null && File(path).parent == parentCheckDirectory) {
+ handleNewEntry(entry)
+ }
+ }
+ } else {
+ handleNew = handleNewEntry
+ }
+ fetchFrom(context, isModified, handleNew, IMAGE_CONTENT_URI, IMAGE_PROJECTION, selection, selectionArgs)
+ fetchFrom(context, isModified, handleNew, VIDEO_CONTENT_URI, VIDEO_PROJECTION, selection, selectionArgs)
+ }
+
+ // the provided URI can point to the wrong media collection,
+ // e.g. a GIF image with the URI `content://media/external/video/media/[ID]`
+ // so the effective entry URI may not match the provided URI
+ override fun fetchSingle(context: Context, uri: Uri, sourceMimeType: String?, allowUnsized: Boolean, callback: ImageOpCallback) {
+ var found = false
+ val fetched = arrayListOf<FieldMap>()
+ val id = uri.tryParseId()
+ val alwaysValid: NewEntryChecker = fun(_: Long, _: Long): Boolean = true
+ val onSuccess: NewEntryHandler = fun(entry: FieldMap) { fetched.add(entry) }
+ if (id != null) {
+ if (sourceMimeType == null || isImage(sourceMimeType)) {
+ val contentUri = ContentUris.withAppendedId(IMAGE_CONTENT_URI, id)
+ found = fetchFrom(context, alwaysValid, onSuccess, contentUri, IMAGE_PROJECTION)
+ }
+ if (!found && (sourceMimeType == null || isVideo(sourceMimeType))) {
+ val contentUri = ContentUris.withAppendedId(VIDEO_CONTENT_URI, id)
+ found = fetchFrom(context, alwaysValid, onSuccess, contentUri, VIDEO_PROJECTION)
+ }
+ }
+ if (!found) {
+ // the uri can be a file media URI (e.g. "content://0@media/external/file/30050")
+ // without an equivalent image/video if it is shared from a file browser
+ // but the file is not publicly visible
+ found = fetchFrom(context, alwaysValid, onSuccess, uri, BASE_PROJECTION, fileMimeType = sourceMimeType)
+ }
+
+ if (found && fetched.isNotEmpty()) {
+ if (fetched.size == 1) {
+ callback.onSuccess(fetched.first())
+ } else {
+ callback.onFailure(Exception("found ${fetched.size} entries at uri=$uri"))
+ }
+ } else {
+ callback.onFailure(Exception("failed to fetch entry at uri=$uri"))
+ }
+ }
+
+ fun checkObsoleteContentIds(context: Context, knownContentIds: List<Long?>): List<Long> {
+ val foundContentIds = HashSet<Long>()
+ fun check(context: Context, contentUri: Uri) {
+ val projection = arrayOf(MediaStore.MediaColumns._ID)
+ try {
+ val cursor = context.contentResolver.query(contentUri, projection, null, null, null)
+ if (cursor != null) {
+ val idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)
+ while (cursor.moveToNext()) {
+ foundContentIds.add(cursor.getLong(idColumn))
+ }
+ cursor.close()
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to get content IDs for contentUri=$contentUri", e)
+ }
+ }
+ check(context, IMAGE_CONTENT_URI)
+ check(context, VIDEO_CONTENT_URI)
+ return knownContentIds.subtract(foundContentIds).filterNotNull().toList()
+ }
+
+ fun checkObsoletePaths(context: Context, knownPathById: Map<Long?, String?>): List<Long> {
+ val obsoleteIds = ArrayList<Long>()
+ fun check(context: Context, contentUri: Uri) {
+ val projection = arrayOf(MediaStore.MediaColumns._ID, MediaStore.MediaColumns.DATA)
+ try {
+ val cursor = context.contentResolver.query(contentUri, projection, null, null, null)
+ if (cursor != null) {
+ val idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)
+ val pathColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
+ while (cursor.moveToNext()) {
+ val id = cursor.getLong(idColumn)
+ val path = cursor.getString(pathColumn)
+ if (knownPathById.containsKey(id) && knownPathById[id] != path) {
+ obsoleteIds.add(id)
+ }
+ }
+ cursor.close()
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to get content IDs for contentUri=$contentUri", e)
+ }
+ }
+ check(context, IMAGE_CONTENT_URI)
+ check(context, VIDEO_CONTENT_URI)
+ return obsoleteIds
+ }
+
+ fun getChangedUris(context: Context, sinceGeneration: Int): List<String> {
+ val changedUris = ArrayList<String>()
+ fun check(context: Context, contentUri: Uri) {
+ val projection = arrayOf(MediaStore.MediaColumns._ID)
+ val selection = "${MediaStore.MediaColumns.GENERATION_MODIFIED} > ?"
+ val selectionArgs = arrayOf(sinceGeneration.toString())
+ try {
+ val cursor = context.contentResolver.query(contentUri, projection, selection, selectionArgs, null)
+ if (cursor != null) {
+ val idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)
+ while (cursor.moveToNext()) {
+ val id = cursor.getLong(idColumn)
+ changedUris.add(ContentUris.withAppendedId(contentUri, id).toString())
+ }
+ cursor.close()
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to get content IDs for contentUri=$contentUri", e)
+ }
+ }
+ check(context, IMAGE_CONTENT_URI)
+ check(context, VIDEO_CONTENT_URI)
+ return changedUris
+ }
+
+ private fun fetchFrom(
+ context: Context,
+ isValidEntry: NewEntryChecker,
+ handleNewEntry: NewEntryHandler,
+ contentUri: Uri,
+ projection: Array<String>,
+ selection: String? = null,
+ selectionArgs: Array<String>? = null,
+ fileMimeType: String? = null,
+ ): Boolean {
+ var found = false
+ val orderBy = "${MediaStore.MediaColumns.DATE_MODIFIED} DESC"
+ try {
+ val cursor = context.contentResolver.query(contentUri, projection, selection, selectionArgs, orderBy)
+ if (cursor != null) {
+ val contentUriContainsId = when (contentUri) {
+ IMAGE_CONTENT_URI, VIDEO_CONTENT_URI -> false
+ else -> true
+ }
+
+ // image & video
+ val idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)
+ val pathColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
+ val mimeTypeColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.MIME_TYPE)
+ val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.SIZE)
+ val widthColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.WIDTH)
+ val heightColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.HEIGHT)
+ val dateAddedSecsColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_ADDED)
+ val dateModifiedSecsColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_MODIFIED)
+ val dateTakenColumn = cursor.getColumnIndex(MediaColumns.DATE_TAKEN)
+
+ // image & video for API >=29, only for images for API <29
+ val orientationColumn = cursor.getColumnIndex(MediaColumns.ORIENTATION)
+
+ // video only
+ val durationColumn = cursor.getColumnIndex(MediaColumns.DURATION)
+ val needDuration = projection.contentEquals(VIDEO_PROJECTION)
+
+ while (cursor.moveToNext()) {
+ val id = cursor.getLong(idColumn)
+ val dateModifiedMillis = cursor.getInt(dateModifiedSecsColumn) * 1000L
+ if (isValidEntry(id, dateModifiedMillis)) {
+ // for multiple items, `contentUri` is the root without ID,
+ // but for single items, `contentUri` already contains the ID
+ val itemUri = if (contentUriContainsId) contentUri else ContentUris.withAppendedId(contentUri, id)
+ // `mimeType` can be registered as null for file media URIs with unsupported media types (e.g. TIFF on old devices)
+ // in that case we try to use the MIME type provided along the URI
+ val mimeType: String? = cursor.getString(mimeTypeColumn) ?: fileMimeType
+ var width = cursor.getInt(widthColumn)
+ var height = cursor.getInt(heightColumn)
+ val durationMillis = if (durationColumn != -1) cursor.getLong(durationColumn) else 0L
+
+ if (mimeType == null) {
+ Log.w(LOG_TAG, "failed to make entry from uri=$itemUri because of null MIME type")
+ } else {
+ val path = cursor.getString(pathColumn)
+
+ val isDir = path != null && File(path).isDirectory
+ if (isDir) {
+ // some directories are wrongly registered as media (e.g. `.../Android/media/is.xyz.mpv`)
+ Log.w(LOG_TAG, "failed to make entry from uri=$itemUri because path=$path refers to a directory")
+ } else {
+ var entryFields: FieldMap = hashMapOf(
+ EntryFields.ORIGIN to SourceEntry.ORIGIN_MEDIA_STORE_CONTENT,
+ EntryFields.URI to itemUri.toString(),
+ EntryFields.PATH to path,
+ EntryFields.SOURCE_MIME_TYPE to mimeType,
+ EntryFields.WIDTH to width,
+ EntryFields.HEIGHT to height,
+ EntryFields.SOURCE_ROTATION_DEGREES to if (orientationColumn != -1) cursor.getInt(orientationColumn) else 0,
+ EntryFields.SIZE_BYTES to cursor.getLong(sizeColumn),
+ EntryFields.DATE_ADDED_SECS to cursor.getInt(dateAddedSecsColumn),
+ EntryFields.DATE_MODIFIED_MILLIS to dateModifiedMillis,
+ EntryFields.SOURCE_DATE_TAKEN_MILLIS to if (dateTakenColumn != -1) cursor.getLong(dateTakenColumn) else null,
+ EntryFields.DURATION_MILLIS to durationMillis,
+ // only for map export
+ EntryFields.CONTENT_ID to id,
+ )
+
+ if (isHeic(mimeType)) {
+ // The reported size for some HEIC images is simply incorrect.
+ try {
+ StorageUtils.openInputStream(context, itemUri)?.use { input ->
+ val options = BitmapFactory.Options().apply {
+ inJustDecodeBounds = true
+ }
+ BitmapFactory.decodeStream(input, null, options)
+ val outWidth = options.outWidth
+ val outHeight = options.outHeight
+ if (outWidth > 0 && outHeight > 0) {
+ width = outWidth
+ height = outHeight
+ entryFields[EntryFields.WIDTH] = width
+ entryFields[EntryFields.HEIGHT] = height
+ }
+ }
+ } catch (_: IOException) {
+ // ignore
+ }
+ }
+
+ if (MimeTypes.isRaw(mimeType)
+ || (width <= 0 || height <= 0) && needSize(mimeType)
+ || durationMillis == 0L && needDuration
+ ) {
+ // Some images are incorrectly registered in the Media Store,
+ // missing some attributes such as width, height, orientation.
+ // Also, the reported size of raw images is inconsistent across devices
+ // and Android versions (sometimes the raw size, sometimes the decoded size).
+ val entry = SourceEntry(entryFields).fillPreCatalogMetadata(context)
+ entryFields = entry.toMap()
+ }
+
+ getFileModifiedDateMillis(path)?.let { entryFields[EntryFields.DATE_MODIFIED_MILLIS] = it }
+
+ handleNewEntry(entryFields)
+ found = true
+ }
+ }
+ }
+ }
+ cursor.close()
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to get entries", e)
+ }
+ return found
+ }
+
+ private fun hasEntry(context: Context, contentUri: Uri): Boolean {
+ var found = false
+ val projection = arrayOf(MediaStore.MediaColumns._ID)
+ try {
+ val cursor = context.contentResolver.query(contentUri, projection, null, null, null)
+ if (cursor != null) {
+ while (cursor.moveToNext()) {
+ found = true
+ }
+ cursor.close()
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to get entry at contentUri=$contentUri", e)
+ }
+ return found
+ }
+
+ private fun needSize(mimeType: String) = MimeTypes.SVG != mimeType
+
+ // `uri` is a media URI, not a document URI
+ override fun delete(contextWrapper: ContextWrapper, uri: Uri, path: String?, mimeType: String) {
+ path ?: throw Exception("failed to delete file because path is null")
+
+ // the following situations are possible:
+ // - there is an entry in the Media Store and there is a file on storage
+ // - there is an entry in the Media Store but there is no longer a file on storage
+ // - there is no entry in the Media Store but there is a file on storage
+ val file = File(path)
+ val fileExists = file.exists()
+
+ if (fileExists) {
+ if (StorageUtils.canEditByFile(contextWrapper, path)) {
+ if (hasEntry(contextWrapper, uri)) {
+ Log.d(LOG_TAG, "delete [permission:file, file exists, content exists] content at uri=$uri path=$path")
+ contextWrapper.contentResolver.delete(uri, null, null)
+ }
+ // in theory, deleting via content resolver should remove the file on storage
+ // in practice, the file may still be there afterwards
+ if (file.exists()) {
+ Log.d(LOG_TAG, "delete [permission:file, file exists after content delete] file at uri=$uri path=$path")
+ if (file.delete()) {
+ // in theory, scanning an obsolete path should remove the entry from the Media Store
+ // in practice, the entry may still be there afterwards
+ scanObsoletePath(contextWrapper, uri, path, mimeType)
+ return
+ }
+ } else {
+ return
+ }
+ } else if (!isMediaUriPermissionGranted(contextWrapper, uri, mimeType)
+ && StorageUtils.requireAccessPermission(contextWrapper, path)
+ ) {
+ // the delete request may yield a `RecoverableSecurityException` when using scoped storage,
+ // even if we have permissions on the tree document via SAF
+ if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q && hasEntry(contextWrapper, uri)) {
+ Log.d(LOG_TAG, "delete [permission:doc, file exists, content exists] content at uri=$uri path=$path")
+ contextWrapper.contentResolver.delete(uri, null, null)
+ }
+
+ // in theory, deleting via content resolver should remove the file on storage
+ // in practice, the file may still be there afterwards
+ if (file.exists()) {
+ Log.d(LOG_TAG, "delete [permission:doc, file exists after content delete] document at uri=$uri path=$path")
+ val df = StorageUtils.getDocumentFile(contextWrapper, path, uri)
+
+ if (df != null && df.delete()) {
+ scanObsoletePath(contextWrapper, uri, path, mimeType)
+ return
+ }
+ throw Exception("failed to delete document with df=$df")
+ } else {
+ return
+ }
+ }
+ } else if (uri.scheme?.lowercase(Locale.ROOT) == ContentResolver.SCHEME_FILE) {
+ val uriFilePath = File(uri.path!!).path
+ // URI and path both point to the same non existent path
+ if (uriFilePath == path) return
+ }
+
+ try {
+ Log.d(LOG_TAG, "delete [file exists=$fileExists] content at uri=$uri path=$path")
+ if (contextWrapper.contentResolver.delete(uri, null, null) > 0) return
+
+ if (hasEntry(contextWrapper, uri) || file.exists()) {
+ throw Exception("failed to delete row from content provider")
+ }
+ } catch (securityException: SecurityException) {
+ // even if the app has access permission granted on the containing directory,
+ // the delete request may yield a `RecoverableSecurityException` on API >=29
+ // when the underlying file no longer exists and this is an orphaned entry in the Media Store
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && contextWrapper is Activity) {
+ Log.w(LOG_TAG, "caught a security exception when attempting to delete uri=$uri", securityException)
+ val rse = securityException as? RecoverableSecurityException ?: throw securityException
+ val intentSender = rse.userAction.actionIntent.intentSender
+
+ // request user permission for this item
+ MainActivity.pendingScopedStoragePermissionCompleter = CompletableFuture<Boolean>()
+ contextWrapper.startIntentSenderForResult(intentSender, DELETE_SINGLE_PERMISSION_REQUEST, null, 0, 0, 0, null)
+ val granted = MainActivity.pendingScopedStoragePermissionCompleter!!.join()
+
+ MainActivity.pendingScopedStoragePermissionCompleter = null
+ if (granted) {
+ delete(contextWrapper, uri, path, mimeType)
+ } else {
+ throw Exception("failed to get delete permission")
+ }
+ } else {
+ throw securityException
+ }
+ }
+ }
+
+ override suspend fun moveMultiple(
+ activity: Activity,
+ copy: Boolean,
+ nameConflictStrategy: NameConflictStrategy,
+ entriesByTargetDir: Map<String, List<AvesEntry>>,
+ isCancelledOp: CancelCheck,
+ callback: ImageOpCallback,
+ ) {
+ entriesByTargetDir.forEach { kv ->
+ val targetDir = kv.key
+ val entries = kv.value
+
+ val toBin = targetDir == StorageUtils.TRASH_PATH_PLACEHOLDER
+ val toVault = StorageUtils.isInVault(activity, targetDir)
+ val toAppDir = toBin || toVault
+
+ var effectiveTargetDir: String? = null
+ var targetDirDocFile: DocumentFileCompat? = null
+ if (!toAppDir) {
+ effectiveTargetDir = targetDir
+ targetDirDocFile = StorageUtils.createDirectoryDocIfAbsent(activity, targetDir)
+ if (!File(targetDir).exists()) {
+ // download subdirectories can be created later by Media Store insertion
+ if (!isDownloadSubdir(activity, targetDir)) {
+ callback.onFailure(Exception("failed to create directory at path=$targetDir"))
+ return
+ }
+ }
+ }
+
+ for (entry in entries) {
+ val mimeType = entry.mimeType
+ val trashed = entry.trashed
+
+ val sourceUri = entry.uri
+ val sourcePath = if (trashed) entry.trashPath else entry.path
+
+ var desiredName: String? = null
+ if (trashed) {
+ entry.path?.let { desiredName = File(it).name }
+ }
+
+ val result: FieldMap = hashMapOf(
+ "uri" to sourceUri.toString(),
+ "success" to false,
+ )
+
+ // on API 30 we cannot get access granted directly to a volume root from its document tree,
+ // but it is still less constraining to use tree document files than to rely on the Media Store
+ //
+ // Relying on `DocumentFile`, we can create an item via `DocumentFile.createFile()`, but:
+ // - we need to scan the file to get the Media Store content URI
+ // - the underlying document provider controls the new file name
+ //
+ // Relying on the Media Store, we can create an item via `ContentResolver.insert()`
+ // with a path, and retrieve its content URI, but:
+ // - the Media Store isolates content by storage volume (e.g. `MediaStore.Images.Media.getContentUri(volumeName)`)
+ // - the volume name should be lower case, not exactly as the `StorageVolume` UUID
+ // cf new method in API 30 `StorageVolume.getMediaStoreVolumeName()`
+ // - inserting on a removable volume works on API 29, but not on API 25 nor 26 (on which API/devices does it work?)
+ // - there is no documentation regarding support for usage with removable storage
+ // - the Media Store only allows inserting in specific primary directories ("DCIM", "Pictures") when using scoped storage
+ try {
+ val appDir = when {
+ toBin -> StorageUtils.trashDirFor(activity, sourcePath ?: StorageUtils.getPrimaryVolumePath(activity))
+ toVault -> File(targetDir)
+ else -> null
+ }
+ if (appDir != null) {
+ effectiveTargetDir = ensureTrailingSeparator(appDir.path)
+ targetDirDocFile = DocumentFileCompat.fromFile(appDir)
+
+ if (toVault) {
+ appDir.mkdirs()
+ }
+ }
+
+ if (effectiveTargetDir != null) {
+ val newFields = if (isCancelledOp()) skippedFieldMap else {
+ val sourceFile = if (sourcePath != null) File(sourcePath) else null
+ if (sourceFile != null && !sourceFile.exists() && toBin) {
+ delete(activity, sourceUri, sourcePath, mimeType = mimeType)
+ deletedFieldMap
+ } else {
+ moveSingle(
+ activity = activity,
+ sourceFile = sourceFile,
+ sourceUri = sourceUri,
+ targetDir = effectiveTargetDir,
+ targetDirDocFile = targetDirDocFile,
+ desiredName = desiredName ?: sourceFile?.name ?: sourceUri.lastPathSegment ?: createTimeStampFileName(),
+ nameConflictStrategy = nameConflictStrategy,
+ mimeType = mimeType,
+ copy = copy,
+ toBin = toBin,
+ )
+ }
+ }
+ result["newFields"] = newFields
+ result["success"] = true
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to move to targetDir=$targetDir entry with sourcePath=$sourcePath", e)
+ }
+ callback.onSuccess(result)
+ }
+ }
+ }
+
+ private suspend fun moveSingle(
+ activity: Activity,
+ sourceFile: File?,
+ sourceUri: Uri,
+ targetDir: String,
+ targetDirDocFile: DocumentFileCompat?,
+ desiredName: String,
+ nameConflictStrategy: NameConflictStrategy,
+ mimeType: String,
+ copy: Boolean,
+ toBin: Boolean,
+ ): FieldMap {
+ val sourcePath = sourceFile?.path
+ val sourceExtension = sourceFile?.extension
+ val sourceDir = sourceFile?.parent?.let { ensureTrailingSeparator(it) }
+ if (sourceDir == targetDir && !(copy && nameConflictStrategy == NameConflictStrategy.RENAME)) {
+ // nothing to do unless it's a renamed copy
+ return skippedFieldMap
+ }
+
+ val desiredNameWithoutExtension = desiredName.substringBeforeLast(".")
+ val resolution = resolveTargetFileNameWithoutExtension(
+ contextWrapper = activity,
+ dir = targetDir,
+ desiredNameWithoutExtension = desiredNameWithoutExtension,
+ mimeType = mimeType,
+ defaultExtension = sourceExtension,
+ conflictStrategy = nameConflictStrategy,
+ )
+ val targetNameWithoutExtension = resolution.nameWithoutExtension ?: return skippedFieldMap
+
+ val sourceDocFile = DocumentFileCompat.fromSingleUri(activity, sourceUri)
+ val targetPath = createSingle(
+ activity = activity,
+ mimeType = mimeType,
+ targetDir = targetDir,
+ targetDirDocFile = targetDirDocFile,
+ targetNameWithoutExtension = targetNameWithoutExtension,
+ defaultExtension = sourceExtension,
+ ) { output: OutputStream ->
+ try {
+ sourceDocFile.copyTo(output)
+ } catch (e: SyncFailedException) {
+ // The copied file is synced after writing, but it consistently fails in some cases
+ // (e.g. copying to SD card on Xiaomi 2201117PG with Android 11).
+ // It seems this failure can be safely ignored, as the new file is complete.
+ Log.w(LOG_TAG, "sync failure after copying from uri=$sourceUri, path=$sourcePath to targetDir=$targetDir", e)
+ }
+ }
+
+ if (!copy) {
+ // delete original entry
+ try {
+ delete(activity, sourceUri, sourcePath, mimeType)
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to delete entry with path=$sourcePath", e)
+ }
+ }
+ return if (toBin) {
+ hashMapOf(
+ EntryFields.TRASHED to true,
+ EntryFields.TRASH_PATH to targetPath,
+ )
+ } else {
+ scanNewPath(activity, targetPath, mimeType)
+ }
+ }
+
+ fun createSingle(
+ activity: Activity,
+ mimeType: String,
+ targetDir: String,
+ targetDirDocFile: DocumentFileCompat?,
+ targetNameWithoutExtension: String,
+ defaultExtension: String?,
+ write: (OutputStream) -> Unit,
+ ): String {
+ if (StorageUtils.isInVault(activity, targetDir)) {
+ return insertByFile(
+ targetDir = targetDir,
+ targetFileName = "$targetNameWithoutExtension${extensionFor(mimeType, defaultExtension)}",
+ write = write,
+ )
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ if (isDownloadSubdir(activity, targetDir)) {
+ return insertByMediaStore(
+ activity = activity,
+ targetDir = targetDir,
+ targetFileName = "$targetNameWithoutExtension${extensionFor(mimeType, defaultExtension)}",
+ write = write,
+ )
+ }
+ }
+
+ return insertByTreeDoc(
+ activity = activity,
+ mimeType = mimeType,
+ targetDir = targetDir,
+ targetDirDocFile = targetDirDocFile,
+ targetNameWithoutExtension = targetNameWithoutExtension,
+ defaultExtension = defaultExtension,
+ write = write,
+ )
+ }
+
+ private fun isDownloadSubdir(context: Context, dir: String): Boolean {
+ val volumePath = StorageUtils.getVolumePath(context, dir) ?: return false
+ val downloadDirPath = ensureTrailingSeparator(File(volumePath, Environment.DIRECTORY_DOWNLOADS).path)
+ // effective download path may have a different case
+ return dir.lowercase().startsWith(downloadDirPath.lowercase())
+ }
+
+ private fun insertByFile(
+ targetDir: String,
+ targetFileName: String,
+ write: (OutputStream) -> Unit,
+ ): String {
+ val file = File(targetDir, targetFileName)
+ FileOutputStream(file).use(write)
+ return file.path
+ }
+
+ @RequiresApi(Build.VERSION_CODES.Q)
+ private fun insertByMediaStore(
+ activity: Activity,
+ targetDir: String,
+ targetFileName: String,
+ write: (OutputStream) -> Unit,
+ ): String {
+ val volumePath = StorageUtils.getVolumePath(activity, targetDir)
+ val relativePath = targetDir.substring(volumePath?.length ?: 0)
+
+ val values = ContentValues().apply {
+ put(MediaStore.MediaColumns.DISPLAY_NAME, targetFileName)
+ put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath)
+ put(MediaStore.MediaColumns.IS_PENDING, 1)
+ }
+ val resolver = activity.contentResolver
+ val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
+
+ uri?.let {
+ resolver.openOutputStream(uri)?.use(write)
+ values.clear()
+ values.put(MediaStore.MediaColumns.IS_PENDING, 0)
+ resolver.update(uri, values, null, null)
+ } ?: throw Exception("MediaStore failed for some reason")
+
+ return File(targetDir, targetFileName).path
+ }
+
+ // `DocumentsContract.moveDocument()` needs `sourceParentDocumentUri`, which could be different for each entry
+ // `DocumentsContract.copyDocument()` yields "Unsupported call: android:copyDocument"
+ // when used with entry URI as `sourceDocumentUri`, and targetDirDocFile URI as `targetParentDocumentUri`
+ private fun insertByTreeDoc(
+ activity: Activity,
+ mimeType: String,
+ targetDir: String,
+ targetDirDocFile: DocumentFileCompat?,
+ targetNameWithoutExtension: String,
+ defaultExtension: String?,
+ write: (OutputStream) -> Unit,
+ ): String {
+ targetDirDocFile ?: throw Exception("failed to get tree doc for directory at path=$targetDir")
+
+ // the file created from a `TreeDocumentFile` is also a `TreeDocumentFile`
+ // but in order to open an output stream to it, we need to use a `SingleDocumentFile`
+ // through a document URI, not a tree URI
+ // note that `DocumentFile.getParentFile()` returns null if we did not pick a tree first
+ var targetTreeFile = targetDirDocFile.createFile(mimeType, targetNameWithoutExtension)
+ var targetDocFile = DocumentFileCompat.fromSingleUri(activity, targetTreeFile.uri)
+
+ // providing a display name and a MIME type does not guarantee
+ // that the created document will be backed by a file with a valid media extension,
+ // but having an extension is essential for media detection by Android,
+ // so we retry with a display name that includes the extension
+ if ((targetDocFile.extension == null || targetDocFile.extension.isEmpty() || targetDocFile.extension == "bin") && defaultExtension != null) {
+ if (targetDocFile.exists()) {
+ targetDocFile.delete()
+ }
+
+ val extension = if (defaultExtension.startsWith(".")) defaultExtension else ".$defaultExtension"
+ targetTreeFile = targetDirDocFile.createFile(mimeType, "$targetNameWithoutExtension$extension")
+ targetDocFile = DocumentFileCompat.fromSingleUri(activity, targetTreeFile.uri)
+ }
+
+ try {
+ targetDocFile.openOutputStream().use(write)
+ } catch (e: Exception) {
+ // remove empty file
+ if (targetDocFile.exists()) {
+ targetDocFile.delete()
+ }
+ throw e
+ }
+
+ // the source file name and the created document file name can be different when:
+ // - a file with the same name already exists, some implementations give a suffix like ` (1)`, some *do not*
+ // - the original extension does not match the extension added by the underlying provider
+ val fileName = targetDocFile.name
+ return targetDir + fileName
+ }
+
+ override suspend fun renameSingle(
+ activity: Activity,
+ mimeType: String,
+ oldMediaUri: Uri,
+ oldPath: String,
+ newFile: File,
+ ): FieldMap = when {
+ StorageUtils.canEditByFile(activity, oldPath) -> renameSingleByFile(activity, mimeType, oldMediaUri, oldPath, newFile)
+ isMediaUriPermissionGranted(activity, oldMediaUri, mimeType) -> renameSingleByMediaStore(activity, mimeType, oldMediaUri, newFile)
+ else -> renameSingleByTreeDoc(activity, mimeType, oldMediaUri, oldPath, newFile)
+ }
+
+ private suspend fun renameSingleByMediaStore(
+ activity: Activity,
+ mimeType: String,
+ mediaUri: Uri,
+ newFile: File
+ ): FieldMap {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
+ throw Exception("unsupported Android version")
+ }
+
+ Log.d(LOG_TAG, "rename content at uri=$mediaUri")
+ val uri = StorageUtils.getMediaStoreScopedStorageSafeUri(mediaUri, mimeType)
+
+ // `IS_PENDING` is necessary for `TITLE`, not for `DISPLAY_NAME`
+ val tempValues = ContentValues().apply {
+ put(MediaStore.MediaColumns.IS_PENDING, 1)
+ }
+ if (activity.contentResolver.update(uri, tempValues, null, null) == 0) {
+ throw Exception("failed to update fields for uri=$uri")
+ }
+
+ val finalValues = ContentValues().apply {
+ put(MediaStore.MediaColumns.DISPLAY_NAME, newFile.name)
+ // scanning the new file will not automatically update `TITLE`
+ put(MediaStore.MediaColumns.TITLE, newFile.nameWithoutExtension)
+ put(MediaStore.MediaColumns.IS_PENDING, 0)
+ }
+ if (activity.contentResolver.update(uri, finalValues, null, null) == 0) {
+ throw Exception("failed to update fields for uri=$uri")
+ }
+
+ // URI should not change
+ return scanNewPathByMediaStore(activity, newFile.path, mimeType)
+ }
+
+ private suspend fun renameSingleByTreeDoc(
+ activity: Activity,
+ mimeType: String,
+ oldMediaUri: Uri,
+ oldPath: String,
+ newFile: File
+ ): FieldMap {
+ Log.d(LOG_TAG, "rename document at uri=$oldMediaUri path=$oldPath")
+ val df = StorageUtils.getDocumentFile(activity, oldPath, oldMediaUri)
+ df ?: throw Exception("failed to get document at path=$oldPath")
+
+ val requestedName = newFile.name
+ val renamed = df.renameTo(newFile.name)
+ if (!renamed) {
+ throw Exception("failed to rename document at path=$oldPath")
+ }
+ val effectiveName = df.name
+ if (requestedName != effectiveName) {
+ Log.w(LOG_TAG, "requested renaming document at uri=$oldMediaUri path=$oldPath with name=${requestedName} but got name=$effectiveName")
+ }
+ val newPath = File(newFile.parentFile, df.name).path
+
+ scanObsoletePath(activity, oldMediaUri, oldPath, mimeType)
+ return scanNewPathByMediaStore(activity, newPath, mimeType)
+ }
+
+ private suspend fun renameSingleByFile(
+ activity: Activity,
+ mimeType: String,
+ oldMediaUri: Uri,
+ oldPath: String,
+ newFile: File
+ ): FieldMap {
+ Log.d(LOG_TAG, "rename file at path=$oldPath")
+ val renamed = File(oldPath).renameTo(newFile)
+ if (!renamed) {
+ throw Exception("failed to rename file at path=$oldPath")
+ }
+ scanObsoletePath(activity, oldMediaUri, oldPath, mimeType)
+ return scanNewPathByMediaStore(activity, newFile.path, mimeType)
+ }
+
+ override fun scanPostMetadataEdit(context: Context, path: String, uri: Uri, mimeType: String, newFields: FieldMap, callback: ImageOpCallback) {
+ MediaScannerConnection.scanFile(context, arrayOf(path), arrayOf(mimeType)) { _, _ ->
+ val projection = arrayOf(
+ MediaStore.MediaColumns.DATE_MODIFIED,
+ MediaStore.MediaColumns.SIZE,
+ )
+ try {
+ val cursor = context.contentResolver.query(uri, projection, null, null, null)
+ if (cursor != null && cursor.moveToFirst()) {
+ cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED).let { if (it != -1) newFields[EntryFields.DATE_MODIFIED_MILLIS] = cursor.getInt(it) * 1000 }
+ cursor.getColumnIndex(MediaStore.MediaColumns.SIZE).let { if (it != -1) newFields[EntryFields.SIZE_BYTES] = cursor.getLong(it) }
+ cursor.close()
+ }
+ } catch (e: Exception) {
+ callback.onFailure(e)
+ return@scanFile
+ }
+ getFileModifiedDateMillis(path)?.let { newFields[EntryFields.DATE_MODIFIED_MILLIS] = it }
+ callback.onSuccess(newFields)
+ }
+ }
+
+ // try to fetch the modified date from the file,
+ // as it is more precise than the one from the Media Store
+ private fun getFileModifiedDateMillis(path: String?): Long? {
+ if (path != null) {
+ try {
+ return File(path).lastModified()
+ } catch (_: SecurityException) {
+ // ignore
+ }
+ }
+ return null
+ }
+
+ private fun scanObsoletePath(context: Context, uri: Uri, path: String, mimeType: String) {
+ val file = File(path)
+ val delayMillis = 500L
+ val maxDelayMillis = 10000L
+ var totalDelayMillis = 0L
+ while (file.exists()) {
+ if (!hasEntry(context, uri)) return
+ if (totalDelayMillis < maxDelayMillis) {
+ Log.d(LOG_TAG, "Trying to scan obsolete path but file exists at path=$path. Will retry in $delayMillis ms (total: $totalDelayMillis ms)")
+ runBlocking { delay(delayMillis) }
+ totalDelayMillis += delayMillis
+ } else {
+ throw Exception("Timeout ($maxDelayMillis ms) to clear MediaStore entry for file at path=$path")
+ }
+ }
+
+ if (hasEntry(context, uri)) {
+ MediaScannerConnection.scanFile(context, arrayOf(path), arrayOf(mimeType)) { _, newUri: Uri? ->
+ if (newUri != null && hasEntry(context, newUri)) {
+ Log.w(LOG_TAG, "Failed to clear Media Store entry at uri=$newUri path=$path")
+ } else {
+ Log.w(LOG_TAG, "Cleared Media Store entry at uri=$newUri path=$path")
+ }
+ }
+ }
+ }
+
+ suspend fun scanNewPathByMediaStore(context: Context, path: String, mimeType: String): FieldMap =
+ suspendCoroutine { cont ->
+ tryScanNewPathByMediaStore(
+ context = context,
+ path = path,
+ mimeType = mimeType,
+ cont = cont,
+ )
+ }
+
+ private fun tryScanNewPathByMediaStore(
+ context: Context,
+ path: String,
+ mimeType: String,
+ cont: Continuation<FieldMap>,
+ iteration: Int = 0,
+ ) {
+ // `scanFile` may (e.g. when copying to SD card on Android 10 (API 29)):
+ // 1) yield no URI,
+ // 2) yield a temporary URI that fails when queried,
+ // 3) yield a temporary URI that succeeds when queried right away, but the Media Store actually won't have an entry for it until device reboot.
+ if (iteration > 5) {
+ // give up
+ cont.resumeWithException(Exception("failed to scan new path=$path after $iteration iterations"))
+ return
+ } else if (iteration > 0) {
+ // waiting and retrying just once usually works out for cases 1) and 2)
+ Thread.sleep(iteration * 100L)
+ } else if (iteration == 0 && Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
+ // waiting before the first scan usually works out for case 3)
+ StorageUtils.getVolumePath(context, path)?.let { volumePath ->
+ if (volumePath != StorageUtils.getPrimaryVolumePath(context)) {
+ Thread.sleep(100L)
+ }
+ }
+ }
+
+ MediaScannerConnection.scanFile(context, arrayOf(path), arrayOf(mimeType)) { _, newUri: Uri? ->
+ fun scanUri(uri: Uri?): FieldMap? {
+ uri ?: return null
+
+ // we retrieve updated fields as the renamed/moved file became a new entry in the Media Store
+ val projection = arrayOf(
+ MediaStore.MediaColumns.DATE_ADDED,
+ MediaStore.MediaColumns.DATE_MODIFIED,
+ )
+ try {
+ val cursor = context.contentResolver.query(uri, projection, null, null, null)
+ if (cursor != null && cursor.moveToFirst()) {
+ val newFields = hashMapOf<String, Any?>(
+ EntryFields.ORIGIN to SourceEntry.ORIGIN_MEDIA_STORE_CONTENT,
+ EntryFields.URI to uri.toString(),
+ EntryFields.CONTENT_ID to uri.tryParseId(),
+ EntryFields.PATH to path,
+ )
+ cursor.getColumnIndex(MediaStore.MediaColumns.DATE_ADDED).let { if (it != -1) newFields[EntryFields.DATE_ADDED_SECS] = cursor.getInt(it) }
+ cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED).let { if (it != -1) newFields[EntryFields.DATE_MODIFIED_MILLIS] = cursor.getInt(it) * 1000 }
+ cursor.close()
+ getFileModifiedDateMillis(path)?.let { newFields[EntryFields.DATE_MODIFIED_MILLIS] = it }
+ return newFields
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to scan uri=$uri", e)
+ }
+ return null
+ }
+
+ if (newUri != null) {
+ var contentUri: Uri? = null
+ // `newURI` is possibly a file media URI (e.g. "content://media/12a9-8b42/file/62872")
+ // but we need an image/video media URI (e.g. "content://media/external/images/media/62872")
+ val contentId = newUri.tryParseId()
+ if (contentId != null) {
+ if (isImage(mimeType)) {
+ contentUri = ContentUris.withAppendedId(IMAGE_CONTENT_URI, contentId)
+ } else if (isVideo(mimeType)) {
+ contentUri = ContentUris.withAppendedId(VIDEO_CONTENT_URI, contentId)
+ }
+ }
+
+ // prefer image/video content URI, fallback to original URI (possibly a file content URI)
+ val newFields = scanUri(contentUri) ?: scanUri(newUri)
+
+ if (newFields != null) {
+ cont.resume(newFields)
+ return@scanFile
+ }
+ }
+
+ tryScanNewPathByMediaStore(context, path = path, mimeType = mimeType, cont, iteration + 1)
+ }
+ }
+
+ fun getContentUriForPath(context: Context, path: String): Uri? {
+ val projection = arrayOf(MediaStore.MediaColumns._ID)
+ val selection = "${MediaStore.MediaColumns.DATA} = ?"
+ val selectionArgs = arrayOf(path)
+
+ fun check(context: Context, contentUri: Uri): Uri? {
+ var mediaContentUri: Uri? = null
+ try {
+ val cursor = context.contentResolver.query(contentUri, projection, selection, selectionArgs, null)
+ if (cursor != null && cursor.moveToFirst()) {
+ val idColumn = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
+ if (idColumn != -1) {
+ val id = cursor.getLong(idColumn)
+ mediaContentUri = ContentUris.withAppendedId(contentUri, id)
+ }
+ cursor.close()
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to get URI for contentUri=$contentUri path=$path", e)
+ }
+ return mediaContentUri
+ }
+ return check(context, IMAGE_CONTENT_URI) ?: check(context, VIDEO_CONTENT_URI)
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<MediaStoreImageProvider>()
+
+ private val IMAGE_CONTENT_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
+ private val VIDEO_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
+
+ private val BASE_PROJECTION = arrayOf(
+ MediaStore.MediaColumns._ID,
+ MediaStore.MediaColumns.DATA,
+ MediaStore.MediaColumns.MIME_TYPE,
+ MediaStore.MediaColumns.SIZE,
+ MediaStore.MediaColumns.WIDTH,
+ MediaStore.MediaColumns.HEIGHT,
+ MediaStore.MediaColumns.DATE_ADDED,
+ MediaStore.MediaColumns.DATE_MODIFIED,
+ MediaColumns.DATE_TAKEN,
+ )
+
+ private val IMAGE_PROJECTION = arrayOf(
+ *BASE_PROJECTION,
+ MediaColumns.ORIENTATION,
+ )
+
+ private val VIDEO_PROJECTION = arrayOf(
+ *BASE_PROJECTION,
+ MediaColumns.DURATION,
+ // `ORIENTATION` was only available for images before Android 10 (API 29)
+ *if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) arrayOf(
+ MediaStore.MediaColumns.ORIENTATION,
+ ) else emptyArray()
+ )
+ }
+}
+
+object MediaColumns {
+ // `DATE_TAKEN`, `ORIENTATION`, `DURATION` used to be in `MediaStore.[Images,Video].Media`
+ // but were moved to `MediaStore.MediaColumns` for API 29
+ // it is safe to use them because they are static strings that have not changed
+
+ @SuppressLint("InlinedApi")
+ const val DATE_TAKEN = MediaStore.MediaColumns.DATE_TAKEN
+
+ @SuppressLint("InlinedApi")
+ const val ORIENTATION = MediaStore.MediaColumns.ORIENTATION
+
+ @SuppressLint("InlinedApi")
+ const val DURATION = MediaStore.MediaColumns.DURATION
+}
+
+typealias NewEntryHandler = (entry: FieldMap) -> Unit
+
+private typealias NewEntryChecker = (contentId: Long, dateModifiedMillis: Long) -> Boolean \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/UnknownContentProvider.kt b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/UnknownContentProvider.kt
new file mode 100644
index 0000000..db2b583
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/model/provider/UnknownContentProvider.kt
@@ -0,0 +1,85 @@
+package deckers.thibault.aves.model.provider
+
+import android.content.Context
+import android.net.Uri
+import android.provider.MediaStore
+import android.provider.OpenableColumns
+import android.util.Log
+import deckers.thibault.aves.metadata.Metadata
+import deckers.thibault.aves.metadata.metadataextractor.Helper
+import deckers.thibault.aves.model.EntryFields
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.model.SourceEntry
+import deckers.thibault.aves.utils.LogUtils
+import deckers.thibault.aves.utils.MimeTypes
+import deckers.thibault.aves.utils.StorageUtils
+
+open class UnknownContentProvider : ImageProvider() {
+ open val reliableProviderMimeType: Boolean
+ get() = false
+
+ override fun fetchSingle(context: Context, uri: Uri, sourceMimeType: String?, allowUnsized: Boolean, callback: ImageOpCallback) {
+ var mimeType = sourceMimeType
+ if (sourceMimeType == null || !reliableProviderMimeType) {
+ // source MIME type may be incorrect, so we get a second opinion if possible
+ try {
+ val safeUri = Uri.fromFile(Metadata.createPreviewFile(context, uri))
+ StorageUtils.openInputStream(context, safeUri)?.use { input ->
+ // `metadata-extractor` is the most reliable, except for `tiff` (false positives, false negatives)
+ // cf https://github.com/drewnoakes/metadata-extractor/issues/296
+ Helper.readMimeType(input)?.takeIf { it != MimeTypes.TIFF }?.let {
+ if (it != sourceMimeType) {
+ Log.d(LOG_TAG, "source MIME type is $sourceMimeType but extracted MIME type is $it for uri=$uri")
+ mimeType = it
+ }
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get MIME type by metadata-extractor for uri=$uri", e)
+ } catch (e: NoClassDefFoundError) {
+ Log.w(LOG_TAG, "failed to get MIME type by metadata-extractor for uri=$uri", e)
+ } catch (e: AssertionError) {
+ Log.w(LOG_TAG, "failed to get MIME type by metadata-extractor for uri=$uri", e)
+ }
+ }
+
+ val fields: FieldMap = hashMapOf(
+ EntryFields.ORIGIN to SourceEntry.ORIGIN_UNKNOWN_CONTENT,
+ EntryFields.URI to uri.toString(),
+ EntryFields.SOURCE_MIME_TYPE to mimeType,
+ )
+ try {
+ // some providers do not provide the mandatory `OpenableColumns`
+ // and the query fails when compiling a projection specifying them
+ // e.g. `content://mms/part/[id]` on Android KitKat
+ val cursor = context.contentResolver.query(uri, null, null, null, null)
+ if (cursor != null && cursor.moveToFirst()) {
+ cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME).let { if (it != -1) fields[EntryFields.TITLE] = cursor.getString(it) }
+ cursor.getColumnIndex(OpenableColumns.SIZE).let { if (it != -1) fields[EntryFields.SIZE_BYTES] = cursor.getLong(it) }
+ cursor.getColumnIndex(MediaStore.MediaColumns.DATA).let { if (it != -1) fields[EntryFields.PATH] = cursor.getString(it) }
+ // mime type fallback if it was not provided and not found via `metadata-extractor`
+ cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE).let { if (it != -1 && mimeType == null) fields[EntryFields.SOURCE_MIME_TYPE] = cursor.getString(it) }
+ cursor.close()
+ }
+ } catch (e: Exception) {
+ callback.onFailure(Exception("Failed to query content, error=${e.message}"))
+ return
+ }
+
+ if (fields[EntryFields.SOURCE_MIME_TYPE] == null) {
+ callback.onFailure(Exception("Failed to find MIME type for uri=$uri"))
+ return
+ }
+
+ val entry = SourceEntry(fields).fillPreCatalogMetadata(context)
+ if (allowUnsized || entry.isSized || entry.isSvg || entry.isVideo) {
+ callback.onSuccess(entry.toMap())
+ } else {
+ callback.onFailure(Exception("entry has no size"))
+ }
+ }
+
+ companion object {
+ private val LOG_TAG = LogUtils.createTag<UnknownContentProvider>()
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/BitmapUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/BitmapUtils.kt
new file mode 100644
index 0000000..0029b65
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/BitmapUtils.kt
@@ -0,0 +1,301 @@
+package deckers.thibault.aves.utils
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.ColorSpace
+import android.os.Build
+import android.util.Half
+import android.util.Log
+import androidx.annotation.RequiresApi
+import com.bumptech.glide.Glide
+import com.bumptech.glide.load.resource.bitmap.TransformationUtils
+import deckers.thibault.aves.metadata.Metadata.getExifCode
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import java.io.ByteArrayOutputStream
+import java.nio.ByteBuffer
+
+object BitmapUtils {
+ private val LOG_TAG = LogUtils.createTag<BitmapUtils>()
+ private const val INITIAL_BUFFER_SIZE = 1 shl 18 // 256kB
+
+ private val freeBaos = ArrayList<ByteArrayOutputStream>()
+ private val mutex = Mutex()
+
+ private const val INT_BYTE_SIZE = 4
+ private const val MAX_2_BITS_FLOAT = 0x3.toFloat()
+ private const val MAX_8_BITS_FLOAT = 0xff.toFloat()
+ private const val MAX_10_BITS_FLOAT = 0x3ff.toFloat()
+
+ private const val FORMAT_BYTE_ENCODED: Int = 0xCA
+ val FORMAT_BYTE_ENCODED_AS_BYTES: ByteArray = ByteArray(1) { _ -> FORMAT_BYTE_ENCODED.toByte() }
+ private const val FORMAT_BYTE_DECODED: Byte = 0xFE.toByte()
+ private const val RAW_BYTES_TRAILER_LENGTH = INT_BYTE_SIZE * 2 + 1
+
+ // bytes per pixel with different bitmap config
+ private const val BPP_ALPHA_8 = 1
+ private const val BPP_RGB_565 = 2
+ private const val BPP_ARGB_8888 = 4
+ private const val BPP_RGBA_1010102 = 4
+ private const val BPP_RGBA_F16 = 8
+
+ fun Bitmap.describe(): String {
+ return "{${
+ arrayListOf(
+ "${width}x${height}",
+ "bytes=$byteCount",
+ "config=$config",
+ ).apply {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) add("cs=${colorSpace}")
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) add("hasGainmap=${hasGainmap()}")
+ }.joinToString(",")
+ }}"
+ }
+
+ private fun getBytePerPixel(config: Bitmap.Config?): Int {
+ return when (config) {
+ Bitmap.Config.ALPHA_8 -> BPP_ALPHA_8
+ Bitmap.Config.RGB_565 -> BPP_RGB_565
+ Bitmap.Config.ARGB_8888 -> BPP_ARGB_8888
+ else -> {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && config == Bitmap.Config.RGBA_F16) {
+ BPP_RGBA_F16
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && config == Bitmap.Config.RGBA_1010102) {
+ BPP_RGBA_1010102
+ } else {
+ // default
+ BPP_ARGB_8888
+ }
+ }
+ }
+ }
+
+ fun getExpectedImageSize(pixelCount: Long, config: Bitmap.Config?): Long {
+ return pixelCount * getBytePerPixel(config)
+ }
+
+ suspend fun getBytes(bitmap: Bitmap?, recycle: Boolean, decoded: Boolean, mimeType: String?): ByteArray? {
+ return if (decoded) {
+ getRawBytes(bitmap, recycle = recycle)
+ } else {
+ getEncodedBytes(bitmap, canHaveAlpha = MimeTypes.canHaveAlpha(mimeType), recycle = recycle)
+ }
+ }
+
+ private fun getRawBytes(bitmap: Bitmap?, recycle: Boolean): ByteArray? {
+ bitmap ?: return null
+
+ val byteCount = bitmap.byteCount
+ val width = bitmap.width
+ val height = bitmap.height
+ val config = bitmap.config
+ val colorSpace = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) bitmap.colorSpace else null
+
+ val byteBufferSize = byteCount + RAW_BYTES_TRAILER_LENGTH
+ if (!MemoryUtils.canAllocate(byteBufferSize)) {
+ throw Exception("bitmap buffer is $byteCount bytes, which cannot be allocated to a new byte array")
+ }
+
+ try {
+ // `ByteBuffer` initial order is always `BIG_ENDIAN`
+ var bytes = ByteBuffer.allocate(byteBufferSize).apply {
+ bitmap.copyPixelsToBuffer(this)
+ }.array()
+
+ // do not access bitmap after recycling
+ if (recycle) bitmap.recycle()
+
+ // convert pixel format and color space, if necessary
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ colorSpace?.let { srcColorSpace ->
+ val dstColorSpace = ColorSpace.get(ColorSpace.Named.SRGB)
+ val connector = ColorSpace.connect(srcColorSpace, dstColorSpace)
+ if (config == Bitmap.Config.ARGB_8888) {
+ if (srcColorSpace != dstColorSpace) {
+ argb8888ToArgb8888(bytes, connector, end = byteCount)
+ }
+ } else if (config == Bitmap.Config.RGBA_F16) {
+ rgbaf16ToArgb8888(bytes, connector, end = byteCount)
+ val newConfigByteCount = byteCount / (BPP_RGBA_F16 / BPP_ARGB_8888)
+ bytes = bytes.sliceArray(0..<newConfigByteCount + RAW_BYTES_TRAILER_LENGTH)
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && config == Bitmap.Config.RGBA_1010102) {
+ rgba1010102ToArgb8888(bytes, connector, end = byteCount)
+ }
+ }
+ }
+
+ // append bitmap size for use by the caller to interpret the raw bytes
+ val trailerOffset = bytes.size - RAW_BYTES_TRAILER_LENGTH
+ bytes = ByteBuffer.wrap(bytes).apply {
+ position(trailerOffset)
+ putInt(width)
+ putInt(height)
+ // trailer byte to indicate whether the returned bytes are decoded/encoded
+ put(FORMAT_BYTE_DECODED)
+ }.array()
+
+ return bytes
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to get bytes from bitmap", e)
+ }
+ return null
+ }
+
+ private suspend fun getEncodedBytes(bitmap: Bitmap?, canHaveAlpha: Boolean = false, quality: Int = 100, recycle: Boolean): ByteArray? {
+ bitmap ?: return null
+
+ val stream: ByteArrayOutputStream
+ mutex.withLock {
+ // this method is called a lot, so we try and reuse output streams
+ // to reduce inner array allocations, and make the GC run less frequently
+ stream = if (freeBaos.isNotEmpty()) {
+ freeBaos.removeAt(0)
+ } else {
+ ByteArrayOutputStream(INITIAL_BUFFER_SIZE)
+ }
+ }
+ try {
+ // `Bitmap.CompressFormat.PNG` is slower than `JPEG`, but it allows transparency
+ // the BMP format allows an alpha channel, but Android decoding seems to ignore it
+ if (canHaveAlpha && bitmap.hasAlpha()) {
+ bitmap.compress(Bitmap.CompressFormat.PNG, quality, stream)
+ } else {
+ bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream)
+ }
+ if (recycle) bitmap.recycle()
+
+ // trailer byte to indicate whether the returned bytes are decoded/encoded
+ stream.write(FORMAT_BYTE_ENCODED)
+
+ val bufferSize = stream.size()
+ if (!MemoryUtils.canAllocate(bufferSize)) {
+ throw Exception("bitmap compressed to $bufferSize bytes, which cannot be allocated to a new byte array")
+ }
+
+ val byteArray = stream.toByteArray()
+ stream.reset()
+ mutex.withLock {
+ freeBaos.add(stream)
+ }
+ return byteArray
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to get bytes from bitmap", e)
+ }
+ return null
+ }
+
+ // convert bytes, without reallocation:
+ // - from original color space to sRGB.
+ @RequiresApi(Build.VERSION_CODES.O)
+ private fun argb8888ToArgb8888(bytes: ByteArray, connector: ColorSpace.Connector, start: Int = 0, end: Int = bytes.size) {
+ // unpacking from ARGB_8888 and packing to ARGB_8888
+ // stored as [3,2,1,0] -> [AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR]
+ for (i in start..<end step BPP_ARGB_8888) {
+ // mask with `0xff` to yield values in [0, 255], instead of [-128, 127]
+ val iB = bytes[i + 2].toInt() and 0xff
+ val iG = bytes[i + 1].toInt() and 0xff
+ val iR = bytes[i].toInt() and 0xff
+
+ // components as floats in sRGB
+ val srgbFloats = connector.transform(iR / MAX_8_BITS_FLOAT, iG / MAX_8_BITS_FLOAT, iB / MAX_8_BITS_FLOAT)
+ val srgbR = (srgbFloats[0] * 255.0f + 0.5f).toInt()
+ val srgbG = (srgbFloats[1] * 255.0f + 0.5f).toInt()
+ val srgbB = (srgbFloats[2] * 255.0f + 0.5f).toInt()
+
+ // keep alpha as it is, in `bytes[i + 3]`
+ bytes[i + 2] = srgbB.toByte()
+ bytes[i + 1] = srgbG.toByte()
+ bytes[i] = srgbR.toByte()
+ }
+ }
+
+ // convert bytes, without reallocation:
+ // - from config RGBA_F16 to ARGB_8888,
+ // - from original color space to sRGB.
+ @RequiresApi(Build.VERSION_CODES.O)
+ private fun rgbaf16ToArgb8888(bytes: ByteArray, connector: ColorSpace.Connector, start: Int = 0, end: Int = bytes.size) {
+ val indexDivider = BPP_RGBA_F16 / BPP_ARGB_8888
+ for (i in start..<end step BPP_RGBA_F16) {
+ // unpacking from RGBA_F16
+ // stored as [7,6,5,4,3,2,1,0] -> [AAAAAAAA AAAAAAAA BBBBBBBB BBBBBBBB GGGGGGGG GGGGGGGG RRRRRRRR RRRRRRRR]
+ val i7 = bytes[i + 7].toInt()
+ val i6 = bytes[i + 6].toInt()
+ val i5 = bytes[i + 5].toInt()
+ val i4 = bytes[i + 4].toInt()
+ val i3 = bytes[i + 3].toInt()
+ val i2 = bytes[i + 2].toInt()
+ val i1 = bytes[i + 1].toInt()
+ val i0 = bytes[i].toInt()
+
+ val hA = Half((((i7 and 0xff) shl 8) or (i6 and 0xff)).toShort())
+ val hB = Half((((i5 and 0xff) shl 8) or (i4 and 0xff)).toShort())
+ val hG = Half((((i3 and 0xff) shl 8) or (i2 and 0xff)).toShort())
+ val hR = Half((((i1 and 0xff) shl 8) or (i0 and 0xff)).toShort())
+
+ // components as floats in sRGB
+ val srgbFloats = connector.transform(hR.toFloat(), hG.toFloat(), hB.toFloat())
+ val srgbR = (srgbFloats[0] * 255.0f + 0.5f).toInt()
+ val srgbG = (srgbFloats[1] * 255.0f + 0.5f).toInt()
+ val srgbB = (srgbFloats[2] * 255.0f + 0.5f).toInt()
+ val alpha = (hA.toFloat() * 255.0f + 0.5f).toInt()
+
+ // packing to ARGB_8888
+ // stored as [3,2,1,0] -> [AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR]
+ val dstI = i / indexDivider
+ bytes[dstI + 3] = alpha.toByte()
+ bytes[dstI + 2] = srgbB.toByte()
+ bytes[dstI + 1] = srgbG.toByte()
+ bytes[dstI] = srgbR.toByte()
+ }
+ }
+
+ // convert bytes, without reallocation:
+ // - from config RGBA_1010102 to ARGB_8888,
+ // - from original color space to sRGB.
+ @RequiresApi(Build.VERSION_CODES.O)
+ private fun rgba1010102ToArgb8888(bytes: ByteArray, connector: ColorSpace.Connector, start: Int = 0, end: Int = bytes.size) {
+ val alphaFactor = 255.0f / MAX_2_BITS_FLOAT
+
+ for (i in start..<end step BPP_RGBA_1010102) {
+ // unpacking from RGBA_1010102
+ // stored as [3,2,1,0] -> [AABBBBBB BBBBGGGG GGGGGGRR RRRRRRRR]
+ val i3 = bytes[i + 3].toInt()
+ val i2 = bytes[i + 2].toInt()
+ val i1 = bytes[i + 1].toInt()
+ val i0 = bytes[i].toInt()
+
+ val iA = ((i3 and 0xc0) shr 6)
+ val iB = ((i3 and 0x3f) shl 4) or ((i2 and 0xf0) shr 4)
+ val iG = ((i2 and 0x0f) shl 6) or ((i1 and 0xfc) shr 2)
+ val iR = ((i1 and 0x03) shl 8) or ((i0 and 0xff) shr 0)
+
+ // components as floats in sRGB
+ val srgbFloats = connector.transform(iR / MAX_10_BITS_FLOAT, iG / MAX_10_BITS_FLOAT, iB / MAX_10_BITS_FLOAT)
+ val srgbR = (srgbFloats[0] * 255.0f + 0.5f).toInt()
+ val srgbG = (srgbFloats[1] * 255.0f + 0.5f).toInt()
+ val srgbB = (srgbFloats[2] * 255.0f + 0.5f).toInt()
+ val alpha = (iA * alphaFactor + 0.5f).toInt()
+
+ // packing to ARGB_8888
+ // stored as [3,2,1,0] -> [AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR]
+ bytes[i + 3] = alpha.toByte()
+ bytes[i + 2] = srgbB.toByte()
+ bytes[i + 1] = srgbG.toByte()
+ bytes[i] = srgbR.toByte()
+ }
+ }
+
+ fun applyExifOrientation(context: Context, bitmap: Bitmap?, rotationDegrees: Int?, isFlipped: Boolean?): Bitmap? {
+ if (bitmap == null || rotationDegrees == null || isFlipped == null) return bitmap
+ if (rotationDegrees == 0 && !isFlipped) return bitmap
+ val exifOrientation = getExifCode(rotationDegrees, isFlipped)
+ return TransformationUtils.rotateImageExif(getBitmapPool(context), bitmap, exifOrientation)
+ }
+
+ fun centerSquareCrop(context: Context, bitmap: Bitmap?, size: Int): Bitmap? {
+ bitmap ?: return null
+ return TransformationUtils.centerCrop(getBitmapPool(context), bitmap, size, size)
+ }
+
+ fun getBitmapPool(context: Context) = Glide.get(context).bitmapPool
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/BmpWriter.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/BmpWriter.kt
new file mode 100644
index 0000000..bfd9947
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/BmpWriter.kt
@@ -0,0 +1,110 @@
+package deckers.thibault.aves.utils
+
+import android.graphics.Bitmap
+import java.io.OutputStream
+import java.nio.ByteBuffer
+
+object BmpWriter {
+ private const val FILE_HEADER_SIZE = 14
+ private const val INFO_HEADER_SIZE = 40
+ private const val BYTE_PER_PIXEL = 3
+ private val pad = ByteArray(3)
+
+ // file header
+ private val bfType = byteArrayOf('B'.code.toByte(), 'M'.code.toByte())
+ private val bfReserved1 = intToWord(0)
+ private val bfReserved2 = intToWord(0)
+ private val bfOffBits = intToDWord(FILE_HEADER_SIZE + INFO_HEADER_SIZE)
+
+ // info header
+ private val biSize = intToDWord(INFO_HEADER_SIZE)
+ private val biPlanes = intToWord(1)
+ private val biBitCount = intToWord(BYTE_PER_PIXEL * 8)
+ private val biCompression = intToDWord(0)
+ private val biXPelsPerMeter = intToDWord(0)
+ private val biYPelsPerMeter = intToDWord(0)
+ private val biClrUsed = intToDWord(0)
+ private val biClrImportant = intToDWord(0)
+
+ // converts an int to a word (2-byte array)
+ private fun intToWord(v: Int): ByteArray {
+ val retValue = ByteArray(2)
+ retValue[0] = (v and 0xFF).toByte()
+ retValue[1] = (v shr 8 and 0xFF).toByte()
+ return retValue
+ }
+
+ // converts an int to a double word (4-byte array)
+ private fun intToDWord(v: Int): ByteArray {
+ val retValue = ByteArray(4)
+ retValue[0] = (v and 0xFF).toByte()
+ retValue[1] = (v shr 8 and 0xFF).toByte()
+ retValue[2] = (v shr 16 and 0xFF).toByte()
+ retValue[3] = (v shr 24 and 0xFF).toByte()
+ return retValue
+ }
+
+ fun writeRGB24(
+ bitmap: Bitmap,
+ outputStream: OutputStream
+ ) {
+ // init
+ val biWidth = bitmap.width
+ val biHeight = bitmap.height
+ val padPerRow = (4 - (biWidth * BYTE_PER_PIXEL) % 4) % 4
+ val biSizeImage = (biWidth * BYTE_PER_PIXEL + padPerRow) * biHeight
+ val bfSize = FILE_HEADER_SIZE + INFO_HEADER_SIZE + biSizeImage
+
+ var buffer = ByteBuffer.allocate(FILE_HEADER_SIZE + INFO_HEADER_SIZE)
+
+ // file header
+ buffer.put(bfType)
+ buffer.put(intToDWord(bfSize))
+ buffer.put(bfReserved1)
+ buffer.put(bfReserved2)
+ buffer.put(bfOffBits)
+
+ // info header
+ buffer.put(biSize)
+ buffer.put(intToDWord(biWidth))
+ buffer.put(intToDWord(biHeight))
+ buffer.put(biPlanes)
+ buffer.put(biBitCount)
+ buffer.put(biCompression)
+ buffer.put(intToDWord(biSizeImage))
+ buffer.put(biXPelsPerMeter)
+ buffer.put(biYPelsPerMeter)
+ buffer.put(biClrUsed)
+ buffer.put(biClrImportant)
+
+ outputStream.write(buffer.array())
+
+ // pixels
+ buffer = ByteBuffer.allocate(biWidth * BYTE_PER_PIXEL + padPerRow)
+ val pixels = IntArray(biWidth)
+ val rgb = ByteArray(BYTE_PER_PIXEL)
+ var value: Int
+ var row = biHeight - 1
+ while (row >= 0) {
+ bitmap.getPixels(pixels, 0, biWidth, 0, row, biWidth, 1)
+
+ var column = 0
+ while (column < biWidth) {
+ // non-premultiplied ARGB values in the sRGB color space
+ value = pixels[column]
+ // blue: [0], green: [1], red: [2]
+ rgb[0] = (value and 0xFF).toByte()
+ rgb[1] = (value shr 8 and 0xFF).toByte()
+ rgb[2] = (value shr 16 and 0xFF).toByte()
+ buffer.put(rgb)
+ column++
+ }
+ if (padPerRow > 0) {
+ buffer.put(pad, 0, padPerRow)
+ }
+ outputStream.write(buffer.array())
+ buffer.clear()
+ row--
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/ByteUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ByteUtils.kt
new file mode 100644
index 0000000..a0e1e83
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ByteUtils.kt
@@ -0,0 +1,15 @@
+package deckers.thibault.aves.utils
+
+import java.nio.ByteBuffer
+
+fun ByteBuffer.toByteArray(): ByteArray {
+ val bytes = ByteArray(remaining())
+ get(bytes, 0, bytes.size)
+ return bytes
+}
+
+fun Int.toHex(): String = "0x${byteArrayOf(shr(8).toByte(), toByte()).toHex()}"
+
+fun ByteArray.toHex(): String = joinToString(separator = "") { it.toHex() }
+
+fun Byte.toHex(): String = "%02x".format(this) \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/CollectionUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/CollectionUtils.kt
new file mode 100644
index 0000000..a2af9f4
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/CollectionUtils.kt
@@ -0,0 +1,44 @@
+package deckers.thibault.aves.utils
+
+import android.os.Build
+
+// compatibility extension for `removeIf` for API <24
+fun <E> MutableList<E>.compatRemoveIf(filter: (t: E) -> Boolean): Boolean {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ this.removeIf(filter)
+ } else {
+ var removed = false
+ val each = this.iterator()
+ while (each.hasNext()) {
+ if (filter(each.next())) {
+ each.remove()
+ removed = true
+ }
+ }
+ return removed
+ }
+}
+
+// Boyer-Moore algorithm for pattern searching
+// Returns: an index of the first occurrence of the pattern or -1 if none is found.
+fun ByteArray.indexOfBytes(pattern: ByteArray, start: Int = 0): Int {
+ val n: Int = this.size
+ val m: Int = pattern.size
+ val badChar = Array(256) { 0 }
+ var i = 0
+ while (i < m) {
+ badChar[pattern[i].toUByte().toInt()] = i
+ i += 1
+ }
+ var j: Int = m - 1
+ var s = start
+ while (s <= (n - m)) {
+ while (j >= 0 && pattern[j] == this[s + j]) {
+ j -= 1
+ }
+ if (j < 0) return s
+ s += Integer.max(1, j - badChar[this[s + j].toUByte().toInt()])
+ j = m - 1
+ }
+ return -1
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat.kt
new file mode 100644
index 0000000..eea1b08
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat.kt
@@ -0,0 +1,84 @@
+package deckers.thibault.aves.utils
+
+import android.app.Activity
+import android.content.Intent
+import android.content.pm.ApplicationInfo
+import android.content.pm.PackageManager
+import android.content.pm.ResolveInfo
+import android.graphics.BitmapRegionDecoder
+import android.location.Address
+import android.location.Geocoder
+import android.os.Build
+import android.os.Parcelable
+import android.view.Display
+import java.io.IOException
+import java.io.InputStream
+
+inline fun <reified T> Intent.getParcelableExtraCompat(name: String): T? {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ getParcelableExtra(name, T::class.java)
+ } else {
+ @Suppress("deprecation")
+ getParcelableExtra<Parcelable>(name) as? T
+ }
+}
+
+fun Activity.getDisplayCompat(): Display? {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ display
+ } else {
+ @Suppress("deprecation")
+ windowManager.defaultDisplay
+ }
+}
+
+fun PackageManager.getApplicationInfoCompat(packageName: String, flags: Int): ApplicationInfo {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ getApplicationInfo(packageName, PackageManager.ApplicationInfoFlags.of(flags.toLong()))
+ } else {
+ getApplicationInfo(packageName, flags)
+ }
+}
+
+fun PackageManager.queryIntentActivitiesCompat(intent: Intent, flags: Int): List<ResolveInfo> {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ queryIntentActivities(intent, PackageManager.ResolveInfoFlags.of(flags.toLong()))
+ } else {
+ queryIntentActivities(intent, flags)
+ }
+}
+
+fun Geocoder.getFromLocationCompat(
+ latitude: Double,
+ longitude: Double,
+ maxResults: Int,
+ processAddresses: (addresses: List<Address>) -> Unit,
+ onError: (errorCode: String, errorMessage: String?, errorDetails: Any?) -> Unit,
+) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ Compat33.geocoderGetFromLocation(this, latitude, longitude, maxResults, processAddresses, onError)
+ } else {
+ try {
+ @Suppress("deprecation")
+ val addresses = getFromLocation(latitude, longitude, maxResults) ?: ArrayList()
+ processAddresses(addresses)
+ } catch (e: IOException) {
+ // `grpc failed`, etc.
+ onError("getAddress-network", "failed to get address because of network issues", e.message)
+ } catch (e: Exception) {
+ onError("getAddress-exception", "failed to get address", e.message)
+ }
+ }
+}
+
+object BitmapRegionDecoderCompat {
+ @Throws(IOException::class)
+ fun newInstance(input: InputStream): BitmapRegionDecoder? {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ BitmapRegionDecoder.newInstance(input)
+ } else {
+ @Suppress("deprecation")
+ BitmapRegionDecoder.newInstance(input, false)
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat33.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat33.kt
new file mode 100644
index 0000000..5377732
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/Compat33.kt
@@ -0,0 +1,30 @@
+package deckers.thibault.aves.utils
+
+import android.location.Address
+import android.location.Geocoder
+import android.os.Build
+import androidx.annotation.RequiresApi
+
+/**
+ * Compatibility layer in a separate object to avoid class loading issues on older Android versions.
+ * e.g. `ClassNotFoundException` for `android.location.Geocoder$GeocodeListener`
+ */
+@RequiresApi(Build.VERSION_CODES.TIRAMISU)
+object Compat33 {
+ fun geocoderGetFromLocation(
+ geocoder: Geocoder,
+ latitude: Double,
+ longitude: Double,
+ maxResults: Int,
+ processAddresses: (addresses: List<Address>) -> Unit,
+ onError: (errorCode: String, errorMessage: String?, errorDetails: Any?) -> Unit,
+ ) {
+ geocoder.getFromLocation(latitude, longitude, maxResults, object : Geocoder.GeocodeListener {
+ override fun onGeocode(addresses: List<Address?>) = processAddresses(addresses.filterNotNull())
+
+ override fun onError(errorMessage: String?) {
+ onError("getAddress-asyncerror", "failed to get address", errorMessage)
+ }
+ })
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/ContextUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ContextUtils.kt
new file mode 100644
index 0000000..7a0b937
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ContextUtils.kt
@@ -0,0 +1,61 @@
+package deckers.thibault.aves.utils
+
+import android.content.ContentResolver
+import android.content.ContentUris
+import android.content.Context
+import android.database.Cursor
+import android.net.Uri
+import android.provider.MediaStore
+import android.util.Log
+import deckers.thibault.aves.utils.UriUtils.tryParseId
+
+object ContextUtils {
+ private val LOG_TAG = LogUtils.createTag<ContextUtils>()
+
+ fun Context.devicePixelRatio(): Float = resources.displayMetrics.density
+
+ fun Context.resourceUri(resourceId: Int): Uri = with(resources) {
+ Uri.Builder()
+ .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
+ .authority(getResourcePackageName(resourceId))
+ .appendPath(getResourceTypeName(resourceId))
+ .appendPath(getResourceEntryName(resourceId))
+ .build()
+ }
+
+ fun Context.queryContentPropValue(uri: Uri, mimeType: String, column: String): Any? {
+ var contentUri: Uri = uri
+ if (StorageUtils.isMediaStoreContentUri(uri)) {
+ uri.tryParseId()?.let { id ->
+ contentUri = when {
+ MimeTypes.isImage(mimeType) -> ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
+ MimeTypes.isVideo(mimeType) -> ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
+ else -> uri
+ }
+ contentUri = StorageUtils.getOriginalUri(this, contentUri)
+ }
+ }
+
+ var value: Any? = null
+ try {
+ val cursor = contentResolver.query(contentUri, arrayOf(column), null, null, null)
+ if (cursor == null || !cursor.moveToFirst()) {
+ Log.w(LOG_TAG, "failed to get cursor for contentUri=$contentUri column=$column")
+ } else {
+ value = when (cursor.getType(0)) {
+ Cursor.FIELD_TYPE_NULL -> null
+ Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(0)
+ Cursor.FIELD_TYPE_FLOAT -> cursor.getFloat(0)
+ Cursor.FIELD_TYPE_STRING -> cursor.getString(0)
+ Cursor.FIELD_TYPE_BLOB -> cursor.getBlob(0)
+ else -> null
+ }
+ cursor.close()
+ }
+ } catch (e: Exception) {
+ // throws SQLiteException/IllegalArgumentException when the requested prop is not a known column
+ Log.w(LOG_TAG, "failed to get value for contentUri=$contentUri column=$column", e)
+ }
+ return value
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/ExceptionUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ExceptionUtils.kt
new file mode 100644
index 0000000..f164c97
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/ExceptionUtils.kt
@@ -0,0 +1,10 @@
+package deckers.thibault.aves.utils
+
+inline fun <reified T : Throwable> Exception.anyCauseIs(): Boolean {
+ var cause: Throwable? = this
+ while (cause != null) {
+ if (cause is T) return true
+ cause = cause.cause
+ }
+ return false
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/FileUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/FileUtils.kt
new file mode 100644
index 0000000..6b8a37e
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/FileUtils.kt
@@ -0,0 +1,45 @@
+package deckers.thibault.aves.utils
+
+import android.os.Build
+import java.io.File
+import java.io.InputStream
+import java.io.OutputStream
+import java.nio.channels.Channels
+import java.nio.channels.FileChannel
+import java.nio.file.StandardOpenOption
+
+object FileUtils {
+ fun File.transferFrom(inputStream: InputStream?, streamLength: Long?) {
+ inputStream ?: return
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && streamLength != null) {
+ FileChannel.open(toPath(), StandardOpenOption.WRITE).use { fileOutput ->
+ Channels.newChannel(inputStream).use { input ->
+ fileOutput.transferFrom(input, 0, streamLength)
+ }
+ }
+ } else {
+ outputStream().use { fileOutput ->
+ inputStream.use { input ->
+ input.copyTo(fileOutput)
+ }
+ }
+ }
+ }
+
+ fun File.transferTo(outputStream: OutputStream) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ FileChannel.open(toPath()).use { fileInput ->
+ Channels.newChannel(outputStream).use { output ->
+ fileInput.transferTo(0, fileInput.size(), output)
+ }
+ }
+ } else {
+ inputStream().use { fileInput ->
+ outputStream.use { output ->
+ fileInput.copyTo(output)
+ }
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/FlutterUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/FlutterUtils.kt
new file mode 100644
index 0000000..e7b1792
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/FlutterUtils.kt
@@ -0,0 +1,72 @@
+package deckers.thibault.aves.utils
+
+import android.content.Context
+import android.os.Handler
+import android.os.Looper
+import android.util.Log
+import io.flutter.FlutterInjector
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.embedding.engine.dart.DartExecutor
+import io.flutter.embedding.engine.loader.FlutterLoader
+import io.flutter.view.FlutterCallbackInformation
+import kotlin.coroutines.Continuation
+import kotlin.coroutines.resume
+import kotlin.coroutines.suspendCoroutine
+
+object FlutterUtils {
+ private val LOG_TAG = LogUtils.createTag<FlutterUtils>()
+
+ suspend fun initFlutterEngine(
+ context: Context,
+ sharedPreferencesKey: String,
+ callbackHandleKey: String,
+ engineSetter: (engine: FlutterEngine) -> Unit,
+ ) {
+ val callbackHandle = context.getSharedPreferences(sharedPreferencesKey, Context.MODE_PRIVATE).getLong(callbackHandleKey, 0)
+ if (callbackHandle == 0L) {
+ Log.e(LOG_TAG, "failed to retrieve registered callback handle for sharedPreferencesKey=$sharedPreferencesKey callbackHandleKey=$callbackHandleKey")
+ return
+ }
+
+ lateinit var flutterLoader: FlutterLoader
+ runOnUiThread {
+ // initialization must happen on the main thread
+ flutterLoader = FlutterInjector.instance().flutterLoader().apply {
+ startInitialization(context)
+ ensureInitializationComplete(context, null)
+ }
+ }
+
+ val callbackInfo = FlutterCallbackInformation.lookupCallbackInformation(callbackHandle)
+ if (callbackInfo == null) {
+ Log.e(LOG_TAG, "failed to find callback information for sharedPreferencesKey=$sharedPreferencesKey callbackHandleKey=$callbackHandleKey")
+ return
+ }
+
+ val args = DartExecutor.DartCallback(
+ context.assets,
+ flutterLoader.findAppBundlePath(),
+ callbackInfo
+ )
+ runOnUiThread {
+ val engine = FlutterEngine(context).apply {
+ dartExecutor.executeDartCallback(args)
+ }
+ engineSetter(engine)
+ }
+ }
+
+ suspend fun runOnUiThread(r: Runnable) {
+ val mainLooper = Looper.getMainLooper()
+ if (Looper.myLooper() != mainLooper) {
+ suspendCoroutine { cont: Continuation<Boolean> ->
+ Handler(mainLooper).post {
+ r.run()
+ cont.resume(true)
+ }
+ }
+ } else {
+ r.run()
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/HashUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/HashUtils.kt
new file mode 100644
index 0000000..c90e317
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/HashUtils.kt
@@ -0,0 +1,35 @@
+package deckers.thibault.aves.utils
+
+import java.io.InputStream
+import java.math.BigInteger
+import java.security.MessageDigest
+
+object HashUtils {
+ fun getHash(input: InputStream, algorithmKey: String): String {
+ val algorithm = toMessageDigestAlgorithm(algorithmKey)
+ val digest = MessageDigest.getInstance(algorithm)
+ val buffer = ByteArray(1 shl 14)
+ var read: Int
+ while ((input.read(buffer).also { read = it }) > 0) {
+ digest.update(buffer, 0, read)
+ }
+ val md5sum = digest.digest()
+ val output = BigInteger(1, md5sum).toString(16)
+
+ return when (algorithm) {
+ "MD5" -> output.padStart(32, '0') // 128 bits = 32 hex digits
+ "SHA-1" -> output.padStart(40, '0') // 160 bits = 40 hex digits
+ "SHA-256" -> output.padStart(64, '0') // 256 bits = 64 hex digits
+ else -> throw IllegalArgumentException("unsupported hash algorithm: $algorithmKey")
+ }
+ }
+
+ private fun toMessageDigestAlgorithm(algorithmKey: String): String {
+ return when (algorithmKey) {
+ "md5" -> "MD5"
+ "sha1" -> "SHA-1"
+ "sha256" -> "SHA-256"
+ else -> throw IllegalArgumentException("unsupported hash algorithm: $algorithmKey")
+ }
+ }
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/LogUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/LogUtils.kt
new file mode 100644
index 0000000..e7fb5f7
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/LogUtils.kt
@@ -0,0 +1,26 @@
+package deckers.thibault.aves.utils
+
+object LogUtils {
+ const val LOG_TAG_MAX_LENGTH = 23
+
+ val LOG_TAG_PACKAGE_PATTERN = Regex("(\\w)(\\w*)\\.")
+ val LOWER_CASE_PATTERN = Regex("[a-z]")
+
+ // create an Android logger friendly log tag for the specified class
+ inline fun <reified T> createTag(): String {
+ val kClass = T::class
+ // shorten class name to "a.b.CccDdd"
+ var logTag = LOG_TAG_PACKAGE_PATTERN.replace(kClass.qualifiedName!!, "$1.")
+ if (logTag.length > LOG_TAG_MAX_LENGTH) {
+ // shorten class name to "a.b.CD"
+ val simpleName = kClass.simpleName!!
+ val shortSimpleName = simpleName.replace(LOWER_CASE_PATTERN, "")
+ logTag = logTag.replace(simpleName, shortSimpleName)
+ if (logTag.length > LOG_TAG_MAX_LENGTH) {
+ // shorten class name to "CD"
+ logTag = shortSimpleName
+ }
+ }
+ return logTag
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/MathUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MathUtils.kt
new file mode 100644
index 0000000..7002c07
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MathUtils.kt
@@ -0,0 +1,9 @@
+package deckers.thibault.aves.utils
+
+import kotlin.math.log2
+import kotlin.math.pow
+
+object MathUtils {
+ fun highestPowerOf2(x: Int): Int = highestPowerOf2(x.toDouble())
+ fun highestPowerOf2(x: Double): Int = if (x < 1) 0 else 2.toDouble().pow(log2(x).toInt()).toInt()
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/MemoryUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MemoryUtils.kt
new file mode 100644
index 0000000..fc91e2d
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MemoryUtils.kt
@@ -0,0 +1,19 @@
+package deckers.thibault.aves.utils
+
+import android.util.Log
+
+object MemoryUtils {
+ private val LOG_TAG = LogUtils.createTag<MemoryUtils>()
+
+ fun canAllocate(byteSize: Number?): Boolean {
+ byteSize ?: return true
+ val availableHeapSize = getAvailableHeapSize()
+ val danger = byteSize.toLong() > availableHeapSize
+ if (danger) {
+ Log.e(LOG_TAG, "trying to handle $byteSize bytes, with only $availableHeapSize free bytes")
+ }
+ return !danger
+ }
+
+ fun getAvailableHeapSize() = Runtime.getRuntime().let { it.maxMemory() - (it.totalMemory() - it.freeMemory()) }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/MimeTypes.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MimeTypes.kt
new file mode 100644
index 0000000..9996813
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/MimeTypes.kt
@@ -0,0 +1,192 @@
+package deckers.thibault.aves.utils
+
+import android.webkit.MimeTypeMap
+import deckers.thibault.aves.glide.MultiPageImage
+import androidx.exifinterface.media.ExifInterfaceFork as ExifInterface
+
+object MimeTypes {
+ const val ANY = "*/*"
+
+ // generic raster
+ private const val AVIF = "image/avif"
+ const val BMP = "image/bmp"
+ private const val DJVU = "image/vnd.djvu"
+ const val GIF = "image/gif"
+ const val HEIC = "image/heic"
+ const val HEIF = "image/heif"
+ private const val ICO = "image/x-icon"
+ const val JPEG = "image/jpeg"
+ const val PNG = "image/png"
+ const val PSD_VND = "image/vnd.adobe.photoshop"
+ const val PSD_X = "image/x-photoshop"
+ const val TIFF = "image/tiff"
+ private const val WBMP = "image/vnd.wap.wbmp"
+ const val WEBP = "image/webp"
+
+ // raw raster
+ private const val ARW = "image/x-sony-arw"
+ private const val CR2 = "image/x-canon-cr2"
+ private const val CRW = "image/x-canon-crw"
+ private const val DCR = "image/x-kodak-dcr"
+ const val DNG = "image/dng"
+ const val DNG_ADOBE = "image/x-adobe-dng"
+ private const val ERF = "image/x-epson-erf"
+ private const val K25 = "image/x-kodak-k25"
+ private const val KDC = "image/x-kodak-kdc"
+ private const val MRW = "image/x-minolta-mrw"
+ private const val NEF = "image/x-nikon-nef"
+ private const val NRW = "image/x-nikon-nrw"
+ private const val ORF = "image/x-olympus-orf"
+ private const val PEF = "image/x-pentax-pef"
+ private const val RAF = "image/x-fuji-raf"
+ private const val RAW = "image/x-panasonic-raw"
+ private const val RW2 = "image/x-panasonic-rw2"
+ private const val SR2 = "image/x-sony-sr2"
+ private const val SRF = "image/x-sony-srf"
+ private const val SRW = "image/x-samsung-srw"
+ private const val X3F = "image/x-sigma-x3f"
+
+ // vector
+ const val SVG = "image/svg+xml"
+
+ // video
+ private const val AVI = "video/avi"
+ private const val AVI_VND = "video/vnd.avi"
+ const val DVD = "video/dvd"
+ private const val MKV = "video/x-matroska"
+ const val MOV = "video/quicktime"
+ private const val MP2T = "video/mp2t"
+ private const val MP2TS = "video/mp2ts"
+ const val MP4 = "video/mp4"
+ private const val OGV = "video/ogg"
+ private const val WEBM = "video/webm"
+
+ // others
+ const val ZIP = "application/zip"
+
+ fun isImage(mimeType: String?) = mimeType != null && mimeType.startsWith("image")
+
+ fun isVideo(mimeType: String?) = mimeType != null && mimeType.startsWith("video")
+
+ // assume that `HEIF` is a `HEIC` (using the default `HEVC` codec)
+ fun isHeic(mimeType: String?) = mimeType == HEIC || mimeType == HEIF
+
+ // `AVIF` and `HEIC` both derive from `HEIF`, which derives from `ISOBMFF`.
+ // `MP4` also derives from `ISOBMFF` but is not an image format.
+ fun isIsoBMFFImage(mimeType: String?) = mimeType == AVIF || isHeic(mimeType)
+
+ fun isRaw(mimeType: String): Boolean {
+ return when (mimeType) {
+ ARW, CR2, CRW, DCR, DNG, DNG_ADOBE, ERF, K25, KDC, MRW, NEF, NRW, ORF, PEF, RAF, RAW, RW2, SR2, SRF, SRW, X3F -> true
+ else -> false
+ }
+ }
+
+ // returns whether the specified MIME type represents
+ // a raster image format that allows an alpha channel
+ fun canHaveAlpha(mimeType: String?) = when (mimeType) {
+ AVIF, BMP, GIF, ICO, PNG, SVG, TIFF, WEBP -> true
+ else -> false
+ }
+
+ // as of Flutter v3.16.4, with additional custom handling for SVG in Dart
+ fun handleEncodedBytesInFlutter(mimeType: String) = when (mimeType) {
+ JPEG, PNG, GIF, WEBP, BMP, WBMP, ICO, SVG -> true
+ else -> false
+ }
+
+ // as of `metadata-extractor` v2.14.0
+ fun canReadWithMetadataExtractor(mimeType: String?) = when (mimeType) {
+ DJVU, SVG, WBMP -> false
+ MKV, MP2T, MP2TS, OGV, WEBM -> false
+ else -> true
+ }
+
+ // as of `ExifInterface` v1.4.1, method `isSupportedMimeType` reports no support for AVIF,
+ // but documentation reports:
+ // * Supported for reading: JPEG, PNG, WebP, HEIC, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW, RAF, AVIF (on API 31+).
+ // * Supported for writing: JPEG, PNG, WebP.
+ fun canReadWithExifInterface(mimeType: String, strict: Boolean = true): Boolean {
+ if (!strict) return true
+ return ExifInterface.isSupportedMimeType(mimeType) || mimeType == AVIF
+ }
+
+ // as of latest PixyMeta
+ fun canReadWithPixyMeta(mimeType: String) = when (mimeType) {
+ JPEG, TIFF, PNG, GIF, BMP -> true
+ else -> false
+ }
+
+ fun canEditExif(mimeType: String) = when (mimeType) {
+ // as of androidx.exifinterface:exifinterface:1.3.4
+ JPEG, PNG, WEBP -> true
+ else -> false
+ }
+
+ fun canEditIptc(mimeType: String) = when (mimeType) {
+ // as of latest PixyMeta
+ JPEG, TIFF -> true
+ else -> false
+ }
+
+ fun canEditXmp(mimeType: String) = when (mimeType) {
+ // as of latest PixyMeta
+ JPEG, TIFF, PNG, GIF -> true
+ // using `mp4parser`
+ MP4 -> true
+ else -> false
+ }
+
+ fun canRemoveMetadata(mimeType: String) = when (mimeType) {
+ // as of latest PixyMeta
+ JPEG, TIFF -> true
+ else -> false
+ }
+
+ // Glide automatically applies EXIF orientation when decoding images of known formats
+ // but we need to rotate the decoded bitmap for the other formats
+ // maybe related to ExifInterface version used by Glide:
+ // https://github.com/bumptech/glide/blob/master/gradle.properties#L21
+ fun needRotationAfterGlide(mimeType: String, pageId: Int?): Boolean {
+ return if (pageId != null && MultiPageImage.isSupported(mimeType)) {
+ true
+ } else when (mimeType) {
+ AVIF, HEIC, HEIF, PNG, TIFF, WEBP -> true
+ else -> isRaw(mimeType)
+ }
+ }
+
+ // Thumbnails obtained from the Media Store are automatically rotated
+ // according to EXIF orientation when decoding images of known formats
+ // but we need to rotate the decoded bitmap for the other formats
+ fun needRotationAfterContentResolverThumbnail(mimeType: String) = when (mimeType) {
+ DNG, DNG_ADOBE, PNG -> true
+ else -> false
+ }
+
+ // extensions
+
+ // among other refs:
+ // - https://android.googlesource.com/platform/external/mime-support/+/refs/heads/master/mime.types
+ fun extensionFor(mimeType: String, defaultExtension: String?): String = when (mimeType) {
+ AVI, AVI_VND -> ".avi"
+ DNG, DNG_ADOBE -> ".dng"
+ HEIC, HEIF -> ".heif"
+ MP2T, MP2TS -> ".m2ts"
+ PSD_VND, PSD_X -> ".psd"
+ else -> {
+ val ext = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType) ?: defaultExtension
+ if (ext != null) {
+ // fallback to provided extension when available,
+ // typically the original file extension when moving/renaming
+ if (ext.startsWith(".")) ext else ".$ext"
+ } else {
+ // fallback to generic extensions,
+ // as incorrect file extensions are better than none for media detection
+ if (isVideo(mimeType)) ".mp4" else ".jpg"
+ }
+ }
+ }
+
+ val TIFF_EXTENSION_PATTERN = Regex(".*\\.tiff?", RegexOption.IGNORE_CASE)
+}
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/PermissionManager.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/PermissionManager.kt
new file mode 100644
index 0000000..a5a2352
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/PermissionManager.kt
@@ -0,0 +1,243 @@
+package deckers.thibault.aves.utils
+
+import android.app.Activity
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Binder
+import android.os.Build
+import android.os.Environment
+import android.provider.DocumentsContract
+import android.provider.MediaStore
+import android.util.Log
+import androidx.annotation.RequiresApi
+import deckers.thibault.aves.MainActivity
+import deckers.thibault.aves.PendingStorageAccessResultHandler
+import deckers.thibault.aves.model.FieldMap
+import deckers.thibault.aves.utils.StorageUtils.PathSegments
+import java.io.File
+import java.util.Locale
+import java.util.concurrent.CompletableFuture
+
+object PermissionManager {
+ private val LOG_TAG = LogUtils.createTag<PermissionManager>()
+
+ private val MEDIA_STORE_INSERTION_PRIMARY_DIRS = listOf(
+ Environment.DIRECTORY_DCIM,
+ Environment.DIRECTORY_DOWNLOADS,
+ Environment.DIRECTORY_PICTURES,
+ )
+
+ fun requestDirectoryAccess(activity: Activity, path: String, onGranted: (uri: Uri) -> Unit, onDenied: () -> Unit) {
+ Log.i(LOG_TAG, "request user to select and grant access permission to path=$path")
+
+ // `StorageVolume.createOpenDocumentTreeIntent` is an alternative,
+ // and it helps with initial volume, but not with initial directory
+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ // initial URI should not be a `tree document URI`, but a simple `document URI`
+ StorageUtils.convertDirPathToDocumentUri(activity, path)?.let {
+ intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, it)
+ }
+ }
+
+ if (intent.resolveActivity(activity.packageManager) != null) {
+ MainActivity.pendingStorageAccessResultHandlers[MainActivity.DOCUMENT_TREE_ACCESS_REQUEST] = PendingStorageAccessResultHandler(path, onGranted, onDenied)
+ activity.startActivityForResult(intent, MainActivity.DOCUMENT_TREE_ACCESS_REQUEST)
+ } else {
+ MainActivity.notifyError("failed to resolve activity for intent=$intent extras=${intent.extras}")
+ onDenied()
+ }
+ }
+
+ @RequiresApi(Build.VERSION_CODES.R)
+ fun requestMediaFileAccess(activity: Activity, uris: List<Uri>, mimeTypes: List<String>): Boolean {
+ val safeUris = uris.mapIndexed { index, uri -> StorageUtils.getMediaStoreScopedStorageSafeUri(uri, mimeTypes[index]) }
+
+ val todoUris = ArrayList<Uri>()
+ val pid = Binder.getCallingPid()
+ val uid = Binder.getCallingUid()
+ val flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ activity.checkUriPermissions(safeUris, pid, uid, flags)
+ } else {
+ safeUris.map { activity.checkUriPermission(it, pid, uid, flags) }.toIntArray()
+ }.forEachIndexed { index, permission ->
+ if (permission != PackageManager.PERMISSION_GRANTED) {
+ todoUris.add(safeUris[index])
+ }
+ }
+ if (todoUris.isEmpty()) return true
+
+ Log.i(LOG_TAG, "request user to select and grant access permission to uris=$todoUris")
+ val intentSender = MediaStore.createWriteRequest(activity.contentResolver, safeUris).intentSender
+ MainActivity.pendingScopedStoragePermissionCompleter = CompletableFuture<Boolean>()
+ activity.startIntentSenderForResult(intentSender, MainActivity.MEDIA_WRITE_BULK_PERMISSION_REQUEST, null, 0, 0, 0, null)
+ val granted = MainActivity.pendingScopedStoragePermissionCompleter!!.join()
+ MainActivity.pendingScopedStoragePermissionCompleter = null
+
+ return granted
+ }
+
+ fun getGrantedDirForPath(context: Context, anyPath: String): String? {
+ return getAccessibleDirs(context).firstOrNull { anyPath.startsWith(it) }
+ }
+
+ fun getInaccessibleDirectories(context: Context, dirPaths: List<String>): List<Map<String, String>> {
+ val concreteDirPaths = dirPaths.filter { it != StorageUtils.TRASH_PATH_PLACEHOLDER }
+ val accessibleDirs = getAccessibleDirs(context)
+ val restrictedPrimaryDirectoriesLower = getRestrictedPrimaryDirectories().map { it.lowercase(Locale.ROOT) }
+
+ // find set of inaccessible directories for each volume
+ val dirsPerVolume = HashMap<String, MutableSet<String>>()
+ for (dirPath in concreteDirPaths.map { if (it.endsWith(File.separator)) it else it + File.separator }) {
+ if (accessibleDirs.none { dirPath.startsWith(it) }) {
+ // inaccessible dirs
+ val segments = PathSegments(context, dirPath)
+ segments.volumePath?.let { volumePath ->
+ val dirSet = dirsPerVolume[volumePath] ?: HashSet()
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ // request primary directory on volume from Android 11 (API 30)
+ val relativeDir = segments.relativeDir
+ if (relativeDir != null) {
+ val dirSegments = relativeDir.split(File.separator).takeWhile { it.isNotEmpty() }
+ val primaryDir = dirSegments.firstOrNull()
+ if (dirSegments.size > 1 && restrictedPrimaryDirectoriesLower.contains(primaryDir?.lowercase(Locale.ROOT))) {
+ // request secondary directory (if any) for restricted primary directory
+ val dir = dirSegments.take(2).joinToString(File.separator)
+ // only register directories that exist on storage, so they can be selected for access grant
+ if (File(volumePath, dir).exists()) {
+ dirSet.add(dir)
+ }
+ } else {
+ primaryDir?.let { dirSet.add(it) }
+ }
+ } else {
+ // the requested path is the volume root itself
+ // which cannot be granted, due to Android 11 restrictions
+ dirSet.add("")
+ }
+ } else {
+ // request volume root until Android 10 (API 29)
+ dirSet.add("")
+ }
+ dirsPerVolume[volumePath] = dirSet
+ }
+ }
+ }
+
+ // format for easier handling on Flutter
+ return ArrayList<Map<String, String>>().apply {
+ addAll(dirsPerVolume.flatMap { (volumePath, relativeDirs) ->
+ relativeDirs.map { relativeDir ->
+ hashMapOf(
+ "volumePath" to volumePath,
+ "relativeDir" to relativeDir,
+ )
+ }
+ })
+ }
+ }
+
+ fun canInsertByMediaStore(directories: List<FieldMap>): Boolean {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ val insertionDirsLower = MEDIA_STORE_INSERTION_PRIMARY_DIRS.map { it.lowercase(Locale.ROOT) }
+ directories.all {
+ val relativeDir = it["relativeDir"] as String
+ val segments = relativeDir.split(File.separator)
+ segments.isNotEmpty() && insertionDirsLower.contains(segments.first().lowercase(Locale.ROOT))
+ }
+ } else {
+ true
+ }
+ }
+
+ fun revokeDirectoryAccess(context: Context, path: String): Boolean {
+ return StorageUtils.convertDirPathToTreeDocumentUri(context, path)?.let {
+ releaseUriPermission(context, it)
+ true
+ } ?: false
+ }
+
+ // returns paths matching directory URIs granted by the user
+ fun getGrantedDirs(context: Context): Set<String> {
+ val grantedDirs = HashSet<String>()
+ for (uriPermission in context.contentResolver.persistedUriPermissions) {
+ val dirPath = StorageUtils.convertTreeDocumentUriToDirPath(context, uriPermission.uri)
+ dirPath?.let { grantedDirs.add(it) }
+ }
+ return grantedDirs
+ }
+
+ // returns paths accessible to the app (granted by the user or by default)
+ private fun getAccessibleDirs(context: Context): Set<String> {
+ val accessibleDirs = HashSet(getGrantedDirs(context))
+ accessibleDirs.addAll(context.getExternalFilesDirs(null).filterNotNull().map { it.path })
+
+ // from API 21 / Android 5.0 / Lollipop, removable storage requires access permission, but directory access grant is possible
+ // from API 30 / Android 11 / R, any storage requires access permission
+ if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {
+ accessibleDirs.add(StorageUtils.getPrimaryVolumePath(context))
+ }
+ return accessibleDirs
+ }
+
+ private fun getRestrictedPrimaryDirectories(): List<String> {
+ val dirs = ArrayList<String>()
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ // cf https://developer.android.com/about/versions/11/privacy/storage#directory-access
+ dirs.add(Environment.DIRECTORY_DOWNLOADS)
+ // depends on device, no documentation
+ dirs.add("Android")
+ }
+ return dirs
+ }
+
+ // cf https://developer.android.com/about/versions/11/privacy/storage#directory-access
+ fun getRestrictedDirectories(context: Context): List<Map<String, String>> {
+ val dirs = ArrayList<Map<String, String>>()
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ val volumePaths = StorageUtils.getVolumePaths(context)
+ dirs.addAll(volumePaths.map {
+ hashMapOf(
+ "volumePath" to it,
+ "relativeDir" to "",
+ )
+ })
+ for (relativeDir in getRestrictedPrimaryDirectories()) {
+ dirs.addAll(volumePaths.map {
+ hashMapOf(
+ "volumePath" to it,
+ "relativeDir" to relativeDir,
+ )
+ })
+ }
+ }
+ return dirs
+ }
+
+ // As of Android 11, `MediaStore.getDocumentUri` fails if any of the persisted
+ // URI permissions we hold points to a folder that no longer exists,
+ // so we should remove these obsolete URIs before proceeding.
+ fun sanitizePersistedUriPermissions(context: Context) {
+ try {
+ for (uriPermission in context.contentResolver.persistedUriPermissions) {
+ val uri = uriPermission.uri
+ val path = StorageUtils.convertTreeDocumentUriToDirPath(context, uri)
+ if (path == null || !File(path).exists()) {
+ Log.d(LOG_TAG, "revoke URI permission for obsolete uri=$uri path=$path")
+ releaseUriPermission(context, uri)
+ }
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to sanitize persisted URI permissions", e)
+ }
+ }
+
+ private fun releaseUriPermission(context: Context, it: Uri) {
+ val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
+ context.contentResolver.releasePersistableUriPermission(it, flags)
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt
new file mode 100644
index 0000000..908d5a0
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/StorageUtils.kt
@@ -0,0 +1,788 @@
+package deckers.thibault.aves.utils
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.content.ContentResolver
+import android.content.ContentUris
+import android.content.Context
+import android.content.pm.PackageManager
+import android.media.MediaMetadataRetriever
+import android.net.Uri
+import android.os.Build
+import android.os.ParcelFileDescriptor
+import android.os.storage.StorageManager
+import android.provider.DocumentsContract
+import android.provider.MediaStore
+import android.text.TextUtils
+import android.util.Log
+import androidx.core.net.toUri
+import androidx.core.text.isDigitsOnly
+import com.commonsware.cwac.document.DocumentFileCompat
+import deckers.thibault.aves.model.provider.ImageProvider
+import deckers.thibault.aves.utils.FileUtils.transferFrom
+import deckers.thibault.aves.utils.MimeTypes.isImage
+import deckers.thibault.aves.utils.MimeTypes.isVideo
+import deckers.thibault.aves.utils.PermissionManager.getGrantedDirForPath
+import deckers.thibault.aves.utils.UriUtils.tryParseId
+import java.io.File
+import java.io.FileInputStream
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+import java.util.Locale
+import java.util.regex.Pattern
+
+object StorageUtils {
+ private val LOG_TAG = LogUtils.createTag<StorageUtils>()
+
+ private const val SCHEME_CONTENT = ContentResolver.SCHEME_CONTENT
+
+ // cf DocumentsContract.EXTERNAL_STORAGE_PROVIDER_AUTHORITY
+ private const val EXTERNAL_STORAGE_PROVIDER_AUTHORITY = "com.android.externalstorage.documents"
+
+ // cf DocumentsContract.EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID
+ private const val EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID = "primary"
+
+ private const val TREE_URI_ROOT = "$SCHEME_CONTENT://$EXTERNAL_STORAGE_PROVIDER_AUTHORITY/tree/"
+
+ private val MEDIA_STORE_VOLUME_EXTERNAL = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) MediaStore.VOLUME_EXTERNAL else "external"
+
+ // TODO TLAD get it from `MediaStore.Images.Media.EXTERNAL_CONTENT_URI`?
+ private val IMAGE_PATH_ROOT = "/$MEDIA_STORE_VOLUME_EXTERNAL/images/"
+
+ // TODO TLAD get it from `MediaStore.Video.Media.EXTERNAL_CONTENT_URI`?
+ private val VIDEO_PATH_ROOT = "/$MEDIA_STORE_VOLUME_EXTERNAL/video/"
+
+ private val UUID_PATTERN = Regex("[A-Fa-f\\d-]+")
+ private val TREE_URI_PATH_PATTERN = Pattern.compile("(.*?):(.*)")
+
+ const val TRASH_PATH_PLACEHOLDER = "#trash"
+
+ // whether the provided path is on one of this app specific directories:
+ // - /storage/{volume}/Android/data/{package_name}/files
+ // - /data/user/0/{package_name}/files
+ private fun isAppFile(context: Context, path: String): Boolean {
+ val dirs = listOf(
+ *context.getExternalFilesDirs(null).filterNotNull().toTypedArray(),
+ context.filesDir,
+ )
+ return dirs.any { path.startsWith(it.path) }
+ }
+
+ private fun appExternalFilesDirFor(context: Context, path: String): File? {
+ val dirs = context.getExternalFilesDirs(null).filterNotNull()
+ val volumePath = getVolumePath(context, path)
+ return volumePath?.let { dirs.firstOrNull { it.startsWith(volumePath) } } ?: dirs.firstOrNull()
+ }
+
+ fun trashDirFor(context: Context, path: String): File? {
+ val externalFilesDir = appExternalFilesDirFor(context, path)
+ if (externalFilesDir == null) {
+ Log.e(LOG_TAG, "failed to find external files dir for path=$path")
+ return null
+ }
+ val trashDir = File(externalFilesDir, "trash")
+ trashDir.mkdirs()
+ if (!trashDir.exists()) {
+ Log.e(LOG_TAG, "failed to create directories at path=$trashDir")
+ return null
+ }
+ return trashDir
+ }
+
+ fun getVaultRoot(context: Context) = ensureTrailingSeparator(File(context.filesDir, "vault").path)
+
+ fun isInVault(context: Context, path: String) = path.startsWith(getVaultRoot(context))
+
+ /**
+ * Volume paths
+ */
+
+ // volume paths, with trailing "/"
+ private var mStorageVolumePaths: Array<String>? = null
+
+ // primary volume path, with trailing "/"
+ private var mPrimaryVolumePath: String? = null
+
+ fun getPrimaryVolumePath(context: Context): String {
+ if (mPrimaryVolumePath == null) {
+ mPrimaryVolumePath = findPrimaryVolumePath(context)
+ }
+ return mPrimaryVolumePath!!
+ }
+
+ fun getVolumePaths(context: Context): Array<String> {
+ if (mStorageVolumePaths == null || mStorageVolumePaths!!.isEmpty()) {
+ mStorageVolumePaths = findVolumePaths(context)
+ }
+ return mStorageVolumePaths!!
+ }
+
+ fun getVolumePath(context: Context, anyPath: String): String? {
+ return getVolumePaths(context).firstOrNull { anyPath.startsWith(it) }
+ }
+
+ private fun getPathStepIterator(context: Context, anyPath: String, root: String?): Iterator<String?>? {
+ val rootLength = (root ?: getVolumePath(context, anyPath))?.length ?: return null
+
+ var fileName: String? = null
+ var relativePath: String? = null
+ val lastSeparatorIndex = anyPath.lastIndexOf(File.separator) + 1
+ if (lastSeparatorIndex > rootLength) {
+ fileName = anyPath.substring(lastSeparatorIndex)
+ relativePath = anyPath.substring(rootLength, lastSeparatorIndex)
+ }
+ relativePath ?: return null
+
+ val pathSteps = relativePath.split(File.separator).filter { it.isNotEmpty() }.toMutableList()
+ if (fileName?.isNotEmpty() == true) {
+ pathSteps.add(fileName)
+ }
+ return pathSteps.iterator()
+ }
+
+ private fun appSpecificVolumePath(file: File?): String? {
+ file ?: return null
+ val appSpecificPath = file.absolutePath
+ val relativePathStartIndex = appSpecificPath.indexOf("Android/data")
+ if (relativePathStartIndex < 0) return null
+ return appSpecificPath.substring(0, relativePathStartIndex)
+ }
+
+ private fun findPrimaryVolumePath(context: Context): String? {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager
+ val path = sm?.primaryStorageVolume?.directory?.path
+ if (path != null) {
+ return ensureTrailingSeparator(path)
+ }
+ }
+
+ // fallback
+ try {
+ // we want:
+ // /storage/emulated/0/
+ // `Environment.getExternalStorageDirectory()` (deprecated) yields:
+ // /storage/emulated/0
+ // `context.getExternalFilesDir(null)` yields:
+ // /storage/emulated/0/Android/data/{package_name}/files
+ return appSpecificVolumePath(context.getExternalFilesDir(null))
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to find primary volume path", e)
+ }
+ return null
+ }
+
+ private fun findVolumePaths(context: Context): Array<String> {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager
+ val paths = sm?.storageVolumes?.mapNotNull { it.directory?.path }
+ if (paths != null) {
+ return paths.map(::ensureTrailingSeparator).toTypedArray()
+ }
+ }
+
+ // fallback
+ val paths = HashSet<String>()
+ try {
+ // Primary emulated SD-CARD
+ val rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET") ?: ""
+ if (TextUtils.isEmpty(rawEmulatedStorageTarget)) {
+ // fix of empty raw emulated storage on marshmallow
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ lateinit var files: List<File>
+ var validFiles: Boolean
+ val retryInterval = 100L
+ val maxDelay = 1000L
+ var totalDelay = 0L
+ do {
+ // `getExternalFilesDirs` sometimes include `null` when called right after getting read access
+ // (e.g. on API 30 emulator) so we retry until the file system is ready.
+ // It can also include `null` when there is a faulty SD card.
+ val externalFilesDirs = context.getExternalFilesDirs(null)
+ validFiles = !externalFilesDirs.contains(null)
+ if (validFiles) {
+ files = externalFilesDirs.filterNotNull()
+ } else {
+ Log.d(LOG_TAG, "External files dirs contain `null`. Retrying...")
+ totalDelay += retryInterval
+ try {
+ Thread.sleep(retryInterval)
+ } catch (e: InterruptedException) {
+ Log.e(LOG_TAG, "insomnia", e)
+ }
+ }
+ } while (!validFiles && totalDelay < maxDelay)
+ paths.addAll(files.mapNotNull(::appSpecificVolumePath))
+ } else {
+ // Primary physical SD-CARD (not emulated)
+ val rawExternalStorage = System.getenv("EXTERNAL_STORAGE") ?: ""
+
+ // Device has physical external storage; use plain paths.
+ if (TextUtils.isEmpty(rawExternalStorage)) {
+ // EXTERNAL_STORAGE undefined; falling back to default.
+ paths.addAll(physicalPaths)
+ } else {
+ paths.add(rawExternalStorage)
+ }
+ }
+ } else {
+ // Device has emulated storage; external storage paths should have userId burned into them.
+ // /storage/emulated/[0,1,2,...]/
+ val path = getPrimaryVolumePath(context)
+ val rawUserId = path.split(File.separator).lastOrNull(String::isNotEmpty)?.takeIf { it.isDigitsOnly() } ?: ""
+ if (rawUserId.isEmpty()) {
+ paths.add(rawEmulatedStorageTarget)
+ } else {
+ paths.add(rawEmulatedStorageTarget + File.separator + rawUserId)
+ }
+ }
+
+ // All Secondary SD-CARDs (all exclude primary) separated by ":"
+ System.getenv("SECONDARY_STORAGE")?.let { secondaryStorages ->
+ paths.addAll(secondaryStorages.split(File.pathSeparator).filter { it.isNotEmpty() })
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to find volume paths", e)
+ }
+
+ return paths.map { ensureTrailingSeparator(it) }.toTypedArray()
+ }
+
+ // returns physicalPaths based on phone model
+ @SuppressLint("SdCardPath")
+ private val physicalPaths = arrayOf(
+ "/storage/sdcard0",
+ "/storage/sdcard1", //Motorola Xoom
+ "/storage/extsdcard", //Samsung SGS3
+ "/storage/sdcard0/external_sdcard", //User request
+ "/mnt/extsdcard",
+ "/mnt/sdcard/external_sd", //Samsung galaxy family
+ "/mnt/external_sd",
+ "/mnt/media_rw/sdcard1", //4.4.2 on CyanogenMod S3
+ "/removable/microsd", //Asus transformer prime
+ "/mnt/emmc",
+ "/storage/external_SD", //LG
+ "/storage/ext_sd", //HTC One Max
+ "/storage/removable/sdcard1", //Sony Xperia Z1
+ "/data/sdext",
+ "/data/sdext2",
+ "/data/sdext3",
+ "/data/sdext4",
+ "/sdcard1", //Sony Xperia Z
+ "/sdcard2", //HTC One M8s
+ "/storage/microsd" //ASUS ZenFone 2
+ )
+
+ /**
+ * Volume tree URIs
+ */
+
+ // e.g.
+ // /storage/emulated/0/ -> primary
+ // /storage/10F9-3F13/Pictures/ -> 10F9-3F13
+ // /storage/extSdCard/ -> 1234-5678 [Android 5.1.1, Samsung Galaxy Core Prime]
+ private fun getVolumeUuidForDocumentUri(context: Context, anyPath: String): String? {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager
+ sm?.getStorageVolume(File(anyPath))?.let { volume ->
+ if (volume.isPrimary) {
+ return EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID
+ }
+ volume.uuid?.let { uuid ->
+ return uuid.uppercase(Locale.ROOT)
+ }
+ }
+ }
+
+ // fallback for <N
+ getVolumePath(context, anyPath)?.let { volumePath ->
+ if (volumePath == getPrimaryVolumePath(context)) {
+ return EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID
+ }
+ volumePath.split(File.separator).lastOrNull { it.isNotEmpty() }?.let { uuid ->
+ if (uuid.matches(UUID_PATTERN)) {
+ return uuid.uppercase(Locale.ROOT)
+ }
+ }
+
+ // fallback when UUID does not appear in the SD card volume path
+ context.contentResolver.persistedUriPermissions.firstOrNull { uriPermission ->
+ convertTreeDocumentUriToDirPath(context, uriPermission.uri)?.let {
+ getVolumePath(context, it)?.let { grantedVolumePath ->
+ grantedVolumePath == volumePath
+ }
+ } ?: false
+ }?.let { uriPermission ->
+ splitTreeDocumentUri(uriPermission.uri)?.let { (uuid, _) ->
+ return uuid
+ }
+ }
+ }
+
+ Log.e(LOG_TAG, "failed to find volume UUID for anyPath=$anyPath")
+ return null
+ }
+
+ // e.g.
+ // primary -> /storage/emulated/0/
+ // 10F9-3F13 -> /storage/10F9-3F13/
+ // 1234-5678 -> /storage/extSdCard/ [Android 5.1.1, Samsung Galaxy Core Prime]
+ private fun getVolumePathFromTreeDocumentUriUuid(context: Context, uuid: String): String? {
+ if (uuid == EXTERNAL_STORAGE_PRIMARY_EMULATED_ROOT_ID) {
+ return getPrimaryVolumePath(context)
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ val sm = context.getSystemService(Context.STORAGE_SERVICE) as? StorageManager
+ if (sm != null) {
+ for (volumePath in getVolumePaths(context)) {
+ try {
+ val volume = sm.getStorageVolume(File(volumePath))
+ if (volume != null && uuid.equals(volume.uuid, ignoreCase = true)) {
+ return volumePath
+ }
+ } catch (_: Exception) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ // fallback for <N
+ for (volumePath in getVolumePaths(context)) {
+ val volumeUuid = volumePath.split(File.separator).lastOrNull { it.isNotEmpty() }
+ if (uuid.equals(volumeUuid, ignoreCase = true)) {
+ return volumePath
+ }
+ }
+
+ // fallback when UUID does not appear in the SD card volume path
+ val primaryVolumePath = getPrimaryVolumePath(context)
+ getVolumePaths(context).firstOrNull { volumePath ->
+ if (volumePath == primaryVolumePath) {
+ false
+ } else {
+ // exclude volumes that use regular naming scheme with UUID in them
+ // to prevent returning path with the UUID of a new volume
+ // when the argument is the UUID of an obsolete volume
+ val volumeUuid = volumePath.split(File.separator).lastOrNull { it.isNotEmpty() }
+ !(volumeUuid == null || volumeUuid.matches(UUID_PATTERN))
+ }
+ }?.let { return it }
+
+ Log.e(LOG_TAG, "failed to find volume path for UUID=$uuid")
+ return null
+ }
+
+ // e.g.
+ // /storage/emulated/0/ -> content://com.android.externalstorage.documents/tree/primary%3A
+ // /storage/10F9-3F13/Pictures/ -> content://com.android.externalstorage.documents/tree/10F9-3F13%3APictures
+ fun convertDirPathToTreeDocumentUri(context: Context, dirPath: String): Uri? {
+ val uuid = getVolumeUuidForDocumentUri(context, dirPath)
+ if (uuid != null) {
+ val relativeDir = removeTrailingSeparator(PathSegments(context, dirPath).relativeDir ?: "")
+ return DocumentsContract.buildTreeDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, "$uuid:$relativeDir")
+ }
+ Log.e(LOG_TAG, "failed to convert dirPath=$dirPath to tree document URI")
+ return null
+ }
+
+ // e.g.
+ // /storage/emulated/0/ -> content://com.android.externalstorage.documents/document/primary%3A
+ // /storage/10F9-3F13/Pictures/ -> content://com.android.externalstorage.documents/document/10F9-3F13%3APictures
+ fun convertDirPathToDocumentUri(context: Context, dirPath: String): Uri? {
+ val uuid = getVolumeUuidForDocumentUri(context, dirPath)
+ if (uuid != null) {
+ val relativeDir = removeTrailingSeparator(PathSegments(context, dirPath).relativeDir ?: "")
+ return DocumentsContract.buildDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, "$uuid:$relativeDir")
+ }
+ Log.e(LOG_TAG, "failed to convert dirPath=$dirPath to document URI")
+ return null
+ }
+
+ // e.g.
+ // content://com.android.externalstorage.documents/tree/primary%3A -> ("primary", "")
+ // content://com.android.externalstorage.documents/tree/10F9-3F13%3APictures -> ("10F9-3F13", "Pictures")
+ private fun splitTreeDocumentUri(treeDocumentUri: Uri): Pair<String, String>? {
+ val treeDocumentUriString = treeDocumentUri.toString()
+ if (treeDocumentUriString.length <= TREE_URI_ROOT.length) return null
+ val encoded = treeDocumentUriString.substring(TREE_URI_ROOT.length)
+ val matcher = TREE_URI_PATH_PATTERN.matcher(Uri.decode(encoded))
+ with(matcher) {
+ if (find()) {
+ val uuid = group(1)
+ val relativePath = group(2)
+ if (uuid != null && relativePath != null) {
+ return Pair(uuid, relativePath)
+ }
+ }
+ }
+ Log.e(LOG_TAG, "failed to split treeDocumentUri=$treeDocumentUri to UUID and relative path")
+ return null
+ }
+
+ // e.g.
+ // content://com.android.externalstorage.documents/tree/primary%3A -> /storage/emulated/0/
+ // content://com.android.externalstorage.documents/tree/10F9-3F13%3APictures -> /storage/10F9-3F13/Pictures/
+ fun convertTreeDocumentUriToDirPath(context: Context, treeDocumentUri: Uri): String? {
+ splitTreeDocumentUri(treeDocumentUri)?.let { (uuid, relativePath) ->
+ val volumePath = getVolumePathFromTreeDocumentUriUuid(context, uuid)
+ if (volumePath != null) {
+ return ensureTrailingSeparator(volumePath + relativePath)
+ }
+ }
+ Log.e(LOG_TAG, "failed to convert treeDocumentUri=$treeDocumentUri to path")
+ return null
+ }
+
+ /**
+ * Document files
+ */
+
+ fun getDocumentFile(context: Context, anyPath: String, mediaUri: Uri): DocumentFileCompat? {
+ try {
+ if (requireAccessPermission(context, anyPath)) {
+ // need a document URI (not a media content URI) to open a `DocumentFile` output stream
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && isMediaStoreContentUri(mediaUri)) {
+ // cleanest API to get it
+ PermissionManager.sanitizePersistedUriPermissions(context)
+ try {
+ val docUri = MediaStore.getDocumentUri(context, mediaUri)
+ if (docUri != null) {
+ return DocumentFileCompat.fromSingleUri(context, docUri)
+ }
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to get document URI for mediaUri=$mediaUri", e)
+ }
+ }
+
+ // fallback for older APIs
+ val df = getVolumePath(context, anyPath)?.let { convertDirPathToTreeDocumentUri(context, it) }?.let { getDocumentFileFromVolumeTree(context, it, anyPath) }
+ if (df != null) return df
+
+ // try to strip user info, if any
+ if (mediaUri.userInfo != null) {
+ val genericMediaUri = stripMediaUriUserInfo(mediaUri)
+ Log.d(LOG_TAG, "retry getDocumentFile for mediaUri=$mediaUri without userInfo: $genericMediaUri")
+ return getDocumentFile(context, anyPath, genericMediaUri)
+ }
+ }
+ // good old `File`
+ return DocumentFileCompat.fromFile(File(anyPath))
+ } catch (e: SecurityException) {
+ Log.w(LOG_TAG, "failed to get document file from mediaUri=$mediaUri", e)
+ }
+ return null
+ }
+
+ // returns the directory `DocumentFile` (from tree URI when scoped storage is required, `File` otherwise)
+ // returns null if directory does not exist and could not be created
+ fun createDirectoryDocIfAbsent(context: Context, dirPath: String): DocumentFileCompat? {
+ try {
+ val targetDirPath = ensureTrailingSeparator(dirPath)
+ return if (requireAccessPermission(context, targetDirPath)) {
+ val grantedDir = getGrantedDirForPath(context, targetDirPath) ?: return null
+ val rootTreeDocumentUri = convertDirPathToTreeDocumentUri(context, grantedDir) ?: return null
+ var parentFile: DocumentFileCompat? = DocumentFileCompat.fromTreeUri(context, rootTreeDocumentUri) ?: return null
+ val pathIterator = getPathStepIterator(context, targetDirPath, grantedDir)
+ var currentDirPath = ensureTrailingSeparator(grantedDir)
+ while (pathIterator?.hasNext() == true) {
+ val dirName = pathIterator.next()
+ var treeDocFile = findDocumentFileIgnoreCase(parentFile, dirName)
+ currentDirPath = ensureTrailingSeparator(currentDirPath + dirName)
+
+ if (treeDocFile == null && File(currentDirPath).exists()) {
+ // `DocumentsProvider` may be temporarily buggy and fail to list children directories.
+ // Better to fail fast and revoke directory access, so that the user is aware
+ // of the issue when trying again with `ACTION_OPEN_DOCUMENT_TREE`.
+ // Otherwise, we would try to recreate the existing (but unlisted) directory,
+ // and the document provider will create a new one with a "(1)" suffix.
+ Log.e(LOG_TAG, "failed to get document file for existing path=$currentDirPath from granted dir=$grantedDir. Revoking granted dir...")
+ PermissionManager.revokeDirectoryAccess(context, grantedDir)
+ throw Exception("failed to get document file for existing path=$currentDirPath from grantedDir=$grantedDir")
+ }
+
+ if (treeDocFile == null || !treeDocFile.exists()) {
+ treeDocFile = parentFile?.createDirectory(dirName)
+ if (treeDocFile == null) {
+ Log.e(LOG_TAG, "failed to create directory with name=$dirName from parent=$parentFile")
+ return null
+ }
+ }
+ parentFile = treeDocFile
+ }
+ parentFile
+ } else {
+ val directory = File(targetDirPath)
+ directory.mkdirs()
+ if (!directory.exists()) {
+ Log.e(LOG_TAG, "failed to create directories at path=$targetDirPath")
+ return null
+ }
+ DocumentFileCompat.fromFile(directory)
+ }
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to create directory at path=$dirPath", e)
+ return null
+ }
+ }
+
+ private fun getDocumentFileFromVolumeTree(context: Context, rootTreeDocumentUri: Uri, anyPath: String): DocumentFileCompat? {
+ var documentFile: DocumentFileCompat? = DocumentFileCompat.fromTreeUri(context, rootTreeDocumentUri) ?: return null
+
+ // follow the entry path down the document tree
+ val pathIterator = getPathStepIterator(context, anyPath, null)
+ while (pathIterator?.hasNext() == true) {
+ documentFile = findDocumentFileIgnoreCase(documentFile, pathIterator.next()) ?: return null
+ }
+ return documentFile
+ }
+
+ // variation on `DocumentFileCompat.findFile()` to allow case insensitive search
+ private fun findDocumentFileIgnoreCase(documentFile: DocumentFileCompat?, displayName: String?): DocumentFileCompat? {
+ documentFile ?: return null
+ for (doc in documentFile.listFiles()) {
+ if (displayName.equals(doc.name, ignoreCase = true)) {
+ return doc
+ }
+ }
+ return null
+ }
+
+ /**
+ * Misc
+ */
+
+ fun canEditByFile(context: Context, path: String) = !requireAccessPermission(context, path)
+
+ fun requireAccessPermission(context: Context, anyPath: String): Boolean {
+ if (isAppFile(context, anyPath)) return false
+
+ // on Android 11, we should always require access permission, even on primary volume
+ if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) return true
+
+ val onPrimaryVolume = anyPath.startsWith(getPrimaryVolumePath(context))
+ return !onPrimaryVolume
+ }
+
+ fun isMediaStoreContentUri(uri: Uri?): Boolean {
+ uri ?: return false
+ // a URI's authority is [userinfo@]host[:port]
+ // but we only want the host when comparing to Media Store's "authority"
+ return SCHEME_CONTENT.equals(uri.scheme, ignoreCase = true) && MediaStore.AUTHORITY.equals(uri.host, ignoreCase = true)
+ }
+
+ fun getOriginalUri(context: Context, uri: Uri): Uri {
+ // we get a permission denial if we require original from a provider other than the media store
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && isMediaStoreContentUri(uri)) {
+ val path = uri.path
+ path ?: return uri
+ // from Android 11 (API 30), accessing the original URI for a `file` or `downloads` media content yields a `SecurityException`
+ if (path.startsWith(IMAGE_PATH_ROOT) || path.startsWith(VIDEO_PATH_ROOT)) {
+ // "Caller must hold ACCESS_MEDIA_LOCATION permission to access original"
+ if (context.checkSelfPermission(Manifest.permission.ACCESS_MEDIA_LOCATION) == PackageManager.PERMISSION_GRANTED) {
+ return MediaStore.setRequireOriginal(uri)
+ }
+ }
+ }
+ return uri
+ }
+
+ // As of Glide v4.12.0, a special loader `QMediaStoreUriLoader` is automatically used
+ // to work around a bug from Android 10 (API 29) where metadata redaction corrupts HEIC images.
+ // This loader relies on `MediaStore.setRequireOriginal` but this yields a `SecurityException`
+ // for some non image/video content URIs (e.g. `downloads`, `file`)
+ fun getGlideSafeUri(context: Context, uri: Uri, mimeType: String, sizeBytes: Long? = null): Uri {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && isMediaStoreContentUri(uri)) {
+ val uriPath = uri.path
+ when {
+ uriPath?.contains("/downloads/") == true -> {
+ // e.g. `content://media/external_primary/downloads/...`
+ getMediaUriImageVideoUri(uri, mimeType)?.let { imageVideoUri -> return imageVideoUri }
+ }
+
+ uriPath?.contains("/file/") == true -> {
+ // e.g. `content://media/external/file/...`
+ // create an ad-hoc temporary file for decoding only
+ createTempFile(context).apply {
+ try {
+ transferFrom(openInputStream(context, uri), sizeBytes)
+ return Uri.fromFile(this)
+ } catch (e: Exception) {
+ Log.e(LOG_TAG, "failed to create temporary file from uri=$uri", e)
+ }
+ }
+ }
+
+ uri.userInfo != null -> return stripMediaUriUserInfo(uri)
+ }
+ }
+ return uri
+ }
+
+ // requesting access or writing to some MediaStore content URIs
+ // yields an exception with `All requested items must be referenced by specific ID`
+ fun getMediaStoreScopedStorageSafeUri(uri: Uri, mimeType: String): Uri {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && isMediaStoreContentUri(uri)) {
+ val uriPath = uri.path
+ when {
+ uriPath?.contains("/downloads/") == true -> {
+ // e.g. `content://media/external_primary/downloads/...`
+ getMediaUriImageVideoUri(uri, mimeType)?.let { imageVideoUri -> return imageVideoUri }
+ }
+
+ uri.userInfo != null -> return stripMediaUriUserInfo(uri)
+ }
+ }
+ return uri
+ }
+
+ // Build a typical `images` or `video` content URI from the original content ID.
+ // We cannot safely apply this to a `file` content URI, as it may point to a file not indexed
+ // by the Media Store (via `.nomedia`), and therefore has no matching image/video content URI.
+ private fun getMediaUriImageVideoUri(uri: Uri, mimeType: String): Uri? {
+ return uri.tryParseId()?.let { id ->
+ return when {
+ isImage(mimeType) -> ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
+ isVideo(mimeType) -> ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
+ else -> uri
+ }
+ }
+ }
+
+ // strip user info, if any
+ // e.g. `content://0@media/...`
+ private fun stripMediaUriUserInfo(uri: Uri) = uri.toString().replaceFirst("${uri.userInfo}@", "").toUri()
+
+ fun openInputStream(context: Context, uri: Uri): InputStream? {
+ val effectiveUri = getOriginalUri(context, uri)
+ return try {
+ return when (uri.scheme) {
+ ContentResolver.SCHEME_FILE -> FileInputStream(uri.path)
+ else -> context.contentResolver.openInputStream(effectiveUri)
+ }
+ } catch (e: Exception) {
+ // among various other exceptions,
+ // opening a file marked pending and owned by another package throws an `IllegalStateException`
+ Log.w(LOG_TAG, "failed to open input stream from effectiveUri=$effectiveUri for uri=$uri", e)
+ null
+ }
+ }
+
+ fun openOutputStream(context: Context, mimeType: String, uri: Uri, mode: String): OutputStream? {
+ val effectiveUri = getMediaStoreScopedStorageSafeUri(uri, mimeType)
+ return try {
+ context.contentResolver.openOutputStream(effectiveUri, mode)
+ } catch (e: Exception) {
+ // among various other exceptions,
+ // opening a file marked pending and owned by another package throws an `IllegalStateException`
+ Log.w(LOG_TAG, "failed to open output stream from effectiveUri=$effectiveUri for uri=$uri mode=$mode", e)
+ null
+ }
+ }
+
+ fun openInputFileDescriptor(context: Context, uri: Uri): ParcelFileDescriptor? {
+ val effectiveUri = getOriginalUri(context, uri)
+ return try {
+ context.contentResolver.openFileDescriptor(effectiveUri, "r")
+ } catch (e: Exception) {
+ // among various other exceptions,
+ // opening a file marked pending and owned by another package throws an `IllegalStateException`
+ Log.w(LOG_TAG, "failed to open input file descriptor from effectiveUri=$effectiveUri for uri=$uri", e)
+ null
+ }
+ }
+
+ fun openOutputFileDescriptor(context: Context, mimeType: String, uri: Uri, path: String, mode: String): ParcelFileDescriptor? {
+ val effectiveUri = if (ImageProvider.isMediaUriPermissionGranted(context, uri, mimeType)) {
+ getMediaStoreScopedStorageSafeUri(uri, mimeType)
+ } else {
+ getDocumentFile(context, path, uri)?.uri ?: throw Exception("failed to get document file for path=$path, uri=$uri")
+ }
+ return try {
+ context.contentResolver.openFileDescriptor(effectiveUri, mode)
+ } catch (e: Exception) {
+ // among various other exceptions,
+ // opening a file marked pending and owned by another package throws an `IllegalStateException`
+ Log.w(LOG_TAG, "failed to open output file descriptor from effectiveUri=$effectiveUri for uri=$uri path=$path", e)
+ null
+ }
+ }
+
+ fun openMetadataRetriever(context: Context, uri: Uri): MediaMetadataRetriever? {
+ val effectiveUri = getOriginalUri(context, uri)
+ return try {
+ MediaMetadataRetriever().apply {
+ // on Android 12 preview, setting the data source works but yields an internal IOException
+ // (`Input file descriptor already original`), whether we provide the original URI or not
+ setDataSource(context, effectiveUri)
+ }
+ } catch (_: Exception) {
+ // unsupported format
+ Log.w(LOG_TAG, "failed to initialize MediaMetadataRetriever for uri=$uri effectiveUri=$effectiveUri")
+ null
+ }
+ }
+
+ private fun getTempDirectory(context: Context): File = File(context.cacheDir, "temp")
+
+ fun createTempFile(context: Context, extension: String? = null): File {
+ val directory = getTempDirectory(context)
+ directory.mkdirs()
+ if (!directory.exists()) {
+ throw IOException("failed to create directories at path=$directory")
+ }
+ val tempFile = File.createTempFile("aves", extension, directory)
+ // `deleteOnExit` is unreliable, but it does not hurt
+ tempFile.deleteOnExit()
+ return tempFile
+ }
+
+ fun deleteTempDirectory(context: Context): Boolean {
+ val directory = getTempDirectory(context)
+ if (!directory.exists()) return false
+ return directory.deleteRecursively()
+ }
+
+ // convenience methods
+
+ fun getFolderSize(f: File): Long {
+ var size: Long = 0
+ if (f.isDirectory) {
+ for (file in f.listFiles()!!) {
+ size += getFolderSize(file)
+ }
+ } else {
+ size = f.length()
+ }
+ return size
+ }
+
+ fun ensureTrailingSeparator(dirPath: String): String {
+ return if (dirPath.endsWith(File.separator)) dirPath else dirPath + File.separator
+ }
+
+ fun removeTrailingSeparator(dirPath: String): String {
+ return if (dirPath.endsWith(File.separator)) dirPath.substring(0, dirPath.length - 1) else dirPath
+ }
+
+ // `fullPath` should match "volumePath + relativeDir + fileName"
+ class PathSegments(context: Context, fullPath: String) {
+ var volumePath: String? = null // `volumePath` with trailing "/"
+ var relativeDir: String? = null // `relativeDir` with trailing "/"
+ private var fileName: String? = null // null for directories
+
+ init {
+ volumePath = getVolumePath(context, fullPath)
+ if (volumePath != null) {
+ val lastSeparatorIndex = fullPath.lastIndexOf(File.separator) + 1
+ val volumePathLength = volumePath!!.length
+ if (lastSeparatorIndex > volumePathLength) {
+ fileName = fullPath.substring(lastSeparatorIndex)
+ relativeDir = fullPath.substring(volumePathLength, lastSeparatorIndex)
+ }
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/kotlin/deckers/thibault/aves/utils/UriUtils.kt b/android/app/src/main/kotlin/deckers/thibault/aves/utils/UriUtils.kt
new file mode 100644
index 0000000..9e10927
--- /dev/null
+++ b/android/app/src/main/kotlin/deckers/thibault/aves/utils/UriUtils.kt
@@ -0,0 +1,18 @@
+package deckers.thibault.aves.utils
+
+import android.content.ContentUris
+import android.net.Uri
+import android.util.Log
+
+object UriUtils {
+ private val LOG_TAG = LogUtils.createTag<UriUtils>()
+
+ fun Uri.tryParseId(): Long? {
+ try {
+ return ContentUris.parseId(this)
+ } catch (e: Exception) {
+ Log.w(LOG_TAG, "failed to parse ID from contentUri=$this")
+ }
+ return null
+ }
+} \ No newline at end of file
diff --git a/android/app/src/main/res/drawable-nodpi/banner.png b/android/app/src/main/res/drawable-nodpi/banner.png
new file mode 100644
index 0000000..ac4ec59
--- /dev/null
+++ b/android/app/src/main/res/drawable-nodpi/banner.png
Binary files differ
diff --git a/android/app/src/main/res/drawable-v26/ic_shortcut_collection_foreground.xml b/android/app/src/main/res/drawable-v26/ic_shortcut_collection_foreground.xml
new file mode 100644
index 0000000..13e0900
--- /dev/null
+++ b/android/app/src/main/res/drawable-v26/ic_shortcut_collection_foreground.xml
@@ -0,0 +1,16 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp"
+ android:height="108dp"
+ android:tint="@color/ic_shortcut_foreground"
+ android:viewportWidth="108"
+ android:viewportHeight="108">
+ <group
+ android:scaleX="1.7226"
+ android:scaleY="1.7226"
+ android:translateX="33.3288"
+ android:translateY="33.3288">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M20,4v12L8,16L8,4h12m0,-2L8,2c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM11.5,11.67l1.69,2.26 2.48,-3.1L19,15L9,15zM2,6v14c0,1.1 0.9,2 2,2h14v-2L4,20L4,6L2,6z" />
+ </group>
+</vector>
diff --git a/android/app/src/main/res/drawable-v26/ic_shortcut_movie_foreground.xml b/android/app/src/main/res/drawable-v26/ic_shortcut_movie_foreground.xml
new file mode 100644
index 0000000..84db2f5
--- /dev/null
+++ b/android/app/src/main/res/drawable-v26/ic_shortcut_movie_foreground.xml
@@ -0,0 +1,16 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp"
+ android:height="108dp"
+ android:tint="@color/ic_shortcut_foreground"
+ android:viewportWidth="108"
+ android:viewportHeight="108">
+ <group
+ android:scaleX="1.7226"
+ android:scaleY="1.7226"
+ android:translateX="33.3288"
+ android:translateY="33.3288">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M4,6.47L5.76,10H20v8H4V6.47M22,4h-4l2,4h-3l-2,-4h-2l2,4h-3l-2,-4H8l2,4H7L5,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V4z" />
+ </group>
+</vector>
diff --git a/android/app/src/main/res/drawable-v26/ic_shortcut_search_foreground.xml b/android/app/src/main/res/drawable-v26/ic_shortcut_search_foreground.xml
new file mode 100644
index 0000000..13f7071
--- /dev/null
+++ b/android/app/src/main/res/drawable-v26/ic_shortcut_search_foreground.xml
@@ -0,0 +1,16 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp"
+ android:height="108dp"
+ android:tint="@color/ic_shortcut_foreground"
+ android:viewportWidth="108"
+ android:viewportHeight="108">
+ <group
+ android:scaleX="1.7226"
+ android:scaleY="1.7226"
+ android:translateX="33.3288"
+ android:translateY="33.3288">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zM9.5,14C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z" />
+ </group>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml
new file mode 100644
index 0000000..4155b35
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,38 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="100dp"
+ android:height="100dp"
+ android:viewportWidth="100"
+ android:viewportHeight="100">
+ <path
+ android:fillColor="#ef435a"
+ android:fillType="evenOdd"
+ android:pathData="m41.03,57.12 l8.31,8.31a1.47,1.47 0,0 1,0 2.08l-3.97,3.97a7.6,7.6 0,0 1,-10.75 0l-3.97,-3.97a1.47,1.47 0,0 1,0 -2.08l8.31,-8.31a1.47,1.47 0,0 1,2.08 0z"
+ android:strokeWidth="1.53903"
+ android:strokeColor="#000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+ <path
+ android:fillColor="#e0e0e0"
+ android:fillType="evenOdd"
+ android:pathData="m53.43,44.71 l8.31,8.31a1.46,1.46 0,0 1,-0 2.08l-8.31,8.31a1.46,1.46 0,0 1,-2.08 0l-8.31,-8.31a1.46,1.46 0,0 1,0 -2.08l8.31,-8.31a1.46,1.46 0,0 1,2.08 0z"
+ android:strokeWidth="1.53902"
+ android:strokeColor="#000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+ <path
+ android:fillColor="#ffc11f"
+ android:fillType="evenOdd"
+ android:pathData="m55.45,40.62a1.47,1.47 0,0 0,0 2.08l8.31,8.31a1.47,1.47 0,0 0,2.08 0l8.31,-8.31a1.47,1.47 0,0 0,0 -2.08l-4.12,-4.12a7.39,7.39 0,0 0,-10.44 0zM63.65,40.51a1.62,1.62 0,0 1,2.29 0,1.62 1.62,0 0,1 0,2.29 1.62,1.62 0,0 1,-2.29 0,1.62 1.62,0 0,1 0,-2.29z"
+ android:strokeWidth="1.53902"
+ android:strokeColor="#000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+ <path
+ android:fillColor="@color/ic_launcher_flavour"
+ android:fillType="evenOdd"
+ android:pathData="m37.26,28.54 l12.13,12.13a1.47,1.47 0,0 1,0 2.08l-8.31,8.31a1.47,1.47 0,0 1,-2.08 0l-5.39,-5.39a11.47,11.47 0,0 1,0 -16.22l0.9,-0.9a1.94,1.94 0,0 1,2.74 0z"
+ android:strokeWidth="1.53903"
+ android:strokeColor="#000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_launcher_mono.xml b/android/app/src/main/res/drawable/ic_launcher_mono.xml
new file mode 100644
index 0000000..9f78191
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_launcher_mono.xml
@@ -0,0 +1,38 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="100dp"
+ android:height="100dp"
+ android:viewportWidth="100"
+ android:viewportHeight="100">
+ <path
+ android:fillColor="#000000"
+ android:fillType="evenOdd"
+ android:pathData="m41.03,57.12 l8.31,8.31a1.47,1.47 0,0 1,0 2.08l-3.97,3.97a7.6,7.6 0,0 1,-10.75 0l-3.97,-3.97a1.47,1.47 0,0 1,0 -2.08l8.3,-8.3a1.47,1.47 0,0 1,2.08 0z"
+ android:strokeWidth="1.53871"
+ android:strokeColor="#00000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+ <path
+ android:fillColor="#000000"
+ android:fillType="evenOdd"
+ android:pathData="m53.43,44.72 l8.31,8.31a1.46,1.46 0,0 1,-0 2.08l-8.31,8.31a1.46,1.46 0,0 1,-2.08 0l-8.31,-8.31a1.46,1.46 0,0 1,0 -2.08L51.35,44.72a1.46,1.46 0,0 1,2.08 0z"
+ android:strokeWidth="1.5387"
+ android:strokeColor="#00000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+ <path
+ android:fillColor="#000000"
+ android:fillType="evenOdd"
+ android:pathData="m55.45,40.62a1.47,1.47 0,0 0,0 2.08l8.31,8.3a1.47,1.47 0,0 0,2.08 0l8.3,-8.3a1.47,1.47 0,0 0,0 -2.08l-4.12,-4.12a7.38,7.38 0,0 0,-10.44 0zM63.65,40.51a1.62,1.62 0,0 1,2.29 0,1.62 1.62,0 0,1 0,2.29 1.62,1.62 0,0 1,-2.29 0,1.62 1.62,0 0,1 0,-2.29z"
+ android:strokeWidth="1.5387"
+ android:strokeColor="#00000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+ <path
+ android:fillColor="#000000"
+ android:fillType="evenOdd"
+ android:pathData="m37.26,28.54 l12.13,12.13a1.47,1.47 0,0 1,0 2.08l-8.31,8.3a1.47,1.47 0,0 1,-2.08 0L33.62,45.67a11.47,11.47 0,0 1,0 -16.22l0.9,-0.9a1.94,1.94 0,0 1,2.74 0z"
+ android:strokeWidth="1.53871"
+ android:strokeColor="#00000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_notification.xml b/android/app/src/main/res/drawable/ic_notification.xml
new file mode 100644
index 0000000..480be0b
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_notification.xml
@@ -0,0 +1,38 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="100dp"
+ android:height="100dp"
+ android:viewportWidth="100"
+ android:viewportHeight="100">
+ <path
+ android:fillColor="#000000"
+ android:fillType="evenOdd"
+ android:pathData="m31.78,63.61 l16.47,16.47a2.91,2.91 0,0 1,0 4.12l-7.87,7.87a15.07,15.07 0,0 1,-21.31 0L11.2,84.2a2.91,2.91 0,0 1,0 -4.12l16.47,-16.47a2.91,2.91 0,0 1,4.12 0z"
+ android:strokeWidth="3.05097"
+ android:strokeColor="#00000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+ <path
+ android:fillColor="#000000"
+ android:fillType="evenOdd"
+ android:pathData="M56.37,39.03L72.84,55.49A2.91,2.91 90,0 1,72.84 59.61L56.37,76.08A2.91,2.91 0,0 1,52.25 76.08L35.78,59.61A2.91,2.91 0,0 1,35.78 55.49L52.25,39.03A2.91,2.91 90,0 1,56.37 39.03z"
+ android:strokeWidth="3.05095"
+ android:strokeColor="#00000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+ <path
+ android:fillColor="#000000"
+ android:fillType="evenOdd"
+ android:pathData="m60.37,30.91a2.91,2.91 0,0 0,0 4.12l16.47,16.47a2.91,2.91 0,0 0,4.12 0l16.47,-16.47a2.91,2.91 0,0 0,0 -4.12l-8.17,-8.17a14.64,14.64 0,0 0,-20.7 0zM76.62,30.7a3.21,3.21 0,0 1,4.54 0,3.21 3.21,0 0,1 0,4.54 3.21,3.21 0,0 1,-4.54 0,3.21 3.21,0 0,1 0,-4.54z"
+ android:strokeWidth="3.05095"
+ android:strokeColor="#00000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+ <path
+ android:fillColor="#000000"
+ android:fillType="evenOdd"
+ android:pathData="m24.31,6.96 l24.04,24.04a2.91,2.91 0,0 1,0 4.12L31.88,51.59a2.91,2.91 0,0 1,-4.12 0L17.08,40.91a22.74,22.74 0,0 1,0 -32.16L18.87,6.96a3.84,3.84 0,0 1,5.43 0z"
+ android:strokeWidth="3.05097"
+ android:strokeColor="#00000000"
+ android:strokeLineCap="round"
+ android:strokeLineJoin="round" />
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_outline_stop_24.xml b/android/app/src/main/res/drawable/ic_outline_stop_24.xml
new file mode 100644
index 0000000..0214f12
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_outline_stop_24.xml
@@ -0,0 +1,9 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="24"
+ android:viewportHeight="24">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M16,8v8H8V8h8m2,-2H6v12h12V6z"/>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_shortcut_collection.xml b/android/app/src/main/res/drawable/ic_shortcut_collection.xml
new file mode 100644
index 0000000..f20e57d
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_shortcut_collection.xml
@@ -0,0 +1,16 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="48dp"
+ android:height="48dp"
+ android:viewportWidth="48"
+ android:viewportHeight="48">
+ <path
+ android:fillColor="@color/ic_shortcut_background"
+ android:pathData="M0,24 A1,1 0 1,1 48,24 A1,1 0 1,1 0,24" />
+ <group
+ android:translateX="12"
+ android:translateY="12">
+ <path
+ android:fillColor="@color/ic_shortcut_foreground"
+ android:pathData="M20,4v12L8,16L8,4h12m0,-2L8,2c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2L22,4c0,-1.1 -0.9,-2 -2,-2zM11.5,11.67l1.69,2.26 2.48,-3.1L19,15L9,15zM2,6v14c0,1.1 0.9,2 2,2h14v-2L4,20L4,6L2,6z" />
+ </group>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_shortcut_map.xml b/android/app/src/main/res/drawable/ic_shortcut_map.xml
new file mode 100644
index 0000000..7dc10d1
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_shortcut_map.xml
@@ -0,0 +1,16 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="48dp"
+ android:height="48dp"
+ android:viewportWidth="48"
+ android:viewportHeight="48">
+ <path
+ android:fillColor="@color/ic_shortcut_background"
+ android:pathData="M0,24 A1,1 0 1,1 48,24 A1,1 0 1,1 0,24" />
+ <group
+ android:translateX="12"
+ android:translateY="12">
+ <path
+ android:fillColor="@color/ic_shortcut_foreground"
+ android:pathData="M20.5,3l-0.16,0.03L15,5.1 9,3 3.36,4.9c-0.21,0.07 -0.36,0.25 -0.36,0.48L3,20.5c0,0.28 0.22,0.5 0.5,0.5l0.16,-0.03L9,18.9l6,2.1 5.64,-1.9c0.21,-0.07 0.36,-0.25 0.36,-0.48L21,3.5c0,-0.28 -0.22,-0.5 -0.5,-0.5zM10,5.47l4,1.4v11.66l-4,-1.4L10,5.47zM5,6.46l3,-1.01v11.7l-3,1.16L5,6.46zM19,17.54l-3,1.01L16,6.86l3,-1.16v11.84z" />
+ </group>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_shortcut_map_foreground.xml b/android/app/src/main/res/drawable/ic_shortcut_map_foreground.xml
new file mode 100644
index 0000000..d450c31
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_shortcut_map_foreground.xml
@@ -0,0 +1,16 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="108dp"
+ android:height="108dp"
+ android:tint="@color/ic_shortcut_foreground"
+ android:viewportWidth="108"
+ android:viewportHeight="108">
+ <group
+ android:scaleX="1.7226"
+ android:scaleY="1.7226"
+ android:translateX="33.3288"
+ android:translateY="33.3288">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M20.5,3l-0.16,0.03L15,5.1 9,3 3.36,4.9c-0.21,0.07 -0.36,0.25 -0.36,0.48L3,20.5c0,0.28 0.22,0.5 0.5,0.5l0.16,-0.03L9,18.9l6,2.1 5.64,-1.9c0.21,-0.07 0.36,-0.25 0.36,-0.48L21,3.5c0,-0.28 -0.22,-0.5 -0.5,-0.5zM10,5.47l4,1.4v11.66l-4,-1.4L10,5.47zM5,6.46l3,-1.01v11.7l-3,1.16L5,6.46zM19,17.54l-3,1.01L16,6.86l3,-1.16v11.84z" />
+ </group>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_shortcut_movie.xml b/android/app/src/main/res/drawable/ic_shortcut_movie.xml
new file mode 100644
index 0000000..c69c379
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_shortcut_movie.xml
@@ -0,0 +1,16 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="48dp"
+ android:height="48dp"
+ android:viewportWidth="48"
+ android:viewportHeight="48">
+ <path
+ android:fillColor="@color/ic_shortcut_background"
+ android:pathData="M0,24 A1,1 0 1,1 48,24 A1,1 0 1,1 0,24" />
+ <group
+ android:translateX="12"
+ android:translateY="12">
+ <path
+ android:fillColor="@color/ic_shortcut_foreground"
+ android:pathData="M4,6.47L5.76,10H20v8H4V6.47M22,4h-4l2,4h-3l-2,-4h-2l2,4h-3l-2,-4H8l2,4H7L5,4H4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2V4z" />
+ </group>
+</vector>
diff --git a/android/app/src/main/res/drawable/ic_shortcut_search.xml b/android/app/src/main/res/drawable/ic_shortcut_search.xml
new file mode 100644
index 0000000..f28c549
--- /dev/null
+++ b/android/app/src/main/res/drawable/ic_shortcut_search.xml
@@ -0,0 +1,16 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="48dp"
+ android:height="48dp"
+ android:viewportWidth="48"
+ android:viewportHeight="48">
+ <path
+ android:fillColor="@color/ic_shortcut_background"
+ android:pathData="M0,24 A1,1 0 1,1 48,24 A1,1 0 1,1 0,24" />
+ <group
+ android:translateX="12"
+ android:translateY="12">
+ <path
+ android:fillColor="@color/ic_shortcut_foreground"
+ android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zM9.5,14C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z" />
+ </group>
+</vector>
diff --git a/android/app/src/main/res/layout/app_widget.xml b/android/app/src/main/res/layout/app_widget.xml
new file mode 100644
index 0000000..b4a2c16
--- /dev/null
+++ b/android/app/src/main/res/layout/app_widget.xml
@@ -0,0 +1,5 @@
+<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/widget_img"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:scaleType="fitCenter" />
diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..fe5fad3
--- /dev/null
+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_launcher_background"/>
+ <foreground android:drawable="@drawable/ic_launcher_foreground"/>
+ <monochrome android:drawable="@drawable/ic_launcher_mono" />
+</adaptive-icon> \ No newline at end of file
diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
new file mode 100644
index 0000000..fe5fad3
--- /dev/null
+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_launcher_background"/>
+ <foreground android:drawable="@drawable/ic_launcher_foreground"/>
+ <monochrome android:drawable="@drawable/ic_launcher_mono" />
+</adaptive-icon> \ No newline at end of file
diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_collection.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_collection.xml
new file mode 100644
index 0000000..8ec076f
--- /dev/null
+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_collection.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_shortcut_background" />
+ <foreground android:drawable="@drawable/ic_shortcut_collection_foreground" />
+</adaptive-icon> \ No newline at end of file
diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_map.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_map.xml
new file mode 100644
index 0000000..2857b49
--- /dev/null
+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_map.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_shortcut_background" />
+ <foreground android:drawable="@drawable/ic_shortcut_map_foreground" />
+</adaptive-icon> \ No newline at end of file
diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_movie.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_movie.xml
new file mode 100644
index 0000000..8789ba0
--- /dev/null
+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_movie.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_shortcut_background" />
+ <foreground android:drawable="@drawable/ic_shortcut_movie_foreground" />
+</adaptive-icon> \ No newline at end of file
diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_search.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_search.xml
new file mode 100644
index 0000000..ab1fb94
--- /dev/null
+++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_shortcut_search.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <background android:drawable="@color/ic_shortcut_background" />
+ <foreground android:drawable="@drawable/ic_shortcut_search_foreground" />
+</adaptive-icon> \ No newline at end of file
diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..7c532b7
--- /dev/null
+++ b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
Binary files differ
diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
new file mode 100644
index 0000000..7407041
--- /dev/null
+++ b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
Binary files differ
diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..f9bbc54
--- /dev/null
+++ b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
Binary files differ
diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
new file mode 100644
index 0000000..c31695e
--- /dev/null
+++ b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
Binary files differ
diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..e3491da
--- /dev/null
+++ b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
Binary files differ
diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..8e5ee2b
--- /dev/null
+++ b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
Binary files differ
diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..51adec0
--- /dev/null
+++ b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..b11aeb8
--- /dev/null
+++ b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
Binary files differ
diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..8da583b
--- /dev/null
+++ b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
Binary files differ
diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..8b7999b
--- /dev/null
+++ b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
Binary files differ
diff --git a/android/app/src/main/res/values-ar/strings.xml b/android/app/src/main/res/values-ar/strings.xml
new file mode 100644
index 0000000..478e4f4
--- /dev/null
+++ b/android/app/src/main/res/values-ar/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_widget_label">إطار الصورة</string>
+ <string name="wallpaper">الخلفية</string>
+ <string name="search_shortcut_short_label">البحث</string>
+ <string name="videos_shortcut_short_label">الفيديوهات</string>
+ <string name="analysis_channel_name">فحص الوسائط</string>
+ <string name="analysis_notification_default_title">يتم فحص الوسائط</string>
+ <string name="analysis_notification_action_stop">إيقاف</string>
+ <string name="app_name">Aves</string>
+ <string name="map_shortcut_short_label">خريطة</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-az/strings.xml b/android/app/src/main/res/values-az/strings.xml
new file mode 100644
index 0000000..31f1b1c
--- /dev/null
+++ b/android/app/src/main/res/values-az/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Şəkil Çərçivəsi</string>
+ <string name="wallpaper">Divar kağızı</string>
+ <string name="map_shortcut_short_label">Xəritə</string>
+ <string name="search_shortcut_short_label">Axtarış</string>
+ <string name="videos_shortcut_short_label">Videolar</string>
+ <string name="analysis_channel_name">Medianı yoxla</string>
+ <string name="analysis_notification_default_title">Media yoxlanılır</string>
+ <string name="analysis_notification_action_stop">Dayandır</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-b+zxx+Shaw/strings.xml b/android/app/src/main/res/values-b+zxx+Shaw/strings.xml
new file mode 100644
index 0000000..f7bb920
--- /dev/null
+++ b/android/app/src/main/res/values-b+zxx+Shaw/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">𐑱𐑝𐑰𐑟</string>
+ <string name="app_widget_label">𐑓𐑴𐑑𐑴 𐑓𐑮𐑱𐑥</string>
+ <string name="wallpaper">𐑢𐑷𐑤𐑐𐑱𐑐𐑼</string>
+ <string name="map_shortcut_short_label">𐑥𐑨𐑐</string>
+ <string name="search_shortcut_short_label">𐑕𐑻𐑗</string>
+ <string name="videos_shortcut_short_label">𐑝𐑦𐑛𐑦𐑴𐑟</string>
+ <string name="analysis_channel_name">𐑥𐑰𐑛𐑾 𐑕𐑒𐑨𐑯</string>
+ <string name="analysis_notification_default_title">𐑕𐑒𐑨𐑯𐑦𐑙 𐑥𐑰𐑛𐑾</string>
+ <string name="analysis_notification_action_stop">𐑕𐑑𐑪𐑐</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-be/strings.xml b/android/app/src/main/res/values-be/strings.xml
new file mode 100644
index 0000000..cf307df
--- /dev/null
+++ b/android/app/src/main/res/values-be/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="analysis_channel_name">Сканаванне носьбітаў</string>
+ <string name="videos_shortcut_short_label">Відэа</string>
+ <string name="wallpaper">Шпалеры</string>
+ <string name="analysis_notification_default_title">Сканаванне носьбітаў</string>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Фотарамка</string>
+ <string name="search_shortcut_short_label">Пошук</string>
+ <string name="analysis_notification_action_stop">Стоп</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-bg/strings.xml b/android/app/src/main/res/values-bg/strings.xml
new file mode 100644
index 0000000..d33ecff
--- /dev/null
+++ b/android/app/src/main/res/values-bg/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Фоторамка</string>
+ <string name="wallpaper">Тапет</string>
+ <string name="map_shortcut_short_label">Карта</string>
+ <string name="search_shortcut_short_label">Търсене</string>
+ <string name="analysis_channel_name">Сканиране медия</string>
+ <string name="analysis_notification_default_title">Сканиране медия</string>
+ <string name="analysis_notification_action_stop">Стоп</string>
+ <string name="videos_shortcut_short_label">Видео</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-bn/strings.xml b/android/app/src/main/res/values-bn/strings.xml
new file mode 100644
index 0000000..936f4ce
--- /dev/null
+++ b/android/app/src/main/res/values-bn/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="wallpaper">ওয়ালপেপার</string>
+ <string name="search_shortcut_short_label">সার্চ</string>
+ <string name="videos_shortcut_short_label">ভিডিও</string>
+ <string name="analysis_notification_default_title">মিডিয়া সন্ধান চলছে</string>
+ <string name="analysis_channel_name">মিডিয়া সন্ধান</string>
+ <string name="analysis_notification_action_stop">থামান</string>
+ <string name="app_name">আভেস</string>
+ <string name="app_widget_label">ছবির ফ্রেম</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-ca/strings.xml b/android/app/src/main/res/values-ca/strings.xml
new file mode 100644
index 0000000..1146f3a
--- /dev/null
+++ b/android/app/src/main/res/values-ca/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Marc de foto</string>
+ <string name="wallpaper">Fons de pantalla</string>
+ <string name="search_shortcut_short_label">Buscar</string>
+ <string name="videos_shortcut_short_label">Vídeos</string>
+ <string name="analysis_channel_name">Exploració de mitjans</string>
+ <string name="analysis_notification_default_title">Explorant mitjans</string>
+ <string name="analysis_notification_action_stop">Atura</string>
+ <string name="map_shortcut_short_label">Mapa</string>
+</resources>
diff --git a/android/app/src/main/res/values-ckb/strings.xml b/android/app/src/main/res/values-ckb/strings.xml
new file mode 100644
index 0000000..65b05be
--- /dev/null
+++ b/android/app/src/main/res/values-ckb/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">ئاڤێس</string>
+ <string name="app_widget_label">قەراغی وێنە</string>
+ <string name="wallpaper">پاشبنەما</string>
+ <string name="search_shortcut_short_label">گەڕان</string>
+ <string name="videos_shortcut_short_label">ڤیدیۆ</string>
+ <string name="analysis_channel_name">گەڕان لە ڕەنگاڵە</string>
+ <string name="analysis_notification_default_title">لە ڕەنگاڵەکان دەگەڕێت</string>
+ <string name="analysis_notification_action_stop">وەستاندن</string>
+ <string name="map_shortcut_short_label">نەخشە</string>
+</resources>
diff --git a/android/app/src/main/res/values-cs/strings.xml b/android/app/src/main/res/values-cs/strings.xml
new file mode 100644
index 0000000..af729a9
--- /dev/null
+++ b/android/app/src/main/res/values-cs/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="wallpaper">Tapeta</string>
+ <string name="search_shortcut_short_label">Hledat</string>
+ <string name="videos_shortcut_short_label">Videa</string>
+ <string name="analysis_channel_name">Prohledat média</string>
+ <string name="analysis_notification_default_title">Prohledávání médií</string>
+ <string name="analysis_notification_action_stop">Zastavit</string>
+ <string name="app_widget_label">Fotorámeček</string>
+ <string name="map_shortcut_short_label">Mapa</string>
+</resources>
diff --git a/android/app/src/main/res/values-da/strings.xml b/android/app/src/main/res/values-da/strings.xml
new file mode 100644
index 0000000..f475147
--- /dev/null
+++ b/android/app/src/main/res/values-da/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_widget_label">Fotoramme</string>
+ <string name="wallpaper">Baggrund</string>
+ <string name="videos_shortcut_short_label">Videoer</string>
+ <string name="analysis_channel_name">Mediescanning</string>
+ <string name="analysis_notification_default_title">Scanner medier</string>
+ <string name="analysis_notification_action_stop">Stop</string>
+ <string name="app_name">Aves</string>
+ <string name="search_shortcut_short_label">Søg</string>
+ <string name="map_shortcut_short_label">Kort</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xml
new file mode 100644
index 0000000..2c7396d
--- /dev/null
+++ b/android/app/src/main/res/values-de/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Bilderrahmen</string>
+ <string name="wallpaper">Hintergrundbild</string>
+ <string name="search_shortcut_short_label">Suche</string>
+ <string name="videos_shortcut_short_label">Videos</string>
+ <string name="analysis_channel_name">Analyse von Medien</string>
+ <string name="analysis_notification_default_title">Medien scannen</string>
+ <string name="analysis_notification_action_stop">Abbrechen</string>
+ <string name="map_shortcut_short_label">Karte</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-el/strings.xml b/android/app/src/main/res/values-el/strings.xml
new file mode 100644
index 0000000..77d0d3a
--- /dev/null
+++ b/android/app/src/main/res/values-el/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Κορνίζα</string>
+ <string name="wallpaper">Ταπετσαρία</string>
+ <string name="search_shortcut_short_label">Αναζήτηση</string>
+ <string name="videos_shortcut_short_label">Βίντεο</string>
+ <string name="analysis_channel_name">Σάρωση πολυμέσων</string>
+ <string name="analysis_notification_default_title">Σάρωση στοιχείων</string>
+ <string name="analysis_notification_action_stop">Διακοπή</string>
+ <string name="map_shortcut_short_label">Χάρτης</string>
+</resources>
diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml
new file mode 100644
index 0000000..6cc0b28
--- /dev/null
+++ b/android/app/src/main/res/values-es/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Marco de foto</string>
+ <string name="wallpaper">Fondo de pantalla</string>
+ <string name="search_shortcut_short_label">Buscar</string>
+ <string name="videos_shortcut_short_label">Vídeos</string>
+ <string name="analysis_channel_name">Explorar medios</string>
+ <string name="analysis_notification_default_title">Explorando medios</string>
+ <string name="analysis_notification_action_stop">Anular</string>
+ <string name="map_shortcut_short_label">Mapa</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-et/strings.xml b/android/app/src/main/res/values-et/strings.xml
new file mode 100644
index 0000000..b596c8b
--- /dev/null
+++ b/android/app/src/main/res/values-et/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Fotoraam</string>
+ <string name="wallpaper">Taustapilt</string>
+ <string name="map_shortcut_short_label">Kaart</string>
+ <string name="search_shortcut_short_label">Otsi</string>
+ <string name="videos_shortcut_short_label">Videod</string>
+ <string name="analysis_channel_name">Meedia tuvastamine</string>
+ <string name="analysis_notification_default_title">Tuvastame meediat</string>
+ <string name="analysis_notification_action_stop">Peata</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-eu/strings.xml b/android/app/src/main/res/values-eu/strings.xml
new file mode 100644
index 0000000..c8e57d8
--- /dev/null
+++ b/android/app/src/main/res/values-eu/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="search_shortcut_short_label">Bilatu</string>
+ <string name="videos_shortcut_short_label">Bideoak</string>
+ <string name="app_widget_label">Argazki-markoa</string>
+ <string name="wallpaper">Horma-papera</string>
+ <string name="analysis_channel_name">Media eskaneatu</string>
+ <string name="analysis_notification_action_stop">Gelditu</string>
+ <string name="analysis_notification_default_title">Media eskaneatzen</string>
+ <string name="app_name">Aves</string>
+ <string name="map_shortcut_short_label">Mapa</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-fa/strings.xml b/android/app/src/main/res/values-fa/strings.xml
new file mode 100644
index 0000000..aa8d9ee
--- /dev/null
+++ b/android/app/src/main/res/values-fa/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="videos_shortcut_short_label">ویدئو ها</string>
+ <string name="analysis_channel_name">کنکاش رسانه</string>
+ <string name="search_shortcut_short_label">جستجو</string>
+ <string name="wallpaper">کاغذدیواری</string>
+ <string name="analysis_notification_default_title">در حال کنکاش رسانه‌ها</string>
+ <string name="analysis_notification_action_stop">توقف کردن</string>
+ <string name="app_widget_label">قاب عکس</string>
+ <string name="app_name">Aves</string>
+ <string name="map_shortcut_short_label">نقشه</string>
+</resources>
diff --git a/android/app/src/main/res/values-fi/strings.xml b/android/app/src/main/res/values-fi/strings.xml
new file mode 100644
index 0000000..9d7d1f8
--- /dev/null
+++ b/android/app/src/main/res/values-fi/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="analysis_notification_action_stop">Lopeta</string>
+ <string name="app_widget_label">Valokuvakehys</string>
+ <string name="analysis_notification_default_title">Mediaa skannataan</string>
+ <string name="videos_shortcut_short_label">Videot</string>
+ <string name="wallpaper">Taustakuva</string>
+ <string name="app_name">Aves</string>
+ <string name="analysis_channel_name">Median skannaus</string>
+ <string name="search_shortcut_short_label">Hae</string>
+ <string name="map_shortcut_short_label">Kartta</string>
+</resources>
diff --git a/android/app/src/main/res/values-fr/strings.xml b/android/app/src/main/res/values-fr/strings.xml
new file mode 100644
index 0000000..159a984
--- /dev/null
+++ b/android/app/src/main/res/values-fr/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Cadre photo</string>
+ <string name="wallpaper">Fond d’écran</string>
+ <string name="search_shortcut_short_label">Recherche</string>
+ <string name="videos_shortcut_short_label">Vidéos</string>
+ <string name="analysis_channel_name">Analyse des images</string>
+ <string name="analysis_notification_default_title">Analyse des images</string>
+ <string name="analysis_notification_action_stop">Annuler</string>
+ <string name="map_shortcut_short_label">Carte</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-gl/strings.xml b/android/app/src/main/res/values-gl/strings.xml
new file mode 100644
index 0000000..a90ab7c
--- /dev/null
+++ b/android/app/src/main/res/values-gl/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Marco de fotos</string>
+ <string name="wallpaper">Fondo da pantalla</string>
+ <string name="search_shortcut_short_label">Procura</string>
+ <string name="videos_shortcut_short_label">Vídeos</string>
+ <string name="analysis_channel_name">Escanear medios</string>
+ <string name="analysis_notification_default_title">Escaneando medios</string>
+ <string name="analysis_notification_action_stop">Pare</string>
+ <string name="map_shortcut_short_label">Mapa</string>
+</resources>
diff --git a/android/app/src/main/res/values-hi/strings.xml b/android/app/src/main/res/values-hi/strings.xml
new file mode 100644
index 0000000..9b6676a
--- /dev/null
+++ b/android/app/src/main/res/values-hi/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="analysis_notification_default_title">मीडिया जाँचा जा राहा है</string>
+ <string name="analysis_notification_action_stop">रोके</string>
+ <string name="app_widget_label">फोटो फ्रेम</string>
+ <string name="wallpaper">वॉलपेपर</string>
+ <string name="search_shortcut_short_label">खोजें</string>
+ <string name="analysis_channel_name">मीडिया जाँचे</string>
+ <string name="app_name">ऐवीज</string>
+ <string name="videos_shortcut_short_label">वीडियो</string>
+ <string name="map_shortcut_short_label">मैप</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-hu/strings.xml b/android/app/src/main/res/values-hu/strings.xml
new file mode 100644
index 0000000..a8da148
--- /dev/null
+++ b/android/app/src/main/res/values-hu/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="wallpaper">Háttérkép</string>
+ <string name="search_shortcut_short_label">Keresés</string>
+ <string name="videos_shortcut_short_label">Videók</string>
+ <string name="analysis_notification_action_stop">Állj</string>
+ <string name="app_widget_label">Fotó keret</string>
+ <string name="analysis_channel_name">Médiafájlok keresése</string>
+ <string name="analysis_notification_default_title">Média beolvasása</string>
+ <string name="map_shortcut_short_label">Térkép</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-id/strings.xml b/android/app/src/main/res/values-id/strings.xml
new file mode 100644
index 0000000..13708b5
--- /dev/null
+++ b/android/app/src/main/res/values-id/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Bingkai Foto</string>
+ <string name="wallpaper">Wallpaper</string>
+ <string name="search_shortcut_short_label">Cari</string>
+ <string name="videos_shortcut_short_label">Video</string>
+ <string name="analysis_channel_name">Pindai media</string>
+ <string name="analysis_notification_default_title">Memindai media</string>
+ <string name="analysis_notification_action_stop">Berhenti</string>
+ <string name="map_shortcut_short_label">Peta</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-is/strings.xml b/android/app/src/main/res/values-is/strings.xml
new file mode 100644
index 0000000..d188a9d
--- /dev/null
+++ b/android/app/src/main/res/values-is/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="analysis_notification_action_stop">Stöðva</string>
+ <string name="app_widget_label">Myndarammi</string>
+ <string name="analysis_notification_default_title">Skanna myndefni</string>
+ <string name="videos_shortcut_short_label">Myndskeið</string>
+ <string name="wallpaper">Bakgrunnur</string>
+ <string name="app_name">Aves</string>
+ <string name="analysis_channel_name">Skönnun myndefnis</string>
+ <string name="search_shortcut_short_label">Leita</string>
+ <string name="map_shortcut_short_label">Landakort</string>
+</resources>
diff --git a/android/app/src/main/res/values-it/strings.xml b/android/app/src/main/res/values-it/strings.xml
new file mode 100644
index 0000000..519f158
--- /dev/null
+++ b/android/app/src/main/res/values-it/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Cornice foto</string>
+ <string name="wallpaper">Sfondo</string>
+ <string name="search_shortcut_short_label">Ricerca</string>
+ <string name="videos_shortcut_short_label">Video</string>
+ <string name="analysis_channel_name">Scansione media</string>
+ <string name="analysis_notification_default_title">Scansione in corso</string>
+ <string name="analysis_notification_action_stop">Annulla</string>
+ <string name="map_shortcut_short_label">Mappa</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-iw/strings.xml b/android/app/src/main/res/values-iw/strings.xml
new file mode 100644
index 0000000..fc8b10d
--- /dev/null
+++ b/android/app/src/main/res/values-iw/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">מסגרת תמונה</string>
+ <string name="wallpaper">טפט</string>
+ <string name="search_shortcut_short_label">חיפוש</string>
+ <string name="videos_shortcut_short_label">סרטים</string>
+ <string name="analysis_channel_name">סריקת מדיה</string>
+ <string name="analysis_notification_default_title">סורק מדיה</string>
+ <string name="analysis_notification_action_stop">הפסק</string>
+ <string name="map_shortcut_short_label">מפה</string>
+</resources>
diff --git a/android/app/src/main/res/values-ja/strings.xml b/android/app/src/main/res/values-ja/strings.xml
new file mode 100644
index 0000000..cf16df9
--- /dev/null
+++ b/android/app/src/main/res/values-ja/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">フォトフレーム</string>
+ <string name="wallpaper">壁紙</string>
+ <string name="search_shortcut_short_label">検索</string>
+ <string name="videos_shortcut_short_label">動画</string>
+ <string name="analysis_channel_name">メディアスキャン</string>
+ <string name="analysis_notification_default_title">メディアをスキャン中</string>
+ <string name="analysis_notification_action_stop">停止</string>
+ <string name="map_shortcut_short_label">マップ</string>
+</resources>
diff --git a/android/app/src/main/res/values-kmr/strings.xml b/android/app/src/main/res/values-kmr/strings.xml
new file mode 100644
index 0000000..d9d18d8
--- /dev/null
+++ b/android/app/src/main/res/values-kmr/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Çarçoveya wêneyê</string>
+ <string name="wallpaper">Paşrû</string>
+ <string name="map_shortcut_short_label">Nexşe</string>
+ <string name="search_shortcut_short_label">Bigere</string>
+ <string name="videos_shortcut_short_label">Vîdyo</string>
+ <string name="analysis_channel_name">Dîtina medya</string>
+ <string name="analysis_notification_default_title">Medya tê dîtin</string>
+ <string name="analysis_notification_action_stop">Rawestîne</string>
+</resources>
diff --git a/android/app/src/main/res/values-kn/strings.xml b/android/app/src/main/res/values-kn/strings.xml
new file mode 100644
index 0000000..c4900bd
--- /dev/null
+++ b/android/app/src/main/res/values-kn/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">ಎವೀಸ್</string>
+ <string name="app_widget_label">ಫೋಟೋ ಫ್ರೇಮ್</string>
+ <string name="wallpaper">ವಾಲ್ಪೇಪರ್</string>
+ <string name="videos_shortcut_short_label">ವೀಡಿಯೊಗಳು</string>
+ <string name="analysis_channel_name">ಮೀಡಿಯಾ ಸ್ಕ್ಯಾನ್</string>
+ <string name="analysis_notification_default_title">ಮೀಡಿಯಾ ಸ್ಕ್ಯಾನ್ ಮಾಡಲಾಗುತ್ತಿದೆ</string>
+ <string name="analysis_notification_action_stop">ನಿಲ್ಲಿಸಿ</string>
+ <string name="search_shortcut_short_label">ಹುಡುಕಿ</string>
+ <string name="map_shortcut_short_label">ನಕ್ಷೆ</string>
+</resources>
diff --git a/android/app/src/main/res/values-ko/strings.xml b/android/app/src/main/res/values-ko/strings.xml
new file mode 100644
index 0000000..207fcda
--- /dev/null
+++ b/android/app/src/main/res/values-ko/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">아베스</string>
+ <string name="app_widget_label">사진 액자</string>
+ <string name="wallpaper">배경화면</string>
+ <string name="search_shortcut_short_label">검색</string>
+ <string name="videos_shortcut_short_label">동영상</string>
+ <string name="analysis_channel_name">미디어 분석</string>
+ <string name="analysis_notification_default_title">미디어 분석</string>
+ <string name="analysis_notification_action_stop">취소</string>
+ <string name="map_shortcut_short_label">지도</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-lt/strings.xml b/android/app/src/main/res/values-lt/strings.xml
new file mode 100644
index 0000000..c8c6027
--- /dev/null
+++ b/android/app/src/main/res/values-lt/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="wallpaper">Ekrano paveikslėlis</string>
+ <string name="videos_shortcut_short_label">Vaizdo įrašai</string>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Nuotraukų rėmelis</string>
+ <string name="analysis_channel_name">Medijos nuskaitymas</string>
+ <string name="search_shortcut_short_label">Paieška</string>
+ <string name="analysis_notification_action_stop">Sustabdyti</string>
+ <string name="analysis_notification_default_title">Nuskaitoma medija</string>
+ <string name="map_shortcut_short_label">Žemėlapis</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-ml/strings.xml b/android/app/src/main/res/values-ml/strings.xml
new file mode 100644
index 0000000..06647e9
--- /dev/null
+++ b/android/app/src/main/res/values-ml/strings.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">എവ്സ്</string>
+ <string name="wallpaper">ചുമർ ചിത്രം</string>
+ <string name="search_shortcut_short_label">തിരയുക</string>
+ <string name="videos_shortcut_short_label">വീഡിയോകൾ</string>
+ <string name="analysis_channel_name">മാധ്യമ സൂക്ഷ്മപരിശോധന</string>
+ <string name="analysis_notification_action_stop">നിർത്തുക</string>
+</resources>
diff --git a/android/app/src/main/res/values-my/strings.xml b/android/app/src/main/res/values-my/strings.xml
new file mode 100644
index 0000000..ae4237c
--- /dev/null
+++ b/android/app/src/main/res/values-my/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">ရုပ်ပုံဘောင်</string>
+ <string name="wallpaper">နောက်ခံ ရုပ်ပုံ</string>
+ <string name="analysis_channel_name">မီဒီယာ စကင်</string>
+ <string name="search_shortcut_short_label">ရှာရန်</string>
+ <string name="videos_shortcut_short_label">ဗီဒီယိုများ</string>
+ <string name="analysis_notification_default_title">မီဒီယာ ကိုစကင်ဖတ်နေသည်</string>
+ <string name="analysis_notification_action_stop">ရပ်ရန်</string>
+ <string name="map_shortcut_short_label">မြေပုံ</string>
+</resources>
diff --git a/android/app/src/main/res/values-nb-rNO/strings.xml b/android/app/src/main/res/values-nb-rNO/strings.xml
new file mode 100644
index 0000000..fd061b6
--- /dev/null
+++ b/android/app/src/main/res/values-nb-rNO/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="videos_shortcut_short_label">Videoer</string>
+ <string name="analysis_channel_name">Mediaskanning</string>
+ <string name="analysis_notification_default_title">Skanning av media</string>
+ <string name="app_widget_label">Bilderamme</string>
+ <string name="wallpaper">Bakgrunnsbilde</string>
+ <string name="search_shortcut_short_label">Søk</string>
+ <string name="analysis_notification_action_stop">Stopp</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-ne/strings.xml b/android/app/src/main/res/values-ne/strings.xml
new file mode 100644
index 0000000..6dc61ac
--- /dev/null
+++ b/android/app/src/main/res/values-ne/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">एभस</string>
+</resources>
diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml
new file mode 100644
index 0000000..807a30b
--- /dev/null
+++ b/android/app/src/main/res/values-night/styles.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:tools="http://schemas.android.com/tools">
+ <style name="NormalTheme" parent="Theme.AppCompat.NoActionBar">
+ <item name="android:windowBackground">@color/window_background_night</item>
+ <item name="android:windowSplashScreenBackground" tools:targetApi="s">@color/window_background_night</item>
+ <item name="android:windowSplashScreenAnimatedIcon" tools:targetApi="s">@mipmap/ic_launcher</item>
+
+ <!-- API28+, draws next to the notch in fullscreen -->
+ <item name="android:windowLayoutInDisplayCutoutMode" tools:targetApi="28">shortEdges</item>
+ </style>
+</resources>
diff --git a/android/app/src/main/res/values-nl/strings.xml b/android/app/src/main/res/values-nl/strings.xml
new file mode 100644
index 0000000..103f471
--- /dev/null
+++ b/android/app/src/main/res/values-nl/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Fotolijst</string>
+ <string name="wallpaper">Achtergrond</string>
+ <string name="search_shortcut_short_label">Zoeken</string>
+ <string name="videos_shortcut_short_label">Video’s</string>
+ <string name="analysis_channel_name">Media indexeren</string>
+ <string name="analysis_notification_default_title">Media indexeren</string>
+ <string name="analysis_notification_action_stop">Stoppen</string>
+ <string name="map_shortcut_short_label">Kaart</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-nn/strings.xml b/android/app/src/main/res/values-nn/strings.xml
new file mode 100644
index 0000000..615c9eb
--- /dev/null
+++ b/android/app/src/main/res/values-nn/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Bileteramme</string>
+ <string name="wallpaper">Bakgrunnsbilete</string>
+ <string name="search_shortcut_short_label">Søk</string>
+ <string name="videos_shortcut_short_label">Videoar</string>
+ <string name="analysis_channel_name">Mediasøking</string>
+ <string name="analysis_notification_default_title">Søkjer igjennom media</string>
+ <string name="analysis_notification_action_stop">Stogg</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-or/strings.xml b/android/app/src/main/res/values-or/strings.xml
new file mode 100644
index 0000000..bec8cc7
--- /dev/null
+++ b/android/app/src/main/res/values-or/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="search_shortcut_short_label">ସନ୍ଧାନ</string>
+</resources>
diff --git a/android/app/src/main/res/values-pl/strings.xml b/android/app/src/main/res/values-pl/strings.xml
new file mode 100644
index 0000000..1cc7a69
--- /dev/null
+++ b/android/app/src/main/res/values-pl/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_widget_label">Ramka Zdjęcia</string>
+ <string name="search_shortcut_short_label">Szukaj</string>
+ <string name="videos_shortcut_short_label">Wideo</string>
+ <string name="analysis_channel_name">Przeskanuj multimedia</string>
+ <string name="analysis_notification_default_title">Skanowanie multimediów</string>
+ <string name="analysis_notification_action_stop">Zatrzymaj</string>
+ <string name="app_name">Aves</string>
+ <string name="wallpaper">Tapeta</string>
+ <string name="map_shortcut_short_label">Mapa</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-pt/strings.xml b/android/app/src/main/res/values-pt/strings.xml
new file mode 100644
index 0000000..a793c01
--- /dev/null
+++ b/android/app/src/main/res/values-pt/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Porta-retratos</string>
+ <string name="wallpaper">Papel de parede</string>
+ <string name="search_shortcut_short_label">Procurar</string>
+ <string name="videos_shortcut_short_label">Vídeos</string>
+ <string name="analysis_channel_name">Digitalização de mídia</string>
+ <string name="analysis_notification_default_title">Digitalizando mídia</string>
+ <string name="analysis_notification_action_stop">Pare</string>
+ <string name="map_shortcut_short_label">Mapa</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-ro/strings.xml b/android/app/src/main/res/values-ro/strings.xml
new file mode 100644
index 0000000..7334d4c
--- /dev/null
+++ b/android/app/src/main/res/values-ro/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Rama foto</string>
+ <string name="wallpaper">Tapet</string>
+ <string name="videos_shortcut_short_label">Videoclipuri</string>
+ <string name="analysis_channel_name">Scanare media</string>
+ <string name="analysis_notification_default_title">Scanarea suporturilor</string>
+ <string name="analysis_notification_action_stop">Stop</string>
+ <string name="search_shortcut_short_label">Căutare</string>
+ <string name="map_shortcut_short_label">Hartă</string>
+</resources>
diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xml
new file mode 100644
index 0000000..ca3cde8
--- /dev/null
+++ b/android/app/src/main/res/values-ru/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Фоторамка</string>
+ <string name="wallpaper">Обои</string>
+ <string name="search_shortcut_short_label">Поиск</string>
+ <string name="videos_shortcut_short_label">Видео</string>
+ <string name="analysis_channel_name">Сканировать медия</string>
+ <string name="analysis_notification_default_title">Сканирование медиа</string>
+ <string name="analysis_notification_action_stop">Стоп</string>
+ <string name="map_shortcut_short_label">Карта</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-sat/strings.xml b/android/app/src/main/res/values-sat/strings.xml
new file mode 100644
index 0000000..5383771
--- /dev/null
+++ b/android/app/src/main/res/values-sat/strings.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">ᱮᱣᱥ</string>
+ <string name="app_widget_label">ᱪᱤᱛᱟᱹᱨ ᱯᱷᱨᱮᱢ</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-sk/strings.xml b/android/app/src/main/res/values-sk/strings.xml
new file mode 100644
index 0000000..a6c5056
--- /dev/null
+++ b/android/app/src/main/res/values-sk/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="search_shortcut_short_label">Hľadať</string>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Rám fotky</string>
+ <string name="wallpaper">Tapeta</string>
+ <string name="videos_shortcut_short_label">Videá</string>
+ <string name="analysis_notification_action_stop">Zastaviť</string>
+ <string name="analysis_channel_name">Skenovanie médií</string>
+ <string name="analysis_notification_default_title">Skenovanie média</string>
+ <string name="map_shortcut_short_label">Mapa</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-sl/strings.xml b/android/app/src/main/res/values-sl/strings.xml
new file mode 100644
index 0000000..dd0bce1
--- /dev/null
+++ b/android/app/src/main/res/values-sl/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_widget_label">Okvir za sliko</string>
+ <string name="app_name">Aves</string>
+ <string name="videos_shortcut_short_label">Videoposnetki</string>
+ <string name="wallpaper">Ozadje</string>
+ <string name="search_shortcut_short_label">Iskanje</string>
+ <string name="analysis_notification_default_title">Skeniram medijske datoteke</string>
+ <string name="analysis_notification_action_stop">Ustavi</string>
+ <string name="analysis_channel_name">Sken za medijske datoteke</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-sr/strings.xml b/android/app/src/main/res/values-sr/strings.xml
new file mode 100644
index 0000000..b03879d
--- /dev/null
+++ b/android/app/src/main/res/values-sr/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_widget_label">Okvir Slike</string>
+ <string name="wallpaper">Pozadina</string>
+ <string name="videos_shortcut_short_label">Snimci</string>
+ <string name="analysis_channel_name">Pretraga medija</string>
+ <string name="analysis_notification_default_title">Skeniranje medija</string>
+ <string name="analysis_notification_action_stop">Stop</string>
+ <string name="app_name">Aves</string>
+ <string name="search_shortcut_short_label">Pretraga</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-sv/strings.xml b/android/app/src/main/res/values-sv/strings.xml
new file mode 100644
index 0000000..fb447ef
--- /dev/null
+++ b/android/app/src/main/res/values-sv/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Fotoram</string>
+ <string name="wallpaper">Bakgrund</string>
+ <string name="videos_shortcut_short_label">Videor</string>
+ <string name="analysis_channel_name">Media scanning</string>
+ <string name="analysis_notification_default_title">Scannar media</string>
+ <string name="analysis_notification_action_stop">Stopp</string>
+ <string name="search_shortcut_short_label">Sök</string>
+ <string name="map_shortcut_short_label">Karta</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-ta/strings.xml b/android/app/src/main/res/values-ta/strings.xml
new file mode 100644
index 0000000..ca82090
--- /dev/null
+++ b/android/app/src/main/res/values-ta/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">ஏவ்ச்</string>
+ <string name="app_widget_label">புகைப்பட சட்டகம்</string>
+ <string name="wallpaper">வால்பேப்பர்</string>
+ <string name="map_shortcut_short_label">வரைபடம்</string>
+ <string name="search_shortcut_short_label">தேடல்</string>
+ <string name="analysis_notification_default_title">ஊடக ச்கேனிங்</string>
+ <string name="videos_shortcut_short_label">வீடியோக்கள்</string>
+ <string name="analysis_channel_name">மீடியா ச்கேன்</string>
+ <string name="analysis_notification_action_stop">நிறுத்து</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-th/strings.xml b/android/app/src/main/res/values-th/strings.xml
new file mode 100644
index 0000000..2ac9295
--- /dev/null
+++ b/android/app/src/main/res/values-th/strings.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">กรอบรูป</string>
+ <string name="wallpaper">ภาพพื้นหลัง</string>
+ <string name="search_shortcut_short_label">ค้นหา</string>
+ <string name="videos_shortcut_short_label">วิดีโอ</string>
+ <string name="analysis_channel_name">สแกนสื่อบันเทิง</string>
+ <string name="analysis_notification_default_title">กำลังสแกนสื่อบันเทิง</string>
+ <string name="analysis_notification_action_stop">หยุด</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-tr/strings.xml b/android/app/src/main/res/values-tr/strings.xml
new file mode 100644
index 0000000..c115ff9
--- /dev/null
+++ b/android/app/src/main/res/values-tr/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Fotoğraf Çerçevesi</string>
+ <string name="wallpaper">Duvar kağıdı</string>
+ <string name="search_shortcut_short_label">Arama</string>
+ <string name="videos_shortcut_short_label">Videolar</string>
+ <string name="analysis_channel_name">Medya tarama</string>
+ <string name="analysis_notification_default_title">Medya taranıyor</string>
+ <string name="analysis_notification_action_stop">Durdur</string>
+ <string name="map_shortcut_short_label">Harita</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-uk/strings.xml b/android/app/src/main/res/values-uk/strings.xml
new file mode 100644
index 0000000..60717a3
--- /dev/null
+++ b/android/app/src/main/res/values-uk/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="wallpaper">Шпалери</string>
+ <string name="search_shortcut_short_label">Пошук</string>
+ <string name="videos_shortcut_short_label">Відео</string>
+ <string name="analysis_channel_name">Сканувати медіа</string>
+ <string name="analysis_notification_action_stop">Стоп</string>
+ <string name="app_widget_label">Фоторамка</string>
+ <string name="analysis_notification_default_title">Сканування медіа</string>
+ <string name="map_shortcut_short_label">Мапа</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-ur/strings.xml b/android/app/src/main/res/values-ur/strings.xml
new file mode 100644
index 0000000..68d8716
--- /dev/null
+++ b/android/app/src/main/res/values-ur/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+</resources>
diff --git a/android/app/src/main/res/values-vi/strings.xml b/android/app/src/main/res/values-vi/strings.xml
new file mode 100644
index 0000000..96db6a4
--- /dev/null
+++ b/android/app/src/main/res/values-vi/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="analysis_notification_action_stop">Dừng</string>
+ <string name="app_widget_label">Khung Ảnh</string>
+ <string name="analysis_notification_default_title">Đang quét phương tiện</string>
+ <string name="videos_shortcut_short_label">Video</string>
+ <string name="wallpaper">Hình nền</string>
+ <string name="app_name">Aves</string>
+ <string name="analysis_channel_name">Quét phương tiện</string>
+ <string name="search_shortcut_short_label">Tìm kiếm</string>
+ <string name="map_shortcut_short_label">Bản đồ</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values-zh-rTW/strings.xml b/android/app/src/main/res/values-zh-rTW/strings.xml
new file mode 100644
index 0000000..bf3e0c4
--- /dev/null
+++ b/android/app/src/main/res/values-zh-rTW/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="videos_shortcut_short_label">影片</string>
+ <string name="wallpaper">桌布</string>
+ <string name="analysis_notification_default_title">掃描媒體中</string>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">相框</string>
+ <string name="search_shortcut_short_label">搜尋</string>
+ <string name="analysis_channel_name">媒體掃描</string>
+ <string name="analysis_notification_action_stop">停止</string>
+ <string name="map_shortcut_short_label">地圖</string>
+</resources>
diff --git a/android/app/src/main/res/values-zh/strings.xml b/android/app/src/main/res/values-zh/strings.xml
new file mode 100644
index 0000000..70b8d1c
--- /dev/null
+++ b/android/app/src/main/res/values-zh/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">相框</string>
+ <string name="wallpaper">壁纸</string>
+ <string name="search_shortcut_short_label">搜索</string>
+ <string name="videos_shortcut_short_label">视频</string>
+ <string name="analysis_channel_name">媒体扫描</string>
+ <string name="analysis_notification_default_title">正在扫描媒体</string>
+ <string name="analysis_notification_action_stop">停止</string>
+ <string name="map_shortcut_short_label">地图</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..8c34775
--- /dev/null
+++ b/android/app/src/main/res/values/colors.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="ic_launcher_background">#FFFFFF</color>
+ <color name="ic_shortcut_background">#FFFFFF</color>
+ <color name="ic_shortcut_foreground">#455A64</color>
+ <color name="ic_launcher_flavour">#1cc8eb</color>
+ <color name="window_background_day">#FFFFFF</color>
+ <color name="window_background_night">#262626</color>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
new file mode 100644
index 0000000..286ae61
--- /dev/null
+++ b/android/app/src/main/res/values/strings.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves</string>
+ <string name="app_widget_label">Photo Frame</string>
+ <string name="wallpaper">Wallpaper</string>
+ <string name="map_shortcut_short_label">Map</string>
+ <string name="search_shortcut_short_label">Search</string>
+ <string name="videos_shortcut_short_label">Videos</string>
+ <string name="analysis_channel_name">Media scan</string>
+ <string name="analysis_notification_default_title">Scanning media</string>
+ <string name="analysis_notification_action_stop">Stop</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..eca13a9
--- /dev/null
+++ b/android/app/src/main/res/values/styles.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources xmlns:tools="http://schemas.android.com/tools">
+ <style name="NormalTheme" parent="Theme.AppCompat.Light.NoActionBar">
+ <item name="android:windowBackground">@color/window_background_day</item>
+ <item name="android:windowSplashScreenBackground" tools:targetApi="s">@color/window_background_day</item>
+ <item name="android:windowSplashScreenAnimatedIcon" tools:targetApi="s">@mipmap/ic_launcher</item>
+
+ <!-- API28+, draws next to the notch in fullscreen -->
+ <item name="android:windowLayoutInDisplayCutoutMode" tools:targetApi="28">shortEdges</item>
+ </style>
+</resources>
diff --git a/android/app/src/main/res/xml/app_widget_info.xml b/android/app/src/main/res/xml/app_widget_info.xml
new file mode 100644
index 0000000..eb1d68c
--- /dev/null
+++ b/android/app/src/main/res/xml/app_widget_info.xml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="utf-8"?>
+<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:configure="deckers.thibault.aves.HomeWidgetSettingsActivity"
+ android:initialLayout="@layout/app_widget"
+ android:minWidth="40dp"
+ android:minHeight="40dp"
+ android:resizeMode="horizontal|vertical"
+ android:targetCellWidth="2"
+ android:targetCellHeight="2"
+ android:updatePeriodMillis="3600000"
+ android:widgetCategory="home_screen"
+ android:widgetFeatures="reconfigurable"
+ tools:targetApi="s" /> \ No newline at end of file
diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xml
new file mode 100644
index 0000000..9f73294
--- /dev/null
+++ b/android/app/src/main/res/xml/data_extraction_rules.xml
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="utf-8"?>
+<data-extraction-rules>
+ <cloud-backup disableIfNoEncryptionCapabilities="true">
+ <include
+ domain="file"
+ path="." />
+ <include
+ domain="database"
+ path="." />
+ <include
+ domain="external"
+ path="." />
+ <include
+ domain="sharedpref"
+ path="." />
+ <exclude
+ domain="sharedpref"
+ path="secret_shared_prefs.xml" />
+ </cloud-backup>
+ <device-transfer>
+ <include
+ domain="file"
+ path="." />
+ <include
+ domain="database"
+ path="." />
+ <include
+ domain="external"
+ path="." />
+ <include
+ domain="sharedpref"
+ path="." />
+ <exclude
+ domain="sharedpref"
+ path="secret_shared_prefs.xml" />
+ </device-transfer>
+</data-extraction-rules>
diff --git a/android/app/src/main/res/xml/full_backup_content.xml b/android/app/src/main/res/xml/full_backup_content.xml
new file mode 100644
index 0000000..5e5ca09
--- /dev/null
+++ b/android/app/src/main/res/xml/full_backup_content.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<full-backup-content>
+ <include
+ domain="file"
+ path="." />
+ <include
+ domain="database"
+ path="." />
+ <include
+ domain="external"
+ path="." />
+ <include
+ domain="sharedpref"
+ path="." />
+ <exclude
+ domain="sharedpref"
+ path="secret_shared_prefs.xml" />
+</full-backup-content>
diff --git a/android/app/src/main/res/xml/provider_paths.xml b/android/app/src/main/res/xml/provider_paths.xml
new file mode 100644
index 0000000..168574e
--- /dev/null
+++ b/android/app/src/main/res/xml/provider_paths.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<paths>
+ <!-- `external-path` only covers files on regular device storage -->
+ <external-path
+ name="external"
+ path="." />
+
+ <!-- `root-path` is necessary to cover files on removable storage -->
+ <!-- cf https://iditect.com/article/fileprovider-for-android-get-content-uri-through-fileprovider.html -->
+ <!--suppress AndroidElementNotAllowed -->
+ <root-path
+ name="root"
+ path="." />
+
+ <!-- embedded images & other media that are exported for viewing and sharing -->
+ <cache-path
+ name="embedded"
+ path="." />
+</paths> \ No newline at end of file
diff --git a/android/app/src/main/res/xml/screen_saver.xml b/android/app/src/main/res/xml/screen_saver.xml
new file mode 100644
index 0000000..d1de689
--- /dev/null
+++ b/android/app/src/main/res/xml/screen_saver.xml
@@ -0,0 +1,2 @@
+<dream xmlns:android="http://schemas.android.com/apk/res/android"
+ android:settingsActivity="@string/screen_saver_settings_activity" /> \ No newline at end of file
diff --git a/android/app/src/main/res/xml/searchable.xml b/android/app/src/main/res/xml/searchable.xml
new file mode 100644
index 0000000..d86475b
--- /dev/null
+++ b/android/app/src/main/res/xml/searchable.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<searchable xmlns:android="http://schemas.android.com/apk/res/android"
+ android:includeInGlobalSearch="true"
+ android:label="@string/app_name"
+ android:searchSuggestAuthority="@string/search_provider"
+ android:searchSuggestIntentAction="android.intent.action.SEARCH"
+ android:searchSuggestSelection=" ?"
+ android:searchSuggestThreshold="3" />
diff --git a/android/app/src/profile/res/values/colors.xml b/android/app/src/profile/res/values/colors.xml
new file mode 100644
index 0000000..9981f6c
--- /dev/null
+++ b/android/app/src/profile/res/values/colors.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="ic_launcher_flavour">#007A78</color>
+</resources> \ No newline at end of file
diff --git a/android/app/src/profile/res/values/strings.xml b/android/app/src/profile/res/values/strings.xml
new file mode 100644
index 0000000..2190231
--- /dev/null
+++ b/android/app/src/profile/res/values/strings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Aves [Profile]</string>
+</resources> \ No newline at end of file
diff --git a/android/app/src/test/kotlin/deckers/thibault/aves/model/provider/ImageProviderTest.kt b/android/app/src/test/kotlin/deckers/thibault/aves/model/provider/ImageProviderTest.kt
new file mode 100644
index 0000000..14a126f
--- /dev/null
+++ b/android/app/src/test/kotlin/deckers/thibault/aves/model/provider/ImageProviderTest.kt
@@ -0,0 +1,18 @@
+package deckers.thibault.aves.model.provider
+
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Test
+import java.time.LocalDate
+import java.time.Month
+import java.util.TimeZone
+
+class ImageProviderTest {
+ @Test
+ fun imageProvider_CorrectEmailSimple_ReturnsTrue() {
+ val date = LocalDate.of(1990, Month.FEBRUARY, 11).toEpochDay()
+ assertEquals("+01:00", ImageProvider.getTimeZoneString(TimeZone.getTimeZone("Europe/Paris"), date))
+ assertEquals("+00:00", ImageProvider.getTimeZoneString(TimeZone.getTimeZone("UTC"), date))
+ assertEquals("+05:30", ImageProvider.getTimeZoneString(TimeZone.getTimeZone("Asia/Kolkata"), date))
+ assertEquals("-06:00", ImageProvider.getTimeZoneString(TimeZone.getTimeZone("America/Chicago"), date))
+ }
+}
diff --git a/android/app/src/test/kotlin/deckers/thibault/aves/utils/MathUtilsTest.kt b/android/app/src/test/kotlin/deckers/thibault/aves/utils/MathUtilsTest.kt
new file mode 100644
index 0000000..48382cc
--- /dev/null
+++ b/android/app/src/test/kotlin/deckers/thibault/aves/utils/MathUtilsTest.kt
@@ -0,0 +1,17 @@
+package deckers.thibault.aves.utils
+
+import deckers.thibault.aves.utils.MathUtils.highestPowerOf2
+import org.junit.jupiter.api.Assertions.assertEquals
+import org.junit.jupiter.api.Test
+
+class MathUtilsTest {
+ @Test
+ fun mathUtils_highestPowerOf2() {
+ assertEquals(1024, highestPowerOf2(1024))
+ assertEquals(32, highestPowerOf2(42))
+ assertEquals(0, highestPowerOf2(0))
+ assertEquals(0, highestPowerOf2(-42))
+ assertEquals(0, highestPowerOf2(.5))
+ assertEquals(1, highestPowerOf2(1.5))
+ }
+}
diff --git a/android/build.gradle b/android/build.gradle
new file mode 100644
index 0000000..af24e79
--- /dev/null
+++ b/android/build.gradle
@@ -0,0 +1,52 @@
+buildscript {
+ ext {
+ agp_version = '8.13.1'
+ glide_version = '5.0.5'
+ abiCodes = ['armeabi-v7a': 1, 'arm64-v8a': 2, 'x86': 3, 'x86_64': 4]
+ useCrashlytics = gradle.startParameter.taskNames.any { task -> task.containsIgnoreCase("play") }
+ }
+
+ repositories {
+ google()
+ mavenCentral()
+ }
+
+ dependencies {
+ classpath "com.android.tools.build:gradle:$agp_version"
+
+ if (useCrashlytics) {
+ // GMS & Firebase Crashlytics (used by some flavors only)
+ classpath 'com.google.gms:google-services:4.4.3'
+ classpath 'com.google.firebase:firebase-crashlytics-gradle:3.0.4'
+ }
+ }
+}
+
+plugins {
+ id 'org.gradlex.reproducible-builds' version '1.1'
+}
+
+allprojects {
+ apply plugin: 'org.gradlex.reproducible-builds'
+
+ repositories {
+ google()
+ mavenCentral()
+ }
+
+// gradle.projectsEvaluated {
+// tasks.withType(JavaCompile) {
+// options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
+// }
+// }
+}
+
+rootProject.buildDir = '../build'
+subprojects {
+ project.buildDir = "${rootProject.buildDir}/${project.name}"
+ project.evaluationDependsOn(':app')
+}
+
+tasks.register('clean', Delete) {
+ delete rootProject.buildDir
+}
diff --git a/android/exifinterface/.gitignore b/android/exifinterface/.gitignore
new file mode 100644
index 0000000..42afabf
--- /dev/null
+++ b/android/exifinterface/.gitignore
@@ -0,0 +1 @@
+/build \ No newline at end of file
diff --git a/android/exifinterface/LICENSE.txt b/android/exifinterface/LICENSE.txt
new file mode 100644
index 0000000..e454a52
--- /dev/null
+++ b/android/exifinterface/LICENSE.txt
@@ -0,0 +1,178 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
diff --git a/android/exifinterface/build.gradle b/android/exifinterface/build.gradle
new file mode 100644
index 0000000..7d83b50
--- /dev/null
+++ b/android/exifinterface/build.gradle
@@ -0,0 +1,31 @@
+plugins {
+ id 'com.android.library'
+}
+
+android {
+ namespace 'androidx.exifinterface.media'
+ compileSdk 35
+
+ defaultConfig {
+ minSdk 21
+
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ consumerProguardFiles "consumer-rules.pro"
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
+ }
+ }
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+}
+
+dependencies {
+ implementation 'androidx.annotation:annotation:1.9.1'
+ implementation 'org.jspecify:jspecify:1.0.0'
+} \ No newline at end of file
diff --git a/android/exifinterface/consumer-rules.pro b/android/exifinterface/consumer-rules.pro
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/android/exifinterface/consumer-rules.pro
diff --git a/android/exifinterface/proguard-rules.pro b/android/exifinterface/proguard-rules.pro
new file mode 100644
index 0000000..481bb43
--- /dev/null
+++ b/android/exifinterface/proguard-rules.pro
@@ -0,0 +1,21 @@
+# Add project specific ProGuard rules here.
+# You can control the set of applied configuration files using the
+# proguardFiles setting in build.gradle.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
+
+# Uncomment this to preserve the line number information for
+# debugging stack traces.
+#-keepattributes SourceFile,LineNumberTable
+
+# If you keep the line number information, uncomment this to
+# hide the original source file name.
+#-renamesourcefileattribute SourceFile \ No newline at end of file
diff --git a/android/exifinterface/src/main/AndroidManifest.xml b/android/exifinterface/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..568741e
--- /dev/null
+++ b/android/exifinterface/src/main/AndroidManifest.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest /> \ No newline at end of file
diff --git a/android/exifinterface/src/main/java/androidx/exifinterface/media/ExifInterfaceFork.java b/android/exifinterface/src/main/java/androidx/exifinterface/media/ExifInterfaceFork.java
new file mode 100644
index 0000000..49d0fe8
--- /dev/null
+++ b/android/exifinterface/src/main/java/androidx/exifinterface/media/ExifInterfaceFork.java
@@ -0,0 +1,8553 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package androidx.exifinterface.media;
+
+import static androidx.exifinterface.media.ExifInterfaceUtilsFork.closeFileDescriptor;
+import static androidx.exifinterface.media.ExifInterfaceUtilsFork.closeQuietly;
+import static androidx.exifinterface.media.ExifInterfaceUtilsFork.convertToLongArray;
+import static androidx.exifinterface.media.ExifInterfaceUtilsFork.copy;
+import static androidx.exifinterface.media.ExifInterfaceUtilsFork.parseSubSeconds;
+import static androidx.exifinterface.media.ExifInterfaceUtilsFork.startsWith;
+import static java.lang.annotation.ElementType.TYPE_USE;
+import static java.nio.ByteOrder.BIG_ENDIAN;
+import static java.nio.ByteOrder.LITTLE_ENDIAN;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+import android.annotation.SuppressLint;
+import android.content.res.AssetManager;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.location.Location;
+import android.media.MediaDataSource;
+import android.media.MediaMetadataRetriever;
+import android.os.Build;
+import android.system.Os;
+import android.system.OsConstants;
+import android.util.Log;
+import android.util.Pair;
+
+import androidx.annotation.IntDef;
+import androidx.annotation.RestrictTo;
+import androidx.annotation.VisibleForTesting;
+import androidx.exifinterface.media.ExifInterfaceUtilsFork.Api23Impl;
+
+import org.jspecify.annotations.NonNull;
+import org.jspecify.annotations.Nullable;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInput;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.charset.Charset;
+import java.text.ParsePosition;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.TimeZone;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.zip.CRC32;
+
+/*
+ * Forked from 'androidx.exifinterface:exifinterface:1.4.1'
+ * Named differently to let ExifInterface be loaded as subdependency.
+ * cf https://maven.google.com/web/index.html?q=exifinterface#androidx.exifinterface:exifinterface
+ * cf https://github.com/androidx/androidx/tree/androidx-main/exifinterface/exifinterface/src/main/java/androidx/exifinterface/media
+ */
+
+/**
+ * This is a class for reading and writing Exif tags in various image file formats.
+ *
+ * <p>Supported for reading: JPEG, PNG, WebP, HEIC, DNG, CR2, NEF, NRW, ARW, RW2, ORF, PEF, SRW,
+ * RAF, AVIF (on API 31+).
+ *
+ * <p>Supported for writing: JPEG, PNG, WebP.
+ *
+ * <p>
+ *
+ * <h3>XMP Support</h3>
+ * <p>
+ * This class can read raw XMP data from the supported image file formats.
+ *
+ * <p>XMP data can be stored within Exif data (under tag 700), but many of the formats also define a
+ * separate storage location for XMP. ExifInterface handles this ambiguity as follows:
+ *
+ * <ul>
+ * <li><b>JPEG</b>
+ * <ul>
+ * <li>The XMP spec part 3 section 3.3.2 forbids the XMP tag (700) being present in the Exif
+ * segment of JPEG files (i.e. XMP should always be in a separate APP1 segment).
+ * <li>If XMP is present in both Exif and separate segments, the XMP from the Exif segment
+ * is returned from {@link #getAttributeBytes} and modifications to the XMP with {@link
+ * #setAttribute} are written back to the XMP in the Exif segment, the XMP in the
+ * separate segment is preserved unmodified. This is contrary to the spec described
+ * above (which suggests the standalone XMP should be preferred over the XMP in the Exif
+ * segment).
+ * <li>If XMP is not present in either location, and is added with {@link #setAttribute}, it
+ * is written as a standalone segment, in line with the spec described above.
+ * </ul>
+ * <li><b>HEIC & AVIF</b>
+ * <ul>
+ * <li>If XMP is present in both Exif and separate segments, the XMP from the separate
+ * segment is returned from {@link #getAttributeBytes}.
+ * </ul>
+ * </ul>
+ */
+public class ExifInterfaceFork {
+ // TLAD threshold for safer Exif attribute parsing
+ private static final int ATTRIBUTE_SIZE_DANGER_THRESHOLD = 3 * (1 << 20); // MB
+
+ // TLAD available heap size, to check allocations
+ private long getAvailableHeapSize() {
+ final Runtime runtime = Runtime.getRuntime();
+ return runtime.maxMemory() - (runtime.totalMemory() - runtime.freeMemory());
+ }
+
+ private static final String TAG = "ExifInterface";
+ private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+
+ // The Exif tag names. See JEITA CP-3451C specifications (Exif 2.3) Section 3-8.
+ // A. Tags related to image data structure
+ /**
+ * <p>The number of columns of image data, equal to the number of pixels per row. In JPEG
+ * compressed data, this tag shall not be used because a JPEG marker is used instead of it.</p>
+ *
+ * <ul>
+ * <li>Tag = 256</li>
+ * <li>Type = Unsigned short or Unsigned long</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_IMAGE_WIDTH = "ImageWidth";
+ /**
+ * <p>The number of rows of image data. In JPEG compressed data, this tag shall not be used
+ * because a JPEG marker is used instead of it.</p>
+ *
+ * <ul>
+ * <li>Tag = 257</li>
+ * <li>Type = Unsigned short or Unsigned long</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_IMAGE_LENGTH = "ImageLength";
+ /**
+ * <p>The number of bits per image component. In this standard each component of the image is
+ * 8 bits, so the value for this tag is 8. See also {@link #TAG_SAMPLES_PER_PIXEL}. In JPEG
+ * compressed data, this tag shall not be used because a JPEG marker is used instead of it.</p>
+ *
+ * <ul>
+ * <li>Tag = 258</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 3</li>
+ * <li>Default = {@link #BITS_PER_SAMPLE_RGB}</li>
+ * </ul>
+ */
+ public static final String TAG_BITS_PER_SAMPLE = "BitsPerSample";
+ /**
+ * <p>The compression scheme used for the image data. When a primary image is JPEG compressed,
+ * this designation is not necessary. So, this tag shall not be recorded. When thumbnails use
+ * JPEG compression, this tag value is set to 6.</p>
+ *
+ * <ul>
+ * <li>Tag = 259</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #DATA_UNCOMPRESSED
+ * @see #DATA_JPEG
+ */
+ public static final String TAG_COMPRESSION = "Compression";
+ /**
+ * <p>The pixel composition. In JPEG compressed data, this tag shall not be used because a JPEG
+ * marker is used instead of it.</p>
+ *
+ * <ul>
+ * <li>Tag = 262</li>
+ * <li>Type = SHORT</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #PHOTOMETRIC_INTERPRETATION_RGB
+ * @see #PHOTOMETRIC_INTERPRETATION_YCBCR
+ */
+ public static final String TAG_PHOTOMETRIC_INTERPRETATION = "PhotometricInterpretation";
+ /**
+ * <p>The image orientation viewed in terms of rows and columns.</p>
+ *
+ * <ul>
+ * <li>Tag = 274</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #ORIENTATION_NORMAL}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #ORIENTATION_UNDEFINED
+ * @see #ORIENTATION_NORMAL
+ * @see #ORIENTATION_FLIP_HORIZONTAL
+ * @see #ORIENTATION_ROTATE_180
+ * @see #ORIENTATION_FLIP_VERTICAL
+ * @see #ORIENTATION_TRANSPOSE
+ * @see #ORIENTATION_ROTATE_90
+ * @see #ORIENTATION_TRANSVERSE
+ * @see #ORIENTATION_ROTATE_270
+ */
+ public static final String TAG_ORIENTATION = "Orientation";
+ /**
+ * <p>The number of components per pixel. Since this standard applies to RGB and YCbCr images,
+ * the value set for this tag is 3. In JPEG compressed data, this tag shall not be used because
+ * a JPEG marker is used instead of it.</p>
+ *
+ * <ul>
+ * <li>Tag = 277</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = 3</li>
+ * </ul>
+ */
+ public static final String TAG_SAMPLES_PER_PIXEL = "SamplesPerPixel";
+ /**
+ * <p>Indicates whether pixel components are recorded in chunky or planar format. In JPEG
+ * compressed data, this tag shall not be used because a JPEG marker is used instead of it.
+ * If this field does not exist, the TIFF default, {@link #FORMAT_CHUNKY}, is assumed.</p>
+ *
+ * <ul>
+ * <li>Tag = 284</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * </ul>
+ * <p>
+ *
+ * @see #FORMAT_CHUNKY
+ * @see #FORMAT_PLANAR
+ */
+ public static final String TAG_PLANAR_CONFIGURATION = "PlanarConfiguration";
+ /**
+ * <p>The sampling ratio of chrominance components in relation to the luminance component.
+ * In JPEG compressed data a JPEG marker is used instead of this tag. So, this tag shall not
+ * be recorded.</p>
+ *
+ * <ul>
+ * <li>Tag = 530</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 2</li>
+ * <ul>
+ * <li>[2, 1] = YCbCr4:2:2</li>
+ * <li>[2, 2] = YCbCr4:2:0</li>
+ * <li>Other = reserved</li>
+ * </ul>
+ * </ul>
+ */
+ public static final String TAG_Y_CB_CR_SUB_SAMPLING = "YCbCrSubSampling";
+ /**
+ * <p>The position of chrominance components in relation to the luminance component. This field
+ * is designated only for JPEG compressed data or uncompressed YCbCr data. The TIFF default is
+ * {@link #Y_CB_CR_POSITIONING_CENTERED}; but when Y:Cb:Cr = 4:2:2 it is recommended in this
+ * standard that {@link #Y_CB_CR_POSITIONING_CO_SITED} be used to record data, in order to
+ * improve the image quality when viewed on TV systems. When this field does not exist,
+ * the reader shall assume the TIFF default. In the case of Y:Cb:Cr = 4:2:0, the TIFF default
+ * ({@link #Y_CB_CR_POSITIONING_CENTERED}) is recommended. If the Exif/DCF reader does not
+ * have the capability of supporting both kinds of positioning, it shall follow the TIFF
+ * default regardless of the value in this field. It is preferable that readers can support
+ * both centered and co-sited positioning.</p>
+ *
+ * <ul>
+ * <li>Tag = 531</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #Y_CB_CR_POSITIONING_CENTERED}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #Y_CB_CR_POSITIONING_CENTERED
+ * @see #Y_CB_CR_POSITIONING_CO_SITED
+ */
+ public static final String TAG_Y_CB_CR_POSITIONING = "YCbCrPositioning";
+ /**
+ * <p>The number of pixels per {@link #TAG_RESOLUTION_UNIT} in the {@link #TAG_IMAGE_WIDTH}
+ * direction. When the image resolution is unknown, 72 [dpi] shall be designated.</p>
+ *
+ * <ul>
+ * <li>Tag = 282</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = 72</li>
+ * </ul>
+ * <p>
+ *
+ * @see #TAG_Y_RESOLUTION
+ * @see #TAG_RESOLUTION_UNIT
+ */
+ public static final String TAG_X_RESOLUTION = "XResolution";
+ /**
+ * <p>The number of pixels per {@link #TAG_RESOLUTION_UNIT} in the {@link #TAG_IMAGE_WIDTH}
+ * direction. The same value as {@link #TAG_X_RESOLUTION} shall be designated.</p>
+ *
+ * <ul>
+ * <li>Tag = 283</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = 72</li>
+ * </ul>
+ * <p>
+ *
+ * @see #TAG_X_RESOLUTION
+ * @see #TAG_RESOLUTION_UNIT
+ */
+ public static final String TAG_Y_RESOLUTION = "YResolution";
+ /**
+ * <p>The unit for measuring {@link #TAG_X_RESOLUTION} and {@link #TAG_Y_RESOLUTION}. The same
+ * unit is used for both {@link #TAG_X_RESOLUTION} and {@link #TAG_Y_RESOLUTION}. If the image
+ * resolution is unknown, {@link #RESOLUTION_UNIT_INCHES} shall be designated.</p>
+ *
+ * <ul>
+ * <li>Tag = 296</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #RESOLUTION_UNIT_INCHES}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #RESOLUTION_UNIT_INCHES
+ * @see #RESOLUTION_UNIT_CENTIMETERS
+ * @see #TAG_X_RESOLUTION
+ * @see #TAG_Y_RESOLUTION
+ */
+ public static final String TAG_RESOLUTION_UNIT = "ResolutionUnit";
+
+ // B. Tags related to recording offset
+ /**
+ * <p>For each strip, the byte offset of that strip. It is recommended that this be selected
+ * so the number of strip bytes does not exceed 64 KBytes.In the case of JPEG compressed data,
+ * this designation is not necessary. So, this tag shall not be recorded.</p>
+ *
+ * <ul>
+ * <li>Tag = 273</li>
+ * <li>Type = Unsigned short or Unsigned long</li>
+ * <li>Count = StripsPerImage (for {@link #FORMAT_CHUNKY})
+ * or {@link #TAG_SAMPLES_PER_PIXEL} * StripsPerImage
+ * (for {@link #FORMAT_PLANAR})</li>
+ * <li>Default = None</li>
+ * </ul>
+ *
+ * <p>StripsPerImage = floor(({@link #TAG_IMAGE_LENGTH} + {@link #TAG_ROWS_PER_STRIP} - 1)
+ * / {@link #TAG_ROWS_PER_STRIP})</p>
+ * <p>
+ *
+ * @see #TAG_ROWS_PER_STRIP
+ * @see #TAG_STRIP_BYTE_COUNTS
+ */
+ public static final String TAG_STRIP_OFFSETS = "StripOffsets";
+ /**
+ * <p>The number of rows per strip. This is the number of rows in the image of one strip when
+ * an image is divided into strips. In the case of JPEG compressed data, this designation is
+ * not necessary. So, this tag shall not be recorded.</p>
+ *
+ * <ul>
+ * <li>Tag = 278</li>
+ * <li>Type = Unsigned short or Unsigned long</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #TAG_STRIP_OFFSETS
+ * @see #TAG_STRIP_BYTE_COUNTS
+ */
+ public static final String TAG_ROWS_PER_STRIP = "RowsPerStrip";
+ /**
+ * <p>The total number of bytes in each strip. In the case of JPEG compressed data, this
+ * designation is not necessary. So, this tag shall not be recorded.</p>
+ *
+ * <ul>
+ * <li>Tag = 279</li>
+ * <li>Type = Unsigned short or Unsigned long</li>
+ * <li>Count = StripsPerImage (when using {@link #FORMAT_CHUNKY})
+ * or {@link #TAG_SAMPLES_PER_PIXEL} * StripsPerImage
+ * (when using {@link #FORMAT_PLANAR})</li>
+ * <li>Default = None</li>
+ * </ul>
+ *
+ * <p>StripsPerImage = floor(({@link #TAG_IMAGE_LENGTH} + {@link #TAG_ROWS_PER_STRIP} - 1)
+ * / {@link #TAG_ROWS_PER_STRIP})</p>
+ */
+ public static final String TAG_STRIP_BYTE_COUNTS = "StripByteCounts";
+ /**
+ * <p>The offset to the start byte (SOI) of JPEG compressed thumbnail data. This shall not be
+ * used for primary image JPEG data.</p>
+ *
+ * <ul>
+ * <li>Tag = 513</li>
+ * <li>Type = Unsigned long</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_JPEG_INTERCHANGE_FORMAT = "JPEGInterchangeFormat";
+ /**
+ * <p>The number of bytes of JPEG compressed thumbnail data. This is not used for primary image
+ * JPEG data. JPEG thumbnails are not divided but are recorded as a continuous JPEG bitstream
+ * from SOI to EOI. APPn and COM markers should not be recorded. Compressed thumbnails shall be
+ * recorded in no more than 64 KBytes, including all other data to be recorded in APP1.</p>
+ *
+ * <ul>
+ * <li>Tag = 514</li>
+ * <li>Type = Unsigned long</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_JPEG_INTERCHANGE_FORMAT_LENGTH = "JPEGInterchangeFormatLength";
+
+ // C. Tags related to Image Data Characteristics
+ /**
+ * <p>A transfer function for the image, described in tabular style. Normally this tag need not
+ * be used, since color space is specified in {@link #TAG_COLOR_SPACE}.</p>
+ *
+ * <ul>
+ * <li>Tag = 301</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 3 * 256</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_TRANSFER_FUNCTION = "TransferFunction";
+ /**
+ * <p>The chromaticity of the white point of the image. Normally this tag need not be used,
+ * since color space is specified in {@link #TAG_COLOR_SPACE}.</p>
+ *
+ * <ul>
+ * <li>Tag = 318</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 2</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_WHITE_POINT = "WhitePoint";
+ /**
+ * <p>The chromaticity of the three primary colors of the image. Normally this tag need not
+ * be used, since color space is specified in {@link #TAG_COLOR_SPACE}.</p>
+ *
+ * <ul>
+ * <li>Tag = 319</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 6</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_PRIMARY_CHROMATICITIES = "PrimaryChromaticities";
+ /**
+ * <p>The matrix coefficients for transformation from RGB to YCbCr image data. About
+ * the default value, please refer to JEITA CP-3451C Spec, Annex D.</p>
+ *
+ * <ul>
+ * <li>Tag = 529</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 3</li>
+ * </ul>
+ */
+ public static final String TAG_Y_CB_CR_COEFFICIENTS = "YCbCrCoefficients";
+ /**
+ * <p>The reference black point value and reference white point value. No defaults are given
+ * in TIFF, but the values below are given as defaults here. The color space is declared in
+ * a color space information tag, with the default being the value that gives the optimal image
+ * characteristics Interoperability these conditions</p>
+ *
+ * <ul>
+ * <li>Tag = 532</li>
+ * <li>Type = RATIONAL</li>
+ * <li>Count = 6</li>
+ * <li>Default = [0, 255, 0, 255, 0, 255] (when {@link #TAG_PHOTOMETRIC_INTERPRETATION}
+ * is {@link #PHOTOMETRIC_INTERPRETATION_RGB})
+ * or [0, 255, 0, 128, 0, 128] (when {@link #TAG_PHOTOMETRIC_INTERPRETATION}
+ * is {@link #PHOTOMETRIC_INTERPRETATION_YCBCR})</li>
+ * </ul>
+ */
+ public static final String TAG_REFERENCE_BLACK_WHITE = "ReferenceBlackWhite";
+
+ // D. Other tags
+ /**
+ * <p>The date and time of image creation. In this standard it is the date and time the file
+ * was changed. The format is "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and
+ * the date and time separated by one blank character ({@code 0x20}). When the date and time
+ * are unknown, all the character spaces except colons (":") should be filled with blank
+ * characters, or else the Interoperability field should be filled with blank characters.
+ * The character string length is 20 Bytes including NULL for termination. When the field is
+ * left blank, it is treated as unknown.</p>
+ *
+ * <ul>
+ * <li>Tag = 306</li>
+ * <li>Type = String</li>
+ * <li>Length = 19</li>
+ * <li>Default = None</li>
+ * </ul>
+ *
+ * <p>Note: The format "YYYY-MM-DD HH:MM:SS" is also supported for reading. For writing,
+ * however, calling {@link #setAttribute(String, String)} with the "YYYY-MM-DD HH:MM:SS"
+ * format will automatically convert it to the primary format, "YYYY:MM:DD HH:MM:SS".
+ */
+ public static final String TAG_DATETIME = "DateTime";
+ /**
+ * <p>An ASCII string giving the title of the image. It is possible to be added a comment
+ * such as "1988 company picnic" or the like. Two-byte character codes cannot be used. When
+ * a 2-byte code is necessary, {@link #TAG_USER_COMMENT} is to be used.</p>
+ *
+ * <ul>
+ * <li>Tag = 270</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_IMAGE_DESCRIPTION = "ImageDescription";
+ /**
+ * <p>The manufacturer of the recording equipment. This is the manufacturer of the DSC,
+ * scanner, video digitizer or other equipment that generated the image. When the field is left
+ * blank, it is treated as unknown.</p>
+ *
+ * <ul>
+ * <li>Tag = 271</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_MAKE = "Make";
+ /**
+ * <p>The model name or model number of the equipment. This is the model name of number of
+ * the DSC, scanner, video digitizer or other equipment that generated the image. When
+ * the field is left blank, it is treated as unknown.</p>
+ *
+ * <ul>
+ * <li>Tag = 272</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_MODEL = "Model";
+ /**
+ * <p>This tag records the name and version of the software or firmware of the camera or image
+ * input device used to generate the image. The detailed format is not specified, but it is
+ * recommended that the example shown below be followed. When the field is left blank, it is
+ * treated as unknown.</p>
+ *
+ * <p>Ex.) "Exif Software Version 1.00a".</p>
+ *
+ * <ul>
+ * <li>Tag = 305</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_SOFTWARE = "Software";
+ /**
+ * <p>This tag records the name of the camera owner, photographer or image creator.
+ * The detailed format is not specified, but it is recommended that the information be written
+ * as in the example below for ease of Interoperability. When the field is left blank, it is
+ * treated as unknown.</p>
+ *
+ * <p>Ex.) "Camera owner, John Smith; Photographer, Michael Brown; Image creator,
+ * Ken James"</p>
+ *
+ * <ul>
+ * <li>Tag = 315</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_ARTIST = "Artist";
+ /**
+ * <p>Copyright information. In this standard the tag is used to indicate both the photographer
+ * and editor copyrights. It is the copyright notice of the person or organization claiming
+ * rights to the image. The Interoperability copyright statement including date and rights
+ * should be written in this field; e.g., "Copyright, John Smith, 19xx. All rights reserved."
+ * In this standard the field records both the photographer and editor copyrights, with each
+ * recorded in a separate part of the statement. When there is a clear distinction between
+ * the photographer and editor copyrights, these are to be written in the order of photographer
+ * followed by editor copyright, separated by NULL (in this case, since the statement also ends
+ * with a NULL, there are two NULL codes) (see example 1). When only the photographer copyright
+ * is given, it is terminated by one NULL code (see example 2). When only the editor copyright
+ * is given, the photographer copyright part consists of one space followed by a terminating
+ * NULL code, then the editor copyright is given (see example 3). When the field is left blank,
+ * it is treated as unknown.</p>
+ *
+ * <p>Ex. 1) When both the photographer copyright and editor copyright are given.
+ * <ul><li>Photographer copyright + NULL + editor copyright + NULL</li></ul></p>
+ * <p>Ex. 2) When only the photographer copyright is given.
+ * <ul><li>Photographer copyright + NULL</li></ul></p>
+ * <p>Ex. 3) When only the editor copyright is given.
+ * <ul><li>Space ({@code 0x20}) + NULL + editor copyright + NULL</li></ul></p>
+ *
+ * <ul>
+ * <li>Tag = 315</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_COPYRIGHT = "Copyright";
+
+ // Exif IFD Attribute Information
+ // A. Tags related to version
+ /**
+ * <p>The version of this standard supported. Nonexistence of this field is taken to mean
+ * nonconformance to the standard. In according with conformance to this standard, this tag
+ * shall be recorded like "0230” as 4-byte ASCII.</p>
+ *
+ * <ul>
+ * <li>Tag = 36864</li>
+ * <li>Type = Undefined</li>
+ * <li>Length = 4</li>
+ * <li>Default = "0230"</li>
+ * </ul>
+ */
+ public static final String TAG_EXIF_VERSION = "ExifVersion";
+ /**
+ * <p>The Flashpix format version supported by a FPXR file. If the FPXR function supports
+ * Flashpix format Ver. 1.0, this is indicated similarly to {@link #TAG_EXIF_VERSION} by
+ * recording "0100" as 4-byte ASCII.</p>
+ *
+ * <ul>
+ * <li>Tag = 40960</li>
+ * <li>Type = Undefined</li>
+ * <li>Length = 4</li>
+ * <li>Default = "0100"</li>
+ * </ul>
+ */
+ public static final String TAG_FLASHPIX_VERSION = "FlashpixVersion";
+
+ // B. Tags related to image data characteristics
+ /**
+ * <p>The color space information tag is always recorded as the color space specifier.
+ * Normally {@link #COLOR_SPACE_S_RGB} is used to define the color space based on the PC
+ * monitor conditions and environment. If a color space other than {@link #COLOR_SPACE_S_RGB}
+ * is used, {@link #COLOR_SPACE_UNCALIBRATED} is set. Image data recorded as
+ * {@link #COLOR_SPACE_UNCALIBRATED} may be treated as {@link #COLOR_SPACE_S_RGB} when it is
+ * converted to Flashpix.</p>
+ *
+ * <ul>
+ * <li>Tag = 40961</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * </ul>
+ * <p>
+ *
+ * @see #COLOR_SPACE_S_RGB
+ * @see #COLOR_SPACE_UNCALIBRATED
+ */
+ public static final String TAG_COLOR_SPACE = "ColorSpace";
+ /**
+ * <p>Indicates the value of coefficient gamma. The formula of transfer function used for image
+ * reproduction is expressed as follows.</p>
+ *
+ * <p>(Reproduced value) = (Input value) ^ gamma</p>
+ *
+ * <p>Both reproduced value and input value indicate normalized value, whose minimum value is
+ * 0 and maximum value is 1.</p>
+ *
+ * <ul>
+ * <li>Tag = 42240</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GAMMA = "Gamma";
+
+ // C. Tags related to image configuration
+ /**
+ * <p>Information specific to compressed data. When a compressed file is recorded, the valid
+ * width of the meaningful image shall be recorded in this tag, whether or not there is padding
+ * data or a restart marker. This tag shall not exist in an uncompressed file.</p>
+ *
+ * <ul>
+ * <li>Tag = 40962</li>
+ * <li>Type = Unsigned short or Unsigned long</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_PIXEL_X_DIMENSION = "PixelXDimension";
+ /**
+ * <p>Information specific to compressed data. When a compressed file is recorded, the valid
+ * height of the meaningful image shall be recorded in this tag, whether or not there is
+ * padding data or a restart marker. This tag shall not exist in an uncompressed file.
+ * Since data padding is unnecessary in the vertical direction, the number of lines recorded
+ * in this valid image height tag will in fact be the same as that recorded in the SOF.</p>
+ *
+ * <ul>
+ * <li>Tag = 40963</li>
+ * <li>Type = Unsigned short or Unsigned long</li>
+ * <li>Count = 1</li>
+ * </ul>
+ */
+ public static final String TAG_PIXEL_Y_DIMENSION = "PixelYDimension";
+ /**
+ * <p>Information specific to compressed data. The channels of each component are arranged
+ * in order from the 1st component to the 4th. For uncompressed data the data arrangement is
+ * given in the {@link #TAG_PHOTOMETRIC_INTERPRETATION}. However, since
+ * {@link #TAG_PHOTOMETRIC_INTERPRETATION} can only express the order of Y, Cb and Cr, this tag
+ * is provided for cases when compressed data uses components other than Y, Cb, and Cr and to
+ * enable support of other sequences.</p>
+ *
+ * <ul>
+ * <li>Tag = 37121</li>
+ * <li>Type = Undefined</li>
+ * <li>Length = 4</li>
+ * <li>Default = 4 5 6 0 (if RGB uncompressed) or 1 2 3 0 (other cases)</li>
+ * <ul>
+ * <li>0 = does not exist</li>
+ * <li>1 = Y</li>
+ * <li>2 = Cb</li>
+ * <li>3 = Cr</li>
+ * <li>4 = R</li>
+ * <li>5 = G</li>
+ * <li>6 = B</li>
+ * <li>other = reserved</li>
+ * </ul>
+ * </ul>
+ */
+ public static final String TAG_COMPONENTS_CONFIGURATION = "ComponentsConfiguration";
+ /**
+ * <p>Information specific to compressed data. The compression mode used for a compressed image
+ * is indicated in unit bits per pixel.</p>
+ *
+ * <ul>
+ * <li>Tag = 37122</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_COMPRESSED_BITS_PER_PIXEL = "CompressedBitsPerPixel";
+
+ // D. Tags related to user information
+ /**
+ * <p>A tag for manufacturers of Exif/DCF writers to record any desired information.
+ * The contents are up to the manufacturer, but this tag shall not be used for any other than
+ * its intended purpose.</p>
+ *
+ * <ul>
+ * <li>Tag = 37500</li>
+ * <li>Type = Undefined</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_MAKER_NOTE = "MakerNote";
+ /**
+ * <p>A tag for Exif users to write keywords or comments on the image besides those in
+ * {@link #TAG_IMAGE_DESCRIPTION}, and without the character code limitations of it.</p>
+ *
+ * <ul>
+ * <li>Tag = 37510</li>
+ * <li>Type = Undefined</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_USER_COMMENT = "UserComment";
+
+ // E. Tags related to related file information
+ /**
+ * <p>This tag is used to record the name of an audio file related to the image data. The only
+ * relational information recorded here is the Exif audio file name and extension (an ASCII
+ * string consisting of 8 characters + '.' + 3 characters). The path is not recorded.</p>
+ *
+ * <p>When using this tag, audio files shall be recorded in conformance to the Exif audio
+ * format. Writers can also store the data such as Audio within APP2 as Flashpix extension
+ * stream data. Audio files shall be recorded in conformance to the Exif audio format.</p>
+ *
+ * <ul>
+ * <li>Tag = 40964</li>
+ * <li>Type = String</li>
+ * <li>Length = 12</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_RELATED_SOUND_FILE = "RelatedSoundFile";
+
+ // F. Tags related to date and time
+ /**
+ * <p>The date and time when the original image data was generated. For a DSC the date and time
+ * the picture was taken are recorded. The format is "YYYY:MM:DD HH:MM:SS" with time shown in
+ * 24-hour format, and the date and time separated by one blank character ({@code 0x20}).
+ * When the date and time are unknown, all the character spaces except colons (":") should be
+ * filled with blank characters, or else the Interoperability field should be filled with blank
+ * characters. When the field is left blank, it is treated as unknown.</p>
+ *
+ * <ul>
+ * <li>Tag = 36867</li>
+ * <li>Type = String</li>
+ * <li>Length = 19</li>
+ * <li>Default = None</li>
+ * </ul>
+ *
+ * <p>Note: The format "YYYY-MM-DD HH:MM:SS" is also supported for reading. For writing,
+ * however, calling {@link #setAttribute(String, String)} with the "YYYY-MM-DD HH:MM:SS"
+ * format will automatically convert it to the primary format, "YYYY:MM:DD HH:MM:SS".
+ */
+ public static final String TAG_DATETIME_ORIGINAL = "DateTimeOriginal";
+ /**
+ * <p>The date and time when the image was stored as digital data. If, for example, an image
+ * was captured by DSC and at the same time the file was recorded, then
+ * {@link #TAG_DATETIME_ORIGINAL} and this tag will have the same contents. The format is
+ * "YYYY:MM:DD HH:MM:SS" with time shown in 24-hour format, and the date and time separated by
+ * one blank character ({@code 0x20}). When the date and time are unknown, all the character
+ * spaces except colons (":")should be filled with blank characters, or else
+ * the Interoperability field should be filled with blank characters. When the field is left
+ * blank, it is treated as unknown.</p>
+ *
+ * <ul>
+ * <li>Tag = 36868</li>
+ * <li>Type = String</li>
+ * <li>Length = 19</li>
+ * <li>Default = None</li>
+ * </ul>
+ *
+ * <p>Note: The format "YYYY-MM-DD HH:MM:SS" is also supported for reading. For writing,
+ * however, calling {@link #setAttribute(String, String)} with the "YYYY-MM-DD HH:MM:SS"
+ * format will automatically convert it to the primary format, "YYYY:MM:DD HH:MM:SS".
+ */
+ public static final String TAG_DATETIME_DIGITIZED = "DateTimeDigitized";
+ /**
+ * <p>A tag used to record the offset from UTC (the time difference from Universal Time
+ * Coordinated including daylight saving time) of the time of DateTime tag. The format when
+ * recording the offset is "±HH:MM". The part of "±" shall be recorded as "+" or "-". When
+ * the offsets are unknown, all the character spaces except colons (":") should be filled
+ * with blank characters, or else the Interoperability field should be filled with blank
+ * characters. The character string length is 7 Bytes including NULL for termination. When
+ * the field is left blank, it is treated as unknown.</p>
+ *
+ * <ul>
+ * <li>Tag = 36880</li>
+ * <li>Type = String</li>
+ * <li>Length = 7</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_OFFSET_TIME = "OffsetTime";
+ /**
+ * <p>A tag used to record the offset from UTC (the time difference from Universal Time
+ * Coordinated including daylight saving time) of the time of DateTimeOriginal tag. The format
+ * when recording the offset is "±HH:MM". The part of "±" shall be recorded as "+" or "-". When
+ * the offsets are unknown, all the character spaces except colons (":") should be filled
+ * with blank characters, or else the Interoperability field should be filled with blank
+ * characters. The character string length is 7 Bytes including NULL for termination. When
+ * the field is left blank, it is treated as unknown.</p>
+ *
+ * <ul>
+ * <li>Tag = 36881</li>
+ * <li>Type = String</li>
+ * <li>Length = 7</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_OFFSET_TIME_ORIGINAL = "OffsetTimeOriginal";
+ /**
+ * <p>A tag used to record the offset from UTC (the time difference from Universal Time
+ * Coordinated including daylight saving time) of the time of DateTimeDigitized tag. The format
+ * when recording the offset is "±HH:MM". The part of "±" shall be recorded as "+" or "-". When
+ * the offsets are unknown, all the character spaces except colons (":") should be filled
+ * with blank characters, or else the Interoperability field should be filled with blank
+ * characters. The character string length is 7 Bytes including NULL for termination. When
+ * the field is left blank, it is treated as unknown.</p>
+ *
+ * <ul>
+ * <li>Tag = 36882</li>
+ * <li>Type = String</li>
+ * <li>Length = 7</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_OFFSET_TIME_DIGITIZED = "OffsetTimeDigitized";
+ /**
+ * <p>A tag used to record fractions of seconds for {@link #TAG_DATETIME}.</p>
+ *
+ * <ul>
+ * <li>Tag = 37520</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_SUBSEC_TIME = "SubSecTime";
+ /**
+ * <p>A tag used to record fractions of seconds for {@link #TAG_DATETIME_ORIGINAL}.</p>
+ *
+ * <ul>
+ * <li>Tag = 37521</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_SUBSEC_TIME_ORIGINAL = "SubSecTimeOriginal";
+ /**
+ * <p>A tag used to record fractions of seconds for {@link #TAG_DATETIME_DIGITIZED}.</p>
+ *
+ * <ul>
+ * <li>Tag = 37522</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_SUBSEC_TIME_DIGITIZED = "SubSecTimeDigitized";
+
+ // G. Tags related to picture-taking condition
+ /**
+ * Exposure time, given in seconds.
+ *
+ * <p>Note: For backwards compatibility this attribute is returned from {@link
+ * #getAttribute(String)} in decimal form (i.e. the format produced by {@link
+ * Double#toString(double)}). It is accepted into {@link #setAttribute(String, String)} in both
+ * rational (e.g. {@code "1/3"}) and decimal forms. The decimal format is anything accepted by
+ * {@link Double#parseDouble(String)}, e.g. {@code "0.125"}.
+ *
+ * <ul>
+ * <li>Tag = 33434
+ * <li>Type = Unsigned rational
+ * <li>Count = 1
+ * <li>Default = None
+ * </ul>
+ */
+ public static final String TAG_EXPOSURE_TIME = "ExposureTime";
+
+ /**
+ * The F number.
+ *
+ * <p>Note: For backwards compatibility this attribute is returned from {@link
+ * #getAttribute(String)} in decimal form (i.e. the format produced by {@link
+ * Double#toString(double)}). It is accepted into {@link #setAttribute(String, String)} in both
+ * rational (e.g. {@code "1/3"}) and decimal forms. The decimal format is anything accepted by
+ * {@link Double#parseDouble(String)}, e.g. {@code "0.125"}.
+ *
+ * <ul>
+ * <li>Tag = 33437
+ * <li>Type = Unsigned rational
+ * <li>Count = 1
+ * <li>Default = None
+ * </ul>
+ */
+ public static final String TAG_F_NUMBER = "FNumber";
+
+ /**
+ * <p>The class of the program used by the camera to set exposure when the picture is taken.
+ * The tag values are as follows.</p>
+ *
+ * <ul>
+ * <li>Tag = 34850</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #EXPOSURE_PROGRAM_NOT_DEFINED}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #EXPOSURE_PROGRAM_NOT_DEFINED
+ * @see #EXPOSURE_PROGRAM_MANUAL
+ * @see #EXPOSURE_PROGRAM_NORMAL
+ * @see #EXPOSURE_PROGRAM_APERTURE_PRIORITY
+ * @see #EXPOSURE_PROGRAM_SHUTTER_PRIORITY
+ * @see #EXPOSURE_PROGRAM_CREATIVE
+ * @see #EXPOSURE_PROGRAM_ACTION
+ * @see #EXPOSURE_PROGRAM_PORTRAIT_MODE
+ * @see #EXPOSURE_PROGRAM_LANDSCAPE_MODE
+ */
+ public static final String TAG_EXPOSURE_PROGRAM = "ExposureProgram";
+ /**
+ * <p>Indicates the spectral sensitivity of each channel of the camera used. The tag value is
+ * an ASCII string compatible with the standard developed by the ASTM Technical committee.</p>
+ *
+ * <ul>
+ * <li>Tag = 34852</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_SPECTRAL_SENSITIVITY = "SpectralSensitivity";
+ /**
+ * @see #TAG_PHOTOGRAPHIC_SENSITIVITY
+ * @deprecated Use {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} instead.
+ */
+ @Deprecated
+ public static final String TAG_ISO_SPEED_RATINGS = "ISOSpeedRatings";
+ /**
+ * <p>This tag indicates the sensitivity of the camera or input device when the image was shot.
+ * More specifically, it indicates one of the following values that are parameters defined in
+ * ISO 12232: standard output sensitivity (SOS), recommended exposure index (REI), or ISO
+ * speed. Accordingly, if a tag corresponding to a parameter that is designated by
+ * {@link #TAG_SENSITIVITY_TYPE} is recorded, the values of the tag and of this tag are
+ * the same. However, if the value is 65535 or higher, the value of this tag shall be 65535.
+ * When recording this tag, {@link #TAG_SENSITIVITY_TYPE} should also be recorded. In addition,
+ * while “Count = Any”, only 1 count should be used when recording this tag.</p>
+ *
+ * <ul>
+ * <li>Tag = 34855</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = Any</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_PHOTOGRAPHIC_SENSITIVITY = "PhotographicSensitivity";
+ /**
+ * <p>Indicates the Opto-Electric Conversion Function (OECF) specified in ISO 14524. OECF is
+ * the relationship between the camera optical input and the image values.</p>
+ *
+ * <ul>
+ * <li>Tag = 34856</li>
+ * <li>Type = Undefined</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_OECF = "OECF";
+ /**
+ * <p>This tag indicates which one of the parameters of ISO12232 is
+ * {@link #TAG_PHOTOGRAPHIC_SENSITIVITY}. Although it is an optional tag, it should be recorded
+ * when {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} is recorded.</p>
+ *
+ * <ul>
+ * <li>Tag = 34864</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #SENSITIVITY_TYPE_UNKNOWN
+ * @see #SENSITIVITY_TYPE_SOS
+ * @see #SENSITIVITY_TYPE_REI
+ * @see #SENSITIVITY_TYPE_ISO_SPEED
+ * @see #SENSITIVITY_TYPE_SOS_AND_REI
+ * @see #SENSITIVITY_TYPE_SOS_AND_ISO
+ * @see #SENSITIVITY_TYPE_REI_AND_ISO
+ * @see #SENSITIVITY_TYPE_SOS_AND_REI_AND_ISO
+ */
+ public static final String TAG_SENSITIVITY_TYPE = "SensitivityType";
+ /**
+ * <p>This tag indicates the standard output sensitivity value of a camera or input device
+ * defined in ISO 12232. When recording this tag, {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} and
+ * {@link #TAG_SENSITIVITY_TYPE} shall also be recorded.</p>
+ *
+ * <ul>
+ * <li>Tag = 34865</li>
+ * <li>Type = Unsigned long</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_STANDARD_OUTPUT_SENSITIVITY = "StandardOutputSensitivity";
+ /**
+ * <p>This tag indicates the recommended exposure index value of a camera or input device
+ * defined in ISO 12232. When recording this tag, {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} and
+ * {@link #TAG_SENSITIVITY_TYPE} shall also be recorded.</p>
+ *
+ * <ul>
+ * <li>Tag = 34866</li>
+ * <li>Type = Unsigned long</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_RECOMMENDED_EXPOSURE_INDEX = "RecommendedExposureIndex";
+ /**
+ * <p>This tag indicates the ISO speed value of a camera or input device that is defined in
+ * ISO 12232. When recording this tag, {@link #TAG_PHOTOGRAPHIC_SENSITIVITY} and
+ * {@link #TAG_SENSITIVITY_TYPE} shall also be recorded.</p>
+ *
+ * <ul>
+ * <li>Tag = 34867</li>
+ * <li>Type = Unsigned long</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_ISO_SPEED = "ISOSpeed";
+ /**
+ * <p>This tag indicates the ISO speed latitude yyy value of a camera or input device that is
+ * defined in ISO 12232. However, this tag shall not be recorded without {@link #TAG_ISO_SPEED}
+ * and {@link #TAG_ISO_SPEED_LATITUDE_ZZZ}.</p>
+ *
+ * <ul>
+ * <li>Tag = 34868</li>
+ * <li>Type = Unsigned long</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_ISO_SPEED_LATITUDE_YYY = "ISOSpeedLatitudeyyy";
+ /**
+ * <p>This tag indicates the ISO speed latitude zzz value of a camera or input device that is
+ * defined in ISO 12232. However, this tag shall not be recorded without {@link #TAG_ISO_SPEED}
+ * and {@link #TAG_ISO_SPEED_LATITUDE_YYY}.</p>
+ *
+ * <ul>
+ * <li>Tag = 34869</li>
+ * <li>Type = Unsigned long</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_ISO_SPEED_LATITUDE_ZZZ = "ISOSpeedLatitudezzz";
+ /**
+ * <p>Shutter speed. The unit is the APEX setting.</p>
+ *
+ * <ul>
+ * <li>Tag = 37377</li>
+ * <li>Type = Signed rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_SHUTTER_SPEED_VALUE = "ShutterSpeedValue";
+ /**
+ * <p>The lens aperture. The unit is the APEX value.</p>
+ *
+ * <ul>
+ * <li>Tag = 37378</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_APERTURE_VALUE = "ApertureValue";
+ /**
+ * <p>The value of brightness. The unit is the APEX value. Ordinarily it is given in the range
+ * of -99.99 to 99.99. Note that if the numerator of the recorded value is 0xFFFFFFFF,
+ * Unknown shall be indicated.</p>
+ *
+ * <ul>
+ * <li>Tag = 37379</li>
+ * <li>Type = Signed rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_BRIGHTNESS_VALUE = "BrightnessValue";
+ /**
+ * <p>The exposure bias. The unit is the APEX value. Ordinarily it is given in the range of
+ * -99.99 to 99.99.</p>
+ *
+ * <ul>
+ * <li>Tag = 37380</li>
+ * <li>Type = Signed rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_EXPOSURE_BIAS_VALUE = "ExposureBiasValue";
+ /**
+ * <p>The smallest F number of the lens. The unit is the APEX value. Ordinarily it is given
+ * in the range of 00.00 to 99.99, but it is not limited to this range.</p>
+ *
+ * <ul>
+ * <li>Tag = 37381</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_MAX_APERTURE_VALUE = "MaxApertureValue";
+
+ /**
+ * The distance to the subject, given in meters.
+ *
+ * <p>Note that if the numerator of the recorded value is 0xFFFFFFFF, Infinity shall be
+ * indicated; and if the numerator is 0, Distance unknown shall be indicated.
+ *
+ * <p>Note: For backwards compatibility this attribute is returned from {@link
+ * #getAttribute(String)} in decimal form (i.e. the format produced by {@link
+ * Double#toString(double)}). It is accepted into {@link #setAttribute(String, String)} in both
+ * rational (e.g. {@code "1/3"}) and decimal forms. The decimal format is anything accepted by
+ * {@link Double#parseDouble(String)}, e.g. {@code "0.125"}.
+ *
+ * <ul>
+ * <li>Tag = 37382
+ * <li>Type = Unsigned rational
+ * <li>Count = 1
+ * <li>Default = None
+ * </ul>
+ */
+ public static final String TAG_SUBJECT_DISTANCE = "SubjectDistance";
+
+ /**
+ * <p>The metering mode.</p>
+ *
+ * <ul>
+ * <li>Tag = 37383</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #METERING_MODE_UNKNOWN}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #METERING_MODE_UNKNOWN
+ * @see #METERING_MODE_AVERAGE
+ * @see #METERING_MODE_CENTER_WEIGHT_AVERAGE
+ * @see #METERING_MODE_SPOT
+ * @see #METERING_MODE_MULTI_SPOT
+ * @see #METERING_MODE_PATTERN
+ * @see #METERING_MODE_PARTIAL
+ * @see #METERING_MODE_OTHER
+ */
+ public static final String TAG_METERING_MODE = "MeteringMode";
+ /**
+ * <p>The kind of light source.</p>
+ *
+ * <ul>
+ * <li>Tag = 37384</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #LIGHT_SOURCE_UNKNOWN}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #LIGHT_SOURCE_UNKNOWN
+ * @see #LIGHT_SOURCE_DAYLIGHT
+ * @see #LIGHT_SOURCE_FLUORESCENT
+ * @see #LIGHT_SOURCE_TUNGSTEN
+ * @see #LIGHT_SOURCE_FLASH
+ * @see #LIGHT_SOURCE_FINE_WEATHER
+ * @see #LIGHT_SOURCE_CLOUDY_WEATHER
+ * @see #LIGHT_SOURCE_SHADE
+ * @see #LIGHT_SOURCE_DAYLIGHT_FLUORESCENT
+ * @see #LIGHT_SOURCE_DAY_WHITE_FLUORESCENT
+ * @see #LIGHT_SOURCE_COOL_WHITE_FLUORESCENT
+ * @see #LIGHT_SOURCE_WHITE_FLUORESCENT
+ * @see #LIGHT_SOURCE_WARM_WHITE_FLUORESCENT
+ * @see #LIGHT_SOURCE_STANDARD_LIGHT_A
+ * @see #LIGHT_SOURCE_STANDARD_LIGHT_B
+ * @see #LIGHT_SOURCE_STANDARD_LIGHT_C
+ * @see #LIGHT_SOURCE_D55
+ * @see #LIGHT_SOURCE_D65
+ * @see #LIGHT_SOURCE_D75
+ * @see #LIGHT_SOURCE_D50
+ * @see #LIGHT_SOURCE_ISO_STUDIO_TUNGSTEN
+ * @see #LIGHT_SOURCE_OTHER
+ */
+ public static final String TAG_LIGHT_SOURCE = "LightSource";
+ /**
+ * <p>This tag indicates the status of flash when the image was shot. Bit 0 indicates the flash
+ * firing status, bits 1 and 2 indicate the flash return status, bits 3 and 4 indicate
+ * the flash mode, bit 5 indicates whether the flash function is present, and bit 6 indicates
+ * "red eye" mode.</p>
+ *
+ * <ul>
+ * <li>Tag = 37385</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * </ul>
+ * <p>
+ *
+ * @see #FLAG_FLASH_FIRED
+ * @see #FLAG_FLASH_RETURN_LIGHT_NOT_DETECTED
+ * @see #FLAG_FLASH_RETURN_LIGHT_DETECTED
+ * @see #FLAG_FLASH_MODE_COMPULSORY_FIRING
+ * @see #FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION
+ * @see #FLAG_FLASH_MODE_AUTO
+ * @see #FLAG_FLASH_NO_FLASH_FUNCTION
+ * @see #FLAG_FLASH_RED_EYE_SUPPORTED
+ */
+ public static final String TAG_FLASH = "Flash";
+ /**
+ * <p>This tag indicates the location and area of the main subject in the overall scene.</p>
+ *
+ * <ul>
+ * <li>Tag = 37396</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 2 or 3 or 4</li>
+ * <li>Default = None</li>
+ * </ul>
+ *
+ * <p>The subject location and area are defined by Count values as follows.</p>
+ *
+ * <ul>
+ * <li>Count = 2 Indicates the location of the main subject as coordinates. The first value
+ * is the X coordinate and the second is the Y coordinate.</li>
+ * <li>Count = 3 The area of the main subject is given as a circle. The circular area is
+ * expressed as center coordinates and diameter. The first value is
+ * the center X coordinate, the second is the center Y coordinate, and
+ * the third is the diameter.</li>
+ * <li>Count = 4 The area of the main subject is given as a rectangle. The rectangular
+ * area is expressed as center coordinates and area dimensions. The first
+ * value is the center X coordinate, the second is the center Y coordinate,
+ * the third is the width of the area, and the fourth is the height of
+ * the area.</li>
+ * </ul>
+ *
+ * <p>Note that the coordinate values, width, and height are expressed in relation to the upper
+ * left as origin, prior to rotation processing as per {@link #TAG_ORIENTATION}.</p>
+ */
+ public static final String TAG_SUBJECT_AREA = "SubjectArea";
+ /**
+ * <p>The actual focal length of the lens, in mm. Conversion is not made to the focal length
+ * of a 35mm film camera.</p>
+ *
+ * <ul>
+ * <li>Tag = 37386</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_FOCAL_LENGTH = "FocalLength";
+ /**
+ * <p>Indicates the strobe energy at the time the image is captured, as measured in Beam Candle
+ * Power Seconds (BCPS).</p>
+ *
+ * <ul>
+ * <li>Tag = 41483</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_FLASH_ENERGY = "FlashEnergy";
+ /**
+ * <p>This tag records the camera or input device spatial frequency table and SFR values in
+ * the direction of image width, image height, and diagonal direction, as specified in
+ * ISO 12233.</p>
+ *
+ * <ul>
+ * <li>Tag = 41484</li>
+ * <li>Type = Undefined</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_SPATIAL_FREQUENCY_RESPONSE = "SpatialFrequencyResponse";
+ /**
+ * <p>Indicates the number of pixels in the image width (X) direction per
+ * {@link #TAG_FOCAL_PLANE_RESOLUTION_UNIT} on the camera focal plane.</p>
+ *
+ * <ul>
+ * <li>Tag = 41486</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_FOCAL_PLANE_X_RESOLUTION = "FocalPlaneXResolution";
+ /**
+ * <p>Indicates the number of pixels in the image height (Y) direction per
+ * {@link #TAG_FOCAL_PLANE_RESOLUTION_UNIT} on the camera focal plane.</p>
+ *
+ * <ul>
+ * <li>Tag = 41487</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_FOCAL_PLANE_Y_RESOLUTION = "FocalPlaneYResolution";
+ /**
+ * <p>Indicates the unit for measuring {@link #TAG_FOCAL_PLANE_X_RESOLUTION} and
+ * {@link #TAG_FOCAL_PLANE_Y_RESOLUTION}. This value is the same as
+ * {@link #TAG_RESOLUTION_UNIT}.</p>
+ *
+ * <ul>
+ * <li>Tag = 41488</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #RESOLUTION_UNIT_INCHES}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #TAG_RESOLUTION_UNIT
+ * @see #RESOLUTION_UNIT_INCHES
+ * @see #RESOLUTION_UNIT_CENTIMETERS
+ */
+ public static final String TAG_FOCAL_PLANE_RESOLUTION_UNIT = "FocalPlaneResolutionUnit";
+ /**
+ * <p>Indicates the location of the main subject in the scene. The value of this tag represents
+ * the pixel at the center of the main subject relative to the left edge, prior to rotation
+ * processing as per {@link #TAG_ORIENTATION}. The first value indicates the X column number
+ * and second indicates the Y row number. When a camera records the main subject location,
+ * it is recommended that {@link #TAG_SUBJECT_AREA} be used instead of this tag.</p>
+ *
+ * <ul>
+ * <li>Tag = 41492</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 2</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_SUBJECT_LOCATION = "SubjectLocation";
+ /**
+ * <p>Indicates the exposure index selected on the camera or input device at the time the image
+ * is captured.</p>
+ *
+ * <ul>
+ * <li>Tag = 41493</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_EXPOSURE_INDEX = "ExposureIndex";
+ /**
+ * <p>Indicates the image sensor type on the camera or input device.</p>
+ *
+ * <ul>
+ * <li>Tag = 41495</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #SENSOR_TYPE_NOT_DEFINED
+ * @see #SENSOR_TYPE_ONE_CHIP
+ * @see #SENSOR_TYPE_TWO_CHIP
+ * @see #SENSOR_TYPE_THREE_CHIP
+ * @see #SENSOR_TYPE_COLOR_SEQUENTIAL
+ * @see #SENSOR_TYPE_TRILINEAR
+ * @see #SENSOR_TYPE_COLOR_SEQUENTIAL_LINEAR
+ */
+ public static final String TAG_SENSING_METHOD = "SensingMethod";
+ /**
+ * <p>Indicates the image source. If a DSC recorded the image, this tag value always shall
+ * be set to {@link #FILE_SOURCE_DSC}.</p>
+ *
+ * <ul>
+ * <li>Tag = 41728</li>
+ * <li>Type = Undefined</li>
+ * <li>Length = 1</li>
+ * <li>Default = {@link #FILE_SOURCE_DSC}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #FILE_SOURCE_OTHER
+ * @see #FILE_SOURCE_TRANSPARENT_SCANNER
+ * @see #FILE_SOURCE_REFLEX_SCANNER
+ * @see #FILE_SOURCE_DSC
+ */
+ public static final String TAG_FILE_SOURCE = "FileSource";
+ /**
+ * <p>Indicates the type of scene. If a DSC recorded the image, this tag value shall always
+ * be set to {@link #SCENE_TYPE_DIRECTLY_PHOTOGRAPHED}.</p>
+ *
+ * <ul>
+ * <li>Tag = 41729</li>
+ * <li>Type = Undefined</li>
+ * <li>Length = 1</li>
+ * <li>Default = 1</li>
+ * </ul>
+ * <p>
+ *
+ * @see #SCENE_TYPE_DIRECTLY_PHOTOGRAPHED
+ */
+ public static final String TAG_SCENE_TYPE = "SceneType";
+ /**
+ * <p>Indicates the color filter array (CFA) geometric pattern of the image sensor when
+ * a one-chip color area sensor is used. It does not apply to all sensing methods.</p>
+ *
+ * <ul>
+ * <li>Tag = 41730</li>
+ * <li>Type = Undefined</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #TAG_SENSING_METHOD
+ * @see #SENSOR_TYPE_ONE_CHIP
+ */
+ public static final String TAG_CFA_PATTERN = "CFAPattern";
+ /**
+ * <p>This tag indicates the use of special processing on image data, such as rendering geared
+ * to output. When special processing is performed, the Exif/DCF reader is expected to disable
+ * or minimize any further processing.</p>
+ *
+ * <ul>
+ * <li>Tag = 41985</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #RENDERED_PROCESS_NORMAL}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #RENDERED_PROCESS_NORMAL
+ * @see #RENDERED_PROCESS_CUSTOM
+ */
+ public static final String TAG_CUSTOM_RENDERED = "CustomRendered";
+ /**
+ * <p>This tag indicates the exposure mode set when the image was shot.
+ * In {@link #EXPOSURE_MODE_AUTO_BRACKET}, the camera shoots a series of frames of the same
+ * scene at different exposure settings.</p>
+ *
+ * <ul>
+ * <li>Tag = 41986</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #EXPOSURE_MODE_AUTO
+ * @see #EXPOSURE_MODE_MANUAL
+ * @see #EXPOSURE_MODE_AUTO_BRACKET
+ */
+ public static final String TAG_EXPOSURE_MODE = "ExposureMode";
+ /**
+ * <p>This tag indicates the white balance mode set when the image was shot.</p>
+ *
+ * <ul>
+ * <li>Tag = 41987</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #WHITEBALANCE_AUTO
+ * @see #WHITEBALANCE_MANUAL
+ */
+ public static final String TAG_WHITE_BALANCE = "WhiteBalance";
+
+ /**
+ * This tag indicates the digital zoom ratio when the image was shot. If the numerator of the
+ * recorded value is 0, this indicates that digital zoom was not used.
+ *
+ * <p>Note: For backwards compatibility this attribute is returned from {@link
+ * #getAttribute(String)} in decimal form (i.e. the format produced by {@link
+ * Double#toString(double)}). It is accepted into {@link #setAttribute(String, String)} in both
+ * rational (e.g. {@code "1/3"}) and decimal forms. The decimal format is anything accepted by
+ * {@link Double#parseDouble(String)}, e.g. {@code "0.125"}.
+ *
+ * <ul>
+ * <li>Tag = 41988
+ * <li>Type = Unsigned rational
+ * <li>Count = 1
+ * <li>Default = None
+ * </ul>
+ */
+ public static final String TAG_DIGITAL_ZOOM_RATIO = "DigitalZoomRatio";
+
+ /**
+ * <p>This tag indicates the equivalent focal length assuming a 35mm film camera, in mm.
+ * A value of 0 means the focal length is unknown. Note that this tag differs from
+ * {@link #TAG_FOCAL_LENGTH}.</p>
+ *
+ * <ul>
+ * <li>Tag = 41989</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_FOCAL_LENGTH_IN_35MM_FILM = "FocalLengthIn35mmFilm";
+ /**
+ * <p>This tag indicates the type of scene that was shot. It may also be used to record
+ * the mode in which the image was shot. Note that this differs from
+ * {@link #TAG_SCENE_TYPE}.</p>
+ *
+ * <ul>
+ * <li>Tag = 41990</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = 0</li>
+ * </ul>
+ * <p>
+ *
+ * @see #SCENE_CAPTURE_TYPE_STANDARD
+ * @see #SCENE_CAPTURE_TYPE_LANDSCAPE
+ * @see #SCENE_CAPTURE_TYPE_PORTRAIT
+ * @see #SCENE_CAPTURE_TYPE_NIGHT
+ */
+ public static final String TAG_SCENE_CAPTURE_TYPE = "SceneCaptureType";
+ /**
+ * <p>This tag indicates the degree of overall image gain adjustment.</p>
+ *
+ * <ul>
+ * <li>Tag = 41991</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #GAIN_CONTROL_NONE
+ * @see #GAIN_CONTROL_LOW_GAIN_UP
+ * @see #GAIN_CONTROL_HIGH_GAIN_UP
+ * @see #GAIN_CONTROL_LOW_GAIN_DOWN
+ * @see #GAIN_CONTROL_HIGH_GAIN_DOWN
+ */
+ public static final String TAG_GAIN_CONTROL = "GainControl";
+ /**
+ * <p>This tag indicates the direction of contrast processing applied by the camera when
+ * the image was shot.</p>
+ *
+ * <ul>
+ * <li>Tag = 41992</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #CONTRAST_NORMAL}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #CONTRAST_NORMAL
+ * @see #CONTRAST_SOFT
+ * @see #CONTRAST_HARD
+ */
+ public static final String TAG_CONTRAST = "Contrast";
+ /**
+ * <p>This tag indicates the direction of saturation processing applied by the camera when
+ * the image was shot.</p>
+ *
+ * <ul>
+ * <li>Tag = 41993</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #SATURATION_NORMAL}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #SATURATION_NORMAL
+ * @see #SATURATION_LOW
+ * @see #SATURATION_HIGH
+ */
+ public static final String TAG_SATURATION = "Saturation";
+ /**
+ * <p>This tag indicates the direction of sharpness processing applied by the camera when
+ * the image was shot.</p>
+ *
+ * <ul>
+ * <li>Tag = 41994</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = {@link #SHARPNESS_NORMAL}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #SHARPNESS_NORMAL
+ * @see #SHARPNESS_SOFT
+ * @see #SHARPNESS_HARD
+ */
+ public static final String TAG_SHARPNESS = "Sharpness";
+ /**
+ * <p>This tag indicates information on the picture-taking conditions of a particular camera
+ * model. The tag is used only to indicate the picture-taking conditions in the Exif/DCF
+ * reader.</p>
+ *
+ * <ul>
+ * <li>Tag = 41995</li>
+ * <li>Type = Undefined</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_DEVICE_SETTING_DESCRIPTION = "DeviceSettingDescription";
+ /**
+ * <p>This tag indicates the distance to the subject.</p>
+ *
+ * <ul>
+ * <li>Tag = 41996</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #SUBJECT_DISTANCE_RANGE_UNKNOWN
+ * @see #SUBJECT_DISTANCE_RANGE_MACRO
+ * @see #SUBJECT_DISTANCE_RANGE_CLOSE_VIEW
+ * @see #SUBJECT_DISTANCE_RANGE_DISTANT_VIEW
+ */
+ public static final String TAG_SUBJECT_DISTANCE_RANGE = "SubjectDistanceRange";
+
+ // H. Other tags
+ /**
+ * <p>This tag indicates an identifier assigned uniquely to each image. It is recorded as
+ * an ASCII string equivalent to hexadecimal notation and 128-bit fixed length.</p>
+ *
+ * <ul>
+ * <li>Tag = 42016</li>
+ * <li>Type = String</li>
+ * <li>Length = 32</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_IMAGE_UNIQUE_ID = "ImageUniqueID";
+ /**
+ * <p>This tag records the owner of a camera used in photography as an ASCII string.</p>
+ *
+ * <ul>
+ * <li>Tag = 42032</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @deprecated Use {@link #TAG_CAMERA_OWNER_NAME} instead.
+ */
+ @Deprecated
+ public static final String TAG_CAMARA_OWNER_NAME = "CameraOwnerName";
+ /**
+ * <p>This tag records the owner of a camera used in photography as an ASCII string.</p>
+ *
+ * <ul>
+ * <li>Tag = 42032</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_CAMERA_OWNER_NAME = "CameraOwnerName";
+ /**
+ * <p>This tag records the serial number of the body of the camera that was used in photography
+ * as an ASCII string.</p>
+ *
+ * <ul>
+ * <li>Tag = 42033</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_BODY_SERIAL_NUMBER = "BodySerialNumber";
+ /**
+ * <p>This tag notes minimum focal length, maximum focal length, minimum F number in the
+ * minimum focal length, and minimum F number in the maximum focal length, which are
+ * specification information for the lens that was used in photography. When the minimum
+ * F number is unknown, the notation is 0/0.</p>
+ *
+ * <ul>
+ * <li>Tag = 42034</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 4</li>
+ * <li>Default = None</li>
+ * <ul>
+ * <li>Value 1 := Minimum focal length (unit: mm)</li>
+ * <li>Value 2 : = Maximum focal length (unit: mm)</li>
+ * <li>Value 3 : = Minimum F number in the minimum focal length</li>
+ * <li>Value 4 : = Minimum F number in the maximum focal length</li>
+ * </ul>
+ * </ul>
+ */
+ public static final String TAG_LENS_SPECIFICATION = "LensSpecification";
+ /**
+ * <p>This tag records the lens manufacturer as an ASCII string.</p>
+ *
+ * <ul>
+ * <li>Tag = 42035</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_LENS_MAKE = "LensMake";
+ /**
+ * <p>This tag records the lens’s model name and model number as an ASCII string.</p>
+ *
+ * <ul>
+ * <li>Tag = 42036</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_LENS_MODEL = "LensModel";
+ /**
+ * <p>This tag records the serial number of the interchangeable lens that was used in
+ * photography as an ASCII string.</p>
+ *
+ * <ul>
+ * <li>Tag = 42037</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_LENS_SERIAL_NUMBER = "LensSerialNumber";
+
+ // GPS Attribute Information
+ /**
+ * <p>Indicates the version of GPS Info IFD. The version is given as 2.3.0.0. This tag is
+ * mandatory when GPS-related tags are present. Note that this tag is written as a different
+ * byte than {@link #TAG_EXIF_VERSION}.</p>
+ *
+ * <ul>
+ * <li>Tag = 0</li>
+ * <li>Type = Byte</li>
+ * <li>Count = 4</li>
+ * <li>Default = 2.3.0.0</li>
+ * <ul>
+ * <li>2300 = Version 2.3</li>
+ * <li>Other = reserved</li>
+ * </ul>
+ * </ul>
+ */
+ public static final String TAG_GPS_VERSION_ID = "GPSVersionID";
+ /**
+ * <p>Indicates whether the latitude is north or south latitude.</p>
+ *
+ * <ul>
+ * <li>Tag = 1</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #LATITUDE_NORTH
+ * @see #LATITUDE_SOUTH
+ */
+ public static final String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef";
+ /**
+ * <p>Indicates the latitude. The latitude is expressed as three RATIONAL values giving
+ * the degrees, minutes, and seconds, respectively. If latitude is expressed as degrees,
+ * minutes and seconds, a typical format would be dd/1,mm/1,ss/1. When degrees and minutes are
+ * used and, for example, fractions of minutes are given up to two decimal places, the format
+ * would be dd/1,mmmm/100,0/1.</p>
+ *
+ * <ul>
+ * <li>Tag = 2</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 3</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_LATITUDE = "GPSLatitude";
+ /**
+ * <p>Indicates whether the longitude is east or west longitude.</p>
+ *
+ * <ul>
+ * <li>Tag = 3</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #LONGITUDE_EAST
+ * @see #LONGITUDE_WEST
+ */
+ public static final String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef";
+ /**
+ * <p>Indicates the longitude. The longitude is expressed as three RATIONAL values giving
+ * the degrees, minutes, and seconds, respectively. If longitude is expressed as degrees,
+ * minutes and seconds, a typical format would be ddd/1,mm/1,ss/1. When degrees and minutes
+ * are used and, for example, fractions of minutes are given up to two decimal places,
+ * the format would be ddd/1,mmmm/100,0/1.</p>
+ *
+ * <ul>
+ * <li>Tag = 4</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 3</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_LONGITUDE = "GPSLongitude";
+ /**
+ * <p>Indicates the altitude used as the reference altitude. If the reference is sea level
+ * and the altitude is above sea level, 0 is given. If the altitude is below sea level,
+ * a value of 1 is given and the altitude is indicated as an absolute value in
+ * {@link #TAG_GPS_ALTITUDE}.</p>
+ *
+ * <ul>
+ * <li>Tag = 5</li>
+ * <li>Type = Byte</li>
+ * <li>Count = 1</li>
+ * <li>Default = 0</li>
+ * </ul>
+ * <p>
+ *
+ * @see #ALTITUDE_ABOVE_SEA_LEVEL
+ * @see #ALTITUDE_BELOW_SEA_LEVEL
+ */
+ public static final String TAG_GPS_ALTITUDE_REF = "GPSAltitudeRef";
+ /**
+ * <p>Indicates the altitude based on the reference in {@link #TAG_GPS_ALTITUDE_REF}.
+ * The reference unit is meters.</p>
+ *
+ * <ul>
+ * <li>Tag = 6</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_ALTITUDE = "GPSAltitude";
+
+ /**
+ * Indicates the time as UTC (Coordinated Universal Time). TimeStamp is expressed as three
+ * unsigned rational values giving the hour, minute, and second.
+ *
+ * <p>Note: This attribute is returned from {@link #getAttribute(String)} and accepted into
+ * {@link #setAttribute(String, String)} as 3 colon-separated integers, e.g. {@code "11:05:32"}.
+ * Decimal or rational hours, minutes or seconds parts are not supported.
+ *
+ * <ul>
+ * <li>Tag = 7
+ * <li>Type = Unsigned rational
+ * <li>Count = 3
+ * <li>Default = None
+ * </ul>
+ */
+ public static final String TAG_GPS_TIMESTAMP = "GPSTimeStamp";
+
+ /**
+ * <p>Indicates the GPS satellites used for measurements. This tag may be used to describe
+ * the number of satellites, their ID number, angle of elevation, azimuth, SNR and other
+ * information in ASCII notation. The format is not specified. If the GPS receiver is incapable
+ * of taking measurements, value of the tag shall be set to {@code null}.</p>
+ *
+ * <ul>
+ * <li>Tag = 8</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_SATELLITES = "GPSSatellites";
+ /**
+ * <p>Indicates the status of the GPS receiver when the image is recorded. 'A' means
+ * measurement is in progress, and 'V' means the measurement is interrupted.</p>
+ *
+ * <ul>
+ * <li>Tag = 9</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #GPS_MEASUREMENT_IN_PROGRESS
+ * @see #GPS_MEASUREMENT_INTERRUPTED
+ */
+ public static final String TAG_GPS_STATUS = "GPSStatus";
+ /**
+ * <p>Indicates the GPS measurement mode. Originally it was defined for GPS, but it may
+ * be used for recording a measure mode to record the position information provided from
+ * a mobile base station or wireless LAN as well as GPS.</p>
+ *
+ * <ul>
+ * <li>Tag = 10</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #GPS_MEASUREMENT_2D
+ * @see #GPS_MEASUREMENT_3D
+ */
+ public static final String TAG_GPS_MEASURE_MODE = "GPSMeasureMode";
+ /**
+ * <p>Indicates the GPS DOP (data degree of precision). An HDOP value is written during
+ * two-dimensional measurement, and PDOP during three-dimensional measurement.</p>
+ *
+ * <ul>
+ * <li>Tag = 11</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_DOP = "GPSDOP";
+ /**
+ * <p>Indicates the unit used to express the GPS receiver speed of movement.</p>
+ *
+ * <ul>
+ * <li>Tag = 12</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = {@link #GPS_SPEED_KILOMETERS_PER_HOUR}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #GPS_SPEED_KILOMETERS_PER_HOUR
+ * @see #GPS_SPEED_MILES_PER_HOUR
+ * @see #GPS_SPEED_KNOTS
+ */
+ public static final String TAG_GPS_SPEED_REF = "GPSSpeedRef";
+ /**
+ * Indicates the speed of GPS receiver movement. The units are indicated by {@link
+ * #TAG_GPS_SPEED_REF}.
+ *
+ * <ul>
+ * <li>Tag = 13</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_SPEED = "GPSSpeed";
+ /**
+ * <p>Indicates the reference for giving the direction of GPS receiver movement.</p>
+ *
+ * <ul>
+ * <li>Tag = 14</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = {@link #GPS_DIRECTION_TRUE}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #GPS_DIRECTION_TRUE
+ * @see #GPS_DIRECTION_MAGNETIC
+ */
+ public static final String TAG_GPS_TRACK_REF = "GPSTrackRef";
+ /**
+ * <p>Indicates the direction of GPS receiver movement.
+ * The range of values is from 0.00 to 359.99.</p>
+ *
+ * <ul>
+ * <li>Tag = 15</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_TRACK = "GPSTrack";
+ /**
+ * <p>Indicates the reference for giving the direction of the image when it is captured.</p>
+ *
+ * <ul>
+ * <li>Tag = 16</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = {@link #GPS_DIRECTION_TRUE}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #GPS_DIRECTION_TRUE
+ * @see #GPS_DIRECTION_MAGNETIC
+ */
+ public static final String TAG_GPS_IMG_DIRECTION_REF = "GPSImgDirectionRef";
+ /**
+ * <p>ndicates the direction of the image when it was captured.
+ * The range of values is from 0.00 to 359.99.</p>
+ *
+ * <ul>
+ * <li>Tag = 17</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_IMG_DIRECTION = "GPSImgDirection";
+ /**
+ * <p>Indicates the geodetic survey data used by the GPS receiver. If the survey data is
+ * restricted to Japan,the value of this tag is 'TOKYO' or 'WGS-84'. If a GPS Info tag is
+ * recorded, it is strongly recommended that this tag be recorded.</p>
+ *
+ * <ul>
+ * <li>Tag = 18</li>
+ * <li>Type = String</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_MAP_DATUM = "GPSMapDatum";
+ /**
+ * <p>Indicates whether the latitude of the destination point is north or south latitude.</p>
+ *
+ * <ul>
+ * <li>Tag = 19</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #LATITUDE_NORTH
+ * @see #LATITUDE_SOUTH
+ */
+ public static final String TAG_GPS_DEST_LATITUDE_REF = "GPSDestLatitudeRef";
+ /**
+ * <p>Indicates the latitude of the destination point. The latitude is expressed as three
+ * unsigned rational values giving the degrees, minutes, and seconds, respectively.
+ * If latitude is expressed as degrees, minutes and seconds, a typical format would be
+ * dd/1,mm/1,ss/1. When degrees and minutes are used and, for example, fractions of minutes
+ * are given up to two decimal places, the format would be dd/1, mmmm/100, 0/1.</p>
+ *
+ * <ul>
+ * <li>Tag = 20</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 3</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_DEST_LATITUDE = "GPSDestLatitude";
+ /**
+ * <p>Indicates whether the longitude of the destination point is east or west longitude.</p>
+ *
+ * <ul>
+ * <li>Tag = 21</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #LONGITUDE_EAST
+ * @see #LONGITUDE_WEST
+ */
+ public static final String TAG_GPS_DEST_LONGITUDE_REF = "GPSDestLongitudeRef";
+ /**
+ * <p>Indicates the longitude of the destination point. The longitude is expressed as three
+ * unsigned rational values giving the degrees, minutes, and seconds, respectively.
+ * If longitude is expressed as degrees, minutes and seconds, a typical format would be ddd/1,
+ * mm/1, ss/1. When degrees and minutes are used and, for example, fractions of minutes are
+ * given up to two decimal places, the format would be ddd/1, mmmm/100, 0/1.</p>
+ *
+ * <ul>
+ * <li>Tag = 22</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 3</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_DEST_LONGITUDE = "GPSDestLongitude";
+ /**
+ * <p>Indicates the reference used for giving the bearing to the destination point.</p>
+ *
+ * <ul>
+ * <li>Tag = 23</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = {@link #GPS_DIRECTION_TRUE}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #GPS_DIRECTION_TRUE
+ * @see #GPS_DIRECTION_MAGNETIC
+ */
+ public static final String TAG_GPS_DEST_BEARING_REF = "GPSDestBearingRef";
+ /**
+ * <p>Indicates the bearing to the destination point.
+ * The range of values is from 0.00 to 359.99.</p>
+ *
+ * <ul>
+ * <li>Tag = 24</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_DEST_BEARING = "GPSDestBearing";
+ /**
+ * <p>Indicates the unit used to express the distance to the destination point.</p>
+ *
+ * <ul>
+ * <li>Tag = 25</li>
+ * <li>Type = String</li>
+ * <li>Length = 1</li>
+ * <li>Default = {@link #GPS_DISTANCE_KILOMETERS}</li>
+ * </ul>
+ * <p>
+ *
+ * @see #GPS_DISTANCE_KILOMETERS
+ * @see #GPS_DISTANCE_MILES
+ * @see #GPS_DISTANCE_NAUTICAL_MILES
+ */
+ public static final String TAG_GPS_DEST_DISTANCE_REF = "GPSDestDistanceRef";
+ /**
+ * <p>Indicates the distance to the destination point.</p>
+ *
+ * <ul>
+ * <li>Tag = 26</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_DEST_DISTANCE = "GPSDestDistance";
+ /**
+ * <p>A character string recording the name of the method used for location finding.
+ * The first byte indicates the character code used, and this is followed by the name of
+ * the method.</p>
+ *
+ * <ul>
+ * <li>Tag = 27</li>
+ * <li>Type = Undefined</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_PROCESSING_METHOD = "GPSProcessingMethod";
+ /**
+ * <p>A character string recording the name of the GPS area. The first byte indicates
+ * the character code used, and this is followed by the name of the GPS area.</p>
+ *
+ * <ul>
+ * <li>Tag = 28</li>
+ * <li>Type = Undefined</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_AREA_INFORMATION = "GPSAreaInformation";
+ /**
+ * <p>A character string recording date and time information relative to UTC (Coordinated
+ * Universal Time). The format is "YYYY:MM:DD".</p>
+ *
+ * <ul>
+ * <li>Tag = 29</li>
+ * <li>Type = String</li>
+ * <li>Length = 10</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_DATESTAMP = "GPSDateStamp";
+ /**
+ * <p>Indicates whether differential correction is applied to the GPS receiver.</p>
+ *
+ * <ul>
+ * <li>Tag = 30</li>
+ * <li>Type = Unsigned short</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ * <p>
+ *
+ * @see #GPS_MEASUREMENT_NO_DIFFERENTIAL
+ * @see #GPS_MEASUREMENT_DIFFERENTIAL_CORRECTED
+ */
+ public static final String TAG_GPS_DIFFERENTIAL = "GPSDifferential";
+ /**
+ * <p>This tag indicates horizontal positioning errors in meters.</p>
+ *
+ * <ul>
+ * <li>Tag = 31</li>
+ * <li>Type = Unsigned rational</li>
+ * <li>Count = 1</li>
+ * <li>Default = None</li>
+ * </ul>
+ */
+ public static final String TAG_GPS_H_POSITIONING_ERROR = "GPSHPositioningError";
+
+ // Interoperability IFD Attribute Information
+ /**
+ * <p>Indicates the identification of the Interoperability rule.</p>
+ *
+ * <ul>
+ * <li>Tag = 1</li>
+ * <li>Type = String</li>
+ * <li>Length = 4</li>
+ * <li>Default = None</li>
+ * <ul>
+ * <li>"R98" = Indicates a file conforming to R98 file specification of Recommended
+ * Exif Interoperability Rules (Exif R 98) or to DCF basic file stipulated
+ * by Design Rule for Camera File System.</li>
+ * <li>"THM" = Indicates a file conforming to DCF thumbnail file stipulated by Design
+ * rule for Camera File System.</li>
+ * <li>“R03” = Indicates a file conforming to DCF Option File stipulated by Design rule
+ * for Camera File System.</li>
+ * </ul>
+ * </ul>
+ */
+ public static final String TAG_INTEROPERABILITY_INDEX = "InteroperabilityIndex";
+
+ /**
+ * @see #TAG_IMAGE_LENGTH
+ */
+ public static final String TAG_THUMBNAIL_IMAGE_LENGTH = "ThumbnailImageLength";
+ /**
+ * @see #TAG_IMAGE_WIDTH
+ */
+ public static final String TAG_THUMBNAIL_IMAGE_WIDTH = "ThumbnailImageWidth";
+
+ // TODO: Unhide this when it can be public.
+ /**
+ * @see #TAG_ORIENTATION
+ */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ public static final String TAG_THUMBNAIL_ORIENTATION = "ThumbnailOrientation";
+ /**
+ * Type is int. DNG Specification 1.4.0.0. Section 4
+ */
+ public static final String TAG_DNG_VERSION = "DNGVersion";
+ /**
+ * Type is int. DNG Specification 1.4.0.0. Section 4
+ */
+ public static final String TAG_DEFAULT_CROP_SIZE = "DefaultCropSize";
+ /**
+ * Type is undefined. See Olympus MakerNote tags in http://www.exiv2.org/tags-olympus.html.
+ */
+ public static final String TAG_ORF_THUMBNAIL_IMAGE = "ThumbnailImage";
+ /**
+ * Type is int. See Olympus Camera Settings tags in http://www.exiv2.org/tags-olympus.html.
+ */
+ public static final String TAG_ORF_PREVIEW_IMAGE_START = "PreviewImageStart";
+ /**
+ * Type is int. See Olympus Camera Settings tags in http://www.exiv2.org/tags-olympus.html.
+ */
+ public static final String TAG_ORF_PREVIEW_IMAGE_LENGTH = "PreviewImageLength";
+ /**
+ * Type is int. See Olympus Image Processing tags in http://www.exiv2.org/tags-olympus.html.
+ */
+ public static final String TAG_ORF_ASPECT_FRAME = "AspectFrame";
+ /**
+ * Type is int. See PanasonicRaw tags in
+ * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
+ */
+ public static final String TAG_RW2_SENSOR_BOTTOM_BORDER = "SensorBottomBorder";
+ /**
+ * Type is int. See PanasonicRaw tags in
+ * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
+ */
+ public static final String TAG_RW2_SENSOR_LEFT_BORDER = "SensorLeftBorder";
+ /**
+ * Type is int. See PanasonicRaw tags in
+ * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
+ */
+ public static final String TAG_RW2_SENSOR_RIGHT_BORDER = "SensorRightBorder";
+ /**
+ * Type is int. See PanasonicRaw tags in
+ * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
+ */
+ public static final String TAG_RW2_SENSOR_TOP_BORDER = "SensorTopBorder";
+ /**
+ * Type is int. See PanasonicRaw tags in
+ * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
+ */
+ public static final String TAG_RW2_ISO = "ISO";
+ /**
+ * Type is undefined. See PanasonicRaw tags in
+ * http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html
+ */
+ public static final String TAG_RW2_JPG_FROM_RAW = "JpgFromRaw";
+ /**
+ * Type is byte[]. See <a href=
+ * "https://en.wikipedia.org/wiki/Extensible_Metadata_Platform">Extensible Metadata Platform
+ * (XMP)</a> for details on contents.
+ *
+ * <p>See also notes about XMP handling in different containers in the class-level javadoc of
+ * this class.
+ */
+ public static final String TAG_XMP = "Xmp";
+ /**
+ * Type is int. See JEITA CP-3451C Spec Section 3: Bilevel Images.
+ */
+ public static final String TAG_NEW_SUBFILE_TYPE = "NewSubfileType";
+ /**
+ * Type is int. See JEITA CP-3451C Spec Section 3: Bilevel Images.
+ */
+ public static final String TAG_SUBFILE_TYPE = "SubfileType";
+
+ /**
+ * Private tags used for pointing the other IFD offsets.
+ * The types of the following tags are int.
+ * See JEITA CP-3451C Section 4.6.3: Exif-specific IFD.
+ * For SubIFD, see Note 1 of Adobe PageMaker® 6.0 TIFF Technical Notes.
+ */
+ private static final String TAG_EXIF_IFD_POINTER = "ExifIFDPointer";
+ private static final String TAG_GPS_INFO_IFD_POINTER = "GPSInfoIFDPointer";
+ private static final String TAG_INTEROPERABILITY_IFD_POINTER = "InteroperabilityIFDPointer";
+ private static final String TAG_SUB_IFD_POINTER = "SubIFDPointer";
+ // Proprietary pointer tags used for ORF files.
+ // See http://www.exiv2.org/tags-olympus.html
+ private static final String TAG_ORF_CAMERA_SETTINGS_IFD_POINTER = "CameraSettingsIFDPointer";
+ private static final String TAG_ORF_IMAGE_PROCESSING_IFD_POINTER = "ImageProcessingIFDPointer";
+
+ private static final int MAX_THUMBNAIL_SIZE = 512;
+
+ // Constants used for the Orientation Exif tag.
+ public static final int ORIENTATION_UNDEFINED = 0;
+ public static final int ORIENTATION_NORMAL = 1;
+ /**
+ * Indicates the image is left right reversed mirror.
+ */
+ public static final int ORIENTATION_FLIP_HORIZONTAL = 2;
+ /**
+ * Indicates the image is rotated by 180 degree clockwise.
+ */
+ public static final int ORIENTATION_ROTATE_180 = 3;
+ /**
+ * Indicates the image is upside down mirror, it can also be represented by flip
+ * horizontally firstly and rotate 180 degree clockwise.
+ */
+ public static final int ORIENTATION_FLIP_VERTICAL = 4;
+ /**
+ * Indicates the image is flipped about top-left <--> bottom-right axis, it can also be
+ * represented by flip horizontally firstly and rotate 270 degree clockwise.
+ */
+ public static final int ORIENTATION_TRANSPOSE = 5;
+ /**
+ * Indicates the image is rotated by 90 degree clockwise.
+ */
+ public static final int ORIENTATION_ROTATE_90 = 6;
+ /**
+ * Indicates the image is flipped about top-right <--> bottom-left axis, it can also be
+ * represented by flip horizontally firstly and rotate 90 degree clockwise.
+ */
+ public static final int ORIENTATION_TRANSVERSE = 7;
+ /**
+ * Indicates the image is rotated by 270 degree clockwise.
+ */
+ public static final int ORIENTATION_ROTATE_270 = 8;
+ private static final List<Integer> ROTATION_ORDER = Arrays.asList(ORIENTATION_NORMAL,
+ ORIENTATION_ROTATE_90, ORIENTATION_ROTATE_180, ORIENTATION_ROTATE_270);
+ private static final List<Integer> FLIPPED_ROTATION_ORDER = Arrays.asList(
+ ORIENTATION_FLIP_HORIZONTAL, ORIENTATION_TRANSVERSE, ORIENTATION_FLIP_VERTICAL,
+ ORIENTATION_TRANSPOSE);
+
+ /**
+ * The constant used by {@link #TAG_PLANAR_CONFIGURATION} to denote Chunky format.
+ */
+ public static final short FORMAT_CHUNKY = 1;
+ /**
+ * The constant used by {@link #TAG_PLANAR_CONFIGURATION} to denote Planar format.
+ */
+ public static final short FORMAT_PLANAR = 2;
+
+ /**
+ * The constant used by {@link #TAG_Y_CB_CR_POSITIONING} to denote Centered positioning.
+ */
+ public static final short Y_CB_CR_POSITIONING_CENTERED = 1;
+ /**
+ * The constant used by {@link #TAG_Y_CB_CR_POSITIONING} to denote Co-sited positioning.
+ */
+ public static final short Y_CB_CR_POSITIONING_CO_SITED = 2;
+
+ /**
+ * The constant used to denote resolution unit as inches.
+ */
+ public static final short RESOLUTION_UNIT_INCHES = 2;
+ /**
+ * The constant used to denote resolution unit as centimeters.
+ */
+ public static final short RESOLUTION_UNIT_CENTIMETERS = 3;
+
+ /**
+ * The constant used by {@link #TAG_COLOR_SPACE} to denote sRGB color space.
+ */
+ public static final int COLOR_SPACE_S_RGB = 1;
+ /**
+ * The constant used by {@link #TAG_COLOR_SPACE} to denote Uncalibrated.
+ */
+ public static final int COLOR_SPACE_UNCALIBRATED = 65535;
+
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is not defined.
+ */
+ public static final short EXPOSURE_PROGRAM_NOT_DEFINED = 0;
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Manual.
+ */
+ public static final short EXPOSURE_PROGRAM_MANUAL = 1;
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Normal.
+ */
+ public static final short EXPOSURE_PROGRAM_NORMAL = 2;
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is
+ * Aperture priority.
+ */
+ public static final short EXPOSURE_PROGRAM_APERTURE_PRIORITY = 3;
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is
+ * Shutter priority.
+ */
+ public static final short EXPOSURE_PROGRAM_SHUTTER_PRIORITY = 4;
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Creative
+ * program (biased toward depth of field).
+ */
+ public static final short EXPOSURE_PROGRAM_CREATIVE = 5;
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Action
+ * program (biased toward fast shutter speed).
+ */
+ public static final short EXPOSURE_PROGRAM_ACTION = 6;
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Portrait
+ * mode (for closeup photos with the background out of focus).
+ */
+ public static final short EXPOSURE_PROGRAM_PORTRAIT_MODE = 7;
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_PROGRAM} to denote exposure program is Landscape
+ * mode (for landscape photos with the background in focus).
+ */
+ public static final short EXPOSURE_PROGRAM_LANDSCAPE_MODE = 8;
+
+ /**
+ * The constant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is unknown.
+ */
+ public static final short SENSITIVITY_TYPE_UNKNOWN = 0;
+ /**
+ * The constant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard
+ * output sensitivity (SOS).
+ */
+ public static final short SENSITIVITY_TYPE_SOS = 1;
+ /**
+ * The constant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Recommended
+ * exposure index (REI).
+ */
+ public static final short SENSITIVITY_TYPE_REI = 2;
+ /**
+ * The constant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is ISO speed.
+ */
+ public static final short SENSITIVITY_TYPE_ISO_SPEED = 3;
+ /**
+ * The constant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard
+ * output sensitivity (SOS) and recommended exposure index (REI).
+ */
+ public static final short SENSITIVITY_TYPE_SOS_AND_REI = 4;
+ /**
+ * The constant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard
+ * output sensitivity (SOS) and ISO speed.
+ */
+ public static final short SENSITIVITY_TYPE_SOS_AND_ISO = 5;
+ /**
+ * The constant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Recommended
+ * exposure index (REI) and ISO speed.
+ */
+ public static final short SENSITIVITY_TYPE_REI_AND_ISO = 6;
+ /**
+ * The constant used by {@link #TAG_SENSITIVITY_TYPE} to denote sensitivity type is Standard
+ * output sensitivity (SOS) and recommended exposure index (REI) and ISO speed.
+ */
+ public static final short SENSITIVITY_TYPE_SOS_AND_REI_AND_ISO = 7;
+
+ /**
+ * The constant used by {@link #TAG_METERING_MODE} to denote metering mode is unknown.
+ */
+ public static final short METERING_MODE_UNKNOWN = 0;
+ /**
+ * The constant used by {@link #TAG_METERING_MODE} to denote metering mode is Average.
+ */
+ public static final short METERING_MODE_AVERAGE = 1;
+ /**
+ * The constant used by {@link #TAG_METERING_MODE} to denote metering mode is
+ * CenterWeightedAverage.
+ */
+ public static final short METERING_MODE_CENTER_WEIGHT_AVERAGE = 2;
+ /**
+ * The constant used by {@link #TAG_METERING_MODE} to denote metering mode is Spot.
+ */
+ public static final short METERING_MODE_SPOT = 3;
+ /**
+ * The constant used by {@link #TAG_METERING_MODE} to denote metering mode is MultiSpot.
+ */
+ public static final short METERING_MODE_MULTI_SPOT = 4;
+ /**
+ * The constant used by {@link #TAG_METERING_MODE} to denote metering mode is Pattern.
+ */
+ public static final short METERING_MODE_PATTERN = 5;
+ /**
+ * The constant used by {@link #TAG_METERING_MODE} to denote metering mode is Partial.
+ */
+ public static final short METERING_MODE_PARTIAL = 6;
+ /**
+ * The constant used by {@link #TAG_METERING_MODE} to denote metering mode is other.
+ */
+ public static final short METERING_MODE_OTHER = 255;
+
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is unknown.
+ */
+ public static final short LIGHT_SOURCE_UNKNOWN = 0;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Daylight.
+ */
+ public static final short LIGHT_SOURCE_DAYLIGHT = 1;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Fluorescent.
+ */
+ public static final short LIGHT_SOURCE_FLUORESCENT = 2;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Tungsten
+ * (incandescent light).
+ */
+ public static final short LIGHT_SOURCE_TUNGSTEN = 3;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Flash.
+ */
+ public static final short LIGHT_SOURCE_FLASH = 4;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Fine weather.
+ */
+ public static final short LIGHT_SOURCE_FINE_WEATHER = 9;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Cloudy weather.
+ */
+ public static final short LIGHT_SOURCE_CLOUDY_WEATHER = 10;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Shade.
+ */
+ public static final short LIGHT_SOURCE_SHADE = 11;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Daylight fluorescent
+ * (D 5700 - 7100K).
+ */
+ public static final short LIGHT_SOURCE_DAYLIGHT_FLUORESCENT = 12;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Day white
+ * fluorescent (N 4600 - 5500K).
+ */
+ public static final short LIGHT_SOURCE_DAY_WHITE_FLUORESCENT = 13;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Cool white
+ * fluorescent (W 3800 - 4500K).
+ */
+ public static final short LIGHT_SOURCE_COOL_WHITE_FLUORESCENT = 14;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is White fluorescent
+ * (WW 3250 - 3800K).
+ */
+ public static final short LIGHT_SOURCE_WHITE_FLUORESCENT = 15;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Warm white
+ * fluorescent (L 2600 - 3250K).
+ */
+ public static final short LIGHT_SOURCE_WARM_WHITE_FLUORESCENT = 16;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Standard light A.
+ */
+ public static final short LIGHT_SOURCE_STANDARD_LIGHT_A = 17;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Standard light B.
+ */
+ public static final short LIGHT_SOURCE_STANDARD_LIGHT_B = 18;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is Standard light C.
+ */
+ public static final short LIGHT_SOURCE_STANDARD_LIGHT_C = 19;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D55.
+ */
+ public static final short LIGHT_SOURCE_D55 = 20;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D65.
+ */
+ public static final short LIGHT_SOURCE_D65 = 21;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D75.
+ */
+ public static final short LIGHT_SOURCE_D75 = 22;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is D50.
+ */
+ public static final short LIGHT_SOURCE_D50 = 23;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is ISO studio tungsten.
+ */
+ public static final short LIGHT_SOURCE_ISO_STUDIO_TUNGSTEN = 24;
+ /**
+ * The constant used by {@link #TAG_LIGHT_SOURCE} to denote light source is other.
+ */
+ public static final short LIGHT_SOURCE_OTHER = 255;
+
+ /**
+ * The flag used by {@link #TAG_FLASH} to indicate whether the flash is fired.
+ */
+ public static final short FLAG_FLASH_FIRED = 0b0000_0001;
+ /**
+ * The flag used by {@link #TAG_FLASH} to indicate strobe return light is not detected.
+ */
+ public static final short FLAG_FLASH_RETURN_LIGHT_NOT_DETECTED = 0b0000_0100;
+ /**
+ * The flag used by {@link #TAG_FLASH} to indicate strobe return light is detected.
+ */
+ public static final short FLAG_FLASH_RETURN_LIGHT_DETECTED = 0b0000_0110;
+ /**
+ * The flag used by {@link #TAG_FLASH} to indicate the camera's flash mode is Compulsory flash
+ * firing.
+ *
+ * @see #FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION
+ * @see #FLAG_FLASH_MODE_AUTO
+ */
+ public static final short FLAG_FLASH_MODE_COMPULSORY_FIRING = 0b0000_1000;
+ /**
+ * The flag used by {@link #TAG_FLASH} to indicate the camera's flash mode is Compulsory flash
+ * suppression.
+ *
+ * @see #FLAG_FLASH_MODE_COMPULSORY_FIRING
+ * @see #FLAG_FLASH_MODE_AUTO
+ */
+ public static final short FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION = 0b0001_0000;
+ /**
+ * The flag used by {@link #TAG_FLASH} to indicate the camera's flash mode is Auto.
+ *
+ * @see #FLAG_FLASH_MODE_COMPULSORY_FIRING
+ * @see #FLAG_FLASH_MODE_COMPULSORY_SUPPRESSION
+ */
+ public static final short FLAG_FLASH_MODE_AUTO = 0b0001_1000;
+ /**
+ * The flag used by {@link #TAG_FLASH} to indicate no flash function is present.
+ */
+ public static final short FLAG_FLASH_NO_FLASH_FUNCTION = 0b0010_0000;
+ /**
+ * The flag used by {@link #TAG_FLASH} to indicate red-eye reduction is supported.
+ */
+ public static final short FLAG_FLASH_RED_EYE_SUPPORTED = 0b0100_0000;
+
+ /**
+ * The constant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is not
+ * defined.
+ */
+ public static final short SENSOR_TYPE_NOT_DEFINED = 1;
+ /**
+ * The constant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is One-chip
+ * color area sensor.
+ */
+ public static final short SENSOR_TYPE_ONE_CHIP = 2;
+ /**
+ * The constant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Two-chip
+ * color area sensor.
+ */
+ public static final short SENSOR_TYPE_TWO_CHIP = 3;
+ /**
+ * The constant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is
+ * Three-chip color area sensor.
+ */
+ public static final short SENSOR_TYPE_THREE_CHIP = 4;
+ /**
+ * The constant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Color
+ * sequential area sensor.
+ */
+ public static final short SENSOR_TYPE_COLOR_SEQUENTIAL = 5;
+ /**
+ * The constant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Trilinear
+ * sensor.
+ */
+ public static final short SENSOR_TYPE_TRILINEAR = 7;
+ /**
+ * The constant used by {@link #TAG_SENSING_METHOD} to denote the image sensor type is Color
+ * sequential linear sensor.
+ */
+ public static final short SENSOR_TYPE_COLOR_SEQUENTIAL_LINEAR = 8;
+
+ /**
+ * The constant used by {@link #TAG_FILE_SOURCE} to denote the source is other.
+ */
+ public static final short FILE_SOURCE_OTHER = 0;
+ /**
+ * The constant used by {@link #TAG_FILE_SOURCE} to denote the source is scanner of transparent
+ * type.
+ */
+ public static final short FILE_SOURCE_TRANSPARENT_SCANNER = 1;
+ /**
+ * The constant used by {@link #TAG_FILE_SOURCE} to denote the source is scanner of reflex type.
+ */
+ public static final short FILE_SOURCE_REFLEX_SCANNER = 2;
+ /**
+ * The constant used by {@link #TAG_FILE_SOURCE} to denote the source is DSC.
+ */
+ public static final short FILE_SOURCE_DSC = 3;
+
+ /**
+ * The constant used by {@link #TAG_SCENE_TYPE} to denote the scene is directly photographed.
+ */
+ public static final short SCENE_TYPE_DIRECTLY_PHOTOGRAPHED = 1;
+
+ /**
+ * The constant used by {@link #TAG_CUSTOM_RENDERED} to denote no special processing is used.
+ */
+ public static final short RENDERED_PROCESS_NORMAL = 0;
+ /**
+ * The constant used by {@link #TAG_CUSTOM_RENDERED} to denote special processing is used.
+ */
+ public static final short RENDERED_PROCESS_CUSTOM = 1;
+
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_MODE} to denote the exposure mode is Auto.
+ */
+ public static final short EXPOSURE_MODE_AUTO = 0;
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_MODE} to denote the exposure mode is Manual.
+ */
+ public static final short EXPOSURE_MODE_MANUAL = 1;
+ /**
+ * The constant used by {@link #TAG_EXPOSURE_MODE} to denote the exposure mode is Auto bracket.
+ */
+ public static final short EXPOSURE_MODE_AUTO_BRACKET = 2;
+
+ /**
+ * The constant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Auto.
+ *
+ * @deprecated Use {@link #WHITE_BALANCE_AUTO} instead.
+ */
+ @Deprecated
+ public static final int WHITEBALANCE_AUTO = 0;
+ /**
+ * The constant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Manual.
+ *
+ * @deprecated Use {@link #WHITE_BALANCE_MANUAL} instead.
+ */
+ @Deprecated
+ public static final int WHITEBALANCE_MANUAL = 1;
+ /**
+ * The constant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Auto.
+ */
+ public static final short WHITE_BALANCE_AUTO = 0;
+ /**
+ * The constant used by {@link #TAG_WHITE_BALANCE} to denote the white balance is Manual.
+ */
+ public static final short WHITE_BALANCE_MANUAL = 1;
+
+ /**
+ * The constant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is
+ * Standard.
+ */
+ public static final short SCENE_CAPTURE_TYPE_STANDARD = 0;
+ /**
+ * The constant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is
+ * Landscape.
+ */
+ public static final short SCENE_CAPTURE_TYPE_LANDSCAPE = 1;
+ /**
+ * The constant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is
+ * Portrait.
+ */
+ public static final short SCENE_CAPTURE_TYPE_PORTRAIT = 2;
+ /**
+ * The constant used by {@link #TAG_SCENE_CAPTURE_TYPE} to denote the scene capture type is
+ * Night scene.
+ */
+ public static final short SCENE_CAPTURE_TYPE_NIGHT = 3;
+
+ /**
+ * The constant used by {@link #TAG_GAIN_CONTROL} to denote none gain adjustment.
+ */
+ public static final short GAIN_CONTROL_NONE = 0;
+ /**
+ * The constant used by {@link #TAG_GAIN_CONTROL} to denote low gain up.
+ */
+ public static final short GAIN_CONTROL_LOW_GAIN_UP = 1;
+ /**
+ * The constant used by {@link #TAG_GAIN_CONTROL} to denote high gain up.
+ */
+ public static final short GAIN_CONTROL_HIGH_GAIN_UP = 2;
+ /**
+ * The constant used by {@link #TAG_GAIN_CONTROL} to denote low gain down.
+ */
+ public static final short GAIN_CONTROL_LOW_GAIN_DOWN = 3;
+ /**
+ * The constant used by {@link #TAG_GAIN_CONTROL} to denote high gain down.
+ */
+ public static final short GAIN_CONTROL_HIGH_GAIN_DOWN = 4;
+
+ /**
+ * The constant used by {@link #TAG_CONTRAST} to denote normal contrast.
+ */
+ public static final short CONTRAST_NORMAL = 0;
+ /**
+ * The constant used by {@link #TAG_CONTRAST} to denote soft contrast.
+ */
+ public static final short CONTRAST_SOFT = 1;
+ /**
+ * The constant used by {@link #TAG_CONTRAST} to denote hard contrast.
+ */
+ public static final short CONTRAST_HARD = 2;
+
+ /**
+ * The constant used by {@link #TAG_SATURATION} to denote normal saturation.
+ */
+ public static final short SATURATION_NORMAL = 0;
+ /**
+ * The constant used by {@link #TAG_SATURATION} to denote low saturation.
+ */
+ public static final short SATURATION_LOW = 0;
+ /**
+ * The constant used by {@link #TAG_SHARPNESS} to denote high saturation.
+ */
+ public static final short SATURATION_HIGH = 0;
+
+ /**
+ * The constant used by {@link #TAG_SHARPNESS} to denote normal sharpness.
+ */
+ public static final short SHARPNESS_NORMAL = 0;
+ /**
+ * The constant used by {@link #TAG_SHARPNESS} to denote soft sharpness.
+ */
+ public static final short SHARPNESS_SOFT = 1;
+ /**
+ * The constant used by {@link #TAG_SHARPNESS} to denote hard sharpness.
+ */
+ public static final short SHARPNESS_HARD = 2;
+
+ /**
+ * The constant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range
+ * is unknown.
+ */
+ public static final short SUBJECT_DISTANCE_RANGE_UNKNOWN = 0;
+ /**
+ * The constant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range
+ * is Macro.
+ */
+ public static final short SUBJECT_DISTANCE_RANGE_MACRO = 1;
+ /**
+ * The constant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range
+ * is Close view.
+ */
+ public static final short SUBJECT_DISTANCE_RANGE_CLOSE_VIEW = 2;
+ /**
+ * The constant used by {@link #TAG_SUBJECT_DISTANCE_RANGE} to denote the subject distance range
+ * is Distant view.
+ */
+ public static final short SUBJECT_DISTANCE_RANGE_DISTANT_VIEW = 3;
+
+ /**
+ * The constant used by GPS latitude-related tags to denote the latitude is North latitude.
+ *
+ * @see #TAG_GPS_LATITUDE_REF
+ * @see #TAG_GPS_DEST_LATITUDE_REF
+ */
+ public static final String LATITUDE_NORTH = "N";
+ /**
+ * The constant used by GPS latitude-related tags to denote the latitude is South latitude.
+ *
+ * @see #TAG_GPS_LATITUDE_REF
+ * @see #TAG_GPS_DEST_LATITUDE_REF
+ */
+ public static final String LATITUDE_SOUTH = "S";
+
+ /**
+ * The constant used by GPS longitude-related tags to denote the longitude is East longitude.
+ *
+ * @see #TAG_GPS_LONGITUDE_REF
+ * @see #TAG_GPS_DEST_LONGITUDE_REF
+ */
+ public static final String LONGITUDE_EAST = "E";
+ /**
+ * The constant used by GPS longitude-related tags to denote the longitude is West longitude.
+ *
+ * @see #TAG_GPS_LONGITUDE_REF
+ * @see #TAG_GPS_DEST_LONGITUDE_REF
+ */
+ public static final String LONGITUDE_WEST = "W";
+
+ /**
+ * The constant used by {@link #TAG_GPS_ALTITUDE_REF} to denote the altitude is above sea level.
+ */
+ public static final short ALTITUDE_ABOVE_SEA_LEVEL = 0;
+ /**
+ * The constant used by {@link #TAG_GPS_ALTITUDE_REF} to denote the altitude is below sea level.
+ */
+ public static final short ALTITUDE_BELOW_SEA_LEVEL = 1;
+
+ /**
+ * The constant used by {@link #TAG_GPS_STATUS} to denote GPS measurement is in progress.
+ */
+ public static final String GPS_MEASUREMENT_IN_PROGRESS = "A";
+ /**
+ * The constant used by {@link #TAG_GPS_STATUS} to denote GPS measurement is interrupted.
+ */
+ public static final String GPS_MEASUREMENT_INTERRUPTED = "V";
+
+ /**
+ * The constant used by {@link #TAG_GPS_MEASURE_MODE} to denote GPS measurement is
+ * 2-dimensional.
+ */
+ public static final String GPS_MEASUREMENT_2D = "2";
+ /**
+ * The constant used by {@link #TAG_GPS_MEASURE_MODE} to denote GPS measurement is
+ * 3-dimensional.
+ */
+ public static final String GPS_MEASUREMENT_3D = "3";
+
+ /**
+ * The constant used by {@link #TAG_GPS_SPEED_REF} to denote the speed unit is kilometers per
+ * hour.
+ */
+ public static final String GPS_SPEED_KILOMETERS_PER_HOUR = "K";
+ /**
+ * The constant used by {@link #TAG_GPS_SPEED_REF} to denote the speed unit is miles per hour.
+ */
+ public static final String GPS_SPEED_MILES_PER_HOUR = "M";
+ /**
+ * The constant used by {@link #TAG_GPS_SPEED_REF} to denote the speed unit is knots.
+ */
+ public static final String GPS_SPEED_KNOTS = "N";
+
+ /**
+ * The constant used by GPS attributes to denote the direction is true direction.
+ */
+ public static final String GPS_DIRECTION_TRUE = "T";
+ /**
+ * The constant used by GPS attributes to denote the direction is magnetic direction.
+ */
+ public static final String GPS_DIRECTION_MAGNETIC = "M";
+
+ /**
+ * The constant used by {@link #TAG_GPS_DEST_DISTANCE_REF} to denote the distance unit is
+ * kilometers.
+ */
+ public static final String GPS_DISTANCE_KILOMETERS = "K";
+ /**
+ * The constant used by {@link #TAG_GPS_DEST_DISTANCE_REF} to denote the distance unit is miles.
+ */
+ public static final String GPS_DISTANCE_MILES = "M";
+ /**
+ * The constant used by {@link #TAG_GPS_DEST_DISTANCE_REF} to denote the distance unit is
+ * nautical miles.
+ */
+ public static final String GPS_DISTANCE_NAUTICAL_MILES = "N";
+
+ /**
+ * The constant used by {@link #TAG_GPS_DIFFERENTIAL} to denote no differential correction is
+ * applied.
+ */
+ public static final short GPS_MEASUREMENT_NO_DIFFERENTIAL = 0;
+ /**
+ * The constant used by {@link #TAG_GPS_DIFFERENTIAL} to denote differential correction is
+ * applied.
+ */
+ public static final short GPS_MEASUREMENT_DIFFERENTIAL_CORRECTED = 1;
+
+ /**
+ * The constant used by {@link #TAG_COMPRESSION} to denote the image is not compressed.
+ */
+ public static final int DATA_UNCOMPRESSED = 1;
+ /**
+ * The constant used by {@link #TAG_COMPRESSION} to denote the image is huffman compressed.
+ */
+ public static final int DATA_HUFFMAN_COMPRESSED = 2;
+ /**
+ * The constant used by {@link #TAG_COMPRESSION} to denote the image is JPEG.
+ */
+ public static final int DATA_JPEG = 6;
+ /**
+ * The constant used by {@link #TAG_COMPRESSION}, see DNG Specification 1.4.0.0.
+ * Section 3, Compression
+ */
+ public static final int DATA_JPEG_COMPRESSED = 7;
+ /**
+ * The constant used by {@link #TAG_COMPRESSION}, see DNG Specification 1.4.0.0.
+ * Section 3, Compression
+ */
+ public static final int DATA_DEFLATE_ZIP = 8;
+ /**
+ * The constant used by {@link #TAG_COMPRESSION} to denote the image is pack-bits compressed.
+ */
+ public static final int DATA_PACK_BITS_COMPRESSED = 32773;
+ /**
+ * The constant used by {@link #TAG_COMPRESSION}, see DNG Specification 1.4.0.0.
+ * Section 3, Compression
+ */
+ public static final int DATA_LOSSY_JPEG = 34892;
+
+ /**
+ * The constant used by {@link #TAG_BITS_PER_SAMPLE}.
+ * See JEITA CP-3451C Spec Section 6, Differences from Palette Color Images
+ */
+ public static final int[] BITS_PER_SAMPLE_RGB = new int[]{8, 8, 8};
+ /**
+ * The constant used by {@link #TAG_BITS_PER_SAMPLE}.
+ * See JEITA CP-3451C Spec Section 4, Differences from Bilevel Images
+ */
+ public static final int[] BITS_PER_SAMPLE_GREYSCALE_1 = new int[]{4};
+ /**
+ * The constant used by {@link #TAG_BITS_PER_SAMPLE}.
+ * See JEITA CP-3451C Spec Section 4, Differences from Bilevel Images
+ */
+ public static final int[] BITS_PER_SAMPLE_GREYSCALE_2 = new int[]{8};
+
+ /**
+ * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}.
+ */
+ public static final int PHOTOMETRIC_INTERPRETATION_WHITE_IS_ZERO = 0;
+ /**
+ * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}.
+ */
+ public static final int PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO = 1;
+ /**
+ * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}.
+ */
+ public static final int PHOTOMETRIC_INTERPRETATION_RGB = 2;
+ /**
+ * The constant used by {@link #TAG_PHOTOMETRIC_INTERPRETATION}.
+ */
+ public static final int PHOTOMETRIC_INTERPRETATION_YCBCR = 6;
+
+ /**
+ * The constant used by {@link #TAG_NEW_SUBFILE_TYPE}. See JEITA CP-3451C Spec Section 8.
+ */
+ public static final int ORIGINAL_RESOLUTION_IMAGE = 0;
+ /**
+ * The constant used by {@link #TAG_NEW_SUBFILE_TYPE}. See JEITA CP-3451C Spec Section 8.
+ */
+ public static final int REDUCED_RESOLUTION_IMAGE = 1;
+
+ /**
+ * Constant used to indicate that the input stream contains the full image data.
+ * <p>
+ * The format of the image data should follow one of the image formats supported by this class.
+ */
+ public static final int STREAM_TYPE_FULL_IMAGE_DATA = 0;
+ /**
+ * Constant used to indicate that the input stream contains only Exif data.
+ * <p>
+ * The format of the Exif-only data must follow the below structure:
+ * Exif Identifier Code ("Exif\0\0") + TIFF header + IFD data
+ * See JEITA CP-3451C Section 4.5.2 and 4.5.4 specifications for more details.
+ */
+ public static final int STREAM_TYPE_EXIF_DATA_ONLY = 1;
+
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({STREAM_TYPE_FULL_IMAGE_DATA, STREAM_TYPE_EXIF_DATA_ONLY})
+ public @interface ExifStreamType {
+ }
+
+ @Retention(RetentionPolicy.SOURCE)
+ @Target(TYPE_USE)
+ @IntDef({
+ XMP_HANDLING_TIFF_700_ONLY,
+ XMP_HANDLING_PREFER_SEPARATE,
+ XMP_HANDLING_PREFER_TIFF_700_IF_PRESENT
+ })
+ private @interface XmpHandling {
+ }
+
+ /**
+ * The format only supports XMP data stored in the TIFF/Exif 700 tag (or it supports storing XMP
+ * in a separate segment but this should never be used).
+ */
+ private static final int XMP_HANDLING_TIFF_700_ONLY = 1;
+
+ /**
+ * The format supports XMP data stored in a separate segment, and this should always be
+ * preferred if present.
+ *
+ * <p>If XMP data is only present in the TIFF/Exif 700 tag it will be read and written from
+ * there.
+ */
+ private static final int XMP_HANDLING_PREFER_SEPARATE = 2;
+
+ /**
+ * The format supports XMP data stored in a separate segment, and this should be preferred
+ * unless XMP is also present in the TIFF/Exif 700 tag.
+ */
+ private static final int XMP_HANDLING_PREFER_TIFF_700_IF_PRESENT = 3;
+
+ // Maximum size for checking file type signature (see image_type_recognition_lite.cc)
+ private static final int SIGNATURE_CHECK_SIZE = 5000;
+
+ static final byte[] JPEG_SIGNATURE = new byte[]{(byte) 0xff, (byte) 0xd8, (byte) 0xff};
+ private static final String RAF_SIGNATURE = "FUJIFILMCCD-RAW";
+ private static final int RAF_OFFSET_TO_JPEG_IMAGE_OFFSET = 84;
+
+ private static final byte[] HEIF_TYPE_FTYP = new byte[]{'f', 't', 'y', 'p'};
+ private static final byte[] HEIF_BRAND_MIF1 = new byte[]{'m', 'i', 'f', '1'};
+ private static final byte[] HEIF_BRAND_HEIC = new byte[]{'h', 'e', 'i', 'c'};
+ private static final byte[] HEIF_BRAND_AVIF = new byte[]{'a', 'v', 'i', 'f'};
+ private static final byte[] HEIF_BRAND_AVIS = new byte[]{'a', 'v', 'i', 's'};
+
+ // See http://fileformats.archiveteam.org/wiki/Olympus_ORF
+ private static final short ORF_SIGNATURE_1 = 0x4f52;
+ private static final short ORF_SIGNATURE_2 = 0x5352;
+ // There are two formats for Olympus Makernote Headers. Each has different identifiers and
+ // offsets to the actual data.
+ // See http://www.exiv2.org/makernote.html#R1
+ private static final byte[] ORF_MAKER_NOTE_HEADER_1 = new byte[]{(byte) 0x4f, (byte) 0x4c,
+ (byte) 0x59, (byte) 0x4d, (byte) 0x50, (byte) 0x00}; // "OLYMP\0"
+ private static final byte[] ORF_MAKER_NOTE_HEADER_2 = new byte[]{(byte) 0x4f, (byte) 0x4c,
+ (byte) 0x59, (byte) 0x4d, (byte) 0x50, (byte) 0x55, (byte) 0x53, (byte) 0x00,
+ (byte) 0x49, (byte) 0x49}; // "OLYMPUS\0II"
+ private static final int ORF_MAKER_NOTE_HEADER_1_SIZE = 8;
+ private static final int ORF_MAKER_NOTE_HEADER_2_SIZE = 12;
+
+ // See http://fileformats.archiveteam.org/wiki/RW2
+ private static final short RW2_SIGNATURE = 0x0055;
+
+ // See http://fileformats.archiveteam.org/wiki/Pentax_PEF
+ private static final String PEF_SIGNATURE = "PENTAX";
+ // See http://www.exiv2.org/makernote.html#R11
+ private static final int PEF_MAKER_NOTE_SKIP_SIZE = 6;
+
+ // See PNG (Portable Network Graphics) Specification, Version 1.2,
+ // 3.1. PNG file signature
+ private static final byte[] PNG_SIGNATURE = new byte[]{(byte) 0x89, (byte) 0x50, (byte) 0x4e,
+ (byte) 0x47, (byte) 0x0d, (byte) 0x0a, (byte) 0x1a, (byte) 0x0a};
+ // See "Extensions to the PNG 1.2 Specification, Version 1.5.0",
+ // 3.7. eXIf Exchangeable Image File (Exif) Profile
+ private static final int PNG_CHUNK_TYPE_EXIF = 'e' << 24 | 'X' << 16 | 'I' << 8 | 'f';
+ // See "XMP Specification Part 3: Storage in Files" section 1.1.5
+ private static final int PNG_CHUNK_TYPE_ITXT = 'i' << 24 | 'T' << 16 | 'X' << 8 | 't';
+ private static final int PNG_CHUNK_TYPE_IHDR = 'I' << 24 | 'H' << 16 | 'D' << 8 | 'R';
+ private static final int PNG_CHUNK_TYPE_IEND = 'I' << 24 | 'E' << 16 | 'N' << 8 | 'D';
+ private static final int PNG_CHUNK_CRC_BYTE_LENGTH = 4;
+
+ /**
+ * The keyword and 5 null bytes defined by XMP spec part 3 table 9 (section 1.1.5).
+ */
+ @VisibleForTesting
+ static final byte[] PNG_ITXT_XMP_KEYWORD = "XML:com.adobe.xmp\0\0\0\0\0".getBytes(UTF_8);
+
+ // See https://developers.google.com/speed/webp/docs/riff_container, Section "WebP File Header"
+ private static final byte[] WEBP_SIGNATURE_1 = new byte[]{'R', 'I', 'F', 'F'};
+ private static final byte[] WEBP_SIGNATURE_2 = new byte[]{'W', 'E', 'B', 'P'};
+ private static final int WEBP_FILE_SIZE_BYTE_LENGTH = 4;
+ private static final byte[] WEBP_CHUNK_TYPE_EXIF = new byte[]{(byte) 0x45, (byte) 0x58,
+ (byte) 0x49, (byte) 0x46};
+ private static final byte[] WEBP_VP8_SIGNATURE = new byte[]{(byte) 0x9d, (byte) 0x01,
+ (byte) 0x2a};
+ private static final byte WEBP_VP8L_SIGNATURE = (byte) 0x2f;
+ private static final byte[] WEBP_CHUNK_TYPE_VP8X = "VP8X".getBytes(Charset.defaultCharset());
+ private static final byte[] WEBP_CHUNK_TYPE_VP8L = "VP8L".getBytes(Charset.defaultCharset());
+ private static final byte[] WEBP_CHUNK_TYPE_VP8 = "VP8 ".getBytes(Charset.defaultCharset());
+ private static final byte[] WEBP_CHUNK_TYPE_ANIM = "ANIM".getBytes(Charset.defaultCharset());
+ private static final byte[] WEBP_CHUNK_TYPE_ANMF = "ANMF".getBytes(Charset.defaultCharset());
+ private static final int WEBP_CHUNK_TYPE_VP8X_DEFAULT_LENGTH = 10;
+ private static final int WEBP_CHUNK_TYPE_BYTE_LENGTH = 4;
+ private static final int WEBP_CHUNK_SIZE_BYTE_LENGTH = 4;
+
+ private static final SimpleDateFormat sFormatterPrimary;
+ private static final SimpleDateFormat sFormatterSecondary;
+
+ // See Exchangeable image file format for digital still cameras: Exif version 2.2.
+ // The following values are for parsing EXIF data area. There are tag groups in EXIF data area.
+ // They are called "Image File Directory". They have multiple data formats to cover various
+ // image metadata from GPS longitude to camera model name.
+
+ // Types of Exif byte alignments (see JEITA CP-3451C Section 4.5.2)
+ static final short BYTE_ALIGN_II = 0x4949; // II: Intel order
+ static final short BYTE_ALIGN_MM = 0x4d4d; // MM: Motorola order
+
+ // TIFF Header Fixed Constant (see JEITA CP-3451C Section 4.5.2)
+ static final byte START_CODE = 0x2a; // 42
+ private static final int IFD_OFFSET = 8;
+
+ // Formats for the value in IFD entry (See TIFF 6.0 Section 2, "Image File Directory".)
+ private static final int IFD_FORMAT_BYTE = 1;
+ private static final int IFD_FORMAT_STRING = 2;
+ private static final int IFD_FORMAT_USHORT = 3;
+ private static final int IFD_FORMAT_ULONG = 4;
+ private static final int IFD_FORMAT_URATIONAL = 5;
+ private static final int IFD_FORMAT_SBYTE = 6;
+ private static final int IFD_FORMAT_UNDEFINED = 7;
+ private static final int IFD_FORMAT_SSHORT = 8;
+ private static final int IFD_FORMAT_SLONG = 9;
+ private static final int IFD_FORMAT_SRATIONAL = 10;
+ private static final int IFD_FORMAT_SINGLE = 11;
+ private static final int IFD_FORMAT_DOUBLE = 12;
+ // Format indicating a new IFD entry (See Adobe PageMaker® 6.0 TIFF Technical Notes, "New Tag")
+ private static final int IFD_FORMAT_IFD = 13;
+
+ private static final int SKIP_BUFFER_SIZE = 8192;
+
+ // Names for the data formats for debugging purpose.
+ private static final String[] IFD_FORMAT_NAMES = new String[]{
+ "", "BYTE", "STRING", "USHORT", "ULONG", "URATIONAL", "SBYTE", "UNDEFINED", "SSHORT",
+ "SLONG", "SRATIONAL", "SINGLE", "DOUBLE", "IFD"
+ };
+ // Sizes of the components of each IFD value format
+ private static final int[] IFD_FORMAT_BYTES_PER_FORMAT = new int[]{
+ 0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1
+ };
+
+ private static final byte[] EXIF_ASCII_PREFIX = new byte[]{
+ 0x41, 0x53, 0x43, 0x49, 0x49, 0x0, 0x0, 0x0
+ };
+
+ // A class for indicating EXIF rational type.
+ // TODO: b/308978831 - Migrate to android.util.Rational when the min API is 21.
+ @VisibleForTesting
+ static class Rational {
+ public final long numerator;
+ public final long denominator;
+
+ private Rational(long numerator, long denominator) {
+ // Handle erroneous case
+ if (denominator == 0) {
+ this.numerator = 0;
+ this.denominator = 1;
+ return;
+ }
+ this.numerator = numerator;
+ this.denominator = denominator;
+ }
+
+ /**
+ * Creates a new {@code Rational} which approximates the provided {@code double} value by
+ * using <a href="https://en.wikipedia.org/wiki/Continued_fraction">continued fractions</a>.
+ */
+ public static @NonNull Rational createFromDouble(double value) {
+ if (value >= Long.MAX_VALUE || value <= Long.MIN_VALUE) {
+ // value is too large to represent as a long, so just return the max/min value.
+ return new Rational(
+ /* numerator= */ value > 0 ? Long.MAX_VALUE : Long.MIN_VALUE,
+ /* denominator= */ 1);
+ }
+
+ double absoluteValue = Math.abs(value);
+ double threshold = 0.00000001 * absoluteValue;
+ double remainingValue = absoluteValue;
+ long numerator = 1;
+ long previousNumerator = 0;
+ long denominator = 0;
+ long previousDenominator = 1;
+ do {
+ double remainder = remainingValue % 1;
+ long wholePart = (long) (remainingValue - remainder);
+ long tmp = numerator;
+ numerator = wholePart * numerator + previousNumerator;
+ previousNumerator = tmp;
+
+ tmp = denominator;
+ denominator = wholePart * denominator + previousDenominator;
+ previousDenominator = tmp;
+
+ remainingValue = 1 / remainder;
+ } while ((Math.abs(absoluteValue - numerator / (double) denominator) > threshold));
+
+ return new Rational(value < 0 ? -numerator : numerator, denominator);
+ }
+
+ @Override
+ public @NonNull String toString() {
+ return numerator + "/" + denominator;
+ }
+
+ public double calculate() {
+ return (double) numerator / denominator;
+ }
+ }
+
+ // A class for indicating EXIF attribute.
+ private static class ExifAttribute {
+ public static final long BYTES_OFFSET_UNKNOWN = -1;
+
+ public final int format;
+ public final int numberOfComponents;
+ public final long bytesOffset;
+ public final byte[] bytes;
+
+ ExifAttribute(int format, int numberOfComponents, byte[] bytes) {
+ this(format, numberOfComponents, BYTES_OFFSET_UNKNOWN, bytes);
+ }
+
+ ExifAttribute(int format, int numberOfComponents, long bytesOffset, byte[] bytes) {
+ this.format = format;
+ this.numberOfComponents = numberOfComponents;
+ this.bytesOffset = bytesOffset;
+ this.bytes = bytes;
+ }
+
+ public static ExifAttribute createUShort(int[] values, ByteOrder byteOrder) {
+ final ByteBuffer buffer = ByteBuffer.wrap(
+ new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_USHORT] * values.length]);
+ buffer.order(byteOrder);
+ for (int value : values) {
+ buffer.putShort((short) value);
+ }
+ return new ExifAttribute(IFD_FORMAT_USHORT, values.length, buffer.array());
+ }
+
+ public static ExifAttribute createUShort(int value, ByteOrder byteOrder) {
+ return createUShort(new int[]{value}, byteOrder);
+ }
+
+ public static ExifAttribute createULong(long[] values, ByteOrder byteOrder) {
+ final ByteBuffer buffer = ByteBuffer.wrap(
+ new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_ULONG] * values.length]);
+ buffer.order(byteOrder);
+ for (long value : values) {
+ buffer.putInt((int) value);
+ }
+ return new ExifAttribute(IFD_FORMAT_ULONG, values.length, buffer.array());
+ }
+
+ public static ExifAttribute createULong(long value, ByteOrder byteOrder) {
+ return createULong(new long[]{value}, byteOrder);
+ }
+
+ public static ExifAttribute createSLong(int[] values, ByteOrder byteOrder) {
+ final ByteBuffer buffer = ByteBuffer.wrap(
+ new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_SLONG] * values.length]);
+ buffer.order(byteOrder);
+ for (int value : values) {
+ buffer.putInt(value);
+ }
+ return new ExifAttribute(IFD_FORMAT_SLONG, values.length, buffer.array());
+ }
+
+ public static ExifAttribute createByte(String value) {
+ // Exception for GPSAltitudeRef tag
+ if (value.length() == 1 && value.charAt(0) >= '0' && value.charAt(0) <= '1') {
+ final byte[] bytes = new byte[]{(byte) (value.charAt(0) - '0')};
+ return new ExifAttribute(IFD_FORMAT_BYTE, bytes.length, bytes);
+ }
+ final byte[] ascii = value.getBytes(ASCII);
+ return new ExifAttribute(IFD_FORMAT_BYTE, ascii.length, ascii);
+ }
+
+ public static ExifAttribute createString(String value) {
+ final byte[] ascii = (value + '\0').getBytes(ASCII);
+ return new ExifAttribute(IFD_FORMAT_STRING, ascii.length, ascii);
+ }
+
+ public static ExifAttribute createURational(Rational[] values, ByteOrder byteOrder) {
+ final ByteBuffer buffer = ByteBuffer.wrap(
+ new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_URATIONAL] * values.length]);
+ buffer.order(byteOrder);
+ for (Rational value : values) {
+ buffer.putInt((int) value.numerator);
+ buffer.putInt((int) value.denominator);
+ }
+ return new ExifAttribute(IFD_FORMAT_URATIONAL, values.length, buffer.array());
+ }
+
+ public static ExifAttribute createURational(Rational value, ByteOrder byteOrder) {
+ return createURational(new Rational[]{value}, byteOrder);
+ }
+
+ public static ExifAttribute createSRational(Rational[] values, ByteOrder byteOrder) {
+ final ByteBuffer buffer = ByteBuffer.wrap(
+ new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_SRATIONAL] * values.length]);
+ buffer.order(byteOrder);
+ for (Rational value : values) {
+ buffer.putInt((int) value.numerator);
+ buffer.putInt((int) value.denominator);
+ }
+ return new ExifAttribute(IFD_FORMAT_SRATIONAL, values.length, buffer.array());
+ }
+
+ public static ExifAttribute createDouble(double[] values, ByteOrder byteOrder) {
+ final ByteBuffer buffer = ByteBuffer.wrap(
+ new byte[IFD_FORMAT_BYTES_PER_FORMAT[IFD_FORMAT_DOUBLE] * values.length]);
+ buffer.order(byteOrder);
+ for (double value : values) {
+ buffer.putDouble(value);
+ }
+ return new ExifAttribute(IFD_FORMAT_DOUBLE, values.length, buffer.array());
+ }
+
+ @Override
+ public @NonNull String toString() {
+ return "(" + IFD_FORMAT_NAMES[format] + ", data length:" + bytes.length + ")";
+ }
+
+ Object getValue(ByteOrder byteOrder) {
+ ByteOrderedDataInputStream inputStream = null;
+ try {
+ inputStream = new ByteOrderedDataInputStream(bytes);
+ inputStream.setByteOrder(byteOrder);
+ switch (format) {
+ case IFD_FORMAT_BYTE:
+ case IFD_FORMAT_SBYTE: {
+ // Exception for GPSAltitudeRef tag
+ if (bytes.length == 1 && bytes[0] >= 0 && bytes[0] <= 1) {
+ return new String(new char[]{(char) (bytes[0] + '0')});
+ }
+ return new String(bytes, ASCII);
+ }
+ case IFD_FORMAT_UNDEFINED:
+ case IFD_FORMAT_STRING: {
+ int index = 0;
+ if (numberOfComponents >= EXIF_ASCII_PREFIX.length) {
+ boolean same = true;
+ for (int i = 0; i < EXIF_ASCII_PREFIX.length; ++i) {
+ if (bytes[i] != EXIF_ASCII_PREFIX[i]) {
+ same = false;
+ break;
+ }
+ }
+ if (same) {
+ index = EXIF_ASCII_PREFIX.length;
+ }
+ }
+
+ StringBuilder stringBuilder = new StringBuilder();
+ while (index < numberOfComponents) {
+ int ch = bytes[index];
+ if (ch == 0) {
+ break;
+ }
+ if (ch >= 32) {
+ stringBuilder.append((char) ch);
+ } else {
+ stringBuilder.append('?');
+ }
+ ++index;
+ }
+ return stringBuilder.toString();
+ }
+ case IFD_FORMAT_USHORT: {
+ final int[] values = new int[numberOfComponents];
+ for (int i = 0; i < numberOfComponents; ++i) {
+ values[i] = inputStream.readUnsignedShort();
+ }
+ return values;
+ }
+ case IFD_FORMAT_ULONG: {
+ final long[] values = new long[numberOfComponents];
+ for (int i = 0; i < numberOfComponents; ++i) {
+ values[i] = inputStream.readUnsignedInt();
+ }
+ return values;
+ }
+ case IFD_FORMAT_URATIONAL: {
+ final Rational[] values = new Rational[numberOfComponents];
+ for (int i = 0; i < numberOfComponents; ++i) {
+ final long numerator = inputStream.readUnsignedInt();
+ final long denominator = inputStream.readUnsignedInt();
+ values[i] = new Rational(numerator, denominator);
+ }
+ return values;
+ }
+ case IFD_FORMAT_SSHORT: {
+ final int[] values = new int[numberOfComponents];
+ for (int i = 0; i < numberOfComponents; ++i) {
+ values[i] = inputStream.readShort();
+ }
+ return values;
+ }
+ case IFD_FORMAT_SLONG: {
+ final int[] values = new int[numberOfComponents];
+ for (int i = 0; i < numberOfComponents; ++i) {
+ values[i] = inputStream.readInt();
+ }
+ return values;
+ }
+ case IFD_FORMAT_SRATIONAL: {
+ final Rational[] values = new Rational[numberOfComponents];
+ for (int i = 0; i < numberOfComponents; ++i) {
+ final long numerator = inputStream.readInt();
+ final long denominator = inputStream.readInt();
+ values[i] = new Rational(numerator, denominator);
+ }
+ return values;
+ }
+ case IFD_FORMAT_SINGLE: {
+ final double[] values = new double[numberOfComponents];
+ for (int i = 0; i < numberOfComponents; ++i) {
+ values[i] = inputStream.readFloat();
+ }
+ return values;
+ }
+ case IFD_FORMAT_DOUBLE: {
+ final double[] values = new double[numberOfComponents];
+ for (int i = 0; i < numberOfComponents; ++i) {
+ values[i] = inputStream.readDouble();
+ }
+ return values;
+ }
+ default:
+ return null;
+ }
+ } catch (IOException e) {
+ Log.w(TAG, "IOException occurred during reading a value", e);
+ return null;
+ } finally {
+ if (inputStream != null) {
+ try {
+ inputStream.close();
+ } catch (IOException e) {
+ Log.e(TAG, "IOException occurred while closing InputStream", e);
+ }
+ }
+ }
+ }
+
+ public double getDoubleValue(ByteOrder byteOrder) {
+ Object value = getValue(byteOrder);
+ if (value == null) {
+ throw new NumberFormatException("NULL can't be converted to a double value");
+ }
+ if (value instanceof String) {
+ return Double.parseDouble((String) value);
+ }
+ if (value instanceof long[]) {
+ long[] array = (long[]) value;
+ if (array.length == 1) {
+ return array[0];
+ }
+ throw new NumberFormatException("There are more than one component");
+ }
+ if (value instanceof int[]) {
+ int[] array = (int[]) value;
+ if (array.length == 1) {
+ return array[0];
+ }
+ throw new NumberFormatException("There are more than one component");
+ }
+ if (value instanceof double[]) {
+ double[] array = (double[]) value;
+ if (array.length == 1) {
+ return array[0];
+ }
+ throw new NumberFormatException("There are more than one component");
+ }
+ if (value instanceof Rational[]) {
+ Rational[] array = (Rational[]) value;
+ if (array.length == 1) {
+ return array[0].calculate();
+ }
+ throw new NumberFormatException("There are more than one component");
+ }
+ throw new NumberFormatException("Couldn't find a double value");
+ }
+
+ public int getIntValue(ByteOrder byteOrder) {
+ Object value = getValue(byteOrder);
+ if (value == null) {
+ throw new NumberFormatException("NULL can't be converted to a integer value");
+ }
+ if (value instanceof String) {
+ return Integer.parseInt((String) value);
+ }
+ if (value instanceof long[]) {
+ long[] array = (long[]) value;
+ if (array.length == 1) {
+ return (int) array[0];
+ }
+ throw new NumberFormatException("There are more than one component");
+ }
+ if (value instanceof int[]) {
+ int[] array = (int[]) value;
+ if (array.length == 1) {
+ return array[0];
+ }
+ throw new NumberFormatException("There are more than one component");
+ }
+ throw new NumberFormatException("Couldn't find a integer value");
+ }
+
+ public String getStringValue(ByteOrder byteOrder) {
+ Object value = getValue(byteOrder);
+ if (value == null) {
+ return null;
+ }
+ if (value instanceof String) {
+ return (String) value;
+ }
+
+ final StringBuilder stringBuilder = new StringBuilder();
+ if (value instanceof long[]) {
+ long[] array = (long[]) value;
+ for (int i = 0; i < array.length; ++i) {
+ stringBuilder.append(array[i]);
+ if (i + 1 != array.length) {
+ stringBuilder.append(",");
+ }
+ }
+ return stringBuilder.toString();
+ }
+ if (value instanceof int[]) {
+ int[] array = (int[]) value;
+ for (int i = 0; i < array.length; ++i) {
+ stringBuilder.append(array[i]);
+ if (i + 1 != array.length) {
+ stringBuilder.append(",");
+ }
+ }
+ return stringBuilder.toString();
+ }
+ if (value instanceof double[]) {
+ double[] array = (double[]) value;
+ for (int i = 0; i < array.length; ++i) {
+ stringBuilder.append(array[i]);
+ if (i + 1 != array.length) {
+ stringBuilder.append(",");
+ }
+ }
+ return stringBuilder.toString();
+ }
+ if (value instanceof Rational[]) {
+ Rational[] array = (Rational[]) value;
+ for (int i = 0; i < array.length; ++i) {
+ stringBuilder.append(array[i].numerator);
+ stringBuilder.append('/');
+ stringBuilder.append(array[i].denominator);
+ if (i + 1 != array.length) {
+ stringBuilder.append(",");
+ }
+ }
+ return stringBuilder.toString();
+ }
+ return null;
+ }
+
+ public int size() {
+ return IFD_FORMAT_BYTES_PER_FORMAT[format] * numberOfComponents;
+ }
+ }
+
+ // A class for indicating EXIF tag.
+ private static class ExifTag {
+ public final int number;
+ public final String name;
+ public final int primaryFormat;
+ public final int secondaryFormat;
+
+ ExifTag(String name, int number, int format) {
+ this.name = name;
+ this.number = number;
+ this.primaryFormat = format;
+ this.secondaryFormat = -1;
+ }
+
+ ExifTag(String name, int number, int primaryFormat, int secondaryFormat) {
+ this.name = name;
+ this.number = number;
+ this.primaryFormat = primaryFormat;
+ this.secondaryFormat = secondaryFormat;
+ }
+
+ boolean isFormatCompatible(int format) {
+ if (primaryFormat == IFD_FORMAT_UNDEFINED || format == IFD_FORMAT_UNDEFINED) {
+ return true;
+ } else if (primaryFormat == format || secondaryFormat == format) {
+ return true;
+ } else if ((primaryFormat == IFD_FORMAT_ULONG || secondaryFormat == IFD_FORMAT_ULONG)
+ && format == IFD_FORMAT_USHORT) {
+ return true;
+ } else if ((primaryFormat == IFD_FORMAT_SLONG || secondaryFormat == IFD_FORMAT_SLONG)
+ && format == IFD_FORMAT_SSHORT) {
+ return true;
+ } else if ((primaryFormat == IFD_FORMAT_DOUBLE || secondaryFormat == IFD_FORMAT_DOUBLE)
+ && format == IFD_FORMAT_SINGLE) {
+ return true;
+ }
+ return false;
+ }
+ }
+
+ // Primary image IFD TIFF tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels)
+ private static final ExifTag[] IFD_TIFF_TAGS = new ExifTag[]{
+ // For below two, see TIFF 6.0 Spec Section 3: Bilevel Images.
+ new ExifTag(TAG_NEW_SUBFILE_TYPE, 254, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_SUBFILE_TYPE, 255, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_IMAGE_WIDTH, 256, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_IMAGE_LENGTH, 257, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_BITS_PER_SAMPLE, 258, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_COMPRESSION, 259, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_IMAGE_DESCRIPTION, 270, IFD_FORMAT_STRING),
+ new ExifTag(TAG_MAKE, 271, IFD_FORMAT_STRING),
+ new ExifTag(TAG_MODEL, 272, IFD_FORMAT_STRING),
+ new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_ORIENTATION, 274, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_SAMPLES_PER_PIXEL, 277, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_ROWS_PER_STRIP, 278, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_STRIP_BYTE_COUNTS, 279, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_X_RESOLUTION, 282, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_Y_RESOLUTION, 283, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_PLANAR_CONFIGURATION, 284, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_RESOLUTION_UNIT, 296, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_TRANSFER_FUNCTION, 301, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_SOFTWARE, 305, IFD_FORMAT_STRING),
+ new ExifTag(TAG_DATETIME, 306, IFD_FORMAT_STRING),
+ new ExifTag(TAG_ARTIST, 315, IFD_FORMAT_STRING),
+ new ExifTag(TAG_WHITE_POINT, 318, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319, IFD_FORMAT_URATIONAL),
+ // See Adobe PageMaker® 6.0 TIFF Technical Notes, Note 1.
+ new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_Y_CB_CR_POSITIONING, 531, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_COPYRIGHT, 33432, IFD_FORMAT_STRING),
+ new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG),
+ // RW2 file tags
+ // See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/PanasonicRaw.html)
+ new ExifTag(TAG_RW2_SENSOR_TOP_BORDER, 4, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_RW2_SENSOR_LEFT_BORDER, 5, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_RW2_SENSOR_BOTTOM_BORDER, 6, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_RW2_SENSOR_RIGHT_BORDER, 7, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_RW2_ISO, 23, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_RW2_JPG_FROM_RAW, 46, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_XMP, 700, IFD_FORMAT_BYTE),
+ };
+
+ // Primary image IFD Exif Private tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels)
+ private static final ExifTag[] IFD_EXIF_TAGS = new ExifTag[]{
+ new ExifTag(TAG_EXPOSURE_TIME, 33434, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_F_NUMBER, 33437, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_EXPOSURE_PROGRAM, 34850, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_SPECTRAL_SENSITIVITY, 34852, IFD_FORMAT_STRING),
+ new ExifTag(TAG_PHOTOGRAPHIC_SENSITIVITY, 34855, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_OECF, 34856, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_SENSITIVITY_TYPE, 34864, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_STANDARD_OUTPUT_SENSITIVITY, 34865, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_RECOMMENDED_EXPOSURE_INDEX, 34866, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_ISO_SPEED, 34867, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_ISO_SPEED_LATITUDE_YYY, 34868, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_ISO_SPEED_LATITUDE_ZZZ, 34869, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_EXIF_VERSION, 36864, IFD_FORMAT_STRING),
+ new ExifTag(TAG_DATETIME_ORIGINAL, 36867, IFD_FORMAT_STRING),
+ new ExifTag(TAG_DATETIME_DIGITIZED, 36868, IFD_FORMAT_STRING),
+ new ExifTag(TAG_OFFSET_TIME, 36880, IFD_FORMAT_STRING),
+ new ExifTag(TAG_OFFSET_TIME_ORIGINAL, 36881, IFD_FORMAT_STRING),
+ new ExifTag(TAG_OFFSET_TIME_DIGITIZED, 36882, IFD_FORMAT_STRING),
+ new ExifTag(TAG_COMPONENTS_CONFIGURATION, 37121, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_COMPRESSED_BITS_PER_PIXEL, 37122, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_SHUTTER_SPEED_VALUE, 37377, IFD_FORMAT_SRATIONAL),
+ new ExifTag(TAG_APERTURE_VALUE, 37378, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_BRIGHTNESS_VALUE, 37379, IFD_FORMAT_SRATIONAL),
+ new ExifTag(TAG_EXPOSURE_BIAS_VALUE, 37380, IFD_FORMAT_SRATIONAL),
+ new ExifTag(TAG_MAX_APERTURE_VALUE, 37381, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_SUBJECT_DISTANCE, 37382, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_METERING_MODE, 37383, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_LIGHT_SOURCE, 37384, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_FLASH, 37385, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_FOCAL_LENGTH, 37386, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_SUBJECT_AREA, 37396, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_MAKER_NOTE, 37500, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_USER_COMMENT, 37510, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_SUBSEC_TIME, 37520, IFD_FORMAT_STRING),
+ new ExifTag(TAG_SUBSEC_TIME_ORIGINAL, 37521, IFD_FORMAT_STRING),
+ new ExifTag(TAG_SUBSEC_TIME_DIGITIZED, 37522, IFD_FORMAT_STRING),
+ new ExifTag(TAG_FLASHPIX_VERSION, 40960, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_COLOR_SPACE, 40961, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_PIXEL_X_DIMENSION, 40962, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_PIXEL_Y_DIMENSION, 40963, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_RELATED_SOUND_FILE, 40964, IFD_FORMAT_STRING),
+ new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_FLASH_ENERGY, 41483, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_SPATIAL_FREQUENCY_RESPONSE, 41484, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_FOCAL_PLANE_X_RESOLUTION, 41486, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_FOCAL_PLANE_Y_RESOLUTION, 41487, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_FOCAL_PLANE_RESOLUTION_UNIT, 41488, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_SUBJECT_LOCATION, 41492, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_EXPOSURE_INDEX, 41493, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_SENSING_METHOD, 41495, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_FILE_SOURCE, 41728, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_SCENE_TYPE, 41729, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_CFA_PATTERN, 41730, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_CUSTOM_RENDERED, 41985, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_EXPOSURE_MODE, 41986, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_WHITE_BALANCE, 41987, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_DIGITAL_ZOOM_RATIO, 41988, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_FOCAL_LENGTH_IN_35MM_FILM, 41989, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_SCENE_CAPTURE_TYPE, 41990, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_GAIN_CONTROL, 41991, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_CONTRAST, 41992, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_SATURATION, 41993, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_SHARPNESS, 41994, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_DEVICE_SETTING_DESCRIPTION, 41995, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_SUBJECT_DISTANCE_RANGE, 41996, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_IMAGE_UNIQUE_ID, 42016, IFD_FORMAT_STRING),
+ new ExifTag(TAG_CAMERA_OWNER_NAME, 42032, IFD_FORMAT_STRING),
+ new ExifTag(TAG_BODY_SERIAL_NUMBER, 42033, IFD_FORMAT_STRING),
+ new ExifTag(TAG_LENS_SPECIFICATION, 42034, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_LENS_MAKE, 42035, IFD_FORMAT_STRING),
+ new ExifTag(TAG_LENS_MODEL, 42036, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GAMMA, 42240, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_DNG_VERSION, 50706, IFD_FORMAT_BYTE),
+ new ExifTag(TAG_DEFAULT_CROP_SIZE, 50720, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG)
+ };
+
+ // Primary image IFD GPS Info tags (See JEITA CP-3451C Section 4.6.6 Tag Support Levels)
+ private static final ExifTag[] IFD_GPS_TAGS = new ExifTag[]{
+ new ExifTag(TAG_GPS_VERSION_ID, 0, IFD_FORMAT_BYTE),
+ new ExifTag(TAG_GPS_LATITUDE_REF, 1, IFD_FORMAT_STRING),
+ // Allow SRATIONAL to be compatible with apps using wrong format and
+ // even if it is negative, it may be valid latitude / longitude.
+ new ExifTag(TAG_GPS_LATITUDE, 2, IFD_FORMAT_URATIONAL, IFD_FORMAT_SRATIONAL),
+ new ExifTag(TAG_GPS_LONGITUDE_REF, 3, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_LONGITUDE, 4, IFD_FORMAT_URATIONAL, IFD_FORMAT_SRATIONAL),
+ new ExifTag(TAG_GPS_ALTITUDE_REF, 5, IFD_FORMAT_BYTE),
+ new ExifTag(TAG_GPS_ALTITUDE, 6, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_GPS_TIMESTAMP, 7, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_GPS_SATELLITES, 8, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_STATUS, 9, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_MEASURE_MODE, 10, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_DOP, 11, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_GPS_SPEED_REF, 12, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_SPEED, 13, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_GPS_TRACK_REF, 14, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_TRACK, 15, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_GPS_IMG_DIRECTION_REF, 16, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_IMG_DIRECTION, 17, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_GPS_MAP_DATUM, 18, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_DEST_LATITUDE_REF, 19, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_DEST_LATITUDE, 20, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_GPS_DEST_LONGITUDE_REF, 21, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_DEST_LONGITUDE, 22, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_GPS_DEST_BEARING_REF, 23, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_DEST_BEARING, 24, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_GPS_DEST_DISTANCE_REF, 25, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_DEST_DISTANCE, 26, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_GPS_PROCESSING_METHOD, 27, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_GPS_AREA_INFORMATION, 28, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_GPS_DATESTAMP, 29, IFD_FORMAT_STRING),
+ new ExifTag(TAG_GPS_DIFFERENTIAL, 30, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_GPS_H_POSITIONING_ERROR, 31, IFD_FORMAT_URATIONAL)
+ };
+ // Primary image IFD Interoperability tag (See JEITA CP-3451C Section 4.6.8 Tag Support Levels)
+ private static final ExifTag[] IFD_INTEROPERABILITY_TAGS = new ExifTag[]{
+ new ExifTag(TAG_INTEROPERABILITY_INDEX, 1, IFD_FORMAT_STRING)
+ };
+ // IFD Thumbnail tags (See JEITA CP-3451C Section 4.6.8 Tag Support Levels)
+ private static final ExifTag[] IFD_THUMBNAIL_TAGS = new ExifTag[]{
+ // For below two, see TIFF 6.0 Spec Section 3: Bilevel Images.
+ new ExifTag(TAG_NEW_SUBFILE_TYPE, 254, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_SUBFILE_TYPE, 255, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_THUMBNAIL_IMAGE_WIDTH, 256, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_THUMBNAIL_IMAGE_LENGTH, 257, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_BITS_PER_SAMPLE, 258, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_COMPRESSION, 259, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_PHOTOMETRIC_INTERPRETATION, 262, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_IMAGE_DESCRIPTION, 270, IFD_FORMAT_STRING),
+ new ExifTag(TAG_MAKE, 271, IFD_FORMAT_STRING),
+ new ExifTag(TAG_MODEL, 272, IFD_FORMAT_STRING),
+ new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_THUMBNAIL_ORIENTATION, 274, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_SAMPLES_PER_PIXEL, 277, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_ROWS_PER_STRIP, 278, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_STRIP_BYTE_COUNTS, 279, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_X_RESOLUTION, 282, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_Y_RESOLUTION, 283, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_PLANAR_CONFIGURATION, 284, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_RESOLUTION_UNIT, 296, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_TRANSFER_FUNCTION, 301, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_SOFTWARE, 305, IFD_FORMAT_STRING),
+ new ExifTag(TAG_DATETIME, 306, IFD_FORMAT_STRING),
+ new ExifTag(TAG_ARTIST, 315, IFD_FORMAT_STRING),
+ new ExifTag(TAG_WHITE_POINT, 318, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_PRIMARY_CHROMATICITIES, 319, IFD_FORMAT_URATIONAL),
+ // See Adobe PageMaker® 6.0 TIFF Technical Notes, Note 1.
+ new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT, 513, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, 514, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_Y_CB_CR_COEFFICIENTS, 529, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_Y_CB_CR_SUB_SAMPLING, 530, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_Y_CB_CR_POSITIONING, 531, IFD_FORMAT_USHORT),
+ new ExifTag(TAG_REFERENCE_BLACK_WHITE, 532, IFD_FORMAT_URATIONAL),
+ new ExifTag(TAG_COPYRIGHT, 33432, IFD_FORMAT_STRING),
+ new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_DNG_VERSION, 50706, IFD_FORMAT_BYTE),
+ new ExifTag(TAG_DEFAULT_CROP_SIZE, 50720, IFD_FORMAT_USHORT, IFD_FORMAT_ULONG)
+ };
+
+ // RAF file tag (See piex.cc line 372)
+ private static final ExifTag TAG_RAF_IMAGE_SIZE =
+ new ExifTag(TAG_STRIP_OFFSETS, 273, IFD_FORMAT_USHORT);
+
+ // ORF file tags (See http://www.exiv2.org/tags-olympus.html)
+ private static final ExifTag[] ORF_MAKER_NOTE_TAGS = new ExifTag[]{
+ new ExifTag(TAG_ORF_THUMBNAIL_IMAGE, 256, IFD_FORMAT_UNDEFINED),
+ new ExifTag(TAG_ORF_CAMERA_SETTINGS_IFD_POINTER, 8224, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_ORF_IMAGE_PROCESSING_IFD_POINTER, 8256, IFD_FORMAT_ULONG)
+ };
+ private static final ExifTag[] ORF_CAMERA_SETTINGS_TAGS = new ExifTag[]{
+ new ExifTag(TAG_ORF_PREVIEW_IMAGE_START, 257, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_ORF_PREVIEW_IMAGE_LENGTH, 258, IFD_FORMAT_ULONG)
+ };
+ private static final ExifTag[] ORF_IMAGE_PROCESSING_TAGS = new ExifTag[]{
+ new ExifTag(TAG_ORF_ASPECT_FRAME, 4371, IFD_FORMAT_USHORT)
+ };
+ // PEF file tag (See http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/Pentax.html)
+ private static final ExifTag[] PEF_TAGS = new ExifTag[]{
+ new ExifTag(TAG_COLOR_SPACE, 55, IFD_FORMAT_USHORT)
+ };
+
+ // See JEITA CP-3451C Section 4.6.3: Exif-specific IFD.
+ // The following values are used for indicating pointers to the other Image File Directories.
+
+ // Indices of Exif Ifd tag groups
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({IFD_TYPE_PRIMARY, IFD_TYPE_EXIF, IFD_TYPE_GPS, IFD_TYPE_INTEROPERABILITY,
+ IFD_TYPE_THUMBNAIL, IFD_TYPE_PREVIEW, IFD_TYPE_ORF_MAKER_NOTE,
+ IFD_TYPE_ORF_CAMERA_SETTINGS, IFD_TYPE_ORF_IMAGE_PROCESSING, IFD_TYPE_PEF})
+ public @interface IfdType {
+ }
+
+ private static final int IFD_TYPE_PRIMARY = 0;
+ private static final int IFD_TYPE_EXIF = 1;
+ private static final int IFD_TYPE_GPS = 2;
+ private static final int IFD_TYPE_INTEROPERABILITY = 3;
+ private static final int IFD_TYPE_THUMBNAIL = 4;
+ private static final int IFD_TYPE_PREVIEW = 5;
+ private static final int IFD_TYPE_ORF_MAKER_NOTE = 6;
+ private static final int IFD_TYPE_ORF_CAMERA_SETTINGS = 7;
+ private static final int IFD_TYPE_ORF_IMAGE_PROCESSING = 8;
+ private static final int IFD_TYPE_PEF = 9;
+
+ // List of Exif tag groups, indexed by the IDF_TYPE_* constants above.
+ static final ExifTag[][] EXIF_TAGS =
+ new ExifTag[][]{
+ IFD_TIFF_TAGS, IFD_EXIF_TAGS, IFD_GPS_TAGS, IFD_INTEROPERABILITY_TAGS,
+ IFD_THUMBNAIL_TAGS, IFD_TIFF_TAGS, ORF_MAKER_NOTE_TAGS, ORF_CAMERA_SETTINGS_TAGS,
+ ORF_IMAGE_PROCESSING_TAGS, PEF_TAGS
+ };
+ // List of tags for pointing to the other image file directory offset.
+ private static final ExifTag[] EXIF_POINTER_TAGS = new ExifTag[]{
+ new ExifTag(TAG_SUB_IFD_POINTER, 330, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_EXIF_IFD_POINTER, 34665, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_GPS_INFO_IFD_POINTER, 34853, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_INTEROPERABILITY_IFD_POINTER, 40965, IFD_FORMAT_ULONG),
+ new ExifTag(TAG_ORF_CAMERA_SETTINGS_IFD_POINTER, 8224, IFD_FORMAT_BYTE),
+ new ExifTag(TAG_ORF_IMAGE_PROCESSING_IFD_POINTER, 8256, IFD_FORMAT_BYTE)
+ };
+
+ // Mappings from tag number to tag name and each item represents one IFD tag group.
+ @SuppressWarnings("unchecked")
+ private static final HashMap<Integer, ExifTag>[] sExifTagMapsForReading =
+ new HashMap[EXIF_TAGS.length];
+ // Mappings from tag name to tag number and each item represents one IFD tag group.
+ @SuppressWarnings("unchecked")
+ private static final HashMap<String, ExifTag>[] sExifTagMapsForWriting =
+ new HashMap[EXIF_TAGS.length];
+
+ /**
+ * These are tags of type 'Unsigned rational' but which are handled in decimal form.
+ *
+ * <p>This means they are output from {@link #getAttribute(String)}, and accepted into {@link
+ * #setAttribute(String, String)}, as strings in decimal form (e.g. {@code "0.125"}, {@code
+ * "6.25E-4"}).
+ *
+ * <p>This is to maintain backwards compatibility with a previous implementation of the {@link
+ * android.media.ExifInterface} (the platform variant of this class).
+ *
+ * <p>See <a
+ * href="http://ag/c/platform/frameworks/base/+/909922/2..9/api/current.txt#b20093">this
+ * internal code review comment from 2016</a> for more details.
+ */
+ private static final Set<String> RATIONAL_TAGS_HANDLED_AS_DECIMALS_FOR_COMPATIBILITY =
+ Collections.unmodifiableSet(
+ new HashSet<>(
+ Arrays.asList(
+ TAG_F_NUMBER,
+ TAG_DIGITAL_ZOOM_RATIO,
+ TAG_EXPOSURE_TIME,
+ TAG_SUBJECT_DISTANCE)));
+
+ // Mappings from tag number to IFD type for pointer tags.
+ private static final HashMap<Integer, Integer> sExifPointerTagMap = new HashMap<>();
+
+ // See JPEG File Interchange Format Version 1.02.
+ // The following values are defined for handling JPEG streams. In this implementation, we are
+ // not only getting information from EXIF but also from some JPEG special segments such as
+ // MARKER_COM for user comment and MARKER_SOFx for image width and height.
+ private static final Charset ASCII = Charset.forName("US-ASCII");
+ // Identifier for EXIF APP1 segment in JPEG
+ @VisibleForTesting
+ static final byte[] IDENTIFIER_EXIF_APP1 = "Exif\0\0".getBytes(ASCII);
+ // Identifier for XMP APP1 segment in JPEG
+ private static final byte[] IDENTIFIER_XMP_APP1 =
+ "http://ns.adobe.com/xap/1.0/\0".getBytes(ASCII);
+ // JPEG segment markers, that each marker consumes two bytes beginning with 0xff and ending with
+ // the indicator. There is no SOF4, SOF8, SOF16 markers in JPEG and SOFx markers indicates start
+ // of frame(baseline DCT) and the image size info exists in its beginning part.
+ private static final byte MARKER = (byte) 0xff;
+ private static final byte MARKER_SOI = (byte) 0xd8;
+ private static final byte MARKER_SOF0 = (byte) 0xc0;
+ private static final byte MARKER_SOF1 = (byte) 0xc1;
+ private static final byte MARKER_SOF2 = (byte) 0xc2;
+ private static final byte MARKER_SOF3 = (byte) 0xc3;
+ private static final byte MARKER_SOF5 = (byte) 0xc5;
+ private static final byte MARKER_SOF6 = (byte) 0xc6;
+ private static final byte MARKER_SOF7 = (byte) 0xc7;
+ private static final byte MARKER_SOF9 = (byte) 0xc9;
+ private static final byte MARKER_SOF10 = (byte) 0xca;
+ private static final byte MARKER_SOF11 = (byte) 0xcb;
+ private static final byte MARKER_SOF13 = (byte) 0xcd;
+ private static final byte MARKER_SOF14 = (byte) 0xce;
+ private static final byte MARKER_SOF15 = (byte) 0xcf;
+ private static final byte MARKER_SOS = (byte) 0xda;
+ @VisibleForTesting
+ static final byte MARKER_APP1 = (byte) 0xe1;
+ private static final byte MARKER_COM = (byte) 0xfe;
+ private static final byte MARKER_EOI = (byte) 0xd9;
+
+ // Supported Image File Types
+ private static final int IMAGE_TYPE_UNKNOWN = 0;
+ private static final int IMAGE_TYPE_DNG = 3;
+ private static final int IMAGE_TYPE_JPEG = 4;
+ private static final int IMAGE_TYPE_ORF = 7;
+ private static final int IMAGE_TYPE_PEF = 8;
+ private static final int IMAGE_TYPE_RAF = 9;
+ private static final int IMAGE_TYPE_RW2 = 10;
+ private static final int IMAGE_TYPE_HEIC = 12;
+ private static final int IMAGE_TYPE_PNG = 13;
+ private static final int IMAGE_TYPE_WEBP = 14;
+ private static final int IMAGE_TYPE_AVIF = 15;
+
+ static {
+ sFormatterPrimary = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.US);
+ sFormatterPrimary.setTimeZone(TimeZone.getTimeZone("UTC"));
+ sFormatterSecondary = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
+ sFormatterSecondary.setTimeZone(TimeZone.getTimeZone("UTC"));
+
+ // Build up the hash tables to look up Exif tags for reading Exif tags.
+ for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) {
+ sExifTagMapsForReading[ifdType] = new HashMap<>();
+ sExifTagMapsForWriting[ifdType] = new HashMap<>();
+ for (ExifTag tag : EXIF_TAGS[ifdType]) {
+ sExifTagMapsForReading[ifdType].put(tag.number, tag);
+ sExifTagMapsForWriting[ifdType].put(tag.name, tag);
+ }
+ }
+
+ // Build up the hash table to look up Exif pointer tags.
+ sExifPointerTagMap.put(EXIF_POINTER_TAGS[0].number, IFD_TYPE_PREVIEW); // 330
+ sExifPointerTagMap.put(EXIF_POINTER_TAGS[1].number, IFD_TYPE_EXIF); // 34665
+ sExifPointerTagMap.put(EXIF_POINTER_TAGS[2].number, IFD_TYPE_GPS); // 34853
+ sExifPointerTagMap.put(EXIF_POINTER_TAGS[3].number, IFD_TYPE_INTEROPERABILITY); // 40965
+ sExifPointerTagMap.put(EXIF_POINTER_TAGS[4].number, IFD_TYPE_ORF_CAMERA_SETTINGS); // 8224
+ sExifPointerTagMap.put(EXIF_POINTER_TAGS[5].number, IFD_TYPE_ORF_IMAGE_PROCESSING); // 8256
+ }
+
+ private String mFilename;
+ private FileDescriptor mSeekableFileDescriptor;
+ private AssetManager.AssetInputStream mAssetInputStream;
+ private int mMimeType;
+ private boolean mIsExifDataOnly;
+ @SuppressWarnings("unchecked")
+ private final HashMap<String, ExifAttribute>[] mAttributes = new HashMap[EXIF_TAGS.length];
+ private Set<Integer> mAttributesOffsets = new HashSet<>(EXIF_TAGS.length);
+ private ByteOrder mExifByteOrder = BIG_ENDIAN;
+ private boolean mHasThumbnail;
+ private boolean mHasThumbnailStrips;
+ private boolean mAreThumbnailStripsConsecutive;
+ // Used to indicate the position of the thumbnail (doesn't include offset to EXIF data segment).
+ private int mThumbnailOffset;
+ private int mThumbnailLength;
+ private byte[] mThumbnailBytes;
+ private int mThumbnailCompression;
+ // Used to indicate offset from the start of the original input stream to EXIF data
+ private int mOffsetToExifData;
+ private int mOrfMakerNoteOffset;
+
+ /**
+ * The position of the thumbnail within the Exif data (from {@link #mOffsetToExifData}).
+ */
+ private int mOrfThumbnailOffset;
+
+ private int mOrfThumbnailLength;
+ private boolean mModified;
+
+ /**
+ * XMP data can occur as either part of the TIFF/Exif data (tag number 700), or as a separate
+ * section of the file (e.g. a separate APP1 segment in JPEG, or an iTXt chunk in PNG). XMP read
+ * from within the TIFF/Exif data is stored in {@link #mAttributes}, while XMP read from a
+ * separate section is here. If both are present, the disambiguation rules vary per file format,
+ * see {@link #getXmpHandlingForImageType(int)}.
+ */
+ @Nullable
+ private ExifAttribute mXmpFromSeparateMarker;
+
+ /**
+ * True if the file on disk contains XMP in a separate section.
+ *
+ * <p>This means the file the instance was loaded with, or the file created by the last call to
+ * {@link #saveAttributes()}.
+ */
+ private boolean mFileOnDiskContainsSeparateXmpMarker;
+
+ // Pattern to check non zero timestamp
+ private static final Pattern NON_ZERO_TIME_PATTERN = Pattern.compile(".*[1-9].*");
+ // Pattern to check gps timestamp
+ private static final Pattern GPS_TIMESTAMP_PATTERN =
+ Pattern.compile("^(\\d{2}):(\\d{2}):(\\d{2})$");
+ // Pattern to check date time primary format (e.g. 2020:01:01 00:00:00)
+ private static final Pattern DATETIME_PRIMARY_FORMAT_PATTERN =
+ Pattern.compile("^(\\d{4}):(\\d{2}):(\\d{2})\\s(\\d{2}):(\\d{2}):(\\d{2})$");
+ // Pattern to check date time secondary format (e.g. 2020-01-01 00:00:00)
+ private static final Pattern DATETIME_SECONDARY_FORMAT_PATTERN =
+ Pattern.compile("^(\\d{4})-(\\d{2})-(\\d{2})\\s(\\d{2}):(\\d{2}):(\\d{2})$");
+ private static final int DATETIME_VALUE_STRING_LENGTH = 19;
+
+ /**
+ * Reads Exif tags from the specified image file.
+ *
+ * @param file the file of the image data
+ * @throws NullPointerException if file is null
+ * @throws IOException if an I/O error occurs while retrieving file descriptor via
+ * {@link FileInputStream#getFD()}.
+ */
+ public ExifInterfaceFork(@NonNull File file) throws IOException {
+ if (file == null) {
+ throw new NullPointerException("file cannot be null");
+ }
+ initForFilename(file.getAbsolutePath());
+ }
+
+ /**
+ * Reads Exif tags from the specified image file.
+ *
+ * @param filename the name of the file of the image data
+ * @throws NullPointerException if file name is null
+ * @throws IOException if an I/O error occurs while retrieving file descriptor via
+ * {@link FileInputStream#getFD()}.
+ */
+ public ExifInterfaceFork(@NonNull String filename) throws IOException {
+ if (filename == null) {
+ throw new NullPointerException("filename cannot be null");
+ }
+ initForFilename(filename);
+ }
+
+ /**
+ * Reads Exif tags from the specified image file descriptor. Attribute mutation is supported
+ * for writable and seekable file descriptors only. This constructor will not rewind the offset
+ * of the given file descriptor. Developers should close the file descriptor after use.
+ *
+ * @param fileDescriptor the file descriptor of the image data
+ * @throws NullPointerException if file descriptor is null
+ * @throws IOException if an error occurs while duplicating the file descriptor.
+ */
+ public ExifInterfaceFork(@NonNull FileDescriptor fileDescriptor) throws IOException {
+ if (fileDescriptor == null) {
+ throw new NullPointerException("fileDescriptor cannot be null");
+ }
+ mAssetInputStream = null;
+ mFilename = null;
+
+ boolean isFdDuped = false;
+ if (isSeekableFD(fileDescriptor)) {
+ mSeekableFileDescriptor = fileDescriptor;
+ // Keep the original file descriptor in order to save attributes when it's seekable.
+ // Otherwise, just close the given file descriptor after reading it because the save
+ // feature won't be working.
+ try {
+ fileDescriptor = Os.dup(fileDescriptor);
+ isFdDuped = true;
+ } catch (Exception e) {
+ throw new IOException("Failed to duplicate file descriptor", e);
+ }
+ } else {
+ mSeekableFileDescriptor = null;
+ }
+ FileInputStream in = null;
+ try {
+ in = new FileInputStream(fileDescriptor);
+ loadAttributes(in);
+ } finally {
+ closeQuietly(in);
+ if (isFdDuped) {
+ closeFileDescriptor(fileDescriptor);
+ }
+ }
+ }
+
+ /**
+ * Reads Exif tags from the specified image input stream. Attribute mutation is not supported
+ * for input streams. The given input stream will proceed from its current position. Developers
+ * should close the input stream after use. This constructor is not intended to be used with
+ * an input stream that performs any networking operations.
+ *
+ * @param inputStream the input stream that contains the image data
+ * @throws NullPointerException if the input stream is null
+ */
+ public ExifInterfaceFork(@NonNull InputStream inputStream) throws IOException {
+ this(inputStream, STREAM_TYPE_FULL_IMAGE_DATA);
+ }
+
+ /**
+ * Reads Exif tags from the specified image input stream based on the stream type. Attribute
+ * mutation is not supported for input streams. The given input stream will proceed from its
+ * current position. Developers should close the input stream after use. This constructor is not
+ * intended to be used with an input stream that performs any networking operations.
+ *
+ * @param inputStream the input stream that contains the image data
+ * @param streamType the type of input stream
+ * @throws NullPointerException if the input stream is null
+ * @throws IOException if an I/O error occurs while retrieving file descriptor via
+ * {@link FileInputStream#getFD()}.
+ */
+ public ExifInterfaceFork(@NonNull InputStream inputStream, @ExifStreamType int streamType)
+ throws IOException {
+ if (inputStream == null) {
+ throw new NullPointerException("inputStream cannot be null");
+ }
+ mFilename = null;
+
+ mIsExifDataOnly = streamType == STREAM_TYPE_EXIF_DATA_ONLY;
+ if (mIsExifDataOnly) {
+ mAssetInputStream = null;
+ mSeekableFileDescriptor = null;
+ } else {
+ if (inputStream instanceof AssetManager.AssetInputStream) {
+ mAssetInputStream = (AssetManager.AssetInputStream) inputStream;
+ mSeekableFileDescriptor = null;
+ } else if (inputStream instanceof FileInputStream
+ && isSeekableFD(((FileInputStream) inputStream).getFD())) {
+ mAssetInputStream = null;
+ mSeekableFileDescriptor = ((FileInputStream) inputStream).getFD();
+ } else {
+ mAssetInputStream = null;
+ mSeekableFileDescriptor = null;
+ }
+ }
+ loadAttributes(inputStream);
+ }
+
+ /**
+ * Returns whether ExifInterface currently supports reading data from the specified mime type
+ * or not.
+ *
+ * @param mimeType the string value of mime type
+ */
+ public static boolean isSupportedMimeType(@NonNull String mimeType) {
+ if (mimeType == null) {
+ throw new NullPointerException("mimeType shouldn't be null");
+ }
+
+ switch (mimeType.toLowerCase(Locale.ROOT)) {
+ case "image/jpeg":
+ case "image/x-adobe-dng":
+ case "image/x-canon-cr2":
+ case "image/x-nikon-nef":
+ case "image/x-nikon-nrw":
+ case "image/x-sony-arw":
+ case "image/x-panasonic-rw2":
+ case "image/x-olympus-orf":
+ case "image/x-pentax-pef":
+ case "image/x-samsung-srw":
+ case "image/x-fuji-raf":
+ case "image/heic":
+ case "image/heif":
+ case "image/png":
+ case "image/webp":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Returns the EXIF attribute of the specified tag or {@code null} if there is no such tag in
+ * the image file.
+ *
+ * @param tag the name of the tag.
+ */
+ private @Nullable ExifAttribute getExifAttribute(@NonNull String tag) {
+ if (tag == null) {
+ throw new NullPointerException("tag shouldn't be null");
+ }
+ // Maintain compatibility.
+ if (TAG_ISO_SPEED_RATINGS.equals(tag)) {
+ if (DEBUG) {
+ Log.d(TAG, "getExifAttribute: Replacing TAG_ISO_SPEED_RATINGS with "
+ + "TAG_PHOTOGRAPHIC_SENSITIVITY.");
+ }
+ tag = TAG_PHOTOGRAPHIC_SENSITIVITY;
+ }
+ if (TAG_XMP.equals(tag)
+ && getXmpHandlingForImageType(mMimeType) == XMP_HANDLING_PREFER_SEPARATE
+ && mXmpFromSeparateMarker != null) {
+ return mXmpFromSeparateMarker;
+ }
+ // Retrieves all tag groups. The value from primary image tag group has a higher priority
+ // than the value from the thumbnail tag group if there are more than one candidates.
+ for (int i = 0; i < EXIF_TAGS.length; ++i) {
+ ExifAttribute value = mAttributes[i].get(tag);
+ if (value != null) {
+ return value;
+ }
+ }
+ if (TAG_XMP.equals(tag) && mXmpFromSeparateMarker != null) {
+ return mXmpFromSeparateMarker;
+ }
+ return null;
+ }
+
+ private static @XmpHandling int getXmpHandlingForImageType(int imageType) {
+ switch (imageType) {
+ // ExifInterface has a documented (but spec-violating) preference for reading and
+ // writing JPEG XMP data from Exif/TIFF tag 700 instead of a separate XMP APP1 segment
+ // if both are present.
+ case IMAGE_TYPE_JPEG:
+ return XMP_HANDLING_PREFER_TIFF_700_IF_PRESENT;
+ case IMAGE_TYPE_AVIF:
+ case IMAGE_TYPE_HEIC:
+ case IMAGE_TYPE_PNG:
+ // RAF stores XMP/Exif in JPEG, but we have no documented backwards-compat obligations
+ // so we can implement the spec to store XMP in a separate APP1 segment.
+ case IMAGE_TYPE_RAF:
+ return XMP_HANDLING_PREFER_SEPARATE;
+ case IMAGE_TYPE_DNG:
+ case IMAGE_TYPE_ORF:
+ case IMAGE_TYPE_PEF:
+ case IMAGE_TYPE_RW2:
+ case IMAGE_TYPE_UNKNOWN:
+ // WebP supports a separate XMP chunk (so should be XMP_HANDLING_PREFER_SEPARATE), but
+ // ExifInterface doesn't currently read or write it.
+ case IMAGE_TYPE_WEBP:
+ default:
+ return XMP_HANDLING_TIFF_700_ONLY;
+ }
+ }
+
+ /**
+ * Returns the value of the specified tag or {@code null} if there
+ * is no such tag in the image file.
+ *
+ * @param tag the name of the tag.
+ */
+ public @Nullable String getAttribute(@NonNull String tag) {
+ if (tag == null) {
+ throw new NullPointerException("tag shouldn't be null");
+ }
+ ExifAttribute attribute = getExifAttribute(tag);
+ if (attribute == null) {
+ return null;
+ }
+ if (tag.equals(TAG_GPS_TIMESTAMP)) {
+ // Convert GPS timestamp value to a custom format for backwards compatibility.
+ if (attribute.format != IFD_FORMAT_URATIONAL
+ && attribute.format != IFD_FORMAT_SRATIONAL) {
+ Log.w(TAG, "GPS Timestamp format is not rational. format=" + attribute.format);
+ return null;
+ }
+ Rational[] array = (Rational[]) attribute.getValue(mExifByteOrder);
+ if (array == null || array.length != 3) {
+ Log.w(TAG, "Invalid GPS Timestamp array. array=" + Arrays.toString(array));
+ return null;
+ }
+ return String.format("%02d:%02d:%02d",
+ (int) ((float) array[0].numerator / array[0].denominator),
+ (int) ((float) array[1].numerator / array[1].denominator),
+ (int) ((float) array[2].numerator / array[2].denominator));
+ } else if (RATIONAL_TAGS_HANDLED_AS_DECIMALS_FOR_COMPATIBILITY.contains(tag)) {
+ // Convert the rational values to the custom formats for backwards compatibility.
+ try {
+ return Double.toString(attribute.getDoubleValue(mExifByteOrder));
+ } catch (NumberFormatException e) {
+ return null;
+ }
+ } else {
+ return attribute.getStringValue(mExifByteOrder);
+ }
+ }
+
+ /**
+ * Returns the integer value of the specified tag. If there is no such tag
+ * in the image file or the value cannot be parsed as integer, return
+ * <var>defaultValue</var>.
+ *
+ * @param tag the name of the tag.
+ * @param defaultValue the value to return if the tag is not available.
+ */
+ public int getAttributeInt(@NonNull String tag, int defaultValue) {
+ if (tag == null) {
+ throw new NullPointerException("tag shouldn't be null");
+ }
+ ExifAttribute exifAttribute = getExifAttribute(tag);
+ if (exifAttribute == null) {
+ return defaultValue;
+ }
+
+ try {
+ return exifAttribute.getIntValue(mExifByteOrder);
+ } catch (NumberFormatException e) {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * Returns the double value of the tag that is specified as rational or contains a
+ * double-formatted value. If there is no such tag in the image file or the value cannot be
+ * parsed as double, return <var>defaultValue</var>.
+ *
+ * @param tag the name of the tag.
+ * @param defaultValue the value to return if the tag is not available.
+ */
+ public double getAttributeDouble(@NonNull String tag, double defaultValue) {
+ if (tag == null) {
+ throw new NullPointerException("tag shouldn't be null");
+ }
+ ExifAttribute exifAttribute = getExifAttribute(tag);
+ if (exifAttribute == null) {
+ return defaultValue;
+ }
+
+ try {
+ return exifAttribute.getDoubleValue(mExifByteOrder);
+ } catch (NumberFormatException e) {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * Sets the value of the specified tag.
+ *
+ * @param tag the name of the tag.
+ * @param value the value of the tag.
+ */
+ @SuppressWarnings("deprecation")
+ public void setAttribute(@NonNull String tag, @Nullable String value) {
+ if (tag == null) {
+ throw new NullPointerException("tag shouldn't be null");
+ }
+
+ // Maintain compatibility.
+ if (TAG_ISO_SPEED_RATINGS.equals(tag)) {
+ if (DEBUG) {
+ Log.d(TAG, "setAttribute: Replacing TAG_ISO_SPEED_RATINGS with "
+ + "TAG_PHOTOGRAPHIC_SENSITIVITY.");
+ }
+ tag = TAG_PHOTOGRAPHIC_SENSITIVITY;
+ }
+ // Maybe convert the given value for backwards compatibility.
+ if (value != null) {
+ if (RATIONAL_TAGS_HANDLED_AS_DECIMALS_FOR_COMPATIBILITY.contains(tag)
+ && !value.contains("/")) {
+ // Convert floating point values to rational for rational tags that are emitted and
+ // consumed as floating point values for backwards compatibility.
+ try {
+ double doubleValue = Double.parseDouble(value);
+ value = Rational.createFromDouble(doubleValue).toString();
+ } catch (NumberFormatException e) {
+ Log.w(TAG, "Invalid value for " + tag + " : " + value);
+ return;
+ }
+ } else if (tag.equals(TAG_GPS_TIMESTAMP)) {
+ Matcher m = GPS_TIMESTAMP_PATTERN.matcher(value);
+ if (!m.find()) {
+ Log.w(TAG, "Invalid value for " + tag + " : " + value);
+ return;
+ }
+ value =
+ Integer.parseInt(m.group(1))
+ + "/1,"
+ + Integer.parseInt(m.group(2))
+ + "/1,"
+ + Integer.parseInt(m.group(3))
+ + "/1";
+ } else if (TAG_DATETIME.equals(tag)
+ || TAG_DATETIME_ORIGINAL.equals(tag)
+ || TAG_DATETIME_DIGITIZED.equals(tag)) {
+ // Validate and convert datetime values if necessary.
+ boolean isPrimaryFormat = DATETIME_PRIMARY_FORMAT_PATTERN.matcher(value).find();
+ boolean isSecondaryFormat = DATETIME_SECONDARY_FORMAT_PATTERN.matcher(value).find();
+ // Validate
+ if (value.length() != DATETIME_VALUE_STRING_LENGTH
+ || (!isPrimaryFormat && !isSecondaryFormat)) {
+ Log.w(TAG, "Invalid value for " + tag + " : " + value);
+ return;
+ }
+ // If datetime value has secondary format (e.g. 2020-01-01 00:00:00), convert it to
+ // primary format (e.g. 2020:01:01 00:00:00) since it is the format in the official
+ // documentation.
+ // See JEITA CP-3451C Section 4.6.4. D. Other Tags, DateTime
+ if (isSecondaryFormat) {
+ // Replace "-" with ":" to match the primary format.
+ value = value.replaceAll("-", ":");
+ }
+ }
+ }
+
+ if (TAG_XMP.equals(tag)) {
+ boolean containsTiff700Xmp =
+ mAttributes[IFD_TYPE_PRIMARY].containsKey(TAG_XMP)
+ || mAttributes[IFD_TYPE_PREVIEW].containsKey(TAG_XMP);
+ @XmpHandling int xmpHandling = getXmpHandlingForImageType(mMimeType);
+ if ((xmpHandling == XMP_HANDLING_PREFER_SEPARATE
+ && (mXmpFromSeparateMarker != null || !containsTiff700Xmp))
+ || (xmpHandling == XMP_HANDLING_PREFER_TIFF_700_IF_PRESENT
+ && !containsTiff700Xmp)) {
+ mXmpFromSeparateMarker = value != null ? ExifAttribute.createByte(value) : null;
+ return;
+ }
+ }
+
+ for (int i = 0; i < EXIF_TAGS.length; ++i) {
+ if (i == IFD_TYPE_THUMBNAIL && !mHasThumbnail) {
+ continue;
+ }
+ final ExifTag exifTag = sExifTagMapsForWriting[i].get(tag);
+ if (exifTag != null) {
+ if (value == null) {
+ mAttributes[i].remove(tag);
+ continue;
+ }
+ Pair<Integer, Integer> guess = guessDataFormat(value);
+ int dataFormat;
+ if (exifTag.primaryFormat == guess.first || exifTag.primaryFormat == guess.second) {
+ dataFormat = exifTag.primaryFormat;
+ } else if (exifTag.secondaryFormat != -1 && (exifTag.secondaryFormat == guess.first
+ || exifTag.secondaryFormat == guess.second)) {
+ dataFormat = exifTag.secondaryFormat;
+ } else if (exifTag.primaryFormat == IFD_FORMAT_BYTE
+ || exifTag.primaryFormat == IFD_FORMAT_UNDEFINED
+ || exifTag.primaryFormat == IFD_FORMAT_STRING) {
+ dataFormat = exifTag.primaryFormat;
+ } else {
+ if (DEBUG) {
+ Log.d(TAG, "Given tag (" + tag
+ + ") value didn't match with one of expected "
+ + "formats: " + IFD_FORMAT_NAMES[exifTag.primaryFormat]
+ + (exifTag.secondaryFormat == -1 ? "" : ", "
+ + IFD_FORMAT_NAMES[exifTag.secondaryFormat]) + " (guess: "
+ + IFD_FORMAT_NAMES[guess.first] + (guess.second == -1 ? "" : ", "
+ + IFD_FORMAT_NAMES[guess.second]) + ")");
+ }
+ continue;
+ }
+ switch (dataFormat) {
+ case IFD_FORMAT_BYTE: {
+ mAttributes[i].put(tag, ExifAttribute.createByte(value));
+ break;
+ }
+ case IFD_FORMAT_UNDEFINED:
+ case IFD_FORMAT_STRING: {
+ mAttributes[i].put(tag, ExifAttribute.createString(value));
+ break;
+ }
+ case IFD_FORMAT_USHORT: {
+ final String[] values = value.split(",", -1);
+ final int[] intArray = new int[values.length];
+ for (int j = 0; j < values.length; ++j) {
+ intArray[j] = Integer.parseInt(values[j]);
+ }
+ mAttributes[i].put(tag,
+ ExifAttribute.createUShort(intArray, mExifByteOrder));
+ break;
+ }
+ case IFD_FORMAT_SLONG: {
+ final String[] values = value.split(",", -1);
+ final int[] intArray = new int[values.length];
+ for (int j = 0; j < values.length; ++j) {
+ intArray[j] = Integer.parseInt(values[j]);
+ }
+ mAttributes[i].put(tag,
+ ExifAttribute.createSLong(intArray, mExifByteOrder));
+ break;
+ }
+ case IFD_FORMAT_ULONG: {
+ final String[] values = value.split(",", -1);
+ final long[] longArray = new long[values.length];
+ for (int j = 0; j < values.length; ++j) {
+ longArray[j] = Long.parseLong(values[j]);
+ }
+ mAttributes[i].put(tag,
+ ExifAttribute.createULong(longArray, mExifByteOrder));
+ break;
+ }
+ case IFD_FORMAT_URATIONAL: {
+ final String[] values = value.split(",", -1);
+ final Rational[] rationalArray = new Rational[values.length];
+ for (int j = 0; j < values.length; ++j) {
+ final String[] numbers = values[j].split("/", -1);
+ rationalArray[j] = new Rational((long) Double.parseDouble(numbers[0]),
+ (long) Double.parseDouble(numbers[1]));
+ }
+ mAttributes[i].put(tag,
+ ExifAttribute.createURational(rationalArray, mExifByteOrder));
+ break;
+ }
+ case IFD_FORMAT_SRATIONAL: {
+ final String[] values = value.split(",", -1);
+ final Rational[] rationalArray = new Rational[values.length];
+ for (int j = 0; j < values.length; ++j) {
+ final String[] numbers = values[j].split("/", -1);
+ rationalArray[j] = new Rational((long) Double.parseDouble(numbers[0]),
+ (long) Double.parseDouble(numbers[1]));
+ }
+ mAttributes[i].put(tag,
+ ExifAttribute.createSRational(rationalArray, mExifByteOrder));
+ break;
+ }
+ case IFD_FORMAT_DOUBLE: {
+ final String[] values = value.split(",", -1);
+ final double[] doubleArray = new double[values.length];
+ for (int j = 0; j < values.length; ++j) {
+ doubleArray[j] = Double.parseDouble(values[j]);
+ }
+ mAttributes[i].put(tag,
+ ExifAttribute.createDouble(doubleArray, mExifByteOrder));
+ break;
+ }
+ default:
+ if (DEBUG) {
+ Log.d(TAG, "Data format isn't one of expected formats: " + dataFormat);
+ }
+ continue;
+ }
+ }
+ }
+ }
+
+ /**
+ * Resets the {@link #TAG_ORIENTATION} of the image to be {@link #ORIENTATION_NORMAL}.
+ */
+ public void resetOrientation() {
+ setAttribute(TAG_ORIENTATION, Integer.toString(ORIENTATION_NORMAL));
+ }
+
+ /**
+ * Rotates the image by the given degree clockwise. The degree should be a multiple of
+ * 90 (e.g, 90, 180, -90, etc.).
+ *
+ * @param degree The degree of rotation.
+ */
+ public void rotate(int degree) {
+ if (degree % 90 != 0) {
+ throw new IllegalArgumentException("degree should be a multiple of 90");
+ }
+
+ int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
+ int currentIndex, newIndex;
+ int resultOrientation;
+ if (ROTATION_ORDER.contains(currentOrientation)) {
+ currentIndex = ROTATION_ORDER.indexOf(currentOrientation);
+ newIndex = (currentIndex + degree / 90) % 4;
+ newIndex += newIndex < 0 ? 4 : 0;
+ resultOrientation = ROTATION_ORDER.get(newIndex);
+ } else if (FLIPPED_ROTATION_ORDER.contains(currentOrientation)) {
+ currentIndex = FLIPPED_ROTATION_ORDER.indexOf(currentOrientation);
+ newIndex = (currentIndex + degree / 90) % 4;
+ newIndex += newIndex < 0 ? 4 : 0;
+ resultOrientation = FLIPPED_ROTATION_ORDER.get(newIndex);
+ } else {
+ resultOrientation = ORIENTATION_UNDEFINED;
+ }
+
+ setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation));
+ }
+
+ /**
+ * Flips the image vertically.
+ */
+ public void flipVertically() {
+ int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
+ int resultOrientation;
+ switch (currentOrientation) {
+ case ORIENTATION_FLIP_HORIZONTAL:
+ resultOrientation = ORIENTATION_ROTATE_180;
+ break;
+ case ORIENTATION_ROTATE_180:
+ resultOrientation = ORIENTATION_FLIP_HORIZONTAL;
+ break;
+ case ORIENTATION_FLIP_VERTICAL:
+ resultOrientation = ORIENTATION_NORMAL;
+ break;
+ case ORIENTATION_TRANSPOSE:
+ resultOrientation = ORIENTATION_ROTATE_270;
+ break;
+ case ORIENTATION_ROTATE_90:
+ resultOrientation = ORIENTATION_TRANSVERSE;
+ break;
+ case ORIENTATION_TRANSVERSE:
+ resultOrientation = ORIENTATION_ROTATE_90;
+ break;
+ case ORIENTATION_ROTATE_270:
+ resultOrientation = ORIENTATION_TRANSPOSE;
+ break;
+ case ORIENTATION_NORMAL:
+ resultOrientation = ORIENTATION_FLIP_VERTICAL;
+ break;
+ case ORIENTATION_UNDEFINED:
+ default:
+ resultOrientation = ORIENTATION_UNDEFINED;
+ break;
+ }
+ setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation));
+ }
+
+ /**
+ * Flips the image horizontally.
+ */
+ public void flipHorizontally() {
+ int currentOrientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
+ int resultOrientation;
+ switch (currentOrientation) {
+ case ORIENTATION_FLIP_HORIZONTAL:
+ resultOrientation = ORIENTATION_NORMAL;
+ break;
+ case ORIENTATION_ROTATE_180:
+ resultOrientation = ORIENTATION_FLIP_VERTICAL;
+ break;
+ case ORIENTATION_FLIP_VERTICAL:
+ resultOrientation = ORIENTATION_ROTATE_180;
+ break;
+ case ORIENTATION_TRANSPOSE:
+ resultOrientation = ORIENTATION_ROTATE_90;
+ break;
+ case ORIENTATION_ROTATE_90:
+ resultOrientation = ORIENTATION_TRANSPOSE;
+ break;
+ case ORIENTATION_TRANSVERSE:
+ resultOrientation = ORIENTATION_ROTATE_270;
+ break;
+ case ORIENTATION_ROTATE_270:
+ resultOrientation = ORIENTATION_TRANSVERSE;
+ break;
+ case ORIENTATION_NORMAL:
+ resultOrientation = ORIENTATION_FLIP_HORIZONTAL;
+ break;
+ case ORIENTATION_UNDEFINED:
+ default:
+ resultOrientation = ORIENTATION_UNDEFINED;
+ break;
+ }
+ setAttribute(TAG_ORIENTATION, Integer.toString(resultOrientation));
+ }
+
+ /**
+ * Returns if the current image orientation is flipped.
+ *
+ * @see #getRotationDegrees()
+ */
+ public boolean isFlipped() {
+ int orientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
+ switch (orientation) {
+ case ORIENTATION_FLIP_HORIZONTAL:
+ case ORIENTATION_TRANSVERSE:
+ case ORIENTATION_FLIP_VERTICAL:
+ case ORIENTATION_TRANSPOSE:
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /**
+ * Returns the rotation degrees for the current image orientation. If the image is flipped,
+ * i.e., {@link #isFlipped()} returns {@code true}, the rotation degrees will be base on
+ * the assumption that the image is first flipped horizontally (along Y-axis), and then do
+ * the rotation. For example, {@link #ORIENTATION_TRANSPOSE} will be interpreted as flipped
+ * horizontally first, and then rotate 270 degrees clockwise.
+ *
+ * @return The rotation degrees of the image after the horizontal flipping is applied, if any.
+ * @see #isFlipped()
+ */
+ public int getRotationDegrees() {
+ int orientation = getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL);
+ switch (orientation) {
+ case ORIENTATION_ROTATE_90:
+ case ORIENTATION_TRANSVERSE:
+ return 90;
+ case ORIENTATION_ROTATE_180:
+ case ORIENTATION_FLIP_VERTICAL:
+ return 180;
+ case ORIENTATION_ROTATE_270:
+ case ORIENTATION_TRANSPOSE:
+ return 270;
+ case ORIENTATION_UNDEFINED:
+ case ORIENTATION_NORMAL:
+ case ORIENTATION_FLIP_HORIZONTAL:
+ default:
+ return 0;
+ }
+ }
+
+ /**
+ * Remove any values of the specified tag.
+ *
+ * @param tag the name of the tag.
+ */
+ private void removeAttribute(String tag) {
+ for (int i = 0; i < EXIF_TAGS.length; ++i) {
+ mAttributes[i].remove(tag);
+ }
+ }
+
+ /**
+ * This function decides which parser to read the image data according to the given input stream
+ * type and the content of the input stream.
+ */
+ private void loadAttributes(@NonNull InputStream in) {
+ try {
+ // Initialize mAttributes.
+ for (int i = 0; i < EXIF_TAGS.length; ++i) {
+ mAttributes[i] = new HashMap<>();
+ }
+
+ // Check file type
+ if (!mIsExifDataOnly) {
+ in = new BufferedInputStream(in, SIGNATURE_CHECK_SIZE);
+ mMimeType = getMimeType((BufferedInputStream) in);
+ }
+
+ if (shouldSupportSeek(mMimeType)) {
+ SeekableByteOrderedDataInputStream inputStream =
+ new SeekableByteOrderedDataInputStream(in);
+ if (mIsExifDataOnly) {
+ if (!getStandaloneAttributes(inputStream)) {
+ return;
+ }
+ } else {
+ if (mMimeType == IMAGE_TYPE_HEIC || mMimeType == IMAGE_TYPE_AVIF) {
+ getHeifAttributes(inputStream, mMimeType);
+ } else if (mMimeType == IMAGE_TYPE_ORF) {
+ getOrfAttributes(inputStream);
+ } else if (mMimeType == IMAGE_TYPE_RW2) {
+ getRw2Attributes(inputStream);
+ } else {
+ getRawAttributes(inputStream);
+ }
+ }
+ // Set thumbnail image offset and length
+ inputStream.seek(mOffsetToExifData);
+ setThumbnailData(inputStream);
+ } else {
+ ByteOrderedDataInputStream inputStream = new ByteOrderedDataInputStream(in);
+ if (mMimeType == IMAGE_TYPE_JPEG) {
+ getJpegAttributes(inputStream, /* offsetToJpeg= */ 0,
+ IFD_TYPE_PRIMARY);
+ } else if (mMimeType == IMAGE_TYPE_PNG) {
+ getPngAttributes(inputStream);
+ } else if (mMimeType == IMAGE_TYPE_RAF) {
+ getRafAttributes(inputStream);
+ } else if (mMimeType == IMAGE_TYPE_WEBP) {
+ getWebpAttributes(inputStream);
+ }
+ }
+ } catch (IOException | UnsupportedOperationException e) {
+ // Ignore exceptions in order to keep the compatibility with the old versions of
+ // ExifInterface.
+ if (DEBUG) {
+ Log.w(TAG, "Invalid image: ExifInterface got an unsupported image format file "
+ + "(ExifInterface supports JPEG and some RAW image formats only) "
+ + "or a corrupted JPEG file to ExifInterface.", e);
+ }
+ } finally {
+ addDefaultValuesForCompatibility();
+
+ if (DEBUG) {
+ printAttributes();
+ }
+ }
+ }
+
+ private static boolean isSeekableFD(FileDescriptor fd) {
+ try {
+ Os.lseek(fd, /* offset= */ 0, /* whence= */ OsConstants.SEEK_CUR);
+ return true;
+ } catch (Exception e) {
+ if (DEBUG) {
+ Log.d(TAG, "The file descriptor for the given input is not seekable");
+ }
+ return false;
+ }
+ }
+
+ // Prints out attributes for debugging.
+ private void printAttributes() {
+ for (int i = 0; i < mAttributes.length; ++i) {
+ Log.d(TAG, "The size of tag group[" + i + "]: " + mAttributes[i].size());
+ for (Map.Entry<String, ExifAttribute> entry : mAttributes[i].entrySet()) {
+ final ExifAttribute tagValue = entry.getValue();
+ Log.d(TAG, "tagName: " + entry.getKey() + ", tagType: " + tagValue.toString()
+ + ", tagValue: '" + tagValue.getStringValue(mExifByteOrder) + "'");
+ }
+ }
+ }
+
+ /**
+ * Save the tag data into the original image file. This is expensive because it involves
+ * copying all the data from one file to another and deleting the old file and renaming the
+ * other. It's best to use {@link #setAttribute(String, String)} to set all attributes to write
+ * and make a single call rather than multiple calls for each attribute.
+ * <p>
+ * This method is supported for JPEG, PNG, and WebP formats.
+ * <p class="note">
+ * Note: after calling this method, any attempts to obtain range information
+ * from {@link #getAttributeRange(String)} or {@link #getThumbnailRange()}
+ * will throw {@link IllegalStateException}, since the offsets may have
+ * changed in the newly written file.
+ * <p>
+ * For WebP format, the Exif data will be stored as an Extended File Format, and it may not be
+ * supported for older readers.
+ * <p>
+ * For PNG format, the Exif data will be stored as an "eXIf" chunk as per
+ * "Extensions to the PNG 1.2 Specification, Version 1.5.0".
+ */
+ public void saveAttributes() throws IOException {
+ if (!isSupportedFormatForSavingAttributes(mMimeType)) {
+ throw new IOException("ExifInterface only supports saving attributes for JPEG, PNG, "
+ + "and WebP formats.");
+ }
+ if (mSeekableFileDescriptor == null && mFilename == null) {
+ throw new IOException(
+ "ExifInterface does not support saving attributes for the current input.");
+ }
+ if (mHasThumbnail && mHasThumbnailStrips && !mAreThumbnailStripsConsecutive) {
+ throw new IOException("ExifInterface does not support saving attributes when the image "
+ + "file has non-consecutive thumbnail strips");
+ }
+
+ // Remember the fact that we've changed the file on disk from what was
+ // originally parsed, meaning we can't answer range questions
+ mModified = true;
+
+ // Keep the thumbnail in memory
+ mThumbnailBytes = getThumbnail();
+
+ FileInputStream in = null;
+ FileOutputStream out = null;
+ File tempFile;
+ try {
+ // Copy the original file to temporary file.
+ tempFile = File.createTempFile("temp", "tmp");
+ if (mFilename != null) {
+ in = new FileInputStream(mFilename);
+ } else {
+ Os.lseek(
+ mSeekableFileDescriptor,
+ /* offset= */ 0,
+ /* whence= */ OsConstants.SEEK_SET);
+ in = new FileInputStream(mSeekableFileDescriptor);
+ }
+ out = new FileOutputStream(tempFile);
+ copy(in, out);
+ } catch (Exception e) {
+ throw new IOException("Failed to copy original file to temp file", e);
+ } finally {
+ closeQuietly(in);
+ closeQuietly(out);
+ }
+
+ in = null;
+ out = null;
+ BufferedInputStream bufferedIn = null;
+ BufferedOutputStream bufferedOut = null;
+ boolean shouldKeepTempFile = false;
+ try {
+ // Save the new file.
+ in = new FileInputStream(tempFile);
+ if (mFilename != null) {
+ out = new FileOutputStream(mFilename);
+ } else {
+ FileDescriptor fd = mSeekableFileDescriptor;
+ Os.lseek(fd, /* offset= */ 0, /* whence= */ OsConstants.SEEK_SET);
+ out = new FileOutputStream(mSeekableFileDescriptor);
+ }
+ bufferedIn = new BufferedInputStream(in);
+ bufferedOut = new BufferedOutputStream(out);
+ if (mMimeType == IMAGE_TYPE_JPEG) {
+ saveJpegAttributes(bufferedIn, bufferedOut);
+ } else if (mMimeType == IMAGE_TYPE_PNG) {
+ savePngAttributes(bufferedIn, bufferedOut);
+ } else if (mMimeType == IMAGE_TYPE_WEBP) {
+ saveWebpAttributes(bufferedIn, bufferedOut);
+ }
+ } catch (Exception e) {
+ try {
+ // Restore original file
+ in = new FileInputStream(tempFile);
+ if (mFilename != null) {
+ out = new FileOutputStream(mFilename);
+ } else {
+ Os.lseek(
+ mSeekableFileDescriptor,
+ /* offset= */ 0,
+ /* whence= */ OsConstants.SEEK_SET);
+ out = new FileOutputStream(mSeekableFileDescriptor);
+ }
+ copy(in, out);
+ } catch (Exception exception) {
+ shouldKeepTempFile = true;
+ throw new IOException("Failed to save new file. Original file is stored in "
+ + tempFile.getAbsolutePath(), exception);
+ } finally {
+ closeQuietly(in);
+ closeQuietly(out);
+ }
+ throw new IOException("Failed to save new file", e);
+ } finally {
+ closeQuietly(bufferedIn);
+ closeQuietly(bufferedOut);
+ if (!shouldKeepTempFile) {
+ tempFile.delete();
+ }
+ }
+
+ // Discard the thumbnail in memory
+ mThumbnailBytes = null;
+ }
+
+ /**
+ * Returns true if the image file has a thumbnail.
+ */
+ public boolean hasThumbnail() {
+ return mHasThumbnail;
+ }
+
+ /**
+ * Returns true if the image file has the given attribute defined.
+ *
+ * @param tag the name of the tag.
+ */
+ public boolean hasAttribute(@NonNull String tag) {
+ return getExifAttribute(tag) != null;
+ }
+
+ /**
+ * Returns the JPEG compressed thumbnail inside the image file, or {@code null} if there is no
+ * JPEG compressed thumbnail.
+ * The returned data can be decoded using
+ * {@link BitmapFactory#decodeByteArray(byte[], int, int)}
+ */
+ public byte @Nullable [] getThumbnail() {
+ if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) {
+ return getThumbnailBytes();
+ }
+ return null;
+ }
+
+ /**
+ * Returns the thumbnail bytes inside the image file, regardless of the compression type of the
+ * thumbnail image.
+ */
+ public byte @Nullable [] getThumbnailBytes() {
+ if (!mHasThumbnail) {
+ return null;
+ }
+ if (mThumbnailBytes != null) {
+ return mThumbnailBytes;
+ }
+
+ // Read the thumbnail.
+ InputStream in = null;
+ FileDescriptor newFileDescriptor = null;
+ try {
+ if (mAssetInputStream != null) {
+ in = mAssetInputStream;
+ if (in.markSupported()) {
+ in.reset();
+ } else {
+ Log.d(TAG, "Cannot read thumbnail from inputstream without mark/reset support");
+ return null;
+ }
+ } else if (mFilename != null) {
+ in = new FileInputStream(mFilename);
+ } else {
+ newFileDescriptor = Os.dup(mSeekableFileDescriptor);
+ Os.lseek(newFileDescriptor, /* offset= */ 0, /* whence= */ OsConstants.SEEK_SET);
+ in = new FileInputStream(newFileDescriptor);
+ }
+ if (in == null) {
+ // Should not be reached this.
+ throw new FileNotFoundException();
+ }
+
+ ByteOrderedDataInputStream inputStream = new ByteOrderedDataInputStream(in);
+ inputStream.skipFully(mThumbnailOffset + mOffsetToExifData);
+
+ // TLAD start
+ if (mThumbnailLength > getAvailableHeapSize()) {
+ throw new IOException("cannot allocate " + mThumbnailLength + " bytes to retrieve thumbnail");
+ }
+ // TLAD end
+
+ // TODO: Need to handle potential OutOfMemoryError
+ byte[] buffer = new byte[mThumbnailLength];
+ inputStream.readFully(buffer);
+ mThumbnailBytes = buffer;
+ return buffer;
+ } catch (Exception e) {
+ // Couldn't get a thumbnail image.
+ Log.d(TAG, "Encountered exception while getting thumbnail", e);
+ } finally {
+ closeQuietly(in);
+ if (newFileDescriptor != null) {
+ closeFileDescriptor(newFileDescriptor);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Creates and returns a Bitmap object of the thumbnail image based on the byte array and the
+ * thumbnail compression value, or {@code null} if the compression type is unsupported.
+ */
+ public @Nullable Bitmap getThumbnailBitmap() {
+ if (!mHasThumbnail) {
+ return null;
+ } else if (mThumbnailBytes == null) {
+ mThumbnailBytes = getThumbnailBytes();
+ }
+
+ if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) {
+ return BitmapFactory.decodeByteArray(mThumbnailBytes, 0, mThumbnailLength);
+ } else if (mThumbnailCompression == DATA_UNCOMPRESSED) {
+ int[] rgbValues = new int[mThumbnailBytes.length / 3];
+ byte alpha = (byte) 0xff000000;
+ for (int i = 0; i < rgbValues.length; i++) {
+ rgbValues[i] = alpha + (mThumbnailBytes[3 * i] << 16)
+ + (mThumbnailBytes[3 * i + 1] << 8) + mThumbnailBytes[3 * i + 2];
+ }
+
+ ExifAttribute imageLengthAttribute =
+ mAttributes[IFD_TYPE_THUMBNAIL].get(TAG_THUMBNAIL_IMAGE_LENGTH);
+ ExifAttribute imageWidthAttribute =
+ mAttributes[IFD_TYPE_THUMBNAIL].get(TAG_THUMBNAIL_IMAGE_WIDTH);
+ if (imageLengthAttribute != null && imageWidthAttribute != null) {
+ int imageLength = imageLengthAttribute.getIntValue(mExifByteOrder);
+ int imageWidth = imageWidthAttribute.getIntValue(mExifByteOrder);
+ return Bitmap.createBitmap(
+ rgbValues, imageWidth, imageLength, Bitmap.Config.ARGB_8888);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns true if thumbnail image is JPEG Compressed, or false if either thumbnail image does
+ * not exist or thumbnail image is uncompressed.
+ */
+ public boolean isThumbnailCompressed() {
+ if (!mHasThumbnail) {
+ return false;
+ }
+ if (mThumbnailCompression == DATA_JPEG || mThumbnailCompression == DATA_JPEG_COMPRESSED) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Returns the offset and length of thumbnail inside the image file, or
+ * {@code null} if either there is no thumbnail or the thumbnail bytes are stored
+ * non-consecutively.
+ *
+ * @return two-element array, the offset in the first value, and length in
+ * the second, or {@code null} if no thumbnail was found or the thumbnail strips are
+ * not placed consecutively.
+ * @throws IllegalStateException if {@link #saveAttributes()} has been
+ * called since the underlying file was initially parsed, since
+ * that means offsets may have changed.
+ */
+ public long @Nullable [] getThumbnailRange() {
+ if (mModified) {
+ throw new IllegalStateException(
+ "The underlying file has been modified since being parsed");
+ }
+
+ if (mHasThumbnail) {
+ if (mHasThumbnailStrips && !mAreThumbnailStripsConsecutive) {
+ return null;
+ }
+ return new long[]{mThumbnailOffset + mOffsetToExifData, mThumbnailLength};
+ }
+ return null;
+ }
+
+ /**
+ * Returns the offset and length of the requested tag inside the image file, or {@code null} if
+ * the tag is not contained.
+ *
+ * <p>If the attribute has been modified with {@link #setAttribute(String, String)} but not yet
+ * written to disk with {@link #saveAttributes()}, the returned range will have the correct
+ * length for the modified value, but an offset of {@code -1} to indicate its position in the
+ * file isn't known.
+ *
+ * @return two-element array, the offset in the first value, and length in the second, or {@code
+ * null} if no tag was found.
+ * @throws IllegalStateException if {@link #saveAttributes()} has been called since the
+ * underlying file was initially parsed, since that means offsets may have changed.
+ */
+ public long @Nullable [] getAttributeRange(@NonNull String tag) {
+ if (tag == null) {
+ throw new NullPointerException("tag shouldn't be null");
+ }
+ if (mModified) {
+ throw new IllegalStateException(
+ "The underlying file has been modified since being parsed");
+ }
+
+ final ExifAttribute attribute = getExifAttribute(tag);
+ if (attribute != null) {
+ return new long[]{attribute.bytesOffset, attribute.bytes.length};
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the raw bytes for the value of the requested tag inside the image
+ * file, or {@code null} if the tag is not contained.
+ *
+ * @return raw bytes for the value of the requested tag, or {@code null} if
+ * no tag was found.
+ */
+ public byte @Nullable [] getAttributeBytes(@NonNull String tag) {
+ if (tag == null) {
+ throw new NullPointerException("tag shouldn't be null");
+ }
+ final ExifAttribute attribute = getExifAttribute(tag);
+ if (attribute != null) {
+ return attribute.bytes;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Stores the latitude and longitude value in a float array. The first element is the latitude,
+ * and the second element is the longitude. Returns false if the Exif tags are not available.
+ *
+ * @deprecated Use {@link #getLatLong()} instead.
+ */
+ @Deprecated
+ public boolean getLatLong(float output[]) {
+ double[] latLong = getLatLong();
+ if (latLong == null) {
+ return false;
+ }
+
+ output[0] = (float) latLong[0];
+ output[1] = (float) latLong[1];
+ return true;
+ }
+
+ /**
+ * Gets the latitude and longitude values.
+ * <p>
+ * If there are valid latitude and longitude values in the image, this method returns a double
+ * array where the first element is the latitude and the second element is the longitude.
+ * Otherwise, it returns null.
+ */
+ public double @Nullable [] getLatLong() {
+ String latValue = getAttribute(TAG_GPS_LATITUDE);
+ String latRef = getAttribute(TAG_GPS_LATITUDE_REF);
+ String lngValue = getAttribute(TAG_GPS_LONGITUDE);
+ String lngRef = getAttribute(TAG_GPS_LONGITUDE_REF);
+
+ if (latValue != null && latRef != null && lngValue != null && lngRef != null) {
+ try {
+ double latitude = convertRationalLatLonToDouble(latValue, latRef);
+ double longitude = convertRationalLatLonToDouble(lngValue, lngRef);
+ return new double[]{latitude, longitude};
+ } catch (IllegalArgumentException e) {
+ Log.w(TAG, "Latitude/longitude values are not parsable. "
+ + String.format("latValue=%s, latRef=%s, lngValue=%s, lngRef=%s",
+ latValue, latRef, lngValue, lngRef));
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Sets the GPS-related information. It will set GPS processing method, latitude and longitude
+ * values, GPS timestamp, and speed information at the same time.
+ * <p>
+ * This method is a No-Op if the location parameter is null.
+ *
+ * @param location the {@link Location} object returned by GPS service.
+ */
+ public void setGpsInfo(@Nullable Location location) {
+ if (location == null) {
+ return;
+ }
+ setAttribute(ExifInterfaceFork.TAG_GPS_PROCESSING_METHOD, location.getProvider());
+ setLatLong(location.getLatitude(), location.getLongitude());
+ setAltitude(location.getAltitude());
+ // Location objects store speeds in m/sec. Translates it to km/hr here.
+ setAttribute(TAG_GPS_SPEED_REF, "K");
+ setAttribute(
+ TAG_GPS_SPEED,
+ Rational.createFromDouble(location.getSpeed() * TimeUnit.HOURS.toSeconds(1) / 1000)
+ .toString());
+ String[] dateTime = sFormatterPrimary.format(
+ new Date(location.getTime())).split("\\s+", -1);
+ setAttribute(ExifInterfaceFork.TAG_GPS_DATESTAMP, dateTime[0]);
+ setAttribute(ExifInterfaceFork.TAG_GPS_TIMESTAMP, dateTime[1]);
+ }
+
+ /**
+ * Sets the latitude and longitude values.
+ *
+ * @param latitude the decimal value of latitude. Must be a valid double value between -90.0 and
+ * 90.0.
+ * @param longitude the decimal value of longitude. Must be a valid double value between -180.0
+ * and 180.0.
+ * @throws IllegalArgumentException If {@code latitude} or {@code longitude} is outside the
+ * specified range.
+ */
+ public void setLatLong(double latitude, double longitude) {
+ if (latitude < -90.0 || latitude > 90.0 || Double.isNaN(latitude)) {
+ throw new IllegalArgumentException("Latitude value " + latitude + " is not valid.");
+ }
+ if (longitude < -180.0 || longitude > 180.0 || Double.isNaN(longitude)) {
+ throw new IllegalArgumentException("Longitude value " + longitude + " is not valid.");
+ }
+ setAttribute(TAG_GPS_LATITUDE_REF, latitude >= 0 ? "N" : "S");
+ setAttribute(TAG_GPS_LATITUDE, convertDecimalDegree(Math.abs(latitude)));
+ setAttribute(TAG_GPS_LONGITUDE_REF, longitude >= 0 ? "E" : "W");
+ setAttribute(TAG_GPS_LONGITUDE, convertDecimalDegree(Math.abs(longitude)));
+ }
+
+ /**
+ * Return the altitude in meters. If the exif tag does not exist, return
+ * <var>defaultValue</var>.
+ *
+ * @param defaultValue the value to return if the tag is not available.
+ */
+ public double getAltitude(double defaultValue) {
+ double altitude = getAttributeDouble(TAG_GPS_ALTITUDE, -1);
+ int ref = getAttributeInt(TAG_GPS_ALTITUDE_REF, -1);
+
+ if (altitude >= 0 && ref >= 0) {
+ return (altitude * ((ref == 1) ? -1 : 1));
+ } else {
+ return defaultValue;
+ }
+ }
+
+ /**
+ * Sets the altitude in meters.
+ */
+ public void setAltitude(double altitude) {
+ String ref = altitude >= 0 ? "0" : "1";
+ setAttribute(TAG_GPS_ALTITUDE, Rational.createFromDouble(Math.abs(altitude)).toString());
+ setAttribute(TAG_GPS_ALTITUDE_REF, ref);
+ }
+
+ /**
+ * Set the date time value.
+ *
+ * @param timeStamp number of milliseconds since Jan. 1, 1970, midnight local time.
+ */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ public void setDateTime(@NonNull Long timeStamp) {
+ if (timeStamp == null) {
+ throw new NullPointerException("Timestamp should not be null.");
+ }
+
+ if (timeStamp < 0) {
+ throw new IllegalArgumentException("Timestamp should a positive value.");
+ }
+
+ long subsec = timeStamp % 1000;
+ String subsecString = Long.toString(subsec);
+ for (int i = subsecString.length(); i < 3; i++) {
+ subsecString = "0" + subsecString;
+ }
+ setAttribute(TAG_DATETIME, sFormatterPrimary.format(new Date(timeStamp)));
+ setAttribute(TAG_SUBSEC_TIME, subsecString);
+ }
+
+ /**
+ * Returns parsed {@link ExifInterfaceFork#TAG_DATETIME} value as number of milliseconds since
+ * Jan. 1, 1970, midnight local time.
+ *
+ * <p>Note: The return value includes the first three digits (or less depending on the length
+ * of the string) of {@link ExifInterfaceFork#TAG_SUBSEC_TIME}.
+ *
+ * @return null if date time information is unavailable or invalid.
+ */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ public @Nullable Long getDateTime() {
+ return parseDateTime(getAttribute(TAG_DATETIME),
+ getAttribute(TAG_SUBSEC_TIME),
+ getAttribute(TAG_OFFSET_TIME));
+ }
+
+ /**
+ * Returns parsed {@link ExifInterfaceFork#TAG_DATETIME_DIGITIZED} value as number of
+ * milliseconds since Jan. 1, 1970, midnight local time.
+ *
+ * <p>Note: The return value includes the first three digits (or less depending on the length
+ * of the string) of {@link ExifInterfaceFork#TAG_SUBSEC_TIME_DIGITIZED}.
+ *
+ * @return null if digitized date time information is unavailable or invalid.
+ */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ public @Nullable Long getDateTimeDigitized() {
+ return parseDateTime(getAttribute(TAG_DATETIME_DIGITIZED),
+ getAttribute(TAG_SUBSEC_TIME_DIGITIZED),
+ getAttribute(TAG_OFFSET_TIME_DIGITIZED));
+ }
+
+ /**
+ * Returns parsed {@link ExifInterfaceFork#TAG_DATETIME_ORIGINAL} value as number of
+ * milliseconds since Jan. 1, 1970, midnight local time.
+ *
+ * <p>Note: The return value includes the first three digits (or less depending on the length
+ * of the string) of {@link ExifInterfaceFork#TAG_SUBSEC_TIME_ORIGINAL}.
+ *
+ * @return null if original date time information is unavailable or invalid.
+ */
+ @RestrictTo(RestrictTo.Scope.LIBRARY)
+ public @Nullable Long getDateTimeOriginal() {
+ return parseDateTime(getAttribute(TAG_DATETIME_ORIGINAL),
+ getAttribute(TAG_SUBSEC_TIME_ORIGINAL),
+ getAttribute(TAG_OFFSET_TIME_ORIGINAL));
+ }
+
+ private static Long parseDateTime(@Nullable String dateTimeString, @Nullable String subSecs,
+ @Nullable String offsetString) {
+ if (dateTimeString == null || !NON_ZERO_TIME_PATTERN.matcher(dateTimeString).matches()) {
+ return null;
+ }
+
+ ParsePosition pos = new ParsePosition(0);
+ try {
+ // The exif field is in local time. Parsing it as if it is UTC will yield time
+ // since 1/1/1970 local time
+ Date dateTime = sFormatterPrimary.parse(dateTimeString, pos);
+ if (dateTime == null) {
+ dateTime = sFormatterSecondary.parse(dateTimeString, pos);
+ if (dateTime == null) {
+ return null;
+ }
+ }
+ long msecs = dateTime.getTime();
+ if (offsetString != null) {
+ String sign = offsetString.substring(0, 1);
+ int hour = Integer.parseInt(offsetString.substring(1, 3));
+ int min = Integer.parseInt(offsetString.substring(4, 6));
+ if (("+".equals(sign) || "-".equals(sign))
+ && ":".equals(offsetString.substring(3, 4))
+ && hour <= 14 /* max UTC hour value */) {
+ msecs += (hour * 60 + min) * 60 * 1000 * ("-".equals(sign) ? 1 : -1);
+ }
+ }
+
+ if (subSecs != null) {
+ msecs += parseSubSeconds(subSecs);
+ }
+ return msecs;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Returns number of milliseconds since 1970-01-01 00:00:00 UTC.
+ *
+ * @return null if the date time information is not available.
+ */
+ @SuppressLint("AutoBoxing") /* Not a performance-critical call, thus not a big concern. */
+ public @Nullable Long getGpsDateTime() {
+ String date = getAttribute(TAG_GPS_DATESTAMP);
+ String time = getAttribute(TAG_GPS_TIMESTAMP);
+ if (date == null || time == null
+ || (!NON_ZERO_TIME_PATTERN.matcher(date).matches()
+ && !NON_ZERO_TIME_PATTERN.matcher(time).matches())) {
+ return null;
+ }
+
+ String dateTimeString = date + ' ' + time;
+
+ ParsePosition pos = new ParsePosition(0);
+ try {
+ Date dateTime = sFormatterPrimary.parse(dateTimeString, pos);
+ if (dateTime == null) {
+ dateTime = sFormatterSecondary.parse(dateTimeString, pos);
+ if (dateTime == null) {
+ return null;
+ }
+ }
+ return dateTime.getTime();
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private void initForFilename(String filename) throws IOException {
+ if (filename == null) {
+ throw new NullPointerException("filename cannot be null");
+ }
+ FileInputStream in = null;
+ mAssetInputStream = null;
+ mFilename = filename;
+ try {
+ in = new FileInputStream(filename);
+ if (isSeekableFD(in.getFD())) {
+ mSeekableFileDescriptor = in.getFD();
+ } else {
+ mSeekableFileDescriptor = null;
+ }
+ loadAttributes(in);
+ } finally {
+ closeQuietly(in);
+ }
+ }
+
+ private static double convertRationalLatLonToDouble(String rationalString, String ref) {
+ try {
+ String[] parts = rationalString.split(",", -1);
+
+ String[] pair;
+ pair = parts[0].split("/", -1);
+ double degrees = Double.parseDouble(pair[0].trim())
+ / Double.parseDouble(pair[1].trim());
+
+ pair = parts[1].split("/", -1);
+ double minutes = Double.parseDouble(pair[0].trim())
+ / Double.parseDouble(pair[1].trim());
+
+ pair = parts[2].split("/", -1);
+ double seconds = Double.parseDouble(pair[0].trim())
+ / Double.parseDouble(pair[1].trim());
+
+ double result = degrees + (minutes / 60.0) + (seconds / 3600.0);
+ if ((ref.equals("S") || ref.equals("W"))) {
+ return -result;
+ } else if (ref.equals("N") || ref.equals("E")) {
+ return result;
+ } else {
+ // Not valid
+ throw new IllegalArgumentException();
+ }
+ } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
+ // Not valid
+ throw new IllegalArgumentException(e);
+ }
+ }
+
+ private String convertDecimalDegree(double decimalDegree) {
+ long degrees = (long) decimalDegree;
+ long minutes = (long) ((decimalDegree - degrees) * 60.0);
+ long seconds = Math.round((decimalDegree - degrees - minutes / 60.0) * 3600.0 * 1e7);
+ return degrees + "/1," + minutes + "/1," + seconds + "/10000000";
+ }
+
+ // Checks the type of image file
+ private int getMimeType(BufferedInputStream in) throws IOException {
+ in.mark(SIGNATURE_CHECK_SIZE);
+ byte[] signatureCheckBytes = new byte[SIGNATURE_CHECK_SIZE];
+ in.read(signatureCheckBytes);
+ in.reset();
+ if (isJpegFormat(signatureCheckBytes)) {
+ return IMAGE_TYPE_JPEG;
+ }
+ if (isRafFormat(signatureCheckBytes)) {
+ return IMAGE_TYPE_RAF;
+ }
+ int heicOrAvifImageType = isHeicOrAvifFormat(signatureCheckBytes);
+ if (heicOrAvifImageType != IMAGE_TYPE_UNKNOWN) {
+ return heicOrAvifImageType;
+ }
+ if (isOrfFormat(signatureCheckBytes)) {
+ return IMAGE_TYPE_ORF;
+ }
+ if (isRw2Format(signatureCheckBytes)) {
+ return IMAGE_TYPE_RW2;
+ }
+ if (isPngFormat(signatureCheckBytes)) {
+ return IMAGE_TYPE_PNG;
+ }
+ if (isWebpFormat(signatureCheckBytes)) {
+ return IMAGE_TYPE_WEBP;
+ }
+ // Certain file formats (PEF) are identified in readImageFileDirectory()
+ return IMAGE_TYPE_UNKNOWN;
+ }
+
+ /**
+ * This method looks at the first 3 bytes to determine if this file is a JPEG file.
+ * See http://www.media.mit.edu/pia/Research/deepview/exif.html, "JPEG format and Marker"
+ */
+ private static boolean isJpegFormat(byte[] signatureCheckBytes) throws IOException {
+ for (int i = 0; i < JPEG_SIGNATURE.length; i++) {
+ if (signatureCheckBytes[i] != JPEG_SIGNATURE[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * This method looks at the first 15 bytes to determine if this file is a RAF file.
+ * There is no official specification for RAF files from Fuji, but there is an online archive of
+ * image file specifications:
+ * http://fileformats.archiveteam.org/wiki/Fujifilm_RAF
+ */
+ private boolean isRafFormat(byte[] signatureCheckBytes) throws IOException {
+ byte[] rafSignatureBytes = RAF_SIGNATURE.getBytes(Charset.defaultCharset());
+ for (int i = 0; i < rafSignatureBytes.length; i++) {
+ if (signatureCheckBytes[i] != rafSignatureBytes[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private int isHeicOrAvifFormat(byte[] signatureCheckBytes) throws IOException {
+ ByteOrderedDataInputStream signatureInputStream = null;
+ try {
+ signatureInputStream = new ByteOrderedDataInputStream(signatureCheckBytes);
+
+ long chunkSize = signatureInputStream.readInt();
+ byte[] chunkType = new byte[4];
+ signatureInputStream.readFully(chunkType);
+
+ if (!Arrays.equals(chunkType, HEIF_TYPE_FTYP)) {
+ return IMAGE_TYPE_UNKNOWN;
+ }
+
+ long chunkDataOffset = 8;
+ if (chunkSize == 1) {
+ // This indicates that the next 8 bytes represent the chunk size,
+ // and chunk data comes after that.
+ chunkSize = signatureInputStream.readLong();
+ if (chunkSize < 16) {
+ // The smallest valid chunk is 16 bytes long in this case.
+ return IMAGE_TYPE_UNKNOWN;
+ }
+ chunkDataOffset += 8;
+ }
+
+ // only sniff up to signatureCheckBytes.length
+ if (chunkSize > signatureCheckBytes.length) {
+ chunkSize = signatureCheckBytes.length;
+ }
+
+ long chunkDataSize = chunkSize - chunkDataOffset;
+
+ // It should at least have major brand (4-byte) and minor version (4-byte).
+ // The rest of the chunk (if any) is a list of (4-byte) compatible brands.
+ if (chunkDataSize < 8) {
+ return IMAGE_TYPE_UNKNOWN;
+ }
+
+ byte[] brand = new byte[4];
+ boolean isMif1 = false;
+ boolean isHeic = false;
+ boolean isAvif = false;
+ for (long i = 0; i < chunkDataSize / 4; ++i) {
+ try {
+ signatureInputStream.readFully(brand);
+ } catch (EOFException e) {
+ return IMAGE_TYPE_UNKNOWN;
+ }
+ if (i == 1) {
+ // Skip this index, it refers to the minorVersion, not a brand.
+ continue;
+ }
+ if (Arrays.equals(brand, HEIF_BRAND_MIF1)) {
+ isMif1 = true;
+ } else if (Arrays.equals(brand, HEIF_BRAND_HEIC)) {
+ isHeic = true;
+ } else if (Arrays.equals(brand, HEIF_BRAND_AVIF)
+ || Arrays.equals(brand, HEIF_BRAND_AVIS)) {
+ isAvif = true;
+ }
+ if (isMif1) {
+ if (isHeic) {
+ return IMAGE_TYPE_HEIC;
+ } else if (isAvif) {
+ return IMAGE_TYPE_AVIF;
+ }
+ }
+ }
+ } catch (Exception e) {
+ if (DEBUG) {
+ Log.d(TAG, "Exception parsing HEIF file type box.", e);
+ }
+ } finally {
+ if (signatureInputStream != null) {
+ signatureInputStream.close();
+ signatureInputStream = null;
+ }
+ }
+ return IMAGE_TYPE_UNKNOWN;
+ }
+
+ /**
+ * ORF has a similar structure to TIFF but it contains a different signature at the TIFF Header.
+ * This method looks at the 2 bytes following the Byte Order bytes to determine if this file is
+ * an ORF file.
+ * There is no official specification for ORF files from Olympus, but there is an online archive
+ * of image file specifications:
+ * http://fileformats.archiveteam.org/wiki/Olympus_ORF
+ */
+ private boolean isOrfFormat(byte[] signatureCheckBytes) throws IOException {
+ ByteOrderedDataInputStream signatureInputStream = null;
+
+ try {
+ signatureInputStream = new ByteOrderedDataInputStream(signatureCheckBytes);
+
+ // Read byte order
+ mExifByteOrder = readByteOrder(signatureInputStream);
+ // Set byte order
+ signatureInputStream.setByteOrder(mExifByteOrder);
+
+ short orfSignature = signatureInputStream.readShort();
+ return orfSignature == ORF_SIGNATURE_1 || orfSignature == ORF_SIGNATURE_2;
+ } catch (Exception e) {
+ // Do nothing
+ } finally {
+ if (signatureInputStream != null) {
+ signatureInputStream.close();
+ }
+ }
+ return false;
+ }
+
+ /**
+ * RW2 is TIFF-based, but stores 0x55 signature byte instead of 0x42 at the header
+ * See http://lclevy.free.fr/raw/
+ */
+ private boolean isRw2Format(byte[] signatureCheckBytes) throws IOException {
+ ByteOrderedDataInputStream signatureInputStream = null;
+
+ try {
+ signatureInputStream = new ByteOrderedDataInputStream(signatureCheckBytes);
+
+ // Read byte order
+ mExifByteOrder = readByteOrder(signatureInputStream);
+ // Set byte order
+ signatureInputStream.setByteOrder(mExifByteOrder);
+
+ short signatureByte = signatureInputStream.readShort();
+ return signatureByte == RW2_SIGNATURE;
+ } catch (Exception e) {
+ // Do nothing
+ } finally {
+ if (signatureInputStream != null) {
+ signatureInputStream.close();
+ }
+ }
+ return false;
+ }
+
+ /**
+ * PNG's file signature is first 8 bytes.
+ * See PNG (Portable Network Graphics) Specification, Version 1.2, 3.1. PNG file signature
+ */
+ private boolean isPngFormat(byte[] signatureCheckBytes) throws IOException {
+ for (int i = 0; i < PNG_SIGNATURE.length; i++) {
+ if (signatureCheckBytes[i] != PNG_SIGNATURE[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * WebP's file signature is composed of 12 bytes:
+ * 'RIFF' (4 bytes) + file length value (4 bytes) + 'WEBP' (4 bytes)
+ * See https://developers.google.com/speed/webp/docs/riff_container, Section "WebP File Header"
+ */
+ private boolean isWebpFormat(byte[] signatureCheckBytes) throws IOException {
+ for (int i = 0; i < WEBP_SIGNATURE_1.length; i++) {
+ if (signatureCheckBytes[i] != WEBP_SIGNATURE_1[i]) {
+ return false;
+ }
+ }
+ for (int i = 0; i < WEBP_SIGNATURE_2.length; i++) {
+ if (signatureCheckBytes[i + WEBP_SIGNATURE_1.length + WEBP_FILE_SIZE_BYTE_LENGTH]
+ != WEBP_SIGNATURE_2[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Loads EXIF attributes from a JPEG input stream.
+ *
+ * @param in The input stream that starts with the JPEG data.
+ * @param offsetToJpeg The offset to JPEG data for the original input stream.
+ * @param imageType The image type from which to retrieve metadata. Use IFD_TYPE_PRIMARY for
+ * primary image, IFD_TYPE_PREVIEW for preview image, and
+ * IFD_TYPE_THUMBNAIL for thumbnail image.
+ * @throws IOException If the data contains invalid JPEG markers, offsets, or length values.
+ */
+ private void getJpegAttributes(ByteOrderedDataInputStream in, int offsetToJpeg, int imageType)
+ throws IOException {
+ // See JPEG File Interchange Format Specification, "JFIF Specification"
+ if (DEBUG) {
+ Log.d(TAG, "getJpegAttributes starting with: " + in);
+ }
+ // JPEG uses Big Endian by default. See https://people.cs.umass.edu/~verts/cs32/endian.html
+ in.setByteOrder(BIG_ENDIAN);
+
+ int bytesRead = 0;
+
+ byte marker;
+ if ((marker = in.readByte()) != MARKER) {
+ throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff));
+ }
+ ++bytesRead;
+ if (in.readByte() != MARKER_SOI) {
+ throw new IOException("Invalid marker: " + Integer.toHexString(marker & 0xff));
+ }
+ ++bytesRead;
+ while (true) {
+ marker = in.readByte();
+ if (marker != MARKER) {
+ throw new IOException("Invalid marker:" + Integer.toHexString(marker & 0xff));
+ }
+ ++bytesRead;
+ marker = in.readByte();
+ if (DEBUG) {
+ Log.d(TAG, "Found JPEG segment indicator: " + Integer.toHexString(marker & 0xff));
+ }
+ ++bytesRead;
+
+ // EOI indicates the end of an image and in case of SOS, JPEG image stream starts and
+ // the image data will terminate right after.
+ if (marker == MARKER_EOI || marker == MARKER_SOS) {
+ break;
+ }
+ int length = in.readUnsignedShort() - 2;
+ bytesRead += 2;
+ if (DEBUG) {
+ Log.d(TAG, "JPEG segment: " + Integer.toHexString(marker & 0xff) + " (length: "
+ + (length + 2) + ")");
+ }
+ if (length < 0) {
+ throw new IOException("Invalid length");
+ }
+ switch (marker) {
+ case MARKER_APP1: {
+ final int start = bytesRead;
+ final byte[] bytes = new byte[length];
+ in.readFully(bytes);
+ bytesRead += length;
+ length = 0;
+
+ if (startsWith(bytes, IDENTIFIER_EXIF_APP1)) {
+ final byte[] value = Arrays.copyOfRange(bytes, IDENTIFIER_EXIF_APP1.length,
+ bytes.length);
+ // Save offset to EXIF data for handling thumbnail and attribute offsets.
+ mOffsetToExifData = offsetToJpeg
+ + /* offset to EXIF from JPEG start */ start
+ + IDENTIFIER_EXIF_APP1.length;
+ readExifSegment(value, imageType);
+
+ setThumbnailData(new ByteOrderedDataInputStream(value));
+ } else if (startsWith(bytes, IDENTIFIER_XMP_APP1)) {
+ // See XMP Specification Part 3: Storage in Files, 1.1.3 JPEG, Table 6
+ final int offset = start + IDENTIFIER_XMP_APP1.length;
+ final byte[] value = Arrays.copyOfRange(bytes,
+ IDENTIFIER_XMP_APP1.length, bytes.length);
+ mXmpFromSeparateMarker =
+ new ExifAttribute(IFD_FORMAT_BYTE, value.length, offset, value);
+ mFileOnDiskContainsSeparateXmpMarker = true;
+ }
+ break;
+ }
+
+ case MARKER_COM: {
+ byte[] bytes = new byte[length];
+ in.readFully(bytes);
+ length = 0;
+ if (getAttribute(TAG_USER_COMMENT) == null) {
+ mAttributes[IFD_TYPE_EXIF].put(TAG_USER_COMMENT, ExifAttribute.createString(
+ new String(bytes, ASCII)));
+ }
+ break;
+ }
+
+ case MARKER_SOF0:
+ case MARKER_SOF1:
+ case MARKER_SOF2:
+ case MARKER_SOF3:
+ case MARKER_SOF5:
+ case MARKER_SOF6:
+ case MARKER_SOF7:
+ case MARKER_SOF9:
+ case MARKER_SOF10:
+ case MARKER_SOF11:
+ case MARKER_SOF13:
+ case MARKER_SOF14:
+ case MARKER_SOF15: {
+ in.skipFully(1);
+ mAttributes[imageType].put(imageType != IFD_TYPE_THUMBNAIL
+ ? TAG_IMAGE_LENGTH : TAG_THUMBNAIL_IMAGE_LENGTH,
+ ExifAttribute.createULong(in.readUnsignedShort(), mExifByteOrder));
+ mAttributes[imageType].put(imageType != IFD_TYPE_THUMBNAIL
+ ? TAG_IMAGE_WIDTH : TAG_THUMBNAIL_IMAGE_WIDTH,
+ ExifAttribute.createULong(in.readUnsignedShort(), mExifByteOrder));
+ length -= 5;
+ break;
+ }
+
+ default: {
+ break;
+ }
+ }
+ if (length < 0) {
+ throw new IOException("Invalid length");
+ }
+ in.skipFully(length);
+ bytesRead += length;
+ }
+ // Restore original byte order
+ in.setByteOrder(mExifByteOrder);
+ }
+
+ private void getRawAttributes(SeekableByteOrderedDataInputStream in) throws IOException {
+ // Parse TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1.
+ parseTiffHeaders(in);
+
+ // Read TIFF image file directories. See JEITA CP-3451C Section 4.5.2. Figure 6.
+ readImageFileDirectory(in, IFD_TYPE_PRIMARY);
+
+ // Update ImageLength/Width tags for all image data.
+ updateImageSizeValues(in, IFD_TYPE_PRIMARY);
+ updateImageSizeValues(in, IFD_TYPE_PREVIEW);
+ updateImageSizeValues(in, IFD_TYPE_THUMBNAIL);
+
+ // Check if each image data is in valid position.
+ validateImages();
+
+ if (mMimeType == IMAGE_TYPE_PEF) {
+ // PEF files contain a MakerNote data, which contains the data for ColorSpace tag.
+ // See http://lclevy.free.fr/raw/ and piex.cc PefGetPreviewData()
+ ExifAttribute makerNoteAttribute =
+ mAttributes[IFD_TYPE_EXIF].get(TAG_MAKER_NOTE);
+ if (makerNoteAttribute != null) {
+ // Create an ordered DataInputStream for MakerNote
+ SeekableByteOrderedDataInputStream makerNoteDataInputStream =
+ new SeekableByteOrderedDataInputStream(makerNoteAttribute.bytes);
+ makerNoteDataInputStream.setByteOrder(mExifByteOrder);
+
+ // Skip to MakerNote data
+ makerNoteDataInputStream.skipFully(PEF_MAKER_NOTE_SKIP_SIZE);
+
+ // Read IFD data from MakerNote
+ readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_PEF);
+
+ // Update ColorSpace tag
+ ExifAttribute colorSpaceAttribute =
+ mAttributes[IFD_TYPE_PEF].get(TAG_COLOR_SPACE);
+ if (colorSpaceAttribute != null) {
+ mAttributes[IFD_TYPE_EXIF].put(TAG_COLOR_SPACE, colorSpaceAttribute);
+ }
+ }
+ }
+ }
+
+ /**
+ * RAF files contains a JPEG and a CFA data.
+ * The JPEG contains two images, a preview and a thumbnail, while the CFA contains a RAW image.
+ * This method looks at the first 160 bytes of a RAF file to retrieve the offset and length
+ * values for the JPEG and CFA data.
+ * Using that data, it parses the JPEG data to retrieve the preview and thumbnail image data,
+ * then parses the CFA metadata to retrieve the primary image length/width values.
+ * For data format details, see http://fileformats.archiveteam.org/wiki/Fujifilm_RAF
+ */
+ private void getRafAttributes(ByteOrderedDataInputStream in) throws IOException {
+ if (DEBUG) {
+ Log.d(TAG, "getRafAttributes starting with: " + in);
+ }
+ // Retrieve offset & length values
+ in.skipFully(RAF_OFFSET_TO_JPEG_IMAGE_OFFSET);
+ byte[] offsetToJpegBytes = new byte[4];
+ byte[] jpegLengthBytes = new byte[4];
+ byte[] cfaHeaderOffsetBytes = new byte[4];
+ in.readFully(offsetToJpegBytes);
+ in.readFully(jpegLengthBytes);
+ in.readFully(cfaHeaderOffsetBytes);
+ int offsetToJpeg = ByteBuffer.wrap(offsetToJpegBytes).getInt();
+ int jpegLength = ByteBuffer.wrap(jpegLengthBytes).getInt();
+ int cfaHeaderOffset = ByteBuffer.wrap(cfaHeaderOffsetBytes).getInt();
+
+ byte[] jpegBytes = new byte[jpegLength];
+ in.skipFully(offsetToJpeg - in.position());
+ in.readFully(jpegBytes);
+
+ // Retrieve JPEG image metadata
+ ByteOrderedDataInputStream jpegInputStream = new ByteOrderedDataInputStream(jpegBytes);
+ getJpegAttributes(jpegInputStream, offsetToJpeg, IFD_TYPE_PREVIEW);
+
+ // Skip to CFA header offset.
+ in.skipFully(cfaHeaderOffset - in.position());
+
+ // Retrieve primary image length/width values, if TAG_RAF_IMAGE_SIZE exists
+ in.setByteOrder(BIG_ENDIAN);
+ int numberOfDirectoryEntry = in.readInt();
+ if (DEBUG) {
+ Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry);
+ }
+ // CFA stores some metadata about the RAW image. Since CFA uses proprietary tags, can only
+ // find and retrieve image size information tags, while skipping others.
+ // See piex.cc RafGetDimension()
+ for (int i = 0; i < numberOfDirectoryEntry; ++i) {
+ int tagNumber = in.readUnsignedShort();
+ int numberOfBytes = in.readUnsignedShort();
+ if (tagNumber == TAG_RAF_IMAGE_SIZE.number) {
+ int imageLength = in.readShort();
+ int imageWidth = in.readShort();
+ ExifAttribute imageLengthAttribute =
+ ExifAttribute.createUShort(imageLength, mExifByteOrder);
+ ExifAttribute imageWidthAttribute =
+ ExifAttribute.createUShort(imageWidth, mExifByteOrder);
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, imageLengthAttribute);
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, imageWidthAttribute);
+ if (DEBUG) {
+ Log.d(TAG, "Updated to length: " + imageLength + ", width: " + imageWidth);
+ }
+ return;
+ }
+ in.skipFully(numberOfBytes);
+ }
+ }
+
+ // Support for getting MediaMetadataRetriever.METADATA_KEY_EXIF_OFFSET and
+ // MediaMetadataRetriever.METADATA_KEY_EXIF_LENGTH was added in SDK 28 for HEIC and in SDK 31
+ // for AVIF.
+ private void getHeifAttributes(final SeekableByteOrderedDataInputStream in, int imageType)
+ throws IOException {
+ if (Build.VERSION.SDK_INT >= 28) {
+ if (imageType == IMAGE_TYPE_AVIF && Build.VERSION.SDK_INT < 31) {
+ throw new UnsupportedOperationException("Reading EXIF from AVIF files "
+ + "is supported from SDK 31 and above");
+ }
+ MediaMetadataRetriever retriever = new MediaMetadataRetriever();
+ try {
+ Api23Impl.setDataSource(retriever, new MediaDataSource() {
+ long mPosition;
+
+ @Override
+ public void close() throws IOException {
+ }
+
+ @Override
+ public int readAt(long position, byte[] buffer, int offset, int size)
+ throws IOException {
+ if (size == 0) {
+ return 0;
+ }
+ if (position < 0) {
+ return -1;
+ }
+ try {
+ if (mPosition != position) {
+ // We don't allow seek to positions after the available bytes,
+ // the input stream won't be able to seek back then.
+ // However, if we hit an exception before (mPosition set to -1),
+ // let it try the seek in hope it might recover.
+ if (mPosition >= 0 && position >= mPosition + in.available()) {
+ return -1;
+ }
+ in.seek(position);
+ mPosition = position;
+ }
+
+ // If the read will cause us to go over the available bytes,
+ // reduce the size so that we stay in the available range.
+ // Otherwise the input stream may not be able to seek back.
+ if (size > in.available()) {
+ size = in.available();
+ }
+
+ int bytesRead = in.read(buffer, offset, size);
+ if (bytesRead >= 0) {
+ mPosition += bytesRead;
+ return bytesRead;
+ }
+ } catch (IOException e) {
+ // do nothing
+ }
+ mPosition = -1; // need to seek on next read
+ return -1;
+ }
+
+ @Override
+ public long getSize() throws IOException {
+ return -1;
+ }
+ });
+
+ String exifOffsetStr = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_EXIF_OFFSET);
+ String exifLengthStr = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_EXIF_LENGTH);
+ String hasImage = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_HAS_IMAGE);
+ String hasVideo = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
+
+ String width = null;
+ String height = null;
+ String rotation = null;
+ final String metadataValueYes = "yes";
+ // If the file has both image and video, prefer image info over video info.
+ // App querying ExifInterface is most likely using the bitmap path which
+ // picks the image first.
+ if (metadataValueYes.equals(hasImage)) {
+ width = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_WIDTH);
+ height = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_HEIGHT);
+ rotation = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_IMAGE_ROTATION);
+ } else if (metadataValueYes.equals(hasVideo)) {
+ width = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
+ height = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
+ rotation = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
+ }
+
+ if (width != null) {
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH,
+ ExifAttribute.createUShort(Integer.parseInt(width), mExifByteOrder));
+ }
+
+ if (height != null) {
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH,
+ ExifAttribute.createUShort(Integer.parseInt(height), mExifByteOrder));
+ }
+
+ if (rotation != null) {
+ int orientation = ExifInterfaceFork.ORIENTATION_NORMAL;
+
+ // all rotation angles in CW
+ switch (Integer.parseInt(rotation)) {
+ case 90:
+ orientation = ExifInterfaceFork.ORIENTATION_ROTATE_90;
+ break;
+ case 180:
+ orientation = ExifInterfaceFork.ORIENTATION_ROTATE_180;
+ break;
+ case 270:
+ orientation = ExifInterfaceFork.ORIENTATION_ROTATE_270;
+ break;
+ }
+
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_ORIENTATION,
+ ExifAttribute.createUShort(orientation, mExifByteOrder));
+ }
+
+ if (exifOffsetStr != null && exifLengthStr != null) {
+ int offset = Integer.parseInt(exifOffsetStr);
+ int length = Integer.parseInt(exifLengthStr);
+ if (length <= 6) {
+ throw new IOException("Invalid exif length");
+ }
+ in.seek(offset);
+ byte[] identifier = new byte[6];
+ in.readFully(identifier);
+ offset += 6;
+ length -= 6;
+ if (!Arrays.equals(identifier, IDENTIFIER_EXIF_APP1)) {
+ throw new IOException("Invalid identifier");
+ }
+
+ // TODO: Need to handle potential OutOfMemoryError
+ byte[] bytes = new byte[length];
+ in.readFully(bytes);
+ // Save offset to EXIF data for handling thumbnail and attribute offsets.
+ mOffsetToExifData = offset;
+ readExifSegment(bytes, IFD_TYPE_PRIMARY);
+ }
+
+ String xmpOffsetStr = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_XMP_OFFSET);
+ String xmpLengthStr = retriever.extractMetadata(
+ MediaMetadataRetriever.METADATA_KEY_XMP_LENGTH);
+ if (xmpOffsetStr != null && xmpLengthStr != null) {
+ int offset = Integer.parseInt(xmpOffsetStr);
+ int length = Integer.parseInt(xmpLengthStr);
+ in.seek(offset);
+ byte[] xmpBytes = new byte[length];
+ in.readFully(xmpBytes);
+ mXmpFromSeparateMarker =
+ new ExifAttribute(IFD_FORMAT_BYTE, xmpBytes.length, offset, xmpBytes);
+ mFileOnDiskContainsSeparateXmpMarker = true;
+ }
+
+ if (DEBUG) {
+ Log.d(TAG, "Heif meta: " + width + "x" + height + ", rotation " + rotation);
+ }
+ } catch (RuntimeException e) {
+ throw new UnsupportedOperationException("Failed to read EXIF from HEIF file. "
+ + "Given stream is either malformed or unsupported.", e);
+ } finally {
+ try {
+ retriever.release();
+ } catch (IOException e) {
+ // Nothing we can do about it.
+ }
+ }
+ } else {
+ throw new UnsupportedOperationException("Reading EXIF from HEIC files "
+ + "is supported from SDK 28 and above");
+ }
+ }
+
+ /**
+ * Reads standalone EXIF data, returning whether the data was read successfully.
+ */
+ private boolean getStandaloneAttributes(SeekableByteOrderedDataInputStream in)
+ throws IOException {
+ byte[] signatureCheckBytes = new byte[IDENTIFIER_EXIF_APP1.length];
+ in.readFully(signatureCheckBytes);
+ if (!Arrays.equals(signatureCheckBytes, IDENTIFIER_EXIF_APP1)) {
+ Log.w(TAG, "Given data is not EXIF-only.");
+ return false;
+ }
+ // TODO: Need to handle potential OutOfMemoryError
+ byte[] data = in.readToEnd();
+ // Save offset to EXIF data for handling thumbnail and attribute offsets.
+ mOffsetToExifData = IDENTIFIER_EXIF_APP1.length;
+ readExifSegment(data, IFD_TYPE_PRIMARY);
+ return true;
+ }
+
+ /**
+ * ORF files contains a primary image data and a MakerNote data that contains preview/thumbnail
+ * images. Both data takes the form of IFDs and can therefore be read with the
+ * readImageFileDirectory() method.
+ * This method reads all the necessary data and updates the primary/preview/thumbnail image
+ * information according to the GetOlympusPreviewImage() method in piex.cc.
+ * For data format details, see the following:
+ * http://fileformats.archiveteam.org/wiki/Olympus_ORF
+ * https://libopenraw.freedesktop.org/wiki/Olympus_ORF
+ */
+ private void getOrfAttributes(SeekableByteOrderedDataInputStream in) throws IOException {
+ // Retrieve primary image data
+ // Other Exif data will be located in the Makernote.
+ getRawAttributes(in);
+
+ // Additionally retrieve preview/thumbnail information from MakerNote tag, which contains
+ // proprietary tags and therefore does not have offical documentation
+ // See GetOlympusPreviewImage() in piex.cc & http://www.exiv2.org/tags-olympus.html
+ ExifAttribute makerNoteAttribute =
+ mAttributes[IFD_TYPE_EXIF].get(TAG_MAKER_NOTE);
+ if (makerNoteAttribute != null) {
+ // Create an ordered DataInputStream for MakerNote
+ SeekableByteOrderedDataInputStream makerNoteDataInputStream =
+ new SeekableByteOrderedDataInputStream(makerNoteAttribute.bytes);
+ makerNoteDataInputStream.setByteOrder(mExifByteOrder);
+
+ // There are two types of headers for Olympus MakerNotes
+ // See http://www.exiv2.org/makernote.html#R1
+ byte[] makerNoteHeader1Bytes = new byte[ORF_MAKER_NOTE_HEADER_1.length];
+ makerNoteDataInputStream.readFully(makerNoteHeader1Bytes);
+ makerNoteDataInputStream.seek(0);
+ byte[] makerNoteHeader2Bytes = new byte[ORF_MAKER_NOTE_HEADER_2.length];
+ makerNoteDataInputStream.readFully(makerNoteHeader2Bytes);
+ // Skip the corresponding amount of bytes for each header type
+ if (Arrays.equals(makerNoteHeader1Bytes, ORF_MAKER_NOTE_HEADER_1)) {
+ makerNoteDataInputStream.seek(ORF_MAKER_NOTE_HEADER_1_SIZE);
+ } else if (Arrays.equals(makerNoteHeader2Bytes, ORF_MAKER_NOTE_HEADER_2)) {
+ makerNoteDataInputStream.seek(ORF_MAKER_NOTE_HEADER_2_SIZE);
+ }
+
+ // Read IFD data from MakerNote
+ readImageFileDirectory(makerNoteDataInputStream, IFD_TYPE_ORF_MAKER_NOTE);
+
+ // Retrieve & update preview image offset & length values
+ ExifAttribute imageStartAttribute =
+ mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_START);
+ ExifAttribute imageLengthAttribute =
+ mAttributes[IFD_TYPE_ORF_CAMERA_SETTINGS].get(TAG_ORF_PREVIEW_IMAGE_LENGTH);
+
+ if (imageStartAttribute != null && imageLengthAttribute != null) {
+ mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT,
+ imageStartAttribute);
+ mAttributes[IFD_TYPE_PREVIEW].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH,
+ imageLengthAttribute);
+ }
+
+ // TODO: Check this behavior in other ORF files
+ // Retrieve primary image length & width values
+ // See piex.cc GetOlympusPreviewImage()
+ ExifAttribute aspectFrameAttribute =
+ mAttributes[IFD_TYPE_ORF_IMAGE_PROCESSING].get(TAG_ORF_ASPECT_FRAME);
+ if (aspectFrameAttribute != null) {
+ int[] aspectFrameValues = (int[]) aspectFrameAttribute.getValue(mExifByteOrder);
+ if (aspectFrameValues == null || aspectFrameValues.length != 4) {
+ Log.w(TAG, "Invalid aspect frame values. frame="
+ + Arrays.toString(aspectFrameValues));
+ return;
+ }
+ if (aspectFrameValues[2] > aspectFrameValues[0] &&
+ aspectFrameValues[3] > aspectFrameValues[1]) {
+ int primaryImageWidth = aspectFrameValues[2] - aspectFrameValues[0] + 1;
+ int primaryImageLength = aspectFrameValues[3] - aspectFrameValues[1] + 1;
+ // Swap width & length values
+ if (primaryImageWidth < primaryImageLength) {
+ primaryImageWidth += primaryImageLength;
+ primaryImageLength = primaryImageWidth - primaryImageLength;
+ primaryImageWidth -= primaryImageLength;
+ }
+ ExifAttribute primaryImageWidthAttribute =
+ ExifAttribute.createUShort(primaryImageWidth, mExifByteOrder);
+ ExifAttribute primaryImageLengthAttribute =
+ ExifAttribute.createUShort(primaryImageLength, mExifByteOrder);
+
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, primaryImageWidthAttribute);
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, primaryImageLengthAttribute);
+ }
+ }
+ }
+ }
+
+ // RW2 contains the primary image data in IFD0 and the preview and/or thumbnail image data in
+ // the JpgFromRaw tag
+ // See https://libopenraw.freedesktop.org/wiki/Panasonic_RAW/ and piex.cc Rw2GetPreviewData()
+ private void getRw2Attributes(SeekableByteOrderedDataInputStream in) throws IOException {
+ if (DEBUG) {
+ Log.d(TAG, "getRw2Attributes starting with: " + in);
+ }
+ // Retrieve primary image data
+ getRawAttributes(in);
+
+ // Retrieve preview and/or thumbnail image data
+ ExifAttribute jpgFromRawAttribute =
+ mAttributes[IFD_TYPE_PRIMARY].get(TAG_RW2_JPG_FROM_RAW);
+ if (jpgFromRawAttribute != null) {
+ ByteOrderedDataInputStream jpegInputStream =
+ new ByteOrderedDataInputStream(jpgFromRawAttribute.bytes);
+ getJpegAttributes(jpegInputStream, (int) jpgFromRawAttribute.bytesOffset,
+ IFD_TYPE_PREVIEW);
+ }
+
+ // Set ISO tag value if necessary
+ ExifAttribute rw2IsoAttribute =
+ mAttributes[IFD_TYPE_PRIMARY].get(TAG_RW2_ISO);
+ ExifAttribute exifIsoAttribute =
+ mAttributes[IFD_TYPE_EXIF].get(TAG_PHOTOGRAPHIC_SENSITIVITY);
+ if (rw2IsoAttribute != null && exifIsoAttribute == null) {
+ // Place this attribute only if it doesn't exist
+ mAttributes[IFD_TYPE_EXIF].put(TAG_PHOTOGRAPHIC_SENSITIVITY, rw2IsoAttribute);
+ }
+ }
+
+ // PNG contains the EXIF data as a Special-Purpose Chunk
+ private void getPngAttributes(ByteOrderedDataInputStream in) throws IOException {
+ if (DEBUG) {
+ Log.d(TAG, "getPngAttributes starting with: " + in);
+ }
+ // PNG uses Big Endian by default.
+ // See PNG (Portable Network Graphics) Specification, Version 1.2,
+ // 2.1. Integers and byte order
+ in.setByteOrder(BIG_ENDIAN);
+
+ int startPosition = in.position();
+
+ // Skip the signature bytes
+ in.skipFully(PNG_SIGNATURE.length);
+
+ // Each chunk is made up of four parts:
+ // 1) Length: 4-byte unsigned integer indicating the number of bytes in the
+ // Chunk Data field. Excludes Chunk Type and CRC bytes.
+ // 2) Chunk Type: 4-byte chunk type code.
+ // 3) Chunk Data: The data bytes. Can be zero-length.
+ // 4) CRC: 4-byte data calculated on the preceding bytes in the chunk. Always
+ // present.
+ // --> 4 (length bytes) + 4 (type bytes) + X (data bytes) + 4 (CRC bytes)
+ // See PNG (Portable Network Graphics) Specification, Version 1.2,
+ // 3.2. Chunk layout
+ try {
+ boolean foundExif = false;
+ boolean foundXmpItxt = false;
+ while (!foundExif || !foundXmpItxt) {
+ int length = in.readInt();
+ int type = in.readInt();
+ int startOfNextChunk = in.position() + length + PNG_CHUNK_CRC_BYTE_LENGTH;
+
+ // The first chunk must be the IHDR chunk
+ if (in.position() - startPosition == 16 && type != PNG_CHUNK_TYPE_IHDR) {
+ throw new IOException(
+ "Encountered invalid PNG file--IHDR chunk should appear as the first "
+ + "chunk");
+ }
+
+ if (type == PNG_CHUNK_TYPE_IEND) {
+ // IEND marks the end of the image.
+ break;
+ } else if (type == PNG_CHUNK_TYPE_EXIF && !foundExif) {
+ // Save offset to EXIF data for handling thumbnail and attribute offsets.
+ mOffsetToExifData = in.position() - startPosition;
+
+ // TLAD start
+ if (length > ATTRIBUTE_SIZE_DANGER_THRESHOLD) {
+ throw new IOException("dangerous exif chunk size=" + length);
+ }
+ // TLAD end
+
+ // TODO: Need to handle potential OutOfMemoryError
+ byte[] data = new byte[length];
+ in.readFully(data);
+
+ // Compare CRC values for potential data corruption.
+ int dataCrcValue = in.readInt();
+ // Cyclic Redundancy Code used to check for corruption of the data
+ CRC32 crc = new CRC32();
+ updateCrcWithInt(crc, type);
+ crc.update(data);
+ if ((int) crc.getValue() != dataCrcValue) {
+ throw new IOException(
+ "Encountered invalid CRC value for PNG-EXIF chunk."
+ + "\n recorded CRC value: "
+ + dataCrcValue
+ + ", calculated CRC "
+ + "value: "
+ + crc.getValue());
+ }
+ readExifSegment(data, IFD_TYPE_PRIMARY);
+ validateImages();
+
+ setThumbnailData(new ByteOrderedDataInputStream(data));
+ foundExif = true;
+ } else if (type == PNG_CHUNK_TYPE_ITXT
+ && !foundXmpItxt
+ && length >= PNG_ITXT_XMP_KEYWORD.length) {
+ // Read the 17 byte keyword and 5 expected null bytes.
+ byte[] keyword = new byte[PNG_ITXT_XMP_KEYWORD.length];
+ in.readFully(keyword);
+ if (Arrays.equals(keyword, PNG_ITXT_XMP_KEYWORD)) {
+ int xmpDataOffset = in.position() - startPosition;
+ int xmpLength = length - keyword.length;
+ byte[] xmpData = new byte[xmpLength];
+ in.readFully(xmpData);
+ mXmpFromSeparateMarker =
+ new ExifAttribute(
+ IFD_FORMAT_BYTE, xmpLength, xmpDataOffset, xmpData);
+ foundXmpItxt = true;
+ }
+ }
+ // Skip to next chunk
+ in.skipFully(startOfNextChunk - in.position());
+ }
+ mFileOnDiskContainsSeparateXmpMarker = foundXmpItxt;
+ } catch (EOFException e) {
+ // Should not reach here. Will only reach here if the file is corrupted or
+ // does not follow the PNG specifications
+ throw new IOException("Encountered corrupt PNG file.", e);
+ }
+ }
+
+ private static void updateCrcWithInt(CRC32 crc, int value) {
+ crc.update(value >>> 24);
+ crc.update(value >>> 16);
+ crc.update(value >>> 8);
+ crc.update(value);
+ }
+
+ // WebP contains EXIF data as a RIFF File Format Chunk
+ // All references below can be found in the following link.
+ // https://developers.google.com/speed/webp/docs/riff_container
+ private void getWebpAttributes(ByteOrderedDataInputStream in) throws IOException {
+ if (DEBUG) {
+ Log.d(TAG, "getWebpAttributes starting with: " + in);
+ }
+ // WebP uses little-endian by default.
+ // See Section "Terminology & Basics"
+ in.setByteOrder(LITTLE_ENDIAN);
+
+ in.skipFully(WEBP_SIGNATURE_1.length);
+ // File size corresponds to the size of the entire file from offset 8.
+ // See Section "WebP File Header"
+ int fileSize = in.readInt() + 8;
+ int bytesRead = 8;
+
+ in.skipFully(WEBP_SIGNATURE_2.length);
+ bytesRead += WEBP_SIGNATURE_2.length;
+
+ try {
+ while (true) {
+ // TODO: Check the first Chunk Type, and if it is VP8X, check if the chunks are
+ // ordered properly.
+
+ // Each chunk is made up of three parts:
+ // 1) Chunk FourCC: 4-byte concatenating four ASCII characters.
+ // 2) Chunk Size: 4-byte unsigned integer indicating the size of the chunk.
+ // Excludes Chunk FourCC and Chunk Size bytes.
+ // 3) Chunk Payload: data payload. A single padding byte ('0') is added if
+ // Chunk Size is odd.
+ // See Section "RIFF File Format"
+ byte[] code = new byte[WEBP_CHUNK_TYPE_BYTE_LENGTH];
+ in.readFully(code);
+ bytesRead += WEBP_CHUNK_TYPE_BYTE_LENGTH;
+
+ int chunkSize = in.readInt();
+ bytesRead += 4;
+
+ if (Arrays.equals(WEBP_CHUNK_TYPE_EXIF, code)) {
+ // TODO: Need to handle potential OutOfMemoryError
+ byte[] payload = new byte[chunkSize];
+ in.readFully(payload);
+
+ // Skip a JPEG APP1 marker that some image libraries incorrectly include in the
+ // Exif data in WebP images (e.g.
+ // https://github.com/ImageMagick/ImageMagick/issues/3140)
+ if (startsWith(payload, IDENTIFIER_EXIF_APP1)) {
+ payload =
+ Arrays.copyOfRange(
+ payload, IDENTIFIER_EXIF_APP1.length, payload.length);
+ }
+
+ // Save offset to EXIF data for handling thumbnail and attribute offsets.
+ mOffsetToExifData = bytesRead;
+ readExifSegment(payload, IFD_TYPE_PRIMARY);
+
+ setThumbnailData(new ByteOrderedDataInputStream(payload));
+ break;
+ } else {
+ // Add a single padding byte at end if chunk size is odd
+ chunkSize = (chunkSize % 2 == 1) ? chunkSize + 1 : chunkSize;
+
+ // Check if skipping to next chunk is necessary
+ if (bytesRead + chunkSize == fileSize) {
+ // Reached end of file
+ break;
+ } else if (bytesRead + chunkSize > fileSize) {
+ throw new IOException("Encountered WebP file with invalid chunk size");
+ }
+
+ // Skip to next chunk
+ in.skipFully(chunkSize);
+ bytesRead += chunkSize;
+ }
+ }
+ } catch (EOFException e) {
+ // Should not reach here. Will only reach here if the file is corrupted or
+ // does not follow the WebP specifications
+ throw new IOException("Encountered corrupt WebP file.", e);
+ }
+ }
+
+ // Stores a new JPEG image with EXIF attributes into a given output stream.
+ private void saveJpegAttributes(InputStream inputStream, OutputStream outputStream)
+ throws IOException {
+ // See JPEG File Interchange Format Specification, "JFIF Specification"
+ if (DEBUG) {
+ Log.d(TAG, "saveJpegAttributes starting with (inputStream: " + inputStream
+ + ", outputStream: " + outputStream + ")");
+ }
+ ByteOrderedDataInputStream dataInputStream = new ByteOrderedDataInputStream(inputStream);
+ ByteOrderedDataOutputStream dataOutputStream =
+ new ByteOrderedDataOutputStream(outputStream, BIG_ENDIAN);
+ if (dataInputStream.readByte() != MARKER) {
+ throw new IOException("Invalid marker");
+ }
+ dataOutputStream.writeByte(MARKER);
+ if (dataInputStream.readByte() != MARKER_SOI) {
+ throw new IOException("Invalid marker");
+ }
+ dataOutputStream.writeByte(MARKER_SOI);
+
+ // Write EXIF APP1 segment
+ dataOutputStream.writeByte(MARKER);
+ dataOutputStream.writeByte(MARKER_APP1);
+ mOffsetToExifData = writeExifSegment(dataOutputStream);
+
+ if (mXmpFromSeparateMarker != null) {
+ // Write XMP APP1 segment. The XMP spec (part 3, section 1.1.3) recommends for this to
+ // directly follow the Exif APP1 segment.
+ dataOutputStream.write(MARKER);
+ dataOutputStream.writeByte(MARKER_APP1);
+ int length = 2 + IDENTIFIER_XMP_APP1.length + mXmpFromSeparateMarker.bytes.length;
+ dataOutputStream.writeUnsignedShort(length);
+ dataOutputStream.write(IDENTIFIER_XMP_APP1);
+ dataOutputStream.write(mXmpFromSeparateMarker.bytes);
+ mFileOnDiskContainsSeparateXmpMarker = true;
+ }
+
+ byte[] bytes = new byte[4096];
+
+ while (true) {
+ byte marker = dataInputStream.readByte();
+ if (marker != MARKER) {
+ throw new IOException("Invalid marker");
+ }
+ marker = dataInputStream.readByte();
+ switch (marker) {
+ case MARKER_APP1: {
+ int length = dataInputStream.readUnsignedShort() - 2;
+ if (length < 0) {
+ throw new IOException("Invalid length");
+ }
+ // If the length is long enough, we read enough bytes for the XMP identifier,
+ // because it's longer than the EXIF one.
+ byte[] identifier;
+ if (length >= IDENTIFIER_XMP_APP1.length) {
+ identifier = new byte[IDENTIFIER_XMP_APP1.length];
+ } else if (length >= IDENTIFIER_EXIF_APP1.length) {
+ identifier = new byte[IDENTIFIER_EXIF_APP1.length];
+ } else {
+ identifier = null;
+ }
+ if (identifier != null) {
+ dataInputStream.readFully(identifier);
+ if (startsWith(identifier, IDENTIFIER_EXIF_APP1)
+ || startsWith(identifier, IDENTIFIER_XMP_APP1)) {
+ // Skip the original EXIF or XMP APP1 segment.
+ dataInputStream.skipFully(length - identifier.length);
+ break;
+ }
+ }
+ // Copy non-EXIF APP1 segment.
+ dataOutputStream.writeByte(MARKER);
+ dataOutputStream.writeByte(marker);
+ dataOutputStream.writeUnsignedShort(length + 2);
+ if (identifier != null) {
+ length -= identifier.length;
+ dataOutputStream.write(identifier);
+ }
+ int read;
+ while (length > 0 && (read = dataInputStream.read(
+ bytes, 0, Math.min(length, bytes.length))) >= 0) {
+ dataOutputStream.write(bytes, 0, read);
+ length -= read;
+ }
+ break;
+ }
+ case MARKER_EOI:
+ case MARKER_SOS: {
+ dataOutputStream.writeByte(MARKER);
+ dataOutputStream.writeByte(marker);
+ // Copy all the remaining data
+ copy(dataInputStream, dataOutputStream);
+ return;
+ }
+ default: {
+ // Copy JPEG segment
+ dataOutputStream.writeByte(MARKER);
+ dataOutputStream.writeByte(marker);
+ int length = dataInputStream.readUnsignedShort();
+ dataOutputStream.writeUnsignedShort(length);
+ length -= 2;
+ if (length < 0) {
+ throw new IOException("Invalid length");
+ }
+ int read;
+ while (length > 0 && (read = dataInputStream.read(
+ bytes, 0, Math.min(length, bytes.length))) >= 0) {
+ dataOutputStream.write(bytes, 0, read);
+ length -= read;
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ private void savePngAttributes(InputStream inputStream, OutputStream outputStream)
+ throws IOException {
+ if (DEBUG) {
+ Log.d(TAG, "savePngAttributes starting with (inputStream: " + inputStream
+ + ", outputStream: " + outputStream + ")");
+ }
+ ByteOrderedDataInputStream dataInputStream = new ByteOrderedDataInputStream(inputStream);
+ ByteOrderedDataOutputStream dataOutputStream =
+ new ByteOrderedDataOutputStream(outputStream, BIG_ENDIAN);
+
+ // Copy PNG signature bytes
+ copy(dataInputStream, dataOutputStream, PNG_SIGNATURE.length);
+
+ boolean needToWriteExif = true;
+ // Either there's some XMP data to write, or it has been cleared locally but was present in
+ // the file when it was read (and so needs to be removed).
+ boolean needToHandleXmpChunk =
+ mXmpFromSeparateMarker != null || mFileOnDiskContainsSeparateXmpMarker;
+ while (needToWriteExif || needToHandleXmpChunk) {
+ int chunkLength = dataInputStream.readInt();
+ int chunkType = dataInputStream.readInt();
+ if (chunkType == PNG_CHUNK_TYPE_IHDR) {
+ dataOutputStream.writeInt(chunkLength);
+ dataOutputStream.writeInt(chunkType);
+ copy(dataInputStream, dataOutputStream, chunkLength + PNG_CHUNK_CRC_BYTE_LENGTH);
+ if (mOffsetToExifData == 0) {
+ // There was no Exif segment in the original file, so we put it directly
+ // after the IHDR chunk.
+ writePngExifChunk(dataOutputStream);
+ needToWriteExif = false;
+ }
+ if (mXmpFromSeparateMarker != null && !mFileOnDiskContainsSeparateXmpMarker) {
+ writePngXmpItxtChunk(dataOutputStream);
+ needToHandleXmpChunk = false;
+ }
+ continue;
+ } else if (chunkType == PNG_CHUNK_TYPE_EXIF && needToWriteExif) {
+ writePngExifChunk(dataOutputStream);
+ dataInputStream.skipFully(chunkLength + PNG_CHUNK_CRC_BYTE_LENGTH);
+ needToWriteExif = false;
+ continue;
+ } else if (chunkType == PNG_CHUNK_TYPE_ITXT
+ && chunkLength >= PNG_ITXT_XMP_KEYWORD.length) {
+ // Read the 17 byte keyword and 5 expected null bytes.
+ byte[] keyword = new byte[PNG_ITXT_XMP_KEYWORD.length];
+ dataInputStream.readFully(keyword);
+ int remainingChunkBytes = chunkLength - keyword.length + PNG_CHUNK_CRC_BYTE_LENGTH;
+ if (Arrays.equals(keyword, PNG_ITXT_XMP_KEYWORD)) {
+ if (mXmpFromSeparateMarker != null) {
+ writePngXmpItxtChunk(dataOutputStream);
+ }
+ dataInputStream.skipFully(remainingChunkBytes);
+ needToHandleXmpChunk = false;
+ } else {
+ // This is a non-XMP iTXt chunk, so just copy it to the output and continue.
+ dataOutputStream.writeInt(chunkLength);
+ dataOutputStream.writeInt(chunkType);
+ dataOutputStream.write(keyword);
+ copy(dataInputStream, dataOutputStream, remainingChunkBytes);
+ }
+ continue;
+ }
+ dataOutputStream.writeInt(chunkLength);
+ dataOutputStream.writeInt(chunkType);
+ copy(dataInputStream, dataOutputStream, chunkLength + PNG_CHUNK_CRC_BYTE_LENGTH);
+ }
+
+ // Copy the rest of the file
+ copy(dataInputStream, dataOutputStream);
+ }
+
+ private void writePngExifChunk(ByteOrderedDataOutputStream dataOutputStream)
+ throws IOException {
+ // Write the eXIF chunk out to an intermediate byte array so we can calculate the CRC value.
+ ByteArrayOutputStream exifByteArrayOutputStream = new ByteArrayOutputStream();
+ // Write eXIF chunk data (including chunk type & length).
+ int exifOffset =
+ writeExifSegment(
+ new ByteOrderedDataOutputStream(exifByteArrayOutputStream, BIG_ENDIAN));
+ mOffsetToExifData = dataOutputStream.mOutputStream.size() + exifOffset;
+ byte[] exifBytes = exifByteArrayOutputStream.toByteArray();
+ dataOutputStream.write(exifBytes);
+ CRC32 crc = new CRC32();
+ crc.update(exifBytes, 4 /* skip length bytes */, exifBytes.length - 4);
+ dataOutputStream.writeInt((int) crc.getValue());
+ }
+
+ private void writePngXmpItxtChunk(ByteOrderedDataOutputStream dataOutputStream)
+ throws IOException {
+ dataOutputStream.writeInt(mXmpFromSeparateMarker.bytes.length + 22);
+ CRC32 crc = new CRC32();
+ dataOutputStream.writeInt(PNG_CHUNK_TYPE_ITXT);
+ updateCrcWithInt(crc, PNG_CHUNK_TYPE_ITXT);
+ dataOutputStream.write(PNG_ITXT_XMP_KEYWORD);
+ crc.update(PNG_ITXT_XMP_KEYWORD);
+ dataOutputStream.write(mXmpFromSeparateMarker.bytes);
+ crc.update(mXmpFromSeparateMarker.bytes);
+ dataOutputStream.writeInt((int) crc.getValue());
+ mFileOnDiskContainsSeparateXmpMarker = true;
+ }
+
+ // A WebP file has a header and a series of chunks.
+ // The header is composed of:
+ // "RIFF" + File Size + "WEBP"
+ //
+ // The structure of the chunks can be divided largely into two categories:
+ // 1) Contains only image data,
+ // 2) Contains image data and extra data.
+ // In the first category, there is only one chunk: type "VP8" (compression with loss) or "VP8L"
+ // (lossless compression).
+ // In the second category, the first chunk will be of type "VP8X", which contains flags
+ // indicating which extra data exist in later chunks. The proceeding chunks must conform to
+ // the following order based on type (if they exist):
+ // Color Profile ("ICCP") + Animation Control Data ("ANIM") + Image Data ("VP8"/"VP8L")
+ // + Exif metadata ("EXIF") + XMP metadata ("XMP")
+ //
+ // And in order to have EXIF data, a WebP file must be of the second structure and thus follow
+ // the following rules:
+ // 1) "VP8X" chunk as the first chunk,
+ // 2) flag for EXIF inside "VP8X" chunk set to 1, and
+ // 3) contain the "EXIF" chunk in the correct order amongst other chunks.
+ //
+ // Based on these rules, this API will support three different cases depending on the contents
+ // of the original file:
+ // 1) "EXIF" chunk already exists
+ // -> replace it with the new "EXIF" chunk
+ // 2) "EXIF" chunk does not exist and the first chunk is "VP8" or "VP8L"
+ // -> add "VP8X" before the "VP8"/"VP8L" chunk (with EXIF flag set to 1), and add new
+ // "EXIF" chunk after the "VP8"/"VP8L" chunk.
+ // 3) "EXIF" chunk does not exist and the first chunk is "VP8X"
+ // -> set EXIF flag in "VP8X" chunk to 1, and add new "EXIF" chunk at the proper location.
+ //
+ // See https://developers.google.com/speed/webp/docs/riff_container for more details.
+ private void saveWebpAttributes(InputStream inputStream, OutputStream outputStream)
+ throws IOException {
+ if (DEBUG) {
+ Log.d(TAG, "saveWebpAttributes starting with (inputStream: " + inputStream
+ + ", outputStream: " + outputStream + ")");
+ }
+ ByteOrderedDataInputStream totalInputStream =
+ new ByteOrderedDataInputStream(inputStream, LITTLE_ENDIAN);
+ ByteOrderedDataOutputStream totalOutputStream =
+ new ByteOrderedDataOutputStream(outputStream, LITTLE_ENDIAN);
+
+ // WebP signature
+ copy(totalInputStream, totalOutputStream, WEBP_SIGNATURE_1.length);
+ int riffLength = totalInputStream.readInt();
+ totalInputStream.skipFully(WEBP_SIGNATURE_2.length);
+
+ // Create a separate byte array to calculate file length
+ ByteArrayOutputStream nonHeaderByteArrayOutputStream = null;
+ int exifOffset = -1;
+ try {
+ nonHeaderByteArrayOutputStream = new ByteArrayOutputStream();
+ ByteOrderedDataOutputStream nonHeaderOutputStream =
+ new ByteOrderedDataOutputStream(nonHeaderByteArrayOutputStream, LITTLE_ENDIAN);
+
+ if (mOffsetToExifData != 0) {
+ // EXIF chunk exists in the original file
+ // Tested by webp_with_exif.webp
+ int bytesRead = WEBP_SIGNATURE_1.length + WEBP_FILE_SIZE_BYTE_LENGTH
+ + WEBP_SIGNATURE_2.length;
+ copy(totalInputStream, nonHeaderOutputStream,
+ mOffsetToExifData - bytesRead - WEBP_CHUNK_TYPE_BYTE_LENGTH
+ - WEBP_CHUNK_SIZE_BYTE_LENGTH);
+
+ // Skip input stream to the end of the EXIF chunk
+ totalInputStream.skipFully(WEBP_CHUNK_TYPE_BYTE_LENGTH);
+ int exifChunkLength = totalInputStream.readInt();
+ // RIFF chunks have a single padding byte at the end if the declared chunk size is
+ // odd.
+ if (exifChunkLength % 2 != 0) {
+ exifChunkLength++;
+ }
+ totalInputStream.skipFully(exifChunkLength);
+
+ // Write new EXIF chunk to output stream
+ exifOffset = writeExifSegment(nonHeaderOutputStream);
+ } else {
+ // EXIF chunk does not exist in the original file
+ byte[] firstChunkType = new byte[WEBP_CHUNK_TYPE_BYTE_LENGTH];
+ totalInputStream.readFully(firstChunkType);
+
+ if (Arrays.equals(firstChunkType, WEBP_CHUNK_TYPE_VP8X)) {
+ // Original file already includes other extra data
+ int size = totalInputStream.readInt();
+ // WebP files have a single padding byte at the end if the chunk size is odd.
+ byte[] data = new byte[(size % 2) == 1 ? size + 1 : size];
+ totalInputStream.readFully(data);
+
+ // Set the EXIF flag to 1
+ data[0] = (byte) (data[0] | (1 << 3));
+
+ // Retrieve Animation flag--in order to check where EXIF data should start
+ boolean containsAnimation = ((data[0] >> 1) & 1) == 1;
+
+ // Write the original VP8X chunk
+ nonHeaderOutputStream.write(WEBP_CHUNK_TYPE_VP8X);
+ nonHeaderOutputStream.writeInt(size);
+ nonHeaderOutputStream.write(data);
+
+ // Animation control data is composed of 1 ANIM chunk and multiple ANMF
+ // chunks and since the image data (VP8/VP8L) chunks are included in the ANMF
+ // chunks, EXIF data should come after the last ANMF chunk.
+ // Also, because there is no value indicating the amount of ANMF chunks, we need
+ // to keep iterating through chunks until we either reach the end of the file or
+ // the XMP chunk (if it exists).
+ // Tested by webp_with_anim_without_exif.webp
+ if (containsAnimation) {
+ copyChunksUpToGivenChunkType(totalInputStream, nonHeaderOutputStream,
+ WEBP_CHUNK_TYPE_ANIM, null);
+
+ while (true) {
+ byte[] type = new byte[WEBP_CHUNK_TYPE_BYTE_LENGTH];
+ boolean animationFinished = false;
+ try {
+ totalInputStream.readFully(type);
+ animationFinished = !Arrays.equals(type, WEBP_CHUNK_TYPE_ANMF);
+ } catch (EOFException e) {
+ animationFinished = true;
+ }
+ if (animationFinished) {
+ exifOffset = writeExifSegment(nonHeaderOutputStream);
+ break;
+ }
+ copyWebPChunk(totalInputStream, nonHeaderOutputStream, type);
+ }
+ } else {
+ // Skip until we find the VP8 or VP8L chunk
+ copyChunksUpToGivenChunkType(totalInputStream, nonHeaderOutputStream,
+ WEBP_CHUNK_TYPE_VP8, WEBP_CHUNK_TYPE_VP8L);
+ exifOffset = writeExifSegment(nonHeaderOutputStream);
+ }
+ } else if (Arrays.equals(firstChunkType, WEBP_CHUNK_TYPE_VP8)
+ || Arrays.equals(firstChunkType, WEBP_CHUNK_TYPE_VP8L)) {
+ int size = totalInputStream.readInt();
+ int bytesToRead = size;
+ // WebP files have a single padding byte at the end if the chunk size is odd.
+ if (size % 2 == 1) {
+ bytesToRead += 1;
+ }
+
+ // Retrieve image width/height
+ int widthAndHeight = 0;
+ int width = 0;
+ int height = 0;
+ boolean alpha = false;
+ // Save VP8 frame data for later
+ byte[] vp8Frame = new byte[3];
+
+ if (Arrays.equals(firstChunkType, WEBP_CHUNK_TYPE_VP8)) {
+ totalInputStream.readFully(vp8Frame);
+
+ // Check signature
+ byte[] vp8Signature = new byte[3];
+ totalInputStream.readFully(vp8Signature);
+ if (!Arrays.equals(WEBP_VP8_SIGNATURE, vp8Signature)) {
+ throw new IOException("Error checking VP8 signature");
+ }
+
+ // Retrieve image width/height
+ widthAndHeight = totalInputStream.readInt();
+ width = widthAndHeight & 0x3FFF;
+ height = (widthAndHeight >> 16) & 0x3FFF;
+ bytesToRead -= (vp8Frame.length + vp8Signature.length + 4);
+ } else if (Arrays.equals(firstChunkType, WEBP_CHUNK_TYPE_VP8L)) {
+ // Check signature
+ byte vp8lSignature = totalInputStream.readByte();
+ if (vp8lSignature != WEBP_VP8L_SIGNATURE) {
+ throw new IOException("Error checking VP8L signature");
+ }
+
+ // Retrieve image width/height
+ widthAndHeight = totalInputStream.readInt();
+ // VP8L stores 14-bit 'width - 1' and 'height - 1' values. See "RIFF Header"
+ // of "WebP Lossless Bitstream Specification".
+ width = (widthAndHeight & 0x3FFF) + 1; // Read bits 0 - 13
+ height = ((widthAndHeight & 0xFFFC000) >>> 14) + 1; // Read bits 14 - 27
+ // Retrieve alpha bit 28
+ alpha = (widthAndHeight & 1 << 28) != 0;
+ bytesToRead -= (1 /* VP8L signature */ + 4);
+ }
+
+ // Create VP8X with Exif flag set to 1
+ nonHeaderOutputStream.write(WEBP_CHUNK_TYPE_VP8X);
+ nonHeaderOutputStream.writeInt(WEBP_CHUNK_TYPE_VP8X_DEFAULT_LENGTH);
+ byte[] data = new byte[WEBP_CHUNK_TYPE_VP8X_DEFAULT_LENGTH];
+ // ALPHA flag
+ if (alpha) {
+ data[0] = (byte) (data[0] | (1 << 4));
+ }
+ // EXIF flag
+ data[0] = (byte) (data[0] | (1 << 3));
+ // VP8X stores Width - 1 and Height - 1 values
+ width -= 1;
+ height -= 1;
+ data[4] = (byte) width;
+ data[5] = (byte) (width >> 8);
+ data[6] = (byte) (width >> 16);
+ data[7] = (byte) height;
+ data[8] = (byte) (height >> 8);
+ data[9] = (byte) (height >> 16);
+ nonHeaderOutputStream.write(data);
+
+ // Write VP8 or VP8L data
+ nonHeaderOutputStream.write(firstChunkType);
+ nonHeaderOutputStream.writeInt(size);
+ if (Arrays.equals(firstChunkType, WEBP_CHUNK_TYPE_VP8)) {
+ nonHeaderOutputStream.write(vp8Frame);
+ nonHeaderOutputStream.write(WEBP_VP8_SIGNATURE);
+ nonHeaderOutputStream.writeInt(widthAndHeight);
+ } else if (Arrays.equals(firstChunkType, WEBP_CHUNK_TYPE_VP8L)) {
+ nonHeaderOutputStream.write(WEBP_VP8L_SIGNATURE);
+ nonHeaderOutputStream.writeInt(widthAndHeight);
+ }
+ copy(totalInputStream, nonHeaderOutputStream, bytesToRead);
+
+ // Write EXIF chunk
+ exifOffset = writeExifSegment(nonHeaderOutputStream);
+ }
+ }
+
+ // Copy the rest of the RIFF part of the file
+ int remainingRiffBytes = riffLength + 8 - totalInputStream.position();
+ copy(totalInputStream, nonHeaderOutputStream, remainingRiffBytes);
+
+ // Write file length + second signature
+ totalOutputStream.writeInt(nonHeaderByteArrayOutputStream.size()
+ + WEBP_SIGNATURE_2.length);
+ totalOutputStream.write(WEBP_SIGNATURE_2);
+ if (exifOffset != -1) {
+ mOffsetToExifData = totalOutputStream.mOutputStream.size() + exifOffset;
+ }
+ nonHeaderByteArrayOutputStream.writeTo(totalOutputStream);
+ // Copy any non-RIFF trailing data
+ copy(totalInputStream, totalOutputStream);
+ } catch (Exception e) {
+ throw new IOException("Failed to save WebP file", e);
+ } finally {
+ closeQuietly(nonHeaderByteArrayOutputStream);
+ }
+ }
+
+ private void copyChunksUpToGivenChunkType(ByteOrderedDataInputStream inputStream,
+ ByteOrderedDataOutputStream outputStream, byte[] firstGivenType,
+ byte[] secondGivenType) throws IOException {
+ while (true) {
+ byte[] type = new byte[WEBP_CHUNK_TYPE_BYTE_LENGTH];
+ inputStream.readFully(type);
+ copyWebPChunk(inputStream, outputStream, type);
+ if (Arrays.equals(type, firstGivenType)
+ || (secondGivenType != null && Arrays.equals(type, secondGivenType))) {
+ break;
+ }
+ }
+ }
+
+ private void copyWebPChunk(ByteOrderedDataInputStream inputStream,
+ ByteOrderedDataOutputStream outputStream, byte[] type) throws IOException {
+ int size = inputStream.readInt();
+ outputStream.write(type);
+ outputStream.writeInt(size);
+ // WebP files have a single padding byte at the end if the chunk size is odd.
+ copy(inputStream, outputStream, (size % 2) == 1 ? size + 1 : size);
+ }
+
+ // Reads the given EXIF byte area and save its tag data into attributes.
+ private void readExifSegment(byte[] exifBytes, int imageType) throws IOException {
+ SeekableByteOrderedDataInputStream dataInputStream =
+ new SeekableByteOrderedDataInputStream(exifBytes);
+
+ // Parse TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1.
+ parseTiffHeaders(dataInputStream);
+
+ // Read TIFF image file directories. See JEITA CP-3451C Section 4.5.2. Figure 6.
+ readImageFileDirectory(dataInputStream, imageType);
+ }
+
+ private void addDefaultValuesForCompatibility() {
+ // If DATETIME tag has no value, then set the value to DATETIME_ORIGINAL tag's.
+ String valueOfDateTimeOriginal = getAttribute(TAG_DATETIME_ORIGINAL);
+ if (valueOfDateTimeOriginal != null && getAttribute(TAG_DATETIME) == null) {
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_DATETIME,
+ ExifAttribute.createString(valueOfDateTimeOriginal));
+ }
+
+ // Add the default value.
+ if (getAttribute(TAG_IMAGE_WIDTH) == null) {
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH,
+ ExifAttribute.createULong(0, mExifByteOrder));
+ }
+ if (getAttribute(TAG_IMAGE_LENGTH) == null) {
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH,
+ ExifAttribute.createULong(0, mExifByteOrder));
+ }
+ if (getAttribute(TAG_ORIENTATION) == null) {
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_ORIENTATION,
+ ExifAttribute.createULong(0, mExifByteOrder));
+ }
+ if (getAttribute(TAG_LIGHT_SOURCE) == null) {
+ mAttributes[IFD_TYPE_EXIF].put(TAG_LIGHT_SOURCE,
+ ExifAttribute.createULong(0, mExifByteOrder));
+ }
+ }
+
+ private ByteOrder readByteOrder(ByteOrderedDataInputStream dataInputStream)
+ throws IOException {
+ // Read byte order.
+ short byteOrder = dataInputStream.readShort();
+ switch (byteOrder) {
+ case BYTE_ALIGN_II:
+ if (DEBUG) {
+ Log.d(TAG, "readExifSegment: Byte Align II");
+ }
+ return LITTLE_ENDIAN;
+ case BYTE_ALIGN_MM:
+ if (DEBUG) {
+ Log.d(TAG, "readExifSegment: Byte Align MM");
+ }
+ return BIG_ENDIAN;
+ default:
+ throw new IOException("Invalid byte order: " + Integer.toHexString(byteOrder));
+ }
+ }
+
+ private void parseTiffHeaders(ByteOrderedDataInputStream dataInputStream) throws IOException {
+ // Read byte order
+ mExifByteOrder = readByteOrder(dataInputStream);
+ // Set byte order
+ dataInputStream.setByteOrder(mExifByteOrder);
+
+ // Check start code
+ int startCode = dataInputStream.readUnsignedShort();
+ if (mMimeType != IMAGE_TYPE_ORF && mMimeType != IMAGE_TYPE_RW2 && startCode != START_CODE) {
+ throw new IOException("Invalid start code: " + Integer.toHexString(startCode));
+ }
+
+ // Read and skip to first ifd offset
+ int firstIfdOffset = dataInputStream.readInt();
+ if (firstIfdOffset < 8) {
+ throw new IOException("Invalid first Ifd offset: " + firstIfdOffset);
+ }
+ firstIfdOffset -= 8;
+ if (firstIfdOffset > 0) {
+ // TLAD start
+ if (firstIfdOffset > ATTRIBUTE_SIZE_DANGER_THRESHOLD) {
+ throw new IOException("dangerous IFD offset=" + firstIfdOffset);
+ }
+ // TLAD end
+ dataInputStream.skipFully(firstIfdOffset);
+ }
+ }
+
+ // Reads image file directory, which is a tag group in EXIF.
+ private void readImageFileDirectory(SeekableByteOrderedDataInputStream dataInputStream,
+ @IfdType int ifdType) throws IOException {
+ // Save offset of current IFD to prevent reading an IFD that is already read.
+ mAttributesOffsets.add(dataInputStream.position());
+
+ // See TIFF 6.0 Section 2: TIFF Structure, Figure 1.
+ short numberOfDirectoryEntry = dataInputStream.readShort();
+ if (DEBUG) {
+ Log.d(TAG, "numberOfDirectoryEntry: " + numberOfDirectoryEntry);
+ }
+ if (numberOfDirectoryEntry <= 0) {
+ // Return if the size of entries is negative.
+ return;
+ }
+
+ // See TIFF 6.0 Section 2: TIFF Structure, "Image File Directory".
+ for (short i = 0; i < numberOfDirectoryEntry; ++i) {
+ int tagNumber = dataInputStream.readUnsignedShort();
+ int dataFormat = dataInputStream.readUnsignedShort();
+ int numberOfComponents = dataInputStream.readInt();
+ // Next four bytes is for data offset or value.
+ long nextEntryOffset = dataInputStream.position() + 4L;
+
+ // Look up a corresponding tag from tag number
+ ExifTag tag = sExifTagMapsForReading[ifdType].get(tagNumber);
+
+ if (DEBUG) {
+ Log.d(TAG, String.format("ifdType: %d, tagNumber: %d, tagName: %s, dataFormat: %d, "
+ + "numberOfComponents: %d", ifdType, tagNumber,
+ tag != null ? tag.name : null, dataFormat, numberOfComponents));
+ }
+
+ long byteCount = 0;
+ boolean valid = false;
+ if (tag == null) {
+ if (DEBUG) {
+ Log.d(TAG, "Skip the tag entry since tag number is not defined: " + tagNumber);
+ }
+ } else if (dataFormat <= 0 || dataFormat >= IFD_FORMAT_BYTES_PER_FORMAT.length) {
+ if (DEBUG) {
+ Log.d(TAG, "Skip the tag entry since data format is invalid: " + dataFormat);
+ }
+ } else if (!tag.isFormatCompatible(dataFormat)) {
+ if (DEBUG) {
+ Log.d(TAG, "Skip the tag entry since data format ("
+ + IFD_FORMAT_NAMES[dataFormat] + ") is unexpected for tag: "
+ + tag.name);
+ }
+ } else {
+ if (dataFormat == IFD_FORMAT_UNDEFINED) {
+ dataFormat = tag.primaryFormat;
+ }
+ byteCount = (long) numberOfComponents * IFD_FORMAT_BYTES_PER_FORMAT[dataFormat];
+ if (byteCount < 0 || byteCount > Integer.MAX_VALUE) {
+ if (DEBUG) {
+ Log.d(TAG, "Skip the tag entry since the number of components is invalid: "
+ + numberOfComponents);
+ }
+ } else {
+ valid = true;
+ }
+ }
+ if (!valid) {
+ dataInputStream.seek(nextEntryOffset);
+ continue;
+ }
+
+ // Read a value from data field or seek to the value offset which is stored in data
+ // field if the size of the entry value is bigger than 4.
+ if (byteCount > 4) {
+ int offset = dataInputStream.readInt();
+ if (DEBUG) {
+ Log.d(TAG, "seek to data offset: " + offset);
+ }
+ if (mMimeType == IMAGE_TYPE_ORF) {
+ if (TAG_MAKER_NOTE.equals(tag.name)) {
+ // Save offset value for reading thumbnail
+ mOrfMakerNoteOffset = offset;
+ } else if (ifdType == IFD_TYPE_ORF_MAKER_NOTE
+ && TAG_ORF_THUMBNAIL_IMAGE.equals(tag.name)) {
+ // Retrieve & update values for thumbnail offset and length values for ORF
+ mOrfThumbnailOffset = offset;
+ mOrfThumbnailLength = numberOfComponents;
+
+ ExifAttribute compressionAttribute =
+ ExifAttribute.createUShort(DATA_JPEG, mExifByteOrder);
+ ExifAttribute jpegInterchangeFormatAttribute =
+ ExifAttribute.createULong(mOrfThumbnailOffset, mExifByteOrder);
+ ExifAttribute jpegInterchangeFormatLengthAttribute =
+ ExifAttribute.createULong(mOrfThumbnailLength, mExifByteOrder);
+
+ mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_COMPRESSION, compressionAttribute);
+ mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT,
+ jpegInterchangeFormatAttribute);
+ mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH,
+ jpegInterchangeFormatLengthAttribute);
+ }
+ }
+ dataInputStream.seek(offset);
+ }
+
+ // Recursively parse IFD when a IFD pointer tag appears.
+ Integer nextIfdType = sExifPointerTagMap.get(tagNumber);
+ if (DEBUG) {
+ Log.d(TAG, "nextIfdType: " + nextIfdType + " byteCount: " + byteCount);
+ }
+
+ if (nextIfdType != null) {
+ long offset = -1L;
+ // Get offset from data field
+ switch (dataFormat) {
+ case IFD_FORMAT_USHORT: {
+ offset = dataInputStream.readUnsignedShort();
+ break;
+ }
+ case IFD_FORMAT_SSHORT: {
+ offset = dataInputStream.readShort();
+ break;
+ }
+ case IFD_FORMAT_ULONG: {
+ offset = dataInputStream.readUnsignedInt();
+ break;
+ }
+ case IFD_FORMAT_SLONG:
+ case IFD_FORMAT_IFD: {
+ offset = dataInputStream.readInt();
+ break;
+ }
+ default: {
+ // Nothing to do
+ break;
+ }
+ }
+ if (DEBUG) {
+ Log.d(TAG, String.format("Offset: %d, tagName: %s", offset, tag.name));
+ }
+
+ // Check if the next IFD offset
+ // 1. Is a non-negative value (within the length of the input, if known), and
+ // 2. Does not point to a previously read IFD.
+ if (offset > 0L
+ && (dataInputStream.length() == ByteOrderedDataInputStream.LENGTH_UNSET
+ || offset < dataInputStream.length())) {
+ if (!mAttributesOffsets.contains((int) offset)) {
+ dataInputStream.seek(offset);
+ readImageFileDirectory(dataInputStream, nextIfdType);
+ } else {
+ if (DEBUG) {
+ Log.d(TAG, "Skip jump into the IFD since it has already been read: "
+ + "IfdType " + nextIfdType + " (at " + offset + ")");
+ }
+ }
+ } else {
+ if (DEBUG) {
+ String message =
+ "Skip jump into the IFD since its offset is invalid: " + offset;
+ if (dataInputStream.length() != ByteOrderedDataInputStream.LENGTH_UNSET) {
+ message += " (total length: " + dataInputStream.length() + ")";
+ }
+ Log.d(TAG, message);
+ }
+ }
+
+ dataInputStream.seek(nextEntryOffset);
+ continue;
+ }
+
+ final int bytesOffset = dataInputStream.position() + mOffsetToExifData;
+ // TLAD start
+ if (byteCount > ATTRIBUTE_SIZE_DANGER_THRESHOLD) {
+ throw new IOException("dangerous attribute size=" + byteCount);
+ }
+ // TLAD end
+ final byte[] bytes = new byte[(int) byteCount];
+ dataInputStream.readFully(bytes);
+ ExifAttribute attribute = new ExifAttribute(dataFormat, numberOfComponents,
+ bytesOffset, bytes);
+ mAttributes[ifdType].put(tag.name, attribute);
+
+ // DNG files have a DNG Version tag specifying the version of specifications that the
+ // image file is following.
+ // See http://fileformats.archiveteam.org/wiki/DNG
+ if (TAG_DNG_VERSION.equals(tag.name)) {
+ mMimeType = IMAGE_TYPE_DNG;
+ }
+
+ // PEF files have a Make or Model tag that begins with "PENTAX" or a compression tag
+ // that is 65535.
+ // See http://fileformats.archiveteam.org/wiki/Pentax_PEF
+ if (((TAG_MAKE.equals(tag.name) || TAG_MODEL.equals(tag.name))
+ && attribute.getStringValue(mExifByteOrder).contains(PEF_SIGNATURE))
+ || (TAG_COMPRESSION.equals(tag.name)
+ && attribute.getIntValue(mExifByteOrder) == 65535)) {
+ mMimeType = IMAGE_TYPE_PEF;
+ }
+
+ // Seek to next tag offset
+ if (dataInputStream.position() != nextEntryOffset) {
+ dataInputStream.seek(nextEntryOffset);
+ }
+ }
+
+ int nextIfdOffset = dataInputStream.readInt();
+ if (DEBUG) {
+ Log.d(TAG, String.format("nextIfdOffset: %d", nextIfdOffset));
+ }
+ // Check if the next IFD offset
+ // 1. Is a non-negative value, and
+ // 2. Does not point to a previously read IFD.
+ if (nextIfdOffset > 0L) {
+ if (!mAttributesOffsets.contains(nextIfdOffset)) {
+ dataInputStream.seek(nextIfdOffset);
+ if (mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) {
+ // Do not overwrite thumbnail IFD data if it already exists.
+ readImageFileDirectory(dataInputStream, IFD_TYPE_THUMBNAIL);
+ } else if (mAttributes[IFD_TYPE_PREVIEW].isEmpty()) {
+ readImageFileDirectory(dataInputStream, IFD_TYPE_PREVIEW);
+ }
+ } else {
+ if (DEBUG) {
+ Log.d(TAG, "Stop reading file since re-reading an IFD may cause an "
+ + "infinite loop: " + nextIfdOffset);
+ }
+ }
+ } else {
+ if (DEBUG) {
+ Log.d(TAG, "Stop reading file since a wrong offset may cause an infinite loop: "
+ + nextIfdOffset);
+ }
+ }
+ }
+
+ /**
+ * JPEG compressed images do not contain IMAGE_LENGTH & IMAGE_WIDTH tags.
+ * This value uses JpegInterchangeFormat(JPEG data offset) value, and calls getJpegAttributes()
+ * to locate SOF(Start of Frame) marker and update the image length & width values.
+ * See JEITA CP-3451C Table 5 and Section 4.8.1. B.
+ */
+ private void retrieveJpegImageSize(SeekableByteOrderedDataInputStream in, int imageType)
+ throws IOException {
+ // Check if image already has IMAGE_LENGTH & IMAGE_WIDTH values
+ ExifAttribute imageLengthAttribute =
+ mAttributes[imageType].get(TAG_IMAGE_LENGTH);
+ ExifAttribute imageWidthAttribute =
+ mAttributes[imageType].get(TAG_IMAGE_WIDTH);
+
+ if (imageLengthAttribute == null || imageWidthAttribute == null) {
+ // Find if offset for JPEG data exists
+ ExifAttribute jpegInterchangeFormatAttribute =
+ mAttributes[imageType].get(TAG_JPEG_INTERCHANGE_FORMAT);
+ ExifAttribute jpegInterchangeFormatLengthAttribute =
+ mAttributes[imageType].get(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH);
+ if (jpegInterchangeFormatAttribute != null
+ && jpegInterchangeFormatLengthAttribute != null) {
+ int jpegInterchangeFormat =
+ jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder);
+ int jpegInterchangeFormatLength =
+ jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder);
+
+ // Searches for SOF marker in JPEG data and updates IMAGE_LENGTH & IMAGE_WIDTH tags
+ in.seek(jpegInterchangeFormat);
+
+ // TLAD start
+ if (jpegInterchangeFormatLength > getAvailableHeapSize()) {
+ throw new IOException("cannot allocate " + jpegInterchangeFormatLength + " bytes to retrieve image size");
+ }
+ // TLAD end
+
+ byte[] jpegBytes = new byte[jpegInterchangeFormatLength];
+ in.readFully(jpegBytes);
+ getJpegAttributes(new ByteOrderedDataInputStream(jpegBytes), jpegInterchangeFormat,
+ imageType);
+ }
+ }
+ }
+
+ // Sets thumbnail offset & length attributes based on JpegInterchangeFormat or StripOffsets tags
+ private void setThumbnailData(ByteOrderedDataInputStream in) throws IOException {
+ HashMap<String, ExifAttribute> thumbnailData = mAttributes[IFD_TYPE_THUMBNAIL];
+
+ ExifAttribute compressionAttribute =
+ thumbnailData.get(TAG_COMPRESSION);
+ if (compressionAttribute != null) {
+ mThumbnailCompression = compressionAttribute.getIntValue(mExifByteOrder);
+ switch (mThumbnailCompression) {
+ case DATA_JPEG: {
+ handleThumbnailFromJfif(in, thumbnailData);
+ break;
+ }
+ case DATA_UNCOMPRESSED:
+ case DATA_JPEG_COMPRESSED: {
+ if (isSupportedDataType(thumbnailData)) {
+ handleThumbnailFromStrips(in, thumbnailData);
+ }
+ break;
+ }
+ }
+ } else {
+ // Thumbnail data may not contain Compression tag value
+ mThumbnailCompression = DATA_JPEG;
+ handleThumbnailFromJfif(in, thumbnailData);
+ }
+ }
+
+ // Check JpegInterchangeFormat(JFIF) tags to retrieve thumbnail offset & length values
+ // and reads the corresponding bytes if stream does not support seek function
+ private void handleThumbnailFromJfif(ByteOrderedDataInputStream in,
+ HashMap<String, ExifAttribute> thumbnailData) throws IOException {
+ ExifAttribute jpegInterchangeFormatAttribute =
+ thumbnailData.get(TAG_JPEG_INTERCHANGE_FORMAT);
+ ExifAttribute jpegInterchangeFormatLengthAttribute =
+ thumbnailData.get(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH);
+ if (jpegInterchangeFormatAttribute != null
+ && jpegInterchangeFormatLengthAttribute != null) {
+ int thumbnailOffset = jpegInterchangeFormatAttribute.getIntValue(mExifByteOrder);
+ int thumbnailLength = jpegInterchangeFormatLengthAttribute.getIntValue(mExifByteOrder);
+
+ if (mMimeType == IMAGE_TYPE_ORF) {
+ // Update offset value since RAF files have IFD data preceding MakerNote data.
+ thumbnailOffset += mOrfMakerNoteOffset;
+ }
+
+ if (thumbnailOffset > 0 && thumbnailLength > 0) {
+ mHasThumbnail = true;
+ if (mFilename == null && mAssetInputStream == null
+ && mSeekableFileDescriptor == null) {
+ // TODO: Need to handle potential OutOfMemoryError
+ // Save the thumbnail in memory if the input doesn't support reading again.
+ byte[] thumbnailBytes = new byte[thumbnailLength];
+ in.skipFully(thumbnailOffset);
+ in.readFully(thumbnailBytes);
+ mThumbnailBytes = thumbnailBytes;
+ }
+ mThumbnailOffset = thumbnailOffset;
+ mThumbnailLength = thumbnailLength;
+ }
+ if (DEBUG) {
+ Log.d(TAG, "Setting thumbnail attributes with offset: " + thumbnailOffset
+ + ", length: " + thumbnailLength);
+ }
+ }
+ }
+
+ // Check StripOffsets & StripByteCounts tags to retrieve thumbnail offset & length values
+ private void handleThumbnailFromStrips(ByteOrderedDataInputStream in,
+ HashMap<String, ExifAttribute> thumbnailData) throws IOException {
+ ExifAttribute stripOffsetsAttribute =
+ thumbnailData.get(TAG_STRIP_OFFSETS);
+ ExifAttribute stripByteCountsAttribute =
+ thumbnailData.get(TAG_STRIP_BYTE_COUNTS);
+
+ if (stripOffsetsAttribute != null && stripByteCountsAttribute != null) {
+ long[] stripOffsets =
+ convertToLongArray(stripOffsetsAttribute.getValue(mExifByteOrder));
+ long[] stripByteCounts =
+ convertToLongArray(stripByteCountsAttribute.getValue(mExifByteOrder));
+
+ if (stripOffsets == null || stripOffsets.length == 0) {
+ Log.w(TAG, "stripOffsets should not be null or have zero length.");
+ return;
+ }
+ if (stripByteCounts == null || stripByteCounts.length == 0) {
+ Log.w(TAG, "stripByteCounts should not be null or have zero length.");
+ return;
+ }
+ if (stripOffsets.length != stripByteCounts.length) {
+ Log.w(TAG, "stripOffsets and stripByteCounts should have same length.");
+ return;
+ }
+
+ long totalStripByteCount = 0;
+ for (long byteCount : stripByteCounts) {
+ totalStripByteCount += byteCount;
+ }
+
+ // TODO: Need to handle potential OutOfMemoryError
+ // Set thumbnail byte array data for non-consecutive strip bytes
+ byte[] totalStripBytes = new byte[(int) totalStripByteCount];
+
+ int bytesRead = 0;
+ int bytesAdded = 0;
+ mHasThumbnail = mHasThumbnailStrips = mAreThumbnailStripsConsecutive = true;
+ for (int i = 0; i < stripOffsets.length; i++) {
+ int stripOffset = (int) stripOffsets[i];
+ int stripByteCount = (int) stripByteCounts[i];
+
+ // Check if strips are consecutive
+ // TODO: Add test for non-consecutive thumbnail image
+ if (i < stripOffsets.length - 1
+ && stripOffset + stripByteCount != stripOffsets[i + 1]) {
+ mAreThumbnailStripsConsecutive = false;
+ }
+
+ // Skip to offset
+ int bytesToSkip = stripOffset - bytesRead;
+ if (bytesToSkip < 0) {
+ Log.d(TAG, "Invalid strip offset value");
+ return;
+ }
+
+ // TLAD start
+ if (bytesToSkip > getAvailableHeapSize()) {
+ throw new IOException("cannot allocate " + bytesToSkip + " bytes to skip to retrieve thumbnail");
+ }
+ // TLAD end
+
+ try {
+ in.skipFully(bytesToSkip);
+ } catch (EOFException e) {
+ Log.d(TAG, "Failed to skip " + bytesToSkip + " bytes.");
+ return;
+ }
+ bytesRead += bytesToSkip;
+ // TODO: Need to handle potential OutOfMemoryError
+ byte[] stripBytes = new byte[stripByteCount];
+ try {
+ in.readFully(stripBytes);
+ } catch (EOFException e) {
+ Log.d(TAG, "Failed to read " + stripByteCount + " bytes.");
+ return;
+ }
+ bytesRead += stripByteCount;
+
+ // Add bytes to array
+ System.arraycopy(stripBytes, 0, totalStripBytes, bytesAdded,
+ stripBytes.length);
+ bytesAdded += stripBytes.length;
+ }
+ mThumbnailBytes = totalStripBytes;
+
+ if (mAreThumbnailStripsConsecutive) {
+ mThumbnailOffset = (int) stripOffsets[0];
+ mThumbnailLength = totalStripBytes.length;
+ }
+ }
+ }
+
+ // Check if thumbnail data type is currently supported or not
+ private boolean isSupportedDataType(HashMap<String, ExifAttribute> thumbnailData) {
+ ExifAttribute bitsPerSampleAttribute =
+ thumbnailData.get(TAG_BITS_PER_SAMPLE);
+ if (bitsPerSampleAttribute != null) {
+ int[] bitsPerSampleValue = (int[]) bitsPerSampleAttribute.getValue(mExifByteOrder);
+
+ if (Arrays.equals(BITS_PER_SAMPLE_RGB, bitsPerSampleValue)) {
+ return true;
+ }
+
+ // See DNG Specification 1.4.0.0. Section 3, Compression.
+ if (mMimeType == IMAGE_TYPE_DNG) {
+ ExifAttribute photometricInterpretationAttribute =
+ thumbnailData.get(TAG_PHOTOMETRIC_INTERPRETATION);
+ if (photometricInterpretationAttribute != null) {
+ int photometricInterpretationValue
+ = photometricInterpretationAttribute.getIntValue(mExifByteOrder);
+ if ((photometricInterpretationValue == PHOTOMETRIC_INTERPRETATION_BLACK_IS_ZERO
+ && Arrays.equals(bitsPerSampleValue, BITS_PER_SAMPLE_GREYSCALE_2))
+ || ((photometricInterpretationValue == PHOTOMETRIC_INTERPRETATION_YCBCR)
+ && Arrays.equals(bitsPerSampleValue, BITS_PER_SAMPLE_RGB))) {
+ return true;
+ } else {
+ // TODO: Add support for lossless Huffman JPEG data
+ }
+ }
+ }
+ }
+ if (DEBUG) {
+ Log.d(TAG, "Unsupported data type value");
+ }
+ return false;
+ }
+
+ // Returns true if the image length and width values are <= 512.
+ // See Section 4.8 of http://standardsproposals.bsigroup.com/Home/getPDF/567
+ private boolean isThumbnail(HashMap<String, ExifAttribute> map) {
+ ExifAttribute imageLengthAttribute = map.get(TAG_IMAGE_LENGTH);
+ ExifAttribute imageWidthAttribute = map.get(TAG_IMAGE_WIDTH);
+
+ if (imageLengthAttribute != null && imageWidthAttribute != null) {
+ int imageLengthValue = imageLengthAttribute.getIntValue(mExifByteOrder);
+ int imageWidthValue = imageWidthAttribute.getIntValue(mExifByteOrder);
+ if (imageLengthValue <= MAX_THUMBNAIL_SIZE && imageWidthValue <= MAX_THUMBNAIL_SIZE) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // Validate primary, preview, thumbnail image data by comparing image size
+ private void validateImages() throws IOException {
+ // Swap images based on size (primary > preview > thumbnail)
+ swapBasedOnImageSize(IFD_TYPE_PRIMARY, IFD_TYPE_PREVIEW);
+ swapBasedOnImageSize(IFD_TYPE_PRIMARY, IFD_TYPE_THUMBNAIL);
+ swapBasedOnImageSize(IFD_TYPE_PREVIEW, IFD_TYPE_THUMBNAIL);
+
+ // TODO (b/142296453): Revise image width/height setting logic
+ // Check if image has PixelXDimension/PixelYDimension tags, which contain valid image
+ // sizes, excluding padding at the right end or bottom end of the image to make sure that
+ // the values are multiples of 64. See JEITA CP-3451C Table 5 and Section 4.8.1. B.
+ ExifAttribute pixelXDimAttribute =
+ mAttributes[IFD_TYPE_EXIF].get(TAG_PIXEL_X_DIMENSION);
+ ExifAttribute pixelYDimAttribute =
+ mAttributes[IFD_TYPE_EXIF].get(TAG_PIXEL_Y_DIMENSION);
+ if (pixelXDimAttribute != null && pixelYDimAttribute != null) {
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_WIDTH, pixelXDimAttribute);
+ mAttributes[IFD_TYPE_PRIMARY].put(TAG_IMAGE_LENGTH, pixelYDimAttribute);
+ }
+
+ // Check whether thumbnail image exists and whether preview image satisfies the thumbnail
+ // image requirements
+ if (mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) {
+ if (isThumbnail(mAttributes[IFD_TYPE_PREVIEW])) {
+ mAttributes[IFD_TYPE_THUMBNAIL] = mAttributes[IFD_TYPE_PREVIEW];
+ mAttributes[IFD_TYPE_PREVIEW] = new HashMap<>();
+ }
+ }
+
+ // Check if the thumbnail image satisfies the thumbnail size requirements
+ if (!isThumbnail(mAttributes[IFD_TYPE_THUMBNAIL])) {
+ Log.d(TAG, "No image meets the size requirements of a thumbnail image.");
+ }
+
+ // TAG_THUMBNAIL_* tags should be replaced with TAG_* equivalents and vice versa if needed.
+ replaceInvalidTags(IFD_TYPE_PRIMARY, TAG_THUMBNAIL_ORIENTATION, TAG_ORIENTATION);
+ replaceInvalidTags(IFD_TYPE_PRIMARY, TAG_THUMBNAIL_IMAGE_LENGTH, TAG_IMAGE_LENGTH);
+ replaceInvalidTags(IFD_TYPE_PRIMARY, TAG_THUMBNAIL_IMAGE_WIDTH, TAG_IMAGE_WIDTH);
+ replaceInvalidTags(IFD_TYPE_PREVIEW, TAG_THUMBNAIL_ORIENTATION, TAG_ORIENTATION);
+ replaceInvalidTags(IFD_TYPE_PREVIEW, TAG_THUMBNAIL_IMAGE_LENGTH, TAG_IMAGE_LENGTH);
+ replaceInvalidTags(IFD_TYPE_PREVIEW, TAG_THUMBNAIL_IMAGE_WIDTH, TAG_IMAGE_WIDTH);
+ replaceInvalidTags(IFD_TYPE_THUMBNAIL, TAG_ORIENTATION, TAG_THUMBNAIL_ORIENTATION);
+ replaceInvalidTags(IFD_TYPE_THUMBNAIL, TAG_IMAGE_LENGTH, TAG_THUMBNAIL_IMAGE_LENGTH);
+ replaceInvalidTags(IFD_TYPE_THUMBNAIL, TAG_IMAGE_WIDTH, TAG_THUMBNAIL_IMAGE_WIDTH);
+ }
+
+ /**
+ * If image is uncompressed, ImageWidth/Length tags are used to store size info.
+ * However, uncompressed images often store extra pixels around the edges of the final image,
+ * which results in larger values for TAG_IMAGE_WIDTH and TAG_IMAGE_LENGTH tags.
+ * This method corrects those tag values by checking first the values of TAG_DEFAULT_CROP_SIZE
+ * See DNG Specification 1.4.0.0. Section 4. (DefaultCropSize)
+ * <p>
+ * If image is a RW2 file, valid image sizes are stored in SensorBorder tags.
+ * See tiff_parser.cc GetFullDimension32()
+ */
+ private void updateImageSizeValues(SeekableByteOrderedDataInputStream in, int imageType)
+ throws IOException {
+ // Uncompressed image valid image size values
+ ExifAttribute defaultCropSizeAttribute =
+ mAttributes[imageType].get(TAG_DEFAULT_CROP_SIZE);
+ // RW2 image valid image size values
+ ExifAttribute topBorderAttribute =
+ mAttributes[imageType].get(TAG_RW2_SENSOR_TOP_BORDER);
+ ExifAttribute leftBorderAttribute =
+ mAttributes[imageType].get(TAG_RW2_SENSOR_LEFT_BORDER);
+ ExifAttribute bottomBorderAttribute =
+ mAttributes[imageType].get(TAG_RW2_SENSOR_BOTTOM_BORDER);
+ ExifAttribute rightBorderAttribute =
+ mAttributes[imageType].get(TAG_RW2_SENSOR_RIGHT_BORDER);
+
+ if (defaultCropSizeAttribute != null) {
+ // Update for uncompressed image
+ ExifAttribute defaultCropSizeXAttribute, defaultCropSizeYAttribute;
+ if (defaultCropSizeAttribute.format == IFD_FORMAT_URATIONAL) {
+ Rational[] defaultCropSizeValue =
+ (Rational[]) defaultCropSizeAttribute.getValue(mExifByteOrder);
+ if (defaultCropSizeValue == null || defaultCropSizeValue.length != 2) {
+ Log.w(TAG, "Invalid crop size values. cropSize="
+ + Arrays.toString(defaultCropSizeValue));
+ return;
+ }
+ defaultCropSizeXAttribute =
+ ExifAttribute.createURational(defaultCropSizeValue[0], mExifByteOrder);
+ defaultCropSizeYAttribute =
+ ExifAttribute.createURational(defaultCropSizeValue[1], mExifByteOrder);
+ } else {
+ int[] defaultCropSizeValue =
+ (int[]) defaultCropSizeAttribute.getValue(mExifByteOrder);
+ if (defaultCropSizeValue == null || defaultCropSizeValue.length != 2) {
+ Log.w(TAG, "Invalid crop size values. cropSize="
+ + Arrays.toString(defaultCropSizeValue));
+ return;
+ }
+ defaultCropSizeXAttribute =
+ ExifAttribute.createUShort(defaultCropSizeValue[0], mExifByteOrder);
+ defaultCropSizeYAttribute =
+ ExifAttribute.createUShort(defaultCropSizeValue[1], mExifByteOrder);
+ }
+ mAttributes[imageType].put(TAG_IMAGE_WIDTH, defaultCropSizeXAttribute);
+ mAttributes[imageType].put(TAG_IMAGE_LENGTH, defaultCropSizeYAttribute);
+ } else if (topBorderAttribute != null && leftBorderAttribute != null &&
+ bottomBorderAttribute != null && rightBorderAttribute != null) {
+ // Update for RW2 image
+ int topBorderValue = topBorderAttribute.getIntValue(mExifByteOrder);
+ int bottomBorderValue = bottomBorderAttribute.getIntValue(mExifByteOrder);
+ int rightBorderValue = rightBorderAttribute.getIntValue(mExifByteOrder);
+ int leftBorderValue = leftBorderAttribute.getIntValue(mExifByteOrder);
+ if (bottomBorderValue > topBorderValue && rightBorderValue > leftBorderValue) {
+ int length = bottomBorderValue - topBorderValue;
+ int width = rightBorderValue - leftBorderValue;
+ ExifAttribute imageLengthAttribute =
+ ExifAttribute.createUShort(length, mExifByteOrder);
+ ExifAttribute imageWidthAttribute =
+ ExifAttribute.createUShort(width, mExifByteOrder);
+ mAttributes[imageType].put(TAG_IMAGE_LENGTH, imageLengthAttribute);
+ mAttributes[imageType].put(TAG_IMAGE_WIDTH, imageWidthAttribute);
+ }
+ } else {
+ retrieveJpegImageSize(in, imageType);
+ }
+ }
+
+ /**
+ * Writes an Exif segment into the given output stream.
+ *
+ * @return The offset of the start of the Exif data (the byte-order marker) written into {@code
+ * dataOutputStream}.
+ */
+ private int writeExifSegment(ByteOrderedDataOutputStream dataOutputStream) throws IOException {
+ // The following variables are for calculating each IFD tag group size in bytes.
+ int[] ifdOffsets = new int[EXIF_TAGS.length];
+ int[] ifdDataSizes = new int[EXIF_TAGS.length];
+
+ // Remove IFD pointer tags (we'll re-add it later.)
+ for (ExifTag tag : EXIF_POINTER_TAGS) {
+ removeAttribute(tag.name);
+ }
+ // Remove old thumbnail data
+ if (mHasThumbnail) {
+ if (mHasThumbnailStrips) {
+ removeAttribute(TAG_STRIP_OFFSETS);
+ removeAttribute(TAG_STRIP_BYTE_COUNTS);
+ } else {
+ removeAttribute(TAG_JPEG_INTERCHANGE_FORMAT);
+ removeAttribute(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH);
+ }
+ }
+
+ // Remove null value tags.
+ for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) {
+ Iterator<Map.Entry<String, ExifAttribute>> entrySetIterator =
+ mAttributes[ifdType].entrySet().iterator();
+ while (entrySetIterator.hasNext()) {
+ Map.Entry<String, ExifAttribute> entry = entrySetIterator.next();
+ if (entry.getValue() == null) {
+ entrySetIterator.remove();
+ }
+ }
+ }
+
+ // Add IFD pointer tags. The next offset of primary image TIFF IFD will have thumbnail IFD
+ // offset when there is one or more tags in the thumbnail IFD.
+ if (!mAttributes[IFD_TYPE_EXIF].isEmpty()) {
+ mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[1].name,
+ ExifAttribute.createULong(0, mExifByteOrder));
+ }
+ if (!mAttributes[IFD_TYPE_GPS].isEmpty()) {
+ mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[2].name,
+ ExifAttribute.createULong(0, mExifByteOrder));
+ }
+ if (!mAttributes[IFD_TYPE_INTEROPERABILITY].isEmpty()) {
+ mAttributes[IFD_TYPE_EXIF].put(EXIF_POINTER_TAGS[3].name,
+ ExifAttribute.createULong(0, mExifByteOrder));
+ }
+ if (mHasThumbnail) {
+ if (mHasThumbnailStrips) {
+ mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_STRIP_OFFSETS,
+ ExifAttribute.createUShort(0, mExifByteOrder));
+ mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_STRIP_BYTE_COUNTS,
+ ExifAttribute.createUShort(mThumbnailLength, mExifByteOrder));
+ } else {
+ mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT,
+ ExifAttribute.createULong(0, mExifByteOrder));
+ mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT_LENGTH,
+ ExifAttribute.createULong(mThumbnailLength, mExifByteOrder));
+ }
+ }
+
+ // Calculate IFD group data area sizes. IFD group data area is assigned to save the entry
+ // value which has a bigger size than 4 bytes.
+ for (int i = 0; i < EXIF_TAGS.length; ++i) {
+ int sum = 0;
+ for (Map.Entry<String, ExifAttribute> entry : mAttributes[i].entrySet()) {
+ final ExifAttribute exifAttribute = entry.getValue();
+ final int size = exifAttribute.size();
+ if (size > 4) {
+ sum += size;
+ }
+ }
+ ifdDataSizes[i] += sum;
+ }
+
+ // Calculate IFD offsets.
+ // 8 bytes are for TIFF headers: 2 bytes (byte order) + 2 bytes (identifier) + 4 bytes
+ // (offset of IFDs)
+ int position = 8;
+ for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) {
+ if (!mAttributes[ifdType].isEmpty()) {
+ ifdOffsets[ifdType] = position;
+ position += 2 + mAttributes[ifdType].size() * 12 + 4 + ifdDataSizes[ifdType];
+ }
+ }
+ if (mHasThumbnail) {
+ int thumbnailOffset = position;
+ if (mHasThumbnailStrips) {
+ mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_STRIP_OFFSETS,
+ ExifAttribute.createUShort(thumbnailOffset, mExifByteOrder));
+ } else {
+ mAttributes[IFD_TYPE_THUMBNAIL].put(TAG_JPEG_INTERCHANGE_FORMAT,
+ ExifAttribute.createULong(thumbnailOffset, mExifByteOrder));
+ }
+ mThumbnailOffset = thumbnailOffset;
+ position += mThumbnailLength;
+ }
+
+ int totalSize = position;
+ if (mMimeType == IMAGE_TYPE_JPEG) {
+ // Add 8 bytes for APP1 size and identifier data
+ totalSize += 8;
+ }
+ if (DEBUG) {
+ for (int i = 0; i < EXIF_TAGS.length; ++i) {
+ Log.d(TAG, String.format("index: %d, offsets: %d, tag count: %d, data sizes: %d, "
+ + "total size: %d", i, ifdOffsets[i], mAttributes[i].size(),
+ ifdDataSizes[i], totalSize));
+ }
+ }
+
+ // Update IFD pointer tags with the calculated offsets.
+ if (!mAttributes[IFD_TYPE_EXIF].isEmpty()) {
+ mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[1].name,
+ ExifAttribute.createULong(ifdOffsets[IFD_TYPE_EXIF], mExifByteOrder));
+ }
+ if (!mAttributes[IFD_TYPE_GPS].isEmpty()) {
+ mAttributes[IFD_TYPE_PRIMARY].put(EXIF_POINTER_TAGS[2].name,
+ ExifAttribute.createULong(ifdOffsets[IFD_TYPE_GPS], mExifByteOrder));
+ }
+ if (!mAttributes[IFD_TYPE_INTEROPERABILITY].isEmpty()) {
+ mAttributes[IFD_TYPE_EXIF].put(EXIF_POINTER_TAGS[3].name, ExifAttribute.createULong(
+ ifdOffsets[IFD_TYPE_INTEROPERABILITY], mExifByteOrder));
+ }
+
+ switch (mMimeType) {
+ case IMAGE_TYPE_JPEG:
+ if (totalSize > 0xFFFF) {
+ throw new IllegalStateException(
+ "Size of exif data (" + totalSize + " bytes) exceeds the max size of a "
+ + "JPEG APP1 segment (65536 bytes)");
+ }
+ // Write JPEG specific data (APP1 size, APP1 identifier)
+ dataOutputStream.writeUnsignedShort(totalSize);
+ dataOutputStream.write(IDENTIFIER_EXIF_APP1);
+ break;
+ case IMAGE_TYPE_PNG:
+ // Write PNG specific data (chunk size, chunk type)
+ dataOutputStream.writeInt(totalSize);
+ dataOutputStream.writeInt(PNG_CHUNK_TYPE_EXIF);
+ break;
+ case IMAGE_TYPE_WEBP:
+ // Write WebP specific data (chunk type, chunk size)
+ dataOutputStream.write(WEBP_CHUNK_TYPE_EXIF);
+ dataOutputStream.writeInt(totalSize);
+ break;
+ }
+
+ int offsetToExifData = dataOutputStream.mOutputStream.size();
+
+ // Write TIFF Headers. See JEITA CP-3451C Section 4.5.2. Table 1.
+ dataOutputStream.writeShort(mExifByteOrder == BIG_ENDIAN ? BYTE_ALIGN_MM : BYTE_ALIGN_II);
+ dataOutputStream.setByteOrder(mExifByteOrder);
+ dataOutputStream.writeUnsignedShort(START_CODE);
+ dataOutputStream.writeUnsignedInt(IFD_OFFSET);
+
+ // Write IFD groups. See JEITA CP-3451C Section 4.5.8. Figure 9.
+ for (int ifdType = 0; ifdType < EXIF_TAGS.length; ++ifdType) {
+ if (!mAttributes[ifdType].isEmpty()) {
+ // See JEITA CP-3451C Section 4.6.2: IFD structure.
+ // Write entry count
+ dataOutputStream.writeUnsignedShort(mAttributes[ifdType].size());
+
+ // Write entry info
+ int dataOffset = ifdOffsets[ifdType] + 2 + mAttributes[ifdType].size() * 12 + 4;
+ for (Map.Entry<String, ExifAttribute> entry : mAttributes[ifdType].entrySet()) {
+ // Convert tag name to tag number.
+ final ExifTag tag = sExifTagMapsForWriting[ifdType].get(entry.getKey());
+ final int tagNumber = tag.number;
+ final ExifAttribute attribute = entry.getValue();
+ final int size = attribute.size();
+
+ dataOutputStream.writeUnsignedShort(tagNumber);
+ dataOutputStream.writeUnsignedShort(attribute.format);
+ dataOutputStream.writeInt(attribute.numberOfComponents);
+ if (size > 4) {
+ dataOutputStream.writeUnsignedInt(dataOffset);
+ dataOffset += size;
+ } else {
+ dataOutputStream.write(attribute.bytes);
+ // Fill zero up to 4 bytes
+ if (size < 4) {
+ for (int i = size; i < 4; ++i) {
+ dataOutputStream.writeByte(0);
+ }
+ }
+ }
+ }
+
+ // Write the next offset. It writes the offset of thumbnail IFD if there is one or
+ // more tags in the thumbnail IFD when the current IFD is the primary image TIFF
+ // IFD; Otherwise 0.
+ if (ifdType == 0 && !mAttributes[IFD_TYPE_THUMBNAIL].isEmpty()) {
+ dataOutputStream.writeUnsignedInt(ifdOffsets[IFD_TYPE_THUMBNAIL]);
+ } else {
+ dataOutputStream.writeUnsignedInt(0);
+ }
+
+ // Write values of data field exceeding 4 bytes after the next offset.
+ for (Map.Entry<String, ExifAttribute> entry : mAttributes[ifdType].entrySet()) {
+ ExifAttribute attribute = entry.getValue();
+
+ if (attribute.bytes.length > 4) {
+ dataOutputStream.write(attribute.bytes, 0, attribute.bytes.length);
+ }
+ }
+ }
+ }
+
+ // Write thumbnail
+ if (mHasThumbnail) {
+ dataOutputStream.write(getThumbnailBytes());
+ }
+
+ // For WebP files, add a single padding byte at end if chunk size is odd
+ if (mMimeType == IMAGE_TYPE_WEBP && totalSize % 2 == 1) {
+ dataOutputStream.writeByte(0);
+ }
+
+ // Reset the byte order to big endian in order to write remaining parts of the JPEG file.
+ dataOutputStream.setByteOrder(BIG_ENDIAN);
+
+ return offsetToExifData;
+ }
+
+ /**
+ * Determines the data format of EXIF entry value.
+ *
+ * @param entryValue The value to be determined.
+ * @return Returns two data formats guessed as a pair in integer. If there is no two candidate
+ * data formats for the given entry value, returns {@code -1} in the second of the pair.
+ */
+ private static Pair<Integer, Integer> guessDataFormat(String entryValue) {
+ // See TIFF 6.0 Section 2, "Image File Directory".
+ // Take the first component if there are more than one component.
+ if (entryValue.contains(",")) {
+ String[] entryValues = entryValue.split(",", -1);
+ Pair<Integer, Integer> dataFormat = guessDataFormat(entryValues[0]);
+ if (dataFormat.first == IFD_FORMAT_STRING) {
+ return dataFormat;
+ }
+ for (int i = 1; i < entryValues.length; ++i) {
+ final Pair<Integer, Integer> guessDataFormat = guessDataFormat(entryValues[i]);
+ int first = -1, second = -1;
+ if (guessDataFormat.first.equals(dataFormat.first)
+ || guessDataFormat.second.equals(dataFormat.first)) {
+ first = dataFormat.first;
+ }
+ if (dataFormat.second != -1 && (guessDataFormat.first.equals(dataFormat.second)
+ || guessDataFormat.second.equals(dataFormat.second))) {
+ second = dataFormat.second;
+ }
+ if (first == -1 && second == -1) {
+ return new Pair<>(IFD_FORMAT_STRING, -1);
+ }
+ if (first == -1) {
+ dataFormat = new Pair<>(second, -1);
+ continue;
+ }
+ if (second == -1) {
+ dataFormat = new Pair<>(first, -1);
+ continue;
+ }
+ }
+ return dataFormat;
+ }
+
+ if (entryValue.contains("/")) {
+ String[] rationalNumber = entryValue.split("/", -1);
+ if (rationalNumber.length == 2) {
+ try {
+ long numerator = (long) Double.parseDouble(rationalNumber[0]);
+ long denominator = (long) Double.parseDouble(rationalNumber[1]);
+ if (numerator < 0L || denominator < 0L) {
+ return new Pair<>(IFD_FORMAT_SRATIONAL, -1);
+ }
+ if (numerator > Integer.MAX_VALUE || denominator > Integer.MAX_VALUE) {
+ return new Pair<>(IFD_FORMAT_URATIONAL, -1);
+ }
+ return new Pair<>(IFD_FORMAT_SRATIONAL, IFD_FORMAT_URATIONAL);
+ } catch (NumberFormatException e) {
+ // Ignored
+ }
+ }
+ return new Pair<>(IFD_FORMAT_STRING, -1);
+ }
+ try {
+ Long longValue = Long.parseLong(entryValue);
+ if (longValue >= 0 && longValue <= 65535) {
+ return new Pair<>(IFD_FORMAT_USHORT, IFD_FORMAT_ULONG);
+ }
+ if (longValue < 0) {
+ return new Pair<>(IFD_FORMAT_SLONG, -1);
+ }
+ return new Pair<>(IFD_FORMAT_ULONG, -1);
+ } catch (NumberFormatException e) {
+ // Ignored
+ }
+ try {
+ Double.parseDouble(entryValue);
+ return new Pair<>(IFD_FORMAT_DOUBLE, -1);
+ } catch (NumberFormatException e) {
+ // Ignored
+ }
+ return new Pair<>(IFD_FORMAT_STRING, -1);
+ }
+
+ // An input stream class that can parse both little and big endian order data and also
+ // supports seeking to any position in the stream via mark/reset.
+ private static class SeekableByteOrderedDataInputStream extends ByteOrderedDataInputStream {
+ SeekableByteOrderedDataInputStream(byte[] bytes) throws IOException {
+ super(bytes);
+ // No need to check if mark is supported here since ByteOrderedDataInputStream will
+ // create a ByteArrayInputStream, which supports mark by default.
+ mDataInputStream.mark(Integer.MAX_VALUE);
+ }
+
+ /**
+ * Given input stream should support mark/reset, and should be set to the beginning of
+ * the stream.
+ */
+ SeekableByteOrderedDataInputStream(InputStream in) throws IOException {
+ super(in);
+ if (!in.markSupported()) {
+ throw new IllegalArgumentException("Cannot create "
+ + "SeekableByteOrderedDataInputStream with stream that does not support "
+ + "mark/reset");
+ }
+ // Mark given InputStream to the maximum value (we can't know the length of the
+ // stream for certain) so that InputStream.reset() may be called at any point in the
+ // stream to reset the stream to an earlier position.
+ mDataInputStream.mark(Integer.MAX_VALUE);
+ }
+
+ /**
+ * Seek to the given absolute position in the stream (i.e. the number of bytes from the
+ * beginning of the stream).
+ */
+ public void seek(long position) throws IOException {
+ if (mPosition > position) {
+ mPosition = 0;
+ mDataInputStream.reset();
+ } else {
+ position -= mPosition;
+ }
+ skipFully((int) position);
+ }
+ }
+
+ // An input stream class that can parse both little and big endian order data.
+ private static class ByteOrderedDataInputStream extends InputStream implements DataInput {
+
+ public static final int LENGTH_UNSET = -1;
+ protected final DataInputStream mDataInputStream;
+ protected int mPosition;
+
+ private ByteOrder mByteOrder;
+ private byte[] mSkipBuffer;
+ private int mLength;
+
+ ByteOrderedDataInputStream(byte[] bytes) throws IOException {
+ this(new ByteArrayInputStream(bytes), BIG_ENDIAN);
+ this.mLength = bytes.length;
+ }
+
+ ByteOrderedDataInputStream(InputStream in) throws IOException {
+ this(in, BIG_ENDIAN);
+ }
+
+ ByteOrderedDataInputStream(InputStream in, ByteOrder byteOrder) {
+ mDataInputStream = new DataInputStream(in);
+ mDataInputStream.mark(0);
+ mPosition = 0;
+ mByteOrder = byteOrder;
+ this.mLength = in instanceof ByteOrderedDataInputStream
+ ? ((ByteOrderedDataInputStream) in).length()
+ : LENGTH_UNSET;
+ }
+
+ public void setByteOrder(ByteOrder byteOrder) {
+ mByteOrder = byteOrder;
+ }
+
+ public int position() {
+ return mPosition;
+ }
+
+ /**
+ * Reads all remaining data.
+ */
+ public byte[] readToEnd() throws IOException {
+ byte[] data = new byte[1024];
+ int bytesRead = 0;
+ while (true) {
+ if (bytesRead == data.length) {
+ data = Arrays.copyOf(data, data.length * 2);
+ }
+ int readResult = mDataInputStream.read(data, bytesRead, data.length - bytesRead);
+ if (readResult != -1) {
+ bytesRead += readResult;
+ mPosition += readResult;
+ } else {
+ break;
+ }
+ }
+ return Arrays.copyOf(data, bytesRead);
+ }
+
+ @Override
+ public int available() throws IOException {
+ return mDataInputStream.available();
+ }
+
+ @Override
+ public int read() throws IOException {
+ ++mPosition;
+ return mDataInputStream.read();
+ }
+
+ @Override
+ public int read(byte[] b, int off, int len) throws IOException {
+ int bytesRead = mDataInputStream.read(b, off, len);
+ mPosition += bytesRead;
+ return bytesRead;
+ }
+
+ @Override
+ public int readUnsignedByte() throws IOException {
+ ++mPosition;
+ return mDataInputStream.readUnsignedByte();
+ }
+
+ @Override
+ public String readLine() throws IOException {
+ Log.d(TAG, "Currently unsupported");
+ return null;
+ }
+
+ @Override
+ public boolean readBoolean() throws IOException {
+ ++mPosition;
+ return mDataInputStream.readBoolean();
+ }
+
+ @Override
+ public char readChar() throws IOException {
+ mPosition += 2;
+ return mDataInputStream.readChar();
+ }
+
+ @Override
+ public String readUTF() throws IOException {
+ mPosition += 2;
+ return mDataInputStream.readUTF();
+ }
+
+ @Override
+ public void readFully(byte[] buffer, int offset, int length) throws IOException {
+ mPosition += length;
+ mDataInputStream.readFully(buffer, offset, length);
+ }
+
+ @Override
+ public void readFully(byte[] buffer) throws IOException {
+ mPosition += buffer.length;
+ mDataInputStream.readFully(buffer);
+ }
+
+ @Override
+ public byte readByte() throws IOException {
+ ++mPosition;
+ int ch = mDataInputStream.read();
+ if (ch < 0) {
+ throw new EOFException();
+ }
+ return (byte) ch;
+ }
+
+ @Override
+ public short readShort() throws IOException {
+ mPosition += 2;
+ int ch1 = mDataInputStream.read();
+ int ch2 = mDataInputStream.read();
+ if ((ch1 | ch2) < 0) {
+ throw new EOFException();
+ }
+ if (mByteOrder == LITTLE_ENDIAN) {
+ return (short) ((ch2 << 8) + ch1);
+ } else if (mByteOrder == BIG_ENDIAN) {
+ return (short) ((ch1 << 8) + ch2);
+ }
+ throw new IOException("Invalid byte order: " + mByteOrder);
+ }
+
+ @Override
+ public int readInt() throws IOException {
+ mPosition += 4;
+ int ch1 = mDataInputStream.read();
+ int ch2 = mDataInputStream.read();
+ int ch3 = mDataInputStream.read();
+ int ch4 = mDataInputStream.read();
+ if ((ch1 | ch2 | ch3 | ch4) < 0) {
+ throw new EOFException();
+ }
+ if (mByteOrder == LITTLE_ENDIAN) {
+ return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + ch1);
+ } else if (mByteOrder == BIG_ENDIAN) {
+ return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4);
+ }
+ throw new IOException("Invalid byte order: " + mByteOrder);
+ }
+
+ @Override
+ public int skipBytes(int n) throws IOException {
+ throw new UnsupportedOperationException("skipBytes is currently unsupported");
+ }
+
+ /**
+ * Discards n bytes of data from the input stream. This method will block until either
+ * the full amount has been skipped or the end of the stream is reached, whichever happens
+ * first.
+ */
+ public void skipFully(int n) throws IOException {
+ int totalSkipped = 0;
+ while (totalSkipped < n) {
+ int skipped = (int) mDataInputStream.skip(n - totalSkipped);
+ if (skipped <= 0) {
+ if (mSkipBuffer == null) {
+ mSkipBuffer = new byte[SKIP_BUFFER_SIZE];
+ }
+ int bytesToSkip = Math.min(SKIP_BUFFER_SIZE, n - totalSkipped);
+ if ((skipped = mDataInputStream.read(mSkipBuffer, 0, bytesToSkip)) == -1) {
+ throw new EOFException("Reached EOF while skipping " + n + " bytes.");
+ }
+ }
+ totalSkipped += skipped;
+ }
+ mPosition += totalSkipped;
+ }
+
+ @Override
+ public int readUnsignedShort() throws IOException {
+ mPosition += 2;
+ int ch1 = mDataInputStream.read();
+ int ch2 = mDataInputStream.read();
+ if ((ch1 | ch2) < 0) {
+ throw new EOFException();
+ }
+ if (mByteOrder == LITTLE_ENDIAN) {
+ return ((ch2 << 8) + ch1);
+ } else if (mByteOrder == BIG_ENDIAN) {
+ return ((ch1 << 8) + ch2);
+ }
+ throw new IOException("Invalid byte order: " + mByteOrder);
+ }
+
+ public long readUnsignedInt() throws IOException {
+ return readInt() & 0xffffffffL;
+ }
+
+ @Override
+ public long readLong() throws IOException {
+ mPosition += 8;
+ int ch1 = mDataInputStream.read();
+ int ch2 = mDataInputStream.read();
+ int ch3 = mDataInputStream.read();
+ int ch4 = mDataInputStream.read();
+ int ch5 = mDataInputStream.read();
+ int ch6 = mDataInputStream.read();
+ int ch7 = mDataInputStream.read();
+ int ch8 = mDataInputStream.read();
+ if ((ch1 | ch2 | ch3 | ch4 | ch5 | ch6 | ch7 | ch8) < 0) {
+ throw new EOFException();
+ }
+ if (mByteOrder == LITTLE_ENDIAN) {
+ return (((long) ch8 << 56) + ((long) ch7 << 48) + ((long) ch6 << 40)
+ + ((long) ch5 << 32) + ((long) ch4 << 24) + ((long) ch3 << 16)
+ + ((long) ch2 << 8) + (long) ch1);
+ } else if (mByteOrder == BIG_ENDIAN) {
+ return (((long) ch1 << 56) + ((long) ch2 << 48) + ((long) ch3 << 40)
+ + ((long) ch4 << 32) + ((long) ch5 << 24) + ((long) ch6 << 16)
+ + ((long) ch7 << 8) + (long) ch8);
+ }
+ throw new IOException("Invalid byte order: " + mByteOrder);
+ }
+
+ @Override
+ public float readFloat() throws IOException {
+ return Float.intBitsToFloat(readInt());
+ }
+
+ @Override
+ public double readDouble() throws IOException {
+ return Double.longBitsToDouble(readLong());
+ }
+
+ @Override
+ public void mark(int readlimit) {
+ throw new UnsupportedOperationException("Mark is currently unsupported");
+ }
+
+ @Override
+ public void reset() {
+ throw new UnsupportedOperationException("Reset is currently unsupported");
+ }
+
+ /**
+ * Return the total length (in bytes) of the underlying stream if known, otherwise
+ * {@link #LENGTH_UNSET}.
+ */
+ public int length() {
+ return mLength;
+ }
+ }
+
+ // An output stream to write EXIF data area, which can be written in either little or big endian
+ // order.
+ private static class ByteOrderedDataOutputStream extends FilterOutputStream {
+ final DataOutputStream mOutputStream;
+ private ByteOrder mByteOrder;
+
+ public ByteOrderedDataOutputStream(OutputStream out, ByteOrder byteOrder) {
+ super(out);
+ mOutputStream = new DataOutputStream(out);
+ mByteOrder = byteOrder;
+ }
+
+ public void setByteOrder(ByteOrder byteOrder) {
+ mByteOrder = byteOrder;
+ }
+
+ @Override
+ public void write(byte[] bytes) throws IOException {
+ mOutputStream.write(bytes);
+ }
+
+ @Override
+ public void write(byte[] bytes, int offset, int length) throws IOException {
+ mOutputStream.write(bytes, offset, length);
+ }
+
+ public void writeByte(int val) throws IOException {
+ mOutputStream.write(val);
+ }
+
+ public void writeShort(short val) throws IOException {
+ if (mByteOrder == LITTLE_ENDIAN) {
+ mOutputStream.write((val >>> 0) & 0xFF);
+ mOutputStream.write((val >>> 8) & 0xFF);
+ } else if (mByteOrder == BIG_ENDIAN) {
+ mOutputStream.write((val >>> 8) & 0xFF);
+ mOutputStream.write((val >>> 0) & 0xFF);
+ }
+ }
+
+ public void writeInt(int val) throws IOException {
+ if (mByteOrder == LITTLE_ENDIAN) {
+ mOutputStream.write((val >>> 0) & 0xFF);
+ mOutputStream.write((val >>> 8) & 0xFF);
+ mOutputStream.write((val >>> 16) & 0xFF);
+ mOutputStream.write((val >>> 24) & 0xFF);
+ } else if (mByteOrder == BIG_ENDIAN) {
+ mOutputStream.write((val >>> 24) & 0xFF);
+ mOutputStream.write((val >>> 16) & 0xFF);
+ mOutputStream.write((val >>> 8) & 0xFF);
+ mOutputStream.write((val >>> 0) & 0xFF);
+ }
+ }
+
+ public void writeUnsignedShort(int val) throws IOException {
+ if (val > 0xFFFF) {
+ throw new IllegalArgumentException("val is larger than the maximum value of a "
+ + "16-bit unsigned integer");
+ }
+ writeShort((short) val);
+ }
+
+ public void writeUnsignedInt(long val) throws IOException {
+ if (val > 0xFFFF_FFFFL) {
+ throw new IllegalArgumentException("val is larger than the maximum value of a "
+ + "32-bit unsigned integer");
+ }
+ writeInt((int) val);
+ }
+ }
+
+ // Swaps image data based on image size
+ private void swapBasedOnImageSize(@IfdType int firstIfdType, @IfdType int secondIfdType)
+ throws IOException {
+ if (mAttributes[firstIfdType].isEmpty() || mAttributes[secondIfdType].isEmpty()) {
+ if (DEBUG) {
+ Log.d(TAG, "Cannot perform swap since only one image data exists");
+ }
+ return;
+ }
+
+ ExifAttribute firstImageLengthAttribute =
+ mAttributes[firstIfdType].get(TAG_IMAGE_LENGTH);
+ ExifAttribute firstImageWidthAttribute =
+ mAttributes[firstIfdType].get(TAG_IMAGE_WIDTH);
+ ExifAttribute secondImageLengthAttribute =
+ mAttributes[secondIfdType].get(TAG_IMAGE_LENGTH);
+ ExifAttribute secondImageWidthAttribute =
+ mAttributes[secondIfdType].get(TAG_IMAGE_WIDTH);
+
+ if (firstImageLengthAttribute == null || firstImageWidthAttribute == null) {
+ if (DEBUG) {
+ Log.d(TAG, "First image does not contain valid size information");
+ }
+ } else if (secondImageLengthAttribute == null || secondImageWidthAttribute == null) {
+ if (DEBUG) {
+ Log.d(TAG, "Second image does not contain valid size information");
+ }
+ } else {
+ int firstImageLengthValue = firstImageLengthAttribute.getIntValue(mExifByteOrder);
+ int firstImageWidthValue = firstImageWidthAttribute.getIntValue(mExifByteOrder);
+ int secondImageLengthValue = secondImageLengthAttribute.getIntValue(mExifByteOrder);
+ int secondImageWidthValue = secondImageWidthAttribute.getIntValue(mExifByteOrder);
+
+ if (firstImageLengthValue < secondImageLengthValue &&
+ firstImageWidthValue < secondImageWidthValue) {
+ HashMap<String, ExifAttribute> tempMap = mAttributes[firstIfdType];
+ mAttributes[firstIfdType] = mAttributes[secondIfdType];
+ mAttributes[secondIfdType] = tempMap;
+ }
+ }
+ }
+
+ private void replaceInvalidTags(@IfdType int ifdType, String invalidTag, String validTag) {
+ if (!mAttributes[ifdType].isEmpty()) {
+ if (mAttributes[ifdType].get(invalidTag) != null) {
+ mAttributes[ifdType].put(validTag,
+ mAttributes[ifdType].get(invalidTag));
+ mAttributes[ifdType].remove(invalidTag);
+ }
+ }
+ }
+
+ /**
+ * Parsing EXIF data requires seek (moving to any position in the stream), so all MIME
+ * types should support seek via mark/reset, unless the MIME type specifies the position and
+ * length of the EXIF data and the EXIF data can be read from the file and wrapped with a
+ * ByteArrayInputStream.
+ */
+ private static boolean shouldSupportSeek(int mimeType) {
+ if (mimeType == IMAGE_TYPE_JPEG || mimeType == IMAGE_TYPE_RAF || mimeType == IMAGE_TYPE_PNG
+ || mimeType == IMAGE_TYPE_WEBP) {
+ return false;
+ }
+ return true;
+ }
+
+ private static boolean isSupportedFormatForSavingAttributes(int mimeType) {
+ if (mimeType == IMAGE_TYPE_JPEG || mimeType == IMAGE_TYPE_PNG
+ || mimeType == IMAGE_TYPE_WEBP) {
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/android/exifinterface/src/main/java/androidx/exifinterface/media/ExifInterfaceUtilsFork.java b/android/exifinterface/src/main/java/androidx/exifinterface/media/ExifInterfaceUtilsFork.java
new file mode 100644
index 0000000..266959a
--- /dev/null
+++ b/android/exifinterface/src/main/java/androidx/exifinterface/media/ExifInterfaceUtilsFork.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package androidx.exifinterface.media;
+
+import android.media.MediaDataSource;
+import android.media.MediaMetadataRetriever;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.util.Log;
+
+import androidx.annotation.RequiresApi;
+
+import java.io.Closeable;
+import java.io.FileDescriptor;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/*
+ * Forked from 'androidx.exifinterface:exifinterface:1.4.1'
+ * Named differently to let ExifInterface be loaded as subdependency.
+ * cf https://github.com/androidx/androidx/tree/androidx-main/exifinterface/exifinterface/src/main/java/androidx/exifinterface/media
+ */
+
+class ExifInterfaceUtilsFork {
+ private static final String TAG = "ExifInterfaceUtils";
+
+ private ExifInterfaceUtilsFork() {
+ // Prevent instantiation
+ }
+
+ /**
+ * Copies all of the bytes from {@code in} to {@code out}. Neither stream is closed.
+ * Returns the total number of bytes transferred.
+ */
+ static int copy(InputStream in, OutputStream out) throws IOException {
+ int total = 0;
+ byte[] buffer = new byte[8192];
+ int c;
+ while ((c = in.read(buffer)) != -1) {
+ total += c;
+ out.write(buffer, 0, c);
+ }
+ return total;
+ }
+
+ /**
+ * Copies the given number of the bytes from {@code in} to {@code out}. Neither stream is
+ * closed.
+ */
+ static void copy(InputStream in, OutputStream out, int numBytes) throws IOException {
+ int remainder = numBytes;
+ byte[] buffer = new byte[8192];
+ while (remainder > 0) {
+ int bytesToRead = Math.min(remainder, 8192);
+ int bytesRead = in.read(buffer, 0, bytesToRead);
+ if (bytesRead != bytesToRead) {
+ throw new IOException("Failed to copy the given amount of bytes from the input"
+ + "stream to the output stream.");
+ }
+ remainder -= bytesRead;
+ out.write(buffer, 0, bytesRead);
+ }
+ }
+
+ /**
+ * Convert given int[] to long[]. If long[] is given, just return it.
+ * Return null for other types of input.
+ */
+ static long[] convertToLongArray(Object inputObj) {
+ if (inputObj instanceof int[]) {
+ int[] input = (int[]) inputObj;
+ long[] result = new long[input.length];
+ for (int i = 0; i < input.length; i++) {
+ result[i] = input[i];
+ }
+ return result;
+ } else if (inputObj instanceof long[]) {
+ return (long[]) inputObj;
+ }
+ return null;
+ }
+
+ static boolean startsWith(byte[] cur, byte[] val) {
+ if (cur == null || val == null) {
+ return false;
+ }
+ if (cur.length < val.length) {
+ return false;
+ }
+ for (int i = 0; i < val.length; i++) {
+ if (cur[i] != val[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ static String byteArrayToHexString(byte[] bytes) {
+ StringBuilder sb = new StringBuilder(bytes.length * 2);
+ for (int i = 0; i < bytes.length; i++) {
+ sb.append(String.format("%02x", bytes[i]));
+ }
+ return sb.toString();
+ }
+
+ static long parseSubSeconds(String subSec) {
+ try {
+ final int len = Math.min(subSec.length(), 3);
+ long sub = Long.parseLong(subSec.substring(0, len));
+ for (int i = len; i < 3; i++) {
+ sub *= 10;
+ }
+ return sub;
+ } catch (NumberFormatException e) {
+ // Ignored
+ }
+ return 0L;
+ }
+
+
+ /**
+ * Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null.
+ */
+ static void closeQuietly(Closeable closeable) {
+ if (closeable != null) {
+ try {
+ closeable.close();
+ } catch (RuntimeException rethrown) {
+ throw rethrown;
+ } catch (Exception ignored) {
+ }
+ }
+ }
+
+ /**
+ * Closes a file descriptor that has been duplicated.
+ */
+ static void closeFileDescriptor(FileDescriptor fd) {
+ try {
+ Os.close(fd);
+ } catch (ErrnoException ex) {
+ Log.e(TAG, "Error closing fd.", ex);
+ }
+ }
+
+ @RequiresApi(23)
+ static class Api23Impl {
+ private Api23Impl() {
+ }
+
+ static void setDataSource(MediaMetadataRetriever retriever, MediaDataSource dataSource) {
+ retriever.setDataSource(dataSource);
+ }
+ }
+}
diff --git a/android/gradle.properties b/android/gradle.properties
new file mode 100644
index 0000000..970dcc0
--- /dev/null
+++ b/android/gradle.properties
@@ -0,0 +1,9 @@
+org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
+android.useAndroidX=true
+
+# Kotlin code style for this project: "official" or "obsolete":
+kotlin.code.style=official
+
+# full mode is too aggressive and removes essential code
+# of `metadata-extractor` even when adding `-keep class com.drew.**{ *; }`
+android.enableR8.fullMode=false
diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..e6045a9
--- /dev/null
+++ b/android/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip
diff --git a/android/key_template.properties b/android/key_template.properties
new file mode 100644
index 0000000..e335f59
--- /dev/null
+++ b/android/key_template.properties
@@ -0,0 +1,5 @@
+storeFile=<KEYSTORE_PATH>
+storePassword=<KEYSTORE_PASSWORD>
+keyAlias=<KEY_ALIAS>
+keyPassword=<KEY_PASSWORD>
+googleApiKey=<GOOGLE_API_KEY>
diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts
new file mode 100644
index 0000000..f193728
--- /dev/null
+++ b/android/settings.gradle.kts
@@ -0,0 +1,28 @@
+pluginManagement {
+ val flutterSdkPath = run {
+ val properties = java.util.Properties()
+ file("local.properties").inputStream().use { properties.load(it) }
+ val flutterSdkPath = properties.getProperty("flutter.sdk")
+ require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
+ flutterSdkPath
+ }
+
+ includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
+
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+plugins {
+ id("dev.flutter.flutter-plugin-loader") version "1.0.0"
+ id("com.android.application") version "8.11.0" apply false
+ id("org.jetbrains.kotlin.android") version "2.2.0" apply false
+ id("com.google.devtools.ksp") version "2.2.0-2.0.2" apply false
+ id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0"
+}
+
+include(":app")
+include(":exifinterface")