AnimeController.php 88 KB

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