BxDolTranscoderVideo.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup UnaCore UNA Core
  7. * @{
  8. */
  9. /**
  10. * This class transcodes videos and generates video thumbnails.
  11. *
  12. * To generate video which plays in all moders browsers along with video poster,
  13. * you need to create 3 different video transcoding objects which will generate .mp4, .webm videos and video poster.
  14. * Video is converting upon first access, so it is probably better to force video conversion by calling @see BxDolTranscoderVideo::getFileUrl just after video uploading.
  15. * Video for conversion is queued and when cron is run video conversion is performed.
  16. * While video is pending for conversion or in the process then
  17. * @see BxDolTranscoderVideo::getFileUrl methods returns empty string for video and predefined image for video poster.
  18. *
  19. * Transcoder object and other params are the same as in @see BxDolTranscoderImage, but it is highly recommended to disable 'atime_pruning' and 'atime_tracking',
  20. * or set it to fairly big value, since video transcoding is not performed on the fly and takes some time.
  21. *
  22. * Video conversion can be performed on separate server or multiple servers, to do it:
  23. * - install the script on separate server(s), but connect to the same DB which your main site is using
  24. * - enable 'sys_transcoder_queue_files' option (when it is enabled it takes a little longer to convert videos)
  25. * - add the following code to the begining of inc/header.inc.php file on the main site, where your actual site in installed:
  26. * @code
  27. * define('BX_TRANSCODER_PROCESS_COMPLETED', '');
  28. * @endcode
  29. * - if you don't want your main site to convert videos, so all conversion will be performed on the separate server, add the following code to the begining of inc/header.inc.php file on the main site:
  30. * @code
  31. * define('BX_TRANSCODER_NO_TRANSCODING', '');
  32. * @endcode
  33. * - all servers must have different host name
  34. * - only main server must be used as site, additional sites are just for video conversion, don't perform any action on these sites
  35. *
  36. *
  37. * Available filters:
  38. * - Mp4 - this filter convert video into .mp4 format along with resizing, the parameters are the following:
  39. * - h - height of resulted video (360px by default), for video it is highly recommended to specify only height parameter (without width parameter)
  40. * - video_bitrate - video bitrate (512k by default)
  41. * - audio_bitrate - video bitrate (128k by default)
  42. * - ffmpeg_options - additional command line options for ffmepeg, as key => value array (empty by default)
  43. * - Webm - this filter convert video into .webm format along with resizing, the parameters are the same as for Mp4 filter
  44. * - Poster - this filter generates video thumbnail, it tries to get poster at 0, 3 and 5 seconds from the beginning, it gets first not fully black/white thumb
  45. *
  46. *
  47. * Example of usage:
  48. * @code
  49. * // transcoder objects which generate .mp4, .webm videos and image poster
  50. * $oTranscoderMp4 = BxDolTranscoder::getObjectInstance('bx_video_mp4');
  51. * $oTranscoderWebm = BxDolTranscoder::getObjectInstance('bx_video_webm');
  52. * $oTranscoderPoster = BxDolTranscoder::getObjectInstance('bx_video_poster');
  53. *
  54. * // make sure to call it only once (for example: during module installation), before the first usage, no need to call it every time
  55. * $oTranscoderMp4->registerHandlers();
  56. * $oTranscoderWebm->registerHandlers();
  57. * $oTranscoderPoster->registerHandlers();
  58. *
  59. * // get URLs of transcoded videos and video thumbnail, 33 is ID of original video file stored in specified storage object
  60. * $sUrlMp4 = $oTranscoderMp4->getFileUrl(33);
  61. * $sUrlWebM = $oTranscoderWebm->getFileUrl(33);
  62. * $sUrlPoster = $oTranscoderPoster->getFileUrl(33);
  63. *
  64. * echo 'My cat:' . BxTemplFunctions::getInstance()->videoPlayer($sUrlPoster, $sUrlMP4, $sUrlWebM);
  65. * @endcode
  66. *
  67. * Also @see transcoder_videos sample for complete example.
  68. */
  69. class BxDolTranscoderVideo extends BxDolTranscoder implements iBxDolFactoryObject
  70. {
  71. protected function __construct($aObject, $oStorage)
  72. {
  73. parent::__construct($aObject, $oStorage);
  74. $this->_sQueueStorage = getParam('sys_transcoder_queue_storage') ? 'sys_transcoder_queue_files' : '';
  75. $this->_oDb = new BxDolTranscoderVideoQuery($aObject);
  76. $this->_sQueueTable = $this->_oDb->getQueueTable();
  77. }
  78. public static function getObjectAbstract()
  79. {
  80. if (isset($GLOBALS['bxDolClasses'][__CLASS__ . '!Abstract']))
  81. return $GLOBALS['bxDolClasses'][__CLASS__ . '!Abstract'];
  82. $aObject = array('object' => 'abstract');
  83. $o = new BxDolTranscoderVideo ($aObject, null);
  84. return ($GLOBALS['bxDolClasses'][__CLASS__ . '!Abstract'] = $o);
  85. }
  86. public static function getDuration($sFile)
  87. {
  88. $sCommand = escapeshellcmd(BX_SYSTEM_FFMPEG) . " -i " . escapeshellarg($sFile) . " 2>&1";
  89. $sResult = shell_exec($sCommand);
  90. $aMatch = array();
  91. if(!preg_match("/[Dd]uration:\s([0-9]{2}):([0-9]{2}):([0-9]{2})\.([0-9]{2})/i", $sResult, $aMatch))
  92. return false;
  93. $aDuration = array_slice($aMatch, 1, -1);
  94. return 3600 * (int)$aDuration[0] + 60 * (int)$aDuration[1] + (int)$aDuration[2];
  95. }
  96. public function getDevicePixelRatioHandlerSuffix ()
  97. {
  98. return '';
  99. }
  100. /**
  101. * check if transcoder suppors given file mime type
  102. */
  103. public function isMimeTypeSupported($sMimeType)
  104. {
  105. if (0 === strncmp($sMimeType, 'video/', 6))
  106. return true;
  107. return false;
  108. }
  109. /**
  110. * If video isn't processed yet then empty string is returned for video, or predefined image is returned for video poster
  111. */
  112. public function getFileUrlNotReady($mixedHandler)
  113. {
  114. return false === $this->getFilterParams('Poster') ? '' : BxDolTemplate::getInstance()->getImageUrl('video-na.png');
  115. }
  116. /**
  117. * Convert video to .jpg format - video poster
  118. */
  119. protected function applyFilter_Poster ($sFile, $aParams)
  120. {
  121. $oImage = BxDolImageResize::getInstance();
  122. $sFileOut = $this->getTmpFilename('.jpg');
  123. $bRet = false;
  124. $aSeconds = array (0, 3, 5, 8, 1);
  125. $sSize = $this->_getOptionSizeForVideo ($sFile, $aParams);
  126. foreach ($aSeconds as $iSecond) {
  127. $bRet = $this->_convertVideo($sFile, $sFileOut, '.jpg', $aParams, array (
  128. 's' => $sSize,
  129. 'ss' => $iSecond,
  130. 'vframes' => 1,
  131. 'f' => 'image2',
  132. 'an' => ' ',
  133. ));
  134. if (!$bRet)
  135. continue;
  136. $aRgb = $oImage->getAverageColor($sFileOut);
  137. $fRgb = ($aRgb['r'] + $aRgb['g'] + $aRgb['b']) / 3;
  138. if ($fRgb > 32 && $fRgb < 224)
  139. break;
  140. }
  141. if (!$bRet) {
  142. @unlink($sFileOut);
  143. return false;
  144. }
  145. return rename($sFileOut, $sFile);
  146. }
  147. /**
  148. * Convert video to .mp4 format
  149. */
  150. protected function applyFilter_Mp4 ($sFile, $aParams)
  151. {
  152. return $this->_convertVideo($sFile, $sFile, '.mp4', $aParams, array (
  153. 'strict' => 'experimental',
  154. 'vcodec' => 'libx264',
  155. 's' => $this->_getOptionSizeForVideo ($sFile, $aParams),
  156. 'b:v' => isset($aParams['video_bitrate']) ? $aParams['video_bitrate'] . 'k' : '512k',
  157. 'movflags' => '+faststart',
  158. 'acodec' => 'aac',
  159. 'ar' => '44100',
  160. 'b:a' => isset($aParams['audio_bitrate']) ? $aParams['audio_bitrate'] . 'k' : '128k',
  161. 'pix_fmt' => 'yuv420p',
  162. ));
  163. }
  164. /**
  165. * Convert video to .webm format
  166. */
  167. protected function applyFilter_Webm ($sFile, $aParams)
  168. {
  169. return $this->_convertVideo($sFile, $sFile, '.webm', $aParams, array (
  170. 's' => $this->_getOptionSizeForVideo ($sFile, $aParams),
  171. 'b:v' => isset($aParams['video_bitrate']) ? $aParams['video_bitrate'] . 'k' : '512k',
  172. 'acodec' => 'libvorbis',
  173. 'ar' => '44100',
  174. 'b:a' => isset($aParams['audio_bitrate']) ? $aParams['audio_bitrate'] . 'k' : '128k',
  175. 'pix_fmt' => 'yuv420p',
  176. ));
  177. }
  178. /**
  179. * Convert video using ffmpeg binary. Video conversion otput is written to the 'log' variable.
  180. * @param $sFile input file for conversion
  181. * @param $sFileOut output file for conversion, can be the same as input file
  182. * @param $sExt output file extension, in the format '.ext'
  183. * @param $aParams filter params
  184. * @param $aOptions ffmpeg options as array
  185. * @return false on error, or true on success
  186. */
  187. protected function _convertVideo ($sFile, $sFileOut, $sExt, $aParams, $aOptions)
  188. {
  189. if (!empty($aParams['ffmpeg_options']) && is_array($aParams['ffmpeg_options']))
  190. $aOptions = array_merge($aOptions, $aParams['ffmpeg_options']);
  191. $sOptions = '';
  192. foreach ($aOptions as $k => $v)
  193. if ($v)
  194. $sOptions .= "-{$k} {$v} ";
  195. $bRename = false;
  196. if ($sFileOut == $sFile) { // if output file is the same as input - generate new tmp file
  197. $sFileOut = $this->getTmpFilename($sExt);
  198. $bRename = true;
  199. }
  200. elseif (file_exists($sFileOut)) {
  201. @unlink($sFileOut);
  202. }
  203. $sCommand = escapeshellcmd(BX_SYSTEM_FFMPEG) . ' -y ' . $this->_getFfmpegThreadsParams() . ' -i ' . escapeshellarg($sFile) . ' ' . $this->_getFfmpegThreadsParams() . ' ' . $sOptions . ' ' . escapeshellarg($sFileOut) . ' 2>&1';
  204. $sOutput = shell_exec($sCommand);
  205. $this->addToLog("\n---\n{$sCommand}\n{$sOutput}\n");
  206. if (!file_exists($sFileOut) || 0 == filesize($sFileOut)) {
  207. bx_log('sys_transcoder', "[{$this->_aObject['object']}] ERROR: _convertVideo failed for file ({$sFile}):\n{$sCommand}\n{$sOutput}\n", BX_LOG_ERR);
  208. return false;
  209. }
  210. if ($bRename && !rename($sFileOut, $sFile)) { // rename tmp file, if tmp file was generated
  211. bx_log('sys_transcoder', "[{$this->_aObject['object']}] ERROR: _convertVideo failed, final rename from {$sFileOut} to {$sFile} failed", BX_LOG_ERR);
  212. return false;
  213. }
  214. return true;
  215. }
  216. public function isProcessHD ($sOrigVideoDim)
  217. {
  218. $iHeight = $this->getMaxResizeDimention('Mp4', 'h');
  219. return ($aDim = explode('x', $sOrigVideoDim)) && isset($aDim[1]) && (int)$aDim[1] >= $iHeight ? true : false;
  220. }
  221. /**
  222. * Get video size.
  223. * It generated image from the video and returns size of the image.
  224. * @param $sFile path to the video file
  225. * @return array where 'w' key is width and 'h' key is height
  226. */
  227. public function getSize ($sFile)
  228. {
  229. $sFileOut = $this->getTmpFilename('.jpg');
  230. $bRet = $this->_convertVideo($sFile, $sFileOut, '.jpg', array(), array (
  231. 'ss' => 0,
  232. 'vframes' => 1,
  233. 'f' => 'image2',
  234. 'an' => ' ',
  235. ));
  236. if (!$bRet) {
  237. @unlink($sFileOut);
  238. return false;
  239. }
  240. $oImage = BxDolImageResize::getInstance();
  241. $aSize = $oImage->getImageSize($sFileOut);
  242. @unlink($sFileOut);
  243. return $aSize;
  244. }
  245. /**
  246. * Get output video size as 'WxH' string.
  247. * It check filter params for 'w' and 'h' options and original video ratio and return the resulted video size.
  248. * - If only height specified in params (desired behavior) or no width or height is specified (default height is 360),
  249. * then width is automatically calculated using original video size ratio.
  250. * - If only width specified in params, then height is automatically calculated using original video size ratio.
  251. * - If width and height specified in params then these values are returned, but the resulted video size can be unproportionate.
  252. * @param $sFile original video file path (to check original video size ratio)
  253. * @param $aParams filter params
  254. * @return WxH string
  255. */
  256. protected function _getOptionSizeForVideo ($sFile, $aParams)
  257. {
  258. if (isset($aParams['w']) && isset($aParams['h']))
  259. return $aParams['w'] . 'x' . $aParams['h'];
  260. if (!isset($aParams['w']) && !isset($aParams['h']))
  261. $aParams['h'] = '360';
  262. $fRatio = 16/9;
  263. $aSize = $this->getSize($sFile);
  264. if ($aSize)
  265. $fRatio = $aSize['w'] / $aSize['h'];
  266. if (isset($aParams['h']))
  267. return round($fRatio * $aParams['h'] / 2) * 2 . 'x' . $aParams['h'];
  268. if (isset($aParams['w']))
  269. return $aParams['w'] . 'x' . round($aParams['w'] / $fRatio / 2) * 2;
  270. return '640x360'; // should never happen
  271. }
  272. protected function _getFfmpegThreadsParams ()
  273. {
  274. $s = '';
  275. // optionally limit number of threads
  276. if (defined('BX_SYSTEM_FFMPEG_THREAD') && ($iThreads = (int)constant('BX_SYSTEM_FFMPEG_THREAD'))) {
  277. $s .= '-threads ' . $iThreads;
  278. }
  279. return $s;
  280. }
  281. }
  282. /** @} */