AnimeController.php 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999
  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. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  377. 'error_message' => $statusResult['error_message'] ?? null,
  378. 'completed_at' => in_array($statusResult['status'], [
  379. 'success',
  380. 'failed'
  381. ]) ? now() : null
  382. ]);
  383. // 如果任务成功,更新分镜表
  384. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  385. try {
  386. DB::beginTransaction();
  387. $now = date('Y-m-d H:i:s');
  388. // 获取分镜ID
  389. $segment = DB::table('mp_episode_segments')
  390. ->where('video_task_id', $taskId)
  391. ->first();
  392. if (!$segment) {
  393. throw new \Exception('未找到对应的分镜记录');
  394. }
  395. $segmentId = $segment->segment_id;
  396. $anime_id = $segment->anime_id;
  397. $episode_number = $segment->episode_number;
  398. $tail_frame = $segment->tail_frame;
  399. // 更新分镜表
  400. $segmentUpdateData = [
  401. 'video_url' => $statusResult['result_url'],
  402. 'video_task_status' => '已完成',
  403. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  404. 'current_type' => 2,
  405. 'updated_at' => $now
  406. ];
  407. $compressed_video_url = compressVideo($segmentUpdateData['video_url']);
  408. if ($compressed_video_url) $segmentUpdateData['preview_video_url'] = $compressed_video_url;
  409. // 只有当video_duration存在且大于0时才更新
  410. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  411. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  412. $segmentUpdateData['video_time_point_start'] = 0;
  413. // $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  414. $segmentUpdateData['video_time_point_end'] = $segment->audio_duration ?? 0;
  415. }
  416. $updateResult = DB::table('mp_episode_segments')
  417. ->where('segment_id', $segmentId)
  418. ->update($segmentUpdateData);
  419. if (!$updateResult) {
  420. Utils::throwError('20003:更新分镜表失败');
  421. }
  422. // 更新分镜视频成功后新增对话记录
  423. // 保存对话记录
  424. $records = [
  425. [
  426. 'uid' => $uid,
  427. 'anime_id' => $anime_id,
  428. 'sequence' => $episode_number,
  429. 'role' => 'user',
  430. 'content' => '图片转视频',
  431. 'segment_id' => $segmentId,
  432. 'video_url' => '',
  433. 'created_at' => $now,
  434. 'updated_at' => $now
  435. ],
  436. [
  437. 'uid' => $uid,
  438. 'anime_id' => $anime_id,
  439. 'sequence' => $episode_number,
  440. 'role' => 'assistant',
  441. 'content' => $tail_frame,
  442. 'segment_id' => $segmentId,
  443. 'video_url' => $statusResult['result_url'],
  444. 'created_at' => $now,
  445. 'updated_at' => $now
  446. ]
  447. ];
  448. DB::table('mp_anime_records')->insert($records);
  449. DB::commit();
  450. } catch (\Exception $e) {
  451. DB::rollBack();
  452. $logData = [
  453. 'task_id' => $taskId,
  454. 'error' => $e->getMessage()
  455. ];
  456. dLog('anime')->error('视频任务处理失败', $logData);
  457. logDB('anime', 'error', '视频任务处理失败', $logData);
  458. }
  459. } elseif ($statusResult['status'] === 'failed') {
  460. DB::table('mp_episode_segments')
  461. ->where('video_task_id', $taskId)
  462. ->update([
  463. 'video_task_status' => '失败',
  464. 'updated_at' => date('Y-m-d H:i:s')
  465. ]);
  466. }
  467. }
  468. }
  469. // 发送当前状态
  470. echo "data: " . json_encode([
  471. 'type' => 'update',
  472. 'data' => [
  473. 'task_id' => $task->id,
  474. 'status' => $task->status,
  475. 'result_url' => $task->result_url,
  476. 'error_message' => $task->error_message,
  477. 'elapsed_time' => time() - $startTime
  478. ]
  479. ]) . "\n\n";
  480. ob_flush();
  481. flush();
  482. // 如果任务完成(成功或失败),结束连接
  483. if (in_array($task->status, [
  484. 'success',
  485. 'failed'
  486. ])) {
  487. echo "data: " . json_encode([
  488. 'type' => 'completed',
  489. 'data' => [
  490. 'task_id' => $task->id,
  491. 'status' => $task->status,
  492. 'video_url' => $task->result_url,
  493. 'last_frame_url' => $task->last_frame_url,
  494. 'error_message' => $task->error_message
  495. ]
  496. ]) . "\n\n";
  497. ob_flush();
  498. flush();
  499. break;
  500. }
  501. sleep($checkInterval);
  502. } catch (\Exception $e) {
  503. echo "data: " . json_encode([
  504. 'type' => 'error',
  505. 'message' => '查询任务状态失败: ' . $e->getMessage()
  506. ]) . "\n\n";
  507. ob_flush();
  508. flush();
  509. sleep($checkInterval);
  510. }
  511. }
  512. // 超时处理
  513. if (time() - $startTime >= $maxDuration) {
  514. echo "data: " . json_encode([
  515. 'type' => 'time_out',
  516. 'message' => '任务执行超时,请稍后查询任务状态',
  517. 'data' => [
  518. 'task_id' => $taskId
  519. ]
  520. ]) . "\n\n";
  521. ob_flush();
  522. flush();
  523. }
  524. }, 200, [
  525. 'Content-Type' => 'text/event-stream',
  526. 'Cache-Control' => 'no-cache',
  527. 'Connection' => 'keep-alive',
  528. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  529. ]);
  530. }
  531. /**
  532. * 批量生成分镜视频
  533. */
  534. public function batchSetSegmentVideos(Request $request) {
  535. // 忽略所有超时限制
  536. set_time_limit(0);
  537. ini_set('max_execution_time', '0');
  538. $data = $request->all();
  539. // 验证参数
  540. $validator = Validator::make($data, [
  541. 'anime_id' => 'required|string',
  542. 'episode_id' => 'required|integer',
  543. ], [
  544. 'anime_id.required' => '动漫对话ID不能为空',
  545. 'episode_id.required' => '剧集ID不能为空',
  546. 'episode_id.integer' => '剧集ID必须是整数',
  547. ]);
  548. if ($validator->fails()) {
  549. Utils::throwError('1002:' . $validator->errors()->first());
  550. }
  551. $animeId = $data['anime_id'];
  552. $episodeId = $data['episode_id'];
  553. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->where('anime_id', $animeId)->first();
  554. if (!$episode) Utils::throwError('20003:分集不存在');
  555. $episodeNumber = $episode->episode_number;
  556. $ratio = !empty($episode->ratio) ? $episode->ratio : '9:16';
  557. // 获取所有分镜信息
  558. $segments = DB::table('mp_episode_segments')
  559. ->where('anime_id', $animeId)
  560. ->where('episode_id', $episodeId)
  561. ->whereNotIn('video_task_status', ['已完成', '生成中'])
  562. ->orderBy('segment_number')
  563. ->get();
  564. if ($segments->isEmpty()) {
  565. Utils::throwError('20003:未找到分镜数据');
  566. }
  567. // 批量创建视频任务
  568. $taskIds = [];
  569. $segmentTasks = [];
  570. foreach ($segments as $segment) {
  571. try {
  572. // 检查视频任务正在生成中或当前状态为视频
  573. if ($segment->video_task_status === '生成中' || (int)$segment->current_type === 2) {
  574. continue;
  575. }
  576. // 获取分镜内容
  577. $segmentContent = $segment->segment_content ?: '';
  578. $tailFrame = $segment->tail_frame ?: '';
  579. // 构建完整的提示词
  580. $fullPrompt = $segmentContent;
  581. if ($tailFrame) {
  582. $fullPrompt .= "\n尾帧描述:$tailFrame";
  583. }
  584. // 智能选择视频时长
  585. // $videoDuration = $this->AnimeService->calculateOptimalVideoDuration($segmentContent, $tailFrame);
  586. $videoDuration = -1;
  587. // 处理视频模型(在循环外统一处理,避免重复)
  588. if (!isset($model)) {
  589. $model = getProp($data, 'model');
  590. if (!$model) {
  591. // 用户没有输入,从episode表获取
  592. $episode = DB::table('mp_anime_episodes')->where('id', $episodeId)->first();
  593. $model = getProp($episode, 'video_model');
  594. if (!$model) {
  595. // episode表也没有,使用默认值
  596. $model = 'doubao-seedance-1-5-pro-251215';
  597. }
  598. }
  599. // 验证模型是否在可用模型表中
  600. if (!DB::table('mp_video_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  601. $model = 'doubao-seedance-1-5-pro-251215';
  602. }
  603. }
  604. // 构建视频生成参数
  605. $videoParams = [
  606. 'model' => $model,
  607. 'alias_segment_id' => $segment->segment_id,
  608. 'prompt' => $fullPrompt,
  609. 'video_duration' => $videoDuration,
  610. 'video_resolution' => '720P',
  611. 'seed' => -1,
  612. 'ratio' => $ratio,
  613. 'generate_audio' => false,
  614. 'draft' => false,
  615. 'watermark' => false,
  616. 'camera_fixed' => false,
  617. // 'callback_url' => 'http://mpaudio.yqsd.cn/api/video/seedanceCallback'
  618. ];
  619. // 如果分镜有图片,作为首帧
  620. $hasImage = !empty($segment->img_url);
  621. $hasVideo = !empty($segment->video_url);
  622. if ($hasImage) {
  623. $videoParams['first_frame_url'] = $segment->img_url;
  624. }
  625. // 构建content数组
  626. $videoParams['content'] = [
  627. [
  628. 'type' => 'text',
  629. 'text' => $videoParams['prompt'],
  630. ]
  631. ];
  632. // 如果有首帧图片,添加到content中
  633. if ($hasImage) {
  634. if (in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  635. $videoParams['content'][] = [
  636. 'type' => 'image_url',
  637. 'image_url' => [
  638. 'url' => $videoParams['first_frame_url'],
  639. ],
  640. 'role' => 'reference_image',
  641. ];
  642. }else {
  643. $videoParams['content'][] = [
  644. 'type' => 'image_url',
  645. 'image_url' => [
  646. 'url' => $videoParams['first_frame_url'],
  647. ],
  648. 'role' => 'first_frame',
  649. ];
  650. }
  651. }
  652. // 获取配音音频URL和时长
  653. $audioUrl = $segment->audio_url ?? '';
  654. $audioDuration = $segment->audio_duration ?? 0;
  655. // 音频传入的前提:必须有至少一张图片或一个视频
  656. $canUseAudio = ($hasImage || $hasVideo) && !empty($audioUrl);
  657. // 根据模型选择不同的视频生成方法
  658. if (strpos($model, 'jimeng') !== false) {
  659. // 即梦模型参数调整
  660. $videoParams['video_duration'] = $audioDuration > 5 ? 10 : 5; // 即梦只支持5s或10s
  661. $videoParams['aspect_ratio'] = $videoParams['ratio']; // 即梦使用aspect_ratio
  662. unset($videoParams['ratio']);
  663. unset($videoParams['content']); // 即梦不使用content格式
  664. $task = $this->AIVideoGenerationService->createJimengTask($videoParams);
  665. } elseif (strpos($model, 'kling') !== false) {
  666. // Keling模型参数调整
  667. $videoParams['video_duration'] = max(3, min(15, ceil($audioDuration))); // Keling支持3-15秒
  668. $videoParams['aspect_ratio'] = $videoParams['ratio']; // Keling使用aspect_ratio
  669. unset($videoParams['ratio']);
  670. unset($videoParams['content']); // Keling不使用content格式
  671. $task = $this->AIVideoGenerationService->createKelingOmniTask($videoParams);
  672. } else {
  673. // 检查是否为 Seedance 2.0 模型,如果是则需要处理配音音频
  674. if ($canUseAudio && in_array($model, ['doubao-seedance-2-0-260128', 'doubao-seedance-2-0-fast-260128'])) {
  675. // 添加配音音频到content中
  676. $videoParams['content'][] = [
  677. 'type' => 'audio_url',
  678. 'audio_url' => [
  679. 'url' => $audioUrl,
  680. ],
  681. 'role' => 'reference_audio',
  682. ];
  683. // 优化提示词,增加音频相关描述
  684. $audioPrompt = "全程使用音频1作为视频配音。" . $fullPrompt;
  685. $videoParams['prompt'] = $audioPrompt;
  686. $videoParams['content'][0]['text'] = $audioPrompt;
  687. } else if ($audioDuration) {
  688. // 有音频时长则需将视频时长设置为比音频时长更长的整数
  689. $videoParams['video_duration'] = max(4, min(12, ceil($audioDuration))); // seedance支持2-12s
  690. }
  691. // Seedance模型(默认)
  692. $task = $this->AIVideoGenerationService->createSeedanceTask($videoParams);
  693. }
  694. $taskIds[] = $task->id;
  695. // 更新分镜表的视频任务信息
  696. DB::table('mp_episode_segments')
  697. ->where('segment_id', $segment->segment_id)
  698. ->update([
  699. 'video_task_id' => $task->id,
  700. 'video_task_status' => '生成中',
  701. 'updated_at' => date('Y-m-d H:i:s')
  702. ]);
  703. $segmentTasks[] = [
  704. 'segment_id' => $segment->segment_id,
  705. 'task_id' => $task->id,
  706. 'segment_number' => $segment->segment_number,
  707. 'tail_frame' => $segment->tail_frame,
  708. 'audio_duration' => $segment->audio_duration,
  709. ];
  710. } catch (\Exception $e) {
  711. $logData = [
  712. 'segment_id' => $segment->segment_id,
  713. 'anime_id' => $animeId,
  714. 'error' => $e->getMessage(),
  715. ];
  716. dLog('anime')->error('创建分镜视频任务失败', $logData);
  717. logDB('anime', 'error', '创建分镜视频任务失败', $logData);
  718. continue;
  719. }
  720. }
  721. if (empty($taskIds)) {
  722. Utils::throwError('20003:没有需要生成视频的分镜');
  723. }
  724. // 保存模型到episode表
  725. if (isset($model)) {
  726. DB::table('mp_anime_episodes')->where('id', $episodeId)->update([
  727. 'video_model' => $model,
  728. 'updated_at' => date('Y-m-d H:i:s')
  729. ]);
  730. }
  731. // 记录开始时间(包含创建任务的时间)
  732. $startTime = time();
  733. $maxDuration = 1800; // 30分钟超时
  734. $uid = Site::getUid();
  735. // 设置 SSE 响应头并开始长连接
  736. return response()->stream(function () use ($taskIds, $segmentTasks, $animeId, $episodeNumber, $episodeId, $startTime, $maxDuration, $uid) {
  737. $checkInterval = 10; // 每10秒检查一次
  738. // 初始化任务数组
  739. $totalTasks = $taskIds; // 所有任务ID
  740. $completeTasks = []; // 已完成的任务ID(包含失败)
  741. $successTasks = []; // 成功的任务ID
  742. // 发送初始任务创建信息
  743. echo "data: " . json_encode([
  744. 'type' => 'init',
  745. 'total_tasks_count' => count($totalTasks),
  746. 'completed_tasks_count' => count($completeTasks),
  747. 'success_tasks_count' => count($successTasks)
  748. ]) . "\n\n";
  749. ob_flush();
  750. flush();
  751. while (time() - $startTime < $maxDuration) {
  752. try {
  753. $hasUpdate = false; // 标记是否有更新
  754. // 获取所有任务的最新状态
  755. foreach ($totalTasks as $taskId) {
  756. // 如果任务已经在完成列表中,跳过
  757. if (in_array($taskId, $completeTasks)) {
  758. continue;
  759. }
  760. $task = \App\Models\MpGenerateVideoTask::find($taskId);
  761. if (!$task) {
  762. continue;
  763. }
  764. // 如果任务还在处理中,查询最新状态
  765. if ($task->status === 'processing') {
  766. // 根据任务类型查询不同的状态
  767. if ($task->task_type === 'jimeng') {
  768. $statusResult = $this->AIVideoGenerationService->queryJimengTaskStatus($task);
  769. } elseif ($task->task_type === 'keling') {
  770. $statusResult = $this->AIVideoGenerationService->queryKelingOmniTaskStatus($task);
  771. } else {
  772. $statusResult = $this->AIVideoGenerationService->querySeedanceTaskStatus($task);
  773. }
  774. if (isset($statusResult['status'])) {
  775. // 更新任务状态
  776. $task->update([
  777. 'status' => $statusResult['status'],
  778. 'result_json' => $statusResult['result_json'] ?? [],
  779. 'result_url' => $statusResult['result_url'] ?? null,
  780. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  781. 'error_message' => $statusResult['error_message'] ?? null,
  782. 'completed_at' => in_array($statusResult['status'], [
  783. 'success',
  784. 'failed'
  785. ]) ? now() : null
  786. ]);
  787. // 如果任务成功,更新分镜表
  788. if ($statusResult['status'] === 'success' && isset($statusResult['result_url'])) {
  789. try {
  790. DB::beginTransaction();
  791. $now = date('Y-m-d H:i:s');
  792. // 获取分镜ID
  793. $segmentId = null;
  794. foreach ($segmentTasks as $segmentTask) {
  795. if ($segmentTask['task_id'] == $taskId) {
  796. $segmentId = $segmentTask['segment_id'];
  797. $tail_frame = $segmentTask['tail_frame'];
  798. $audio_duration = $segmentTask['audio_duration'];
  799. break;
  800. }
  801. }
  802. if ($segmentId) {
  803. // 更新分镜表
  804. $segmentUpdateData = [
  805. 'video_url' => $statusResult['result_url'],
  806. 'video_task_status' => '已完成',
  807. 'last_frame_url' => $statusResult['last_frame_url'] ?? '',
  808. 'current_type' => 2,
  809. 'updated_at' => $now
  810. ];
  811. $compressed_video_url = compressVideo($segmentUpdateData['video_url']);
  812. if ($compressed_video_url) $segmentUpdateData['preview_video_url'] = $compressed_video_url;
  813. // 只有当video_duration存在且大于0时才更新
  814. if (isset($statusResult['video_duration']) && $statusResult['video_duration'] > 0) {
  815. $segmentUpdateData['video_duration'] = $statusResult['video_duration'];
  816. $segmentUpdateData['video_time_point_start'] = 0;
  817. // $segmentUpdateData['video_time_point_end'] = $statusResult['video_duration'];
  818. $segmentUpdateData['video_time_point_end'] = $audio_duration ?? 0;
  819. }
  820. $updateResult = DB::table('mp_episode_segments')
  821. ->where('segment_id', $segmentId)
  822. ->update($segmentUpdateData);
  823. if ($updateResult) {
  824. // 更新分镜视频成功后新增对话记录
  825. $records = [
  826. [
  827. 'uid' => $uid,
  828. 'anime_id' => $animeId,
  829. 'sequence' => $episodeNumber,
  830. 'role' => 'user',
  831. 'content' => '图片转视频',
  832. 'segment_id' => $segmentId,
  833. 'video_url' => '',
  834. 'created_at' => $now,
  835. 'updated_at' => $now
  836. ],
  837. [
  838. 'uid' => $uid,
  839. 'anime_id' => $animeId,
  840. 'sequence' => $episodeNumber,
  841. 'role' => 'assistant',
  842. 'content' => $tail_frame ?? '',
  843. 'segment_id' => $segmentId,
  844. 'video_url' => $statusResult['result_url'],
  845. 'created_at' => $now,
  846. 'updated_at' => $now
  847. ]
  848. ];
  849. DB::table('mp_anime_records')->insert($records);
  850. }
  851. }
  852. DB::commit();
  853. } catch (\Exception $e) {
  854. DB::rollBack();
  855. $logData = [
  856. 'task_id' => $taskId,
  857. 'error' => $e->getMessage()
  858. ];
  859. dLog('anime')->error('视频任务处理失败', $logData);
  860. logDB('anime', 'error', '视频任务处理失败', $logData);
  861. }
  862. } elseif ($statusResult['status'] === 'failed') {
  863. // 获取分镜ID并更新失败状态
  864. foreach ($segmentTasks as $segmentTask) {
  865. if ($segmentTask['task_id'] == $taskId) {
  866. DB::table('mp_episode_segments')
  867. ->where('segment_id', $segmentTask['segment_id'])
  868. ->update([
  869. 'video_task_status' => '失败',
  870. 'updated_at' => date('Y-m-d H:i:s')
  871. ]);
  872. break;
  873. }
  874. }
  875. }
  876. }
  877. }
  878. // 检查任务是否完成(成功或失败)
  879. if (in_array($task->status, ['success', 'failed'])) {
  880. $completeTasks[] = $taskId;
  881. $hasUpdate = true;
  882. if ($task->status === 'success') {
  883. $successTasks[] = $taskId;
  884. }
  885. }
  886. }
  887. // 如果有更新,发送update通知
  888. if ($hasUpdate) {
  889. echo "data: " . json_encode([
  890. 'type' => 'update',
  891. 'total_tasks_count' => count($totalTasks),
  892. 'completed_tasks_count' => count($completeTasks),
  893. 'success_tasks_count' => count($successTasks)
  894. ]) . "\n\n";
  895. ob_flush();
  896. flush();
  897. }
  898. // 如果所有任务都完成了,结束连接
  899. if (count($completeTasks) >= count($totalTasks)) {
  900. // 获取所有成功任务的分镜信息
  901. $successSegments = [];
  902. foreach ($successTasks as $taskId) {
  903. // 通过taskId找到对应的segmentTask
  904. foreach ($segmentTasks as $segmentTask) {
  905. if ($segmentTask['task_id'] == $taskId) {
  906. $segment = DB::table('mp_episode_segments')
  907. ->where('segment_id', $segmentTask['segment_id'])
  908. ->select('segment_id', 'video_url')
  909. ->first();
  910. if ($segment && !empty($segment->video_url)) {
  911. $successSegments[] = [
  912. 'segment_id' => $segment->segment_id,
  913. 'video_url' => $segment->video_url
  914. ];
  915. }
  916. break;
  917. }
  918. }
  919. }
  920. echo "data: " . json_encode([
  921. 'type' => 'completed',
  922. 'total_tasks_count' => count($totalTasks),
  923. 'completed_tasks_count' => count($completeTasks),
  924. 'success_tasks_count' => count($successTasks),
  925. 'success_segments' => $successSegments
  926. ]) . "\n\n";
  927. ob_flush();
  928. flush();
  929. break;
  930. }
  931. // 检查是否超时
  932. if (time() - $startTime >= $maxDuration) {
  933. break;
  934. }
  935. sleep($checkInterval);
  936. } catch (\Exception $e) {
  937. echo "data: " . json_encode([
  938. 'type' => 'error',
  939. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  940. 'total_tasks_count' => count($totalTasks),
  941. 'completed_tasks_count' => count($completeTasks),
  942. 'success_tasks_count' => count($successTasks)
  943. ]) . "\n\n";
  944. ob_flush();
  945. flush();
  946. // 检查是否超时,如果超时则停止循环
  947. if (time() - $startTime >= $maxDuration) {
  948. break;
  949. }
  950. sleep($checkInterval);
  951. }
  952. }
  953. // 超时处理
  954. if (time() - $startTime >= $maxDuration) {
  955. echo "data: " . json_encode([
  956. 'type' => 'time_out',
  957. 'message' => '批量视频生成已超时30分钟,停止状态查询',
  958. 'total_tasks_count' => count($totalTasks),
  959. 'completed_tasks_count' => count($completeTasks),
  960. 'success_tasks_count' => count($successTasks)
  961. ]) . "\n\n";
  962. ob_flush();
  963. flush();
  964. }
  965. }, 200, [
  966. 'Content-Type' => 'text/event-stream',
  967. 'Cache-Control' => 'no-cache',
  968. 'Connection' => 'keep-alive',
  969. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  970. ]);
  971. }
  972. // 应用有声制作参数
  973. public function applyAudioData(Request $request) {
  974. $data = $request->all();
  975. $result = $this->AnimeService->applyAudioData($data);
  976. return $this->success($result);
  977. }
  978. // 获取分集生成图片信息
  979. public function episodePicsInfo(Request $request) {
  980. // 忽略所有超时限制
  981. set_time_limit(0);
  982. ini_set('max_execution_time', '0');
  983. $data = $request->all();
  984. // 获取生成器函数
  985. $streamGenerator = $this->AnimeService->episodePicsInfo($data);
  986. // 返回 SSE 响应
  987. return response()->stream($streamGenerator, 200, [
  988. 'Content-Type' => 'text/event-stream',
  989. 'Cache-Control' => 'no-cache',
  990. 'Connection' => 'keep-alive',
  991. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  992. ]);
  993. }
  994. public function clipSegmentVideo(Request $request) {
  995. $data = $request->all();
  996. $result = $this->AnimeService->clipSegmentVideo($data);
  997. return $this->success(['success'=>$result ? 1: 0]);
  998. }
  999. /**
  1000. * 创建完整视频合成任务
  1001. *
  1002. * @param Request $request
  1003. * @return \Illuminate\Http\JsonResponse
  1004. */
  1005. public function createCompleteVideoTask(Request $request)
  1006. {
  1007. // 忽略所有超时限制
  1008. set_time_limit(0);
  1009. ini_set('max_execution_time', '0');
  1010. $data = $request->all();
  1011. // 验证参数
  1012. $validator = Validator::make($data, [
  1013. 'anime_id' => 'required|string',
  1014. 'episode_id' => 'required|string',
  1015. ], [
  1016. 'anime_id.required' => '请选择动漫',
  1017. 'episode_id.required' => '请选择分集',
  1018. ]);
  1019. if ($validator->fails()) {
  1020. Utils::throwError('1002:' . $validator->errors()->first());
  1021. }
  1022. try {
  1023. $result = $this->AnimeService->createCompleteVideoTask($data);
  1024. return $this->success($result);
  1025. } catch (\Exception $e) {
  1026. $logData = [
  1027. 'anime_id' => $data['anime_id'] ?? '',
  1028. 'episode_id' => $data['episode_id'] ?? '',
  1029. 'error' => $e->getMessage()
  1030. ];
  1031. dLog('anime')->error('创建完整视频合成任务失败', $logData);
  1032. logDB('anime', 'error', '创建完整视频合成任务失败', $logData);
  1033. return $this->error('20003:'.$e->getMessage());
  1034. }
  1035. }
  1036. // 文生图(通用)
  1037. public function generateImg(Request $request) {
  1038. $data = $request->all();
  1039. $result = $this->AnimeService->generateImg($data);
  1040. return $this->success($result);
  1041. }
  1042. /**
  1043. * 导出分集的全部图片(下载并打包)
  1044. */
  1045. public function exportEpisodeImages(Request $request) {
  1046. // 忽略所有超时限制
  1047. set_time_limit(0);
  1048. ini_set('max_execution_time', '0');
  1049. ini_set('memory_limit', '512M');
  1050. $data = $request->all();
  1051. // 验证参数
  1052. $validator = Validator::make($data, [
  1053. 'anime_id' => 'required|string',
  1054. 'episode_id' => 'required|string',
  1055. ], [
  1056. 'anime_id.required' => '动漫ID不能为空',
  1057. 'episode_id.required' => '剧集ID不能为空',
  1058. ]);
  1059. if ($validator->fails()) {
  1060. Utils::throwError('1002:' . $validator->errors()->first());
  1061. }
  1062. $animeId = $data['anime_id'];
  1063. $episodeId = $data['episode_id'];
  1064. try {
  1065. // 获取剧集信息
  1066. $episode = DB::table('mp_anime_episodes')
  1067. ->where('anime_id', $animeId)
  1068. ->where('id', $episodeId)
  1069. ->select('episode_number', 'title')
  1070. ->first();
  1071. if (!$episode) {
  1072. Utils::throwError('20003:未找到剧集信息');
  1073. }
  1074. // 获取所有分镜图片和音频
  1075. $segments = DB::table('mp_episode_segments')
  1076. ->where('anime_id', $animeId)
  1077. ->where('episode_id', $episodeId)
  1078. ->whereNotNull('img_url')
  1079. ->where('img_url', '!=', '')
  1080. ->orderBy('segment_number')
  1081. ->select('segment_id', 'segment_number', 'img_url', 'video_url', 'audio_url', 'act_number', 'act_title')
  1082. ->get();
  1083. if ($segments->isEmpty()) {
  1084. Utils::throwError('20003:该剧集暂无图片可导出');
  1085. }
  1086. // 创建临时目录
  1087. $tempDir = storage_path('app/temp/episode_images_' . time() . '_' . mt_rand(1000, 9999));
  1088. if (!file_exists($tempDir)) {
  1089. mkdir($tempDir, 0755, true);
  1090. }
  1091. // 下载图片或视频
  1092. $downloadedFiles = [];
  1093. foreach ($segments as $segment) {
  1094. try {
  1095. // 优先使用video_url,如果没有则使用img_url
  1096. $mediaUrl = !empty($segment->video_url) ? $segment->video_url : $segment->img_url;
  1097. if (empty($mediaUrl)) {
  1098. continue;
  1099. }
  1100. // 获取文件扩展名
  1101. $extension = pathinfo(parse_url($mediaUrl, PHP_URL_PATH), PATHINFO_EXTENSION);
  1102. if (empty($extension)) {
  1103. // 根据URL类型设置默认扩展名
  1104. $extension = !empty($segment->video_url) ? 'mp4' : 'jpg';
  1105. }
  1106. // 构建文件名:分镜序号.扩展名
  1107. $fileName = sprintf(
  1108. '%03d.%s',
  1109. $segment->segment_number,
  1110. $extension
  1111. );
  1112. $filePath = $tempDir . '/' . $fileName;
  1113. // 下载文件(使用file_get_contents,兼容性更好)
  1114. $context = stream_context_create([
  1115. 'http' => [
  1116. 'timeout' => 30,
  1117. 'follow_location' => 1,
  1118. 'ignore_errors' => true
  1119. ],
  1120. 'ssl' => [
  1121. 'verify_peer' => false,
  1122. 'verify_peer_name' => false
  1123. ]
  1124. ]);
  1125. $fileData = @file_get_contents($mediaUrl, false, $context);
  1126. if ($fileData !== false && !empty($fileData)) {
  1127. file_put_contents($filePath, $fileData);
  1128. $downloadedFiles[] = $filePath;
  1129. } else {
  1130. $logData = [
  1131. 'segment_id' => $segment->segment_id,
  1132. 'media_url' => $mediaUrl,
  1133. 'type' => !empty($segment->video_url) ? 'video' : 'image'
  1134. ];
  1135. dLog('anime')->warning('文件下载失败', $logData);
  1136. logDB('anime', 'warning', '文件下载失败', $logData);
  1137. }
  1138. } catch (\Exception $e) {
  1139. $logData = [
  1140. 'segment_id' => $segment->segment_id,
  1141. 'video_url' => $segment->video_url,
  1142. 'img_url' => $segment->img_url,
  1143. 'error' => $e->getMessage()
  1144. ];
  1145. dLog('anime')->error('下载文件异常', $logData);
  1146. logDB('anime', 'error', '下载文件异常', $logData);
  1147. continue;
  1148. }
  1149. }
  1150. if (empty($downloadedFiles)) {
  1151. // 清理临时目录
  1152. if (file_exists($tempDir)) {
  1153. array_map('unlink', glob("$tempDir/*"));
  1154. rmdir($tempDir);
  1155. }
  1156. Utils::throwError('20003:没有成功下载任何图片');
  1157. }
  1158. // 处理音频合成
  1159. $mergedAudioPath = null;
  1160. try {
  1161. // 检查 FFmpeg 是否可用
  1162. exec('which ffmpeg 2>&1', $ffmpegCheck, $ffmpegReturnCode);
  1163. $hasFfmpeg = ($ffmpegReturnCode === 0);
  1164. if ($hasFfmpeg) {
  1165. // 下载所有分镜的音频文件
  1166. $audioFiles = [];
  1167. foreach ($segments as $segment) {
  1168. if (!empty($segment->audio_url)) {
  1169. try {
  1170. $context = stream_context_create([
  1171. 'http' => [
  1172. 'timeout' => 30,
  1173. 'follow_location' => 1,
  1174. 'ignore_errors' => true
  1175. ],
  1176. 'ssl' => [
  1177. 'verify_peer' => false,
  1178. 'verify_peer_name' => false
  1179. ]
  1180. ]);
  1181. $audioData = @file_get_contents($segment->audio_url, false, $context);
  1182. if ($audioData !== false && !empty($audioData)) {
  1183. // 获取音频文件扩展名
  1184. $audioExtension = pathinfo(parse_url($segment->audio_url, PHP_URL_PATH), PATHINFO_EXTENSION);
  1185. if (empty($audioExtension)) {
  1186. $audioExtension = 'wav';
  1187. }
  1188. $audioFileName = sprintf('audio_%03d.%s', $segment->segment_number, $audioExtension);
  1189. $audioFilePath = $tempDir . '/' . $audioFileName;
  1190. file_put_contents($audioFilePath, $audioData);
  1191. $audioFiles[] = $audioFilePath;
  1192. } else {
  1193. $logData = [
  1194. 'segment_id' => $segment->segment_id,
  1195. 'audio_url' => $segment->audio_url
  1196. ];
  1197. dLog('anime')->warning('音频下载失败', $logData);
  1198. logDB('anime', 'warning', '音频下载失败', $logData);
  1199. }
  1200. } catch (\Exception $e) {
  1201. $logData = [
  1202. 'segment_id' => $segment->segment_id,
  1203. 'audio_url' => $segment->audio_url,
  1204. 'error' => $e->getMessage()
  1205. ];
  1206. dLog('anime')->error('下载音频异常', $logData);
  1207. logDB('anime', 'error', '下载音频异常', $logData);
  1208. }
  1209. }
  1210. }
  1211. // 如果有音频文件,则进行合成
  1212. if (!empty($audioFiles)) {
  1213. // 创建 FFmpeg concat 文件列表
  1214. $concatFile = $tempDir . '/concat.txt';
  1215. $concatContent = '';
  1216. foreach ($audioFiles as $audioFile) {
  1217. // 使用相对路径,避免路径中的特殊字符问题
  1218. $concatContent .= "file '" . basename($audioFile) . "'\n";
  1219. }
  1220. file_put_contents($concatFile, $concatContent);
  1221. // 合成音频文件
  1222. $mergedAudioPath = $tempDir . '/tts.wav';
  1223. // 使用 FFmpeg 合并音频,转换为统一的 WAV 格式
  1224. $ffmpegCommand = sprintf(
  1225. 'cd %s && ffmpeg -f concat -safe 0 -i %s -ar 44100 -ac 2 -y %s 2>&1',
  1226. escapeshellarg($tempDir),
  1227. escapeshellarg(basename($concatFile)),
  1228. escapeshellarg(basename($mergedAudioPath))
  1229. );
  1230. exec($ffmpegCommand, $ffmpegOutput, $ffmpegReturnCode);
  1231. if ($ffmpegReturnCode !== 0 || !file_exists($mergedAudioPath)) {
  1232. $logData = [
  1233. 'command' => $ffmpegCommand,
  1234. 'output' => implode("\n", $ffmpegOutput),
  1235. 'return_code' => $ffmpegReturnCode
  1236. ];
  1237. dLog('anime')->error('FFmpeg 合成音频失败', $logData);
  1238. logDB('anime', 'error', 'FFmpeg 合成音频失败', $logData);
  1239. $mergedAudioPath = null;
  1240. } else {
  1241. $logData = [
  1242. 'audio_count' => count($audioFiles),
  1243. 'output_file' => $mergedAudioPath,
  1244. 'file_size' => filesize($mergedAudioPath)
  1245. ];
  1246. dLog('anime')->info('音频合成成功', $logData);
  1247. logDB('anime', 'info', '音频合成成功', $logData);
  1248. }
  1249. // 清理临时音频文件和 concat 文件
  1250. foreach ($audioFiles as $audioFile) {
  1251. if (file_exists($audioFile)) {
  1252. @unlink($audioFile);
  1253. }
  1254. }
  1255. if (file_exists($concatFile)) {
  1256. @unlink($concatFile);
  1257. }
  1258. }
  1259. } else {
  1260. dLog('anime')->warning('FFmpeg 未安装,跳过音频合成');
  1261. logDB('anime', 'warning', 'FFmpeg 未安装,跳过音频合成', []);
  1262. }
  1263. } catch (\Exception $e) {
  1264. $logData = [
  1265. 'error' => $e->getMessage(),
  1266. 'trace' => $e->getTraceAsString()
  1267. ];
  1268. dLog('anime')->error('音频合成过程异常', $logData);
  1269. logDB('anime', 'error', '音频合成过程异常', $logData);
  1270. // 音频合成失败不影响图片导出
  1271. $mergedAudioPath = null;
  1272. }
  1273. // 创建zip文件
  1274. $zipFileName = sprintf(
  1275. '%s.zip',
  1276. $episode->title ?: '未命名'
  1277. );
  1278. $zipFilePath = storage_path('app/temp/' . $zipFileName);
  1279. $zip = new \ZipArchive();
  1280. if ($zip->open($zipFilePath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
  1281. // 清理临时文件
  1282. array_map('unlink', $downloadedFiles);
  1283. rmdir($tempDir);
  1284. Utils::throwError('20003:创建ZIP文件失败');
  1285. }
  1286. // 添加图片文件到zip
  1287. foreach ($downloadedFiles as $file) {
  1288. $zip->addFile($file, basename($file));
  1289. }
  1290. // 添加合成的音频文件到zip
  1291. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1292. $zip->addFile($mergedAudioPath, 'tts.wav');
  1293. }
  1294. $zip->close();
  1295. // 清理临时图片文件
  1296. array_map('unlink', $downloadedFiles);
  1297. // 清理合成的音频文件
  1298. if ($mergedAudioPath && file_exists($mergedAudioPath)) {
  1299. @unlink($mergedAudioPath);
  1300. }
  1301. rmdir($tempDir);
  1302. // 返回文件下载响应
  1303. return response()->download($zipFilePath, $zipFileName)->deleteFileAfterSend(true);
  1304. } catch (\Exception $e) {
  1305. $logData = [
  1306. 'anime_id' => $animeId,
  1307. 'episode_id' => $episodeId,
  1308. 'error' => $e->getMessage()
  1309. ];
  1310. dLog('anime')->error('导出分集图片失败', $logData);
  1311. logDB('anime', 'error', '导出分集图片失败', $logData);
  1312. // 清理可能存在的临时文件
  1313. if (isset($tempDir) && file_exists($tempDir)) {
  1314. array_map('unlink', glob("$tempDir/*"));
  1315. rmdir($tempDir);
  1316. }
  1317. if (isset($zipFilePath) && file_exists($zipFilePath)) {
  1318. unlink($zipFilePath);
  1319. }
  1320. throw $e;
  1321. }
  1322. }
  1323. /**
  1324. * 监控分镜图片和音频生成任务进度(SSE)
  1325. */
  1326. public function monitorSegmentTasks(Request $request) {
  1327. // 忽略所有超时限制
  1328. set_time_limit(0);
  1329. ini_set('max_execution_time', '0');
  1330. $data = $request->all();
  1331. // 验证参数
  1332. $validator = Validator::make($data, [
  1333. 'anime_id' => 'required|string',
  1334. 'episode_id' => 'required|string',
  1335. ], [
  1336. 'anime_id.required' => '动漫ID不能为空',
  1337. 'episode_id.required' => '剧集ID不能为空',
  1338. ]);
  1339. if ($validator->fails()) {
  1340. Utils::throwError('1002:' . $validator->errors()->first());
  1341. }
  1342. $animeId = $data['anime_id'];
  1343. $episodeId = $data['episode_id'];
  1344. // 查询没有pic_task_id的分镜个数
  1345. $noPicTaskCount = DB::table('mp_episode_segments')
  1346. ->where('anime_id', $animeId)
  1347. ->where('episode_id', $episodeId)
  1348. ->where(function($query) {
  1349. $query->whereNull('pic_task_id')
  1350. ->orWhere('pic_task_id', '');
  1351. })
  1352. ->count('id');
  1353. // 获取所有分镜信息
  1354. $segments = DB::table('mp_episode_segments')
  1355. ->where('anime_id', $animeId)
  1356. ->where('episode_id', $episodeId)
  1357. ->where('pic_task_id', '!=', '')
  1358. ->orderBy('segment_number')
  1359. ->get();
  1360. if (env('APP_ENV') == 'production') { // 正式环境才压缩
  1361. // 循环判断分镜中preview_video_url是否存在,如果没有但video_url有值,则压缩video_url并赋值给preview_video_url
  1362. foreach ($segments as $segment) {
  1363. $segment = (array)$segment;
  1364. if ((empty($segment['preview_video_url']) || $segment['preview_video_url'] === '')
  1365. && !empty($segment['video_url']) && $segment['video_url'] !== '') {
  1366. // 压缩视频
  1367. $compressedUrl = compressVideo($segment['video_url'], 'videos');
  1368. // 只有压缩成功才更新数据库
  1369. if ($compressedUrl !== '') {
  1370. DB::table('mp_episode_segments')
  1371. ->where('id', $segment['id'])
  1372. ->update(['preview_video_url' => $compressedUrl]);
  1373. }
  1374. }
  1375. }
  1376. }
  1377. // 判断是否有未完成的任务
  1378. $uncompleted_pic_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)
  1379. ->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->whereNotIn('pic_task_status', ['已完成', '失败'])->count('id');
  1380. // 获取dialogue和voice_type存在但audio_url不存在的分镜个数
  1381. $uncompleted_audio_count = DB::table('mp_episode_segments')
  1382. ->where('anime_id', $animeId)
  1383. ->where('episode_id', $episodeId)
  1384. ->where('dialogue', '<>', '')
  1385. ->whereNotNull('dialogue')
  1386. ->where('voice_type', '<>', '')
  1387. ->whereNotNull('voice_type')
  1388. ->where(function($query) {
  1389. $query->whereNull('audio_url')
  1390. ->orWhere('audio_url', '');
  1391. })
  1392. ->count('id');
  1393. if ($segments->isEmpty()) {
  1394. Utils::throwError('20003:未找到分镜任务数据');
  1395. }
  1396. $startTime = time();
  1397. $maxDuration = 900; // 15分钟超时
  1398. $checkInterval = 5; // 每5秒检查一次
  1399. // 设置 SSE 响应头并开始长连接
  1400. return response()->stream(function () use ($segments, $animeId, $episodeId, $startTime, $maxDuration, $checkInterval, $uncompleted_pic_count, $uncompleted_audio_count, $noPicTaskCount) {
  1401. if ($uncompleted_pic_count == 0 && $uncompleted_audio_count == 0) {
  1402. $completedCount = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episodeId)->where('pic_task_id', '<>', '')->where('pic_task_status', '已完成')->count('id');
  1403. // 获取剧集信息之前先处理视频截止时间点
  1404. $this->handleVideoTimePointEnd();
  1405. // 获取剧集信息
  1406. $episode = DB::table('mp_anime_episodes')
  1407. ->where('anime_id', $animeId)
  1408. ->where('id', $episodeId)
  1409. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1410. ->first();
  1411. if ($episode) {
  1412. $episode = (array)$episode;
  1413. $episode['roles'] = json_decode($episode['roles'], true);
  1414. $episode['scenes'] = json_decode($episode['scenes'], true);
  1415. // 获取所有分镜信息
  1416. $allSegments = DB::table('mp_episode_segments')
  1417. ->where('anime_id', $animeId)
  1418. ->where('episode_id', $episodeId)
  1419. ->orderBy('segment_number')
  1420. ->select('*')
  1421. ->get()
  1422. ->map(function ($value) {
  1423. return (array)$value;
  1424. })->toArray();
  1425. // 按照episodeInfo的格式组织数据
  1426. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1427. $episode['acts'] = $segmentsStructure['acts'];
  1428. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1429. }
  1430. echo "data: " . json_encode([
  1431. 'type' => 'completed',
  1432. 'data' => [
  1433. 'anime_id' => $animeId,
  1434. 'episode_id' => $episodeId,
  1435. 'completed_count' => $completedCount, // 成功完成的数量
  1436. 'processed_count' => count($segments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1437. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1438. 'total_elapsed_time' => time() - $startTime,
  1439. 'episode_info' => $episode ?? null
  1440. ]
  1441. ]) . "\n\n";
  1442. ob_flush();
  1443. flush();
  1444. return;
  1445. }
  1446. // 发送初始任务信息
  1447. echo "data: " . json_encode([
  1448. 'type' => 'init',
  1449. 'data' => [
  1450. 'anime_id' => $animeId,
  1451. 'episode_id' => $episodeId,
  1452. 'total_segments' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1453. 'start_time' => $startTime,
  1454. 'max_duration' => $maxDuration
  1455. ]
  1456. ]) . "\n\n";
  1457. ob_flush();
  1458. flush();
  1459. $completedSegments = [];
  1460. $processedSegments = []; // 记录已处理完成的分镜(成功或失败)
  1461. $notifiedSegments = []; // 记录已通知过的分镜,避免重复通知
  1462. while (time() - $startTime < $maxDuration) {
  1463. try {
  1464. $updatedImages = []; // 记录本次循环中更新的图片信息
  1465. foreach ($segments as $segment) {
  1466. $segmentId = $segment->segment_id;
  1467. $picTaskId = $segment->pic_task_id;
  1468. $audioUrl = $segment->audio_url;
  1469. // 跳过已处理完成的分镜
  1470. if (in_array($segmentId, $processedSegments)) {
  1471. continue;
  1472. }
  1473. $picCompleted = false;
  1474. $audioCompleted = false;
  1475. $picProcessed = false;
  1476. $audioProcessed = false;
  1477. // 检查图片任务状态
  1478. if ($picTaskId) {
  1479. $picTask = DB::table('mp_generate_pic_tasks')
  1480. ->where('id', $picTaskId)
  1481. ->select('status', 'result_url', 'error_message')
  1482. ->first();
  1483. if ($picTask && in_array($picTask->status, ['success', 'failed'])) {
  1484. $updateData = [
  1485. 'pic_task_status' => $picTask->status === 'success' ? '已完成' : '失败',
  1486. 'updated_at' => date('Y-m-d H:i:s')
  1487. ];
  1488. $imgUrl = '';
  1489. if ($picTask->status === 'success' && !empty($picTask->result_url)) {
  1490. // 更新分镜表的图片URL
  1491. $resultUrls = json_decode($picTask->result_url, true);
  1492. $imgUrl = is_array($resultUrls) ? $resultUrls[0] : $picTask->result_url;
  1493. $updateData['img_url'] = $imgUrl;
  1494. $picCompleted = true;
  1495. } else if ($picTask->status === 'failed') {
  1496. // 失败时清空图片URL
  1497. $updateData['img_url'] = '';
  1498. }
  1499. DB::table('mp_episode_segments')
  1500. ->where('segment_id', $segmentId)
  1501. ->update($updateData);
  1502. // 记录更新的图片信息(只有未通知过的才记录)
  1503. if (!in_array($segmentId, $notifiedSegments)) {
  1504. $updatedImages[] = [
  1505. 'segment_id' => $segmentId,
  1506. 'segment_number' => $segment->segment_number,
  1507. 'img_url' => $imgUrl,
  1508. 'status' => $picTask->status === 'success' ? 'success' : 'failed'
  1509. ];
  1510. // 标记为已通知
  1511. $notifiedSegments[] = $segmentId;
  1512. }
  1513. $picProcessed = true;
  1514. }
  1515. }
  1516. // 检查音频状态
  1517. // 获取分镜的dialogue、voice_type和audio_url信息
  1518. $segmentInfo = DB::table('mp_episode_segments')
  1519. ->where('segment_id', $segmentId)
  1520. ->select('dialogue', 'voice_type', 'audio_url')
  1521. ->first();
  1522. $needAudio = false;
  1523. $currentAudioUrl = '';
  1524. if ($segmentInfo) {
  1525. $dialogue = trim((string)getProp($segmentInfo, 'dialogue'));
  1526. $voiceType = trim((string)getProp($segmentInfo, 'voice_type'));
  1527. $currentAudioUrl = trim((string)getProp($segmentInfo, 'audio_url'));
  1528. // 如果有对话和音色类型,则需要音频
  1529. if (!empty($dialogue) && !empty($voiceType)) {
  1530. $needAudio = true;
  1531. }
  1532. }
  1533. // 判断音频状态
  1534. if ($needAudio) {
  1535. // 需要音频的情况下,检查audio_url是否有值
  1536. if (!empty($currentAudioUrl)) {
  1537. $audioCompleted = true;
  1538. $audioProcessed = true;
  1539. } else {
  1540. // 需要音频但还没有,继续等待
  1541. $audioCompleted = false;
  1542. $audioProcessed = false;
  1543. }
  1544. } else {
  1545. // 不需要音频,直接标记为已处理
  1546. $audioCompleted = false;
  1547. $audioProcessed = true;
  1548. }
  1549. // 如果图片和音频都成功完成,标记为已完成
  1550. if ($picCompleted && ($audioCompleted || !$needAudio)) {
  1551. $completedSegments[] = $segmentId;
  1552. }
  1553. // 如果图片和音频都已处理完成(成功或失败),标记为已处理
  1554. if ($picProcessed && $audioProcessed) {
  1555. $processedSegments[] = $segmentId;
  1556. }
  1557. }
  1558. // 如果有图片更新,发送具体的图片更新信息
  1559. if (!empty($updatedImages)) {
  1560. echo "data: " . json_encode([
  1561. 'type' => 'update',
  1562. 'data' => [
  1563. 'anime_id' => $animeId,
  1564. 'episode_id' => $episodeId,
  1565. 'updated_images' => $updatedImages,
  1566. 'completed_count' => count($completedSegments), // 成功完成的数量
  1567. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1568. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1569. 'elapsed_time' => time() - $startTime,
  1570. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1571. ]
  1572. ]) . "\n\n";
  1573. ob_flush();
  1574. flush();
  1575. }
  1576. // 如果所有分镜都已处理完成(成功或失败),获取最终结果并结束连接
  1577. if (count($processedSegments) === count($segments)) {
  1578. // 获取剧集信息之前先处理视频截止时间点
  1579. $this->handleVideoTimePointEnd();
  1580. // 获取剧集信息
  1581. $episode = DB::table('mp_anime_episodes')
  1582. ->where('anime_id', $animeId)
  1583. ->where('id', $episodeId)
  1584. ->select('id as episode_id', 'anime_id', 'episode_number', 'title', 'intro', 'art_style', 'roles', 'scenes')
  1585. ->first();
  1586. if ($episode) {
  1587. $episode = (array)$episode;
  1588. $episode['roles'] = json_decode($episode['roles'], true);
  1589. $episode['scenes'] = json_decode($episode['scenes'], true);
  1590. // 获取所有分镜信息
  1591. $allSegments = DB::table('mp_episode_segments')
  1592. ->where('anime_id', $animeId)
  1593. ->where('episode_id', $episodeId)
  1594. ->orderBy('segment_number')
  1595. ->select('*')
  1596. ->get()
  1597. ->map(function ($value) {
  1598. return (array)$value;
  1599. })->toArray();
  1600. // 按照episodeInfo的格式组织数据
  1601. $segmentsStructure = $this->AnimeService->buildEpisodeSegmentsStructure($allSegments);
  1602. $episode['acts'] = $segmentsStructure['acts'];
  1603. $episode['total_duration'] = $segmentsStructure['total_duration'];
  1604. }
  1605. echo "data: " . json_encode([
  1606. 'type' => 'completed',
  1607. 'data' => [
  1608. 'anime_id' => $animeId,
  1609. 'episode_id' => $episodeId,
  1610. 'completed_count' => count($completedSegments), // 成功完成的数量
  1611. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1612. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1613. 'total_elapsed_time' => time() - $startTime,
  1614. 'episode_info' => $episode ?? null
  1615. ]
  1616. ]) . "\n\n";
  1617. ob_flush();
  1618. flush();
  1619. break;
  1620. }
  1621. // 检查是否超时
  1622. if (time() - $startTime >= $maxDuration) {
  1623. break;
  1624. }
  1625. sleep($checkInterval);
  1626. } catch (\Exception $e) {
  1627. echo "data: " . json_encode([
  1628. 'type' => 'error',
  1629. 'message' => '查询任务状态失败: ' . $e->getMessage(),
  1630. 'elapsed_time' => time() - $startTime,
  1631. 'remaining_time' => max(0, $maxDuration - (time() - $startTime))
  1632. ]) . "\n\n";
  1633. ob_flush();
  1634. flush();
  1635. if (time() - $startTime >= $maxDuration) {
  1636. break;
  1637. }
  1638. sleep($checkInterval);
  1639. }
  1640. }
  1641. // 超时处理
  1642. if (time() - $startTime >= $maxDuration) {
  1643. echo "data: " . json_encode([
  1644. 'type' => 'time_out',
  1645. 'message' => '分镜任务监控已超时15分钟,停止状态查询',
  1646. 'data' => [
  1647. 'anime_id' => $animeId,
  1648. 'episode_id' => $episodeId,
  1649. 'completed_count' => count($completedSegments), // 成功完成的数量
  1650. 'processed_count' => count($processedSegments) + $noPicTaskCount, // 已处理完成的数量(成功+失败)+ 没有pic_task_id的分镜
  1651. 'total_count' => count($segments) + $noPicTaskCount, // 总数包含没有pic_task_id的分镜
  1652. 'total_elapsed_time' => time() - $startTime,
  1653. 'timeout_duration' => $maxDuration
  1654. ]
  1655. ]) . "\n\n";
  1656. ob_flush();
  1657. flush();
  1658. }
  1659. }, 200, [
  1660. 'Content-Type' => 'text/event-stream',
  1661. 'Cache-Control' => 'no-cache',
  1662. 'Connection' => 'keep-alive',
  1663. 'X-Accel-Buffering' => 'no', // 禁用 Nginx 缓冲
  1664. ]);
  1665. }
  1666. /**
  1667. * 音频试听接口
  1668. * 创建音频任务并返回结果
  1669. */
  1670. public function previewAudio(Request $request) {
  1671. $data = $request->all();
  1672. $result = $this->AnimeService->previewAudio($data);
  1673. return $this->success($result);
  1674. }
  1675. private function handleVideoTimePointEnd() {
  1676. // 处理音频时长,循环查询dub_video_task_queue列表中的任务
  1677. $queueLength = Redis::llen('dub_video_task_queue');
  1678. if ($queueLength > 0) {
  1679. $processedTaskIds = []; // 记录已处理的任务ID
  1680. // 遍历队列中的所有任务
  1681. for ($i = 0; $i < $queueLength; $i++) {
  1682. $dubTaskId = Redis::lindex('dub_video_task_queue', $i);
  1683. if (!$dubTaskId) continue;
  1684. // 查询任务状态
  1685. $dubTask = DB::table('mp_dub_video_tasks')
  1686. ->where('id', $dubTaskId)
  1687. ->first();
  1688. if (!$dubTask) {
  1689. // 任务不存在,标记为需要删除
  1690. $processedTaskIds[] = $dubTaskId;
  1691. continue;
  1692. }
  1693. // 如果任务状态是已完成
  1694. if ($dubTask->generate_status === '执行成功') {
  1695. // 获取对应的分镜信息
  1696. $segment = DB::table('mp_episode_segments')
  1697. ->where('segment_id', $dubTask->alias_segment_id)
  1698. ->first();
  1699. // 如果分镜存在且audio_duration大于0
  1700. if ($segment && isset($segment->audio_duration) && $segment->audio_duration > 0) {
  1701. // 更新video_time_point_end字段
  1702. DB::table('mp_episode_segments')
  1703. ->where('segment_id', $dubTask->alias_segment_id)
  1704. ->update([
  1705. 'video_time_point_end' => $segment->audio_duration,
  1706. 'updated_at' => date('Y-m-d H:i:s')
  1707. ]);
  1708. dLog('anime')->info('更新分镜视频截止时间点', [
  1709. 'task_id' => $dubTaskId,
  1710. 'segment_id' => $dubTask->alias_segment_id,
  1711. 'audio_duration' => $segment->audio_duration
  1712. ]);
  1713. }
  1714. // 标记为需要从队列中删除
  1715. $processedTaskIds[] = $dubTaskId;
  1716. }
  1717. }
  1718. // 从Redis列表中删除已处理的任务ID
  1719. foreach ($processedTaskIds as $taskId) {
  1720. Redis::lrem('dub_video_task_queue', 0, $taskId);
  1721. }
  1722. }
  1723. }
  1724. }