Skip to main content

video_normalizer 0.1.0 copy "video_normalizer: ^0.1.0" to clipboard
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.

example/lib/main.dart

import 'dart:async';

import 'package:file_picker/file_picker.dart';
import 'package:material_ui/material_ui.dart';
import 'package:video_normalizer/video_normalizer.dart';
import 'package:video_player/video_player.dart';

import 'src/platform_support.dart';

void main() {
  runApp(const VideoNormalizerExampleApp());
}

/// Root widget of the example app.
class VideoNormalizerExampleApp extends StatelessWidget {
  /// Creates the example app.
  const VideoNormalizerExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'video_normalizer example',
      theme: ThemeData(colorSchemeSeed: Colors.indigo),
      home: const NormalizerPage(),
    );
  }
}

/// Picks a video, normalizes it, shows progress and plays the result.
class NormalizerPage extends StatefulWidget {
  /// Creates the page.
  const NormalizerPage({super.key});

  @override
  State<NormalizerPage> createState() => _NormalizerPageState();
}

class _NormalizerPageState extends State<NormalizerPage> {
  final VideoNormalizer _normalizer = VideoNormalizer.instance;

  VideoInput? _input;
  String? _inputName;
  VideoInfo? _sourceInfo;
  VideoPreset _preset = VideoPreset.compatibility;
  bool _stripLocation = true;

  String? _activeRequestId;
  StreamSubscription<VideoProcessingProgress>? _progressSubscription;
  VideoProcessingProgress? _progress;

  VideoNormalizationResult? _result;
  VideoPlayerController? _player;
  String? _error;

  @override
  void initState() {
    super.initState();
    // Remove leftovers of a run that was interrupted, for example because
    // the app was killed while a video was being processed.
    unawaited(_normalizer.cleanupTemporaryFiles().catchError((Object _) => 0));
  }

  @override
  void dispose() {
    unawaited(_progressSubscription?.cancel());
    unawaited(_player?.dispose());
    super.dispose();
  }

  Future<void> _pick() async {
    final PlatformFile? file = await FilePicker.pickFile(type: FileType.video);
    if (file == null) {
      return;
    }
    await _reset();
    try {
      final VideoInput input = await inputFromPickedFile(file);
      final VideoInfo info = await _normalizer.inspect(input);
      setState(() {
        _input = input;
        _inputName = file.name;
        _sourceInfo = info;
      });
    } on VideoNormalizationException catch (error) {
      setState(() => _error = '${error.code}: ${error.message}');
    }
  }

  Future<void> _reset() async {
    await _player?.dispose();
    await _result?.output?.release();
    setState(() {
      _player = null;
      _result = null;
      _error = null;
      _progress = null;
      _sourceInfo = null;
      _input = null;
      _inputName = null;
    });
  }

  Future<void> _normalize() async {
    final VideoInput? input = _input;
    if (input == null) {
      return;
    }
    await _player?.dispose();
    await _result?.output?.release();

    final VideoNormalizationRequest request = VideoNormalizationRequest(
      input: input,
      preset: _preset,
      metadataPolicy: _stripLocation
          ? MetadataPolicy.stripLocation
          : MetadataPolicy.preserve,
    );
    setState(() {
      _player = null;
      _result = null;
      _error = null;
      _progress = null;
      _activeRequestId = request.id;
    });

    // The progress stream may be listened to before the request starts.
    _progressSubscription = _normalizer.progress(request.id).listen((
      VideoProcessingProgress progress,
    ) {
      setState(() => _progress = progress);
    });

    try {
      final VideoNormalizationResult result = await _normalizer.normalize(
        request,
      );
      VideoPlayerController? player;
      final VideoOutput? output = result.output;
      if (output != null) {
        player = createPlayer(output);
        if (player != null) {
          await player.initialize();
        }
      }
      setState(() {
        _result = result;
        _player = player;
      });
    } on NormalizationCancelled {
      setState(() => _error = 'Cancelled.');
    } on VideoNormalizationException catch (error) {
      // Every failure has a stable code; see docs/ERRORS.md.
      setState(() => _error = '${error.code}: ${error.message}');
    } finally {
      await _progressSubscription?.cancel();
      setState(() => _activeRequestId = null);
    }
  }

