react-native-video-processing 3.0.0-beta.1 → 3.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +56 -5
  2. package/android/src/main/java/com/shahenlibrary/videoprocessing/ColorMatrixEffect.kt +114 -0
  3. package/android/src/main/java/com/shahenlibrary/videoprocessing/ProcessPlan.kt +9 -0
  4. package/android/src/main/java/com/shahenlibrary/videoprocessing/ThumbnailGenerator.kt +25 -3
  5. package/android/src/main/java/com/shahenlibrary/videoprocessing/VideoProcessingModule.kt +1 -0
  6. package/android/src/main/java/com/shahenlibrary/videoprocessing/VideoProcessor.kt +10 -3
  7. package/ios/ColorMatrix.swift +36 -0
  8. package/ios/FrameRenderer.swift +11 -6
  9. package/ios/ProcessPlan.swift +5 -1
  10. package/ios/ThumbnailGenerator.swift +18 -1
  11. package/ios/VideoExporter.swift +1 -1
  12. package/lib/module/ProcessingBuilder.js +271 -0
  13. package/lib/module/ProcessingBuilder.js.map +1 -0
  14. package/lib/module/VideoProcessing.js +16 -1
  15. package/lib/module/VideoProcessing.js.map +1 -1
  16. package/lib/module/filters.js +142 -0
  17. package/lib/module/filters.js.map +1 -0
  18. package/lib/module/index.js +2 -0
  19. package/lib/module/index.js.map +1 -1
  20. package/lib/module/validation.js +18 -0
  21. package/lib/module/validation.js.map +1 -1
  22. package/lib/typescript/src/ProcessingBuilder.d.ts +56 -0
  23. package/lib/typescript/src/ProcessingBuilder.d.ts.map +1 -0
  24. package/lib/typescript/src/VideoProcessing.d.ts +2 -1
  25. package/lib/typescript/src/VideoProcessing.d.ts.map +1 -1
  26. package/lib/typescript/src/filters.d.ts +58 -0
  27. package/lib/typescript/src/filters.d.ts.map +1 -0
  28. package/lib/typescript/src/index.d.ts +2 -0
  29. package/lib/typescript/src/index.d.ts.map +1 -1
  30. package/lib/typescript/src/types.d.ts +37 -0
  31. package/lib/typescript/src/types.d.ts.map +1 -1
  32. package/lib/typescript/src/validation.d.ts +6 -1
  33. package/lib/typescript/src/validation.d.ts.map +1 -1
  34. package/package.json +1 -1
  35. package/src/ProcessingBuilder.ts +302 -0
  36. package/src/VideoProcessing.ts +19 -1
  37. package/src/filters.ts +195 -0
  38. package/src/index.tsx +2 -0
  39. package/src/types.ts +25 -0
  40. package/src/validation.ts +28 -2
package/README.md CHANGED
@@ -80,27 +80,78 @@ controller.abort(); // job rejects with code E_CANCELLED and partial output is d
80
80
 
81
81
  #### Combining operations
82
82
 
83
- `trim`, `crop`, `merge`, `reverse` and `boomerang` are shorthands for `process`, which plays a list of segments back to back in a single encode:
83
+ `ProcessingBuilder` puts several operations into one export:
84
+
85
+ ```ts
86
+ import { ProcessingBuilder, presets } from 'react-native-video-processing';
87
+
88
+ const { uri } = await new ProcessingBuilder(clip)
89
+ .trim(2, 8)
90
+ .crop({ x: 0, y: 280, width: 1080, height: 1080 })
91
+ .append(outro, (c) => c.trim(0, 2))
92
+ .filter(presets.vintage)
93
+ .resize({ width: 720 })
94
+ .bitrate(2_000_000)
95
+ .export({ onProgress: setProgress });
96
+ ```
97
+
98
+ - `trim`, `crop` and `reverse` change the most recently added clip. Calling `trim` or `crop` again narrows the earlier one: `trim(2, 8).trim(1, 3)` keeps seconds 3 to 5 of the source.
99
+ - `filter`, `resize`, `bitrate` and `removeAudio` apply to the whole result. Frames always go through crop, then filters, then scaling, whatever order you call the methods in; only the order of `filter` calls matters.
100
+ - `append` adds a clip, and `boomerang` adds the current clip played backwards.
101
+ - Every method returns a new builder, so a base edit can be branched, for example to preview several looks with `thumbnail(time)`.
102
+
103
+ `toSpec()` turns an edit into plain data that can be stored as JSON, and `ProcessingBuilder.fromSpec(spec)` reads it back. `process(spec)` runs a spec directly:
84
104
 
