Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

811 lines
24 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. //----------------------------------------------------------------------------------------
  4. #define WIN32_LEAN_AND_MEAN
  5. #include "webm_video.h"
  6. #include "webm_recorder.h"
  7. #include "filesystem.h"
  8. #ifdef _WIN32
  9. #include "windows.h"
  10. #endif
  11. // Bitrate table for various resolutions, used to compute estimated size of files as well
  12. // as to set the WebM codec.
  13. struct WebMEncodingDataRateInfo_t
  14. {
  15. int m_XResolution;
  16. int m_YResolution;
  17. float m_MinDataRate; // in KBits / second
  18. float m_MaxDataRate; // in KBits / second
  19. float m_MinAudioDataRate; // in KBits / second
  20. float m_MaxAudioDataRate; // in KBits / second
  21. };
  22. // Quality is passed into us as a number between 0 and 100, we use that to scale between the min and max bitrates.
  23. static WebMEncodingDataRateInfo_t s_WebMEncodeRates[] =
  24. {
  25. { 320, 240, 1000, 1000, 128, 128},
  26. { 640, 960, 2000, 2000, 128, 128},
  27. { 960, 640, 2000, 2000, 128, 128},
  28. { 720, 480, 2500, 2500, 128, 128},
  29. {1280, 720, 5000, 5000, 384, 384},
  30. {1920, 1080, 8000, 8000, 384, 384},
  31. };
  32. // ===========================================================================
  33. // CWebMVideoRecorder class - implements IVideoRecorder interface for
  34. // WebM and buffers commands to the actual encoder object
  35. // ===========================================================================
  36. CWebMVideoRecorder::CWebMVideoRecorder() :
  37. m_LastResult( VideoResult::SUCCESS ),
  38. m_bHasAudio( false ),
  39. m_bMovieFinished( false ),
  40. m_SrcImageYV12Buffer( NULL ),
  41. m_nFramesAdded( 0 ),
  42. m_nAudioFramesAdded( 0 ),
  43. m_nSamplesAdded( 0 ),
  44. m_audioChannels( 2 ),
  45. m_audioSampleRate( 44100 ),
  46. m_audioBitDepth( 16 ),
  47. m_audioSampleGroupSize( 0 )
  48. {
  49. #ifdef LOG_ENCODER_OPERATIONS
  50. Msg("CWebMVideoRecorder::CWebMVideoRecorder() \n");
  51. #endif
  52. }
  53. CWebMVideoRecorder::~CWebMVideoRecorder()
  54. {
  55. #ifdef LOG_ENCODER_OPERATIONS
  56. Msg("CWebMVideoRecorder::~CWebMVideoRecorder() \n");
  57. #endif
  58. if (m_SrcImageYV12Buffer)
  59. {
  60. vpx_img_free(m_SrcImageYV12Buffer);
  61. m_SrcImageYV12Buffer = NULL;
  62. }
  63. }
  64. // All webm movies use 1000000 as a scale
  65. #define WEBM_TIMECODE_SCALE 1000000
  66. // All webm movies using 128kbps as audio bitrate
  67. #define WEBM_AUDIO_BITRATE 128000
  68. bool CWebMVideoRecorder::CreateNewMovieFile( const char *pFilename, bool hasAudio )
  69. {
  70. #ifdef LOG_ENCODER_OPERATIONS
  71. Msg("CWebMVideoRecorder::CreateNewMovieFile() \n");
  72. #endif
  73. SetResult( VideoResult::BAD_INPUT_PARAMETERS );
  74. AssertExitF( IS_NOT_EMPTY( pFilename ) );
  75. SetResult( VideoResult::OPERATION_ALREADY_PERFORMED );
  76. // crete the webm file
  77. if (!m_mkvWriter.Open(pFilename))
  78. {
  79. SetResult( VideoResult::OPERATION_ALREADY_PERFORMED );
  80. return false;
  81. }
  82. // init the webm file and write out the header
  83. m_mkvMuxerSegment.Init(&m_mkvWriter);
  84. m_mkvMuxerSegment.set_mode(mkvmuxer::Segment::kFile);
  85. m_mkvMuxerSegment.OutputCues(true);
  86. mkvmuxer::SegmentInfo* const mkvInfo = m_mkvMuxerSegment.GetSegmentInfo();
  87. mkvInfo->set_timecode_scale(WEBM_TIMECODE_SCALE);
  88. // get the app name
  89. char appname[ 256 ];
  90. KeyValues *modinfo = new KeyValues( "ModInfo" );
  91. if ( modinfo->LoadFromFile( g_pFullFileSystem, "gameinfo.txt" ) )
  92. Q_strncpy( appname, modinfo->GetString( "game" ), sizeof( appname ) );
  93. else
  94. Q_strncpy( appname, "Source1 Game", sizeof( appname ) );
  95. modinfo->deleteThis();
  96. modinfo = NULL;
  97. mkvInfo->set_writing_app(appname);
  98. m_bHasAudio = hasAudio;
  99. SetResult( VideoResult::SUCCESS );
  100. return true;
  101. }
  102. bool CWebMVideoRecorder::SetMovieVideoParameters( VideoEncodeCodec_t theCodec, int videoQuality, int movieFrameWidth, int movieFrameHeight, VideoFrameRate_t movieFPS, VideoEncodeGamma_t gamma )
  103. {
  104. #ifdef LOG_ENCODER_OPERATIONS
  105. Msg("CWebMVideoRecorder::SetMovieVideoParameters()\n");
  106. #endif
  107. SetResult( VideoResult::BAD_INPUT_PARAMETERS );
  108. AssertExitF( IS_IN_RANGECOUNT( theCodec, VideoEncodeCodec::DEFAULT_CODEC, VideoEncodeCodec::CODEC_COUNT ) );
  109. AssertExitF( IS_IN_RANGE( videoQuality, VideoEncodeQuality::MIN_QUALITY, VideoEncodeQuality::MAX_QUALITY ) );
  110. AssertExitF( IS_IN_RANGE( movieFrameWidth, cMinVideoFrameWidth, cMaxVideoFrameWidth ) && IS_IN_RANGE( movieFrameHeight, cMinVideoFrameHeight, cMaxVideoFrameHeight ) );
  111. AssertExitF( IS_IN_RANGE( movieFPS.GetFPS(), cMinFPS, cMaxFPS ) );
  112. AssertExitF( IS_IN_RANGECOUNT( gamma, VideoEncodeGamma::NO_GAMMA_ADJUST, VideoEncodeGamma::GAMMA_COUNT ) );
  113. SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
  114. // Get the defaults for the WebM encoder
  115. if (vpx_codec_enc_config_default(vpx_codec_vp8_cx(), &m_vpxConfig, 0) != VPX_CODEC_OK)
  116. {
  117. SetResult( VideoResult::INITIALIZATION_ERROR_OCCURED );
  118. return false;
  119. }
  120. m_MovieFrameWidth = movieFrameWidth;
  121. m_MovieFrameHeight = movieFrameHeight;
  122. m_MovieGamma = gamma;
  123. m_vpxConfig.g_h = movieFrameHeight;
  124. m_vpxConfig.g_w = movieFrameWidth;
  125. // How many threads should we use? How about 1 per logical processor
  126. const CPUInformation *pi = GetCPUInformation();
  127. m_vpxConfig.g_threads = pi->m_nLogicalProcessors;
  128. // FPS
  129. m_vpxConfig.g_timebase.den = movieFPS.GetUnitsPerSecond();
  130. m_vpxConfig.g_timebase.num = movieFPS.GetUnitsPerFrame();
  131. m_MovieRecordFPS = movieFPS;
  132. m_DurationPerFrame = m_MovieRecordFPS.GetUnitsPerFrame();
  133. m_MovieTimeScale = m_MovieRecordFPS.GetUnitsPerSecond();
  134. // Compute how long each frame is, in nanoseconds
  135. m_FrameDuration = (unsigned long)(((double)m_DurationPerFrame*(double)1000000000)/(double)m_MovieTimeScale);
  136. // Set the bitrate for this size and level of quality
  137. m_vpxConfig.rc_target_bitrate = GetVideoDataRate(videoQuality, movieFrameWidth, movieFrameHeight);
  138. #ifdef LOG_ENCODER_OPERATIONS
  139. Msg( "Video Frame Rate = %f FPS\n %d time units per second\n %d time units per frame\n", m_MovieRecordFPS.GetFPS(), m_MovieRecordFPS.GetUnitsPerSecond(), m_MovieRecordFPS.GetUnitsPerFrame() );
  140. if ( m_MovieRecordFPS.IsNTSCRate() )
  141. Msg( " IS CONSIDERED NTSC RATE\n");
  142. Msg( "Using %d threads for WebM encoding\n", m_vpxConfig.g_threads);
  143. Msg( "MovieTimeScale is being set to %d\nDuration Per Frame is %d\n", m_MovieTimeScale, m_DurationPerFrame );
  144. Msg( "Time per frame in nanoseconds %d\n\n", m_FrameDuration);
  145. #endif
  146. // Init the codec
  147. if (vpx_codec_enc_init(&m_vpxContext, vpx_codec_vp8_cx(), &m_vpxConfig, 0) != VPX_CODEC_OK)
  148. {
  149. SetResult( VideoResult::INITIALIZATION_ERROR_OCCURED );
  150. return false;
  151. }
  152. // add the video track
  153. m_vid_track = m_mkvMuxerSegment.AddVideoTrack(static_cast<int>(m_vpxConfig.g_w),
  154. static_cast<int>(m_vpxConfig.g_h),
  155. 1);
  156. mkvmuxer::VideoTrack* const video =
  157. static_cast<mkvmuxer::VideoTrack*>(
  158. m_mkvMuxerSegment.GetTrackByNumber(m_vid_track));
  159. video->set_display_width(m_vpxConfig.g_w);
  160. video->set_display_height(m_vpxConfig.g_h);
  161. video->set_frame_rate(movieFPS.GetFPS());
  162. return true;
  163. }
  164. bool CWebMVideoRecorder::SetMovieSourceImageParameters( VideoEncodeSourceFormat_t srcImageFormat, int imgWidth, int imgHeight )
  165. {
  166. #ifdef LOG_ENCODER_OPERATIONS
  167. Msg("CWebMVideoRecorder::SetMovieSourceImageParameters()\n");
  168. #endif
  169. SetResult( VideoResult::BAD_INPUT_PARAMETERS );
  170. AssertExitF( IS_IN_RANGECOUNT( srcImageFormat, VideoEncodeSourceFormat::VIDEO_FORMAT_FIRST, VideoEncodeSourceFormat::VIDEO_FORMAT_COUNT ) );
  171. // WebM Recorder only supports BGRA_32BIT and BGR_24BIT
  172. AssertExitF( (srcImageFormat == VideoEncodeSourceFormat::BGRA_32BIT) ||
  173. (srcImageFormat == VideoEncodeSourceFormat::BGR_24BIT) );
  174. AssertExitF( IS_IN_RANGE( imgWidth, cMinVideoFrameWidth, cMaxVideoFrameWidth ) && IS_IN_RANGE( imgHeight, cMinVideoFrameHeight, cMaxVideoFrameHeight ) );
  175. SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
  176. m_SrcImageWidth = imgWidth;
  177. m_SrcImageHeight = imgHeight;
  178. m_SrcImageFormat = srcImageFormat;
  179. // Setup the buffers for encoding the frame. WebM requires a frame in YV12 format
  180. m_SrcImageYV12Buffer = vpx_img_alloc(NULL, VPX_IMG_FMT_YV12, m_SrcImageWidth, m_SrcImageHeight, 1);
  181. // Set Cues element attributes
  182. mkvmuxer::Cues* const cues = m_mkvMuxerSegment.GetCues();
  183. cues->set_output_block_number(1);
  184. m_mkvMuxerSegment.CuesTrack(m_vid_track);
  185. SetResult( VideoResult::SUCCESS );
  186. return true;
  187. }
  188. bool CWebMVideoRecorder::SetMovieSourceAudioParameters( AudioEncodeSourceFormat_t srcAudioFormat, int audioSampleRate, AudioEncodeOptions_t audioOptions, int audioSampleGroupSize )
  189. {
  190. #ifdef LOG_ENCODER_OPERATIONS
  191. Msg("CWebMVideoRecorder::SetMovieSourceAudioParameters()\n");
  192. #endif
  193. SetResult( VideoResult::ILLEGAL_OPERATION );
  194. AssertExitF( m_bHasAudio );
  195. SetResult( VideoResult::BAD_INPUT_PARAMETERS );
  196. AssertExitF( IS_IN_RANGECOUNT( srcAudioFormat, AudioEncodeSourceFormat::AUDIO_NONE, AudioEncodeSourceFormat::AUDIO_FORMAT_COUNT ) );
  197. AssertExitF( audioSampleRate == 0 || IS_IN_RANGE( audioSampleRate, cMinSampleRate, cMaxSampleRate ) );
  198. SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
  199. m_audioSampleRate = audioSampleRate;
  200. m_audioSampleGroupSize = audioSampleGroupSize;
  201. // now setup the audio
  202. vorbis_info_init(&m_vi);
  203. // We are always using 128kbps for the audio
  204. int ret=vorbis_encode_init(&m_vi,m_audioChannels,m_audioSampleRate,-1,WEBM_AUDIO_BITRATE,-1);
  205. if (ret)
  206. {
  207. SetResult( VideoResult::BAD_INPUT_PARAMETERS );
  208. return false;
  209. }
  210. /* set up the analysis state and auxiliary encoding storage */
  211. vorbis_comment_init(&m_vc);
  212. // get the app name
  213. char appname[ 256 ];
  214. KeyValues *modinfo = new KeyValues( "ModInfo" );
  215. if ( modinfo->LoadFromFile( g_pFullFileSystem, "gameinfo.txt" ) )
  216. Q_strncpy( appname, modinfo->GetString( "game" ), sizeof( appname ) );
  217. else
  218. Q_strncpy( appname, "Source1 Game", sizeof( appname ) );
  219. modinfo->deleteThis();
  220. modinfo = NULL;
  221. vorbis_comment_add_tag(&m_vc,"ENCODER",appname);
  222. vorbis_analysis_init(&m_vd,&m_vi);
  223. vorbis_block_init(&m_vd,&m_vb);
  224. // setup the audio track
  225. m_aud_track = m_mkvMuxerSegment.AddAudioTrack(static_cast<int>(m_audioSampleRate),
  226. static_cast<int>(m_audioChannels),
  227. 0);
  228. if (!m_aud_track)
  229. {
  230. printf("\n Could not add audio track.\n");
  231. return false;
  232. }
  233. mkvmuxer::AudioTrack* const audio =
  234. static_cast<mkvmuxer::AudioTrack*>(
  235. m_mkvMuxerSegment.GetTrackByNumber(m_aud_track));
  236. if (!audio)
  237. {
  238. SetResult( VideoResult::BAD_INPUT_PARAMETERS );
  239. return false;
  240. }
  241. /* Vorbis streams begin with three headers; the initial header (with
  242. most of the codec setup parameters) which is mandated by the Ogg
  243. bitstream spec. The second header holds any comment fields. The
  244. third header holds the bitstream codebook. We merely need to
  245. make the headers, then pass them to libvorbis one at a time;
  246. libvorbis handles the additional Ogg bitstream constraints */
  247. {
  248. ogg_packet ident_packet;
  249. ogg_packet comments_packet;
  250. ogg_packet setup_packet;
  251. int iHeaderLength;
  252. uint8 *privateHeader=NULL;
  253. uint8 *pbPrivateHeader=NULL;
  254. vorbis_analysis_headerout(&m_vd,&m_vc,&ident_packet,&comments_packet,&setup_packet);
  255. iHeaderLength = 3 + ident_packet.bytes + comments_packet.bytes + setup_packet.bytes;
  256. privateHeader = new uint8[iHeaderLength];
  257. pbPrivateHeader = privateHeader;
  258. *pbPrivateHeader++ = 2; // number of headers - 1
  259. *pbPrivateHeader++ = (uint8)ident_packet.bytes;
  260. *pbPrivateHeader++ = (uint8)comments_packet.bytes;
  261. memcpy(pbPrivateHeader, ident_packet.packet, ident_packet.bytes);
  262. pbPrivateHeader+= ident_packet.bytes;
  263. memcpy(pbPrivateHeader, comments_packet.packet, comments_packet.bytes);
  264. pbPrivateHeader+= comments_packet.bytes;
  265. memcpy(pbPrivateHeader, setup_packet.packet, setup_packet.bytes);
  266. pbPrivateHeader+= setup_packet.bytes;
  267. audio->SetCodecPrivate(privateHeader,iHeaderLength);
  268. delete [] privateHeader;
  269. }
  270. SetResult( VideoResult::SUCCESS );
  271. return true;
  272. }
  273. bool CWebMVideoRecorder::IsReadyToRecord()
  274. {
  275. #ifdef LOG_ENCODER_OPERATIONS
  276. Msg("CWebMVideoRecorder::IsReadyToRecord()\n");
  277. #endif
  278. return ( m_SrcImageYV12Buffer != NULL && !m_bMovieFinished);
  279. }
  280. VideoResult_t CWebMVideoRecorder::GetLastResult()
  281. {
  282. #ifdef LOG_ENCODER_OPERATIONS
  283. Msg("CWebMVideoRecorder::GetLastResult()\n");
  284. #endif
  285. return m_LastResult;
  286. }
  287. void CWebMVideoRecorder::SetResult( VideoResult_t resultCode )
  288. {
  289. m_LastResult = resultCode;
  290. }
  291. void CWebMVideoRecorder::ConvertBGRAToYV12( void *pFrameBuffer, int nStrideAdjustBytes, vpx_image_t *m_SrcImageYV12Buffer, bool fIncludesAlpha )
  292. {
  293. int iSrcBytesPerPixel;
  294. // Handle 32-bit with alpha and 24-bit
  295. if (fIncludesAlpha)
  296. iSrcBytesPerPixel = 4;
  297. else
  298. iSrcBytesPerPixel = 3;
  299. int srcStride = m_SrcImageWidth * iSrcBytesPerPixel + nStrideAdjustBytes;
  300. int iX,iY;
  301. byte *pSrc;
  302. byte *pDstY,*pDstU,*pDstV;
  303. byte r,g,b,a;
  304. byte y,u,v;
  305. // This isn't fast or good, but it works and that's good enough for a first pass
  306. pSrc = (byte *)pFrameBuffer;
  307. // YV12 has a complete frame of Y, followed by half sized U and V
  308. pDstY = m_SrcImageYV12Buffer->planes[0];
  309. pDstU = m_SrcImageYV12Buffer->planes[1];
  310. pDstV = m_SrcImageYV12Buffer->planes[2];
  311. for (iY=0;iY<m_MovieFrameHeight;iY++)
  312. {
  313. for(iX=0;iX<m_MovieFrameWidth;iX++)
  314. {
  315. b = pSrc[iSrcBytesPerPixel*iX+0];
  316. g = pSrc[iSrcBytesPerPixel*iX+1];
  317. r = pSrc[iSrcBytesPerPixel*iX+2];
  318. if (fIncludesAlpha)
  319. a = pSrc[iSrcBytesPerPixel*iX+3];
  320. y = (byte)((66*r + 129*g + 25*b + 128) >> 8) + 16;
  321. pDstY[iX] = y;
  322. if ((iY%2 == 0) && (iX%2 == 0))
  323. {
  324. u = (byte)((-38*r - 74*g + 112*b + 128) >> 8) + 128;
  325. v = (byte)((112*r - 94*g - 18*b + 128) >> 8) + 128;
  326. pDstU[iX/2] = u;
  327. pDstV[iX/2] = v;
  328. }
  329. }
  330. // next row, using strides
  331. pDstY += m_SrcImageYV12Buffer->stride[0];
  332. if ((iY%2) == 0)
  333. {
  334. pDstU += m_SrcImageYV12Buffer->stride[1];
  335. pDstV += m_SrcImageYV12Buffer->stride[2];
  336. }
  337. pSrc += srcStride;
  338. }
  339. }
  340. bool CWebMVideoRecorder::AppendVideoFrame( void *pFrameBuffer, int nStrideAdjustBytes )
  341. {
  342. uint64 time_ns;
  343. #ifdef LOG_ENCODER_OPERATIONS
  344. Msg("CWebMVideoRecorder::AppendVideoFrame()\n");
  345. #endif
  346. // $$$DEBUG Dump the Frame $$$DEBUG
  347. // If you are trying to debug how the webm libraries work it's very difficult to use the full TF2 replay system as a testbed
  348. // so this section of code here and in the AppendAudioSamples writes out the data TF2 would send to the video recorder to
  349. // plain files on the disc. You can then use those files with an extracted framework to work with the webm libraries
  350. #ifdef NEVER
  351. {
  352. FILE *fp=NULL;
  353. char rgch[256];
  354. int i,j;
  355. byte *pByte;
  356. sprintf(rgch, "./frames/vid_%d", m_nFramesAdded);
  357. fp = fopen(rgch, "wb");
  358. pByte = (byte *)pFrameBuffer;
  359. for (i=0;i<m_MovieFrameHeight;i++)
  360. {
  361. fwrite(pByte, 4, m_MovieFrameWidth, fp);
  362. pByte += (m_MovieFrameWidth*4 + nStrideAdjustBytes);
  363. }
  364. fclose(fp);
  365. }
  366. #endif
  367. SetResult( VideoResult::BAD_INPUT_PARAMETERS );
  368. AssertExitF( pFrameBuffer != nullptr );
  369. SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
  370. AssertExitF( IsReadyToRecord() );
  371. // Convert the frame in pFrameBuffer into YV12 and add it to the stream
  372. // only convert BGRA_32BIT and BGR_24BIT right now
  373. switch(m_SrcImageFormat)
  374. {
  375. case VideoEncodeSourceFormat::BGR_24BIT:
  376. ConvertBGRAToYV12(pFrameBuffer, nStrideAdjustBytes, m_SrcImageYV12Buffer, false);
  377. break;
  378. case VideoEncodeSourceFormat::BGRA_32BIT:
  379. ConvertBGRAToYV12(pFrameBuffer, nStrideAdjustBytes, m_SrcImageYV12Buffer, true);
  380. break;
  381. default:
  382. SetResult( VideoResult::BAD_INPUT_PARAMETERS );
  383. return false;
  384. }
  385. // Compress it with the webm codec
  386. time_ns = ((uint64)m_FrameDuration*(uint64)(m_nFramesAdded+1));
  387. vpx_codec_err_t vpxError = vpx_codec_encode(&m_vpxContext, m_SrcImageYV12Buffer, time_ns, m_FrameDuration, 0, 0);
  388. if (vpxError != VPX_CODEC_OK)
  389. {
  390. SetResult( VideoResult::VIDEO_ERROR_OCCURED );
  391. return false;
  392. }
  393. // Add this frame to the stream
  394. vpx_codec_iter_t vpxIter = NULL;
  395. const vpx_codec_cx_pkt_t *vpxPacket;
  396. bool bKeyframe=false;
  397. while ( ( vpxPacket = vpx_codec_get_cx_data(&m_vpxContext, &vpxIter)) != NULL )
  398. {
  399. if (vpxPacket->kind == VPX_CODEC_CX_FRAME_PKT)
  400. {
  401. // Extract if this is a keyframe from the first packet of data for each frame
  402. bKeyframe = vpxPacket->data.frame.flags & VPX_FRAME_IS_KEY;
  403. m_mkvMuxerSegment.AddFrame((const uint8 *)vpxPacket->data.frame.buf, vpxPacket->data.frame.sz, m_vid_track,
  404. time_ns, bKeyframe);
  405. }
  406. }
  407. m_nFramesAdded++;
  408. SetResult( VideoResult::SUCCESS );
  409. return true;
  410. }
  411. bool CWebMVideoRecorder::FlushAudioSamples()
  412. {
  413. ogg_packet op;
  414. // See if there are any samples available
  415. while (vorbis_analysis_blockout(&m_vd, &m_vb) == 1)
  416. {
  417. int status_analysis = vorbis_analysis(&m_vb, NULL);
  418. if (status_analysis)
  419. {
  420. return false;
  421. }
  422. status_analysis = vorbis_bitrate_addblock(&m_vb);
  423. if (status_analysis)
  424. {
  425. return false;
  426. }
  427. while ((status_analysis = vorbis_bitrate_flushpacket(&m_vd, &op)) > 0)
  428. {
  429. // Add this packet to the webm stream
  430. uint64 time_ns = ((uint64)m_FrameDuration*(uint64)(m_nFramesAdded+1));
  431. if (!m_mkvMuxerSegment.AddFrame(op.packet,
  432. op.bytes,
  433. m_aud_track,
  434. time_ns,
  435. true))
  436. {
  437. return false;
  438. }
  439. }
  440. }
  441. return true;
  442. }
  443. bool CWebMVideoRecorder::AppendAudioSamples( void *pSampleBuffer, size_t sampleSize )
  444. {
  445. #ifdef LOG_ENCODER_OPERATIONS
  446. Msg("CWebMVideoRecorder::AppendAudioSamples()\n");
  447. #endif
  448. SetResult( VideoResult::ILLEGAL_OPERATION );
  449. AssertExitF( m_bHasAudio );
  450. SetResult( VideoResult::BAD_INPUT_PARAMETERS );
  451. AssertExitF( pSampleBuffer != nullptr );
  452. SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
  453. AssertExitF( IsReadyToRecord() );
  454. // $$$DEBUG Dump the Audio $$$DEBUG
  455. // The audio version of the dumping of video/audio data to files for debugging
  456. // You may need to change the path to put these files where you want them.
  457. #ifdef NEVER
  458. {
  459. FILE *fp=NULL;
  460. char rgch[256];
  461. int i,j;
  462. byte *pByte;
  463. static int i_AudSample_batch=0;
  464. static int i_AudSample_frame=-1;
  465. if (m_nFramesAdded != i_AudSample_frame)
  466. i_AudSample_batch = 0;
  467. i_AudSample_frame = m_nFramesAdded;
  468. sprintf(rgch, "./frames/aud_%d_%d", i_AudSample_frame, i_AudSample_batch);
  469. fp = fopen(rgch, "wb");
  470. // Size
  471. fwrite(&sampleSize, sizeof(sampleSize), 1, fp);
  472. // Data
  473. pByte = (byte *)pSampleBuffer;
  474. fwrite(pByte, sampleSize, 1, fp);
  475. fclose(fp);
  476. i_AudSample_batch++;
  477. }
  478. #endif
  479. int num_blocks = sampleSize / ((m_audioBitDepth/8)*m_audioChannels);
  480. float **buffer=vorbis_analysis_buffer(&m_vd,num_blocks);
  481. // Deinterleave input samples, convert them to float, and store them in
  482. // buffer
  483. const int16* pPCMsamples = (int16*)pSampleBuffer;
  484. for (int i = 0; i < num_blocks; ++i)
  485. {
  486. for (int c = 0; c < m_audioChannels; ++c)
  487. {
  488. buffer[c][i] = pPCMsamples[i * m_audioChannels + c] / 32768.f;
  489. }
  490. }
  491. vorbis_analysis_wrote(&m_vd, num_blocks);
  492. FlushAudioSamples();
  493. return true;
  494. }
  495. int CWebMVideoRecorder::GetFrameCount()
  496. {
  497. #ifdef LOG_ENCODER_OPERATIONS
  498. Msg("CWebMVideoRecorder::GetFrameCount()\n");
  499. #endif
  500. return m_nFramesAdded;
  501. }
  502. int CWebMVideoRecorder::GetSampleCount()
  503. {
  504. #ifdef LOG_ENCODER_OPERATIONS
  505. Msg("CWebMVideoRecorder::GetSampleCount()\n");
  506. #endif
  507. // return ( m_pEncoder == nullptr ) ? 0 : m_pEncoder->GetSampleCount();
  508. return true;
  509. }
  510. VideoFrameRate_t CWebMVideoRecorder::GetFPS()
  511. {
  512. #ifdef LOG_ENCODER_OPERATIONS
  513. Msg("CWebMVideoRecorder::GetFPS()\n");
  514. #endif
  515. return m_MovieRecordFPS;
  516. }
  517. int CWebMVideoRecorder::GetSampleRate()
  518. {
  519. #ifdef LOG_ENCODER_OPERATIONS
  520. Msg("CWebMVideoRecorder::GetSampleRate()\n");
  521. #endif
  522. // return ( m_pEncoder == nullptr ) ? 0 : m_pEncoder->GetSampleRate();
  523. return true;
  524. }
  525. bool CWebMVideoRecorder::AbortMovie()
  526. {
  527. #ifdef LOG_ENCODER_OPERATIONS
  528. Msg("CWebMVideoRecorder::AbortMovie()\n");
  529. #endif
  530. SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
  531. // AssertExitF( m_pEncoder != nullptr && !m_bMovieFinished );
  532. m_bMovieFinished = true;
  533. // return m_pEncoder->AbortMovie();
  534. return true;
  535. }
  536. bool CWebMVideoRecorder::FinishMovie( bool SaveMovieToDisk )
  537. {
  538. #ifdef LOG_ENCODER_OPERATIONS
  539. Msg("CWebMVideoRecorder::FinishMovie()\n");
  540. #endif
  541. // Have to finish out the compress with a NULL frame
  542. // Compress it with the webm codec
  543. m_nFramesAdded++;
  544. uint64 time_ns = ((uint64)m_FrameDuration*(uint64)(m_nFramesAdded+1));
  545. vpx_codec_err_t vpxError = vpx_codec_encode(&m_vpxContext, NULL, time_ns, m_FrameDuration, 0, 0);
  546. if (vpxError != VPX_CODEC_OK)
  547. {
  548. return false;
  549. }
  550. // Add this frame to the stream
  551. vpx_codec_iter_t vpxIter = NULL;
  552. const vpx_codec_cx_pkt_t *vpxPacket;
  553. while ( ( vpxPacket = vpx_codec_get_cx_data(&m_vpxContext, &vpxIter) ) != NULL )
  554. {
  555. if (vpxPacket->kind == VPX_CODEC_CX_FRAME_PKT)
  556. {
  557. uint64 time_ns;
  558. bool bKeyframe=false;
  559. // Extract if this is a keyframe from the first packet of data for each frame
  560. bKeyframe = vpxPacket->data.frame.flags & VPX_FRAME_IS_KEY;
  561. time_ns = ((uint64)m_FrameDuration*(uint64)m_nFramesAdded);
  562. m_mkvMuxerSegment.AddFrame((const uint8 *)vpxPacket->data.frame.buf, vpxPacket->data.frame.sz, m_vid_track, time_ns, bKeyframe);
  563. }
  564. }
  565. m_mkvMuxerSegment.Finalize();
  566. m_mkvWriter.Close();
  567. vorbis_dsp_clear(&m_vd);
  568. vorbis_block_clear(&m_vb);
  569. vorbis_info_clear(&m_vi);
  570. m_bMovieFinished = true;
  571. #ifdef LOG_ENCODER_OPERATIONS
  572. Msg("CWebMVideoRecorder::FinishMovie() movie encoded.\n");
  573. Msg("Total frames written: %d Time for movie in nanoseconds: %lu\n", m_nFramesAdded, ((unsigned long)m_nFramesAdded*m_FrameDuration));
  574. #endif
  575. SetResult( VideoResult::SUCCESS );
  576. return true;
  577. }
  578. bool CWebMVideoRecorder::EstimateMovieFileSize( size_t *pEstSize, int movieWidth, int movieHeight, VideoFrameRate_t movieFps, float movieDuration, VideoEncodeCodec_t theCodec, int videoQuality, AudioEncodeSourceFormat_t srcAudioFormat, int audioSampleRate )
  579. {
  580. #ifdef LOG_ENCODER_OPERATIONS
  581. Msg("CWebMVideoRecorder::EstimateMovieFileSize()\n");
  582. #endif
  583. float fVidRate;
  584. float fAudRate;
  585. float movieDurationInSeconds;
  586. fVidRate = GetVideoDataRate(videoQuality, movieWidth, movieHeight);
  587. fAudRate = GetAudioDataRate(videoQuality, movieWidth, movieHeight);
  588. movieDurationInSeconds = movieDuration;
  589. // data rates is in killobits/second so convert to bytes/second
  590. *pEstSize = (size_t)((fVidRate*1000*movieDurationInSeconds/8) + (fAudRate*1000*movieDuration*movieDurationInSeconds/8));
  591. SetResult( VideoResult::SUCCESS );
  592. return true;
  593. }
  594. float CWebMVideoRecorder::GetVideoDataRate( int quality, int width, int height )
  595. {
  596. #ifdef LOG_ENCODER_OPERATIONS
  597. Msg("CWebMVideoRecorder::GetDataRate()\n");
  598. #endif
  599. for(int i = 0; i< ARRAYSIZE( s_WebMEncodeRates ); i++ )
  600. {
  601. if (s_WebMEncodeRates[i].m_XResolution == width && s_WebMEncodeRates[i].m_YResolution == height)
  602. {
  603. return s_WebMEncodeRates[i].m_MinDataRate + (((s_WebMEncodeRates[i].m_MaxDataRate - s_WebMEncodeRates[i].m_MinDataRate)*(float)quality)/100.0);
  604. }
  605. }
  606. // Didn't find the resolution, odd
  607. Msg("Unable to find WebM resolution (%d, %d) at quality %d\n", width, height, quality);
  608. // Default to 2kb/s
  609. return 2000.0f;
  610. }
  611. float CWebMVideoRecorder::GetAudioDataRate( int quality, int width, int height )
  612. {
  613. #ifdef LOG_ENCODER_OPERATIONS
  614. Msg("CWebMVideoRecorder::GetDataRate()\n");
  615. #endif
  616. for(int i = 0; i< ARRAYSIZE( s_WebMEncodeRates ); i++ )
  617. {
  618. if (s_WebMEncodeRates[i].m_XResolution == width && s_WebMEncodeRates[i].m_YResolution == height)
  619. {
  620. return s_WebMEncodeRates[i].m_MinAudioDataRate + (((s_WebMEncodeRates[i].m_MaxAudioDataRate - s_WebMEncodeRates[i].m_MinAudioDataRate)*(float)quality)/100.0);
  621. }
  622. }
  623. // Didn't find the resolution, odd
  624. Msg("Unable to find WebM resolution (%d, %d) at quality %d\n", width, height, quality);
  625. // Default to 128kb/s for audio
  626. return 128.0f;
  627. }