video_playback_diagnostics.dart 2.06 KB
import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:video_player/video_player.dart';
import 'package:wow_english/utils/toast_util.dart';

/// Shared timeout and user-visible diagnostics for video_player based screens.
class VideoPlaybackDiagnostics {
  static const initializeTimeout = Duration(seconds: 10);
  static const commandTimeout = Duration(seconds: 5);
  static const bufferingWarningDelay = Duration(seconds: 10);

  /// Starts native player disposal while keeping a stuck teardown bounded.
  static Future<void> disposeController(
    VideoPlayerController controller, {
    required String context,
  }) async {
    try {
      await controller.dispose().timeout(commandTimeout);
    } catch (error) {
      debugPrint('$context播放器释放失败或超时: $error');
    }
  }

  static String messageFor(Object error, {required String stage}) {
    final detail = error.toString().toLowerCase();
    if (error is TimeoutException) {
      if (stage == '视频初始化') return '视频初始化超时,请检查网络或设备解码能力';
      if (stage == '播放器配置') return '播放器配置超时,设备可能不支持当前播放参数';
      if (stage == '恢复播放进度') return '恢复播放进度超时';
      return '$stage超时';
    }
    if (detail.contains('decoder') ||
        detail.contains('codec') ||
        detail.contains('mediacodec') ||
        detail.contains('acodec')) {
      return '视频解码器启动失败,可能是设备兼容性问题';
    }
    if (detail.contains('http') ||
        detail.contains('socket') ||
        detail.contains('network') ||
        detail.contains('connection') ||
        detail.contains('source error') ||
        detail.contains('sourceerror')) {
      return '视频网络请求失败,请检查网络或视频地址';
    }
    return '$stage失败,请重试';
  }

  static void show(String message, {int? videoId}) {
    final idSuffix = videoId == null ? '' : '(视频ID: $videoId)';
    showToast('$message$idSuffix', duration: const Duration(seconds: 4));
  }
}