85
105
  ```ts
86
106
  import { process } from 'react-native-video-processing';
87
107
 
88
- await process(
89
- [
108
+ await process({
109
+ clips: [
90
110
  { source: intro, endTime: 2 },
91
111
  { source: clip, startTime: 5, endTime: 9, crop: { x: 0, y: 280, width: 1080, height: 1080 } },
92
112
  { source: clip, startTime: 5, endTime: 9, reverse: true },
93
113
  ],
94
- { width: 720, bitrate: 2_000_000 }
95
- );
114
+ filters: presets.warm,
115
+ width: 720,
116
+ bitrate: 2_000_000,
117
+ });
96
118
  ```
97
119
 
120
+ `trim`, `crop`, `merge`, `reverse` and `boomerang`, and the original `process(segments, options)` form, all still work and build the same edits.
121
+
98
122
  The output takes the size of the first segment (after cropping), fitted inside `width`/`height`. Later segments are letterboxed to that size.
99
123
 
100
124
  Crop rectangles are in display pixels with a top-left origin, so a portrait phone video is cropped the way it appears on screen.
101
125
 
102
126
  Reversed segments are silent. `boomerang` output is silent.
103
127
 
128
+ #### Filters
129
+
130
+ Colour filters go in `filters`, on any processing call and on thumbnails, so a filter picker can show previews that match the export:
131
+
132
+ ```ts
133
+ import { compress, getThumbnail, presets } from 'react-native-video-processing';
134
+
135
+ await compress(source, {
136
+ filters: [
137
+ { type: 'saturation', amount: -0.3 },
138
+ { type: 'contrast', amount: 0.2 },
139
+ ],
140
+ });
141
+
142
+ await compress(source, { filters: presets.vintage });
143
+
144
+ const preview = await getThumbnail(source, 1, { filters: presets.noir });
145
+ ```
146
+
147
+ | Filter | Options | Neutral value |
148
+ |---|---|---|
149
+ | `brightness`, `contrast`, `saturation` | `amount` from -1 to 1 | 0 |
150
+ | `hue` | `degrees` | 0 |
151
+ | `grayscale`, `sepia`, `invert` | `amount` from 0 to 1, default 1 | 0 |
152
+
153
+ The filters behave like CSS `filter()` functions and apply in order, after cropping. They're combined into a single colour matrix, so a long list costs no more than one filter. `presets` has `vintage`, `noir`, `fade`, `vivid` and `warm`, which are plain filter lists you can extend. `filterMatrix(filters)` returns the combined 4×5 matrix, for showing the same look elsewhere in your UI.
154
+
104
155
  #### Errors
105
156
 
106
157
  Rejections carry a `code`:
