Skip to main content

mova 0.4.2 copy "mova: ^0.4.2" to clipboard
mova: ^0.4.2 copied to clipboard

media_kit (libmpv/ffmpeg) based video player plugin with gestures, VOD/live control bar, quality switching with ABR and picture-in-picture.

example/lib/main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:mova/mova.dart';

import 'spike_audio_extract.dart';
import 'spike_dual_engine.dart';
import 'spike_native_tracks.dart';

/// Example entry: init mova core, then run the demo app.
///
/// 示例入口:初始化 mova 内核,随后运行演示 app。
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MovaEngine.ensureInitialized();
  runApp(const MyApp());
}

/// Demo app root.
///
/// 演示 app 根组件。
class MyApp extends StatelessWidget {
  /// Creates the demo app.
  ///
  /// 创建演示 app。
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(theme: ThemeData.dark(), home: const PlayerPage());
  }
}

/// A demo source with a display name and the options it needs.
///
/// 带显示名与所需配置的演示源。
class _Demo {
  /// Label shown in the app bar.
  ///
  /// 应用栏上显示的名称。
  final String name;

  /// The media source this entry plays.
  ///
  /// 该入口播放的媒体源。
  final MovaSource source;

  /// Player options this entry needs (live mode, timeshift builder, …).
  ///
  /// 该入口所需的播放器配置(直播模式、时移地址构造器等)。
  final MovaOpts options;

  /// Creates a demo entry.
  ///
  /// 创建一个演示入口。
  const _Demo(this.name, this.source, {this.options = const MovaOpts()});
}

/// Sample danmaku for the bilibili-skin demo entry, timed to the first
/// ~20 seconds of the shared demo mp4.
///
/// bilibili 皮肤演示入口用的示例弹幕,按共用演示 mp4 的前约 20 秒计时。
const _sampleDanmaku = [
  MovaDanmakuItem(text: '前方高能', time: Duration(seconds: 2)),
  MovaDanmakuItem(text: '哈哈哈哈', time: Duration(seconds: 4)),
  MovaDanmakuItem(text: '这也太好看了吧', time: Duration(seconds: 6)),
  MovaDanmakuItem(text: '弹幕护体', time: Duration(seconds: 8)),
  MovaDanmakuItem(text: '一键三连', time: Duration(seconds: 10)),
];

/// The demo sources: VOD mp4, multi-quality HLS, a custom-skin variant, a
/// DVR-seekable live stream, a time-shift (reopen-on-seek) live stream, and a
/// bilibili-style skin with danmaku + speed button.
///
/// 演示源:点播 mp4、多清晰度 HLS、自定义皮肤变体、DVR 可拖直播、
/// 时移(拖动即换源)直播、带弹幕 + 倍速按钮的 bilibili 风格皮肤。
final _demos = [
  _Demo(
    'VOD · mp4',
    MovaSource(
      'https://user-images.githubusercontent.com/28951144/229373695-22f88f13-d18f-4288-9bf1-c3e078d83722.mp4',
      title: '示例点播 mp4',
    ),
  ),
  _Demo(
    'ffmpeg瘦身 · HEVC',
    MovaSource(
      'https://test-videos.co.uk/vids/bigbuckbunny/mp4/h265/720/Big_Buck_Bunny_720_10s_1MB.mp4',
      title: 'HEVC 硬解/软解验证',
    ),
  ),
  _Demo(
    'ffmpeg瘦身 · VP9',
    MovaSource(
      'https://test-videos.co.uk/vids/bigbuckbunny/webm/vp9/720/Big_Buck_Bunny_720_10s_1MB.webm',
      title: 'VP9 硬解验证',
    ),
  ),
  _Demo(
    'ffmpeg瘦身 · AV1',
    MovaSource(
      'https://api.elysiatools.com/public/samples/av1/earth_720p_horizontal.mp4',
      title: 'AV1 硬解/软解验证',
    ),
  ),
  _Demo(
    'HLS · 多清晰度',
    MovaSource(
      'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8',
      title: 'HLS 多清晰度示例',
    ),
  ),
  _Demo(
    '自定义皮肤 · 无画中画按钮',
    MovaSource(
      'https://user-images.githubusercontent.com/28951144/229373695-22f88f13-d18f-4288-9bf1-c3e078d83722.mp4',
      title: '自定义皮肤示例',
    ),
  ),
  _Demo(
    '直播 · DVR 可拖',
    MovaSource(
      'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8',
      type: MovaStreamType.live,
      title: '直播(DVR 窗口内可回看)',
    ),
    options: const MovaOpts(
      live: MovaLiveConfig(seekMode: MovaLiveSeekMode.dvr),
    ),
  ),
  _Demo(
    '直播 · 时移换源',
    MovaSource(
      'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8',
      type: MovaStreamType.live,
      title: '直播(时移:拖动即换源)',
    ),
    options: MovaOpts(
      live: MovaLiveConfig(
        seekMode: MovaLiveSeekMode.timeshift,
        dvrWindow: const Duration(minutes: 10),
        // Demo-only: this public test stream has no timeshift endpoint, so the
        // builder just appends a query the server ignores. It exists to show
        // *where* a real deployment plugs its own URL scheme in.
        //
        // 仅用于演示:这个公开测试流没有时移接口,构造器只是拼一个服务端会忽略
        // 的查询参数。它的意义是展示真实部署应当在**哪里**接入自己的地址方案。
        urlBuilder: (uri, behind, wallClock) =>
            '$uri?begin=${wallClock.subtract(behind).millisecondsSinceEpoch}',
      ),
    ),
  ),
  _Demo(
    'bilibili 皮肤',
    MovaSource(
      'https://user-images.githubusercontent.com/28951144/229373695-22f88f13-d18f-4288-9bf1-c3e078d83722.mp4',
      title: 'bilibili 风格皮肤示例',
    ),
    options: const MovaOpts(danmaku: MovaDanmakuConfig(enabled: true, items: _sampleDanmaku)),
  ),
];

