AnimeController.php 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987
  1. <?php
  2. namespace App\Http\Controllers\Anime;
  3. use App\Transformer\Anime\AnimeTransformer;
  4. use App\Facade\Site;
  5. use App\Consts\ErrorConst;
  6. use App\Exceptions\ApiException;
  7. use App\Libs\ApiResponse;
  8. use App\Libs\Utils;
  9. use App\Models\MpGenerateVideoTask;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use App\Services\AIGeneration\AIVideoGenerationService;
  12. use App\Services\Anime\AnimeService;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Routing\Controller as BaseController;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Redis;
  17. use Illuminate\Support\Facades\Validator;
  18. class AnimeController extends BaseController
  19. {
  20. use ApiResponse;
  21. protected $AnimeService;
  22. protected $AIImageGenerationService;
  23. protected $AIVideoGenerationService;
  24. public function __construct(
  25. AnimeService $AnimeService,
  26. AIImageGenerationService $AIImageGenerationService,
  27. AIVideoGenerationService $AIVideoGenerationService
  28. ) {
  29. $this->AnimeService = $AnimeService;
  30. $this->AIImageGenerationService = $AIImageGenerationService;
  31. $this->AIVideoGenerationService = $AIVideoGenerationService;
  32. }
  33. // 文字模型
  34. public function textModel() {
  35. $query = DB::table('mp_text_models')->where('is_enabled', 1);
  36. // 支持 model 搜索
  37. if ($model = request('model')) {
  38. $query->where('model', 'like', "%{$model}%");
  39. }
  40. // 支持 name 搜索
  41. if ($name = request('name')) {
  42. $query->where('name', 'like', "%{$name}%");
  43. }
  44. $models = $query->select('model', 'name')->get()->map(function ($value) {
  45. return (array)$value;
  46. })->toArray();
  47. return $this->success($models);
  48. }
  49. // 图片模型
  50. public function imageModel() {
  51. $query = DB::table('mp_image_models')->where('is_enabled', 1);
  52. // 支持 model 搜索
  53. if ($model = request('model')) {
  54. $query->where('model', 'like', "%{$model}%");
  55. }
  56. // 支持 name 搜索
  57. if ($name = request('name')) {
  58. $query->where('name', 'like', "%{$name}%");
  59. }
  60. $models = $query->select('model', 'name')->get()->map(function ($value) {
  61. return (array)$value;
  62. })->toArray();
  63. return $this->success($models);
  64. }
  65. // 视频模型
  66. public function videoModel() {
  67. $query = DB::table('mp_video_models')->where('is_enabled', 1);
  68. // 支持 model 搜索
  69. if ($model = request('model')) {
  70. $query->where('model', 'like', "%{$model}%");
  71. }
  72. // 支持 name 搜索
  73. if ($name = request('name')) {
  74. $query->where('name', 'like', "%{$name}%");
  75. }
  76. $models = $query->select('model', 'name')->get()->map(function ($value) {
  77. return (array)$value;
  78. })->toArray();
  79. return $this->success($models);
  80. }
  81. public function artStyleList()
  82. {
  83. $result = [
  84. [
  85. 'art_style' => '唯美真人风格',
  86. 'pic_url' => "http://zw-ai.oss-cn-hangzhou.aliyuncs.com/mp_audio/art_styles/%E5%94%AF%E7%BE%8E%E7%9C%9F%E4%BA%BA.jpg"
  87. ],
  88. [
  89. 'art_style' => '真人古风风格',
  90. 'pic_url' => "http://zw-ai.oss-cn-hangzhou.aliyuncs.com/mp_audio/art_styles/%E7%9C%9F%E4%BA%BA%E5%8F%A4%E9%A3%8E.jpg"
  91. ],
  92. [
  93. 'art_style' => '日系动漫风格',
  94. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/日系动漫风格.jpg"
  95. ],
  96. [
  97. 'art_style' => '国漫风格',
  98. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/国漫风格.jpg"
  99. ],
  100. [
  101. 'art_style' => 'Q版卡通风格',
  102. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/Q版卡通风格.jpg"
  103. ],
  104. [
  105. 'art_style' => '简约扁平风格',
  106. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/简约扁平风格.jpg"
  107. ],
  108. [
  109. 'art_style' => '古风仙侠风格',
  110. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/古风仙侠风格.jpg"
  111. ],
  112. [
  113. 'art_style' => '武侠风格',
  114. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/武侠风格.jpg"
  115. ],
  116. [
  117. 'art_style' => '新中式水墨风格',
  118. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/新中式水墨风格.jpg"
  119. ],
  120. [
  121. 'art_style' => '写实插画风格',
  122. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/写实插画风格.jpg"
  123. ],
  124. [
  125. 'art_style' => '3D卡通风格',
  126. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/3D卡通风格.jpg"
  127. ],
  128. [
  129. 'art_style' => '条漫风格',
  130. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/条漫风格.jpg"
  131. ],
  132. [
  133. 'art_style' => '赛博朋克风格',
  134. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/赛博朋克风格.jpg"
  135. ],
  136. [
  137. 'art_style' => '暗黑悬疑风格',
  138. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/暗黑悬疑风格.jpg"
  139. ],
  140. [
  141. 'art_style' => '治愈清新风格',
  142. 'pic_url' => "https://cdn-zwai.ycsd.cn/mp_audio/art_styles/治愈清新风格.jpg"
  143. ],
  144. ];
  145. return $this->success($result);
  146. }
  147. // 新建动漫
  148. public function createAnime(Request $request) {
  149. $data = $request->all();
  150. $result = $this->AnimeService->createAnime($data);
  151. return $this->success(['anime_id' => $result]);
  152. }
  153. // 编辑动漫
  154. public function editAnime(Request $request) {
  155. $data = $request->all();
  156. $result = $this->AnimeService->editAnime($data);
  157. return $this->success(['success'=>$result ? 1 : 0]);
  158. }
  159. // 删除动漫
  160. public function delAnime(Request $request) {
  161. $data = $request->all();
  162. $result = $this->AnimeService->delAnime($data);
  163. return $this->success(['success'=>$result ? 1 : 0]);
  164. }
  165. // 批量生成主体图片
  166. public function batchSetRoleImg(Request $request) {
  167. // 忽略所有超时限制
  168. set_time_limit(0);
  169. ini_set('max_execution_time', '0');
  170. $data = $request->all();
  171. $result = $this->AnimeService->batchSetRoleImg($data);
  172. return $this->success($result);
  173. }
  174. // 批量生成场景图片
  175. public function batchSetSceneImg(Request $request) {
  176. // 忽略所有超时限制
  177. set_time_limit(0);
  178. ini_set('max_execution_time', '0');
  179. $data = $request->all();
  180. $result = $this->AnimeService->batchSetSceneImg($data);
  181. return $this->success($result);
  182. }
  183. // 修改分集主体列表
  184. public function changeEpisodeRoles(Request $request) {
  185. $data = $request->all();
  186. $result = $this->AnimeService->changeEpisodeRoles($data);
  187. return $this->success(['success'=>$result ? 1 : 0]);
  188. }
  189. // 修改分集场景列表
  190. public function changeEpisodeScenes(Request $request) {
  191. $data = $request->all();
  192. $result = $this->AnimeService->changeEpisodeScenes($data);
  193. return $this->success(['success'=>$result ? 1 : 0]);
  194. }
  195. // 编辑分镜剧本
  196. public function editSegment(Request $request) {
  197. $data = $request->all();
  198. $result = $this->AnimeService->editSegment($data);
  199. return $this->success(['success'=>$result ? 1 : 0]);
  200. }
  201. // 动漫对话列表
  202. public function chatList(Request $request) {
  203. $data = $request->all();
  204. $result = $this->AnimeService->chatList($data);
  205. return $this->success($result, [new AnimeTransformer(), 'newBuildChatList']);
  206. }
  207. // 动漫对话历史记录
  208. public function chatHistory(Request $request) {
  209. $data = $request->all();
  210. $result = $this->AnimeService->chatHistory($data);
  211. return $this->success($result);
  212. }
  213. // 动漫大纲
  214. public function animeDetail(Request $request) {
  215. $data = $request->all();
  216. $result = $this->AnimeService->animeDetail($data);
  217. return $this->success($result);
  218. }
  219. // 动漫剧集
  220. public function episodeInfo(Request $request) {
  221. $data = $request->all();
  222. $result = $this->AnimeService->episodeInfo($data);
  223. return $this->success($result);
  224. }
  225. // 分镜信息
  226. public function segmentInfo(Request $request) {
  227. $data = $request->all();
  228. $result = $this->AnimeService->segmentInfo($data);
  229. return $this->success($result);
  230. }
  231. // 复制剧集副本
  232. public function copyEpisodeVersion(Request $request) {
  233. $data = $request->all();
  234. $result = $this->AnimeService->copyEpisodeVersion($data);
  235. return $this->success($result);
  236. }
  237. // 剧集副本列表
  238. public function episodeVersions(Request $request) {
  239. $data = $request->all();
  240. $result = $this->AnimeService->episodeVersions($data);
  241. return $this->success($result);
  242. }
  243. // 绑定剧集副本
  244. public function bindEpisodeVersion(Request $request) {
  245. $data = $request->all();
  246. $result = $this->AnimeService->bindEpisodeVersion($data);
  247. return $this->success(['success' => $result ? 1 : 0]);
  248. }
  249. // 对话改图
  250. public function chatChangeImg(Request $request) {
  251. $data = $request->all();
  252. $result = $this->AnimeService->chatChangeImg($data);
  253. return $this->success(['img_url' => $result]);
  254. }
  255. public function segmentChatHistory(Request $request) {
  256. $data = $request->all();
  257. $result = $this->AnimeService->segmentChatHistory($data);
  258. return $this->success($result);
  259. }
  260. // 一键生成分镜
  261. public function batchSetSegmentPics(Request $request) {
  262. // 忽略所有超时限制
  263. set_time_limit(0);
  264. ini_set('max_execution_time', '0');
  265. $data = $request->all();
  266. $result = $this->AnimeService->batchSetSegmentPics($data);
  267. return $this->success($result);
  268. }
  269. // 重新生成分镜
  270. public function reGenerateSegment(Request $request) {
  271. // 忽略所有超时限制
  272. set_time_limit(0);
  273. ini_set('max_execution_time', '0');
  274. $data = $request->all();
  275. $result = $this->AnimeService->reGenerateSegment($data);
  276. return $this->success(['img_url'=>$result]);
  277. }
  278. // 添加分镜
  279. public function addSegment(Request $request) {
  280. // 忽略所有超时限制
  281. set_time_limit(0);
  282. ini_set('max_execution_time', '0');
  283. $data = $request->all();
  284. $result = $this->AnimeService->addSegment($data);
  285. return $this->success($result);
  286. }
  287. // 复制分镜
  288. public function copySegment(Request $request) {
  289. $data = $request->all();
  290. $result = $this->AnimeService->copySegment($data);
  291. return $this->success($result);
  292. }
  293. // 移动分镜
  294. public function moveSegment(Request $request) {
  295. $data = $request->all();
  296. $result = $this->AnimeService->moveSegment($data);
  297. return $this->success(['success'=>$result ? 1: 0]);
  298. }
  299. // 删除分镜
  300. public function delSegment(Request $request) {
  301. $data = $request->all();
  302. $result = $this->AnimeService->delSegment($data);
  303. return $this->success(['success'=>$result ? 1: 0]);
  304. }
  305. public function applySegment(Request $request) {
  306. $data = $request->all();
  307. $result = $this->AnimeService->applySegment($data);
  308. return $this->success(['success'=>$result ? 1: 0]);
  309. }
  310. // 分镜历史图片|视频
  311. public function segmentHistory(Request $request) {
  312. $data = $request->all();
  313. $result = $this->AnimeService->segmentHistory($data);
  314. return $this->success($result);
  315. }
  316. public function createSegmentVideoTask(Request $request) {
  317. $uid = Site::getUid();
  318. // 忽略所有超时限制
  319. set_time_limit(0);
  320. ini_set('max_execution_time', '0');
  321. $data = $request->all();
  322. // 验证参数
  323. $validator = Validator::make($data, [
  324. 'segment_id' => 'required|string',
  325. 'tail_frame' => 'nullable|string|max:500',
  326. ], [
  327. 'segment_id.required' => '分镜ID不能为空',
  328. 'tail_frame.max' => '尾帧描述不能超过500个字符',
  329. ]);
  330. if ($validator->fails()) {
  331. Utils::throwError('1002:' . $validator->errors()->first());
  332. }
  333. // 创建视频生成任务
  334. $result = $this->AnimeService->createSegmentVideoTask($data);
  335. $taskId = $result['task_id'];
  336. // 设置 SSE 响应头
  337. return response()->stream(function () use ($taskId, $result, $uid) {
  338. // 设置 SSE 响应头
  339. echo "data: " . json_encode([
  340. 'type' => 'init',
  341. 'data' => $result
  342. ]) . "\n\n";
  343. ob_flush();
  344. flush();
  345. $startTime = time();
  346. $maxDuration = 300; // 5分钟超时
  347. $checkInterval = 5; // 每5秒检查一次
  348. while (time() - $startTime < $maxDuration) {
  349. try {
  350. // 查询任务状态
  351. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  352. if (!$task) {
  353. echo "data: " . json_encode([
  354. 'type' => 'error',
  355. 'message' => '任务不存在'
  356. ]) . "\n\n";
  357. ob_flush();
  358. flush();
  359. break;
  360. }
  361. // 如果任务还在处理中,查询最新状态
  362. if ($task->status === 'processing') {
  363. // 根据任务类型查询不同的状态
  364. if ($task->task_type === 'jimeng') {
  365. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  366. } elseif ($task->task_type === 'keling') {
  367. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  368. } else {
  369. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  370. }
  371. if (isset($statusResult['status'])) {
  372. // 更新任务状态
  373. $task->update([
  374. 'status' => $statusResult['status'],
  375. 'result_url' => $statusResult['result_url'] ?? null,
  376. 'compressed_url' => $statusResult['compressed_url'] ?? null,
  377. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  378. 'error_message' => $statusResult['error_message'] ?? null,
  379. 'completed_at' => in_array($statusResult['status'], [
  380. 'success',
  381. 'failed'
  382. ]) ? now() : null
  383. ]);
  384. // 如果任务成功,更新分镜表
  385. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  386. try {
  387. DB::beginTransaction();
  388. $now = date('Y-m-d H:i:s');
  389. // 获取分镜ID
  390. $segment = DB::table('mp_episode_segments')
  391. ->where('video_task_id', $taskId)
  392. ->first();
  393. if (!$segment) {
  394. throw new \Exception('未找到对应的分镜记录');
  395. }
  396. $segmentId = $segment->segment_id;
  397. $anime_id = $segment->anime_id;
  398. $episode_number = $segment->episode_number;
  399. $tail_frame = $segment->tail_frame;
  400. // 更新分镜表
  401. $segmentUpdateData = [
  402. 'origin_video_url' => $statusResult['result_url'],
  403. 'video_task_status' => '已完成',
  404. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  405. 'current_type' => 2,
  406. 'updated_at' => $now
  407. ];
  408. $compressed_video_url = compressVideo($statusResult['result_url']);
  409. $segmentUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
  410. // 只有当video_duration存在且大于0时才更新
  411. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  412. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  413. $segmentUpdateData['video_time_point_start'] = 0;
  414. // $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  415. $segmentUpdateData['video_time_point_end'] = $segment->audio_duration ?? 0;
  416. }
  417. $updateResult = DB::table('mp_episode_segments')
  418. ->where('segment_id', $segmentId)
  419. ->update($segmentUpdateData);
  420. if (!$updateResult) {
  421. Utils::throwError('20003:更新分镜表失败');
  422. }
  423. // 更新分镜视频成功后新增对话记录
  424. // 保存对话记录
  425. $records = [
  426. [
  427. 'uid' => $uid,
  428. 'anime_id' => $anime_id,
  429. 'sequence' => $episode_number,
  430. 'role' => 'user',
  431. 'content' => '图片转视频',
  432. 'segment_id' => $segmentId,
  433. 'video_url' => '',
  434. 'created_at' => $now,
  435. 'updated_at' => $now
  436. ],
  437. [
  438. 'uid' => $uid,
  439. 'anime_id' => $anime_id,
  440. 'sequence' => $episode_number,
  441. 'role' => 'assistant',
  442. 'content' => $tail_frame,
  443. 'segment_id' => $segmentId,
  444. 'video_url' => $statusResult['result_url'],
  445. 'created_at' => $now,
  446. 'updated_at' => $now
  447. ]
  448. ];
  449. DB::table('mp_anime_records')->insert($records);
  450. DB::commit();
  451. } catch (\Exception $e) {
  452. DB::rollBack();
  453. $logData = [
  454. 'task_id' => $taskId,
  455. 'error' => $e->getMessage()
  456. ];
  457. dLog('anime')->error('视频任务处理失败', $logData);
  458. logDB('anime', 'error', '视频任务处理失败', $logData);
  459. }
  460. } elseif ($statusResult['status'] === 'failed') {
  461. DB::table('mp_episode_segments')
  462. ->where('video_task_id', $taskId)
  463. ->update([
  464. 'video_task_status' => '失败',
  465. 'updated_at' => date('Y-m-d H:i:s')
  466. ]);
  467. }
  468. }
  469. }
  470. // 发送当前状态
  471. echo "data: " . json_encode([
  472. 'type' => 'update',
  473. 'data' => [
  474. 'task_id' => $task->id,
  475. 'status' => $task->status,
  476. 'result_url' => $task->result_url,
  477. 'error_message' => $task->error_message,
  478. 'elapsed_time' => time() - $startTime
  479. ]
  480. ]) . "\n\n";
  481. ob_flush();
  482. flush();
  483. // 如果任务完成(成功或失败),结束连接
  484. if (in_array($task->status, [
  485. 'success',
  486. 'failed'
  487. ])) {
  488. echo "data: " . json_encode([
  489. 'type' => 'completed',
  490. 'data' => [
  491. 'task_id' => $task->id,
  492. 'status' => $task->status,
  493. 'video_url' => $task->compressed_url ?: $task->result_url,
  494. 'origin_video_url' => $task->result_url,
  495. 'last_frame_url' => $task->last_frame_url,
  496. 'error_message' => $task->error_message
  497. ]
  498. ]) . "\n\n";
  499. ob_flush();
  500. flush();
  501. break;
  502. }
  503. sleep($checkInterval);
  504. } catch (\Exception $e) {
  505. echo "data: " . json_encode([
  506. 'type' => 'error',
  507. 'message' => '查询任务状态失败: ' . $e->getMessage()
  508. ]) . "\n\n";
  509. ob_flush();
  510. flush();
  511. sleep($checkInterval);
  512. }
  513. }
  514. // 超时处理
  515. if (time() - $startTime >= $maxDuration) {
  516. echo "data: " . json_encode([
  517. 'type' => 'time_out',
  518. 'message' => '任务执行超时,请稍后查询任务状态',
  519. 'data' => [
  520. 'task_id' => $taskId
  521. ]
  522. ]) . "\n\n";
  523. ob_flush();
  524. flush();
  525. }
  526. }, 200, [
  527. 'Content-Type' => 'text/event-stream',
  528. 'Cache-Control' => 'no-cache',
  529. 'Connection' => 'keep-alive',
  530. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  531. ]);
  532. }
  533. /**
  534. * 批量生成分镜视频
  535. */
  536. public function batchSetSegmentVideos(Request $request) {
  537. // 忽略所有超时限制
  538. set_time_limit(0);
  539. ini_set('max_execution_time', '0');
  540. $data = $request->all();
  541. // 验证参数
  542. $validator = Validator::make($data, [
  543. 'anime_id' => 'required|string',
  544. 'episode_id' => 'required|integer',
  545. ], [
  546. 'anime_id.required' => '动漫对话ID不能为空',
  547. 'episode_id.required' => '剧集ID不能为空',
  548. 'episode_id.integer' => '剧集ID必须是整数',
  549. ]);
  550. if ($validator->fails()) {
  551. Utils::throwError('1002:' . $validator->errors()->first());
  552. }
  553. $animeId = $data['anime_id'];
  554. $episodeId = $data['episode_id'];
  555. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  556. if (!$episode) Utils::throwError('20003:分集不存在');
  557. $episodeNumber = $episode->episode_number;
  558. $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
  559. // 获取所有分镜信息
  560. $segments = DB::table('mp_episode_segments')
  561. ->where('anime_id', $animeId)
  562. ->where('episode_id', $episodeId)
  563. ->whereNotIn('video_task_status', ['已完成', '生成中'])
  564. ->orderBy('segment_number')
  565. ->get();
  566. if ($segments->isEmpty()) {
  567. Utils::throwError('20003:未找到分镜数据');
  568. }
  569. // 批量创建视频任务
  570. $taskIds = [];
  571. $segmentTasks = [];
  572. foreach ($segments as $segment) {
  573. try {
  574. // 检查视频任务正在生成中或当前状态为视频
  575. if ($segment->video_task_status === '生成中' || (int)$segment->current_type === 2) {
  576. continue;
  577. }
  578. // 获取分镜内容
  579. $segmentContent = $segment->segment_content ?: '';
  580. $tailFrame = $segment->tail_frame ?: '';
  581. // 构建完整的提示词
  582. $fullPrompt = $segmentContent;
  583. if ($tailFrame) {
  584. $fullPrompt .= "\n尾帧描述:$tailFrame";
  585. }
  586. // 智能选择视频时长
  587. // $videoDuration = $this->AnimeService->calculateOptimalVideoDuration($segmentContent, $tailFrame);
  588. $videoDuration = -1;
  589. // 处理视频模型(在循环外统一处理,避免重复)
  590. if (!isset($model)) {
  591. $model = getProp($data, 'model');
  592. if (!$model) {
  593. // 用户没有输入,从episode表获取
  594. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->first();
  595. $model = getProp($episode, 'video_model');
  596. if (!$model) {
  597. // episode表也没有,使用默认值
  598. $model = 'doubao-seedance-1-5-pro-251215';
  599. }
  600. }
  601. // 验证模型是否在可用模型表中
  602. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  603. $model = 'doubao-seedance-1-5-pro-251215';
  604. }
  605. }
  606. // 构建视频生成参数
  607. $videoParams = [
  608. 'model' => $model,
  609. 'alias_segment_id' => $segment->segment_id,
  610. 'prompt' => $fullPrompt,
  611. 'video_duration' => $videoDuration,
  612. 'video_resolution' => '720P',
  613. 'seed' => -1,
  614. 'ratio' => $ratio,
  615. 'generate_audio' => false,
  616. 'draft' => false,
  617. 'watermark' => false,
  618. 'camera_fixed' => false,
  619. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  620. ];
  621. // 如果分镜有图片,作为首帧
  622. $hasImage = !empty($segment->img_url);
  623. $hasVideo = !empty($segment->video_url);
  624. if ($hasImage) {
  625. $videoParams['first_frame_url'] = $segment->img_url;
  626. }
  627. // 构建content数组
  628. $videoParams['content'] = [
  629. [
  630. 'type' => 'text',
  631. 'text' => $videoParams['prompt'],
  632. ]
  633. ];
  634. // 如果有首帧图片,添加到content中
  635. if ($hasImage) {
  636. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  637. $videoParams['content'][] = [
  638. 'type' => 'image_url',
  639. 'image_url' => [
  640. 'url' => $videoParams['first_frame_url'],
  641. ],
  642. 'role' => 'reference_image',
  643. ];
  644. }else {
  645. $videoParams['content'][] = [
  646. 'type' => 'image_url',
  647. 'image_url' => [
  648. 'url' => $videoParams['first_frame_url'],
  649. ],
  650. 'role' => 'first_frame',
  651. ];
  652. }
  653. }
  654. // 获取配音音频URL和时长
  655. $audioUrl = $segment->audio_url ?? '';
  656. $audioDuration = $segment->audio_duration ?? 0;
  657. // 音频传入的前提:必须有至少一张图片或一个视频
  658. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  659. // 根据模型选择不同的视频生成方法
  660. if (strpos($model, 'jimeng') !== false) {
  661. // 即梦模型参数调整
  662. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  663. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
  664. unset($videoParams['ratio']);
  665. unset($videoParams['content']); // 即梦不使用content格式
  666. $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
  667. } elseif (strpos($model, 'kling') !== false) {
  668. // Keling模型参数调整
  669. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  670. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  671. unset($videoParams['ratio']);
  672. unset($videoParams['content']); // Keling不使用content格式
  673. $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
  674. } else {
  675. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  676. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  677. // 添加配音音频到content中
  678. $videoParams['content'][] = [
  679. 'type' => 'audio_url',
  680. 'audio_url' => [
  681. 'url' => $audioUrl,
  682. ],
  683. 'role' => 'reference_audio',
  684. ];
  685. // 优化提示词,增加音频相关描述
  686. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  687. $videoParams['prompt'] = $audioPrompt;
  688. $videoParams['content'][0]['text'] = $audioPrompt;
  689. } else if ($audioDuration) {
  690. // 有音频时长则需将视频时长设置为比音频时长更长的整数
  691. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  692. }
  693. // Seedance模型(默认)
  694. $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
  695. }
  696. $taskIds[] = $task->id;
  697. // 更新分镜表的视频任务信息
  698. DB::table('mp_episode_segments')
  699. ->where('segment_id', $segment->segment_id)
  700. ->update([
  701. 'video_task_id' => $task->id,
  702. 'video_task_status' => '生成中',
  703. 'updated_at' => date('Y-m-d H:i:s')
  704. ]);
  705. $segmentTasks[] = [
  706. 'segment_id' => $segment->segment_id,
  707. 'task_id' => $task->id,
  708. 'segment_number' => $segment->segment_number,
  709. 'tail_frame' => $segment->tail_frame,
  710. 'audio_duration' => $segment->audio_duration,
  711. ];
  712. } catch (\Exception $e) {
  713. $logData = [
  714. 'segment_id' => $segment->segment_id,
  715. 'anime_id' => $animeId,
  716. 'error' => $e->getMessage(),
  717. ];
  718. dLog('anime')->error('创建分镜视频任务失败', $logData);
  719. logDB('anime', 'error', '创建分镜视频任务失败', $logData);
  720. continue;
  721. }
  722. }
  723. if (empty($taskIds)) {
  724. Utils::throwError('20003:没有需要生成视频的分镜');
  725. }
  726. // 保存模型到episode表
  727. if (isset($model)) {
  728. DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
  729. 'video_model' => $model,
  730. 'updated_at' => date('Y-m-d H:i:s')
  731. ]);
  732. }
  733. // 记录开始时间(包含创建任务的时间)
  734. $startTime = time();
  735. $maxDuration = 1800; // 30分钟超时
  736. $uid = Site::getUid();
  737. // 设置 SSE 响应头并开始长连接
  738. return response()->stream(function () use ($taskIds, $segmentTasks, $animeId, $episodeNumber, $episodeId, $startTime, $maxDuration, $uid) {
  739. $checkInterval = 10; // 每10秒检查一次
  740. // 初始化任务数组
  741. $totalTasks = $taskIds; // 所有任务ID
  742. $completeTasks = []; // 已完成的任务ID(包含失败)
  743. $successTasks = []; // 成功的任务ID
  744. // 发送初始任务创建信息
  745. echo "data: " . json_encode([
  746. 'type' => 'init',
  747. 'total_tasks_count' => count($totalTasks),
  748. 'completed_tasks_count' => count($completeTasks),
  749. 'success_tasks_count' => count($successTasks)
  750. ]) . "\n\n";
  751. ob_flush();
  752. flush();
  753. while (time() - $startTime < $maxDuration) {
  754. try {
  755. $hasUpdate = false; // 标记是否有更新
  756. // 获取所有任务的最新状态
  757. foreach ($totalTasks as $taskId) {
  758. // 如果任务已经在完成列表中,跳过
  759. if (in_array($taskId, $completeTasks)) {
  760. continue;
  761. }
  762. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  763. if (!$task) {
  764. continue;
  765. }
  766. // 如果任务还在处理中,查询最新状态
  767. if ($task->status === 'processing') {
  768. // 根据任务类型查询不同的状态
  769. if ($task->task_type === 'jimeng') {
  770. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  771. } elseif ($task->task_type === 'keling') {
  772. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  773. } else {
  774. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  775. }
  776. if (isset($statusResult['status'])) {
  777. // 更新任务状态
  778. $task->update([
  779. 'status' => $statusResult['status'],
  780. 'result_json' => $statusResult['result_json'] ?? [],
  781. 'result_url' => $statusResult['result_url'] ?? null,
  782. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  783. 'error_message' => $statusResult['error_message'] ?? null,
  784. 'completed_at' => in_array($statusResult['status'], [
  785. 'success',
  786. 'failed'
  787. ]) ? now() : null
  788. ]);
  789. // 如果任务成功,更新分镜表
  790. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  791. try {
  792. DB::beginTransaction();
  793. $now = date('Y-m-d H:i:s');
  794. // 获取分镜ID
  795. $segmentId = null;
  796. foreach ($segmentTasks as $segmentTask) {
  797. if ($segmentTask['task_id'] == $taskId) {
  798. $segmentId = $segmentTask['segment_id'];
  799. $tail_frame = $segmentTask['tail_frame'];
  800. $audio_duration = $segmentTask['audio_duration'];
  801. break;
  802. }
  803. }
  804. if ($segmentId) {
  805. // 更新分镜表
  806. $segmentUpdateData = [
  807. 'origin_video_url' => $statusResult['result_url'],
  808. 'video_task_status' => '已完成',
  809. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  810. 'current_type' => 2,
  811. 'updated_at' => $now
  812. ];
  813. $compressed_video_url = compressVideo($statusResult['result_url']);
  814. $segmentUpdateData['video_url'] = $compressed_video_url ?: $statusResult['result_url'];
  815. // 只有当video_duration存在且大于0时才更新
  816. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  817. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  818. $segmentUpdateData['video_time_point_start'] = 0;
  819. // $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  820. $segmentUpdateData['video_time_point_end'] = $audio_duration ?? 0;
  821. }
  822. $updateResult = DB::table('mp_episode_segments')
  823. ->where('segment_id', $segmentId)
  824. ->update($segmentUpdateData);
  825. if ($updateResult) {
  826. // 更新分镜视频成功后新增对话记录
  827. $records = [
  828. [
  829. 'uid' => $uid,
  830. 'anime_id' => $animeId,
  831. 'sequence' => $episodeNumber,
  832. 'role' => 'user',
  833. 'content' => '图片转视频',
  834. 'segment_id' => $segmentId,
  835. 'video_url' => '',
  836. 'created_at' => $now,
  837. 'updated_at' => $now
  838. ],
  839. [
  840. 'uid' => $uid,
  841. 'anime_id' => $animeId,
  842. 'sequence' => $episodeNumber,
  843. 'role' => 'assistant',
  844. 'content' => $tail_frame ?? '',
  845. 'segment_id' => $segmentId,
  846. 'video_url' => $statusResult['result_url'],
  847. 'created_at' => $now,
  848. 'updated_at' => $now
  849. ]
  850. ];
  851. DB::table('mp_anime_records')->insert($records);
  852. }
  853. }
  854. DB::commit();
  855. } catch (\Exception $e) {
  856. DB::rollBack();
  857. $logData = [
  858. 'task_id' => $taskId,
  859. 'error' => $e->getMessage()
  860. ];
  861. dLog('anime')->error('视频任务处理失败', $logData);
  862. logDB('anime', 'error', '视频任务处理失败', $logData);
  863. }
  864. } elseif ($statusResult['status'] === 'failed') {
  865. // 获取分镜ID并更新失败状态
  866. foreach ($segmentTasks as $segmentTask) {
  867. if ($segmentTask['task_id'] == $taskId) {
  868. DB::table('mp_episode_segments')
  869. ->where('segment_id', $segmentTask['segment_id'])
  870. ->update([
  871. 'video_task_status' => '失败',
  872. 'updated_at' => date('Y-m-d H:i:s')
  873. ]);
  874. break;
  875. }
  876. }
  877. }
  878. }
  879. }
  880. // 检查任务是否完成(成功或失败)
  881. if (in_array($task->status, ['success', 'failed'])) {
  882. $completeTasks[] = $taskId;
  883. $hasUpdate = true;
  884. if ($task->status === 'success') {
  885. $successTasks[] = $taskId;
  886. }
  887. }
  888. }
  889. // 如果有更新,发送update通知
  890. if ($hasUpdate) {
  891. echo "data: " . json_encode([
  892. 'type' => 'update',
  893. 'total_tasks_count' => count($totalTasks),
  894. 'completed_tasks_count' => count($completeTasks),
  895. 'success_tasks_count' => count($successTasks)
  896. ]) . "\n\n";
  897. ob_flush();
  898. flush();
  899. }
  900. // 如果所有任务都完成了,结束连接
  901. if (count($completeTasks) >= count($totalTasks)) {
  902. // 获取所有成功任务的分镜信息
  903. $successSegments = [];
  904. foreach ($successTasks as $taskId) {
  905. // 通过taskId找到对应的segmentTask
  906. foreach ($segmentTasks as $segmentTask) {
  907. if ($segmentTask['task_id'] == $taskId) {
  908. $segment = DB::table('mp_episode_segments')
  909. ->where('segment_id', $segmentTask['segment_id'])
  910. ->select('segment_id', 'video_url')
  911. ->first();
  912. if ($segment && !empty($segment->video_url)) {
  913. $successSegments[] = [
  914. 'segment_id' => $segment->segment_id,
  915. 'video_url' => $segment->video_url
  916. ];
  917. }
  918. break;
  919. }
  920. }
  921. }
  922. echo "data: " . json_encode([
  923. 'type' => 'completed',
  924. 'total_tasks_count' => count($totalTasks),
  925. 'completed_tasks_count' => count($completeTasks),
  926. 'success_tasks_count' => count($successTasks),
  927. 'success_segments' => $successSegments
  928. ]) . "\n\n";
  929. ob_flush();
  930. flush();
  931. break;
  932. }
  933. // 检查是否超时
  934. if (time() - $startTime >= $maxDuration) {
  935. break;
  936. }
  937. sleep($checkInterval);
  938. } catch (\Exception $e) {
  939. echo "data: " . json_encode([
  940. 'type' => 'error',
  941. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  942. 'total_tasks_count' => count($totalTasks),
  943. 'completed_tasks_count' => count($completeTasks),
  944. 'success_tasks_count' => count($successTasks)
  945. ]) . "\n\n";
  946. ob_flush();
  947. flush();
  948. // 检查是否超时,如果超时则停止循环
  949. if (time() - $startTime >= $maxDuration) {
  950. break;
  951. }
  952. sleep($checkInterval);
  953. }
  954. }
  955. // 超时处理
  956. if (time() - $startTime >= $maxDuration) {
  957. echo "data: " . json_encode([
  958. 'type' => 'time_out',
  959. 'message' => '批量视频生成已超时30分钟,停止状态查询',
  960. 'total_tasks_count' => count($totalTasks),
  961. 'completed_tasks_count' => count($completeTasks),
  962. 'success_tasks_count' => count($successTasks)
  963. ]) . "\n\n";
  964. ob_flush();
  965. flush();
  966. }
  967. }, 200, [
  968. 'Content-Type' => 'text/event-stream',
  969. 'Cache-Control' => 'no-cache',
  970. 'Connection' => 'keep-alive',
  971. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  972. ]);
  973. }
  974. // 应用有声制作参数
  975. public function applyAudioData(Request $request) {
  976. $data = $request->all();
  977. $result = $this->AnimeService->applyAudioData($data);
  978. return $this->success($result);
  979. }
  980. // 获取分集生成图片信息
  981. public function episodePicsInfo(Request $request) {
  982. // 忽略所有超时限制
  983. set_time_limit(0);
  984. ini_set('max_execution_time', '0');
  985. $data = $request->all();
  986. // 获取生成器函数
  987. $streamGenerator = $this->AnimeService->episodePicsInfo($data);
  988. // 返回 SSE 响应
  989. return response()->stream($streamGenerator, 200, [
  990. 'Content-Type' => 'text/event-stream',
  991. 'Cache-Control' => 'no-cache',
  992. 'Connection' => 'keep-alive',
  993. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  994. ]);
  995. }
  996. public function clipSegmentVideo(Request $request) {
  997. $data = $request->all();
  998. $result = $this->AnimeService->clipSegmentVideo($data);
  999. return $this->success(['success'=>$result ? 1: 0]);
  1000. }
  1001. /**
  1002. * 创建完整视频合成任务
  1003. *
  1004. * @param Request $request
  1005. * @return \Illuminate\Http\JsonResponse
  1006. */
  1007. public function createCompleteVideoTask(Request $request)
  1008. {
  1009. // 忽略所有超时限制
  1010. set_time_limit(0);
  1011. ini_set('max_execution_time', '0');
  1012. $data = $request->all();
  1013. // 验证参数
  1014. $validator = Validator::make($data, [
  1015. 'anime_id' => 'required|string',
  1016. 'episode_id' => 'required|string',
  1017. ], [
  1018. 'anime_id.required' => '请选择动漫',
  1019. 'episode_id.required' => '请选择分集',
  1020. ]);
  1021. if ($validator->fails()) {
  1022. Utils::throwError('1002:' . $validator->errors()->first());
  1023. }
  1024. try {
  1025. $result = $this->AnimeService->createCompleteVideoTask($data);
  1026. return $this->success($result);
  1027. } catch (\Exception $e) {
  1028. $logData = [
  1029. 'anime_id' => $data['anime_id'] ?? '',
  1030. 'episode_id' => $data['episode_id'] ?? '',
  1031. 'error' => $e->getMessage()
  1032. ];
  1033. dLog('anime')->error('创建完整视频合成任务失败', $logData);
  1034. logDB('anime', 'error', '创建完整视频合成任务失败', $logData);
  1035. return $this->error('20003:'.$e->getMessage());
  1036. }
  1037. }
  1038. // 文生图(通用)
  1039. public function generateImg(Request $request) {
  1040. // 忽略所有超时限制
  1041. set_time_limit(0);
  1042. ini_set('max_execution_time', '0');
  1043. $data = $request->all();
  1044. $result = $this->AnimeService->generateImg($data);
  1045. return $this->success($result);
  1046. }
  1047. /**
  1048. * 导出分集的全部图片(下载并打包)
  1049. */
  1050. public function exportEpisodeImages(Request $request) {
  1051. // 忽略所有超时限制
  1052. set_time_limit(0);
  1053. ini_set('max_execution_time', '0');
  1054. ini_set('memory_limit', '512M');
  1055. $data = $request->all();
  1056. // 验证参数
  1057. $validator = Validator::make($data, [
  1058. 'anime_id' => 'required|string',
  1059. 'episode_id' => 'required|string',
  1060. ], [
  1061. 'anime_id.required' => '动漫ID不能为空',
  1062. 'episode_id.required' => '剧集ID不能为空',
  1063. ]);
  1064. if ($validator->fails()) {
  1065. Utils::throwError('1002:' . $validator->errors()->first());
  1066. }
  1067. $animeId = $data['anime_id'];
  1068. $episodeId = $data['episode_id'];
  1069. try {
  1070. // 获取剧集信息
  1071. $episode = DB::table('mp_anime_episodes')
  1072. ->where('anime_id', $animeId)
  1073. ->where('id', $episodeId)
  1074. ->select('episode_number', 'title')
  1075. ->first();
  1076. if (!$episode) {
  1077. Utils::throwError('20003:未找到剧集信息');
  1078. }
  1079. // 获取所有分镜图片和音频
  1080. $segments = DB::table('mp_episode_segments')
  1081. ->where('anime_id', $animeId)
  1082. ->where('episode_id', $episodeId)
  1083. ->whereNotNull('img_url')
  1084. ->where('img_url', '!=', '')
  1085. ->orderBy('segment_number')
  1086. ->select('segment_id', 'segment_number', 'img_url', 'video_url', 'audio_url', 'act_number', 'act_title')
  1087. ->get();
  1088. if ($segments->isEmpty()) {
  1089. Utils::throwError('20003:该剧集暂无图片可导出');
  1090. }
  1091. // 创建临时目录
  1092. $tempDir = storage_path('app/temp/episode_images_' . time() . '_' . mt_rand(1000, 9999));
  1093. if (!file_exists($tempDir)) {
  1094. mkdir($tempDir, 0755, true);
  1095. }
  1096. // 下载图片或视频
  1097. $downloadedFiles = [];
  1098. foreach ($segments as $segment) {
  1099. try {
  1100. // 优先使用video_url,如果没有则使用img_url
  1101. $mediaUrl = !empty($segment->video_url) ? $segment->video_url : $segment->img_url;
  1102. if (empty($mediaUrl)) {
  1103. continue;
  1104. }
  1105. // 获取文件扩展名
  1106. $extension = pathinfo(parse_url($mediaUrl, PHP_URL_PATH), PATHINFO_EXTENSION);
  1107. if (empty($extension)) {
  1108. // 根据URL类型设置默认扩展名
  1109. $extension = !empty($segment->video_url) ? 'mp4' : 'jpg';
  1110. }
  1111. // 构建文件名:分镜序号.扩展名
  1112. $fileName = sprintf(
  1113. '%03d.%s',
  1114. $segment->segment_number,
  1115. $extension
  1116. );
  1117. $filePath = $tempDir . '/' . $fileName;
  1118. // 下载文件(使用file_get_contents,兼容性更好)
  1119. $context = stream_context_create([
  1120. 'http' => [
  1121. 'timeout' => 30,
  1122. 'follow_location' => 1,
  1123. 'ignore_errors' => true
  1124. ],
  1125. 'ssl' => [
  1126. 'verify_peer' => false,
  1127. 'verify_peer_name' => false
  1128. ]
  1129. ]);
  1130. $fileData = @file_get_contents($mediaUrl, false, $context);
  1131. if ($fileData !== false && !empty($fileData)) {
  1132. file_put_contents($filePath, $fileData);
  1133. $downloadedFiles[] = $filePath;
  1134. } else {
  1135. $logData = [
  1136. 'segment_id' => $segment->segment_id,
  1137. 'media_url' => $mediaUrl,
  1138. 'type' => !empty($segment->video_url) ? 'video' : 'image'
  1139. ];
  1140. dLog('anime')->warning('文件下载失败', $logData);
  1141. logDB('anime', 'warning', '文件下载失败', $logData);
  1142. }
  1143. } catch (\Exception $e) {
  1144. $logData = [
  1145. 'segment_id' => $segment->segment_id,
  1146. 'video_url' => $segment->video_url,
  1147. 'img_url' => $segment->img_url,
  1148. 'error' => $e->getMessage()
  1149. ];
  1150. dLog('anime')->error('下载文件异常', $logData);
  1151. logDB('anime', 'error', '下载文件异常', $logData);
  1152. continue;
  1153. }
  1154. }
  1155. if (empty($downloadedFiles)) {
  1156. // 清理临时目录
  1157. if (file_exists($tempDir)) {
  1158. array_map('unlink', glob("$tempDir/*"));
  1159. rmdir($tempDir);
  1160. }
  1161. Utils::throwError('20003:没有成功下载任何图片');
  1162. }
  1163. // 处理音频合成
  1164. $mergedAudioPath = null;
  1165. try {
  1166. // 检查 FFmpeg 是否可用
  1167. exec('which ffmpeg 2>&1', $ffmpegCheck, $ffmpegReturnCode);
  1168. $hasFfmpeg = ($ffmpegReturnCode === 0);
  1169. if ($hasFfmpeg) {
  1170. // 下载所有分镜的音频文件
  1171. $audioFiles = [];
  1172. foreach ($segments as $segment) {
  1173. if (!empty($segment->audio_url)) {
  1174. try {
  1175. $context = stream_context_create([
  1176. 'http' => [
  1177. 'timeout' => 30,
  1178. 'follow_location' => 1,
  1179. 'ignore_errors' => true
  1180. ],
  1181. 'ssl' => [
  1182. 'verify_peer' => false,
  1183. 'verify_peer_name' => false
  1184. ]
  1185. ]);
  1186. $audioData = @file_get_contents($segment->audio_url, false, $context);
  1187. if ($audioData !== false && !empty($audioData)) {
  1188. // 获取音频文件扩展名
  1189. $audioExtension = pathinfo(parse_url($segment->audio_url, PHP_URL_PATH), PATHINFO_EXTENSION);
  1190. if (empty($audioExtension)) {
  1191. $audioExtension = 'wav';
  1192. }
  1193. $audioFileName = sprintf('audio_%03d.%s', $segment->segment_number, $audioExtension);
  1194. $audioFilePath = $tempDir . '/' . $audioFileName;
  1195. file_put_contents($audioFilePath, $audioData);
  1196. $audioFiles[] = $audioFilePath;
  1197. } else {
  1198. $logData = [
  1199. 'segment_id' => $segment->segment_id,
  1200. 'audio_url' => $segment->audio_url
  1201. ];
  1202. dLog('anime')->warning('音频下载失败', $logData);
  1203. logDB('anime', 'warning', '音频下载失败', $logData);
  1204. }
  1205. } catch (\Exception $e) {
  1206. $logData = [
  1207. 'segment_id' => $segment->segment_id,
  1208. 'audio_url' => $segment->audio_url,
  1209. 'error' => $e->getMessage()
  1210. ];
  1211. dLog('anime')->error('下载音频异常', $logData);
  1212. logDB('anime', 'error', '下载音频异常', $logData);
  1213. }
  1214. }
  1215. }
  1216. // 如果有音频文件,则进行合成
  1217. if (!empty($audioFiles)) {
  1218. // 创建 FFmpeg concat 文件列表
  1219. $concatFile = $tempDir . '/concat.txt';
  1220. $concatContent = '';
  1221. foreach ($audioFiles as $audioFile) {
  1222. // 使用相对路径,避免路径中的特殊字符问题
  1223. $concatContent .= "file '" . basename($audioFile) . "'\n";
  1224. }
  1225. file_put_contents($concatFile, $concatContent);
  1226. // 合成音频文件
  1227. $mergedAudioPath = $tempDir . '/tts.wav';
  1228. // 使用 FFmpeg 合并音频,转换为统一的 WAV 格式
  1229. $ffmpegCommand = sprintf(
  1230. 'cd %s && ffmpeg -f concat -safe 0 -i %s -ar 44100 -ac 2 -y %s 2>&1',
  1231. escapeshellarg($tempDir),
  1232. escapeshellarg(basename($concatFile)),
  1233. escapeshellarg(basename($mergedAudioPath))
  1234. );
  1235. exec($ffmpegCommand, $ffmpegOutput, $ffmpegReturnCode);
  1236. if ($ffmpegReturnCode !== 0 || !file_exists($mergedAudioPath)) {
  1237. $logData = [
  1238. 'command' => $ffmpegCommand,
  1239. 'output' => implode("\n", $ffmpegOutput),
  1240. 'return_code' => $ffmpegReturnCode
  1241. ];
  1242. dLog('anime')->error('FFmpeg 合成音频失败', $logData);
  1243. logDB('anime', 'error', 'FFmpeg 合成音频失败', $logData);
  1244. $mergedAudioPath = null;
  1245. } else {
  1246. $logData = [
  1247. 'audio_count' => count($audioFiles),
  1248. 'output_file' => $mergedAudioPath,
  1249. 'file_size' => filesize($mergedAudioPath)
  1250. ];
  1251. dLog('anime')->info('音频合成成功', $logData);
  1252. logDB('anime', 'info', '音频合成成功', $logData);
  1253. }
  1254. // 清理临时音频文件和 concat 文件
  1255. foreach ($audioFiles as $audioFile) {
  1256. if (file_exists($audioFile)) {
  1257. @unlink($audioFile);
  1258. }
  1259. }
  1260. if (file_exists($concatFile)) {
  1261. @unlink($concatFile);
  1262. }
  1263. }
  1264. } else {
  1265. dLog('anime')->warning('FFmpeg 未安装,跳过音频合成');
  1266. logDB('anime', 'warning', 'FFmpeg 未安装,跳过音频合成', []);
  1267. }
  1268. } catch (\Exception $e) {
  1269. $logData = [
  1270. 'error' => $e->getMessage(),
  1271. 'trace' => $e->getTraceAsString()
  1272. ];
  1273. dLog('anime')->error('音频合成过程异常', $logData);
  1274. logDB('anime', 'error', '音频合成过程异常', $logData);
  1275. // 音频合成失败不影响图片导出
  1276. $mergedAudioPath = null;
  1277. }
  1278. // 创建zip文件
  1279. $zipFileName = sprintf(
  1280. '%s.zip',
  1281. $episode->title ?: '未命名'
  1282. );
  1283. $zipFilePath = storage_path('app/temp/' . $zipFileName);
  1284. $zip = new \ZipArchive();
  1285. if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
  1286. // 清理临时文件
  1287. array_map('unlink', $downloadedFiles);
  1288. rmdir($tempDir);
  1289. Utils::throwError('20003:创建ZIP文件失败');
  1290. }
  1291. // 添加图片文件到zip
  1292. foreach ($downloadedFiles as $file) {
  1293. $zip->addFile($file, basename($file));
  1294. }
  1295. // 添加合成的音频文件到zip
  1296. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1297. $zip->addFile($mergedAudioPath, 'tts.wav');
  1298. }
  1299. $zip->close();
  1300. // 清理临时图片文件
  1301. array_map('unlink', $downloadedFiles);
  1302. // 清理合成的音频文件
  1303. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1304. @unlink($mergedAudioPath);
  1305. }
  1306. rmdir($tempDir);
  1307. // 返回文件下载响应
  1308. return response()->download($zipFilePath, $zipFileName)->deleteFileAfterSend(true);
  1309. } catch (\Exception $e) {
  1310. $logData = [
  1311. 'anime_id' => $animeId,
  1312. 'episode_id' => $episodeId,
  1313. 'error' => $e->getMessage()
  1314. ];
  1315. dLog('anime')->error('导出分集图片失败', $logData);
  1316. logDB('anime', 'error', '导出分集图片失败', $logData);
  1317. // 清理可能存在的临时文件
  1318. if (isset($tempDir) && file_exists($tempDir)) {
  1319. array_map('unlink', glob("$tempDir/*"));
  1320. rmdir($tempDir);
  1321. }
  1322. if (isset($zipFilePath) && file_exists($zipFilePath)) {
  1323. unlink($zipFilePath);
  1324. }
  1325. throw $e;
  1326. }
  1327. }
  1328. /**
  1329. * 监控分镜图片和音频生成任务进度(SSE)
  1330. */
  1331. public function monitorSegmentTasks(Request $request) {
  1332. // 忽略所有超时限制
  1333. set_time_limit(0);
  1334. ini_set('max_execution_time', '0');
  1335. $data = $request->all();
  1336. // 验证参数
  1337. $validator = Validator::make($data, [
  1338. 'anime_id' => 'required|string',
  1339. 'episode_id' => 'required|string',
  1340. ], [
  1341. 'anime_id.required' => '动漫ID不能为空',
  1342. 'episode_id.required' => '剧集ID不能为空',
  1343. ]);
  1344. if ($validator->fails()) {
  1345. Utils::throwError('1002:' . $validator->errors()->first());
  1346. }
  1347. $animeId = $data['anime_id'];
  1348. $episodeId = $data['episode_id'];
  1349. // 查询没有pic_task_id的分镜个数
  1350. $noPicTaskCount = DB::table('mp_episode_segments')
  1351. ->where('anime_id', $animeId)
  1352. ->where('episode_id', $episodeId)
  1353. ->where(function($query) {
  1354. $query->whereNull('pic_task_id')
  1355. ->orWhere('pic_task_id', '');
  1356. })
  1357. ->count('id');
  1358. // 获取所有分镜信息
  1359. $segments = DB::table('mp_episode_segments')
  1360. ->where('anime_id', $animeId)
  1361. ->where('episode_id', $episodeId)
  1362. ->where('pic_task_id', '!=', '')
  1363. ->orderBy('segment_number')
  1364. ->get();
  1365. // 判断是否有未完成的任务
  1366. $uncompleted_pic_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)
  1367. ->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->whereNotIn('pic_task_status', ['已完成', '失败'])->count('id');
  1368. // 获取dialogue和voice_type存在但audio_url不存在的分镜个数
  1369. $uncompleted_audio_count = DB::table('mp_episode_segments')
  1370. ->where('anime_id', $animeId)
  1371. ->where('episode_id', $episodeId)
  1372. ->where('dialogue', '<>', '')
  1373. ->whereNotNull('dialogue')
  1374. ->where('voice_type', '<>', '')
  1375. ->whereNotNull('voice_type')
  1376. ->where(function($query) {
  1377. $query->whereNull('audio_url')
  1378. ->orWhere('audio_url', '');
  1379. })
  1380. ->count('id');
  1381. if ($segments->isEmpty()) {
  1382. Utils::throwError('20003:未找到分镜任务数据');
  1383. }
  1384. $startTime = time();
  1385. $maxDuration = 900; // 15分钟超时
  1386. $checkInterval = 5; // 每5秒检查一次
  1387. // 设置 SSE 响应头并开始长连接
  1388. return response()->stream(function () use ($segments, $animeId, $episodeId, $startTime, $maxDuration, $checkInterval, $uncompleted_pic_count, $uncompleted_audio_count, $noPicTaskCount) {
  1389. if ($uncompleted_pic_count == 0 && $uncompleted_audio_count == 0) {
  1390. $completedCount = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->where('pic_task_status', '已完成')->count('id');
  1391. // 获取剧集信息之前先处理视频截止时间点
  1392. $this->handleVideoTimePointEnd();
  1393. // 获取剧集信息
  1394. $episode = DB::table('mp_anime_episodes')
  1395. ->where('anime_id', $animeId)
  1396. ->where('id', $episodeId)
  1397. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1398. ->first();
  1399. if ($episode) {
  1400. $episode = (array)$episode;
  1401. $episode['roles'] = json_decode($episode['roles'], true);
  1402. $episode['scenes'] = json_decode($episode['scenes'], true);
  1403. // 获取所有分镜信息
  1404. $allSegments = DB::table('mp_episode_segments')
  1405. ->where('anime_id', $animeId)
  1406. ->where('episode_id', $episodeId)
  1407. ->orderBy('segment_number')
  1408. ->select('*')
  1409. ->get()
  1410. ->map(function ($value) {
  1411. return (array)$value;
  1412. })->toArray();
  1413. // 按照episodeInfo的格式组织数据
  1414. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1415. $episode['acts'] = $segmentsStructure['acts'];
  1416. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1417. }
  1418. echo "data: " . json_encode([
  1419. 'type' => 'completed',
  1420. 'data' => [
  1421. 'anime_id' => $animeId,
  1422. 'episode_id' => $episodeId,
  1423. 'completed_count' => $completedCount, // 成功完成的数量
  1424. 'processed_count' => count($segments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1425. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1426. 'total_elapsed_time' => time() - $startTime,
  1427. 'episode_info' => $episode ?? null
  1428. ]
  1429. ]) . "\n\n";
  1430. ob_flush();
  1431. flush();
  1432. return;
  1433. }
  1434. // 发送初始任务信息
  1435. echo "data: " . json_encode([
  1436. 'type' => 'init',
  1437. 'data' => [
  1438. 'anime_id' => $animeId,
  1439. 'episode_id' => $episodeId,
  1440. 'total_segments' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1441. 'start_time' => $startTime,
  1442. 'max_duration' => $maxDuration
  1443. ]
  1444. ]) . "\n\n";
  1445. ob_flush();
  1446. flush();
  1447. $completedSegments = [];
  1448. $processedSegments = []; // 记录已处理完成的分镜(成功或失败)
  1449. $notifiedSegments = []; // 记录已通知过的分镜,避免重复通知
  1450. while (time() - $startTime < $maxDuration) {
  1451. try {
  1452. $updatedImages = []; // 记录本次循环中更新的图片信息
  1453. foreach ($segments as $segment) {
  1454. $segmentId = $segment->segment_id;
  1455. $picTaskId = $segment->pic_task_id;
  1456. $audioUrl = $segment->audio_url;
  1457. // 跳过已处理完成的分镜
  1458. if (in_array($segmentId, $processedSegments)) {
  1459. continue;
  1460. }
  1461. $picCompleted = false;
  1462. $audioCompleted = false;
  1463. $picProcessed = false;
  1464. $audioProcessed = false;
  1465. // 检查图片任务状态
  1466. if ($picTaskId) {
  1467. $picTask = DB::table('mp_generate_pic_tasks')
  1468. ->where('id', $picTaskId)
  1469. ->select('status', 'result_url', 'error_message')
  1470. ->first();
  1471. if ($picTask && in_array($picTask->status, ['success', 'failed'])) {
  1472. $updateData = [
  1473. 'pic_task_status' => $picTask->status === 'success' ? '已完成' : '失败',
  1474. 'updated_at' => date('Y-m-d H:i:s')
  1475. ];
  1476. $imgUrl = '';
  1477. if ($picTask->status === 'success' && !empty($picTask->result_url)) {
  1478. // 更新分镜表的图片URL
  1479. $resultUrls = json_decode($picTask->result_url, true);
  1480. $imgUrl = is_array($resultUrls) ? $resultUrls[0] : $picTask->result_url;
  1481. $updateData['img_url'] = $imgUrl;
  1482. $picCompleted = true;
  1483. } else if ($picTask->status === 'failed') {
  1484. // 失败时清空图片URL
  1485. $updateData['img_url'] = '';
  1486. }
  1487. DB::table('mp_episode_segments')
  1488. ->where('segment_id', $segmentId)
  1489. ->update($updateData);
  1490. // 记录更新的图片信息(只有未通知过的才记录)
  1491. if (!in_array($segmentId, $notifiedSegments)) {
  1492. $updatedImages[] = [
  1493. 'segment_id' => $segmentId,
  1494. 'segment_number' => $segment->segment_number,
  1495. 'img_url' => $imgUrl,
  1496. 'status' => $picTask->status === 'success' ? 'success' : 'failed'
  1497. ];
  1498. // 标记为已通知
  1499. $notifiedSegments[] = $segmentId;
  1500. }
  1501. $picProcessed = true;
  1502. }
  1503. }
  1504. // 检查音频状态
  1505. // 获取分镜的dialogue、voice_type和audio_url信息
  1506. $segmentInfo = DB::table('mp_episode_segments')
  1507. ->where('segment_id', $segmentId)
  1508. ->select('dialogue', 'voice_type', 'audio_url')
  1509. ->first();
  1510. $needAudio = false;
  1511. $currentAudioUrl = '';
  1512. if ($segmentInfo) {
  1513. $dialogue = trim((string)getProp($segmentInfo, 'dialogue'));
  1514. $voiceType = trim((string)getProp($segmentInfo, 'voice_type'));
  1515. $currentAudioUrl = trim((string)getProp($segmentInfo, 'audio_url'));
  1516. // 如果有对话和音色类型,则需要音频
  1517. if (!empty($dialogue) && !empty($voiceType)) {
  1518. $needAudio = true;
  1519. }
  1520. }
  1521. // 判断音频状态
  1522. if ($needAudio) {
  1523. // 需要音频的情况下,检查audio_url是否有值
  1524. if (!empty($currentAudioUrl)) {
  1525. $audioCompleted = true;
  1526. $audioProcessed = true;
  1527. } else {
  1528. // 需要音频但还没有,继续等待
  1529. $audioCompleted = false;
  1530. $audioProcessed = false;
  1531. }
  1532. } else {
  1533. // 不需要音频,直接标记为已处理
  1534. $audioCompleted = false;
  1535. $audioProcessed = true;
  1536. }
  1537. // 如果图片和音频都成功完成,标记为已完成
  1538. if ($picCompleted && ($audioCompleted || !$needAudio)) {
  1539. $completedSegments[] = $segmentId;
  1540. }
  1541. // 如果图片和音频都已处理完成(成功或失败),标记为已处理
  1542. if ($picProcessed && $audioProcessed) {
  1543. $processedSegments[] = $segmentId;
  1544. }
  1545. }
  1546. // 如果有图片更新,发送具体的图片更新信息
  1547. if (!empty($updatedImages)) {
  1548. echo "data: " . json_encode([
  1549. 'type' => 'update',
  1550. 'data' => [
  1551. 'anime_id' => $animeId,
  1552. 'episode_id' => $episodeId,
  1553. 'updated_images' => $updatedImages,
  1554. 'completed_count' => count($completedSegments), // 成功完成的数量
  1555. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1556. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1557. 'elapsed_time' => time() - $startTime,
  1558. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1559. ]
  1560. ]) . "\n\n";
  1561. ob_flush();
  1562. flush();
  1563. }
  1564. // 如果所有分镜都已处理完成(成功或失败),获取最终结果并结束连接
  1565. if (count($processedSegments) === count($segments)) {
  1566. // 获取剧集信息之前先处理视频截止时间点
  1567. $this->handleVideoTimePointEnd();
  1568. // 获取剧集信息
  1569. $episode = DB::table('mp_anime_episodes')
  1570. ->where('anime_id', $animeId)
  1571. ->where('id', $episodeId)
  1572. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1573. ->first();
  1574. if ($episode) {
  1575. $episode = (array)$episode;
  1576. $episode['roles'] = json_decode($episode['roles'], true);
  1577. $episode['scenes'] = json_decode($episode['scenes'], true);
  1578. // 获取所有分镜信息
  1579. $allSegments = DB::table('mp_episode_segments')
  1580. ->where('anime_id', $animeId)
  1581. ->where('episode_id', $episodeId)
  1582. ->orderBy('segment_number')
  1583. ->select('*')
  1584. ->get()
  1585. ->map(function ($value) {
  1586. return (array)$value;
  1587. })->toArray();
  1588. // 按照episodeInfo的格式组织数据
  1589. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1590. $episode['acts'] = $segmentsStructure['acts'];
  1591. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1592. }
  1593. echo "data: " . json_encode([
  1594. 'type' => 'completed',
  1595. 'data' => [
  1596. 'anime_id' => $animeId,
  1597. 'episode_id' => $episodeId,
  1598. 'completed_count' => count($completedSegments), // 成功完成的数量
  1599. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1600. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1601. 'total_elapsed_time' => time() - $startTime,
  1602. 'episode_info' => $episode ?? null
  1603. ]
  1604. ]) . "\n\n";
  1605. ob_flush();
  1606. flush();
  1607. break;
  1608. }
  1609. // 检查是否超时
  1610. if (time() - $startTime >= $maxDuration) {
  1611. break;
  1612. }
  1613. sleep($checkInterval);
  1614. } catch (\Exception $e) {
  1615. echo "data: " . json_encode([
  1616. 'type' => 'error',
  1617. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  1618. 'elapsed_time' => time() - $startTime,
  1619. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1620. ]) . "\n\n";
  1621. ob_flush();
  1622. flush();
  1623. if (time() - $startTime >= $maxDuration) {
  1624. break;
  1625. }
  1626. sleep($checkInterval);
  1627. }
  1628. }
  1629. // 超时处理
  1630. if (time() - $startTime >= $maxDuration) {
  1631. echo "data: " . json_encode([
  1632. 'type' => 'time_out',
  1633. 'message' => '分镜任务监控已超时15分钟,停止状态查询',
  1634. 'data' => [
  1635. 'anime_id' => $animeId,
  1636. 'episode_id' => $episodeId,
  1637. 'completed_count' => count($completedSegments), // 成功完成的数量
  1638. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1639. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1640. 'total_elapsed_time' => time() - $startTime,
  1641. 'timeout_duration' => $maxDuration
  1642. ]
  1643. ]) . "\n\n";
  1644. ob_flush();
  1645. flush();
  1646. }
  1647. }, 200, [
  1648. 'Content-Type' => 'text/event-stream',
  1649. 'Cache-Control' => 'no-cache',
  1650. 'Connection' => 'keep-alive',
  1651. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  1652. ]);
  1653. }
  1654. /**
  1655. * 音频试听接口
  1656. * 创建音频任务并返回结果
  1657. */
  1658. public function previewAudio(Request $request) {
  1659. $data = $request->all();
  1660. $result = $this->AnimeService->previewAudio($data);
  1661. return $this->success($result);
  1662. }
  1663. private function handleVideoTimePointEnd() {
  1664. // 处理音频时长,循环查询dub_video_task_queue列表中的任务
  1665. $queueLength = Redis::llen('dub_video_task_queue');
  1666. if ($queueLength > 0) {
  1667. $processedTaskIds = []; // 记录已处理的任务ID
  1668. // 遍历队列中的所有任务
  1669. for ($i = 0; $i < $queueLength; $i++) {
  1670. $dubTaskId = Redis::lindex('dub_video_task_queue', $i);
  1671. if (!$dubTaskId) continue;
  1672. // 查询任务状态
  1673. $dubTask = DB::table('mp_dub_video_tasks')
  1674. ->where('id', $dubTaskId)
  1675. ->first();
  1676. if (!$dubTask) {
  1677. // 任务不存在,标记为需要删除
  1678. $processedTaskIds[] = $dubTaskId;
  1679. continue;
  1680. }
  1681. // 如果任务状态是已完成
  1682. if ($dubTask->generate_status === '执行成功') {
  1683. // 获取对应的分镜信息
  1684. $segment = DB::table('mp_episode_segments')
  1685. ->where('segment_id', $dubTask->alias_segment_id)
  1686. ->first();
  1687. // 如果分镜存在且audio_duration大于0
  1688. if ($segment && isset($segment->audio_duration) && $segment->audio_duration > 0) {
  1689. // 更新video_time_point_end字段
  1690. DB::table('mp_episode_segments')
  1691. ->where('segment_id', $dubTask->alias_segment_id)
  1692. ->update([
  1693. 'video_time_point_end' => $segment->audio_duration,
  1694. 'updated_at' => date('Y-m-d H:i:s')
  1695. ]);
  1696. dLog('anime')->info('更新分镜视频截止时间点', [
  1697. 'task_id' => $dubTaskId,
  1698. 'segment_id' => $dubTask->alias_segment_id,
  1699. 'audio_duration' => $segment->audio_duration
  1700. ]);
  1701. }
  1702. // 标记为需要从队列中删除
  1703. $processedTaskIds[] = $dubTaskId;
  1704. }
  1705. }
  1706. // 从Redis列表中删除已处理的任务ID
  1707. foreach ($processedTaskIds as $taskId) {
  1708. Redis::lrem('dub_video_task_queue', 0, $taskId);
  1709. }
  1710. }
  1711. }
  1712. }