BxDolTranscoderVideo.php 11 KB

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