@@ -29,7 +29,7 @@ interface VideoMetadataExtractor : AutoCloseable {
29
29
30
30
@ContributesBinding(AppScope ::class )
31
31
class DefaultVideoMetadataExtractor @AssistedInject constructor(
32
- @ApplicationContext context : Context ,
32
+ @ApplicationContext private val context : Context ,
33
33
@Assisted private val uri : Uri ,
34
34
) : VideoMetadataExtractor {
35
35
@ContributesBinding(AppScope ::class )
@@ -38,15 +38,16 @@ class DefaultVideoMetadataExtractor @AssistedInject constructor(
38
38
override fun create (uri : Uri ): DefaultVideoMetadataExtractor
39
39
}
40
40
41
- private val mediaMetadataRetriever = MediaMetadataRetriever ()
42
-
43
- init {
44
- mediaMetadataRetriever.setDataSource(context, uri)
41
+ // Don't use `by lazy` so we can catch any exceptions thrown during initialization
42
+ private val mediaMetadataRetriever = lazy {
43
+ MediaMetadataRetriever ().apply {
44
+ setDataSource(context, uri)
45
+ }
45
46
}
46
47
47
48
override fun getSize (): Result <Size > = runCatchingExceptions {
48
- val width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever .METADATA_KEY_VIDEO_WIDTH )?.toInt()
49
- val height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever .METADATA_KEY_VIDEO_HEIGHT )?.toInt()
49
+ val width = mediaMetadataRetriever.value. extractMetadata(MediaMetadataRetriever .METADATA_KEY_VIDEO_WIDTH )?.toInt()
50
+ val height = mediaMetadataRetriever.value. extractMetadata(MediaMetadataRetriever .METADATA_KEY_VIDEO_HEIGHT )?.toInt()
50
51
51
52
@Suppress(" ComplexCondition" )
52
53
if (width != null && width > 0 && height != null && height > 0 ) {
@@ -57,12 +58,14 @@ class DefaultVideoMetadataExtractor @AssistedInject constructor(
57
58
}
58
59
59
60
override fun getDuration (): Result <Long > = runCatchingExceptions {
60
- mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever .METADATA_KEY_DURATION )?.toLong()
61
+ mediaMetadataRetriever.value. extractMetadata(MediaMetadataRetriever .METADATA_KEY_DURATION )?.toLong()
61
62
?.takeIf { it > 0L }
62
63
? : error(" Could not retrieve video duration from metadata" )
63
64
}
64
65
65
66
override fun close () {
66
- mediaMetadataRetriever.release()
67
+ if (mediaMetadataRetriever.isInitialized()) {
68
+ mediaMetadataRetriever.value.release()
69
+ }
67
70
}
68
71
}
0 commit comments