+ int err;
+ again:
+ if ( ( err = av_read_frame( stream->ffmpeg_ic, stream->ffmpeg_pkt )) < 0 )
+ {
+ // XXX the following conditional is to handle avi files that
+ // use M$ 'packed b-frames' and occasionally have negative
+ // sizes for the null frames these require.
+ if ( err != AVERROR_NOMEM || stream->ffmpeg_pkt->size >= 0 )
+ // eof
+ return 0;
+ }
+ if ( stream->ffmpeg_pkt->size <= 0 )
+ {
+ // M$ "invalid and inefficient" packed b-frames require 'null frames'
+ // following them to preserve the timing (since the packing puts two
+ // or more frames in what looks like one avi frame). The contents and
+ // size of these null frames are ignored by the ff_h263_decode_frame
+ // as long as they're < 20 bytes. We need a positive size so we use
+ // one byte if we're given a zero or negative size. We don't know
+ // if the pkt data points anywhere reasonable so we just stick a
+ // byte of zero in our outbound buf.
+ buf->size = 1;
+ *buf->data = 0;
+ }
+ else
+ {
+ if ( stream->ffmpeg_pkt->size > buf->alloc )
+ {
+ // sometimes we get absurd sizes from ffmpeg
+ if ( stream->ffmpeg_pkt->size >= (1 << 25) )
+ {
+ hb_log( "ffmpeg_read: pkt too big: %d bytes", stream->ffmpeg_pkt->size );
+ av_free_packet( stream->ffmpeg_pkt );
+ return ffmpeg_read( stream, buf );
+ }
+ // need to expand buffer
+ hb_buffer_realloc( buf, stream->ffmpeg_pkt->size );
+ }
+ memcpy( buf->data, stream->ffmpeg_pkt->data, stream->ffmpeg_pkt->size );
+ buf->size = stream->ffmpeg_pkt->size;
+ }
+ buf->id = stream->ffmpeg_pkt->stream_index;
+ if ( buf->id == stream->ffmpeg_video_id )
+ {
+ if ( stream->need_keyframe )
+ {
+ // we've just done a seek (generally for scan or live preview) and
+ // want to start at a keyframe. Some ffmpeg codecs seek to a key
+ // frame but most don't. So we spin until we either get a keyframe
+ // or we've looked through 50 video frames without finding one.
+ if ( ! ffmpeg_is_keyframe( stream ) && ++stream->need_keyframe < 50 )
+ {
+ av_free_packet( stream->ffmpeg_pkt );
+ goto again;
+ }
+ stream->need_keyframe = 0;
+ }
+ ++stream->frames;
+ }