GeneratePreviewVideo.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Libraries\CommonHelper;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Carbon;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Log;
  8. use Dcat\Admin\Traits\HasUploadedFile;
  9. use FFMpeg\FFMpeg;
  10. use FFMpeg\Coordinate\TimeCode;
  11. /*
  12. * 生成预览10秒视频
  13. *
  14. * @author <EMAIL>
  15. * 运行命令:php artisan command:preview-video
  16. */
  17. class GeneratePreviewVideo extends Command
  18. {
  19. use HasUploadedFile;
  20. /**
  21. * The name and signature of the console command.
  22. *
  23. * @var string
  24. */
  25. protected $signature = 'command:preview-video';
  26. /**
  27. * The console command description.
  28. *
  29. * @var string
  30. */
  31. protected $description = '生成预览视频';
  32. public $timeSecond = 5;
  33. /**
  34. * Execute the console command.
  35. *
  36. * @return int
  37. */
  38. public function handle()
  39. {
  40. $disk = $this->disk('oss');
  41. //如果目录不存在则创建
  42. $localPreviewPath = storage_path('tmp/previews');
  43. if (!file_exists($localPreviewPath)) {
  44. mkdir($localPreviewPath, 0777, true);
  45. }
  46. $reslut = DB::table('site_preview_video')
  47. ->where('status', '==', 0) // 过滤非空 video 字段
  48. ->orderBy('id') // 按主键排序确保顺序
  49. ->limit(1) // 限制处理 1 条
  50. ->get();
  51. foreach ($reslut as $item) {
  52. try {
  53. $video_oss_url = $this->ossUrl($item->video_url);
  54. $fileName = basename($video_oss_url);
  55. $fileInfo = pathinfo($fileName);
  56. //下载$video_url到本地
  57. $localFilePath = $localPreviewPath. '/'. $fileName;
  58. $this->saveLocal($video_oss_url, $localFilePath);
  59. $previewName = $fileInfo['filename'] . '_preview.' . $fileInfo['extension'];
  60. $previewPath = storage_path('tmp/previews/'.$previewName);
  61. //截取视频前5秒
  62. $this->generatePreview($localFilePath, $previewPath);
  63. //上传到OSS
  64. $uploadPath = 'videos/uploads/previews/'. date('Ym').'/'.$previewName;
  65. $disk->putFile($uploadPath,$previewPath);
  66. dd('success111cc');
  67. DB::table('site_preview_video')
  68. ->where('id', $item->id)
  69. ->update([
  70. 'preview_url' => $uploadPath . '/' . $previewName,
  71. 'status' => 1
  72. ]);
  73. } catch (\Exception $e) {
  74. DB::table('site_preview_video')
  75. ->where('id', $item->id)
  76. ->update([
  77. 'remark' => $e->getMessage(),
  78. 'status' => -1
  79. ]);
  80. }
  81. }
  82. //$this->importVideo();
  83. return dd('success');
  84. }
  85. private function saveLocal($url, $localPath) {
  86. $remote = fopen($url, 'rb');
  87. $local = fopen($localPath, 'wb');
  88. while (!feof($remote)) {
  89. fwrite($local, fread($remote, 8192)); // 8KB分块
  90. }
  91. fclose($remote);
  92. fclose($local);
  93. return $localPath;
  94. }
  95. private function ossUrl($url)
  96. {
  97. if (strpos($url, 'http:') === 0 || strpos($url, 'https:') === 0) {
  98. return $url;
  99. }
  100. return "https://mietublcom.oss-cn-hongkong.aliyuncs.com".'/'.$url;
  101. }
  102. public function generatePreview($inputUrl, $outputPath) {
  103. $ffmpeg = FFMpeg::create([
  104. 'ffmpeg.binaries' => '/usr/bin/ffmpeg',
  105. 'ffprobe.binaries' => '/usr/bin/ffprobe',
  106. 'timeout' => 300
  107. ]);
  108. $video = $ffmpeg->open($inputUrl);
  109. $video->filters()->clip(TimeCode::fromSeconds(0), TimeCode::fromSeconds($this->timeSecond));
  110. // 输出为H.264编码的MP4
  111. $format = new \FFMpeg\Format\Video\X264();
  112. $video->save($format, $outputPath);
  113. return $outputPath;
  114. }
  115. /*ssssssss
  116. * 把旧数据导入新的预览表
  117. */
  118. function importVideo()
  119. {
  120. try {
  121. // 分批处理数据,避免内存溢出
  122. DB::table('site_album')
  123. ->where('video', '<>', '[]') // 过滤非空 video 字段
  124. ->orderBy('id') // 按主键排序确保顺序
  125. ->chunkById(10000, function ($albums) { // 每次处理 100 条
  126. $insertData = [];
  127. foreach ($albums as $album) {
  128. // 跳过无效 JSON 数据
  129. $videos = json_decode($album->video, true);
  130. if (json_last_error() !== JSON_ERROR_NONE || !is_array($videos)) {
  131. Log::warning("Invalid JSON in album ID: {$album->id}");
  132. continue;
  133. }
  134. foreach ($videos as $video) {
  135. // 校验必要字段存在性
  136. if (empty($video['video_src']) || empty($video['cover'])) {
  137. Log::warning("Missing video_src or cover in album ID: {$album->id}");
  138. continue;
  139. }
  140. // 处理 URL 长度限制
  141. $videoUrl = substr($video['video_src'], 0, 255);
  142. // 构建插入数据
  143. $insertData[] = [
  144. 'video_url' => $videoUrl,
  145. 'preview_url' => '',
  146. 'status' => 0,
  147. 'created_at' => Carbon::now(),
  148. 'updated_at' => Carbon::now(),
  149. ];
  150. }
  151. }
  152. // 插入剩余数据
  153. if (!empty($insertData)) {
  154. DB::table('site_preview_video')->insert($insertData);
  155. }
  156. });
  157. return true;
  158. } catch (\Exception $e) {
  159. Log::error("Video import failed: " . $e->getMessage());
  160. return false;
  161. }
  162. }
  163. }