BxDolTranscoderVideo.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 function getDevicePixelRatioHandlerSuffix ()
  79. {
  80. return '';
  81. }
  82. /**
  83. * If video isn't processed yet then empty string is returned for video, or predefined image is returned for video poster
  84. */
  85. public function getFileUrlNotReady($mixedHandler)
  86. {
  87. return false === $this->getFilterParams('Poster') ? '' : BxDolTemplate::getInstance()->getImageUrl('video-na.png');
  88. }
  89. /**
  90. * Convert video to .jpg format - video poster
  91. */
  92. protected function applyFilter_Poster ($sFile, $aParams)
  93. {
  94. $oImage = BxDolImageResize::getInstance();
  95. $sFileOut = $this->getTmpFilename('.jpg');
  96. $bRet = false;
  97. $aSeconds = array (0, 3, 5, 0);
  98. $sSize = $this->_getOptionSizeForVideo ($sFile, $aParams);
  99. foreach ($aSeconds as $iSecond) {
  100. $bRet = $this->_convertVideo($sFile, $sFileOut, '.jpg', $aParams, array (
  101. 's' => $sSize,
  102. 'ss' => $iSecond,
  103. 'vframes' => 1,
  104. 'f' => 'image2',
  105. 'an' => ' ',
  106. ));
  107. if (!$bRet)
  108. continue;
  109. $aRgb = $oImage->getAverageColor($sFileOut);
  110. $fRgb = ($aRgb['r'] + $aRgb['g'] + $aRgb['b']) / 3;
  111. if ($fRgb > 32 && $fRgb < 224)
  112. break;
  113. }
  114. if (!$bRet) {
  115. @unlink($sFileOut);
  116. return false;
  117. }
  118. return rename($sFileOut, $sFile);
  119. }
  120. /**
  121. * Convert video to .mp4 format
  122. */
  123. protected function applyFilter_Mp4 ($sFile, $aParams)
  124. {
  125. return $this->_convertVideo($sFile, $sFile, '.mp4', $aParams, array (
  126. 'strict' => 'experimental',
  127. 'vcodec' => 'libx264',
  128. 's' => $this->_getOptionSizeForVideo ($sFile, $aParams),
  129. 'b:v' => isset($aParams['video_bitrate']) ? $aParams['video_bitrate'] . 'k' : '512k',
  130. 'movflags' => '+faststart',
  131. 'acodec' => 'aac',
  132. 'ar' => '44100',
  133. 'b:a' => isset($aParams['audio_bitrate']) ? $aParams['audio_bitrate'] . 'k' : '128k',
  134. ));
  135. }
  136. /**
  137. * Convert video to .webm format
  138. */
  139. protected function applyFilter_Webm ($sFile, $aParams)
  140. {
  141. return $this->_convertVideo($sFile, $sFile, '.webm', $aParams, array (
  142. 's' => $this->_getOptionSizeForVideo ($sFile, $aParams),
  143. 'b:v' => isset($aParams['video_bitrate']) ? $aParams['video_bitrate'] . 'k' : '512k',
  144. 'acodec' => 'libvorbis',
  145. 'ar' => '44100',
  146. 'b:a' => isset($aParams['audio_bitrate']) ? $aParams['audio_bitrate'] . 'k' : '128k',
  147. ));
  148. }
  149. /**
  150. * Convert video using ffmpeg binary. Video conversion otput is written to the 'log' variable.
  151. * @param $sFile input file for conversion
  152. * @param $sFileOut output file for conversion, can be the same as input file
  153. * @param $sExt output file extension, in the format '.ext'
  154. * @param $aParams filter params
  155. * @param $aOptions ffmpeg options as array
  156. * @return false on error, or true on success
  157. */
  158. protected function _convertVideo ($sFile, $sFileOut, $sExt, $aParams, $aOptions)
  159. {
  160. if (!empty($aParams['ffmpeg_options']) && is_array($aParams['ffmpeg_options']))
  161. $aOptions = array_merge($aOptions, $aParams['ffmpeg_options']);
  162. $sOptions = '';
  163. foreach ($aOptions as $k => $v)
  164. if ($v)
  165. $sOptions .= "-{$k} {$v} ";
  166. $bRename = false;
  167. if ($sFileOut == $sFile) { // if output file is the same as input - generate new tmp file
  168. $sFileOut = $this->getTmpFilename($sExt);
  169. $bRename = true;
  170. }
  171. elseif (file_exists($sFileOut)) {
  172. @unlink($sFileOut);
  173. }
  174. $sCommand = escapeshellcmd(BX_SYSTEM_FFMPEG) . ' -y -i ' . escapeshellarg($sFile) . ' ' . $sOptions . ' ' . escapeshellarg($sFileOut) . ' 2>&1';
  175. $sOutput = `$sCommand`;
  176. $this->addToLog("\n---\n{$sCommand}\n{$sOutput}\n");
  177. if (!file_exists($sFileOut) || 0 == filesize($sFileOut))
  178. return false;
  179. if ($bRename && !rename($sFileOut, $sFile)) // rename tmp file, if tmp file was generated
  180. return false;
  181. return true;
  182. }
  183. /**
  184. * Get video size.
  185. * It generated image from the video and returns size of the image.
  186. * @param $sFile path to the video file
  187. * @return array where 'w' key is width and 'h' key is height
  188. */
  189. protected function _getVideoSize ($sFile)
  190. {
  191. $sFileOut = $this->getTmpFilename('.jpg');
  192. $bRet = $this->_convertVideo($sFile, $sFileOut, '.jpg', array(), array (
  193. 'ss' => 0,
  194. 'vframes' => 1,
  195. 'f' => 'image2',
  196. 'an' => ' ',
  197. ));
  198. if (!$bRet) {
  199. @unlink($sFileOut);
  200. return false;
  201. }
  202. $oImage = BxDolImageResize::getInstance();
  203. $aSize = $oImage->getImageSize($sFileOut);
  204. @unlink($sFileOut);
  205. return $aSize;
  206. }
  207. /**
  208. * Get output video size as 'WxH' string.
  209. * It check filter params for 'w' and 'h' options and original video ratio and return the resulted video size.
  210. * - If only height specified in params (desired behavior) or no width or height is specified (default height is 360),
  211. * then width is automatically calculated using original video size ratio.
  212. * - If only width specified in params, then height is automatically calculated using original video size ratio.
  213. * - If width and height specified in params then these values are returned, but the resulted video size can be unproportionate.
  214. * @param $sFile original video file path (to check original video size ratio)
  215. * @param $aParams filter params
  216. * @return WxH string
  217. */
  218. protected function _getOptionSizeForVideo ($sFile, $aParams)
  219. {
  220. if (isset($aParams['w']) && isset($aParams['h']))
  221. return $aParams['w'] . 'x' . $aParams['h'];
  222. if (!isset($aParams['w']) && !isset($aParams['h']))
  223. $aParams['h'] = '360';
  224. $fRatio = 16/9;
  225. $aSize = $this->_getVideoSize($sFile);
  226. if ($aSize)
  227. $fRatio = $aSize['w'] / $aSize['h'];
  228. if (isset($aParams['h']))
  229. return round($fRatio * $aParams['h'] / 2) * 2 . 'x' . $aParams['h'];
  230. if (isset($aParams['w']))
  231. return $aParams['w'] . 'x' . round($aParams['w'] / $fRatio / 2) * 2;
  232. return '640x360'; // should never happen
  233. }
  234. }
  235. /** @} */