@@ -0,0 +1,114 @@
1
+ package com.shahenlibrary.videoprocessing
2
+
3
+ import android.content.Context
4
+ import android.opengl.GLES20
5
+ import androidx.annotation.OptIn
6
+ import androidx.media3.common.VideoFrameProcessingException
7
+ import androidx.media3.common.util.GlProgram
8
+ import androidx.media3.common.util.GlUtil
9
+ import androidx.media3.common.util.Size
10
+ import androidx.media3.common.util.UnstableApi
11
+ import androidx.media3.effect.BaseGlShaderProgram
12
+ import androidx.media3.effect.GlEffect
13
+
14
+ /**
15
+ * Applies the 4x5 row-major colour matrix from JS (`filterMatrix`) to the RGB channels. Custom
16
+ * shader programs receive SDR frames gamma-encoded, as stored, which is the space the matrix is
17
+ * defined in; Media3's own RgbMatrix works in linear light, so it isn't used here.
18
+ */
19
+ @OptIn(UnstableApi::class)
20
+ class ColorMatrixEffect(private val matrix: FloatArray) : GlEffect {
21
+ init {
22
+ require(matrix.size == 20) { "A colour matrix has 20 values, got ${matrix.size}" }
23
+ }
24
+
25
+ override fun toGlShaderProgram(context: Context, useHdr: Boolean): BaseGlShaderProgram =
26
+ ColorMatrixShaderProgram(useHdr, rgbMatrixColumnMajor(), rgbOffset())
27
+
28
+ /** GLSL matrices are column-major. */
29
+ private fun rgbMatrixColumnMajor(): FloatArray =
30
+ FloatArray(9) { index -> matrix[(index % 3) * 5 + index / 3] }
31
+
32
+ private fun rgbOffset(): FloatArray = floatArrayOf(matrix[4], matrix[9], matrix[14])
33
+
34
+ fun toAndroidColorMatrix(): android.graphics.ColorMatrix {
35
+ val scaled = matrix.copyOf()
36
+ for (row in 0 until 4) {
37
+ scaled[row * 5 + 4] *= 255f
38
+ }
39
+ return android.graphics.ColorMatrix(scaled)
40
+ }
41
+ }
42
+
43
+ @OptIn(UnstableApi::class)
44
+ private class ColorMatrixShaderProgram(
45
+ useHdr: Boolean,
46
+ rgbMatrix: FloatArray,
47
+ rgbOffset: FloatArray,
48
+ ) : BaseGlShaderProgram(/* useHighPrecisionColorComponents= */ useHdr, /* texturePoolCapacity= */ 1) {
49
+ private val glProgram: GlProgram
50
+
51
+ init {
52
+ try {
53
+ glProgram = GlProgram(VERTEX_SHADER, FRAGMENT_SHADER)
54
+ } catch (error: GlUtil.GlException) {
55
+ throw VideoFrameProcessingException(error)
56
+ }
57
+ glProgram.setBufferAttribute(
58
+ "aFramePosition",
59
+ GlUtil.getNormalizedCoordinateBounds(),
60
+ GlUtil.HOMOGENEOUS_COORDINATE_VECTOR_SIZE,
61
+ )
62
+ glProgram.setFloatsUniform("uRgbMatrix", rgbMatrix)
63
+ glProgram.setFloatsUniform("uRgbOffset", rgbOffset)
64
+ }
65
+
66
+ override fun configure(inputWidth: Int, inputHeight: Int): Size = Size(inputWidth, inputHeight)
67
+
68
+ override fun drawFrame(inputTexId: Int, presentationTimeUs: Long) {
69
+ try {
70
+ glProgram.use()
71
+ glProgram.setSamplerTexIdUniform("uTexSampler", inputTexId, /* texUnitIndex= */ 0)
72
+ glProgram.bindAttributesAndUniforms()
73
+ GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, /* first= */ 0, /* count= */ 4)
74
+ } catch (error: GlUtil.GlException) {
75
+ throw VideoFrameProcessingException(error, presentationTimeUs)
76
+ }
77
+ }
78
+
79
+ override fun release() {
80
+ super.release()
81
+ try {
82
+ glProgram.delete()
83
+ } catch (error: GlUtil.GlException) {
84
+ throw VideoFrameProcessingException(error)
85
+ }
86
+ }
87
+
88
+ private companion object {
89
+ const val VERTEX_SHADER = """
90
+ attribute vec4 aFramePosition;
91
+ varying vec2 vTexSamplingCoord;
92
+ void main() {
93
+ gl_Position = aFramePosition;
94
+ vTexSamplingCoord = aFramePosition.xy * 0.5 + 0.5;
95
+ }
96
+ """
97
+
98
+ const val FRAGMENT_SHADER = """
99
+ #ifdef GL_FRAGMENT_PRECISION_HIGH
100
+ precision highp float;
101
+ #else
102
+ precision mediump float;
103
+ #endif
104
+ uniform sampler2D uTexSampler;
105
+ uniform mat3 uRgbMatrix;
106
+ uniform vec3 uRgbOffset;
107
+ varying vec2 vTexSamplingCoord;
108
+ void main() {
109
+ vec4 color = texture2D(uTexSampler, vTexSamplingCoord);
110
+ gl_FragColor = vec4(clamp(uRgbMatrix * color.rgb + uRgbOffset, 0.0, 1.0), color.a);
111
+ }
112
+ """
113
+ }
114
+ }
@@ -17,6 +17,7 @@ data class OutputRequest(
17
17
  val height: Int?,
18
18
  val bitrate: Int?,
19
19
  val removeAudio: Boolean,
20
+ val colorMatrix: FloatArray?,
20
21
  )
21
22
 
