videoEncoderTheora.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifdef TORQUE_OGGTHEORA
  23. #include "videoCapture.h"
  24. #include "core/stream/fileStream.h"
  25. #include "console/console.h"
  26. #include "gfx/bitmap/gBitmap.h"
  27. #include "gfx/bitmap/bitmapUtils.h"
  28. #include "platform/threads/thread.h"
  29. #include "platform/threads/threadSafeDeque.h"
  30. #include "platform/threads/semaphore.h"
  31. #include "theora/theoraenc.h"
  32. #include "vorbis/codec.h"
  33. #include "vorbis/vorbisenc.h"
  34. #include "platform/profiler.h"
  35. //#define THEORA_ENCODER_SINGLE_THREAD
  36. // These are the coefficient lookup tables, so we don't need to multiply
  37. dALIGN( static S32 sYRGB[ 256 ][ 4 ] );
  38. dALIGN( static S32 sURGB[ 256 ][ 4 ] );
  39. dALIGN( static S32 sVRGB[ 256 ][ 4 ] );
  40. /// Initialize the lookup tables used in the RGB-YUV transcoding
  41. static void initLookupTables()
  42. {
  43. static bool sGenerated = false;
  44. if( !sGenerated )
  45. {
  46. for( S32 i = 0; i < 256; ++ i )
  47. {
  48. //Y = ( ( 66 * R + 129 * G + 25 * B + 128) >> 8) + 16
  49. //U = ( ( -38 * R - 74 * G + 112 * B + 128) >> 8) + 128
  50. //V = ( ( 112 * R - 94 * G - 18 * B + 128) >> 8) + 128
  51. // Y coefficients
  52. sYRGB[ i ][ 0 ] = 66 * i;
  53. sYRGB[ i ][ 1 ] = 129 * i;
  54. sYRGB[ i ][ 2 ] = 25 * i + 128 + (16 << 8);
  55. // U coefficients
  56. sURGB[ i ][ 0 ] = -38 * i;
  57. sURGB[ i ][ 1 ] = -74 * i;
  58. sURGB[ i ][ 2 ] = 112 * i + 128 + (128 << 8);
  59. // V coefficients
  60. sVRGB[ i ][ 0 ] = 112 * i;
  61. sVRGB[ i ][ 1 ] = -94 * i;
  62. sVRGB[ i ][ 2 ] = -18 * i + 128 + (128 << 8);
  63. }
  64. sGenerated = true;
  65. }
  66. }
  67. /// Theora video capture encoder
  68. class VideoEncoderTheora : public VideoEncoder, public Thread
  69. {
  70. U32 mCurrentFrame;
  71. ogg_stream_state to; // take physical pages, weld into a logical stream of packets
  72. th_enc_ctx *td; // Theora encoder context
  73. th_info ti; // Theora info structure
  74. th_comment tc; // Theora comment structure
  75. FileStream mFile; // Output file
  76. th_ycbcr_buffer mBuffer; // YCbCr buffer
  77. GBitmap* mLastFrame;
  78. ThreadSafeDeque< GBitmap* > mFrameBitmapList; // List with unprocessed frame bitmaps
  79. Semaphore mSemaphore; //Semaphore for preventing the encoder from being lagged behind the game
  80. bool mErrorStatus; //Status flag, true if OK, false if an error ocurred
  81. /// Sets our error status
  82. bool setStatus(bool status)
  83. {
  84. mErrorStatus = status;
  85. return mErrorStatus;
  86. }
  87. bool getStatus() { return mErrorStatus; }
  88. /// Encodes one frame
  89. void encodeFrame( GBitmap* bitmap, bool isLast=false )
  90. {
  91. PROFILE_SCOPE(Theora_encodeFrame);
  92. //Copy bitmap to YUV buffer
  93. copyBitmapToYUV420(bitmap);
  94. PROFILE_START(th_encode_ycbcr_in);
  95. //Submit frame for encoding
  96. if (th_encode_ycbcr_in(td, mBuffer))
  97. {
  98. Platform::outputDebugString("VideoEncoderTheora::encodeFrame() - The buffer size does not match the frame size the encoder was initialized with, or encoding has already completed. .");
  99. setStatus(false);
  100. PROFILE_END();
  101. return;
  102. }
  103. PROFILE_END();
  104. //Fetch the encoded packets
  105. ogg_packet packet;
  106. if (!th_encode_packetout(td, isLast, &packet))
  107. {
  108. Platform::outputDebugString("VideoEncoderTheora::encodeFrame() - Internal Theora library error.");
  109. setStatus(false);
  110. return;
  111. }
  112. //Insert packet into vorbis stream page
  113. ogg_stream_packetin(&to,&packet);
  114. //Increment
  115. mCurrentFrame++;
  116. //Is there a video page flushed?
  117. ogg_page videopage;
  118. while (ogg_stream_pageout(&to,&videopage))
  119. {
  120. //Write the video page to disk
  121. mFile.write(videopage.header_len, videopage.header);
  122. mFile.write(videopage.body_len, videopage.body);
  123. F64 videotime = th_granule_time(td,ogg_page_granulepos(&videopage));
  124. if (videotime > 0)
  125. {
  126. S32 hundredths=(int)(videotime*100-(long)videotime*100);
  127. S32 seconds=(long)videotime%60;
  128. Platform::outputDebugString("Encoding time %g %02i.%02i", videotime, seconds, hundredths);
  129. }
  130. }
  131. mSemaphore.release();
  132. }
  133. bool process(bool ending)
  134. {
  135. if (!getStatus())
  136. return false;
  137. //Try getting a bitmap for encoding
  138. GBitmap* bitmap = NULL;
  139. if (mFrameBitmapList.tryPopFront(bitmap))
  140. {
  141. encodeFrame(bitmap, false);
  142. }
  143. //Delete previous bitmap
  144. if (!ending && bitmap)
  145. {
  146. if (mLastFrame)
  147. pushProcessedBitmap(mLastFrame);
  148. mLastFrame = bitmap;
  149. }
  150. //If we're stopping encoding, but didn't have a frame, re-encode the last frame
  151. if (ending && !bitmap && mLastFrame)
  152. {
  153. encodeFrame(mLastFrame, true);
  154. pushProcessedBitmap(mLastFrame);
  155. mLastFrame = NULL;
  156. }
  157. // We'll live while we have a last frame
  158. return (mLastFrame != NULL);
  159. }
  160. public:
  161. VideoEncoderTheora() :
  162. mCurrentFrame(0), td(NULL), mLastFrame(NULL)
  163. {
  164. dMemset(&to, 0, sizeof(to));
  165. dMemset(&ti, 0, sizeof(ti));
  166. dMemset(&tc, 0, sizeof(tc));
  167. dMemset(&mBuffer, 0, sizeof(mBuffer));
  168. setStatus(false);
  169. }
  170. virtual void run( void* arg )
  171. {
  172. _setName( "TheoraEncoderThread" );
  173. while (!checkForStop())
  174. process(false);
  175. // Encode all pending frames and close the last one
  176. while (process(true));
  177. }
  178. /// Begins accepting frames for encoding
  179. bool begin()
  180. {
  181. mPath += ".ogv";
  182. mCurrentFrame = 0;
  183. //Try opening the file for writing
  184. if ( !mFile.open( mPath, Torque::FS::File::Write ) )
  185. {
  186. Platform::outputDebugString( "VideoEncoderTheora::begin() - Failed to open output file '%s'!", mPath.c_str() );
  187. return setStatus(false);
  188. }
  189. ogg_stream_init(&to, Platform::getRandom() * double(S32_MAX));
  190. ogg_packet op;
  191. th_info_init(&ti);
  192. ti.frame_width = mResolution.x;
  193. ti.frame_height = mResolution.y;
  194. ti.pic_width = mResolution.x;
  195. ti.pic_height = mResolution.y;
  196. ti.pic_x = 0;
  197. ti.pic_y = 0;
  198. ti.fps_numerator = (int)(mFramerate * 1000.0f);
  199. ti.fps_denominator = 1000;
  200. ti.aspect_numerator = 0;
  201. ti.aspect_denominator = 0;
  202. ti.colorspace = TH_CS_UNSPECIFIED;
  203. ti.target_bitrate = 0;
  204. ti.quality = 63;
  205. ti.pixel_fmt = TH_PF_420;
  206. td = th_encode_alloc(&ti);
  207. if (td == NULL)
  208. {
  209. Platform::outputDebugString("VideoEncoderTheora::begin() - Theora initialization error.");
  210. return setStatus(false);
  211. }
  212. th_info_clear(&ti);
  213. // This is needed for youtube compatibility
  214. S32 vp3_compatible = 1;
  215. th_encode_ctl(td, TH_ENCCTL_SET_VP3_COMPATIBLE, &vp3_compatible, sizeof(vp3_compatible));
  216. // Set the encoder to max speed
  217. S32 speed_max;
  218. S32 ret;
  219. ret = th_encode_ctl(td, TH_ENCCTL_GET_SPLEVEL_MAX, &speed_max, sizeof(speed_max));
  220. if(ret<0){
  221. Platform::outputDebugString("VideoEncoderTheora::begin() - could not determine maximum speed level.");
  222. speed_max = 0;
  223. }
  224. ret = th_encode_ctl(td, TH_ENCCTL_SET_SPLEVEL, &speed_max, sizeof(speed_max));
  225. // write the bitstream header packets with proper page interleave
  226. th_comment_init(&tc);
  227. // first packet will get its own page automatically
  228. if(th_encode_flushheader(td,&tc,&op) <= 0)
  229. {
  230. Platform::outputDebugString("VideoEncoderTheora::begin() - Internal Theora library error.");
  231. return setStatus(false);
  232. }
  233. ogg_page og;
  234. ogg_stream_packetin(&to,&op);
  235. if(ogg_stream_pageout(&to,&og) != 1)
  236. {
  237. Platform::outputDebugString("VideoEncoderTheora::begin() - Internal Ogg library error.");
  238. return setStatus(false);
  239. }
  240. mFile.write(og.header_len, og.header);
  241. mFile.write(og.body_len, og.body);
  242. // create the remaining theora headers
  243. while((ret = th_encode_flushheader(td,&tc,&op)) != 0)
  244. {
  245. if(ret < 0)
  246. {
  247. Platform::outputDebugString("VideoEncoderTheora::begin() - Internal Theora library error.");
  248. return setStatus(false);
  249. }
  250. ogg_stream_packetin(&to,&op);
  251. }
  252. // Flush the rest of our headers. This ensures
  253. // the actual data in each stream will start
  254. // on a new page, as per spec.
  255. while((ret = ogg_stream_flush(&to,&og)) != 0)
  256. {
  257. if(ret < 0)
  258. {
  259. Platform::outputDebugString("VideoEncoderTheora::begin() - Internal Ogg library error.");
  260. return setStatus(false);
  261. }
  262. mFile.write(og.header_len, og.header);
  263. mFile.write(og.body_len, og.body);
  264. }
  265. //Initialize the YUV buffer
  266. S32 decimation[] = {0,1,1};
  267. for (U32 i=0; i<3; i++)
  268. {
  269. mBuffer[i].width = mResolution.x >> decimation[i];
  270. mBuffer[i].height = mResolution.y >> decimation[i];
  271. mBuffer[i].stride = mBuffer[i].width * sizeof(U8);
  272. mBuffer[i].data = new U8[mBuffer[i].width*mBuffer[i].height*sizeof(U8)];
  273. }
  274. //Initialize the YUV coefficient lookup tables
  275. initLookupTables();
  276. setStatus(true);
  277. #ifndef THEORA_ENCODER_SINGLE_THREAD
  278. start();
  279. #endif
  280. return getStatus();
  281. }
  282. /// Pushes a new frame into the video stream
  283. bool pushFrame( GBitmap * bitmap )
  284. {
  285. // Push the bitmap into the frame list
  286. mFrameBitmapList.pushBack( bitmap );
  287. mSemaphore.acquire();
  288. #ifdef THEORA_ENCODER_SINGLE_THREAD
  289. process(false);
  290. #endif
  291. return getStatus();
  292. }
  293. /// Finishes the encoding and closes the video
  294. bool end()
  295. {
  296. //Let's wait the thread stop doing whatever it needs to do
  297. stop();
  298. join();
  299. #ifdef THEORA_ENCODER_SINGLE_THREAD
  300. while (process(true));
  301. #endif
  302. th_encode_free(td);
  303. ogg_stream_clear(&to);
  304. th_comment_clear(&tc);
  305. mFile.close();
  306. return true;
  307. }
  308. void setResolution( Point2I* resolution )
  309. {
  310. /* Theora has a divisible-by-sixteen restriction for the encoded frame size */
  311. /* scale the picture size up to the nearest /16 and calculate offsets */
  312. resolution->x = (resolution->x) + 15 & ~0xF;
  313. resolution->y = (resolution->y) + 15 & ~0xF;
  314. mResolution = *resolution;
  315. }
  316. /// Converts the bitmap to YUV420 and copies it into our internal buffer
  317. void copyBitmapToYUV420( GBitmap* bitmap )
  318. {
  319. PROFILE_SCOPE(copyBitmapToYUV420);
  320. // Convert luma
  321. const U8* rgb = bitmap->getBits();
  322. // Chroma planes are half width and half height
  323. U32 w = mResolution.x / 2;
  324. U32 h = mResolution.y / 2;
  325. // We'll update two luminance rows at once
  326. U8* yuv_y0 = mBuffer[0].data;
  327. U8* yuv_y1 = mBuffer[0].data + mBuffer[0].stride;
  328. // Get pointers to chroma planes
  329. U8* yuv_u = mBuffer[1].data;
  330. U8* yuv_v = mBuffer[2].data;
  331. // We'll also need to read two RGB rows at once
  332. U32 rgbStride = mResolution.x * bitmap->getBytesPerPixel();
  333. const U8* row0 = rgb;
  334. const U8* row1 = row0 + rgbStride;
  335. for(U32 y = 0; y < h; y++)
  336. {
  337. for(U32 x = 0; x < w; x++)
  338. {
  339. // Fetch two RGB samples from each RGB row (for downsampling the chroma)
  340. U8 r0 = *row0++;
  341. U8 g0 = *row0++;
  342. U8 b0 = *row0++;
  343. U8 r1 = *row0++;
  344. U8 g1 = *row0++;
  345. U8 b1 = *row0++;
  346. U8 r2 = *row1++;
  347. U8 g2 = *row1++;
  348. U8 b2 = *row1++;
  349. U8 r3 = *row1++;
  350. U8 g3 = *row1++;
  351. U8 b3 = *row1++;
  352. // Convert the four RGB samples into four luminance samples
  353. *yuv_y0 = ( (sYRGB[r0][0] + sYRGB[g0][1] + sYRGB[b0][2]) >> 8);
  354. yuv_y0++;
  355. *yuv_y0 = ( (sYRGB[r1][0] + sYRGB[g1][1] + sYRGB[b1][2]) >> 8);
  356. yuv_y0++;
  357. *yuv_y1 = ( (sYRGB[r2][0] + sYRGB[g2][1] + sYRGB[b2][2]) >> 8);
  358. yuv_y1++;
  359. *yuv_y1 = ( (sYRGB[r3][0] + sYRGB[g3][1] + sYRGB[b3][2]) >> 8);
  360. yuv_y1++;
  361. // Downsample the four RGB samples
  362. U8 r = (r0 + r1 + r2 + r3) >> 2;
  363. U8 g = (g0 + g1 + g2 + g3) >> 2;
  364. U8 b = (b0 + b1 + b2 + b3) >> 2;
  365. // Convert downsampled RGB into chroma
  366. *yuv_u = ( (sURGB[r][0] + sURGB[g][1] + sURGB[b][2]) >> 8);
  367. *yuv_v = ( (sVRGB[r][0] + sVRGB[g][1] + sVRGB[b][2]) >> 8);
  368. yuv_u++;
  369. yuv_v++;
  370. }
  371. //Next RGB rows
  372. row0 += rgbStride;
  373. row1 += rgbStride;
  374. //Next luminance rows
  375. yuv_y0 += mBuffer[0].stride;
  376. yuv_y1 += mBuffer[0].stride;
  377. }
  378. }
  379. };
  380. REGISTER_VIDEO_ENCODER(VideoEncoderTheora, THEORA)
  381. #endif