AnimeController.php 89 KB

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