22
23
  /** A segment once its source has been probed and its options checked against it. */
@@ -36,6 +37,7 @@ data class ProcessPlan(
36
37
  val height: Int,
37
38
  val bitrate: Int,
38
39
  val hasAudio: Boolean,
40
+ val colorMatrix: FloatArray?,
39
41
  )
40
42
 
41
43
  object ProcessPlanner {
@@ -64,6 +66,7 @@ object ProcessPlanner {
64
66
  height = map.optionalDouble("height")?.roundToInt(),
65
67
  bitrate = map.optionalDouble("bitrate")?.roundToInt(),
66
68
  removeAudio = map.hasKey("removeAudio") && map.getBoolean("removeAudio"),
69
+ colorMatrix = map.colorMatrix(),
67
70
  )
68
71
 
69
72
  fun plan(segments: List<Pair<SegmentRequest, VideoMetadata>>, output: OutputRequest): ProcessPlan {
@@ -85,6 +88,7 @@ object ProcessPlanner {
85
88
  outputHeight = height,
86
89
  ),
87
90
  hasAudio = hasForwardAudio && !output.removeAudio,
91
+ colorMatrix = output.colorMatrix,
88
92
  )
89
93
  }
90
94
 
@@ -98,3 +102,8 @@ object ProcessPlanner {
98
102
  private fun ReadableMap.optionalDouble(key: String): Double? =
99
103
  if (hasKey(key) && !isNull(key)) getDouble(key) else null
100
104
  }
105
+
106
+ fun ReadableMap.colorMatrix(): FloatArray? {
107
+ val values = if (hasKey("colorMatrix") && !isNull("colorMatrix")) getArray("colorMatrix") else null
108
+ return values?.let { array -> FloatArray(array.size()) { array.getDouble(it).toFloat() } }
109
+ }
@@ -2,8 +2,12 @@ package com.shahenlibrary.videoprocessing
2
2
 
3
3
  import android.content.Context
4
4
  import android.graphics.Bitmap
5
+ import android.graphics.Canvas
6
+ import android.graphics.ColorMatrixColorFilter
7
+ import android.graphics.Paint
5
8
  import android.media.MediaMetadataRetriever
6
9
  import android.net.Uri
10
+ import android.os.Build
7
11
  import java.io.File
8
12
  import java.util.UUID
9
13
  import kotlin.math.min