  Future<void> _cancel() async {
    final String? id = _activeRequestId;
    if (id != null) {
      await _normalizer.cancel(id);
    }
  }

  Future<void> _showCapabilities() async {
    final VideoCapabilities capabilities = await _normalizer.capabilities();
    if (!mounted) {
      return;
    }
    await showDialog<void>(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        title: const Text('Capabilities'),
        content: SingleChildScrollView(
          child: Text(
            <String>[
              'Platform: ${capabilities.platform} ${capabilities.osVersion ?? ''}',
              'Backend: ${capabilities.backend ?? 'unknown'}',
              'H.264 encoder: ${capabilities.canEncodeH264}',
              'AAC encoder: ${capabilities.canEncodeAac}',
              'Hardware H.264: ${capabilities.hasHardwareH264Encoder}',
              'Max encode size: ${capabilities.maxEncodeWidth}x${capabilities.maxEncodeHeight}',
              'HDR to SDR: ${capabilities.supportsHdrToSdrToneMapping}'
                  '${capabilities.hdrToneMappingDetail == null ? '' : ' (${capabilities.hdrToneMappingDetail})'}',
              if (capabilities.missingCapabilities.isNotEmpty)
                'Missing: ${capabilities.missingCapabilities.join(', ')}',
              '',
              for (final VideoEncoderCapability encoder
                  in capabilities.encoders)
                '${encoder.codec}: ${encoder.name}'
                    '${encoder.isHardwareAccelerated == true ? ' (hardware)' : ''}',
            ].join('\n'),
          ),
        ),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Close'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final bool busy = _activeRequestId != null;
    final VideoProcessingProgress? progress = _progress;
    final VideoNormalizationResult? result = _result;
    final VideoPlayerController? player = _player;

    return Scaffold(
      appBar: AppBar(
        title: const Text('video_normalizer'),
        actions: <Widget>[
          IconButton(
            tooltip: 'Capabilities',
            icon: const Icon(Icons.memory),
            onPressed: _showCapabilities,
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: <Widget>[
          FilledButton.icon(
            onPressed: busy ? null : _pick,
            icon: const Icon(Icons.video_library),
            label: const Text('Pick a video'),
          ),
          if (_inputName != null) ...<Widget>[
            const SizedBox(height: 12),
            Text(_inputName!, style: Theme.of(context).textTheme.titleMedium),
          ],
          if (_sourceInfo != null)
            _InfoCard(title: 'Source', info: _sourceInfo!),
          const SizedBox(height: 12),
          DropdownButtonFormField<VideoPreset>(
            initialValue: _preset,
            decoration: const InputDecoration(
              labelText: 'Preset',
              border: OutlineInputBorder(),
            ),
            items: <DropdownMenuItem<VideoPreset>>[
              for (final VideoPreset preset in VideoPreset.values)
                if (preset != VideoPreset.custom)
                  DropdownMenuItem<VideoPreset>(
                    value: preset,
                    child: Text(preset.name),
                  ),
            ],
            onChanged: busy
                ? null
                : (VideoPreset? value) =>
                      setState(() => _preset = value ?? _preset),
          ),
          SwitchListTile(
            contentPadding: EdgeInsets.zero,
            title: const Text('Remove location and device metadata'),
            value: _stripLocation,
            onChanged: busy
                ? null
                : (bool value) => setState(() => _stripLocation = value),
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: FilledButton(
                  onPressed: busy || _input == null ? null : _normalize,
                  child: const Text('Normalize'),
                ),
              ),
              const SizedBox(width: 12),
              OutlinedButton(
                onPressed: busy ? _cancel : null,
                child: const Text('Cancel'),
              ),
            ],
          ),
          if (busy && progress != null) ...<Widget>[
            const SizedBox(height: 16),
            // A null fraction means the engine cannot report progress; an
            // indeterminate bar is shown rather than an invented value.
            LinearProgressIndicator(value: progress.fraction),
            const SizedBox(height: 4),
            Text(
              '${progress.stage.name}'
              '${progress.fraction == null ? '' : '  ${(progress.fraction! * 100).toStringAsFixed(0)} %'}'
              '${progress.estimatedRemaining == null ? '' : '  about ${progress.estimatedRemaining!.inSeconds} s left'}',
            ),
          ],
          if (_error != null) ...<Widget>[
            const SizedBox(height: 16),
            Text(
              _error!,
              style: TextStyle(color: Theme.of(context).colorScheme.error),
            ),
          ],
          if (result != null) ...<Widget>[
            const SizedBox(height: 16),
            _ResultCard(result: result),
          ],
          if (player != null && player.value.isInitialized) ...<Widget>[
            const SizedBox(height: 16),
            AspectRatio(
              aspectRatio: player.value.aspectRatio,
              child: VideoPlayer(player),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                IconButton(
                  icon: const Icon(Icons.play_arrow),
                  onPressed: player.play,
                ),
                IconButton(
                  icon: const Icon(Icons.pause),
                  onPressed: player.pause,
                ),
              ],
            ),
          ],
        ],
      ),
    );
  }
}