/// A skin used by the third demo entry: the default skin with the
/// picture-in-picture button patched out of the top bar.
///
/// 第三个演示入口使用的皮肤:在默认皮肤基础上,从顶栏中移除画中画按钮。
const _noPipSkin = MovaDefaultSkin(
  patches: [
    MovaPatch.remove(
      '${MovaTopBarComponent.componentName}/${MovaPipButtonComponent.componentName}',
    ),
  ],
);

/// Index of the bilibili-skin demo entry in [_demos].
///
/// [_demos] 中 bilibili 皮肤演示入口的下标。
const _bilibiliDemoIndex = 5;

/// A page that plays a demo source with [MovaPlayer] and a source switcher.
///
/// 用 [MovaPlayer] 播放演示源并提供源切换的页面。
class PlayerPage extends StatefulWidget {
  /// Creates the player page.
  ///
  /// 创建播放页面。
  const PlayerPage({super.key});

  @override
  State<PlayerPage> createState() => _PlayerPageState();
}

/// State for [PlayerPage]; owns the [MovaEngine] lifecycle.
///
/// [PlayerPage] 的状态;持有 [MovaEngine] 的生命周期。
class _PlayerPageState extends State<PlayerPage> {
  /// The playback facade backing every demo entry.
  ///
  /// 支撑每个演示入口的播放能力面。
  late MovaEngine _engine;

  /// Index of the currently selected demo source.
  ///
  /// 当前选中的演示源下标。
  int _index = 0;

  /// Whether the scrub-preview bubble is enabled in this demo run.
  ///
  /// 本次 demo 运行中是否启用拖动预览气泡。
  bool _previewOn = true;

  @override
  void initState() {
    super.initState();
    _engine = createMovaEngine(options: _optionsFor(_index), extractor: MovaFrameExtractor());
    _engine.open(_demos[_index].source);
  }

  /// Builds the effective options for demo [i]: that demo's own `options`
  /// (live mode, timeshift builder, …) with the preview section overridden to
  /// respect [_previewOn] and relax the network policy for desktop/emulator
  /// use, where the connection type is unknown; production defaults to
  /// `wifiOnly`.
  ///
  /// 构建第 [i] 个演示的生效配置:该演示自身的 `options`(直播模式、时移地址
  /// 构造器等),并覆盖预览一节以遵循 [_previewOn]、放宽桌面/模拟器场景下
  /// 未知的网络策略;生产环境默认是 `wifiOnly`。
  ///
  /// - [i]: index into [_demos] / [_demos] 下标
  MovaOpts _optionsFor(int i) => _demos[i].options.copyWith(
        preview: MovaPreviewConfig(
          enabled: _previewOn,
          network: MovaPreviewNet.always,
        ),
      );

  /// Rebuilds the engine with preview switched to [on], reopening the current
  /// demo source.
  ///
  /// 以预览开关 [on] 重建 engine,并重新打开当前演示源。
  ///
  /// - [on]: whether the preview bubble should be enabled / 是否启用预览气泡
  Future<void> _togglePreview(bool on) async {
    final old = _engine;
    setState(() {
      _previewOn = on;
      _engine = createMovaEngine(options: _optionsFor(_index), extractor: MovaFrameExtractor());
    });
    await old.dispose();
    await _engine.open(_demos[_index].source);
  }

  @override
  void dispose() {
    _engine.dispose();
    super.dispose();
  }

