diff --git a/packages/stream_thumbnail/CHANGELOG.md b/packages/stream_thumbnail/CHANGELOG.md index 2e577303..b7df49ab 100644 --- a/packages/stream_thumbnail/CHANGELOG.md +++ b/packages/stream_thumbnail/CHANGELOG.md @@ -1,3 +1,24 @@ +## Upcoming + +### ✨ Features + +- Added `StreamThumbnailSource`, which says whether a video is a network URL, a local file or an Android content + URI. + +### 💥 BREAKING CHANGES + +- Removed the `video`, `videos` and `headers` parameters; `source` and `sources` are now required. Pass + `StreamThumbnailSource.network(url, headers: ...)`, `StreamThumbnailSource.file(path)` or + `StreamThumbnailSource.contentUri(uri)` instead. +- Only `http` and `https` URLs are fetched; any other scheme fails with an `UNSUPPORTED_SOURCE` `PlatformException`. +- On Windows, a file source must be an absolute path on a local drive. +- On Linux, videos are read only from single-file containers; playlists such as HLS and DASH are not supported. + +### 🐞 Fixed + +- On Android 10 and later, a local video with `maxWidth` or `maxHeight` left at `0` now produces a + thumbnail instead of failing. + ## 0.2.0 ### ✨ Features diff --git a/packages/stream_thumbnail/README.md b/packages/stream_thumbnail/README.md index 234d0d62..8bea8791 100644 --- a/packages/stream_thumbnail/README.md +++ b/packages/stream_thumbnail/README.md @@ -4,9 +4,9 @@ A Flutter plugin for creating a thumbnail image from a video. Give it a local file path or a video URL and it returns the thumbnail as bytes or as a saved image file. Works on Android, iOS, macOS, Windows, Linux, and web. -Windows requires the [Media Feature Pack](https://support.microsoft.com/en-us/topic/media-feature-pack-list-for-windows-n-editions-c1c6bfba-4bf7-4be6-ae13-8608318bf3d4) for decoding (present by default outside of "N"/"KN" Windows editions), and doesn't yet support `StreamThumbnailFormat.webp` or `headers` for authenticated remote videos. +Windows requires the [Media Feature Pack](https://support.microsoft.com/en-us/topic/media-feature-pack-list-for-windows-n-editions-c1c6bfba-4bf7-4be6-ae13-8608318bf3d4) for decoding (present by default outside of "N"/"KN" Windows editions), and doesn't yet support `StreamThumbnailFormat.webp` or headers for authenticated remote videos. File sources must be absolute paths on a local drive. -Linux requires FFmpeg and libwebp development packages on the build machine, e.g. on Debian/Ubuntu: `libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libwebp-dev`. +Linux requires FFmpeg and libwebp development packages on the build machine, e.g. on Debian/Ubuntu: `libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libwebp-dev`. Videos are read from single-file containers only, not playlists such as HLS or DASH. ## Installation @@ -23,13 +23,23 @@ dependencies: import 'package:stream_thumbnail/stream_thumbnail.dart'; ``` +### Sources + +Every method takes a `StreamThumbnailSource` that says where the video comes from: + +| Source | Use for | +| ------ | ------- | +| `StreamThumbnailSource.network(url, headers: ...)` | A video URL. Only `http` and `https` URLs are fetched. | +| `StreamThumbnailSource.file(path)` | A video stored on the device, such as one the user picked. On web, the object URL of the video. | +| `StreamThumbnailSource.contentUri(uri)` | A video an Android content provider serves. Android only. | + ### Bytes Get the thumbnail as in-memory bytes — ideal for `Image.memory`: ```dart final bytes = await StreamThumbnail.thumbnailData( - video: 'https://example.com/video.mp4', + source: StreamThumbnailSource.network(Uri.parse('https://example.com/video.mp4')), imageFormat: StreamThumbnailFormat.jpeg, maxWidth: 128, // 0 keeps the source resolution quality: 25, @@ -45,7 +55,7 @@ import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; final thumbnail = await StreamThumbnail.thumbnailFile( - video: '/path/to/video.mp4', + source: StreamThumbnailSource.file('/path/to/video.mp4'), imageFormat: StreamThumbnailFormat.png, maxHeight: 200, ); @@ -65,7 +75,10 @@ Generate thumbnails for several videos in one call: ```dart final thumbnails = await StreamThumbnail.thumbnailFiles( - videos: ['/path/to/a.mp4', '/path/to/b.mp4'], + sources: [ + StreamThumbnailSource.file('/path/to/a.mp4'), + StreamThumbnailSource.file('/path/to/b.mp4'), + ], ); ``` @@ -75,8 +88,7 @@ Every method accepts the same options: | Option | Description | | --------------- | ------------------------------------------------------------------------------- | -| `video`(s) | Path to a local video file or a video URL. | -| `headers` | HTTP headers sent when fetching a remote video. Not supported on Windows. | +| `source`(s) | The video to thumbnail; see [Sources](#sources). `network` sources carry the HTTP headers to send, which Windows ignores. | | `imageFormat` | `JPEG`, `PNG`, or `WEBP`. Defaults to `PNG`. WebP on iOS/macOS is backed by `libwebp`; not yet supported on Windows.| | `maxHeight` / `maxWidth` | Max size in pixels, or `0` to keep the source resolution. | | `timeMs` | Capture position in milliseconds. | diff --git a/packages/stream_thumbnail/android/src/main/kotlin/io/getstream/stream_thumbnail/Messages.g.kt b/packages/stream_thumbnail/android/src/main/kotlin/io/getstream/stream_thumbnail/Messages.g.kt index 2114c96d..6d70a3e1 100644 --- a/packages/stream_thumbnail/android/src/main/kotlin/io/getstream/stream_thumbnail/Messages.g.kt +++ b/packages/stream_thumbnail/android/src/main/kotlin/io/getstream/stream_thumbnail/Messages.g.kt @@ -205,6 +205,25 @@ enum class ThumbnailFormat(val raw: Int) { } } +/** + * Where [ThumbnailRequest.video] is read from, and so how it may be opened. + * + * `network` must only be fetched over http or https, `file` must only be + * opened as a local path, and `contentUri` only through an Android content + * resolver. + */ +enum class ThumbnailSourceKind(val raw: Int) { + NETWORK(0), + FILE(1), + CONTENT_URI(2); + + companion object { + fun ofRaw(raw: Int): ThumbnailSourceKind? { + return values().firstOrNull { it.raw == raw } + } + } +} + /** * A single thumbnail generation request sent to the native platform. * @@ -212,6 +231,7 @@ enum class ThumbnailFormat(val raw: Int) { */ data class ThumbnailRequest ( val video: String, + val sourceKind: ThumbnailSourceKind, val headers: Map? = null, val format: ThumbnailFormat, val maxHeight: Long, @@ -223,18 +243,20 @@ data class ThumbnailRequest ( companion object { fun fromList(pigeonVar_list: List): ThumbnailRequest { val video = pigeonVar_list[0] as String - val headers = pigeonVar_list[1] as Map? - val format = pigeonVar_list[2] as ThumbnailFormat - val maxHeight = pigeonVar_list[3] as Long - val maxWidth = pigeonVar_list[4] as Long - val timeMs = pigeonVar_list[5] as Long - val quality = pigeonVar_list[6] as Long - return ThumbnailRequest(video, headers, format, maxHeight, maxWidth, timeMs, quality) + val sourceKind = pigeonVar_list[1] as ThumbnailSourceKind + val headers = pigeonVar_list[2] as Map? + val format = pigeonVar_list[3] as ThumbnailFormat + val maxHeight = pigeonVar_list[4] as Long + val maxWidth = pigeonVar_list[5] as Long + val timeMs = pigeonVar_list[6] as Long + val quality = pigeonVar_list[7] as Long + return ThumbnailRequest(video, sourceKind, headers, format, maxHeight, maxWidth, timeMs, quality) } } fun toList(): List { return listOf( video, + sourceKind, headers, format, maxHeight, @@ -251,12 +273,13 @@ data class ThumbnailRequest ( return true } val other = other as ThumbnailRequest - return MessagesPigeonUtils.deepEquals(this.video, other.video) && MessagesPigeonUtils.deepEquals(this.headers, other.headers) && MessagesPigeonUtils.deepEquals(this.format, other.format) && MessagesPigeonUtils.deepEquals(this.maxHeight, other.maxHeight) && MessagesPigeonUtils.deepEquals(this.maxWidth, other.maxWidth) && MessagesPigeonUtils.deepEquals(this.timeMs, other.timeMs) && MessagesPigeonUtils.deepEquals(this.quality, other.quality) + return MessagesPigeonUtils.deepEquals(this.video, other.video) && MessagesPigeonUtils.deepEquals(this.sourceKind, other.sourceKind) && MessagesPigeonUtils.deepEquals(this.headers, other.headers) && MessagesPigeonUtils.deepEquals(this.format, other.format) && MessagesPigeonUtils.deepEquals(this.maxHeight, other.maxHeight) && MessagesPigeonUtils.deepEquals(this.maxWidth, other.maxWidth) && MessagesPigeonUtils.deepEquals(this.timeMs, other.timeMs) && MessagesPigeonUtils.deepEquals(this.quality, other.quality) } override fun hashCode(): Int { var result = javaClass.hashCode() result = 31 * result + MessagesPigeonUtils.deepHash(this.video) + result = 31 * result + MessagesPigeonUtils.deepHash(this.sourceKind) result = 31 * result + MessagesPigeonUtils.deepHash(this.headers) result = 31 * result + MessagesPigeonUtils.deepHash(this.format) result = 31 * result + MessagesPigeonUtils.deepHash(this.maxHeight) @@ -266,7 +289,7 @@ data class ThumbnailRequest ( return result } override fun toString(): String { - return "ThumbnailRequest(video=$video, headers=$headers, format=$format, maxHeight=$maxHeight, maxWidth=$maxWidth, timeMs=$timeMs, quality=$quality)" + return "ThumbnailRequest(video=$video, sourceKind=$sourceKind, headers=$headers, format=$format, maxHeight=$maxHeight, maxWidth=$maxWidth, timeMs=$timeMs, quality=$quality)" } } private open class MessagesPigeonCodec : StandardMessageCodec() { @@ -278,6 +301,11 @@ private open class MessagesPigeonCodec : StandardMessageCodec() { } } 130.toByte() -> { + return (readValue(buffer) as Long?)?.let { + ThumbnailSourceKind.ofRaw(it.toInt()) + } + } + 131.toByte() -> { return (readValue(buffer) as? List)?.let { ThumbnailRequest.fromList(it) } @@ -291,8 +319,12 @@ private open class MessagesPigeonCodec : StandardMessageCodec() { stream.write(129) writeValue(stream, value.raw.toLong()) } - is ThumbnailRequest -> { + is ThumbnailSourceKind -> { stream.write(130) + writeValue(stream, value.raw.toLong()) + } + is ThumbnailRequest -> { + stream.write(131) writeValue(stream, value.toList()) } else -> super.writeValue(stream, value) diff --git a/packages/stream_thumbnail/android/src/main/kotlin/io/getstream/stream_thumbnail/StreamThumbnailPlugin.kt b/packages/stream_thumbnail/android/src/main/kotlin/io/getstream/stream_thumbnail/StreamThumbnailPlugin.kt index 5a667593..2997d2e2 100644 --- a/packages/stream_thumbnail/android/src/main/kotlin/io/getstream/stream_thumbnail/StreamThumbnailPlugin.kt +++ b/packages/stream_thumbnail/android/src/main/kotlin/io/getstream/stream_thumbnail/StreamThumbnailPlugin.kt @@ -14,13 +14,15 @@ import android.util.Size import io.flutter.embedding.engine.plugins.FlutterPlugin import java.io.ByteArrayOutputStream import java.io.File -import java.io.FileDescriptor import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.util.UUID import java.util.concurrent.Executors +/** A video the request's source kind doesn't allow this plugin to open. */ +private class UnsupportedSourceException(message: String) : IllegalArgumentException(message) + /** StreamThumbnailPlugin */ class StreamThumbnailPlugin : FlutterPlugin, StreamThumbnailHostApi { private val TAG = "ThumbnailPlugin" @@ -58,6 +60,8 @@ class StreamThumbnailPlugin : FlutterPlugin, StreamThumbnailHostApi { executor.execute { val result = try { Result.success(block()) + } catch (e: UnsupportedSourceException) { + Result.failure(FlutterError("UNSUPPORTED_SOURCE", e.message, null)) } catch (e: Exception) { Result.failure(FlutterError("THUMBNAIL_ERROR", e.message, e.stackTraceToString())) } @@ -68,6 +72,7 @@ class StreamThumbnailPlugin : FlutterPlugin, StreamThumbnailHostApi { private fun buildThumbnailData(request: ThumbnailRequest): ByteArray { val bitmap = createVideoThumbnail( request.video, + request.sourceKind, request.headers ?: emptyMap(), request.maxHeight.toInt(), request.maxWidth.toInt(), @@ -109,13 +114,15 @@ class StreamThumbnailPlugin : FlutterPlugin, StreamThumbnailHostApi { * Create a video thumbnail for a video. May return null if the video is corrupt * or the format is not supported. * - * @param video the URI of video - * @param targetH the max height of the thumbnail - * @param targetW the max width of the thumbnail + * @param video the URL, path or content URI of the video + * @param sourceKind how [video] may be opened + * @param targetH the max height of the thumbnail + * @param targetW the max width of the thumbnail */ @Throws(IOException::class) - fun createVideoThumbnail( + private fun createVideoThumbnail( video: String, + sourceKind: ThumbnailSourceKind, headers: Map, targetH: Int, targetW: Int, @@ -125,26 +132,33 @@ class StreamThumbnailPlugin : FlutterPlugin, StreamThumbnailHostApi { var retriever: MediaMetadataRetriever? = null try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && video.startsWith("/") && timeMs == -1) { + val filePath = if (sourceKind == ThumbnailSourceKind.FILE) video.removePrefix("file://") else null + val fitsBothBounds = targetW > 0 && targetH > 0 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && filePath != null && timeMs == -1 && fitsBothBounds) { bitmap = - ThumbnailUtils.createVideoThumbnail(File(video), Size(targetW, targetH), null) + ThumbnailUtils.createVideoThumbnail(File(filePath), Size(targetW, targetH), null) } else { retriever = MediaMetadataRetriever() - if (video.startsWith("/")) { - setDataSource(video, retriever) - } else if (video.startsWith("file://")) { - setDataSource(video.substring(7), retriever) - } else if (video.startsWith("content://")) { - val contentResolver: ContentResolver = context!!.contentResolver - val assetFileDescriptor = - contentResolver.openAssetFileDescriptor(Uri.parse(video), "r") - if (assetFileDescriptor != null) { - val fileDescriptor: FileDescriptor = assetFileDescriptor.fileDescriptor - retriever.setDataSource(fileDescriptor) - assetFileDescriptor.close() + when (sourceKind) { + ThumbnailSourceKind.FILE -> setDataSource(filePath!!, retriever) + ThumbnailSourceKind.CONTENT_URI -> { + val uri = Uri.parse(video) + if (uri.scheme != ContentResolver.SCHEME_CONTENT) { + throw UnsupportedSourceException("A content video must be a content URI.") + } + val contentResolver: ContentResolver = context!!.contentResolver + val assetFileDescriptor = contentResolver.openAssetFileDescriptor(uri, "r") + ?: throw IOException("Failed to open the content URI.") + assetFileDescriptor.use { retriever.setDataSource(it.fileDescriptor) } + } + ThumbnailSourceKind.NETWORK -> { + val uri = Uri.parse(video) + val scheme = uri.scheme?.lowercase() + if ((scheme != "http" && scheme != "https") || uri.host.isNullOrEmpty()) { + throw UnsupportedSourceException("A network video must be an http or https URL.") + } + retriever.setDataSource(video, headers) } - } else { - retriever.setDataSource(video, headers) } if (targetH != 0 || targetW != 0) { diff --git a/packages/stream_thumbnail/example/android/gradle/wrapper/gradle-wrapper.properties b/packages/stream_thumbnail/example/android/gradle/wrapper/gradle-wrapper.properties index 2d428bfb..76d4386d 100644 --- a/packages/stream_thumbnail/example/android/gradle/wrapper/gradle-wrapper.properties +++ b/packages/stream_thumbnail/example/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-all.zip diff --git a/packages/stream_thumbnail/example/android/settings.gradle.kts b/packages/stream_thumbnail/example/android/settings.gradle.kts index c21f0c5b..989ac5e4 100644 --- a/packages/stream_thumbnail/example/android/settings.gradle.kts +++ b/packages/stream_thumbnail/example/android/settings.gradle.kts @@ -19,8 +19,8 @@ pluginManagement { plugins { id("dev.flutter.flutter-plugin-loader") version "1.0.0" - id("com.android.application") version "9.0.1" apply false - id("org.jetbrains.kotlin.android") version "2.3.20" apply false + id("com.android.application") version "9.3.1" apply false + id("org.jetbrains.kotlin.android") version "2.4.20" apply false } include(":app") diff --git a/packages/stream_thumbnail/example/integration_test/plugin_smoke_test.dart b/packages/stream_thumbnail/example/integration_test/plugin_smoke_test.dart index fe8d8d9f..afb9304b 100644 --- a/packages/stream_thumbnail/example/integration_test/plugin_smoke_test.dart +++ b/packages/stream_thumbnail/example/integration_test/plugin_smoke_test.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; +import 'package:stream_thumbnail/src/messages.g.dart'; import 'package:stream_thumbnail/stream_thumbnail.dart'; import 'package:stream_thumbnail_example/main.dart'; @@ -40,7 +41,7 @@ void main() { testWidgets('thumbnailData generates real jpeg bytes from a local video', (tester) async { final bytes = await StreamThumbnail.thumbnailData( - video: video, + source: StreamThumbnailSource.file(video), imageFormat: StreamThumbnailFormat.jpeg, maxWidth: 300, quality: 75, @@ -54,7 +55,7 @@ void main() { testWidgets('thumbnailData generates real png bytes from a local video', (tester) async { final bytes = await StreamThumbnail.thumbnailData( - video: video, + source: StreamThumbnailSource.file(video), maxWidth: 300, ); @@ -67,7 +68,7 @@ void main() { 'thumbnailData generates real webp bytes from a local video', (tester) async { final bytes = await StreamThumbnail.thumbnailData( - video: video, + source: StreamThumbnailSource.file(video), imageFormat: StreamThumbnailFormat.webp, maxWidth: 300, quality: 80, @@ -85,7 +86,7 @@ void main() { 'thumbnailData generates real jpeg bytes from a remote video', (tester) async { final bytes = await StreamThumbnail.thumbnailData( - video: _remoteVideo, + source: StreamThumbnailSource.network(Uri.parse(_remoteVideo)), imageFormat: StreamThumbnailFormat.jpeg, maxWidth: 300, quality: 75, @@ -100,7 +101,7 @@ void main() { ); testWidgets('thumbnailFile writes a png named after the video', (tester) async { - final thumbnail = await StreamThumbnail.thumbnailFile(video: video, maxWidth: 300); + final thumbnail = await StreamThumbnail.thumbnailFile(source: StreamThumbnailSource.file(video), maxWidth: 300); final written = File(thumbnail.path); expect(written.existsSync(), isTrue, reason: 'the reported path must be the file that was written'); @@ -110,8 +111,8 @@ void main() { }); testWidgets('thumbnailFile gives each call its own directory', (tester) async { - final first = await StreamThumbnail.thumbnailFile(video: video, maxWidth: 300); - final second = await StreamThumbnail.thumbnailFile(video: video, maxWidth: 300); + final first = await StreamThumbnail.thumbnailFile(source: StreamThumbnailSource.file(video), maxWidth: 300); + final second = await StreamThumbnail.thumbnailFile(source: StreamThumbnailSource.file(video), maxWidth: 300); // Same video, so the same file name — only the directory keeps them apart. expect(first.name, second.name); @@ -128,7 +129,7 @@ void main() { addTearDown(spaced.deleteSync); final thumbnail = await StreamThumbnail.thumbnailFile( - video: 'file://${Uri.encodeFull(spaced.path)}', + source: StreamThumbnailSource.file('file://${Uri.encodeFull(spaced.path)}'), maxWidth: 300, ); @@ -146,7 +147,10 @@ void main() { // The unencoded form callers usually build. Before iOS 17 / macOS 14 `URL(string:)` // rejects the space outright, so on those versions this is the raw-path fallback; // on newer ones URL parsing accepts it. Both must resolve to the same file. - final thumbnail = await StreamThumbnail.thumbnailFile(video: 'file://${spaced.path}', maxWidth: 300); + final thumbnail = await StreamThumbnail.thumbnailFile( + source: StreamThumbnailSource.file('file://${spaced.path}'), + maxWidth: 300, + ); expect(File(thumbnail.path).existsSync(), isTrue); }); @@ -160,7 +164,10 @@ void main() { await awkward.writeAsBytes(await File(video).readAsBytes(), flush: true); addTearDown(awkward.deleteSync); - final thumbnail = await StreamThumbnail.thumbnailFile(video: 'file://${awkward.path}', maxWidth: 300); + final thumbnail = await StreamThumbnail.thumbnailFile( + source: StreamThumbnailSource.file('file://${awkward.path}'), + maxWidth: 300, + ); expect(File(thumbnail.path).existsSync(), isTrue, reason: '$name must resolve to the real file'); expect(await File(thumbnail.path).length(), greaterThan(0)); @@ -178,7 +185,7 @@ void main() { addTearDown(awkward.deleteSync); final thumbnail = await StreamThumbnail.thumbnailFile( - video: 'file://localhost${awkward.path}', + source: StreamThumbnailSource.file('file://localhost${awkward.path}'), maxWidth: 300, ); @@ -188,7 +195,10 @@ void main() { ); testWidgets('thumbnailFiles returns one file per video', (tester) async { - final thumbnails = await StreamThumbnail.thumbnailFiles(videos: [video, video], maxWidth: 300); + final thumbnails = await StreamThumbnail.thumbnailFiles( + sources: [StreamThumbnailSource.file(video), StreamThumbnailSource.file(video)], + maxWidth: 300, + ); expect(thumbnails, hasLength(2)); expect(thumbnails.map((it) => it.path).toSet(), hasLength(2)); @@ -219,4 +229,73 @@ void main() { expect(pathLabel, showsPath ? findsOneWidget : findsNothing, reason: '"$button" path label'); } }); + + testWidgets('a file source given an https URL fails with UNSUPPORTED_SOURCE', (tester) async { + await expectLater( + StreamThumbnail.thumbnailData(source: StreamThumbnailSource.file(_remoteVideo)), + throwsA(isA().having((e) => e.code, 'code', 'UNSUPPORTED_SOURCE')), + ); + }); + + testWidgets( + 'a relative file path fails with UNSUPPORTED_SOURCE on Windows', + (tester) async { + await expectLater( + StreamThumbnail.thumbnailData(source: StreamThumbnailSource.file(r'videos\a.mp4')), + throwsA(isA().having((e) => e.code, 'code', 'UNSUPPORTED_SOURCE')), + ); + }, + skip: !Platform.isWindows, + ); + + testWidgets( + 'a file request naming a network share fails on Windows with UNSUPPORTED_SOURCE', + (tester) async { + await expectLater( + StreamThumbnailHostApi().thumbnailData( + ThumbnailRequest( + video: r'\\example.invalid\share\a.mp4', + sourceKind: ThumbnailSourceKind.file, + format: ThumbnailFormat.png, + maxHeight: 0, + maxWidth: 0, + timeMs: 0, + quality: 10, + ), + ), + throwsA(isA().having((e) => e.code, 'code', 'UNSUPPORTED_SOURCE')), + ); + }, + skip: !Platform.isWindows, + ); + + testWidgets( + 'a content URI is rejected outside Android', + (tester) async { + await expectLater( + StreamThumbnail.thumbnailData(source: StreamThumbnailSource.contentUri(Uri.parse('content://media/1'))), + throwsA(isA().having((e) => e.code, 'code', 'UNSUPPORTED_SOURCE')), + ); + }, + skip: Platform.isAndroid, + ); + + testWidgets('a network request that is not http or https fails on the platform with UNSUPPORTED_SOURCE', ( + tester, + ) async { + await expectLater( + StreamThumbnailHostApi().thumbnailData( + ThumbnailRequest( + video: 'file://$video', + sourceKind: ThumbnailSourceKind.network, + format: ThumbnailFormat.png, + maxHeight: 0, + maxWidth: 0, + timeMs: 0, + quality: 10, + ), + ), + throwsA(isA().having((e) => e.code, 'code', 'UNSUPPORTED_SOURCE')), + ); + }); } diff --git a/packages/stream_thumbnail/example/lib/main.dart b/packages/stream_thumbnail/example/lib/main.dart index 917a8c5e..f2dce3ec 100644 --- a/packages/stream_thumbnail/example/lib/main.dart +++ b/packages/stream_thumbnail/example/lib/main.dart @@ -40,9 +40,16 @@ class _ThumbnailPageState extends State { super.dispose(); } + StreamThumbnailSource get _source { + final input = _controller.text; + final url = Uri.tryParse(input); + if (url != null && (url.isScheme('http') || url.isScheme('https'))) return StreamThumbnailSource.network(url); + return StreamThumbnailSource.file(input); + } + Future _generateData() async { final bytes = await StreamThumbnail.thumbnailData( - video: _controller.text, + source: _source, imageFormat: StreamThumbnailFormat.jpeg, maxWidth: 300, quality: 75, @@ -53,7 +60,7 @@ class _ThumbnailPageState extends State { Future _generateFile() async { final file = await StreamThumbnail.thumbnailFile( - video: _controller.text, + source: _source, imageFormat: StreamThumbnailFormat.jpeg, maxWidth: 300, quality: 75, diff --git a/packages/stream_thumbnail/ios/stream_thumbnail/Sources/stream_thumbnail/Messages.g.swift b/packages/stream_thumbnail/ios/stream_thumbnail/Sources/stream_thumbnail/Messages.g.swift index 82492202..3b79892c 100644 --- a/packages/stream_thumbnail/ios/stream_thumbnail/Sources/stream_thumbnail/Messages.g.swift +++ b/packages/stream_thumbnail/ios/stream_thumbnail/Sources/stream_thumbnail/Messages.g.swift @@ -191,11 +191,23 @@ enum ThumbnailFormat: Int, CaseIterable { case webp = 2 } +/// Where [ThumbnailRequest.video] is read from, and so how it may be opened. +/// +/// `network` must only be fetched over http or https, `file` must only be +/// opened as a local path, and `contentUri` only through an Android content +/// resolver. +enum ThumbnailSourceKind: Int, CaseIterable { + case network = 0 + case file = 1 + case contentUri = 2 +} + /// A single thumbnail generation request sent to the native platform. /// /// Generated class from Pigeon that represents data sent in messages. struct ThumbnailRequest: Hashable, CustomStringConvertible { var video: String + var sourceKind: ThumbnailSourceKind var headers: [String: String]? = nil var format: ThumbnailFormat var maxHeight: Int64 @@ -207,15 +219,17 @@ struct ThumbnailRequest: Hashable, CustomStringConvertible { // swift-format-ignore: AlwaysUseLowerCamelCase static func fromList(_ pigeonVar_list: [Any?]) -> ThumbnailRequest? { let video = pigeonVar_list[0] as! String - let headers: [String: String]? = nilOrValue(pigeonVar_list[1]) - let format = pigeonVar_list[2] as! ThumbnailFormat - let maxHeight = pigeonVar_list[3] as! Int64 - let maxWidth = pigeonVar_list[4] as! Int64 - let timeMs = pigeonVar_list[5] as! Int64 - let quality = pigeonVar_list[6] as! Int64 + let sourceKind = pigeonVar_list[1] as! ThumbnailSourceKind + let headers: [String: String]? = nilOrValue(pigeonVar_list[2]) + let format = pigeonVar_list[3] as! ThumbnailFormat + let maxHeight = pigeonVar_list[4] as! Int64 + let maxWidth = pigeonVar_list[5] as! Int64 + let timeMs = pigeonVar_list[6] as! Int64 + let quality = pigeonVar_list[7] as! Int64 return ThumbnailRequest( video: video, + sourceKind: sourceKind, headers: headers, format: format, maxHeight: maxHeight, @@ -227,6 +241,7 @@ struct ThumbnailRequest: Hashable, CustomStringConvertible { func toList() -> [Any?] { return [ video, + sourceKind, headers, format, maxHeight, @@ -239,12 +254,13 @@ struct ThumbnailRequest: Hashable, CustomStringConvertible { if Swift.type(of: lhs) != Swift.type(of: rhs) { return false } - return MessagesPigeonInternal.deepEquals(lhs.video, rhs.video) && MessagesPigeonInternal.deepEquals(lhs.headers, rhs.headers) && MessagesPigeonInternal.deepEquals(lhs.format, rhs.format) && MessagesPigeonInternal.deepEquals(lhs.maxHeight, rhs.maxHeight) && MessagesPigeonInternal.deepEquals(lhs.maxWidth, rhs.maxWidth) && MessagesPigeonInternal.deepEquals(lhs.timeMs, rhs.timeMs) && MessagesPigeonInternal.deepEquals(lhs.quality, rhs.quality) + return MessagesPigeonInternal.deepEquals(lhs.video, rhs.video) && MessagesPigeonInternal.deepEquals(lhs.sourceKind, rhs.sourceKind) && MessagesPigeonInternal.deepEquals(lhs.headers, rhs.headers) && MessagesPigeonInternal.deepEquals(lhs.format, rhs.format) && MessagesPigeonInternal.deepEquals(lhs.maxHeight, rhs.maxHeight) && MessagesPigeonInternal.deepEquals(lhs.maxWidth, rhs.maxWidth) && MessagesPigeonInternal.deepEquals(lhs.timeMs, rhs.timeMs) && MessagesPigeonInternal.deepEquals(lhs.quality, rhs.quality) } func hash(into hasher: inout Hasher) { hasher.combine("ThumbnailRequest") MessagesPigeonInternal.deepHash(value: video, hasher: &hasher) + MessagesPigeonInternal.deepHash(value: sourceKind, hasher: &hasher) MessagesPigeonInternal.deepHash(value: headers, hasher: &hasher) MessagesPigeonInternal.deepHash(value: format, hasher: &hasher) MessagesPigeonInternal.deepHash(value: maxHeight, hasher: &hasher) @@ -254,7 +270,7 @@ struct ThumbnailRequest: Hashable, CustomStringConvertible { } public var description: String { - return "ThumbnailRequest(video: \(String(describing: video)), headers: \(String(describing: headers)), format: \(String(describing: format)), maxHeight: \(String(describing: maxHeight)), maxWidth: \(String(describing: maxWidth)), timeMs: \(String(describing: timeMs)), quality: \(String(describing: quality)))" + return "ThumbnailRequest(video: \(String(describing: video)), sourceKind: \(String(describing: sourceKind)), headers: \(String(describing: headers)), format: \(String(describing: format)), maxHeight: \(String(describing: maxHeight)), maxWidth: \(String(describing: maxWidth)), timeMs: \(String(describing: timeMs)), quality: \(String(describing: quality)))" } } @@ -268,6 +284,12 @@ private class MessagesPigeonCodecReader: FlutterStandardReader { } return nil case 130: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return ThumbnailSourceKind(rawValue: enumResultAsInt) + } + return nil + case 131: return ThumbnailRequest.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) @@ -280,8 +302,11 @@ private class MessagesPigeonCodecWriter: FlutterStandardWriter { if let value = value as? ThumbnailFormat { super.writeByte(129) super.writeValue(value.rawValue) - } else if let value = value as? ThumbnailRequest { + } else if let value = value as? ThumbnailSourceKind { super.writeByte(130) + super.writeValue(value.rawValue) + } else if let value = value as? ThumbnailRequest { + super.writeByte(131) super.writeValue(value.toList()) } else { super.writeValue(value) diff --git a/packages/stream_thumbnail/ios/stream_thumbnail/Sources/stream_thumbnail/StreamThumbnailPlugin.swift b/packages/stream_thumbnail/ios/stream_thumbnail/Sources/stream_thumbnail/StreamThumbnailPlugin.swift index a5b1a1ae..9b44037e 100644 --- a/packages/stream_thumbnail/ios/stream_thumbnail/Sources/stream_thumbnail/StreamThumbnailPlugin.swift +++ b/packages/stream_thumbnail/ios/stream_thumbnail/Sources/stream_thumbnail/StreamThumbnailPlugin.swift @@ -3,11 +3,12 @@ import Flutter import UIKit import libwebp -/// A generation failure that couldn't produce a frame/encode, or a failure -/// writing the encoded thumbnail to disk. +/// A generation failure that couldn't produce a frame/encode, a failure +/// writing the encoded thumbnail to disk, or a video this platform won't open. private enum ThumbnailError: Error { case generationFailed case writeFailed(NSError) + case unsupportedSource(String) } public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHostApi { @@ -48,6 +49,8 @@ public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHost case ThumbnailError.generationFailed: return PigeonError( code: "THUMBNAIL_ERROR", message: "Failed to generate a thumbnail for the video.", details: nil) + case ThumbnailError.unsupportedSource(let message): + return PigeonError(code: "UNSUPPORTED_SOURCE", message: message, details: nil) case ThumbnailError.writeFailed(let nsError): return PigeonError(code: "Error \(nsError.code)", message: nsError.domain, details: nsError.localizedDescription) default: @@ -55,7 +58,24 @@ public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHost } } - private static func videoURL(for video: String) throws -> URL { + private static func videoURL(for request: ThumbnailRequest) throws -> URL { + switch request.sourceKind { + case .network: + guard let url = URL(string: request.video), + let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", + let host = url.host, !host.isEmpty + else { + throw ThumbnailError.unsupportedSource("A network video must be an http or https URL.") + } + return url + case .file: + return fileURL(for: request.video) + case .contentUri: + throw ThumbnailError.unsupportedSource("Content URIs are only supported on Android.") + } + } + + private static func fileURL(for video: String) -> URL { if video.hasPrefix("file://") { // Parsed as a URL first, so percent-encoding is decoded: `file:///tmp/a%20b.mp4` // names `a b.mp4`, not a literal `a%20b.mp4`. The raw path is the fallback for @@ -79,12 +99,8 @@ public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHost var path = String(video.dropFirst(7)) if path.hasPrefix("localhost/") { path = String(path.dropFirst(9)) } return URL(fileURLWithPath: path) - } else if video.hasPrefix("/") { - return URL(fileURLWithPath: video) - } else if let url = URL(string: video) { - return url } - throw ThumbnailError.generationFailed + return URL(fileURLWithPath: video) } private static func writeThumbnailFile(request: ThumbnailRequest) throws -> String { @@ -96,7 +112,7 @@ public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHost .appendingPathComponent("stream_thumbnail", isDirectory: true) .appendingPathComponent(UUID().uuidString, isDirectory: true) - let stem = try videoURL(for: request.video).deletingPathExtension().lastPathComponent + let stem = try videoURL(for: request).deletingPathExtension().lastPathComponent let thumbnailURL = outputDir .appendingPathComponent(stem.isEmpty ? "thumbnail" : stem) .appendingPathExtension(fileExtension(for: request.format)) @@ -112,7 +128,7 @@ public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHost } private static func generateThumbnailData(request: ThumbnailRequest) throws -> Data { - let url = try videoURL(for: request.video) + let url = try videoURL(for: request) var options: [String: Any]? if let headers = request.headers, !headers.isEmpty { diff --git a/packages/stream_thumbnail/lib/src/messages.g.dart b/packages/stream_thumbnail/lib/src/messages.g.dart index 9713669a..ee7337aa 100644 --- a/packages/stream_thumbnail/lib/src/messages.g.dart +++ b/packages/stream_thumbnail/lib/src/messages.g.dart @@ -101,10 +101,22 @@ enum ThumbnailFormat { webp, } +/// Where [ThumbnailRequest.video] is read from, and so how it may be opened. +/// +/// `network` must only be fetched over http or https, `file` must only be +/// opened as a local path, and `contentUri` only through an Android content +/// resolver. +enum ThumbnailSourceKind { + network, + file, + contentUri, +} + /// A single thumbnail generation request sent to the native platform. class ThumbnailRequest { ThumbnailRequest({ required this.video, + required this.sourceKind, this.headers, required this.format, required this.maxHeight, @@ -115,6 +127,8 @@ class ThumbnailRequest { String video; + ThumbnailSourceKind sourceKind; + Map? headers; ThumbnailFormat format; @@ -130,6 +144,7 @@ class ThumbnailRequest { List _toList() { return [ video, + sourceKind, headers, format, maxHeight, @@ -147,12 +162,13 @@ class ThumbnailRequest { result as List; return ThumbnailRequest( video: result[0]! as String, - headers: (result[1] as Map?)?.cast(), - format: result[2]! as ThumbnailFormat, - maxHeight: result[3]! as int, - maxWidth: result[4]! as int, - timeMs: result[5]! as int, - quality: result[6]! as int, + sourceKind: result[1]! as ThumbnailSourceKind, + headers: (result[2] as Map?)?.cast(), + format: result[3]! as ThumbnailFormat, + maxHeight: result[4]! as int, + maxWidth: result[5]! as int, + timeMs: result[6]! as int, + quality: result[7]! as int, ); } @@ -166,6 +182,7 @@ class ThumbnailRequest { return true; } return _deepEquals(video, other.video) && + _deepEquals(sourceKind, other.sourceKind) && _deepEquals(headers, other.headers) && _deepEquals(format, other.format) && _deepEquals(maxHeight, other.maxHeight) && @@ -180,7 +197,7 @@ class ThumbnailRequest { @override String toString() { - return 'ThumbnailRequest(video: $video, headers: $headers, format: $format, maxHeight: $maxHeight, maxWidth: $maxWidth, timeMs: $timeMs, quality: $quality)'; + return 'ThumbnailRequest(video: $video, sourceKind: $sourceKind, headers: $headers, format: $format, maxHeight: $maxHeight, maxWidth: $maxWidth, timeMs: $timeMs, quality: $quality)'; } } @@ -194,8 +211,11 @@ class _PigeonCodec extends StandardMessageCodec { } else if (value is ThumbnailFormat) { buffer.putUint8(129); writeValue(buffer, value.index); - } else if (value is ThumbnailRequest) { + } else if (value is ThumbnailSourceKind) { buffer.putUint8(130); + writeValue(buffer, value.index); + } else if (value is ThumbnailRequest) { + buffer.putUint8(131); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); @@ -209,6 +229,9 @@ class _PigeonCodec extends StandardMessageCodec { final value = readValue(buffer) as int?; return value == null ? null : ThumbnailFormat.values[value]; case 130: + final value = readValue(buffer) as int?; + return value == null ? null : ThumbnailSourceKind.values[value]; + case 131: return ThumbnailRequest.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); diff --git a/packages/stream_thumbnail/lib/src/stream_thumbnail.dart b/packages/stream_thumbnail/lib/src/stream_thumbnail.dart index de854884..c451db2b 100644 --- a/packages/stream_thumbnail/lib/src/stream_thumbnail.dart +++ b/packages/stream_thumbnail/lib/src/stream_thumbnail.dart @@ -7,19 +7,15 @@ import 'package:flutter/services.dart'; import 'stream_thumbnail_format.dart'; import 'stream_thumbnail_platform.dart'; +import 'stream_thumbnail_source.dart'; /// Creates thumbnails from a local video file or from a video URL. abstract final class StreamThumbnail { - /// Generates a thumbnail file for each of the given `videos`. + /// Generates a thumbnail file for each of [sources], in order. /// - /// Each video can be a local file or a URL in an iOS/Android supported video - /// format. Use `maxHeight`/`maxWidth` to bound the size, or `0` to keep the - /// source resolution. A lower `quality` reduces image quality but is ignored - /// for the `PNG` format. - /// - /// The videos are processed one at a time rather than concurrently: every - /// platform holds a hardware video decoder open per in-flight request, and - /// devices cap how many can exist at once. + /// Use [maxHeight] and [maxWidth] to bound the size, or `0` to keep the + /// source resolution. A lower [quality] reduces image quality but is ignored + /// for [StreamThumbnailFormat.png]. The videos are processed one at a time. /// /// Each thumbnail is written to its own temporary directory. Use /// [XFile.saveTo] to copy one somewhere permanent; the temporary file is left @@ -28,20 +24,24 @@ abstract final class StreamThumbnail { /// On web there is no file system: each [XFile] wraps an object URL that the /// caller owns and should release with `URL.revokeObjectURL` once the bytes /// have been read via [XFile.readAsBytes]. + /// + /// Fails with an `UNSUPPORTED_SOURCE` [PlatformException] if a source can't + /// be opened on this platform. static Future> thumbnailFiles({ - required List videos, - Map? headers, + required List sources, StreamThumbnailFormat imageFormat = StreamThumbnailFormat.png, int maxHeight = 0, int maxWidth = 0, int? timeMs, int quality = 10, }) async { - if (videos.isEmpty) return []; + if (sources.isEmpty) return []; + for (final source in sources) { + if (source.unsupportedReason case final reason?) throw reason; + } return StreamThumbnailPlatform.instance.thumbnailFiles( - videos: videos, - headers: headers, + sources: sources, imageFormat: imageFormat, maxHeight: maxHeight, maxWidth: maxWidth, @@ -50,12 +50,11 @@ abstract final class StreamThumbnail { ); } - /// Generates a thumbnail file for the given `video`. + /// Generates a thumbnail file for [source]. /// - /// The video can be a local file or a URL in an iOS/Android supported video - /// format. Use `maxHeight`/`maxWidth` to bound the size, or `0` to keep the - /// source resolution. A lower `quality` reduces image quality but is ignored - /// for the `PNG` format. + /// Use [maxHeight] and [maxWidth] to bound the size, or `0` to keep the + /// source resolution. A lower [quality] reduces image quality but is ignored + /// for [StreamThumbnailFormat.png]. /// /// The thumbnail is written to its own temporary directory. Use [XFile.saveTo] /// to copy it somewhere permanent; the temporary file is left behind for the @@ -64,20 +63,21 @@ abstract final class StreamThumbnail { /// On web there is no file system: the [XFile] wraps an object URL that the /// caller owns and should release with `URL.revokeObjectURL` once the bytes /// have been read via [XFile.readAsBytes]. + /// + /// Fails with an `UNSUPPORTED_SOURCE` [PlatformException] if [source] can't + /// be opened on this platform. static Future thumbnailFile({ - required String video, - Map? headers, + required StreamThumbnailSource source, StreamThumbnailFormat imageFormat = StreamThumbnailFormat.png, int maxHeight = 0, int maxWidth = 0, int? timeMs, int quality = 10, }) { - assert(video.isNotEmpty); + if (source.unsupportedReason case final reason?) return Future.error(reason); return StreamThumbnailPlatform.instance.thumbnailFile( - video: video, - headers: headers, + source: source, imageFormat: imageFormat, maxHeight: maxHeight, maxWidth: maxWidth, @@ -86,27 +86,27 @@ abstract final class StreamThumbnail { ); } - /// Generates a thumbnail for the given `video` as in-memory bytes. + /// Generates a thumbnail for [source] as in-memory bytes. + /// + /// The returned bytes can be rendered directly with `Image.memory`. Use + /// [maxHeight] and [maxWidth] to bound the size, or `0` to keep the source + /// resolution. A lower [quality] reduces image quality but is ignored for + /// [StreamThumbnailFormat.png]. /// - /// The returned bytes can be rendered directly with `Image.memory`. The video - /// can be a local file or a URL in an iOS/Android supported video format. Use - /// `maxHeight`/`maxWidth` to bound the size, or `0` to keep the source - /// resolution. A lower `quality` reduces image quality but is ignored for the - /// `PNG` format. + /// Fails with an `UNSUPPORTED_SOURCE` [PlatformException] if [source] can't + /// be opened on this platform. static Future thumbnailData({ - required String video, - Map? headers, + required StreamThumbnailSource source, StreamThumbnailFormat imageFormat = StreamThumbnailFormat.png, int maxHeight = 0, int maxWidth = 0, int? timeMs, int quality = 10, }) { - assert(video.isNotEmpty); + if (source.unsupportedReason case final reason?) return Future.error(reason); return StreamThumbnailPlatform.instance.thumbnailData( - video: video, - headers: headers, + source: source, imageFormat: imageFormat, maxHeight: maxHeight, maxWidth: maxWidth, diff --git a/packages/stream_thumbnail/lib/src/stream_thumbnail_method_channel.dart b/packages/stream_thumbnail/lib/src/stream_thumbnail_method_channel.dart index 08a83c31..4c36e3a9 100644 --- a/packages/stream_thumbnail/lib/src/stream_thumbnail_method_channel.dart +++ b/packages/stream_thumbnail/lib/src/stream_thumbnail_method_channel.dart @@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart'; import 'messages.g.dart'; import 'stream_thumbnail_format.dart'; import 'stream_thumbnail_platform.dart'; +import 'stream_thumbnail_source.dart'; /// An implementation of [StreamThumbnailPlatform] that uses a Pigeon-generated /// platform channel. @@ -32,8 +33,7 @@ class MethodChannelStreamThumbnail extends StreamThumbnailPlatform { } ThumbnailRequest _request({ - required String video, - required Map? headers, + required StreamThumbnailSource source, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -41,8 +41,13 @@ class MethodChannelStreamThumbnail extends StreamThumbnailPlatform { required int quality, }) { return ThumbnailRequest( - video: video, - headers: headers, + video: source.location, + sourceKind: switch (source.kind) { + StreamThumbnailSourceKind.network => ThumbnailSourceKind.network, + StreamThumbnailSourceKind.file => ThumbnailSourceKind.file, + StreamThumbnailSourceKind.contentUri => ThumbnailSourceKind.contentUri, + }, + headers: source.headers, format: _wireFormat(imageFormat), maxHeight: maxHeight, maxWidth: maxWidth, @@ -53,8 +58,7 @@ class MethodChannelStreamThumbnail extends StreamThumbnailPlatform { @override Future> thumbnailFiles({ - required List videos, - required Map? headers, + required List sources, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -63,11 +67,10 @@ class MethodChannelStreamThumbnail extends StreamThumbnailPlatform { }) async { final results = []; - for (final video in videos) { + for (final source in sources) { results.add( await thumbnailFile( - video: video, - headers: headers, + source: source, imageFormat: imageFormat, maxHeight: maxHeight, maxWidth: maxWidth, @@ -82,8 +85,7 @@ class MethodChannelStreamThumbnail extends StreamThumbnailPlatform { @override Future thumbnailFile({ - required String video, - required Map? headers, + required StreamThumbnailSource source, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -92,8 +94,7 @@ class MethodChannelStreamThumbnail extends StreamThumbnailPlatform { }) async { final path = await _hostApi.thumbnailFile( _request( - video: video, - headers: headers, + source: source, imageFormat: imageFormat, maxHeight: maxHeight, maxWidth: maxWidth, @@ -106,8 +107,7 @@ class MethodChannelStreamThumbnail extends StreamThumbnailPlatform { @override Future thumbnailData({ - required String video, - required Map? headers, + required StreamThumbnailSource source, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -116,8 +116,7 @@ class MethodChannelStreamThumbnail extends StreamThumbnailPlatform { }) { return _hostApi.thumbnailData( _request( - video: video, - headers: headers, + source: source, imageFormat: imageFormat, maxHeight: maxHeight, maxWidth: maxWidth, diff --git a/packages/stream_thumbnail/lib/src/stream_thumbnail_platform.dart b/packages/stream_thumbnail/lib/src/stream_thumbnail_platform.dart index 4402a455..2aca624f 100644 --- a/packages/stream_thumbnail/lib/src/stream_thumbnail_platform.dart +++ b/packages/stream_thumbnail/lib/src/stream_thumbnail_platform.dart @@ -8,6 +8,7 @@ import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'stream_thumbnail_format.dart'; import 'stream_thumbnail_method_channel.dart'; +import 'stream_thumbnail_source.dart'; /// The interface that platform-specific implementations of /// `stream_thumbnail` must implement. @@ -32,10 +33,9 @@ abstract class StreamThumbnailPlatform extends PlatformInterface { _instance = instance; } - /// Generates a thumbnail file for each of the given `videos`. + /// Generates a thumbnail file for each of [sources]. Future> thumbnailFiles({ - required List videos, - required Map? headers, + required List sources, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -45,10 +45,9 @@ abstract class StreamThumbnailPlatform extends PlatformInterface { throw UnimplementedError('thumbnailFiles() has not been implemented.'); } - /// Generates a thumbnail file for the given `video`. + /// Generates a thumbnail file for [source]. Future thumbnailFile({ - required String video, - required Map? headers, + required StreamThumbnailSource source, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -58,10 +57,9 @@ abstract class StreamThumbnailPlatform extends PlatformInterface { throw UnimplementedError('thumbnailFile() has not been implemented.'); } - /// Generates a thumbnail for the given `video` as in-memory bytes. + /// Generates a thumbnail for [source] as in-memory bytes. Future thumbnailData({ - required String video, - required Map? headers, + required StreamThumbnailSource source, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, diff --git a/packages/stream_thumbnail/lib/src/stream_thumbnail_source.dart b/packages/stream_thumbnail/lib/src/stream_thumbnail_source.dart new file mode 100644 index 00000000..b223f1d2 --- /dev/null +++ b/packages/stream_thumbnail/lib/src/stream_thumbnail_source.dart @@ -0,0 +1,129 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import 'stream_thumbnail.dart'; + +/// Where a [StreamThumbnailSource] reads its video from. +@internal +enum StreamThumbnailSourceKind { network, file, contentUri } + +/// The video a thumbnail is generated from. +/// +/// [StreamThumbnailSource.network] fetches an `http` or `https` URL, +/// [StreamThumbnailSource.file] reads a video stored on this device, and +/// [StreamThumbnailSource.contentUri] reads from an Android content provider. +/// +/// {@tool snippet} +/// Thumbnail a video attachment, preferring the local copy when there is one: +/// +/// ```dart +/// final source = localPath != null +/// ? StreamThumbnailSource.file(localPath) +/// : StreamThumbnailSource.network(Uri.parse(videoUrl)); +/// +/// final bytes = await StreamThumbnail.thumbnailData(source: source); +/// ``` +/// {@end-tool} +/// +/// See also: +/// +/// * [StreamThumbnail.thumbnailData], which generates the thumbnail as bytes. +/// * [StreamThumbnail.thumbnailFile], which writes the thumbnail to a file. +@immutable +final class StreamThumbnailSource { + /// A video fetched from [url]. + /// + /// Only `http` and `https` URLs with a host are fetched; generating a + /// thumbnail for any other URL fails with an `UNSUPPORTED_SOURCE` + /// [PlatformException]. + /// + /// [headers] are sent with the request, except on Windows, which cannot + /// attach them. + StreamThumbnailSource.network(Uri url, {Map? headers}) + : kind = StreamThumbnailSourceKind.network, + location = url.toString(), + headers = headers == null ? null : Map.unmodifiable(headers); + + /// A video stored on this device at [path]. + /// + /// [path] is a file system path or a `file:` URI. On web, where there is no + /// file system, it is the object URL of the video, such as the `path` of a + /// picked `XFile`. + /// + /// Generating a thumbnail fails with an `UNSUPPORTED_SOURCE` + /// [PlatformException] for a URL naming a host, such as an `https` URL, and + /// on Windows for anything other than an absolute path on a local drive. + StreamThumbnailSource.file(String path) + : assert(path.isNotEmpty, 'path must not be empty'), + kind = StreamThumbnailSourceKind.file, + location = path, + headers = null; + + /// A video an Android content provider serves at [uri]. + /// + /// Only supported on Android; generating a thumbnail on any other platform, + /// or for a URI whose scheme isn't `content`, fails with an + /// `UNSUPPORTED_SOURCE` [PlatformException]. + StreamThumbnailSource.contentUri(Uri uri) + : kind = StreamThumbnailSourceKind.contentUri, + location = uri.toString(), + headers = null; + + /// Where the video is read from. + @internal + final StreamThumbnailSourceKind kind; + + /// The URL, path or URI of the video, as the platform receives it. + @internal + final String location; + + /// The HTTP headers sent when fetching a [StreamThumbnailSource.network] + /// video, or `null` for other sources. + @internal + final Map? headers; + + /// Why this source can't be opened on any platform, or `null` if it can. + @internal + PlatformException? get unsupportedReason { + final uri = Uri.tryParse(location); + return switch (kind) { + StreamThumbnailSourceKind.network + when uri == null || !(uri.isScheme('http') || uri.isScheme('https')) || uri.host.isEmpty => + PlatformException(code: 'UNSUPPORTED_SOURCE', message: 'A network video must be an http or https URL.'), + StreamThumbnailSourceKind.file when uri != null && uri.hasAuthority && !uri.isScheme('file') => PlatformException( + code: 'UNSUPPORTED_SOURCE', + message: 'A file video must be a path on this device.', + ), + StreamThumbnailSourceKind.contentUri when uri == null || !uri.isScheme('content') => PlatformException( + code: 'UNSUPPORTED_SOURCE', + message: 'A content video must be a content URI.', + ), + StreamThumbnailSourceKind.network || + StreamThumbnailSourceKind.file || + StreamThumbnailSourceKind.contentUri => null, + }; + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is StreamThumbnailSource && + other.kind == kind && + other.location == location && + mapEquals(other.headers, headers); + } + + @override + int get hashCode => Object.hash( + kind, + location, + headers == null ? null : Object.hashAllUnordered(headers!.entries.map((e) => Object.hash(e.key, e.value))), + ); + + @override + String toString() { + final uri = Uri.tryParse(location); + final shown = uri != null && uri.hasAuthority ? '${uri.scheme}://${uri.host}${uri.path}' : location; + return 'StreamThumbnailSource.${kind.name}($shown)'; + } +} diff --git a/packages/stream_thumbnail/lib/stream_thumbnail.dart b/packages/stream_thumbnail/lib/stream_thumbnail.dart index 43e01693..7f33af71 100644 --- a/packages/stream_thumbnail/lib/stream_thumbnail.dart +++ b/packages/stream_thumbnail/lib/stream_thumbnail.dart @@ -9,3 +9,4 @@ export 'package:cross_file/cross_file.dart' show XFile; export 'src/stream_thumbnail.dart' show StreamThumbnail; export 'src/stream_thumbnail_format.dart' show StreamThumbnailFormat; +export 'src/stream_thumbnail_source.dart' show StreamThumbnailSource; diff --git a/packages/stream_thumbnail/lib/stream_thumbnail_web.dart b/packages/stream_thumbnail/lib/stream_thumbnail_web.dart index e8c16dea..9db53178 100644 --- a/packages/stream_thumbnail/lib/stream_thumbnail_web.dart +++ b/packages/stream_thumbnail/lib/stream_thumbnail_web.dart @@ -12,6 +12,7 @@ import 'package:web/web.dart' as web; import 'src/stream_thumbnail_format.dart'; import 'src/stream_thumbnail_platform.dart'; +import 'src/stream_thumbnail_source.dart'; // An error code value to error name Map. // See: https://developer.mozilla.org/en-US/docs/Web/API/MediaError/code @@ -47,8 +48,7 @@ class StreamThumbnailWeb extends StreamThumbnailPlatform { @override Future> thumbnailFiles({ - required List videos, - required Map? headers, + required List sources, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -57,10 +57,9 @@ class StreamThumbnailWeb extends StreamThumbnailPlatform { }) async { final files = []; - for (final video in videos) { + for (final source in sources) { final blob = await _createThumbnail( - videoSrc: video, - headers: headers, + source: source, imageFormat: imageFormat, maxHeight: maxHeight, maxWidth: maxWidth, @@ -72,7 +71,7 @@ class StreamThumbnailWeb extends StreamThumbnailPlatform { XFile( web.URL.createObjectURL(blob), mimeType: blob.type, - name: _thumbnailName(video, imageFormat), + name: _thumbnailName(source.location, imageFormat), ), ); } @@ -82,8 +81,7 @@ class StreamThumbnailWeb extends StreamThumbnailPlatform { @override Future thumbnailFile({ - required String video, - required Map? headers, + required StreamThumbnailSource source, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -91,8 +89,7 @@ class StreamThumbnailWeb extends StreamThumbnailPlatform { required int quality, }) async { final blob = await _createThumbnail( - videoSrc: video, - headers: headers, + source: source, imageFormat: imageFormat, maxHeight: maxHeight, maxWidth: maxWidth, @@ -103,14 +100,13 @@ class StreamThumbnailWeb extends StreamThumbnailPlatform { return XFile( web.URL.createObjectURL(blob), mimeType: blob.type, - name: _thumbnailName(video, imageFormat), + name: _thumbnailName(source.location, imageFormat), ); } @override Future thumbnailData({ - required String video, - required Map? headers, + required StreamThumbnailSource source, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -118,8 +114,7 @@ class StreamThumbnailWeb extends StreamThumbnailPlatform { required int quality, }) async { final blob = await _createThumbnail( - videoSrc: video, - headers: headers, + source: source, imageFormat: imageFormat, maxHeight: maxHeight, maxWidth: maxWidth, @@ -135,14 +130,22 @@ class StreamThumbnailWeb extends StreamThumbnailPlatform { } Future _createThumbnail({ - required String videoSrc, - required Map? headers, + required StreamThumbnailSource source, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, required int quality, int timeMs = 0, }) async { + switch (source.kind) { + case StreamThumbnailSourceKind.contentUri: + throw PlatformException(code: 'UNSUPPORTED_SOURCE', message: 'Content URIs are only supported on Android.'); + case StreamThumbnailSourceKind.network || StreamThumbnailSourceKind.file: + if (source.unsupportedReason case final reason?) throw reason; + } + + final videoSrc = source.location; + final headers = source.headers; final completer = Completer(); final video = web.document.createElement('video') as web.HTMLVideoElement; diff --git a/packages/stream_thumbnail/linux/pigeon/messages.g.cc b/packages/stream_thumbnail/linux/pigeon/messages.g.cc index e610ad34..cc5a0b52 100644 --- a/packages/stream_thumbnail/linux/pigeon/messages.g.cc +++ b/packages/stream_thumbnail/linux/pigeon/messages.g.cc @@ -290,6 +290,7 @@ struct _StreamThumbnailThumbnailRequest { GObject parent_instance; gchar* video; + StreamThumbnailThumbnailSourceKind source_kind; FlValue* headers; StreamThumbnailThumbnailFormat format; int64_t max_height; @@ -314,9 +315,10 @@ static void stream_thumbnail_thumbnail_request_class_init(StreamThumbnailThumbna G_OBJECT_CLASS(klass)->dispose = stream_thumbnail_thumbnail_request_dispose; } -StreamThumbnailThumbnailRequest* stream_thumbnail_thumbnail_request_new(const gchar* video, FlValue* headers, StreamThumbnailThumbnailFormat format, int64_t max_height, int64_t max_width, int64_t time_ms, int64_t quality) { +StreamThumbnailThumbnailRequest* stream_thumbnail_thumbnail_request_new(const gchar* video, StreamThumbnailThumbnailSourceKind source_kind, FlValue* headers, StreamThumbnailThumbnailFormat format, int64_t max_height, int64_t max_width, int64_t time_ms, int64_t quality) { StreamThumbnailThumbnailRequest* self = STREAM_THUMBNAIL_THUMBNAIL_REQUEST(g_object_new(stream_thumbnail_thumbnail_request_get_type(), nullptr)); self->video = g_strdup(video); + self->source_kind = source_kind; if (headers != nullptr) { self->headers = fl_value_ref(headers); } @@ -336,6 +338,11 @@ const gchar* stream_thumbnail_thumbnail_request_get_video(StreamThumbnailThumbna return self->video; } +StreamThumbnailThumbnailSourceKind stream_thumbnail_thumbnail_request_get_source_kind(StreamThumbnailThumbnailRequest* self) { + g_return_val_if_fail(STREAM_THUMBNAIL_IS_THUMBNAIL_REQUEST(self), static_cast(0)); + return self->source_kind; +} + FlValue* stream_thumbnail_thumbnail_request_get_headers(StreamThumbnailThumbnailRequest* self) { g_return_val_if_fail(STREAM_THUMBNAIL_IS_THUMBNAIL_REQUEST(self), nullptr); return self->headers; @@ -369,6 +376,7 @@ int64_t stream_thumbnail_thumbnail_request_get_quality(StreamThumbnailThumbnailR static FlValue* stream_thumbnail_thumbnail_request_to_list(StreamThumbnailThumbnailRequest* self) { FlValue* values = fl_value_new_list(); fl_value_append_take(values, fl_value_new_string(self->video)); + fl_value_append_take(values, fl_value_new_custom(stream_thumbnail_thumbnail_source_kind_type_id, fl_value_new_int(self->source_kind), (GDestroyNotify)fl_value_unref)); fl_value_append_take(values, self->headers != nullptr ? fl_value_ref(self->headers) : fl_value_new_null()); fl_value_append_take(values, fl_value_new_custom(stream_thumbnail_thumbnail_format_type_id, fl_value_new_int(self->format), (GDestroyNotify)fl_value_unref)); fl_value_append_take(values, fl_value_new_int(self->max_height)); @@ -382,21 +390,23 @@ static StreamThumbnailThumbnailRequest* stream_thumbnail_thumbnail_request_new_f FlValue* value0 = fl_value_get_list_value(values, 0); const gchar* video = fl_value_get_string(value0); FlValue* value1 = fl_value_get_list_value(values, 1); + StreamThumbnailThumbnailSourceKind source_kind = static_cast(fl_value_get_int(reinterpret_cast(const_cast(fl_value_get_custom_value(value1))))); + FlValue* value2 = fl_value_get_list_value(values, 2); FlValue* headers = nullptr; - if (fl_value_get_type(value1) != FL_VALUE_TYPE_NULL) { - headers = value1; + if (fl_value_get_type(value2) != FL_VALUE_TYPE_NULL) { + headers = value2; } - FlValue* value2 = fl_value_get_list_value(values, 2); - StreamThumbnailThumbnailFormat format = static_cast(fl_value_get_int(reinterpret_cast(const_cast(fl_value_get_custom_value(value2))))); FlValue* value3 = fl_value_get_list_value(values, 3); - int64_t max_height = fl_value_get_int(value3); + StreamThumbnailThumbnailFormat format = static_cast(fl_value_get_int(reinterpret_cast(const_cast(fl_value_get_custom_value(value3))))); FlValue* value4 = fl_value_get_list_value(values, 4); - int64_t max_width = fl_value_get_int(value4); + int64_t max_height = fl_value_get_int(value4); FlValue* value5 = fl_value_get_list_value(values, 5); - int64_t time_ms = fl_value_get_int(value5); + int64_t max_width = fl_value_get_int(value5); FlValue* value6 = fl_value_get_list_value(values, 6); - int64_t quality = fl_value_get_int(value6); - return stream_thumbnail_thumbnail_request_new(video, headers, format, max_height, max_width, time_ms, quality); + int64_t time_ms = fl_value_get_int(value6); + FlValue* value7 = fl_value_get_list_value(values, 7); + int64_t quality = fl_value_get_int(value7); + return stream_thumbnail_thumbnail_request_new(video, source_kind, headers, format, max_height, max_width, time_ms, quality); } gboolean stream_thumbnail_thumbnail_request_equals(StreamThumbnailThumbnailRequest* a, StreamThumbnailThumbnailRequest* b) { @@ -409,6 +419,9 @@ gboolean stream_thumbnail_thumbnail_request_equals(StreamThumbnailThumbnailReque if (g_strcmp0(a->video, b->video) != 0) { return FALSE; } + if (a->source_kind != b->source_kind) { + return FALSE; + } if (!flpigeon_deep_equals(a->headers, b->headers)) { return FALSE; } @@ -434,6 +447,7 @@ guint stream_thumbnail_thumbnail_request_hash(StreamThumbnailThumbnailRequest* s g_return_val_if_fail(STREAM_THUMBNAIL_IS_THUMBNAIL_REQUEST(self), 0); guint result = 0; result = result * 31 + (self->video != nullptr ? g_str_hash(self->video) : 0); + result = result * 31 + static_cast(self->source_kind); result = result * 31 + flpigeon_deep_hash(self->headers); result = result * 31 + static_cast(self->format); result = result * 31 + static_cast(self->max_height); @@ -453,6 +467,8 @@ gchar* stream_thumbnail_thumbnail_request_to_string(StreamThumbnailThumbnailRequ else { g_string_append(str, "null"); } + g_string_append(str, ", source_kind: "); + g_string_append_printf(str, "%d", static_cast(self->source_kind)); g_string_append(str, ", headers: "); if (self->headers != nullptr) { gchar* val_str = flpigeon_to_string(self->headers); @@ -484,7 +500,8 @@ struct _StreamThumbnailMessageCodec { G_DEFINE_TYPE(StreamThumbnailMessageCodec, stream_thumbnail_message_codec, fl_standard_message_codec_get_type()) const int stream_thumbnail_thumbnail_format_type_id = 129; -const int stream_thumbnail_thumbnail_request_type_id = 130; +const int stream_thumbnail_thumbnail_source_kind_type_id = 130; +const int stream_thumbnail_thumbnail_request_type_id = 131; static gboolean stream_thumbnail_message_codec_write_stream_thumbnail_thumbnail_format(FlStandardMessageCodec* codec, GByteArray* buffer, FlValue* value, GError** error) { uint8_t type = stream_thumbnail_thumbnail_format_type_id; @@ -492,6 +509,12 @@ static gboolean stream_thumbnail_message_codec_write_stream_thumbnail_thumbnail_ return fl_standard_message_codec_write_value(codec, buffer, value, error); } +static gboolean stream_thumbnail_message_codec_write_stream_thumbnail_thumbnail_source_kind(FlStandardMessageCodec* codec, GByteArray* buffer, FlValue* value, GError** error) { + uint8_t type = stream_thumbnail_thumbnail_source_kind_type_id; + g_byte_array_append(buffer, &type, sizeof(uint8_t)); + return fl_standard_message_codec_write_value(codec, buffer, value, error); +} + static gboolean stream_thumbnail_message_codec_write_stream_thumbnail_thumbnail_request(FlStandardMessageCodec* codec, GByteArray* buffer, StreamThumbnailThumbnailRequest* value, GError** error) { uint8_t type = stream_thumbnail_thumbnail_request_type_id; g_byte_array_append(buffer, &type, sizeof(uint8_t)); @@ -504,6 +527,8 @@ static gboolean stream_thumbnail_message_codec_write_value(FlStandardMessageCode switch (fl_value_get_custom_type(value)) { case stream_thumbnail_thumbnail_format_type_id: return stream_thumbnail_message_codec_write_stream_thumbnail_thumbnail_format(codec, buffer, reinterpret_cast(const_cast(fl_value_get_custom_value(value))), error); + case stream_thumbnail_thumbnail_source_kind_type_id: + return stream_thumbnail_message_codec_write_stream_thumbnail_thumbnail_source_kind(codec, buffer, reinterpret_cast(const_cast(fl_value_get_custom_value(value))), error); case stream_thumbnail_thumbnail_request_type_id: return stream_thumbnail_message_codec_write_stream_thumbnail_thumbnail_request(codec, buffer, STREAM_THUMBNAIL_THUMBNAIL_REQUEST(fl_value_get_custom_value_object(value)), error); } @@ -516,6 +541,10 @@ static FlValue* stream_thumbnail_message_codec_read_stream_thumbnail_thumbnail_f return fl_value_new_custom(stream_thumbnail_thumbnail_format_type_id, fl_standard_message_codec_read_value(codec, buffer, offset, error), (GDestroyNotify)fl_value_unref); } +static FlValue* stream_thumbnail_message_codec_read_stream_thumbnail_thumbnail_source_kind(FlStandardMessageCodec* codec, GBytes* buffer, size_t* offset, GError** error) { + return fl_value_new_custom(stream_thumbnail_thumbnail_source_kind_type_id, fl_standard_message_codec_read_value(codec, buffer, offset, error), (GDestroyNotify)fl_value_unref); +} + static FlValue* stream_thumbnail_message_codec_read_stream_thumbnail_thumbnail_request(FlStandardMessageCodec* codec, GBytes* buffer, size_t* offset, GError** error) { g_autoptr(FlValue) values = fl_standard_message_codec_read_value(codec, buffer, offset, error); if (values == nullptr) { @@ -535,6 +564,8 @@ static FlValue* stream_thumbnail_message_codec_read_value_of_type(FlStandardMess switch (type) { case stream_thumbnail_thumbnail_format_type_id: return stream_thumbnail_message_codec_read_stream_thumbnail_thumbnail_format(codec, buffer, offset, error); + case stream_thumbnail_thumbnail_source_kind_type_id: + return stream_thumbnail_message_codec_read_stream_thumbnail_thumbnail_source_kind(codec, buffer, offset, error); case stream_thumbnail_thumbnail_request_type_id: return stream_thumbnail_message_codec_read_stream_thumbnail_thumbnail_request(codec, buffer, offset, error); default: diff --git a/packages/stream_thumbnail/linux/pigeon/messages.g.h b/packages/stream_thumbnail/linux/pigeon/messages.g.h index 26b2b81a..6fcb3db1 100644 --- a/packages/stream_thumbnail/linux/pigeon/messages.g.h +++ b/packages/stream_thumbnail/linux/pigeon/messages.g.h @@ -22,6 +22,24 @@ typedef enum { STREAM_THUMBNAIL_THUMBNAIL_FORMAT_WEBP = 2 } StreamThumbnailThumbnailFormat; +/** + * StreamThumbnailThumbnailSourceKind: + * STREAM_THUMBNAIL_THUMBNAIL_SOURCE_KIND_NETWORK: + * STREAM_THUMBNAIL_THUMBNAIL_SOURCE_KIND_FILE: + * STREAM_THUMBNAIL_THUMBNAIL_SOURCE_KIND_CONTENT_URI: + * + * Where [ThumbnailRequest.video] is read from, and so how it may be opened. + * + * `network` must only be fetched over http or https, `file` must only be + * opened as a local path, and `contentUri` only through an Android content + * resolver. + */ +typedef enum { + STREAM_THUMBNAIL_THUMBNAIL_SOURCE_KIND_NETWORK = 0, + STREAM_THUMBNAIL_THUMBNAIL_SOURCE_KIND_FILE = 1, + STREAM_THUMBNAIL_THUMBNAIL_SOURCE_KIND_CONTENT_URI = 2 +} StreamThumbnailThumbnailSourceKind; + /** * StreamThumbnailThumbnailRequest: * @@ -33,6 +51,7 @@ G_DECLARE_FINAL_TYPE(StreamThumbnailThumbnailRequest, stream_thumbnail_thumbnail /** * stream_thumbnail_thumbnail_request_new: * video: field in this object. + * source_kind: field in this object. * headers: field in this object. * format: field in this object. * max_height: field in this object. @@ -44,7 +63,7 @@ G_DECLARE_FINAL_TYPE(StreamThumbnailThumbnailRequest, stream_thumbnail_thumbnail * * Returns: a new #StreamThumbnailThumbnailRequest */ -StreamThumbnailThumbnailRequest* stream_thumbnail_thumbnail_request_new(const gchar* video, FlValue* headers, StreamThumbnailThumbnailFormat format, int64_t max_height, int64_t max_width, int64_t time_ms, int64_t quality); +StreamThumbnailThumbnailRequest* stream_thumbnail_thumbnail_request_new(const gchar* video, StreamThumbnailThumbnailSourceKind source_kind, FlValue* headers, StreamThumbnailThumbnailFormat format, int64_t max_height, int64_t max_width, int64_t time_ms, int64_t quality); /** * stream_thumbnail_thumbnail_request_get_video @@ -56,6 +75,16 @@ StreamThumbnailThumbnailRequest* stream_thumbnail_thumbnail_request_new(const gc */ const gchar* stream_thumbnail_thumbnail_request_get_video(StreamThumbnailThumbnailRequest* object); +/** + * stream_thumbnail_thumbnail_request_get_source_kind + * @object: a #StreamThumbnailThumbnailRequest. + * + * Gets the value of the sourceKind field of @object. + * + * Returns: the field value. + */ +StreamThumbnailThumbnailSourceKind stream_thumbnail_thumbnail_request_get_source_kind(StreamThumbnailThumbnailRequest* object); + /** * stream_thumbnail_thumbnail_request_get_headers * @object: a #StreamThumbnailThumbnailRequest. @@ -157,6 +186,7 @@ G_DECLARE_FINAL_TYPE(StreamThumbnailMessageCodec, stream_thumbnail_message_codec * They may be used in custom object creation functions to identify the type. */ extern const int stream_thumbnail_thumbnail_format_type_id; +extern const int stream_thumbnail_thumbnail_source_kind_type_id; extern const int stream_thumbnail_thumbnail_request_type_id; G_DECLARE_FINAL_TYPE(StreamThumbnailStreamThumbnailHostApi, stream_thumbnail_stream_thumbnail_host_api, STREAM_THUMBNAIL, STREAM_THUMBNAIL_HOST_API, GObject) diff --git a/packages/stream_thumbnail/linux/stream_thumbnail_plugin.cc b/packages/stream_thumbnail/linux/stream_thumbnail_plugin.cc index f73041f8..96081a9b 100644 --- a/packages/stream_thumbnail/linux/stream_thumbnail_plugin.cc +++ b/packages/stream_thumbnail/linux/stream_thumbnail_plugin.cc @@ -64,19 +64,44 @@ using FramePtr = std::unique_ptr; using PacketPtr = std::unique_ptr; using SwsContextPtr = std::unique_ptr; -// True only for an explicit non-file URL scheme, e.g. "https://host/clip.mp4". -// Bare absolute and relative paths are local. -bool IsRemoteUrl(const std::string &video) { - const size_t scheme = video.find("://"); - return scheme != std::string::npos && video.compare(0, scheme, "file") != 0; -} - // Strips a leading "file://" prefix, if present. std::string VideoPath(const std::string &video) { if (video.rfind("file://", 0) == 0) return video.substr(7); return video; } +bool HasHttpScheme(const std::string &video) { + return g_ascii_strncasecmp(video.c_str(), "http://", 7) == 0 || + g_ascii_strncasecmp(video.c_str(), "https://", 8) == 0; +} + +// What FFmpeg is allowed to open for one request. +struct InputSpec { + std::string url; + std::string protocol_whitelist; +}; + +// Single-file containers only; playlist and concatenating demuxers (hls, dash, +// concat, ...) are not supported. +constexpr char kFormatWhitelist[] = "mov,matroska,avi,flv,mpegts,mpeg,ogg,asf"; + +// A network video is fetched over http(s), with tls/tcp as the transports https +// and http sit on. A file is opened through the `file:` protocol only. +InputSpec ResolveInput(const std::string &video, StreamThumbnailThumbnailSourceKind kind) { + switch (kind) { + case STREAM_THUMBNAIL_THUMBNAIL_SOURCE_KIND_NETWORK: + if (!HasHttpScheme(video)) { + throw ThumbnailException("UNSUPPORTED_SOURCE", "A network video must be an http or https URL."); + } + return {video, "http,https,tls,tcp"}; + case STREAM_THUMBNAIL_THUMBNAIL_SOURCE_KIND_FILE: + return {"file:" + VideoPath(video), "file"}; + case STREAM_THUMBNAIL_THUMBNAIL_SOURCE_KIND_CONTENT_URI: + throw ThumbnailException("UNSUPPORTED_SOURCE", "Content URIs are only supported on Android."); + } + throw ThumbnailException("UNSUPPORTED_SOURCE", "Unknown video source."); +} + std::string FileExtension(StreamThumbnailThumbnailFormat format) { switch (format) { case STREAM_THUMBNAIL_THUMBNAIL_FORMAT_JPEG: @@ -104,10 +129,10 @@ std::string OutputFileName(const std::string &video, const std::string &ext) { return stem + "." + ext; } -// Decodes a single frame from `video` at `time_ms`, at its native resolution +// Decodes a single frame from `input` at `time_ms`, at its native resolution // and pixel format. Unlike Media Foundation (Windows), FFmpeg's http(s) // protocol handler has a simple, direct way to attach custom headers. -FramePtr DecodeFrame(const std::string &video, const std::map *headers, int64_t time_ms) { +FramePtr DecodeFrame(const InputSpec &input, const std::map *headers, int64_t time_ms) { AVDictionary *options = nullptr; if (headers != nullptr && !headers->empty()) { std::string header_lines; @@ -117,16 +142,11 @@ FramePtr DecodeFrame(const std::string &video, const std::map tcp) — and allow `file` only for local inputs. - const std::string protocols = IsRemoteUrl(video) ? "http,https,tls,tcp" : "file,http,https,tls,tcp"; - av_dict_set(&options, "protocol_whitelist", protocols.c_str(), 0); + av_dict_set(&options, "protocol_whitelist", input.protocol_whitelist.c_str(), 0); + av_dict_set(&options, "format_whitelist", kFormatWhitelist, 0); AVFormatContext *raw_format_ctx = nullptr; - const int open_result = avformat_open_input(&raw_format_ctx, video.c_str(), nullptr, &options); + const int open_result = avformat_open_input(&raw_format_ctx, input.url.c_str(), nullptr, &options); av_dict_free(&options); if (open_result < 0) { throw ThumbnailException("THUMBNAIL_ERROR", "Failed to open the video."); @@ -280,10 +300,11 @@ std::vector EncodeWebP(const AVFrame *frame, int64_t quality) { return result; } -std::vector GenerateThumbnailData(const std::string &video, const std::map *headers, +std::vector GenerateThumbnailData(const std::string &video, StreamThumbnailThumbnailSourceKind kind, + const std::map *headers, StreamThumbnailThumbnailFormat format, int64_t max_width, int64_t max_height, int64_t time_ms, int64_t quality) { - const FramePtr native = DecodeFrame(VideoPath(video), headers, time_ms); + const FramePtr native = DecodeFrame(ResolveInput(video, kind), headers, time_ms); int width, height; ScaledSize(native->width, native->height, max_width, max_height, &width, &height); @@ -305,10 +326,12 @@ std::vector GenerateThumbnailData(const std::string &video, const std:: throw ThumbnailException("THUMBNAIL_ERROR", "Unknown image format."); } -std::string WriteThumbnailFile(const std::string &video, const std::map *headers, +std::string WriteThumbnailFile(const std::string &video, StreamThumbnailThumbnailSourceKind kind, + const std::map *headers, StreamThumbnailThumbnailFormat format, int64_t max_width, int64_t max_height, int64_t time_ms, int64_t quality) { - const std::vector data = GenerateThumbnailData(video, headers, format, max_width, max_height, time_ms, quality); + const std::vector data = + GenerateThumbnailData(video, kind, headers, format, max_width, max_height, time_ms, quality); // The file name comes from the video, so a directory per request is what keeps // two same-named videos from different folders off each other. g_dir_make_tmp @@ -360,6 +383,7 @@ std::unique_ptr> ExtractHeaders(FlValue *head // functions from a non-main thread. struct ThumbnailDataTaskData { std::string video; + StreamThumbnailThumbnailSourceKind source_kind; std::unique_ptr> headers; StreamThumbnailThumbnailFormat format; int64_t max_width; @@ -377,6 +401,7 @@ struct ThumbnailDataResult { struct ThumbnailFileTaskData { std::string video; + StreamThumbnailThumbnailSourceKind source_kind; std::unique_ptr> headers; StreamThumbnailThumbnailFormat format; int64_t max_width; @@ -396,9 +421,8 @@ void ThumbnailDataThread(GTask *task, gpointer, gpointer task_data, GCancellable auto *data = static_cast(task_data); auto *result = new ThumbnailDataResult(); try { - result->bytes = - GenerateThumbnailData(data->video, data->headers.get(), data->format, data->max_width, data->max_height, - data->time_ms, data->quality); + result->bytes = GenerateThumbnailData(data->video, data->source_kind, data->headers.get(), data->format, + data->max_width, data->max_height, data->time_ms, data->quality); result->ok = true; } catch (const ThumbnailException &e) { result->error_code = e.code(); @@ -432,8 +456,8 @@ void ThumbnailFileThread(GTask *task, gpointer, gpointer task_data, GCancellable auto *data = static_cast(task_data); auto *result = new ThumbnailFileResult(); try { - result->path = WriteThumbnailFile(data->video, data->headers.get(), data->format, data->max_width, - data->max_height, data->time_ms, data->quality); + result->path = WriteThumbnailFile(data->video, data->source_kind, data->headers.get(), data->format, + data->max_width, data->max_height, data->time_ms, data->quality); result->ok = true; } catch (const ThumbnailException &e) { result->error_code = e.code(); @@ -462,6 +486,7 @@ void HandleThumbnailData(StreamThumbnailThumbnailRequest *request, StreamThumbna gpointer) { auto *data = new ThumbnailDataTaskData{ stream_thumbnail_thumbnail_request_get_video(request), + stream_thumbnail_thumbnail_request_get_source_kind(request), ExtractHeaders(stream_thumbnail_thumbnail_request_get_headers(request)), stream_thumbnail_thumbnail_request_get_format(request), stream_thumbnail_thumbnail_request_get_max_width(request), @@ -480,6 +505,7 @@ void HandleThumbnailFile(StreamThumbnailThumbnailRequest *request, StreamThumbna gpointer) { auto *data = new ThumbnailFileTaskData{ stream_thumbnail_thumbnail_request_get_video(request), + stream_thumbnail_thumbnail_request_get_source_kind(request), ExtractHeaders(stream_thumbnail_thumbnail_request_get_headers(request)), stream_thumbnail_thumbnail_request_get_format(request), stream_thumbnail_thumbnail_request_get_max_width(request), diff --git a/packages/stream_thumbnail/macos/stream_thumbnail/Sources/stream_thumbnail/Messages.g.swift b/packages/stream_thumbnail/macos/stream_thumbnail/Sources/stream_thumbnail/Messages.g.swift index 82492202..3b79892c 100644 --- a/packages/stream_thumbnail/macos/stream_thumbnail/Sources/stream_thumbnail/Messages.g.swift +++ b/packages/stream_thumbnail/macos/stream_thumbnail/Sources/stream_thumbnail/Messages.g.swift @@ -191,11 +191,23 @@ enum ThumbnailFormat: Int, CaseIterable { case webp = 2 } +/// Where [ThumbnailRequest.video] is read from, and so how it may be opened. +/// +/// `network` must only be fetched over http or https, `file` must only be +/// opened as a local path, and `contentUri` only through an Android content +/// resolver. +enum ThumbnailSourceKind: Int, CaseIterable { + case network = 0 + case file = 1 + case contentUri = 2 +} + /// A single thumbnail generation request sent to the native platform. /// /// Generated class from Pigeon that represents data sent in messages. struct ThumbnailRequest: Hashable, CustomStringConvertible { var video: String + var sourceKind: ThumbnailSourceKind var headers: [String: String]? = nil var format: ThumbnailFormat var maxHeight: Int64 @@ -207,15 +219,17 @@ struct ThumbnailRequest: Hashable, CustomStringConvertible { // swift-format-ignore: AlwaysUseLowerCamelCase static func fromList(_ pigeonVar_list: [Any?]) -> ThumbnailRequest? { let video = pigeonVar_list[0] as! String - let headers: [String: String]? = nilOrValue(pigeonVar_list[1]) - let format = pigeonVar_list[2] as! ThumbnailFormat - let maxHeight = pigeonVar_list[3] as! Int64 - let maxWidth = pigeonVar_list[4] as! Int64 - let timeMs = pigeonVar_list[5] as! Int64 - let quality = pigeonVar_list[6] as! Int64 + let sourceKind = pigeonVar_list[1] as! ThumbnailSourceKind + let headers: [String: String]? = nilOrValue(pigeonVar_list[2]) + let format = pigeonVar_list[3] as! ThumbnailFormat + let maxHeight = pigeonVar_list[4] as! Int64 + let maxWidth = pigeonVar_list[5] as! Int64 + let timeMs = pigeonVar_list[6] as! Int64 + let quality = pigeonVar_list[7] as! Int64 return ThumbnailRequest( video: video, + sourceKind: sourceKind, headers: headers, format: format, maxHeight: maxHeight, @@ -227,6 +241,7 @@ struct ThumbnailRequest: Hashable, CustomStringConvertible { func toList() -> [Any?] { return [ video, + sourceKind, headers, format, maxHeight, @@ -239,12 +254,13 @@ struct ThumbnailRequest: Hashable, CustomStringConvertible { if Swift.type(of: lhs) != Swift.type(of: rhs) { return false } - return MessagesPigeonInternal.deepEquals(lhs.video, rhs.video) && MessagesPigeonInternal.deepEquals(lhs.headers, rhs.headers) && MessagesPigeonInternal.deepEquals(lhs.format, rhs.format) && MessagesPigeonInternal.deepEquals(lhs.maxHeight, rhs.maxHeight) && MessagesPigeonInternal.deepEquals(lhs.maxWidth, rhs.maxWidth) && MessagesPigeonInternal.deepEquals(lhs.timeMs, rhs.timeMs) && MessagesPigeonInternal.deepEquals(lhs.quality, rhs.quality) + return MessagesPigeonInternal.deepEquals(lhs.video, rhs.video) && MessagesPigeonInternal.deepEquals(lhs.sourceKind, rhs.sourceKind) && MessagesPigeonInternal.deepEquals(lhs.headers, rhs.headers) && MessagesPigeonInternal.deepEquals(lhs.format, rhs.format) && MessagesPigeonInternal.deepEquals(lhs.maxHeight, rhs.maxHeight) && MessagesPigeonInternal.deepEquals(lhs.maxWidth, rhs.maxWidth) && MessagesPigeonInternal.deepEquals(lhs.timeMs, rhs.timeMs) && MessagesPigeonInternal.deepEquals(lhs.quality, rhs.quality) } func hash(into hasher: inout Hasher) { hasher.combine("ThumbnailRequest") MessagesPigeonInternal.deepHash(value: video, hasher: &hasher) + MessagesPigeonInternal.deepHash(value: sourceKind, hasher: &hasher) MessagesPigeonInternal.deepHash(value: headers, hasher: &hasher) MessagesPigeonInternal.deepHash(value: format, hasher: &hasher) MessagesPigeonInternal.deepHash(value: maxHeight, hasher: &hasher) @@ -254,7 +270,7 @@ struct ThumbnailRequest: Hashable, CustomStringConvertible { } public var description: String { - return "ThumbnailRequest(video: \(String(describing: video)), headers: \(String(describing: headers)), format: \(String(describing: format)), maxHeight: \(String(describing: maxHeight)), maxWidth: \(String(describing: maxWidth)), timeMs: \(String(describing: timeMs)), quality: \(String(describing: quality)))" + return "ThumbnailRequest(video: \(String(describing: video)), sourceKind: \(String(describing: sourceKind)), headers: \(String(describing: headers)), format: \(String(describing: format)), maxHeight: \(String(describing: maxHeight)), maxWidth: \(String(describing: maxWidth)), timeMs: \(String(describing: timeMs)), quality: \(String(describing: quality)))" } } @@ -268,6 +284,12 @@ private class MessagesPigeonCodecReader: FlutterStandardReader { } return nil case 130: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return ThumbnailSourceKind(rawValue: enumResultAsInt) + } + return nil + case 131: return ThumbnailRequest.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) @@ -280,8 +302,11 @@ private class MessagesPigeonCodecWriter: FlutterStandardWriter { if let value = value as? ThumbnailFormat { super.writeByte(129) super.writeValue(value.rawValue) - } else if let value = value as? ThumbnailRequest { + } else if let value = value as? ThumbnailSourceKind { super.writeByte(130) + super.writeValue(value.rawValue) + } else if let value = value as? ThumbnailRequest { + super.writeByte(131) super.writeValue(value.toList()) } else { super.writeValue(value) diff --git a/packages/stream_thumbnail/macos/stream_thumbnail/Sources/stream_thumbnail/StreamThumbnailPlugin.swift b/packages/stream_thumbnail/macos/stream_thumbnail/Sources/stream_thumbnail/StreamThumbnailPlugin.swift index 736357cf..fd0ae760 100644 --- a/packages/stream_thumbnail/macos/stream_thumbnail/Sources/stream_thumbnail/StreamThumbnailPlugin.swift +++ b/packages/stream_thumbnail/macos/stream_thumbnail/Sources/stream_thumbnail/StreamThumbnailPlugin.swift @@ -3,11 +3,12 @@ import Cocoa import FlutterMacOS import libwebp -/// A generation failure that couldn't produce a frame/encode, or a failure -/// writing the encoded thumbnail to disk. +/// A generation failure that couldn't produce a frame/encode, a failure +/// writing the encoded thumbnail to disk, or a video this platform won't open. private enum ThumbnailError: Error { case generationFailed case writeFailed(NSError) + case unsupportedSource(String) } public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHostApi { @@ -48,6 +49,8 @@ public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHost case ThumbnailError.generationFailed: return PigeonError( code: "THUMBNAIL_ERROR", message: "Failed to generate a thumbnail for the video.", details: nil) + case ThumbnailError.unsupportedSource(let message): + return PigeonError(code: "UNSUPPORTED_SOURCE", message: message, details: nil) case ThumbnailError.writeFailed(let nsError): return PigeonError(code: "Error \(nsError.code)", message: nsError.domain, details: nsError.localizedDescription) default: @@ -55,7 +58,24 @@ public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHost } } - private static func videoURL(for video: String) throws -> URL { + private static func videoURL(for request: ThumbnailRequest) throws -> URL { + switch request.sourceKind { + case .network: + guard let url = URL(string: request.video), + let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", + let host = url.host, !host.isEmpty + else { + throw ThumbnailError.unsupportedSource("A network video must be an http or https URL.") + } + return url + case .file: + return fileURL(for: request.video) + case .contentUri: + throw ThumbnailError.unsupportedSource("Content URIs are only supported on Android.") + } + } + + private static func fileURL(for video: String) -> URL { if video.hasPrefix("file://") { // Parsed as a URL first, so percent-encoding is decoded: `file:///tmp/a%20b.mp4` // names `a b.mp4`, not a literal `a%20b.mp4`. The raw path is the fallback for @@ -79,12 +99,8 @@ public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHost var path = String(video.dropFirst(7)) if path.hasPrefix("localhost/") { path = String(path.dropFirst(9)) } return URL(fileURLWithPath: path) - } else if video.hasPrefix("/") { - return URL(fileURLWithPath: video) - } else if let url = URL(string: video) { - return url } - throw ThumbnailError.generationFailed + return URL(fileURLWithPath: video) } private static func writeThumbnailFile(request: ThumbnailRequest) throws -> String { @@ -96,7 +112,7 @@ public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHost .appendingPathComponent("stream_thumbnail", isDirectory: true) .appendingPathComponent(UUID().uuidString, isDirectory: true) - let stem = try videoURL(for: request.video).deletingPathExtension().lastPathComponent + let stem = try videoURL(for: request).deletingPathExtension().lastPathComponent let thumbnailURL = outputDir .appendingPathComponent(stem.isEmpty ? "thumbnail" : stem) .appendingPathExtension(fileExtension(for: request.format)) @@ -112,7 +128,7 @@ public class StreamThumbnailPlugin: NSObject, FlutterPlugin, StreamThumbnailHost } private static func generateThumbnailData(request: ThumbnailRequest) throws -> Data { - let url = try videoURL(for: request.video) + let url = try videoURL(for: request) var options: [String: Any]? if let headers = request.headers, !headers.isEmpty { diff --git a/packages/stream_thumbnail/pigeons/messages.dart b/packages/stream_thumbnail/pigeons/messages.dart index 782d1007..8e8dc652 100644 --- a/packages/stream_thumbnail/pigeons/messages.dart +++ b/packages/stream_thumbnail/pigeons/messages.dart @@ -22,10 +22,18 @@ import 'package:pigeon/pigeon.dart'; /// Wire representation of the image format for a generated thumbnail. enum ThumbnailFormat { jpeg, png, webp } +/// Where [ThumbnailRequest.video] is read from, and so how it may be opened. +/// +/// `network` must only be fetched over http or https, `file` must only be +/// opened as a local path, and `contentUri` only through an Android content +/// resolver. +enum ThumbnailSourceKind { network, file, contentUri } + /// A single thumbnail generation request sent to the native platform. class ThumbnailRequest { ThumbnailRequest({ required this.video, + required this.sourceKind, required this.headers, required this.format, required this.maxHeight, @@ -35,6 +43,7 @@ class ThumbnailRequest { }); final String video; + final ThumbnailSourceKind sourceKind; final Map? headers; final ThumbnailFormat format; final int maxHeight; diff --git a/packages/stream_thumbnail/test/stream_thumbnail_source_test.dart b/packages/stream_thumbnail/test/stream_thumbnail_source_test.dart new file mode 100644 index 00000000..4e2ac0d9 --- /dev/null +++ b/packages/stream_thumbnail/test/stream_thumbnail_source_test.dart @@ -0,0 +1,51 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stream_thumbnail/stream_thumbnail.dart'; + +void main() { + test('file rejects an empty path', () { + expect(() => StreamThumbnailSource.file(''), throwsA(isA())); + }); + + test('network sources with the same headers in any order are equal', () { + final url = Uri.parse('https://cdn.example.com/a.mp4'); + final first = StreamThumbnailSource.network(url, headers: const {'a': '1', 'b': '2'}); + final second = StreamThumbnailSource.network(url, headers: const {'b': '2', 'a': '1'}); + + expect(first, second); + expect(first.hashCode, second.hashCode); + }); + + test('a network source keeps its headers when the map it was given changes', () { + final headers = {'a': '1'}; + final source = StreamThumbnailSource.network(Uri.parse('https://cdn.example.com/a.mp4'), headers: headers); + final hashCode = source.hashCode; + + headers['b'] = '2'; + + expect(source.headers, {'a': '1'}); + expect(source.hashCode, hashCode); + }); + + test('network sources with different headers are not equal', () { + final url = Uri.parse('https://cdn.example.com/a.mp4'); + + expect(StreamThumbnailSource.network(url), isNot(StreamThumbnailSource.network(url, headers: const {'a': '1'}))); + }); + + test('file sources with different paths are not equal', () { + expect(StreamThumbnailSource.file('/a.mp4'), isNot(StreamThumbnailSource.file('/b.mp4'))); + }); + + test('a file source is not equal to a content URI source with the same location', () { + expect( + StreamThumbnailSource.file('content://media/1'), + isNot(StreamThumbnailSource.contentUri(Uri.parse('content://media/1'))), + ); + }); + + test('toString shows the kind and the URL without its query', () { + final source = StreamThumbnailSource.network(Uri.parse('https://cdn.example.com/a.mp4?w=640')); + + expect(source.toString(), 'StreamThumbnailSource.network(https://cdn.example.com/a.mp4)'); + }); +} diff --git a/packages/stream_thumbnail/test/stream_thumbnail_test.dart b/packages/stream_thumbnail/test/stream_thumbnail_test.dart index 4ee847ba..e443cf20 100644 --- a/packages/stream_thumbnail/test/stream_thumbnail_test.dart +++ b/packages/stream_thumbnail/test/stream_thumbnail_test.dart @@ -10,6 +10,7 @@ import 'package:stream_thumbnail/src/stream_thumbnail.dart'; import 'package:stream_thumbnail/src/stream_thumbnail_format.dart'; import 'package:stream_thumbnail/src/stream_thumbnail_method_channel.dart'; import 'package:stream_thumbnail/src/stream_thumbnail_platform.dart'; +import 'package:stream_thumbnail/src/stream_thumbnail_source.dart'; /// A fake platform that records the last call it received and returns canned /// results. Extending [StreamThumbnailPlatform] inherits its token, so it @@ -39,8 +40,7 @@ class FakeStreamThumbnailPlatform extends StreamThumbnailPlatform { @override Future thumbnailData({ - required String video, - required Map? headers, + required StreamThumbnailSource source, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -48,8 +48,7 @@ class FakeStreamThumbnailPlatform extends StreamThumbnailPlatform { required int quality, }) async { lastDataCall = { - 'video': video, - 'headers': headers, + 'source': source, 'imageFormat': imageFormat, 'maxHeight': maxHeight, 'maxWidth': maxWidth, @@ -61,8 +60,7 @@ class FakeStreamThumbnailPlatform extends StreamThumbnailPlatform { @override Future thumbnailFile({ - required String video, - required Map? headers, + required StreamThumbnailSource source, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -70,7 +68,7 @@ class FakeStreamThumbnailPlatform extends StreamThumbnailPlatform { required int quality, }) async { lastFileCall = { - 'video': video, + 'source': source, 'imageFormat': imageFormat, }; return _file; @@ -78,8 +76,7 @@ class FakeStreamThumbnailPlatform extends StreamThumbnailPlatform { @override Future> thumbnailFiles({ - required List videos, - required Map? headers, + required List sources, required StreamThumbnailFormat imageFormat, required int maxHeight, required int maxWidth, @@ -88,7 +85,7 @@ class FakeStreamThumbnailPlatform extends StreamThumbnailPlatform { }) async { _filesCalled = true; lastFilesCall = { - 'videos': videos, + 'sources': sources, 'imageFormat': imageFormat, }; return []; @@ -116,6 +113,7 @@ void main() { registerFallbackValue( ThumbnailRequest( video: '', + sourceKind: ThumbnailSourceKind.file, format: ThumbnailFormat.png, maxHeight: 0, maxWidth: 0, @@ -126,10 +124,12 @@ void main() { }); group('StreamThumbnail', () { + final video = StreamThumbnailSource.file('/videos/a.mp4'); + test('thumbnailData forwards to the platform and returns its bytes', () async { final fake = useFakePlatform(); - final result = await StreamThumbnail.thumbnailData(video: 'a.mp4'); + final result = await StreamThumbnail.thumbnailData(source: video); expect(result, same(fake.data)); }); @@ -137,11 +137,10 @@ void main() { test('thumbnailData applies the documented default options', () async { final fake = useFakePlatform(); - await StreamThumbnail.thumbnailData(video: 'a.mp4'); + await StreamThumbnail.thumbnailData(source: video); expect(fake.lastDataCall, { - 'video': 'a.mp4', - 'headers': null, + 'source': video, 'imageFormat': StreamThumbnailFormat.png, 'maxHeight': 0, 'maxWidth': 0, @@ -153,45 +152,95 @@ void main() { test('thumbnailFile forwards to the platform and returns its file', () async { final fake = useFakePlatform(); - final result = await StreamThumbnail.thumbnailFile(video: 'a.mp4'); + final result = await StreamThumbnail.thumbnailFile(source: video); expect(result, same(fake.file)); - expect(fake.lastFileCall?['video'], 'a.mp4'); + expect(fake.lastFileCall?['source'], video); }); - test('thumbnailFiles returns an empty list without hitting the platform for no videos', () async { + test('thumbnailFiles returns an empty list without hitting the platform for no sources', () async { final fake = useFakePlatform(); - final result = await StreamThumbnail.thumbnailFiles(videos: []); + final result = await StreamThumbnail.thumbnailFiles(sources: []); expect(result, isEmpty); expect(fake.filesCalled, isFalse); }); - test('thumbnailFiles forwards every video to the platform', () async { + test('thumbnailFiles forwards every source to the platform', () async { final fake = useFakePlatform(); + final other = StreamThumbnailSource.network(Uri.parse('https://cdn.example.com/b.mp4')); await StreamThumbnail.thumbnailFiles( - videos: ['a.mp4', 'b.mp4'], + sources: [video, other], imageFormat: StreamThumbnailFormat.webp, ); expect(fake.lastFilesCall, { - 'videos': ['a.mp4', 'b.mp4'], + 'sources': [video, other], 'imageFormat': StreamThumbnailFormat.webp, }); }); + }); + + group('StreamThumbnail with an unsupported source', () { + final unsupported = StreamThumbnailSource.network(Uri.parse('ftp://example.com/a.mp4')); + final isUnsupported = throwsA(isA().having((e) => e.code, 'code', 'UNSUPPORTED_SOURCE')); + + for (final source in [ + unsupported, + StreamThumbnailSource.network(Uri.parse('file:///videos/a.mp4')), + StreamThumbnailSource.network(Uri.parse('https:/a.mp4')), + StreamThumbnailSource.contentUri(Uri.parse('file:///videos/a.mp4')), + StreamThumbnailSource.file('https://cdn.example.com/a.mp4'), + StreamThumbnailSource.file('//example.com/share/a.mp4'), + ]) { + test('thumbnailData fails for $source without reaching the platform', () async { + final fake = useFakePlatform(); + + await expectLater(StreamThumbnail.thumbnailData(source: source), isUnsupported); + expect(fake.lastDataCall, isNull); + }); + } - test('thumbnailData rejects an empty video path', () { - useFakePlatform(); + test('thumbnailFile fails without reaching the platform', () async { + final fake = useFakePlatform(); + + await expectLater(StreamThumbnail.thumbnailFile(source: unsupported), isUnsupported); + expect(fake.lastFileCall, isNull); + }); - expect( - () => StreamThumbnail.thumbnailData(video: ''), - throwsA(isA()), + test('thumbnailFiles fails without reaching the platform if any source is unsupported', () async { + final fake = useFakePlatform(); + + await expectLater( + StreamThumbnail.thumbnailFiles(sources: [StreamThumbnailSource.file('/videos/a.mp4'), unsupported]), + isUnsupported, ); + expect(fake.filesCalled, isFalse); }); }); + group('StreamThumbnail with a supported source', () { + for (final source in [ + StreamThumbnailSource.network(Uri.parse('http://cdn.example.com/a.mp4')), + StreamThumbnailSource.network(Uri.parse('HTTPS://cdn.example.com/b.mp4')), + StreamThumbnailSource.file('/videos/a.mp4'), + StreamThumbnailSource.file('file:///videos/a.mp4'), + StreamThumbnailSource.file(r'C:\videos\a.mp4'), + StreamThumbnailSource.file('C:/videos/a.mp4'), + StreamThumbnailSource.file('blob:https://example.com/0f8e'), + ]) { + test('thumbnailData forwards $source to the platform', () async { + final fake = useFakePlatform(); + + await StreamThumbnail.thumbnailData(source: source); + + expect(fake.lastDataCall?['source'], source); + }); + } + }); + group('MethodChannelStreamThumbnail', () { late MockStreamThumbnailHostApi hostApi; late MethodChannelStreamThumbnail channel; @@ -206,8 +255,7 @@ void main() { when(() => hostApi.thumbnailData(any())).thenAnswer((_) async => data); final result = await channel.thumbnailData( - video: 'a.mp4', - headers: null, + source: StreamThumbnailSource.file('a.mp4'), imageFormat: StreamThumbnailFormat.webp, maxHeight: 10, maxWidth: 20, @@ -218,6 +266,7 @@ void main() { expect(result, data); final request = verify(() => hostApi.thumbnailData(captureAny())).captured.single as ThumbnailRequest; expect(request.video, 'a.mp4'); + expect(request.sourceKind, ThumbnailSourceKind.file); expect(request.format, ThumbnailFormat.webp); expect(request.maxHeight, 10); expect(request.maxWidth, 20); @@ -229,8 +278,7 @@ void main() { when(() => hostApi.thumbnailFile(any())).thenAnswer((_) async => '/tmp/thumb.png'); final result = await channel.thumbnailFile( - video: 'a.mp4', - headers: null, + source: StreamThumbnailSource.file('a.mp4'), imageFormat: StreamThumbnailFormat.png, maxHeight: 0, maxWidth: 0, @@ -247,8 +295,7 @@ void main() { await expectLater( channel.thumbnailData( - video: 'a.mp4', - headers: null, + source: StreamThumbnailSource.file('a.mp4'), imageFormat: StreamThumbnailFormat.png, maxHeight: 0, maxWidth: 0, @@ -264,8 +311,9 @@ void main() { when(() => hostApi.thumbnailFile(any())).thenAnswer((_) async => paths[index++]); final result = await channel.thumbnailFiles( - videos: ['a.mp4', 'b.mp4', 'c.mp4'], - headers: null, + sources: [ + for (final v in ['a.mp4', 'b.mp4', 'c.mp4']) StreamThumbnailSource.file(v), + ], imageFormat: StreamThumbnailFormat.png, maxHeight: 0, maxWidth: 0, @@ -288,8 +336,9 @@ void main() { await expectLater( channel.thumbnailFiles( - videos: ['a.mp4', 'b.mp4', 'c.mp4'], - headers: null, + sources: [ + for (final v in ['a.mp4', 'b.mp4', 'c.mp4']) StreamThumbnailSource.file(v), + ], imageFormat: StreamThumbnailFormat.png, maxHeight: 0, maxWidth: 0, @@ -309,8 +358,9 @@ void main() { }); final result = channel.thumbnailFiles( - videos: ['a.mp4', 'b.mp4', 'c.mp4'], - headers: null, + sources: [ + for (final v in ['a.mp4', 'b.mp4', 'c.mp4']) StreamThumbnailSource.file(v), + ], imageFormat: StreamThumbnailFormat.png, maxHeight: 0, maxWidth: 0, @@ -334,14 +384,67 @@ void main() { expect((await result).map((file) => file.path), ['/a.png', '/b.png', '/c.png']); }); + test('a network source is sent as network with its URL and headers', () async { + when(() => hostApi.thumbnailData(any())).thenAnswer((_) async => Uint8List(0)); + + await channel.thumbnailData( + source: StreamThumbnailSource.network( + Uri.parse('https://cdn.example.com/a.mp4?w=640'), + headers: const {'X-Client': 'example'}, + ), + imageFormat: StreamThumbnailFormat.png, + maxHeight: 0, + maxWidth: 0, + quality: 10, + ); + + final request = verify(() => hostApi.thumbnailData(captureAny())).captured.single as ThumbnailRequest; + expect(request.sourceKind, ThumbnailSourceKind.network); + expect(request.video, 'https://cdn.example.com/a.mp4?w=640'); + expect(request.headers, const {'X-Client': 'example'}); + }); + + test('a file source is sent as file with its path', () async { + when(() => hostApi.thumbnailData(any())).thenAnswer((_) async => Uint8List(0)); + + await channel.thumbnailData( + source: StreamThumbnailSource.file('/videos/a.mp4'), + imageFormat: StreamThumbnailFormat.png, + maxHeight: 0, + maxWidth: 0, + quality: 10, + ); + + final request = verify(() => hostApi.thumbnailData(captureAny())).captured.single as ThumbnailRequest; + expect(request.sourceKind, ThumbnailSourceKind.file); + expect(request.video, '/videos/a.mp4'); + expect(request.headers, isNull); + }); + + test('a content URI source is sent as contentUri with its URI', () async { + when(() => hostApi.thumbnailData(any())).thenAnswer((_) async => Uint8List(0)); + + await channel.thumbnailData( + source: StreamThumbnailSource.contentUri(Uri.parse('content://media/1')), + imageFormat: StreamThumbnailFormat.png, + maxHeight: 0, + maxWidth: 0, + quality: 10, + ); + + final request = verify(() => hostApi.thumbnailData(captureAny())).captured.single as ThumbnailRequest; + expect(request.sourceKind, ThumbnailSourceKind.contentUri); + expect(request.video, 'content://media/1'); + expect(request.headers, isNull); + }); + test('a null timeMs is sent as -1 on Android', () async { debugDefaultTargetPlatformOverride = TargetPlatform.android; addTearDown(() => debugDefaultTargetPlatformOverride = null); when(() => hostApi.thumbnailData(any())).thenAnswer((_) async => Uint8List(0)); await channel.thumbnailData( - video: 'a.mp4', - headers: null, + source: StreamThumbnailSource.file('a.mp4'), imageFormat: StreamThumbnailFormat.png, maxHeight: 0, maxWidth: 0, @@ -358,8 +461,7 @@ void main() { when(() => hostApi.thumbnailData(any())).thenAnswer((_) async => Uint8List(0)); await channel.thumbnailData( - video: 'a.mp4', - headers: null, + source: StreamThumbnailSource.file('a.mp4'), imageFormat: StreamThumbnailFormat.png, maxHeight: 0, maxWidth: 0, diff --git a/packages/stream_thumbnail/windows/pigeon/messages.g.cpp b/packages/stream_thumbnail/windows/pigeon/messages.g.cpp index 1fe8c57f..c1a0bb1b 100644 --- a/packages/stream_thumbnail/windows/pigeon/messages.g.cpp +++ b/packages/stream_thumbnail/windows/pigeon/messages.g.cpp @@ -323,12 +323,14 @@ std::string PigeonInternalToString(const ::flutter::EncodableValue& v) { ThumbnailRequest::ThumbnailRequest( const std::string& video, + const ThumbnailSourceKind& source_kind, const ThumbnailFormat& format, int64_t max_height, int64_t max_width, int64_t time_ms, int64_t quality) : video_(video), + source_kind_(source_kind), format_(format), max_height_(max_height), max_width_(max_width), @@ -337,6 +339,7 @@ ThumbnailRequest::ThumbnailRequest( ThumbnailRequest::ThumbnailRequest( const std::string& video, + const ThumbnailSourceKind& source_kind, const EncodableMap* headers, const ThumbnailFormat& format, int64_t max_height, @@ -344,6 +347,7 @@ ThumbnailRequest::ThumbnailRequest( int64_t time_ms, int64_t quality) : video_(video), + source_kind_(source_kind), headers_(headers ? std::optional(*headers) : std::nullopt), format_(format), max_height_(max_height), @@ -360,6 +364,15 @@ void ThumbnailRequest::set_video(std::string_view value_arg) { } +const ThumbnailSourceKind& ThumbnailRequest::source_kind() const { + return source_kind_; +} + +void ThumbnailRequest::set_source_kind(const ThumbnailSourceKind& value_arg) { + source_kind_ = value_arg; +} + + const EncodableMap* ThumbnailRequest::headers() const { return headers_ ? &(*headers_) : nullptr; } @@ -420,8 +433,9 @@ void ThumbnailRequest::set_quality(int64_t value_arg) { EncodableList ThumbnailRequest::ToEncodableList() const { EncodableList list; - list.reserve(7); + list.reserve(8); list.push_back(EncodableValue(video_)); + list.push_back(CustomEncodableValue(source_kind_)); list.push_back(headers_ ? EncodableValue(*headers_) : EncodableValue()); list.push_back(CustomEncodableValue(format_)); list.push_back(EncodableValue(max_height_)); @@ -434,12 +448,13 @@ EncodableList ThumbnailRequest::ToEncodableList() const { ThumbnailRequest ThumbnailRequest::FromEncodableList(const EncodableList& list) { ThumbnailRequest decoded( std::get(list[0]), - std::any_cast(std::get(list[2])), - std::get(list[3]), + std::any_cast(std::get(list[1])), + std::any_cast(std::get(list[3])), std::get(list[4]), std::get(list[5]), - std::get(list[6])); - auto& encodable_headers = list[1]; + std::get(list[6]), + std::get(list[7])); + auto& encodable_headers = list[2]; if (!encodable_headers.IsNull()) { decoded.set_headers(std::get(encodable_headers)); } @@ -447,7 +462,7 @@ ThumbnailRequest ThumbnailRequest::FromEncodableList(const EncodableList& list) } bool ThumbnailRequest::operator==(const ThumbnailRequest& other) const { - return PigeonInternalDeepEquals(video_, other.video_) && PigeonInternalDeepEquals(headers_, other.headers_) && PigeonInternalDeepEquals(format_, other.format_) && PigeonInternalDeepEquals(max_height_, other.max_height_) && PigeonInternalDeepEquals(max_width_, other.max_width_) && PigeonInternalDeepEquals(time_ms_, other.time_ms_) && PigeonInternalDeepEquals(quality_, other.quality_); + return PigeonInternalDeepEquals(video_, other.video_) && PigeonInternalDeepEquals(source_kind_, other.source_kind_) && PigeonInternalDeepEquals(headers_, other.headers_) && PigeonInternalDeepEquals(format_, other.format_) && PigeonInternalDeepEquals(max_height_, other.max_height_) && PigeonInternalDeepEquals(max_width_, other.max_width_) && PigeonInternalDeepEquals(time_ms_, other.time_ms_) && PigeonInternalDeepEquals(quality_, other.quality_); } bool ThumbnailRequest::operator!=(const ThumbnailRequest& other) const { @@ -457,6 +472,7 @@ bool ThumbnailRequest::operator!=(const ThumbnailRequest& other) const { size_t ThumbnailRequest::Hash() const { size_t result = 1; result = result * 31 + PigeonInternalDeepHash(video_); + result = result * 31 + PigeonInternalDeepHash(source_kind_); result = result * 31 + PigeonInternalDeepHash(headers_); result = result * 31 + PigeonInternalDeepHash(format_); result = result * 31 + PigeonInternalDeepHash(max_height_); @@ -472,6 +488,8 @@ std::ostream& operator<<( os << "ThumbnailRequest("; os << "video: "; os << PigeonInternalToString(obj.video_); + os << ", source_kind: "; + os << PigeonInternalToString(obj.source_kind_); os << ", headers: "; if (obj.headers_) { os << PigeonInternalToString(*obj.headers_); @@ -510,6 +528,11 @@ EncodableValue PigeonInternalCodecSerializer::ReadValueOfType( return encodable_enum_arg.IsNull() ? EncodableValue() : CustomEncodableValue(static_cast(enum_arg_value)); } case 130: { + const auto& encodable_enum_arg = ReadValue(stream); + const int64_t enum_arg_value = encodable_enum_arg.IsNull() ? 0 : encodable_enum_arg.LongValue(); + return encodable_enum_arg.IsNull() ? EncodableValue() : CustomEncodableValue(static_cast(enum_arg_value)); + } + case 131: { return CustomEncodableValue(ThumbnailRequest::FromEncodableList(std::get(ReadValue(stream)))); } default: @@ -526,8 +549,13 @@ void PigeonInternalCodecSerializer::WriteValue( WriteValue(EncodableValue(static_cast(std::any_cast(*custom_value))), stream); return; } - if (custom_value->type() == typeid(ThumbnailRequest)) { + if (custom_value->type() == typeid(ThumbnailSourceKind)) { stream->WriteByte(130); + WriteValue(EncodableValue(static_cast(std::any_cast(*custom_value))), stream); + return; + } + if (custom_value->type() == typeid(ThumbnailRequest)) { + stream->WriteByte(131); WriteValue(EncodableValue(std::any_cast(*custom_value).ToEncodableList()), stream); return; } diff --git a/packages/stream_thumbnail/windows/pigeon/messages.g.h b/packages/stream_thumbnail/windows/pigeon/messages.g.h index 980cd455..212efb4e 100644 --- a/packages/stream_thumbnail/windows/pigeon/messages.g.h +++ b/packages/stream_thumbnail/windows/pigeon/messages.g.h @@ -64,6 +64,17 @@ enum class ThumbnailFormat { kWebp = 2 }; +// Where [ThumbnailRequest.video] is read from, and so how it may be opened. +// +// `network` must only be fetched over http or https, `file` must only be +// opened as a local path, and `contentUri` only through an Android content +// resolver. +enum class ThumbnailSourceKind { + kNetwork = 0, + kFile = 1, + kContentUri = 2 +}; + // A single thumbnail generation request sent to the native platform. // @@ -73,6 +84,7 @@ class ThumbnailRequest { // Constructs an object setting all non-nullable fields. explicit ThumbnailRequest( const std::string& video, + const ThumbnailSourceKind& source_kind, const ThumbnailFormat& format, int64_t max_height, int64_t max_width, @@ -82,6 +94,7 @@ class ThumbnailRequest { // Constructs an object setting all fields. explicit ThumbnailRequest( const std::string& video, + const ThumbnailSourceKind& source_kind, const ::flutter::EncodableMap* headers, const ThumbnailFormat& format, int64_t max_height, @@ -92,6 +105,9 @@ class ThumbnailRequest { const std::string& video() const; void set_video(std::string_view value_arg); + const ThumbnailSourceKind& source_kind() const; + void set_source_kind(const ThumbnailSourceKind& value_arg); + const ::flutter::EncodableMap* headers() const; void set_headers(const ::flutter::EncodableMap* value_arg); void set_headers(const ::flutter::EncodableMap& value_arg); @@ -123,6 +139,7 @@ class ThumbnailRequest { friend class StreamThumbnailHostApi; friend class PigeonInternalCodecSerializer; std::string video_; + ThumbnailSourceKind source_kind_; std::optional<::flutter::EncodableMap> headers_; ThumbnailFormat format_; int64_t max_height_; diff --git a/packages/stream_thumbnail/windows/stream_thumbnail_plugin.cpp b/packages/stream_thumbnail/windows/stream_thumbnail_plugin.cpp index 02921964..aad58d60 100644 --- a/packages/stream_thumbnail/windows/stream_thumbnail_plugin.cpp +++ b/packages/stream_thumbnail/windows/stream_thumbnail_plugin.cpp @@ -10,11 +10,13 @@ #include #include #include +#include #include #include #include +#include #include #include #include @@ -25,6 +27,7 @@ using stream_thumbnail_windows::ErrorOr; using stream_thumbnail_windows::FlutterError; using stream_thumbnail_windows::ThumbnailFormat; using stream_thumbnail_windows::ThumbnailRequest; +using stream_thumbnail_windows::ThumbnailSourceKind; namespace stream_thumbnail { @@ -66,6 +69,41 @@ std::string VideoPath(const std::string &video) { return video; } +bool HasHttpScheme(const std::string &video) { + return _strnicmp(video.c_str(), "http://", 7) == 0 || _strnicmp(video.c_str(), "https://", 8) == 0; +} + +// An absolute path on a local drive, such as `C:\videos\a.mp4`. Network shares +// (`\\host\share`, `//host/share`), device paths and relative paths don't qualify. +bool IsDriveLetterPath(const std::string &path) { + return path.size() >= 3 && std::isalpha(static_cast(path[0])) && path[1] == ':' && + (path[2] == '\\' || path[2] == '/'); +} + +// The URL or path Media Foundation is given for `video`. Media Foundation picks a +// scheme handler from whatever it is handed, so a network video must name http(s) +// and a file must be a path on a local drive. +std::string ResolveInput(const std::string &video, ThumbnailSourceKind kind) { + switch (kind) { + case ThumbnailSourceKind::kNetwork: + if (!HasHttpScheme(video)) { + throw ThumbnailException("UNSUPPORTED_SOURCE", "A network video must be an http or https URL."); + } + return video; + case ThumbnailSourceKind::kFile: { + std::string path = VideoPath(video); + if (path.size() >= 4 && path[0] == '/' && IsDriveLetterPath(path.substr(1))) path.erase(0, 1); + if (!IsDriveLetterPath(path)) { + throw ThumbnailException("UNSUPPORTED_SOURCE", "A file video must be an absolute path on a local drive."); + } + return path; + } + case ThumbnailSourceKind::kContentUri: + throw ThumbnailException("UNSUPPORTED_SOURCE", "Content URIs are only supported on Android."); + } + throw ThumbnailException("UNSUPPORTED_SOURCE", "Unknown video source."); +} + std::string FileExtension(ThumbnailFormat format) { switch (format) { case ThumbnailFormat::kJpeg: @@ -86,12 +124,12 @@ struct DecodedFrame { LONG stride = 0; }; -// Decodes a single frame from `video` at `time_ms` via Media Foundation. +// Decodes a single frame from `input` at `time_ms` via Media Foundation. // // NOTE: unlike AVFoundation (iOS/macOS) and MediaMetadataRetriever (Android), // IMFSourceReader has no simple way to attach custom HTTP headers to a remote // URL, so `request.headers()` is not applied on Windows. -DecodedFrame DecodeFrame(const std::string &video, int64_t time_ms) { +DecodedFrame DecodeFrame(const std::string &input, int64_t time_ms) { ComPtr attributes; ComPtr reader; ComPtr type; @@ -104,7 +142,7 @@ DecodedFrame DecodeFrame(const std::string &video, int64_t time_ms) { hr = attributes->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, TRUE); } - const std::wstring wide_path = Utf8ToWide(VideoPath(video)); + const std::wstring wide_path = Utf8ToWide(input); if (SUCCEEDED(hr)) { hr = MFCreateSourceReaderFromURL(wide_path.c_str(), attributes.Get(), &reader); } @@ -277,7 +315,7 @@ std::vector GenerateThumbnailData(const ThumbnailRequest &request) { throw ThumbnailException("UNSUPPORTED_FORMAT", "WebP is not yet supported on Windows."); } - const DecodedFrame frame = DecodeFrame(request.video(), request.time_ms()); + const DecodedFrame frame = DecodeFrame(ResolveInput(request.video(), request.source_kind()), request.time_ms()); ComPtr stream; HRESULT hr = CreateStreamOnHGlobal(nullptr, TRUE, &stream);