class _InfoCard extends StatelessWidget {
  const _InfoCard({required this.title, required this.info});

  final String title;
  final VideoInfo info;

  @override
  Widget build(BuildContext context) {
    String show(Object? value) => value?.toString() ?? 'unknown';
    return Card(
      margin: const EdgeInsets.only(top: 12),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Text(
          '$title\n'
          'Container: ${show(info.container?.token)}'
          '${info.isFastStart == null ? '' : (info.isFastStart! ? ' (fast-start)' : ' (index at end)')}\n'
          'Video: ${show(info.videoCodec?.token)} ${show(info.videoProfile)}'
          '${info.videoLevel == null ? '' : ' L${info.videoLevel! / 10}'}, '
          '${show(info.displayWidth)}x${show(info.displayHeight)}, '
          '${info.effectiveFrameRate?.toStringAsFixed(2) ?? 'unknown'} fps, '
          '${show(info.hdrFormat?.token)}\n'
          'Audio: ${info.hasAudio == false ? 'none' : '${show(info.audioCodec?.token)} ${show(info.audioProfile)}, '
                    '${show(info.audioSampleRate)} Hz, ${show(info.audioChannels)} ch'}\n'
          'Duration: ${info.duration == null ? 'unknown' : '${(info.duration!.inMilliseconds / 1000).toStringAsFixed(2)} s'}'
          ', size: ${info.fileSize == null ? 'unknown' : '${(info.fileSize! / 1e6).toStringAsFixed(2)} MB'}\n'
          'Location metadata: ${show(info.hasLocationMetadata)}',
        ),
      ),
    );
  }
}

class _ResultCard extends StatelessWidget {
  const _ResultCard({required this.result});

  final VideoNormalizationResult result;

  @override
  Widget build(BuildContext context) {
    final VideoNormalizationStatistics stats = result.statistics;
    final VideoInfo? output = result.outputInfo;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Text(
          'Result: ${result.action.name}'
          '${result.decision.reasons.isEmpty ? '' : ' (${result.decision.reasons.map((NormalizationReason r) => r.name).join(', ')})'}',
          style: Theme.of(context).textTheme.titleMedium,
        ),
        Text(
          'Size: ${stats.sourceSize ?? '?'} -> ${stats.outputSize ?? '?'} bytes'
          '${stats.percentageReduction == null ? '' : ' (${stats.percentageReduction!.toStringAsFixed(1)} % smaller)'}'
          ', took ${(stats.processingTime.inMilliseconds / 1000).toStringAsFixed(1)} s',
        ),
        for (final VideoNormalizationWarning warning in result.warnings)
          Text('Warning ${warning.code}: ${warning.message}'),
        if (output != null && result.action != VideoNormalizationAction.skipped)
          _InfoCard(title: 'Output', info: output),
      ],
    );
  }
}
1
likes
0
points
144
downloads

Publisher

unverified uploader

Weekly Downloads

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.

Repository (GitHub)
View/report issues

Topics

#video #transcoding #compression #media #mp4

License

unknown (license)

Dependencies

flutter, meta, video_normalizer_android, video_normalizer_ios, video_normalizer_platform_interface, video_normalizer_web

More

Packages that depend on video_normalizer

Packages that implement video_normalizer