video_normalizer 0.1.0
video_normalizer: ^0.1.0 copied to clipboard
Normalizes picked videos into a standard MP4 (H.264 + AAC-LC, SDR 8-bit, 720p30 or lower) that plays on current and older Android and iOS devices. Local processing only, no FFmpeg.
video_normalizer #
Turns a video a user picked into a standard MP4 that plays everywhere — H.264 + AAC-LC, SDR 8-bit, at most 720p30 by default — before your app uploads it. Processing is local: on the device, or in the browser. Nothing is sent to a transcoding service, and no FFmpeg is bundled.
Phone cameras record 4K, HEVC, 10-bit HDR, 60 fps and QuickTime containers. Older and low-end Android phones cannot play much of that. This package fixes the file once, on the device that recorded it, so that every viewer can play it.
| Platform | Engine | Status |
|---|---|---|
| Android 7.0+ (API 24) | Jetpack Media3 Transformer | Integration tested on emulators (API 34; the release build also on API 35 with 16 KB pages). Not tested on physical devices |
| iOS 15+ | AVFoundation (AVAssetReader / AVAssetWriter) |
Implemented, never compiled or run: see below |
| Web, Chromium-based browsers | WebCodecs in a dedicated Web Worker | Verified in Chrome 158 on Windows 11 (all suites) and Edge 158 (smoke suite). Other browsers, systems and phones: not tested. A browser that lacks a required feature is refused up front (verified with Firefox 161) |
Read docs/COMPATIBILITY.md for exactly what
was built and tested, on what, and what was not.
Install #
dependencies:
video_normalizer: ^0.1.0
No permissions, no Gradle or Podfile edits, no native libraries.
Requirements: Flutter 3.50 / Dart 3.14 or newer. On Android that means AGP 9.1.1+ and Gradle 9.3.1+, which are Flutter 3.50's own minimums.
Use #
import 'package:video_normalizer/video_normalizer.dart';
final request = VideoNormalizationRequest(
input: VideoInput.file(pickedPath), // or .contentUri(...), .fileUrl(...), .webFile(...)
preset: VideoPreset.compatibility, // the default
);
final sub = VideoNormalizer.instance
.progress(request.id)
.listen((p) => debugPrint('${p.stage.name} ${p.fraction}'));
try {
final result = await VideoNormalizer.instance.normalize(request);
// What happened: skipped, remuxed or transcoded.
print(result.action);
print(result.statistics.percentageReduction);
await upload(result.output!.path!); // result.output!.blob on the web
await result.output!.release(); // deletes the temp file; never the source
} on VideoNormalizationException catch (e) {
print('${e.code}: ${e.message}'); // stable codes, see docs/ERRORS.md
} finally {
await sub.cancel();
}
What you get back #
Every output is an MP4 with the index first (it starts playing before it has finished downloading), one H.264 video track and at most one AAC-LC audio track, upright, 8-bit SDR.
compatibility |
balanced |
highQuality |
|
|---|---|---|---|
| H.264 | Main, Level 3.1 | Main, Level 3.1 | High, Level 4.0 |
| Max size | 1280 × 720 | 1280 × 720 | 1920 × 1080 |
| Max frame rate | 30 fps | 30 fps | 30 fps |
| Bits per pixel per frame | 0.08 (≈ 2.2 Mbps at 720p30) | 0.10 (≈ 2.8 Mbps) | 0.14 (≈ 8.7 Mbps at 1080p30) |
The aspect ratio is preserved, nothing is ever upscaled, and the bitrate never
exceeds the source's. Full rules and worked examples:
docs/PRESETS.md.
Smart Skip #
Not every file needs work. The source is analyzed first:
- already compliant → skipped:
result.outputis the source itself; - compliant, but carries GPS/device metadata or has its index at the end → remuxed: the streams are copied, not re-encoded, so it is lossless and takes seconds;
- anything else → transcoded.
result.decision.reasons says why. To only find out what would happen:
final result = await VideoNormalizer.instance.normalize(
VideoNormalizationRequest(input: input, skipPolicy: SkipPolicy.analyzeOnly),
);
print('${result.action}: ${result.decision.reasons}');
Progress and cancellation #
VideoNormalizer.instance.progress(request.id).listen((p) {
// p.stage: initializing, analyzing, preparing, transcoding | remuxing,
// finalizing, validating, then completed | cancelled | failed
// p.fraction: 0..1 from the native engine, or null when it cannot tell.
// It is never estimated from elapsed time.
// p.estimatedRemaining: only after 10 % and 3 s, from measured throughput
});
final stopped = await VideoNormalizer.instance.cancel(request.id);
cancel completes after the native task has stopped, its partial output has
been deleted and its codecs released; normalize() has then thrown
NormalizationCancelled. Streams are per request id, deliver at most four
events per second, and never mix events of different requests.
Several videos #
final batch = VideoNormalizer.instance.normalizeAll([
for (final path in pickedPaths)
VideoNormalizationRequest(input: VideoInput.file(path)),
]);
batch.progress.listen((p) {
// p.finished of p.total, p.currentIndex, p.current (the running request's
// own progress), p.fraction for the batch as a whole
});
for (final item in await batch.done) { // never throws
if (item.isSuccess) {
await upload(item.result!.output!);
await item.result!.output!.release();
} else {
report(item.request, item.error!); // a VideoNormalizationException
}
}
await batch.cancel(); // stops the running request and skips the rest
A batch processes one video at a time, in the order given, and only looks
at the next source when the previous one has finished. A video that fails
does not stop the others unless stopOnError: true is passed. Calling
normalize() several times instead also queues the work, but analyzes all
sources up front.
Inspecting and capabilities #
final info = await VideoNormalizer.instance.inspect(VideoInput.file(path));
print('${info.videoCodec} ${info.displayWidth}x${info.displayHeight} ${info.hdrFormat}');
// Every field is nullable: what the platform cannot read is null, never guessed.
final caps = await VideoNormalizer.instance.capabilities();
print(caps.supportsHdrToSdrToneMapping);
Options #
VideoNormalizationRequest(
input: input,
preset: VideoPreset.custom,
configuration: VideoNormalizationConfiguration.balanced.copyWith(maxFrameRate: 25),
skipPolicy: SkipPolicy.skipWhenCompliant, // or alwaysTranscode, analyzeOnly
metadataPolicy: MetadataPolicy.stripLocation, // the default; or preserve
targetSizeBytes: 20 * 1000 * 1000, // fails with TargetSizeUnreachable rather than ruin the video
destination: '/path/to/output.mp4', // default: the app's cache directory
timeout: const Duration(minutes: 10),
);
await VideoNormalizer.instance.setMaxConcurrentJobs(2); // default 1; requests queue first-in first-out
await VideoNormalizer.instance.cleanupTemporaryFiles(); // call once at start-up
HDR #
HDR input (HLG, HDR10, Dolby Vision) is tone-mapped to SDR. If the device
cannot do that, the request fails with HdrConversionUnsupported instead of
producing a washed-out or still-HDR file. HdrFallback.passThrough is an
explicit opt-in to continue anyway; the result then carries a warning.
Errors #
One sealed hierarchy, VideoNormalizationException, with a stable code per
subclass, identical on every platform: invalid_input,
hdr_conversion_unsupported, encoder_configuration_unsupported,
insufficient_storage, output_validation_failed, cancelled, … The full
table is in docs/ERRORS.md.
Before normalize() returns, the platform reopens the file it wrote with its
own reader and compares it with what was asked for. A file that does not match
is deleted and reported as output_validation_failed; it is never returned.
Guarantees #
- The source file is never modified, moved or deleted.
- The whole video is never loaded into memory.
- An unsupported output configuration is never replaced by a different one
silently. The two adjustments that can happen (a lower H.264 level, rotation
metadata instead of rotated pixels) are reported in
result.warnings. - Progress values are never invented.
- A partially written file is never exposed.
Platform notes #
Android. Media3 Transformer 1.11.1. minSdk 24. The plugin ships no native
library; use tool/check_16kb.py to check your own
app's APK for 16 KB page-size compatibility. See
docs/ANDROID_BUILD.md. Everything so far ran
on emulators, which have software codecs only; HDR tone mapping could not be
run there at all. docs/handoff/ANDROID_DEVICES.md
is the test plan for real phones.
iOS. The Swift implementation was written on Windows against Apple's
documentation and has never been compiled or run. Treat it as unverified
until someone has executed docs/handoff/IOS.md
on a Mac; expect the first build to need small fixes. WebM sources fail with
unsupported_container there, because AVFoundation does not read them.
Web. WebCodecs in a dedicated Web Worker; no FFmpeg, no WebAssembly, no
server. The input is a Blob or File (VideoInput.blob,
VideoInput.webFile), the output a Blob (result.output!.blob), with
objectUrl(), download(fileName) and release(). The page must be served
over HTTPS (or from localhost). A browser that lacks a required feature
gets BrowserCapabilityError before anything is read; error.missing says
what. In practice that means Chromium-based browsers on systems with an
H.264 and an AAC encoder: Firefox on Windows, for one, has no AAC encoder and
is refused. HEVC sources need a hardware HEVC decoder. The largest output is
1920x1080, and a destination path is not accepted. Everything was verified
on one Windows machine; read
docs/WEB_BROWSERS.md before relying on it,
and docs/handoff/BROWSERS.md for the test
plan for other browsers. The worker script adds about 585 kB to the app.
License #
BSD-3-Clause. See LICENSE.