Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions packages/stream_thumbnail/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
26 changes: 19 additions & 7 deletions packages/stream_thumbnail/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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,
Expand All @@ -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,
);
Expand All @@ -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'),
],
);
```

Expand All @@ -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. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,13 +205,33 @@ 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.
*
* Generated class from Pigeon that represents data sent in messages.
*/
data class ThumbnailRequest (
val video: String,
val sourceKind: ThumbnailSourceKind,
val headers: Map<String, String>? = null,
val format: ThumbnailFormat,
val maxHeight: Long,
Expand All @@ -223,18 +243,20 @@ data class ThumbnailRequest (
companion object {
fun fromList(pigeonVar_list: List<Any?>): ThumbnailRequest {
val video = pigeonVar_list[0] as String
val headers = pigeonVar_list[1] as Map<String, String>?
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<String, String>?
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<Any?> {
return listOf(
video,
sourceKind,
headers,
format,
maxHeight,
Expand All @@ -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)
Expand All @@ -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() {
Expand All @@ -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<Any?>)?.let {
ThumbnailRequest.fromList(it)
}
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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()))
}
Expand All @@ -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(),
Expand Down Expand Up @@ -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<String, String>,
targetH: Int,
targetW: Int,
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Loading
Loading