  /// Switches to demo source [i], rebuilding the engine because options are
  /// construction-time.
  ///
  /// 切换到第 [i] 个演示源;因为配置是构造期参数,需要重建 engine。
  ///
  /// - [i]: index into the demo list / 演示列表下标
  Future<void> _switch(int i) async {
    final old = _engine;
    setState(() {
      _index = i;
      _engine = createMovaEngine(options: _optionsFor(i), extractor: MovaFrameExtractor());
    });
    await old.dispose();
    await _engine.open(_demos[i].source);
    await _engine.loadQualities();
    if (mounted) setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('mova'),
        actions: [
          IconButton(
            tooltip: '抖音风 feed 演示',
            icon: const Icon(Icons.view_carousel_rounded),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const DouyinFeedDemoPage()),
            ),
          ),
          IconButton(
            tooltip: '播放列表 + 下一集演示',
            icon: const Icon(Icons.playlist_play_rounded),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const PlaylistDemoPage()),
            ),
          ),
          IconButton(
            tooltip: '广告演示(前/中贴片 + 运行时插入)',
            icon: const Icon(Icons.ad_units_rounded),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const AdDemoPage()),
            ),
          ),
          IconButton(
            tooltip: '无缝广告演示(默认开启 MovaCutoverEngine)',
            icon: const Icon(Icons.bolt_rounded),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const SeamlessAdDemoPage()),
            ),
          ),
          IconButton(
            tooltip: '广告编排演示(delay / duration / 等待就绪 / 失败兜底)',
            icon: const Icon(Icons.timer_rounded),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const AdOrchestrationDemoPage()),
            ),
          ),
          IconButton(
            tooltip: '双引擎内存 spike',
            icon: const Icon(Icons.memory_rounded),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const DualEngineMemorySpikePage()),
            ),
          ),
          IconButton(
            tooltip: '音频抽取 spike',
            icon: const Icon(Icons.audiotrack_rounded),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const AudioExtractSpikePage()),
            ),
          ),
          IconButton(
            tooltip: '原生 track spike(清晰度迁原生)',
            icon: const Icon(Icons.high_quality_rounded),
            onPressed: () => Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => const NativeTracksSpikePage()),
            ),
          ),
          IconButton(
            tooltip: _previewOn ? '关闭预览' : '开启预览',
            icon: Icon(_previewOn ? Icons.image : Icons.image_not_supported),
            onPressed: () => _togglePreview(!_previewOn),
          ),
          // The demo count keeps growing (6 as of the bilibili entry) and a
          // plain Row silently clips the tail entries off-screen on anything
          // narrower than a very wide monitor — `bilibili 皮肤` was
          // unreachable by mouse before this. Scroll just this segment
          // instead of the whole actions row, so the feed/preview icons stay
          // put.
          //
          // demo 数量一直在涨(加上 bilibili 这条已到 6 个),普通 Row 在
          // 不够宽的显示器上会把尾部条目静默裁掉——加上 `bilibili 皮肤` 之前
          // 鼠标根本点不到它。只让这一段可横向滚动,而非整个 actions 行,
          // feed/预览图标保持固定位置。
          Expanded(
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Row(
                children: [
                  for (var i = 0; i < _demos.length; i++)
                    TextButton(
                      onPressed: i == _index ? null : () => _switch(i),
                      child: Text(
                        _demos[i].name,
                        style: TextStyle(color: i == _index ? Colors.grey : Colors.white),
                      ),
                    ),
                ],
              ),
            ),
          ),
        ],
      ),
      body: Center(
        // Deliberately NOT the demo videos' own ~16:9 aspect ratio: when the
        // box matches the content exactly, contain/cover/fill render
        // identically and the fit-mode button appears to do nothing. 4:3
        // guarantees visible letterboxing/cropping/stretching between modes.
        //
        // 故意不用演示视频自身的 ~16:9 宽高比:容器与内容完全一致时,
        // contain/cover/fill 渲染结果相同,观感上"填充模式"按钮像是没反应。
        // 4:3 能保证三种模式之间出现可见的黑边/裁切/拉伸差异。
        child: AspectRatio(
          aspectRatio: 4 / 3,
          child: MovaPlayer(
            api: _engine,
            skin: _index == 2
                ? _noPipSkin
                : _index == _bilibiliDemoIndex
                    ? MovaBilibiliSkin()
                    : const MovaDefaultSkin(),
          ),
        ),
      ),
    );
  }
}

/// Sample feed items for the douyin-style demo: three short public mp4s,
/// looped with per-loop-varying like/comment/share counts so repeated swipes
/// visibly show different numbers rather than the exact same three forever.
///
/// 抖音风演示的示例 feed 条目:三个公开短 mp4 循环播放,点赞/评论/分享数按圈数
/// 变化,使反复上滑时数字可见地在变,而非永远是完全相同的三条。
final _feedSources = [
  'https://user-images.githubusercontent.com/28951144/229373695-22f88f13-d18f-4288-9bf1-c3e078d83722.mp4',
  'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4',
  'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/friday.mp4',
];

/// A full-screen page demoing [MovaFeedPlayer]: vertical swipe-for-next-video,
/// douyin-style social rail, and local like state — see doc/SPEC.md's feed
/// entry for the engine-pool architecture this is built on.
///
/// 演示 [MovaFeedPlayer] 的全屏页面:纵向上滑切下一个视频、抖音风社交竖排、
/// 本地点赞状态——其所基于的引擎池架构见 doc/SPEC.md 的 feed 条目。
class DouyinFeedDemoPage extends StatefulWidget {
  /// Creates the douyin-feed demo page.
  ///
  /// 创建抖音 feed 演示页面。
  const DouyinFeedDemoPage({super.key});

  @override
  State<DouyinFeedDemoPage> createState() => _DouyinFeedDemoPageState();
}

