@@ -334,10 +334,6 @@ size_t VideoProperties::getBitRate() const
334
334
if (!_codecContext->width || !_codecContext->height )
335
335
throw std::runtime_error (" cannot compute bit rate: invalid frame size" );
336
336
337
- // Needed to get the gop size
338
- if (getGopSize () == 0 )
339
- throw std::runtime_error (" cannot compute bit rate: need to get info from the first gop (see eAnalyseLevelFirstGop)" );
340
-
341
337
LOG_WARN (" The bitrate of the stream '" << _streamIndex << " ' of file '" << _formatContext->filename << " ' is unknown." )
342
338
LOG_INFO (" Decode the first GOP to compute the bitrate." )
343
339
@@ -350,8 +346,10 @@ size_t VideoProperties::getBitRate() const
350
346
avcodec_open2 (_codecContext, _codec, NULL );
351
347
352
348
int gotFrame = 0 ;
353
- size_t count = 0 ;
349
+ size_t nbDecodedFrames = 0 ;
354
350
int gopFramesSize = 0 ;
351
+ int positionOfFirstKeyFrame = -1 ;
352
+ int positionOfLastKeyFrame = -1 ;
355
353
356
354
while (!av_read_frame (const_cast <AVFormatContext*>(_formatContext), &pkt))
357
355
{
@@ -360,20 +358,35 @@ size_t VideoProperties::getBitRate() const
360
358
avcodec_decode_video2 (_codecContext, &frame.getAVFrame (), &gotFrame, &pkt);
361
359
if (gotFrame)
362
360
{
361
+ // check distance between key frames
362
+ AVFrame& avFrame = frame.getAVFrame ();
363
+ if (avFrame.pict_type == AV_PICTURE_TYPE_I)
364
+ {
365
+ if (positionOfFirstKeyFrame == -1 )
366
+ positionOfFirstKeyFrame = nbDecodedFrames;
367
+ else
368
+ positionOfLastKeyFrame = nbDecodedFrames;
369
+ }
370
+ ++nbDecodedFrames;
371
+
372
+ // added size of all frames of the same gop
373
+ if (positionOfLastKeyFrame == -1 )
374
+ {
363
375
#if LIBAVUTIL_VERSION_INT >= AV_VERSION_INT(54, 7, 100)
364
- gopFramesSize += frame.getEncodedSize ();
376
+ gopFramesSize += frame.getEncodedSize ();
365
377
#else
366
- gopFramesSize += pkt.size ;
378
+ gopFramesSize += pkt.size ;
367
379
#endif
368
- ++count;
380
+ }
369
381
}
370
382
}
371
383
av_free_packet (&pkt);
372
- if (getGopSize () == count )
384
+ if (positionOfFirstKeyFrame != - 1 && positionOfLastKeyFrame != - 1 )
373
385
break ;
374
386
}
375
387
376
- return (gopFramesSize / getGopSize ()) * 8 * getFps ();
388
+ const size_t gopSize = positionOfLastKeyFrame - positionOfFirstKeyFrame;
389
+ return (gopFramesSize / gopSize) * 8 * getFps ();
377
390
}
378
391
379
392
size_t VideoProperties::getMaxBitRate () const
0 commit comments