@@ -14,6 +18,7 @@ data class ThumbnailOptions(
14
18
  val maxHeight: Int?,
15
19
  val format: Bitmap.CompressFormat,
16
20
  val quality: Double,
21
+ val colorMatrix: FloatArray?,
17
22
  ) {
18
23
  val extension: String
19
24
  get() = if (format == Bitmap.CompressFormat.PNG) "png" else "jpg"
@@ -28,15 +33,16 @@ object ThumbnailGenerator {
28
33
  try {
29
34
  retriever.setDataSource(context, source)
30
35
  return times.map { time ->
31
- val frame = retriever.getFrameAtTime((time * 1_000_000).toLong(), MediaMetadataRetriever.OPTION_CLOSEST)
36
+ val frame = retriever.frameAt((time * 1_000_000).toLong())
32
37
  ?: throw VideoProcessingError(VideoProcessingError.PROCESSING, "No frame at ${time}s in $source")
33
38
  val scaled = scaleToFit(frame, options.maxWidth, options.maxHeight)
34
39
  if (scaled !== frame) {
35
40
  frame.recycle()
36
41
  }
42
+ val image = options.colorMatrix?.let { filtered(scaled, ColorMatrixEffect(it)).also { scaled.recycle() } } ?: scaled
37
43
  val file = File(directory, "${UUID.randomUUID()}.${options.extension}")
38
- file.outputStream().use { scaled.compress(options.format, (options.quality * 100).roundToInt(), it) }
39
- Thumbnail("file://${file.absolutePath}", time, scaled.width, scaled.height).also { scaled.recycle() }
44
+ file.outputStream().use { image.compress(options.format, (options.quality * 100).roundToInt(), it) }
45
+ Thumbnail("file://${file.absolutePath}", time, image.width, image.height).also { image.recycle() }
40
46
  }
41
47
  } catch (error: VideoProcessingError) {
42
48
  throw error
@@ -47,6 +53,22 @@ object ThumbnailGenerator {
47
53
  }
48
54
  }
49
55
 
56
+ /** Without BitmapParams the retriever returns RGB_565 frames, which band and shift colours by up to 8 levels. */
57
+ private fun MediaMetadataRetriever.frameAt(timeUs: Long): Bitmap? =
58
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
59
+ getFrameAtTime(timeUs, MediaMetadataRetriever.OPTION_CLOSEST, MediaMetadataRetriever.BitmapParams())
60
+ } else {
61
+ getFrameAtTime(timeUs, MediaMetadataRetriever.OPTION_CLOSEST)
62
+ }
63
+
64
+ /** Bitmaps hold gamma-encoded values, like the frames the export's shader sees. */
65
+ private fun filtered(source: Bitmap, effect: ColorMatrixEffect): Bitmap {
66
+ val output = Bitmap.createBitmap(source.width, source.height, Bitmap.Config.ARGB_8888)
67
+ val paint = Paint().apply { colorFilter = ColorMatrixColorFilter(effect.toAndroidColorMatrix()) }
68
+ Canvas(output).drawBitmap(source, 0f, 0f, paint)
69
+ return output
70
+ }
71
+
50
72
  private fun scaleToFit(bitmap: Bitmap, maxWidth: Int?, maxHeight: Int?): Bitmap {
51
73
  val widthScale = maxWidth?.let { it.toDouble() / bitmap.width } ?: 1.0
52
74
  val heightScale = maxHeight?.let { it.toDouble() / bitmap.height } ?: 1.0
@@ -111,6 +111,7 @@ class VideoProcessingModule(reactContext: ReactApplicationContext) :
111
111
  maxHeight = options.takeIf { it.hasKey("maxHeight") }?.getInt("maxHeight"),
112
112
  format = if (options.getString("format") == "png") Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG,
113
113
  quality = if (options.hasKey("quality")) options.getDouble("quality") else 0.8,
114
+ colorMatrix = options.colorMatrix(),
114
115
  )
115
116
 
116
117
  private fun VideoMetadata.toWritableMap(source: String): WritableMap =
@@ -57,7 +57,7 @@ class VideoProcessor(private val context: Context, private val sourceResolver: S
57
57
  }
58
58
  TransformerRunner.export(
59
59
  context,
60
- Composition.Builder(sequence).build(),
60
+ composition(sequence, plan),
61
61
  outputFile,
62
62
  encoderSettings(plan.bitrate),
63
63
  reportStage,
@@ -99,7 +99,7 @@ class VideoProcessor(private val context: Context, private val sourceResolver: S
99
99
 
100
100
  TransformerRunner.export(
101
101
  context,
102
- Composition.Builder(EditedMediaItemSequence.withVideoFrom(listOf(forward))).build(),
102
+ composition(EditedMediaItemSequence.withVideoFrom(listOf(forward)), plan),
103
103
  keyframesOnly,
104
104
  keyframeOnlySettings(plan.bitrate),
105
105
  onProgress,
@@ -115,9 +115,16 @@ class VideoProcessor(private val context: Context, private val sourceResolver: S
115
115
 
116
116
  private fun frameEffects(segment: PlannedSegment, plan: ProcessPlan): List<Effect> {
117
117
  val crop = segment.request.crop?.let { toNdcCrop(it, segment.metadata.width, segment.metadata.height) }
118
- return listOfNotNull(crop, presentation(plan))
118
+ val colorMatrix = plan.colorMatrix?.let(::ColorMatrixEffect)
119
+ return listOfNotNull(crop, colorMatrix, presentation(plan))
119
120
  }
120
121
 
122
+ /** The colour matrix is defined for SDR values, so HDR input is tone-mapped first when it's used. */
123
+ private fun composition(sequence: EditedMediaItemSequence, plan: ProcessPlan): Composition =
124
+ Composition.Builder(sequence)
125
+ .apply { if (plan.colorMatrix != null) setHdrMode(Composition.HDR_MODE_TONE_MAP_HDR_TO_SDR_USING_OPEN_GL) }
126
+ .build()
127
+
121
128
  private fun presentation(plan: ProcessPlan): Presentation =
122
129
  Presentation.createForWidthAndHeight(plan.width, plan.height, Presentation.LAYOUT_SCALE_TO_FIT)
123
130
 
@@ -0,0 +1,36 @@
1
+ import CoreImage
2
+
3
+ /// A 4x5 row-major colour matrix from JS (`filterMatrix`), applied with CIColorMatrix. Offsets are
4
+ /// in 0–1 units, and values are gamma-encoded, so contexts using it must have colour management off.
5
+ struct ColorMatrix {
6
+ private let values: [CGFloat]
7
+
8
+ init?(_ value: Any?) {
9
+ guard let numbers = value as? [NSNumber], numbers.count == 20 else {
10
+ return nil
11
+ }
12
+ values = numbers.map { CGFloat($0.doubleValue) }
13
+ }
14
+
15
+ func apply(to image: CIImage) -> CIImage {
16
+ image.applyingFilter("CIColorMatrix", parameters: [
17
+ "inputRVector": vector(row: 0),
18
+ "inputGVector": vector(row: 1),
19
+ "inputBVector": vector(row: 2),
20
+ "inputAVector": vector(row: 3),
21
+ "inputBiasVector": CIVector(x: values[4], y: values[9], z: values[14], w: values[19]),
22
+ ])
23
+ }
24
+
25
+ private func vector(row: Int) -> CIVector {
26
+ let start = row * 5
27
+ return CIVector(x: values[start], y: values[start + 1], z: values[start + 2], w: values[start + 3])
28
+ }
29
+ }
30
+
31
+ extension CIContext {
32
+ /// No colour management: filters see the same encoded values as the stored video, matching Android.
33
+ static func unmanaged() -> CIContext {
34
+ CIContext(options: [.workingColorSpace: NSNull(), .cacheIntermediates: false])
35
+ }
36
+ }
@@ -1,16 +1,17 @@
1
1
  import AVFoundation
2
2
  import CoreImage
3
3
 
4
- /// Per-frame work for the export: orient, crop, fit into the output size. Filters belong between
5
- /// cropping and fitting, so they see the frame as the user framed it.
4
+ /// Per-frame work for the export: orient, crop, filter, fit into the output size. Filters run
5
+ /// between cropping and fitting, so they see the frame as the user framed it.
6
6
  final class FrameRenderer {
7
- private let context = CIContext(options: [.cacheIntermediates: false])
7
+ private let context = CIContext.unmanaged()
8
8
  private let outputSize: CGSize
9
- private let outputColorSpace = CGColorSpace(name: CGColorSpace.itur_709) ?? CGColorSpaceCreateDeviceRGB()
9
+ private let colorMatrix: ColorMatrix?
10
10
  private let background: CIImage
11
11
 
12
- init(width: Int, height: Int) {
12
+ init(width: Int, height: Int, colorMatrix: ColorMatrix?) {
13
13
  outputSize = CGSize(width: width, height: height)
14
+ self.colorMatrix = colorMatrix
14
15
  background = CIImage(color: .black).cropped(to: CGRect(origin: .zero, size: outputSize))
15
16
  }
16
17
 
@@ -31,12 +32,16 @@ final class FrameRenderer {
31
32
  image = image.cropped(to: rect).transformed(by: CGAffineTransform(translationX: -rect.minX, y: -rect.minY))
32
33
  }
33
34
 
35
+ if let colorMatrix {
36
+ image = colorMatrix.apply(to: image)
37
+ }
38
+
34
39
  image = fit(image)
35
40
  context.render(
36
41
  image.composited(over: background),
37
42
  to: destination,
38
43
  bounds: CGRect(origin: .zero, size: outputSize),
39
- colorSpace: outputColorSpace
44
+ colorSpace: nil
40
45
  )
41
46
  }
42
47
 
@@ -31,12 +31,14 @@ struct OutputRequest {
31
31
  let height: Int?
32
32
  let bitrate: Int?
33
33
  let removeAudio: Bool
34
+ let colorMatrix: ColorMatrix?
34
35
 
35
36
  init(_ dictionary: NSDictionary) {
36
37
  width = (dictionary["width"] as? NSNumber)?.intValue
37
38
  height = (dictionary["height"] as? NSNumber)?.intValue
38
39
  bitrate = (dictionary["bitrate"] as? NSNumber)?.intValue
39
40
  removeAudio = (dictionary["removeAudio"] as? NSNumber)?.boolValue ?? false
41
+ colorMatrix = ColorMatrix(dictionary["colorMatrix"])
40
42
  }
41
43
  }
42
44
 
@@ -57,6 +59,7 @@ struct ProcessPlan {
57
59
  let bitrate: Int
58
60
  let frameRate: Float
59
61
  let hasAudio: Bool
62
+ let colorMatrix: ColorMatrix?
60
63
 
61
64
  var totalDuration: CMTime {
62
65
  segments.reduce(.zero) { $0 + $1.timeRange.duration }
@@ -90,7 +93,8 @@ enum ProcessPlanner {
90
93
  outputHeight: height
91
94
  ),
92
95
  frameRate: first.metadata.frameRate > 0 ? first.metadata.frameRate : 30,
93
- hasAudio: hasForwardAudio && !output.removeAudio
96
+ hasAudio: hasForwardAudio && !output.removeAudio,
97
+ colorMatrix: output.colorMatrix
94
98
  )
95
99
  }
96
100
 
@@ -1,4 +1,5 @@
1
1
  import AVFoundation
2
+ import CoreImage
2
3
  import UIKit
3
4
 
4
5
  struct ThumbnailOptions {
@@ -6,12 +7,14 @@ struct ThumbnailOptions {
6
7
  let maxHeight: Int?
7
8
  let isPNG: Bool
8
9
  let quality: Double
10
+ let colorMatrix: ColorMatrix?
9
11
 
10
12
  init(_ dictionary: NSDictionary) {
11
13
  maxWidth = (dictionary["maxWidth"] as? NSNumber)?.intValue
12
14
  maxHeight = (dictionary["maxHeight"] as? NSNumber)?.intValue
13
15
  isPNG = dictionary["format"] as? String == "png"
14
16
  quality = (dictionary["quality"] as? NSNumber)?.doubleValue ?? 0.8
17
+ colorMatrix = ColorMatrix(dictionary["colorMatrix"])
15
18
  }
16
19
  }
17
20
 
@@ -27,8 +30,13 @@ enum ThumbnailGenerator {
27
30
  let lastFrameTime = lastFrameSeconds(metadata)
28
31
  var thumbnails: [[String: Any]] = []
29
32
 
33
+ let context = options.colorMatrix.map { _ in CIContext.unmanaged() }
34
+
30
35
  for time in times {
31
- let image = try await frame(generator, at: min(time, lastFrameTime))
36
+ var image = try await frame(generator, at: min(time, lastFrameTime))
37
+ if let colorMatrix = options.colorMatrix, let context {
38
+ image = try filtered(image, with: colorMatrix, in: context)
39
+ }
32
40
  let uiImage = UIImage(cgImage: image)
33
41
  guard let data = options.isPNG ? uiImage.pngData() : uiImage.jpegData(compressionQuality: options.quality) else {
34
42
  throw VideoProcessingError.processing("Could not encode the frame at \(time)s")
@@ -45,6 +53,15 @@ enum ThumbnailGenerator {
45
53
  return thumbnails
46
54
  }
47
55
 
56
+ private static func filtered(_ image: CGImage, with colorMatrix: ColorMatrix, in context: CIContext) throws -> CGImage {
57
+ let input = CIImage(cgImage: image)
58
+ let colorSpace = image.colorSpace ?? CGColorSpaceCreateDeviceRGB()
59
+ guard let output = context.createCGImage(colorMatrix.apply(to: input), from: input.extent, format: .RGBA8, colorSpace: colorSpace) else {
60
+ throw VideoProcessingError.processing("Could not apply filters to the thumbnail")
61
+ }
62
+ return output
63
+ }
64
+
48
65
  /// Zero tolerance fails at exactly the duration, so requests past the end get the final frame.
49
66
  private static func lastFrameSeconds(_ metadata: VideoMetadata) -> Double {
50
67
  let frameDuration = metadata.frameRate > 0 ? 1 / Double(metadata.frameRate) : 0.04
@@ -49,7 +49,7 @@ final class VideoExporter {
49
49
 
50
50
  let videoSource = VideoFrameSource(
51
51
  plan: plan,
52
- renderer: FrameRenderer(width: plan.width, height: plan.height),
52
+ renderer: FrameRenderer(width: plan.width, height: plan.height, colorMatrix: plan.colorMatrix),
53
53
  makeBuffer: { try Self.makeBuffer(from: adaptor) },
54
54
  isCancelled: { [weak self] in self?.isCancelled ?? true }
55
55
  )