/// State for [DouyinFeedDemoPage]. Note it owns no engine of its own — the
/// feed's pool creates and disposes every engine, the host only supplies the
/// factory.
///
/// [DouyinFeedDemoPage] 的状态。注意它自身不持有任何引擎——所有引擎都由 feed
/// 的引擎池创建与释放,宿主只负责提供工厂。
class _DouyinFeedDemoPageState extends State<DouyinFeedDemoPage> {
  /// Resolves feed item [index], looping over [_feedSources] forever — a
  /// real app would page through a backend feed API instead and return
  /// `null` once exhausted.
  ///
  /// 解析 feed 第 [index] 条,在 [_feedSources] 上无限循环——真实 app 应改为
  /// 分页请求后端 feed 接口,取完后返回 `null`。
  ///
  /// - [index]: the feed index to resolve / 要解析的 feed 索引
  Future<MovaFeedItem?> _loadItem(int index) async {
    final loop = index ~/ _feedSources.length;
    final uri = _feedSources[index % _feedSources.length];
    return MovaFeedItem(
      source: MovaSource(uri),
      authorName: 'demo_user_$index',
      musicName: '原创音频 · demo',
      initialLikeCount: 100 + loop * 37 + index,
      commentCount: 10 + index,
      shareCount: 3 + index,
      onLikeChanged: (liked, count) => debugPrint('feed[$index] liked=$liked count=$count'),
      onComment: () => debugPrint('feed[$index] comment tapped'),
      onShare: () => debugPrint('feed[$index] share tapped'),
      onAvatarTap: () => debugPrint('feed[$index] avatar tapped'),
      onFollowTap: () => debugPrint('feed[$index] follow tapped'),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          MovaFeedPlayer(engineFactory: createMovaEngine, loader: _loadItem),
          SafeArea(
            child: IconButton(
              icon: const Icon(Icons.close_rounded, color: Colors.white),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ),
        ],
      ),
    );
  }
}

/// Playlist items for the playlist demo: three short public mp4s treated as a
/// three-episode series, reusing the same URLs as the feed demo.
///
/// 播放列表演示的项:三个公开短 mp4 当作三集连播,复用与 feed 演示相同的 URL。
final _playlistItems = [
  for (var i = 0; i < _feedSources.length; i++)
    MovaPlaylistItem(
      source: MovaSource(_feedSources[i], title: '第 ${i + 1} 集'),
      subtitle: '播放列表演示 · 共 ${_feedSources.length} 集',
    ),
];

/// A page demoing sequential playlist playback: a [MovaPlaylist] drives
/// auto-advance between three episodes, a [MovaNextUpComponent] fades in near each
/// item's end, and manual prev/next buttons exercise the same navigation.
///
/// 演示顺序播放列表:[MovaPlaylist] 在三集间驱动自动续播,
/// [MovaNextUpComponent] 在每项临近结束时淡入,手动上一集/下一集按钮演示同一套导航。
class PlaylistDemoPage extends StatefulWidget {
  /// Creates the playlist demo page.
  ///
  /// 创建播放列表演示页面。
  const PlaylistDemoPage({super.key});

  @override
  State<PlaylistDemoPage> createState() => _PlaylistDemoPageState();
}

/// State for [PlaylistDemoPage]; owns the engine and the playlist controller.
///
/// [PlaylistDemoPage] 的状态;持有引擎与播放列表控制器。
class _PlaylistDemoPageState extends State<PlaylistDemoPage> {
  /// The playback facade backing the playlist.
  ///
  /// 支撑播放列表的播放能力面。
  late MovaEngine _engine;

  /// Drives current-index tracking and prev/next/auto-advance navigation.
  ///
  /// 驱动当前下标跟踪与上一集/下一集/自动续播导航。
  late MovaPlaylist _controller;

  @override
  void initState() {
    super.initState();
    _engine = createMovaEngine(
      options: MovaOpts(
        playlist: MovaPlaylistConfig(enabled: true, items: _playlistItems),
      ),
    );
    _controller = MovaPlaylist(_engine);
    // The controller never opens the first item on its own — the host kicks
    // playback off.
    //
    // 控制器不会自动打开首项——由宿主起播。
    _controller.jumpTo(0);
  }

