FixNewVideoTasks720pCommand.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <?php
  2. namespace App\Console\Commands;
  3. use GuzzleHttp\Client;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\DB;
  6. /**
  7. * 处理 id >= 12835 的新数据视频任务(动漫 act/分镜链路):
  8. * 1. 480p 档任务切换为 720p(处理 480p -> 720p 档位残留);
  9. * 2. 检查 sr_720p / 720p / 480p 成功任务的 result_url、compressed_url 是否真的是 720p:
  10. * - result 为 480p 档 -> 本地超分到 720p,重新压缩,更新任务两列 URL;
  11. * - result 已是 720p+ 但 compressed 为 480p 档 -> 基于 result 重新压缩;
  12. * - 同步关联 mp_episode_segments 的 origin_video_url / video_url(仅 URL,其余字段不动);
  13. * - 同步关联 mp_anime_records 中 assistant 记录(video_url 指向该任务旧 result_url)为修复后的 result_url。
  14. *
  15. * 注意:本命令依赖 ffmpeg/ffprobe 且需在 APP_ENV != local 的环境执行
  16. * (upgrade480pTo720p / compressVideo 在 local 会短路)。
  17. */
  18. class FixNewVideoTasks720pCommand extends Command
  19. {
  20. /**
  21. * @var string
  22. */
  23. protected $signature = 'video:fix-new-tasks-720p
  24. {--min-id=12835 : 只处理 id 大于等于该值的任务}
  25. {--apply : 真正执行超分与更新;不带此参数时仅探测并输出报告}';
  26. /**
  27. * @var string
  28. */
  29. protected $description = '检查并修复 id>=12835 新数据任务的 720p 交付(超分 result/compressed 并同步分镜 URL)';
  30. /**
  31. * @return int
  32. */
  33. public function handle(): int
  34. {
  35. if (env('APP_ENV') === 'local') {
  36. $this->error('本命令需要在 APP_ENV != local 且安装 ffmpeg/ffprobe 的环境执行(local 下超分/压缩 helper 会短路)。');
  37. return 1;
  38. }
  39. $apply = (bool)$this->option('apply');
  40. $minId = (int)$this->option('min-id');
  41. $this->info($apply ? '开始执行修复(--apply)...' : '检查模式:仅探测与输出报告,加 --apply 才会超分并更新。');
  42. $tasks = DB::table('mp_generate_video_tasks')
  43. ->select([
  44. 'id', 'video_resolution', 'status', 'api_type',
  45. 'alias_segment_id', 'alias_act_id', 'result_url', 'compressed_url',
  46. ])
  47. ->where('id', '>=', $minId)
  48. ->whereIn('video_resolution', ['sr_720p', '720p', '480p'])
  49. ->where('status', 'success')
  50. ->whereNotNull('result_url')
  51. ->where('result_url', '<>', '')
  52. ->orderBy('id')
  53. ->get();
  54. $this->line(sprintf('候选任务数:%d', $tasks->count()));
  55. $alreadyOk = 0;
  56. $needResultFix = 0;
  57. $needCompressedFix = 0;
  58. $probeFailed = 0;
  59. $updated = 0;
  60. foreach ($tasks as $task) {
  61. $resultProbe = $this->probeUrl($task->result_url);
  62. if (!$resultProbe['ok']) {
  63. $probeFailed++;
  64. $this->warn(sprintf('#%d 探测 result_url 失败:%s', $task->id, $task->result_url));
  65. continue;
  66. }
  67. $resultShort = min($resultProbe['width'], $resultProbe['height']);
  68. $resultIs480 = $resultShort > 0 && abs($resultShort - 480) <= 60;
  69. $compressedShort = null;
  70. if (!empty($task->compressed_url)) {
  71. $compProbe = $this->probeUrl($task->compressed_url);
  72. if ($compProbe['ok']) {
  73. $compressedShort = min($compProbe['width'], $compProbe['height']);
  74. }
  75. }
  76. $compressedIs480 = $compressedShort !== null && abs($compressedShort - 480) <= 60;
  77. $this->line(sprintf(
  78. '#%d [%s] result=%dx%d compressed=%s%s',
  79. $task->id,
  80. $task->video_resolution,
  81. $resultProbe['width'],
  82. $resultProbe['height'],
  83. $compressedShort === null ? '?' : $compressedShort,
  84. $compressedShort === null ? ' (探测失败)' : ''
  85. ));
  86. $needChange = false;
  87. $newResult = $task->result_url;
  88. $newCompressed = $task->compressed_url;
  89. if ($resultIs480) {
  90. $needResultFix++;
  91. $needChange = true;
  92. if ($apply) {
  93. $enhanced = upgrade480pTo720p($task->result_url, 'video', false, '720p');
  94. if ($enhanced && $enhanced !== $task->result_url) {
  95. $newResult = $enhanced;
  96. $compressed = compressVideo($enhanced);
  97. $newCompressed = $compressed ?: $enhanced;
  98. $this->line(sprintf(
  99. ' -> 超分完成:%s%s',
  100. $newResult,
  101. $compressed ? '' : '(重新压缩失败,compressed_url 使用超分结果)'
  102. ));
  103. } else {
  104. $this->warn(sprintf('#%d 超分失败,保留原 result_url', $task->id));
  105. $needChange = false;
  106. }
  107. }
  108. } elseif ($compressedIs480 && !empty($task->compressed_url)) {
  109. $needCompressedFix++;
  110. $needChange = true;
  111. if ($apply) {
  112. $compressed = compressVideo($task->result_url);
  113. if ($compressed) {
  114. $newCompressed = $compressed;
  115. $this->line(' -> 基于已合格的 result 重新压缩完成');
  116. } else {
  117. $this->warn(sprintf('#%d 重新压缩失败,compressed_url 保持不变', $task->id));
  118. $needChange = false;
  119. }
  120. }
  121. } else {
  122. $alreadyOk++;
  123. }
  124. if (!$needChange) {
  125. continue;
  126. }
  127. if ($apply) {
  128. DB::table('mp_generate_video_tasks')
  129. ->where('id', $task->id)
  130. ->update([
  131. 'result_url' => $newResult,
  132. 'compressed_url' => $newCompressed,
  133. ]);
  134. $segmentSynced = $this->syncSegmentUrls($task, $newResult, $newCompressed);
  135. $recordSynced = $this->syncAnimeRecordUrls($task, $newResult);
  136. $this->line(sprintf(
  137. '#%d 已更新任务 URL(分镜同步:%s;anime_records 同步:%d 条)',
  138. $task->id,
  139. $segmentSynced ? '是' : '跳过/无关联',
  140. $recordSynced
  141. ));
  142. $updated++;
  143. }
  144. }
  145. $this->info(sprintf(
  146. '汇总:待超分 result=%d,需重压 compressed=%d,已合格=%d,探测失败=%d,已更新任务=%d',
  147. $needResultFix,
  148. $needCompressedFix,
  149. $alreadyOk,
  150. $probeFailed,
  151. $updated
  152. ));
  153. if (!$apply) {
  154. $this->line('以上为检查结果;确认后在生产环境加 --apply 执行。');
  155. }
  156. return 0;
  157. }
  158. /**
  159. * 下载并探测视频分辨率
  160. *
  161. * @param string $url
  162. * @return array{ok:bool, width:int, height:int}
  163. */
  164. private function probeUrl(string $url): array
  165. {
  166. $tempDir = storage_path('app/temp/video_fix_check');
  167. if (!is_dir($tempDir)) {
  168. mkdir($tempDir, 0775, true);
  169. }
  170. $inputFile = '';
  171. try {
  172. $ext = getVideoExtFromUrl($url) ?: '.mp4';
  173. $inputFile = $tempDir . '/' . uniqid('vfix_') . bin2hex(random_bytes(3)) . $ext;
  174. $client = new Client(['timeout' => 300, 'verify' => false]);
  175. $client->get($url, ['sink' => $inputFile]);
  176. if (!file_exists($inputFile) || filesize($inputFile) <= 0) {
  177. return ['ok' => false, 'width' => 0, 'height' => 0];
  178. }
  179. $ffprobe = env('FFPROBE_PATH', 'ffprobe');
  180. $cmd = '"' . $ffprobe . '" -v quiet -print_format json -show_streams "' . $inputFile . '" 2>&1';
  181. $output = shell_exec($cmd);
  182. $info = json_decode((string)$output, true);
  183. $width = 0;
  184. $height = 0;
  185. if (isset($info['streams']) && is_array($info['streams'])) {
  186. foreach ($info['streams'] as $stream) {
  187. if (isset($stream['codec_type']) && $stream['codec_type'] === 'video') {
  188. $width = (int)($stream['width'] ?? 0);
  189. $height = (int)($stream['height'] ?? 0);
  190. break;
  191. }
  192. }
  193. }
  194. return ['ok' => $width > 0 && $height > 0, 'width' => $width, 'height' => $height];
  195. } catch (\Throwable $e) {
  196. return ['ok' => false, 'width' => 0, 'height' => 0];
  197. } finally {
  198. if ($inputFile && file_exists($inputFile)) {
  199. @unlink($inputFile);
  200. }
  201. }
  202. }
  203. /**
  204. * 同步 mp_anime_records 中 assistant 对话记录的 video_url
  205. * 仅更新 video_task_id 匹配、role=assistant 且 video_url 仍指向该任务旧 result_url 的行,
  206. * 避免覆盖同 act 其他任务写入的记录。
  207. *
  208. * @param object $task
  209. * @param string $newResultUrl
  210. * @return int 更新的记录数
  211. */
  212. private function syncAnimeRecordUrls($task, string $newResultUrl): int
  213. {
  214. return DB::table('mp_anime_records')
  215. ->where('video_task_id', $task->id)
  216. ->where('role', 'assistant')
  217. ->where('video_url', $task->result_url)
  218. ->update(['video_url' => $newResultUrl]);
  219. }
  220. /**
  221. * 同步关联 mp_episode_segments 的 URL(仅 origin_video_url / video_url)
  222. * 仅当分镜当前指向的就是该任务旧 URL 时才更新,避免覆盖同一分镜更新任务的产物。
  223. *
  224. * @param object $task
  225. * @param string $newResultUrl
  226. * @param string $newCompressedUrl
  227. * @return bool
  228. */
  229. private function syncSegmentUrls($task, string $newResultUrl, string $newCompressedUrl): bool
  230. {
  231. if (!empty($task->alias_segment_id)) {
  232. $segment = DB::table('mp_episode_segments')
  233. ->where('segment_id', $task->alias_segment_id)
  234. ->first(['id', 'origin_video_url', 'video_url']);
  235. if (!$segment) {
  236. return false;
  237. }
  238. $pointsToThisTask = $segment->origin_video_url === $task->result_url
  239. || $segment->video_url === $task->compressed_url;
  240. if (!$pointsToThisTask) {
  241. return false;
  242. }
  243. DB::table('mp_episode_segments')
  244. ->where('id', $segment->id)
  245. ->update([
  246. 'origin_video_url' => $newResultUrl,
  247. 'video_url' => $newCompressedUrl,
  248. ]);
  249. return true;
  250. }
  251. if (!empty($task->alias_act_id)) {
  252. $segment = DB::table('mp_episode_segments')
  253. ->where('id', $task->alias_act_id)
  254. ->first(['id', 'origin_video_url', 'video_url']);
  255. if (!$segment) {
  256. return false;
  257. }
  258. $pointsToThisTask = $segment->origin_video_url === $task->result_url
  259. || $segment->video_url === $task->compressed_url;
  260. if (!$pointsToThisTask) {
  261. return false;
  262. }
  263. DB::table('mp_episode_segments')
  264. ->where('id', $segment->id)
  265. ->update([
  266. 'origin_video_url' => $newResultUrl,
  267. 'video_url' => $newCompressedUrl,
  268. ]);
  269. return true;
  270. }
  271. return false;
  272. }
  273. }