  @override
  void dispose() {
    _controller.dispose();
    _engine.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('播放列表 + 下一集')),
      body: Column(
        children: [
          AspectRatio(
            aspectRatio: 16 / 9,
            child: MovaPlayer(
              api: _engine,
              // Patch the "next up" card into the overlay slot; it reads the
              // controller directly for the running index.
              //
              // 把"下一集"卡片补进 overlay 槽位;它直接从控制器读取运行时下标。
              skin: MovaDefaultSkin(
                patches: [MovaPatch.add(MovaSlot.overlay, MovaNextUpComponent(_controller))],
              ),
            ),
          ),
          // Manual navigation, mirroring what auto-advance and the card do.
          //
          // 手动导航,与自动续播、卡片所做的一致。
          Padding(
            padding: const EdgeInsets.all(16),
            child: StreamBuilder<int>(
              stream: _controller.indexChanges,
              builder: (context, _) {
                final item = _controller.currentItem;
                return Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    TextButton.icon(
                      onPressed: _controller.hasPrevious ? _controller.previous : null,
                      icon: const Icon(Icons.skip_previous_rounded),
                      label: const Text('上一集'),
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      child: Text(item?.displayTitle ?? '—'),
                    ),
                    TextButton.icon(
                      onPressed: _controller.hasNext ? _controller.next : null,
                      icon: const Icon(Icons.skip_next_rounded),
                      label: const Text('下一集'),
                    ),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

/// Content + ad schedule for the ad demo: a pre-roll and a mid-roll at 10s,
/// both skippable after 3s, built from the shared sample clips.
///
/// 广告演示的正片 + 广告排期:一个前贴片、一个 10 秒处的中插,均 3 秒后可跳过,
/// 复用共享样片构建。
final _adContent = MovaSource(_feedSources[0], title: '正片');
final _adBreaks = [
  MovaAdBreak(
    kind: MovaAdBreakKind.pre,
    source: MovaSource(_feedSources[1]),
    skippableAfter: const Duration(seconds: 3),
    clickThroughUrl: 'https://example.com/ad',
  ),
  MovaAdBreak(
    kind: MovaAdBreakKind.mid,
    source: MovaSource(_feedSources[2]),
    offset: const Duration(seconds: 10),
    skippableAfter: const Duration(seconds: 3),
  ),
];

/// A minimal, always-seamless ad demo: no manual toggle, seamless swapping is
/// on from the moment the page opens, and the shadow starts warming the
/// content up the instant the ad itself starts (via [MovaEagerWarm]) rather
/// than waiting for the ad's last couple of seconds — so the content gets
/// the ad's *entire* runtime to actually download and buffer over the
/// network, instead of the ~2s [MovaLeadWarm] budget that turned out to be
/// too tight for a real network fetch on a real device. This page exists
/// purely to acceptance-test "no black frame, or at most a flash" — see
/// doc/plans/2026-09-16-seamless-swap.md Task 11.
///
/// 一个默认即开启无缝、没有手动开关的最小广告演示:从页面一打开就是无缝切换
/// 状态,且影子引擎从广告**一开始播放**就开始预热正片(用 [MovaEagerWarm]),
/// 而不是等到广告最后一两秒——这样正片能拿到整段广告的时长去真正走网络下载、
/// 缓冲,而不是 [MovaLeadWarm] 那约 2 秒的预算(真机上验证过对真实网络下载来说
/// 太紧)。这个页面存在的唯一目的就是验收"没有黑屏,或最多一闪而过"——见
/// doc/plans/2026-09-16-seamless-swap.md Task 11。
class SeamlessAdDemoPage extends StatefulWidget {
  /// Creates the always-seamless ad demo page.
  ///
  /// 创建默认无缝的广告演示页面。
  const SeamlessAdDemoPage({super.key});

  @override
  State<SeamlessAdDemoPage> createState() => _SeamlessAdDemoPageState();
}

/// State for [SeamlessAdDemoPage]; owns the [MovaCutoverEngine] and its ad
/// controller for the lifetime of the page.
///
/// [SeamlessAdDemoPage] 的状态;在页面生命周期内持有 [MovaCutoverEngine] 与其
/// 广告控制器。
class _SeamlessAdDemoPageState extends State<SeamlessAdDemoPage> {
  /// The cutover engine ads run on — always seamless on this page.
  ///
  /// 广告运行其上的切换引擎——本页始终无缝。
  late final MovaCutoverEngine _engine;

  /// Orchestrates the pre/mid/post-roll ads and drives [_engine]'s cutover.
  ///
  /// 编排前/中/后贴片广告,并驱动 [_engine] 的切换。
  late final MovaAds _controller;

  /// The most recent ad lifecycle event, shown so the callback is visible.
  ///
  /// 最近一次广告生命周期事件,展示出来以便看到回调。
  final ValueNotifier<String> _lastEvent = ValueNotifier<String>('—');

  @override
  void initState() {
    super.initState();
    final opts = MovaOpts(
      ads: MovaAdConfig(enabled: true, breaks: _adBreaks, onAdEvent: _onAdEvent),
      // MovaEagerWarm: start warming the instant the ad starts, not just its
      // last couple of seconds — see the class doc above for why.
      //
      // MovaEagerWarm:广告一开始播放就预热,而非只在最后一两秒——原因见
      // 上方类注释。
      cutover: const MovaCutoverConfig(enabled: true, trigger: MovaEagerWarm()),
    );
    _engine = MovaCutoverEngine(engineFactory: () => createMovaEngine(options: opts));
    _controller = MovaAds(_engine, cutover: _engine);
    _controller.load(_adContent);
  }

  /// Records an ad event for display.
  ///
  /// 记录一次广告事件用于展示。
  void _onAdEvent(MovaAdEvent e) {
    final url = e.type == MovaAdEventType.clicked ? e.adBreak.clickThroughUrl : null;
    _lastEvent.value = url == null ? e.type.name : '${e.type.name} → $url';
  }

  @override
  void dispose() {
    _controller.dispose();
    _engine.dispose();
    _lastEvent.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('无缝广告演示(默认开启)')),
      body: Column(
        children: [
          AspectRatio(
            aspectRatio: 16 / 9,
            child: MovaPlayer(
              api: _engine,
              skin: MovaDefaultSkin(
                patches: [MovaPatch.add(MovaSlot.overlay, MovaAdOverlayComponent(_controller))],
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                TextButton.icon(
                  onPressed: () => _controller.playAdNow(MovaAdBreak(
                    kind: MovaAdBreakKind.mid,
                    source: MovaSource(_feedSources[2]),
                    skippableAfter: const Duration(seconds: 2),
                  )),
                  icon: const Icon(Icons.ad_units_rounded),
                  label: const Text('此刻插入广告'),
                ),
                ValueListenableBuilder<String>(
                  valueListenable: _lastEvent,
                  builder: (context, value, _) => Text('广告事件:$value'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

/// A page demoing pre/mid-roll ads plus runtime insertion: a [MovaAds]
/// orchestrates the content↔ad source swaps, [MovaAdOverlayComponent] renders the
/// badge/skip/countdown, a button inserts an ad at the current position via
/// [MovaAds.playAdNow], and click-through is surfaced through
/// [MovaAdConfig.onAdEvent] (no url_launcher — the host decides what to do).
///
/// 演示前/中贴片广告与运行时插入:[MovaAds] 编排正片↔广告的源切换,
/// [MovaAdOverlayComponent] 渲染角标/跳过/倒计时,一个按钮经
/// [MovaAds.playAdNow] 在当前位置插播广告,点击跳转经
/// [MovaAdConfig.onAdEvent] 暴露(不引 url_launcher——由宿主决定如何处理)。
class AdDemoPage extends StatefulWidget {
  /// Creates the ad demo page.
  ///
  /// 创建广告演示页面。
  const AdDemoPage({super.key});

  @override
  State<AdDemoPage> createState() => _AdDemoPageState();
}

/// State for [AdDemoPage]; owns the engine, the ad controller, and the last
/// reported ad event for display.
///
/// [AdDemoPage] 的状态;持有引擎、广告控制器,以及用于展示的最近一次广告事件。
class _AdDemoPageState extends State<AdDemoPage> {
  /// The playback facade the ads run on — a plain [MovaEngine], or a
  /// [MovaCutoverEngine] wrapping one when [_seamless] is on.
  ///
  /// 广告运行其上的播放能力面——普通 [MovaEngine],或 [_seamless] 开启时包裹
  /// 它的 [MovaCutoverEngine]。
  late MovaApi _engine;

  /// Orchestrates the pre/mid/post-roll and runtime-inserted ads.
  ///
  /// 编排前/中/后贴片与运行时插入的广告。
  late MovaAds _controller;

  /// The most recent ad lifecycle event, shown so the callback is visible.
  ///
  /// 最近一次广告生命周期事件,展示出来以便看到回调。
  final ValueNotifier<String> _lastEvent = ValueNotifier<String>('—');

  /// Whether the ad→content resume uses [MovaCutoverEngine] (no black
  /// frame) instead of today's plain `open()` rebuild. Off by default,
  /// matching [MovaCutoverConfig.enabled]'s own default — this toggle is what
  /// on-device verification (Task 11) flips back and forth to compare.
  ///
  /// 广告→正片续播是否走 [MovaCutoverEngine](无黑屏),而非今天的普通 `open()`
  /// 重建。默认关闭,对齐 [MovaCutoverConfig.enabled] 自身的默认值——这个开关就是
  /// 真机验证(Task 11)用来来回切换对比的那个。
  bool _seamless = false;

  @override
  void initState() {
    super.initState();
    _buildEngine();
  }

  /// (Re)builds [_engine]/[_controller] for the current [_seamless] setting.
  ///
  /// 按当前 [_seamless] 设置(重新)构建 [_engine]/[_controller]。
  void _buildEngine() {
    MovaOpts optsFor() => MovaOpts(
          ads: MovaAdConfig(enabled: true, breaks: _adBreaks, onAdEvent: _onAdEvent),
          cutover: MovaCutoverConfig(enabled: _seamless),
        );
    if (_seamless) {
      final cutover = MovaCutoverEngine(engineFactory: () => createMovaEngine(options: optsFor()));
      _engine = cutover;
      _controller = MovaAds(cutover, cutover: cutover);
    } else {
      final engine = createMovaEngine(options: optsFor());
      _engine = engine;
      _controller = MovaAds(engine);
    }
    _controller.load(_adContent);
  }

  /// Tears down the current engine/controller and rebuilds with [_seamless]
  /// flipped.
  ///
  /// 释放当前引擎/控制器,并以翻转后的 [_seamless] 重建。
  Future<void> _toggleSeamless(bool value) async {
    final oldController = _controller;
    final oldEngine = _engine;
    setState(() {
      _seamless = value;
      _buildEngine();
    });
    await oldController.dispose();
    await oldEngine.dispose();
  }

  /// Records an ad event for display; a real host would act on a
  /// [MovaAdEventType.clicked] event's click-through URL here.
  ///
  /// 记录一次广告事件用于展示;真实宿主会在此处理 [MovaAdEventType.clicked]
  /// 事件的点击跳转地址。
  void _onAdEvent(MovaAdEvent e) {
    final url = e.type == MovaAdEventType.clicked ? e.adBreak.clickThroughUrl : null;
    _lastEvent.value = url == null ? e.type.name : '${e.type.name} → $url';
  }

  @override
  void dispose() {
    _controller.dispose();
    _engine.dispose();
    _lastEvent.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('广告演示')),
      body: Column(
        children: [
          AspectRatio(
            aspectRatio: 16 / 9,
            child: MovaPlayer(
              api: _engine,
              // Patch the ad overlay into the overlay slot; it reads the
              // controller for the current ad and skip state.
              //
              // 把广告叠层补进 overlay 槽位;它从控制器读取当前广告与跳过状态。
              skin: MovaDefaultSkin(
                patches: [MovaPatch.add(MovaSlot.overlay, MovaAdOverlayComponent(_controller))],
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                // Toggles between the plain open()-rebuild resume and the
                // seamless MovaCutoverEngine path, for on-device A/B comparison.
                //
                // 在普通 open() 重建续播与无缝 MovaCutoverEngine 路径间切换,
                // 供真机 A/B 对比。
                SwitchListTile(
                  value: _seamless,
                  onChanged: _toggleSeamless,
                  title: const Text('无缝切换(MovaCutoverEngine)'),
                  subtitle: const Text('开启后广告→正片续播不经过黑屏/loading'),
                ),
                // Insert an ad at the current content position on demand.
                //
                // 按需在当前正片位置插播一条广告。
                TextButton.icon(
                  onPressed: () => _controller.playAdNow(MovaAdBreak(
                    kind: MovaAdBreakKind.mid,
                    source: MovaSource(_feedSources[2]),
                    skippableAfter: const Duration(seconds: 2),
                  )),
                  icon: const Icon(Icons.ad_units_rounded),
                  label: const Text('此刻插入广告'),
                ),
                ValueListenableBuilder<String>(
                  valueListenable: _lastEvent,
                  builder: (context, value, _) => Text('广告事件:$value'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

/// Ad-orchestration demo for 0.5.0: the `delay` countdown, the fixed-slot
/// `duration`, the per-kind readiness wait, and the load-failure fallback —
/// each behind its own switch so a device run can flip one variable at a time.
///
/// A separate page from [AdDemoPage] on purpose: these four knobs interact, and
/// the on-screen log below is what makes a device run evidential. The log is
/// fed by **real** callbacks — [MovaAdConfig.onAdEvent] and the engine's own
/// [MovaCutoverChange] events — not by print statements, so a release build on a
/// phone with no logcat access still shows what actually happened and when.
///
/// 0.5.0 的广告编排演示:`delay` 倒计时、定长 `duration`、按类型的就绪等待、
/// 加载失败兜底——每项各有开关,使真机验证能一次只动一个变量。
///
/// 刻意与 [AdDemoPage] 分开建页:这四个旋钮彼此有交互,而下方的屏上日志正是让
/// 真机验证"有据可查"的关键。日志由**真实**回调打点——[MovaAdConfig.onAdEvent]
/// 与引擎自身的 [MovaCutoverChange] 事件——而非 print,因此在拿不到 logcat 的手机
/// release 包上也能看清到底发生了什么、何时发生。
class AdOrchestrationDemoPage extends StatefulWidget {
  /// Creates the ad-orchestration demo page.
  ///
  /// 创建广告编排演示页面。
  const AdOrchestrationDemoPage({super.key});

  @override
  State<AdOrchestrationDemoPage> createState() => _AdOrchestrationDemoPageState();
}

/// State for [AdOrchestrationDemoPage]; rebuilds the engine whenever a switch
/// changes, because the ad schedule is read once at construction.
///
/// [AdOrchestrationDemoPage] 的状态;任一开关变化都重建引擎,因为广告排期在构造时
/// 只读取一次。
class _AdOrchestrationDemoPageState extends State<AdOrchestrationDemoPage> {
  /// The cutover engine every variant runs on; waiting for readiness needs one.
  ///
  /// 所有变体都运行其上的切换引擎;等待就绪必须有它。
  late MovaCutoverEngine _engine;

  /// Orchestrates the demo's ad schedule.
  ///
  /// 编排本演示的广告排期。
  late MovaAds _controller;

  /// Subscription to the engine's own events, for the cutover-phase log lines.
  ///
  /// 对引擎自身事件的订阅,用于记录切换阶段日志行。
  StreamSubscription<MovaEvent>? _eventSub;

  /// Whether the mid-roll carries a 3s visible countdown.
  ///
  /// 中插是否带 3 秒可见倒计时。
  bool _delay = false;

  /// Whether the mid-roll is force-resumed after 8s regardless of the media.
  ///
  /// 中插是否在 8 秒后被强制续播(与素材长度无关)。
  bool _duration = false;

  /// Whether mid-rolls wait for readiness before cutting in (the 0.5.0
  /// default).
  ///
  /// 中插是否等待就绪后才切入(0.5.0 的默认值)。
  bool _waitForMid = true;

  /// Whether the mid-roll points at a deliberately broken URL.
  ///
  /// 中插是否指向一个故意写坏的地址。
  bool _breakTheAd = false;

  /// The most recent log lines, newest last.
  ///
  /// 最近的日志行,最新的在最后。
  final ValueNotifier<List<String>> _log = ValueNotifier<List<String>>(<String>[]);

  /// Wall-clock origin for the log's relative timestamps.
  ///
  /// 日志相对时间戳的墙钟起点。
  final Stopwatch _clock = Stopwatch()..start();

  @override
  void initState() {
    super.initState();
    _build();
  }

  /// Appends one timestamped line to the on-screen log.
  ///
  /// 向屏上日志追加一行带时间戳的记录。
  void _note(String line) {
    final t = (_clock.elapsedMilliseconds / 1000).toStringAsFixed(2);
    final next = <String>[..._log.value, '[${t}s] $line'];
    _log.value = next.length <= 40 ? next : next.sublist(next.length - 40);
  }

  /// The mid-roll for the current switch combination.
  ///
  /// 当前开关组合对应的中插广告位。
  MovaAdBreak get _mid => MovaAdBreak(
        kind: MovaAdBreakKind.mid,
        source: MovaSource(
          _breakTheAd ? 'https://host.invalid/definitely-missing.mp4' : _feedSources[2],
        ),
        offset: const Duration(seconds: 10),
        delay: _delay ? const Duration(seconds: 3) : Duration.zero,
        duration: _duration ? const Duration(seconds: 8) : null,
        // skippableAfter stays below duration: the assert in assertValid()
        // would otherwise fire, since a slot reclaimed before the skip control
        // appears is unskippable in practice.
        //
        // skippableAfter 保持小于 duration:否则 assertValid() 里的断言会触发,
        // 因为在跳过控件出现之前就被收回的广告位实际上不可跳过。
        skippableAfter: const Duration(seconds: 3),
      );

  /// (Re)builds the engine and controller for the current switches.
  ///
  /// 按当前开关(重新)构建引擎与控制器。
  void _build() {
    MovaOpts opts() => MovaOpts(
          ads: MovaAdConfig(
            enabled: true,
            breaks: [
              // A pre-roll, to show it does NOT wait by default.
              //
              // 一条前贴片,用于展示它默认*不*等待。
              MovaAdBreak(
                kind: MovaAdBreakKind.pre,
                source: MovaSource(_feedSources[1]),
                skippableAfter: const Duration(seconds: 3),
              ),
              _mid,
            ],
            onAdEvent: (e) =>
                _note('ad ${e.type.name}${e.error == null ? '' : ' (${e.error})'}'),
            waitForAdReady: MovaAdWaitByKind(mid: _waitForMid),
          ),
          cutover: const MovaCutoverConfig(enabled: true),
        );
    _engine = MovaCutoverEngine(engineFactory: () => createMovaEngine(options: opts()));
    _controller = MovaAds(_engine, cutover: _engine);
    _eventSub = _engine.events.listen((e) {
      if (e is MovaCutoverChange) _note('cutover ${e.phase.name}');
    });
    _controller.load(_adContent);
  }

  /// Tears the current engine down and rebuilds with the new switch values.
  ///
  /// 释放当前引擎并以新的开关值重建。
  Future<void> _rebuild(VoidCallback apply) async {
    final oldController = _controller;
    final oldEngine = _engine;
    final oldSub = _eventSub;
    setState(() {
      apply();
      _clock.reset();
      _log.value = <String>[];
      _build();
    });
    await oldSub?.cancel();
    await oldController.dispose();
    await oldEngine.dispose();
  }

  @override
  void dispose() {
    _eventSub?.cancel();
    _controller.dispose();
    _engine.dispose();
    _log.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('广告编排演示')),
      body: ListView(
        children: [
          AspectRatio(
            aspectRatio: 16 / 9,
            child: MovaPlayer(
              api: _engine,
              skin: MovaDefaultSkin(
                patches: [MovaPatch.add(MovaSlot.overlay, MovaAdOverlayComponent(_controller))],
              ),
            ),
          ),
          SwitchListTile(
            value: _delay,
            onChanged: (v) => _rebuild(() => _delay = v),
            title: const Text('delay:中插前 3 秒倒计时'),
            subtitle: const Text('倒计时期间正片继续播,角标显示"N 秒后播放广告"'),
          ),
          SwitchListTile(
            value: _duration,
            onChanged: (v) => _rebuild(() => _duration = v),
            title: const Text('duration:中插固定 8 秒'),
            subtitle: const Text('素材更长也会被准时收回,且不应卡死'),
          ),
          SwitchListTile(
            value: _waitForMid,
            onChanged: (v) => _rebuild(() => _waitForMid = v),
            title: const Text('等待就绪(中插,默认开)'),
            subtitle: const Text('开:预热好才原子切入;关:立刻硬切。前贴片始终不等待'),
          ),
          SwitchListTile(
            value: _breakTheAd,
            onChanged: (v) => _rebuild(() => _breakTheAd = v),
            title: const Text('把中插换成坏地址'),
            subtitle: const Text('走失败兜底:默认跳过该条、正片正常续播'),
          ),
          const Divider(),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Text('事件日志(真实回调打点)', style: Theme.of(context).textTheme.titleSmall),
          ),
          ValueListenableBuilder<List<String>>(
            valueListenable: _log,
            builder: (context, lines, _) => Padding(
              padding: const EdgeInsets.all(16),
              child: Text(
                lines.isEmpty ? '—' : lines.join('\n'),
                style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
1
likes
0
points
645
downloads

Publisher

unverified uploader

Weekly Downloads

media_kit (libmpv/ffmpeg) based video player plugin with gestures, VOD/live control bar, quality switching with ABR and picture-in-picture.

Repository (GitHub)
View/report issues

Topics

#video #player #media-kit #hls #picture-in-picture

License

unknown (license)

Dependencies

connectivity_plus, flutter, media_kit, media_kit_libs_video, media_kit_video, meta, path_provider, plugin_platform_interface, screen_brightness

More

Packages that depend on mova

Packages that implement mova