12 // work arounds (centos)
15 #define INT64_MAX 9223372036854775807LL
17 #define MAX_RETRY 1000
20 #include "bccmodels.h"
22 #include "fileffmpeg.h"
25 #include "indexfile.h"
26 #include "interlacemodes.h"
29 #include "mainerror.h"
34 #define VIDEO_INBUF_SIZE 0x10000
35 #define AUDIO_INBUF_SIZE 0x10000
36 #define VIDEO_REFILL_THRESH 0
37 #define AUDIO_REFILL_THRESH 0x1000
38 #define AUDIO_MIN_FRAME_SZ 128
40 Mutex FFMPEG::fflock("FFMPEG::fflock");
42 static void ff_err(int ret, const char *fmt, ...)
47 vsnprintf(msg, sizeof(msg), fmt, ap);
49 char errmsg[BCSTRLEN];
50 av_strerror(ret, errmsg, sizeof(errmsg));
51 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
57 pkt.data = 0; pkt.size = 0;
59 void FFPacket::finit()
61 av_packet_unref(&pkt);
64 FFrame::FFrame(FFStream *fst)
67 frm = av_frame_alloc();
68 init = fst->init_frame(frm);
76 void FFrame::queue(int64_t pos)
82 void FFrame::dequeue()
87 int FFAudioStream::read(float *fp, long len)
95 while( --k >= 0 ) *fp++ = *op++;
96 if( op >= lmt ) op = bfr;
101 void FFAudioStream::realloc(long nsz, int nch, long len)
103 long bsz = nsz * nch;
104 float *np = new float[bsz];
105 inp = np + read(np, len) * nch;
110 delete [] bfr; bfr = np;
113 void FFAudioStream::realloc(long nsz, int nch)
115 if( nsz > sz || this->nch != nch ) {
116 long len = this->nch != nch ? 0 : hpos;
117 if( len > sz ) len = sz;
119 realloc(nsz, nch, len);
123 void FFAudioStream::reserve(long nsz, int nch)
125 long len = (inp - outp) / nch;
127 if( nsz > sz || this->nch != nch ) {
128 if( this->nch != nch ) len = 0;
129 realloc(nsz, nch, len);
132 if( (len*=nch) > 0 && bfr != outp )
133 memmove(bfr, outp, len*sizeof(*bfr));
138 long FFAudioStream::used()
140 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
143 long FFAudioStream::avail()
146 if( in1 >= lmt ) in1 = bfr;
147 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
150 void FFAudioStream::reset_history()
154 memset(bfr, 0, lmt-bfr);
157 void FFAudioStream::iseek(int64_t ofs)
159 if( ofs > hpos ) ofs = hpos;
160 if( ofs > sz ) ofs = sz;
161 outp = inp - ofs*nch;
162 if( outp < bfr ) outp += sz*nch;
165 float *FFAudioStream::get_outp(int ofs)
172 int64_t FFAudioStream::put_inp(int ofs)
175 return (inp-outp) / nch;
178 int FFAudioStream::write(const float *fp, long len)
186 while( --k >= 0 ) *ip++ = *fp++;
187 if( ip >= lmt ) ip = bfr;
194 int FFAudioStream::zero(long len)
202 while( --k >= 0 ) *ip++ = 0;
203 if( ip >= lmt ) ip = bfr;
210 // does not advance outp
211 int FFAudioStream::read(double *dp, long len, int ch)
214 float *op = outp + ch;
215 float *lmt1 = lmt + nch-1;
217 int k = (lmt1 - op) / nch;
220 while( --k >= 0 ) { *dp++ = *op; op += nch; }
221 if( op >= lmt ) op -= sz*nch;
226 // load linear buffer, no wrapping allowed, does not advance inp
227 int FFAudioStream::write(const double *dp, long len, int ch)
230 float *ip = inp + ch;
231 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
236 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
238 this->ffmpeg = ffmpeg;
241 frm_lock = new Mutex("FFStream::frm_lock");
248 nudge = AV_NOPTS_VALUE;
249 seek_pos = curr_pos = 0;
251 reading = writing = 0;
262 FFStream::~FFStream()
264 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
265 if( avctx ) avcodec_free_context(&avctx);
266 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
267 if( bsfc ) av_bsf_free(&bsfc);
268 while( frms.first ) frms.remove(frms.first);
269 if( filter_graph ) avfilter_graph_free(&filter_graph);
270 if( frame ) av_frame_free(&frame);
271 if( fframe ) av_frame_free(&fframe);
273 if( stats_fp ) fclose(stats_fp);
274 if( stats_in ) av_freep(&stats_in);
275 delete [] stats_filename;
278 void FFStream::ff_lock(const char *cp)
280 FFMPEG::fflock.lock(cp);
283 void FFStream::ff_unlock()
285 FFMPEG::fflock.unlock();
288 void FFStream::queue(FFrame *frm)
290 frm_lock->lock("FFStream::queue");
294 ffmpeg->mux_lock->unlock();
297 void FFStream::dequeue(FFrame *frm)
299 frm_lock->lock("FFStream::dequeue");
301 frms.remove_pointer(frm);
305 int FFStream::encode_activate()
308 writing = ffmpeg->encode_activate();
312 int FFStream::decode_activate()
314 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
315 ff_lock("FFStream::decode_activate");
317 AVDictionary *copts = 0;
318 av_dict_copy(&copts, ffmpeg->opts, 0);
320 // this should be avformat_copy_context(), but no copy avail
321 ret = avformat_open_input(&fmt_ctx, ffmpeg->fmt_ctx->filename, NULL, &copts);
323 ret = avformat_find_stream_info(fmt_ctx, 0);
324 st = fmt_ctx->streams[fidx];
327 if( ret >= 0 && st != 0 ) {
328 AVCodecID codec_id = st->codecpar->codec_id;
329 AVCodec *decoder = avcodec_find_decoder(codec_id);
330 avctx = avcodec_alloc_context3(decoder);
332 eprintf(_("cant allocate codec context\n"));
333 ret = AVERROR(ENOMEM);
336 av_codec_set_pkt_timebase(avctx, st->time_base);
337 if( decoder->capabilities & AV_CODEC_CAP_DR1 )
338 avctx->flags |= CODEC_FLAG_EMU_EDGE;
339 avcodec_parameters_to_context(avctx, st->codecpar);
340 if( !av_dict_get(copts, "threads", NULL, 0) )
341 avctx->thread_count = ffmpeg->ff_cpus();
342 ret = avcodec_open2(avctx, decoder, &copts);
348 eprintf(_("open decoder failed\n"));
351 eprintf(_("can't clone input file\n"));
352 av_dict_free(&copts);
358 int FFStream::read_packet()
360 av_packet_unref(ipkt);
361 int ret = av_read_frame(fmt_ctx, ipkt);
364 if( ret == AVERROR_EOF ) return 0;
365 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
372 int FFStream::decode(AVFrame *frame)
375 int retries = MAX_RETRY;
377 while( ret >= 0 && !flushed && --retries >= 0 ) {
379 if( (ret=read_packet()) < 0 ) break;
380 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
382 if( pkt->stream_index != st->index ) continue;
383 if( !pkt->data | !pkt->size ) continue;
385 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
386 ff_err(ret, "FFStream::decode: avcodec_send_packet failed\n");
392 if( (ret=decode_frame(frame)) > 0 ) break;
400 fprintf(stderr, "FFStream::decode: Retry limit\n");
404 fprintf(stderr, "FFStream::decode: failed\n");
408 int FFStream::load_filter(AVFrame *frame)
410 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
412 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
416 int FFStream::read_filter(AVFrame *frame)
418 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
420 if( ret == AVERROR(EAGAIN) ) return 0;
421 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
422 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
428 int FFStream::read_frame(AVFrame *frame)
430 av_frame_unref(frame);
431 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
432 return decode(frame);
433 if( !fframe && !(fframe=av_frame_alloc()) ) {
434 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
438 while( !flushed && !(ret=read_filter(frame)) ) {
439 if( (ret=decode(fframe)) < 0 ) break;
440 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
445 int FFStream::write_packet(FFPacket &pkt)
449 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
450 pkt->stream_index = st->index;
451 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
454 ret = av_bsf_send_packet(bsfc, pkt);
457 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
458 if( ret == AVERROR(EAGAIN) ) return 0;
459 if( ret == AVERROR_EOF ) return -1;
462 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
463 bs->stream_index = st->index;
464 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
468 ff_err(ret, "FFStream::write_packet: write packet failed\n");
472 int FFStream::encode_frame(AVFrame *frame)
474 int pkts = 0, ret = 0;
475 for( int retry=100; --retry>=0; ) {
477 ret = avcodec_send_frame(avctx, frame);
478 if( !ret && frame ) return pkts;
479 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
481 ret = avcodec_receive_packet(avctx, opkt);
482 if( !frame && ret == AVERROR_EOF ) return pkts;
484 ret = write_packet(opkt);
487 if( frame && stats_fp ) {
488 ret = write_stats_file();
492 ff_err(ret, "FFStream::encode_frame: encode failed\n");
496 int FFStream::flush()
500 int ret = encode_frame(0);
501 if( ret >= 0 && stats_fp ) {
502 ret = write_stats_file();
506 ff_err(ret, "FFStream::flush");
507 return ret >= 0 ? 0 : 1;
511 int FFStream::open_stats_file()
513 stats_fp = fopen(stats_filename,"w");
514 return stats_fp ? 0 : AVERROR(errno);
517 int FFStream::close_stats_file()
520 fclose(stats_fp); stats_fp = 0;
525 int FFStream::read_stats_file()
527 int64_t len = 0; struct stat stats_st;
528 int fd = open(stats_filename, O_RDONLY);
529 int ret = fd >= 0 ? 0: ENOENT;
530 if( !ret && fstat(fd, &stats_st) )
533 len = stats_st.st_size;
534 stats_in = (char *)av_malloc(len+1);
538 if( !ret && read(fd, stats_in, len+1) != len )
542 avctx->stats_in = stats_in;
546 return !ret ? 0 : AVERROR(ret);
549 int FFStream::write_stats_file()
552 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
553 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
555 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file");
560 int FFStream::init_stats_file()
563 if( (pass & 2) && (ret = read_stats_file()) < 0 )
564 ff_err(ret, "stat file read: %s", stats_filename);
565 if( (pass & 1) && (ret=open_stats_file()) < 0 )
566 ff_err(ret, "stat file open: %s", stats_filename);
567 return ret >= 0 ? 0 : ret;
570 int FFStream::seek(int64_t no, double rate)
572 // default ffmpeg native seek
574 int64_t pos = no, pkt_pos = -1;
575 IndexMarks *index_markers = get_markers();
576 if( index_markers && index_markers->size() > 1 ) {
577 IndexMarks &marks = *index_markers;
578 int i = marks.find(pos);
579 int64_t n = i < 0 ? (i=0) : marks[i].no;
580 // if indexed seek point not too far away (<30 secs), use index
581 if( no-n < 30*rate ) {
584 if( i < marks.size() ) pkt_pos = marks[i].pos;
588 if( pos == curr_pos ) return 0;
589 double secs = pos < 0 ? 0. : pos / rate;
590 AVRational time_base = st->time_base;
591 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
593 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
594 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
595 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
596 else tstmp = INT64_MIN+1;
598 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
601 // seek all streams using the default timebase.
602 // this is how ffmpeg and ffplay work. stream seeks are less tested.
603 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
607 avcodec_flush_buffers(avctx);
608 avformat_flush(fmt_ctx);
610 int64_t seek = tstmp;
611 int flags = AVSEEK_FLAG_ANY;
612 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
614 flags = AVSEEK_FLAG_BYTE;
616 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
618 // finds the first index frame below the target time
619 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
620 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
622 int retry = MAX_RETRY;
624 need_packet = 0; flushed = 0;
625 seeked = 1; st_eof(0);
626 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
627 while( --retry >= 0 ) {
628 if( read_packet() <= 0 ) { ret = -1; break; }
629 if( ipkt->stream_index != st->index ) continue;
630 if( !ipkt->data || !ipkt->size ) continue;
631 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
632 if( --npkts <= 0 ) break;
633 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
634 if( pkt_ts == AV_NOPTS_VALUE ) continue;
635 if( pkt_ts >= tstmp ) break;
638 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
642 ret = avcodec_send_packet(avctx, ipkt);
644 //some codecs need more than one pkt to resync
645 if( ret == AVERROR_INVALIDDATA ) ret = 0;
647 ff_err(ret, "FFStream::avcodec_send_packet failed\n");
652 printf("** seek fail %jd, %jd\n", pos, tstmp);
653 seeked = need_packet = 0;
657 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
658 seek_pos = curr_pos = pos;
662 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
663 : FFStream(ffmpeg, strm, fidx)
666 channel0 = channels = 0;
669 frame_sz = AUDIO_MIN_FRAME_SZ;
671 resample_context = 0;
672 swr_ichs = swr_ifmt = swr_irate = 0;
681 bfr = new float[bsz];
686 FFAudioStream::~FFAudioStream()
688 if( resample_context ) swr_free(&resample_context);
693 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
695 if( resample_context ) {
696 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
698 swr_free(&resample_context);
700 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
701 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
703 uint64_t ilayout = av_get_default_channel_layout(ichs);
704 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
705 uint64_t olayout = av_get_default_channel_layout(channels);
706 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
707 resample_context = swr_alloc_set_opts(NULL,
708 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
709 ilayout, (AVSampleFormat)ifmt, irate,
711 if( resample_context )
712 swr_init(resample_context);
715 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
717 samples = *(float **)data;
718 if( resample_context ) {
719 if( len > aud_bfr_sz ) {
725 aud_bfr = new float[aud_bfr_sz*channels];
727 int ret = swr_convert(resample_context,
728 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
730 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
739 int FFAudioStream::load_history(uint8_t **data, int len)
742 len = get_samples(samples, data, len);
744 // biggest user bfr since seek + frame
745 realloc(mbsz + len + 1, channels);
751 int FFAudioStream::decode_frame(AVFrame *frame)
753 int first_frame = seeked; seeked = 0;
754 int ret = avcodec_receive_frame(avctx, frame);
756 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
757 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
758 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame\n");
761 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
762 if( pkt_ts != AV_NOPTS_VALUE )
763 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * sample_rate + 0.5;
767 int FFAudioStream::encode_activate()
769 if( writing >= 0 ) return writing;
770 if( !avctx->codec ) return writing = 0;
771 frame_sz = avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE ?
772 10000 : avctx->frame_size;
773 return FFStream::encode_activate();
776 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
778 reserve(len+1, st->codecpar->channels);
779 for( int ch=0; ch<nch; ++ch )
780 write(sp[ch], len, ch);
784 int FFAudioStream::in_history(int64_t pos)
786 if( pos > curr_pos ) return 0;
788 if( len > sz ) len = sz;
789 if( pos < curr_pos - len ) return 0;
794 int FFAudioStream::init_frame(AVFrame *frame)
796 frame->nb_samples = frame_sz;
797 frame->format = avctx->sample_fmt;
798 frame->channel_layout = avctx->channel_layout;
799 frame->sample_rate = avctx->sample_rate;
800 int ret = av_frame_get_buffer(frame, 0);
802 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
806 int FFAudioStream::load(int64_t pos, int len)
808 if( audio_seek(pos) < 0 ) return -1;
809 if( !frame && !(frame=av_frame_alloc()) ) {
810 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
813 if( mbsz < len ) mbsz = len;
814 int64_t end_pos = pos + len;
815 int ret = 0, i = len / frame_sz + MAX_RETRY;
816 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
817 ret = read_frame(frame);
818 if( ret > 0 && frame->nb_samples > 0 ) {
819 init_swr(frame->channels, frame->format, frame->sample_rate);
820 load_history(&frame->extended_data[0], frame->nb_samples);
821 curr_pos += frame->nb_samples;
824 if( end_pos > curr_pos ) {
825 zero(end_pos - curr_pos);
828 len = curr_pos - pos;
833 int FFAudioStream::audio_seek(int64_t pos)
835 if( decode_activate() <= 0 ) return -1;
836 if( !st->codecpar ) return -1;
837 if( in_history(pos) ) return 0;
838 if( pos == curr_pos ) return 0;
839 reset_history(); mbsz = 0;
840 // guarentee preload > 1sec samples
841 if( seek(pos-sample_rate, sample_rate) < 0 ) return -1;
845 int FFAudioStream::encode(double **samples, int len)
847 if( encode_activate() <= 0 ) return -1;
850 int64_t count = samples ? load_buffer(samples, len) : used();
851 int frame_sz1 = samples ? frame_sz-1 : 0;
854 while( ret >= 0 && count > frame_sz1 ) {
855 frm = new FFrame(this);
856 if( (ret=frm->initted()) < 0 ) break;
857 AVFrame *frame = *frm;
858 len = count >= frame_sz ? frame_sz : count;
859 float *bfrp = get_outp(len);
860 ret = swr_convert(resample_context,
861 (uint8_t **)frame->extended_data, len,
862 (const uint8_t **)&bfrp, len);
864 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
867 frame->nb_samples = len;
868 frm->queue(curr_pos);
875 return ret >= 0 ? 0 : 1;
878 int FFAudioStream::drain()
883 int FFAudioStream::encode_frame(AVFrame *frame)
885 return FFStream::encode_frame(frame);
888 int FFAudioStream::write_packet(FFPacket &pkt)
890 return FFStream::write_packet(pkt);
893 void FFAudioStream::load_markers()
895 IndexState *index_state = ffmpeg->file_base->asset->index_state;
896 if( !index_state || idx >= index_state->audio_markers.size() ) return;
897 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
898 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
901 IndexMarks *FFAudioStream::get_markers()
903 IndexState *index_state = ffmpeg->file_base->asset->index_state;
904 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
905 return index_state->audio_markers[idx];
908 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
909 : FFStream(ffmpeg, strm, fidx)
920 FFVideoStream::~FFVideoStream()
924 int FFVideoStream::decode_frame(AVFrame *frame)
926 int first_frame = seeked; seeked = 0;
927 int ret = avcodec_receive_frame(avctx, frame);
929 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
930 if( ret == AVERROR(EAGAIN) ) return 0;
931 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
932 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame\n");
935 int64_t pkt_ts = av_frame_get_best_effort_timestamp(frame);
936 if( pkt_ts != AV_NOPTS_VALUE )
937 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
941 int FFVideoStream::load(VFrame *vframe, int64_t pos)
943 int ret = video_seek(pos);
944 if( ret < 0 ) return -1;
945 if( !frame && !(frame=av_frame_alloc()) ) {
946 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
949 int i = MAX_RETRY + pos - curr_pos;
950 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
951 ret = read_frame(frame);
952 if( ret > 0 ) ++curr_pos;
954 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
957 ret = convert_cmodel(vframe, frame);
959 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
963 int FFVideoStream::video_seek(int64_t pos)
965 if( decode_activate() <= 0 ) return -1;
966 if( !st->codecpar ) return -1;
967 if( pos == curr_pos-1 && !seeked ) return 0;
968 // if close enough, just read up to current
969 int gop = avctx->gop_size;
970 if( gop < 4 ) gop = 4;
971 if( gop > 64 ) gop = 64;
972 int read_limit = curr_pos + 3*gop;
973 if( pos >= curr_pos && pos <= read_limit ) return 0;
974 // guarentee preload more than 2*gop frames
975 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
979 int FFVideoStream::init_frame(AVFrame *picture)
981 picture->format = avctx->pix_fmt;
982 picture->width = avctx->width;
983 picture->height = avctx->height;
984 int ret = av_frame_get_buffer(picture, 32);
988 int FFVideoStream::encode(VFrame *vframe)
990 if( encode_activate() <= 0 ) return -1;
992 FFrame *picture = new FFrame(this);
993 int ret = picture->initted();
995 AVFrame *frame = *picture;
996 frame->pts = curr_pos;
997 ret = convert_pixfmt(vframe, frame);
1000 picture->queue(curr_pos);
1004 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1007 return ret >= 0 ? 0 : 1;
1010 int FFVideoStream::drain()
1015 int FFVideoStream::encode_frame(AVFrame *frame)
1018 frame->interlaced_frame = interlaced;
1019 frame->top_field_first = top_field_first;
1021 return FFStream::encode_frame(frame);
1024 int FFVideoStream::write_packet(FFPacket &pkt)
1026 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1028 return FFStream::write_packet(pkt);
1031 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1033 switch( color_model ) {
1034 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1035 case BC_RGB888: return AV_PIX_FMT_RGB24;
1036 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1037 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1038 case BC_BGR888: return AV_PIX_FMT_BGR24;
1039 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1040 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1041 case BC_RGB8: return AV_PIX_FMT_RGB8;
1042 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1043 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1044 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1045 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1046 case BC_RGB565: return AV_PIX_FMT_RGB565;
1047 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1048 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1049 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1050 case BC_GBRP: return AV_PIX_FMT_GBRP;
1054 return AV_PIX_FMT_NB;
1057 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1060 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1061 case AV_PIX_FMT_RGB24: return BC_RGB888;
1062 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1063 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1064 case AV_PIX_FMT_BGR24: return BC_BGR888;
1065 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1066 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1067 case AV_PIX_FMT_RGB8: return BC_RGB8;
1068 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1069 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1070 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1071 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1072 case AV_PIX_FMT_RGB565: return BC_RGB565;
1073 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1074 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1075 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1076 case AV_PIX_FMT_GBRP: return BC_GBRP;
1083 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1085 AVFrame *ipic = av_frame_alloc();
1086 int ret = convert_picture_vframe(frame, ip, ipic);
1087 av_frame_free(&ipic);
1091 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1093 int cmodel = frame->get_color_model();
1094 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1095 if( ofmt == AV_PIX_FMT_NB ) return -1;
1096 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1097 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1098 if( size < 0 ) return -1;
1100 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1101 int ysz = bpp * frame->get_w(), usz = ysz;
1110 // override av_image_fill_arrays() for planar types
1111 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1112 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1113 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1116 ipic->data[0] = frame->get_data();
1117 ipic->linesize[0] = frame->get_bytes_per_line();
1121 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1122 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1123 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1124 if( !convert_ctx ) {
1125 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1126 " sws_getCachedContext() failed\n");
1129 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1130 ipic->data, ipic->linesize);
1132 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1138 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1140 // try direct transfer
1141 if( !convert_picture_vframe(frame, ip) ) return 1;
1142 // use indirect transfer
1143 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1144 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1146 for( int i = 0; i <desc->nb_components; ++i ) {
1147 int bits = desc->comp[i].depth;
1148 if( bits > max_bits ) max_bits = bits;
1150 int imodel = pix_fmt_to_color_model(ifmt);
1151 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1152 int cmodel = frame->get_color_model();
1153 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1154 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1155 imodel = cmodel_is_yuv ?
1156 (BC_CModels::has_alpha(cmodel) ?
1158 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1159 (BC_CModels::has_alpha(cmodel) ?
1160 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1161 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1163 VFrame vframe(ip->width, ip->height, imodel);
1164 if( convert_picture_vframe(&vframe, ip) ) return -1;
1165 frame->transfer_from(&vframe);
1169 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1171 int ret = convert_cmodel(frame, ifp);
1173 const AVDictionary *src = av_frame_get_metadata(ifp);
1174 AVDictionaryEntry *t = NULL;
1175 BC_Hash *hp = frame->get_params();
1177 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1178 hp->update(t->key, t->value);
1183 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1185 AVFrame *opic = av_frame_alloc();
1186 int ret = convert_vframe_picture(frame, op, opic);
1187 av_frame_free(&opic);
1191 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1193 int cmodel = frame->get_color_model();
1194 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1195 if( ifmt == AV_PIX_FMT_NB ) return -1;
1196 int size = av_image_fill_arrays(opic->data, opic->linesize,
1197 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1198 if( size < 0 ) return -1;
1200 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1201 int ysz = bpp * frame->get_w(), usz = ysz;
1210 // override av_image_fill_arrays() for planar types
1211 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1212 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1213 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1216 opic->data[0] = frame->get_data();
1217 opic->linesize[0] = frame->get_bytes_per_line();
1221 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1222 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1223 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1224 if( !convert_ctx ) {
1225 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1226 " sws_getCachedContext() failed\n");
1229 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1230 op->data, op->linesize);
1232 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1238 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1240 // try direct transfer
1241 if( !convert_vframe_picture(frame, op) ) return 1;
1242 // use indirect transfer
1243 int cmodel = frame->get_color_model();
1244 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1245 max_bits /= BC_CModels::components(cmodel);
1246 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1247 int imodel = pix_fmt_to_color_model(ofmt);
1248 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1249 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1250 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1251 imodel = cmodel_is_yuv ?
1252 (BC_CModels::has_alpha(cmodel) ?
1254 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1255 (BC_CModels::has_alpha(cmodel) ?
1256 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1257 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1259 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1260 vframe.transfer_from(frame);
1261 if( !convert_vframe_picture(&vframe, op) ) return 1;
1265 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1267 int ret = convert_pixfmt(frame, ofp);
1269 BC_Hash *hp = frame->get_params();
1270 AVDictionary **dict = avpriv_frame_get_metadatap(ofp);
1271 //av_dict_free(dict);
1272 for( int i=0; i<hp->size(); ++i ) {
1273 char *key = hp->get_key(i), *val = hp->get_value(i);
1274 av_dict_set(dict, key, val, 0);
1280 void FFVideoStream::load_markers()
1282 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1283 if( !index_state || idx >= index_state->video_markers.size() ) return;
1284 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1287 IndexMarks *FFVideoStream::get_markers()
1289 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1290 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1291 return !index_state ? 0 : index_state->video_markers[idx];
1295 FFMPEG::FFMPEG(FileBase *file_base)
1298 this->file_base = file_base;
1299 memset(file_format,0,sizeof(file_format));
1300 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1301 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1304 decoding = encoding = 0;
1305 has_audio = has_video = 0;
1308 opt_video_filter = 0;
1309 opt_audio_filter = 0;
1310 char option_path[BCTEXTLEN];
1311 set_option_path(option_path, "%s", "ffmpeg.opts");
1312 read_options(option_path, opts);
1317 ff_lock("FFMPEG::~FFMPEG()");
1319 ffaudio.remove_all_objects();
1320 ffvideo.remove_all_objects();
1321 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1325 av_dict_free(&opts);
1326 delete [] opt_video_filter;
1327 delete [] opt_audio_filter;
1330 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1332 const int *p = codec->supported_samplerates;
1333 if( !p ) return sample_rate;
1335 if( *p == sample_rate ) return *p;
1341 static inline AVRational std_frame_rate(int i)
1343 static const int m1 = 1001*12, m2 = 1000*12;
1344 static const int freqs[] = {
1345 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1346 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1348 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1349 return (AVRational) { freq, 1001*12 };
1352 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1354 const AVRational *p = codec->supported_framerates;
1355 AVRational rate, best_rate = (AVRational) { 0, 0 };
1356 double max_err = 1.; int i = 0;
1357 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1358 double framerate = (double) rate.num / rate.den;
1359 double err = fabs(frame_rate/framerate - 1.);
1360 if( err >= max_err ) continue;
1364 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1367 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1370 double display_aspect = asset->width / (double)asset->height;
1371 double sample_aspect = display_aspect / asset->aspect_ratio;
1372 int width = 1000000, height = width * sample_aspect + 0.5;
1374 MWindow::create_aspect_ratio(w, h, width, height);
1375 return (AVRational){(int)w, (int)h};
1378 return (AVRational){1, 1};
1382 AVRational FFMPEG::to_time_base(int sample_rate)
1384 return (AVRational){1, sample_rate};
1387 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1389 char *ep = path + BCTEXTLEN-1;
1390 strncpy(path, File::get_cindat_path(), ep-path);
1391 strncat(path, "/ffmpeg/", ep-path);
1392 path += strlen(path);
1395 path += vsnprintf(path, ep-path, fmt, ap);
1400 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1405 set_option_path(path, "%s/%s", type, spec);
1408 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1410 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1411 get_option_path(option_path, path, spec);
1412 FILE *fp = fopen(option_path,"r");
1415 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1417 line[sizeof(line)-1] = 0;
1418 ret = scan_option_line(line, format, codec);
1424 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1426 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1427 get_option_path(option_path, path, spec);
1428 FILE *fp = fopen(option_path,"r");
1431 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1434 line[sizeof(line)-1] = 0;
1435 ret = scan_option_line(line, format, codec);
1438 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1439 while( vp < ep && *vp && *vp != '|' ) ++vp;
1440 if( *vp == '|' ) --vp;
1441 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1446 int FFMPEG::get_file_format()
1448 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1449 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1450 audio_muxer[0] = audio_format[0] = 0;
1451 video_muxer[0] = video_format[0] = 0;
1452 Asset *asset = file_base->asset;
1453 int ret = asset ? 0 : 1;
1454 if( !ret && asset->audio_data ) {
1455 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1456 if( get_format(audio_muxer, "format", audio_format) ) {
1457 strcpy(audio_muxer, audio_format);
1458 audio_format[0] = 0;
1462 if( !ret && asset->video_data ) {
1463 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1464 if( get_format(video_muxer, "format", video_format) ) {
1465 strcpy(video_muxer, video_format);
1466 video_format[0] = 0;
1470 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1472 if( !ret && audio_muxer[0] && video_muxer[0] &&
1473 strcmp(audio_muxer, video_muxer) ) ret = -1;
1474 if( !ret && audio_format[0] && video_format[0] &&
1475 strcmp(audio_format, video_format) ) ret = -1;
1477 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1478 (audio_muxer[0] ? audio_muxer : video_muxer) :
1479 (audio_format[0] ? audio_format : video_format));
1483 int FFMPEG::scan_option_line(char *cp, char *tag, char *val)
1485 while( *cp == ' ' || *cp == '\t' ) ++cp;
1487 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1489 if( !len || len > BCSTRLEN-1 ) return 1;
1490 while( bp < cp ) *tag++ = *bp++;
1492 while( *cp == ' ' || *cp == '\t' ) ++cp;
1493 if( *cp == '=' ) ++cp;
1494 while( *cp == ' ' || *cp == '\t' ) ++cp;
1496 while( *cp && *cp != '\n' ) ++cp;
1498 if( len > BCTEXTLEN-1 ) return 1;
1499 while( bp < cp ) *val++ = *bp++;
1504 int FFMPEG::load_defaults(const char *path, const char *type,
1505 char *codec, char *codec_options, int len)
1507 char default_file[BCTEXTLEN];
1508 set_option_path(default_file, "%s/%s.dfl", path, type);
1509 FILE *fp = fopen(default_file,"r");
1511 fgets(codec, BCSTRLEN, fp);
1513 while( *cp && *cp!='\n' ) ++cp;
1515 while( len > 0 && fgets(codec_options, len, fp) ) {
1516 int n = strlen(codec_options);
1517 codec_options += n; len -= n;
1520 set_option_path(default_file, "%s/%s", path, codec);
1521 return load_options(default_file, codec_options, len);
1524 void FFMPEG::set_asset_format(Asset *asset, const char *text)
1526 if( asset->format != FILE_FFMPEG ) return;
1527 if( text != asset->fformat )
1528 strcpy(asset->fformat, text);
1529 if( !asset->ff_audio_options[0] ) {
1530 asset->audio_data = !load_defaults("audio", text, asset->acodec,
1531 asset->ff_audio_options, sizeof(asset->ff_audio_options));
1533 if( !asset->ff_video_options[0] ) {
1534 asset->video_data = !load_defaults("video", text, asset->vcodec,
1535 asset->ff_video_options, sizeof(asset->ff_video_options));
1539 int FFMPEG::get_encoder(const char *options,
1540 char *format, char *codec, char *bsfilter)
1542 FILE *fp = fopen(options,"r");
1544 eprintf(_("options open failed %s\n"),options);
1547 if( get_encoder(fp, format, codec, bsfilter) )
1548 eprintf(_("format/codec not found %s\n"), options);
1553 int FFMPEG::get_encoder(FILE *fp,
1554 char *format, char *codec, char *bsfilter)
1556 format[0] = codec[0] = bsfilter[0] = 0;
1557 char line[BCTEXTLEN];
1558 if( !fgets(line, sizeof(line), fp) ) return 1;
1559 line[sizeof(line)-1] = 0;
1560 if( scan_option_line(line, format, codec) ) return 1;
1562 while( *cp && *cp != '|' ) ++cp;
1563 if( !*cp ) return 0;
1565 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1566 while( *++cp && (*cp==' ' || *cp == '\t') );
1568 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1573 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1575 FILE *fp = fopen(options,"r");
1578 while( !ret && --skip >= 0 ) {
1580 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1581 if( ch < 0 ) ret = 1;
1584 ret = read_options(fp, options, opts);
1589 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1591 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1593 int ret = read_options(fp, options, opts);
1595 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1596 if( tag ) st->id = strtol(tag->value,0,0);
1600 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1602 int ret = 0, no = 0;
1603 char line[BCTEXTLEN];
1604 while( !ret && fgets(line, sizeof(line), fp) ) {
1605 line[sizeof(line)-1] = 0;
1606 if( line[0] == '#' ) continue;
1607 if( line[0] == '\n' ) continue;
1608 char key[BCSTRLEN], val[BCTEXTLEN];
1609 if( scan_option_line(line, key, val) ) {
1610 eprintf(_("err reading %s: line %d\n"), options, no);
1614 if( !strcmp(key, "duration") )
1615 opt_duration = strtod(val, 0);
1616 else if( !strcmp(key, "video_filter") )
1617 opt_video_filter = cstrdup(val);
1618 else if( !strcmp(key, "audio_filter") )
1619 opt_audio_filter = cstrdup(val);
1620 else if( !strcmp(key, "loglevel") )
1623 av_dict_set(&opts, key, val, 0);
1629 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1631 char option_path[BCTEXTLEN];
1632 set_option_path(option_path, "%s", options);
1633 return read_options(option_path, opts);
1636 int FFMPEG::load_options(const char *path, char *bfr, int len)
1639 FILE *fp = fopen(path, "r");
1641 fgets(bfr, len, fp); // skip hdr
1642 len = fread(bfr, 1, len-1, fp);
1643 if( len < 0 ) len = 0;
1649 void FFMPEG::set_loglevel(const char *ap)
1651 if( !ap || !*ap ) return;
1656 { "quiet" , AV_LOG_QUIET },
1657 { "panic" , AV_LOG_PANIC },
1658 { "fatal" , AV_LOG_FATAL },
1659 { "error" , AV_LOG_ERROR },
1660 { "warning", AV_LOG_WARNING },
1661 { "info" , AV_LOG_INFO },
1662 { "verbose", AV_LOG_VERBOSE },
1663 { "debug" , AV_LOG_DEBUG },
1665 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1666 if( !strcmp(log_levels[i].name, ap) ) {
1667 av_log_set_level(log_levels[i].level);
1671 av_log_set_level(atoi(ap));
1674 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1676 double base_time = time == AV_NOPTS_VALUE ? 0 :
1677 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1678 return base_time / AV_TIME_BASE;
1681 int FFMPEG::info(char *text, int len)
1683 if( len <= 0 ) return 0;
1685 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1687 report("format: %s\n",fmt_ctx->iformat->name);
1688 if( ffvideo.size() > 0 )
1689 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1690 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1691 FFVideoStream *vid = ffvideo[vidx];
1692 AVStream *st = vid->st;
1693 AVCodecID codec_id = st->codecpar->codec_id;
1694 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1695 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1696 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1697 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1698 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1699 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1700 report(" pix %s\n", pfn ? pfn : "(unkn)");
1701 double secs = to_secs(st->duration, st->time_base);
1702 int64_t length = secs * vid->frame_rate + 0.5;
1703 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1704 int64_t nudge = ofs * vid->frame_rate;
1705 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1706 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
1707 int hrs = secs/3600; secs -= hrs*3600;
1708 int mins = secs/60; secs -= mins*60;
1709 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1711 if( ffaudio.size() > 0 )
1712 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
1713 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
1714 FFAudioStream *aud = ffaudio[aidx];
1715 AVStream *st = aud->st;
1716 AVCodecID codec_id = st->codecpar->codec_id;
1717 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
1718 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1719 int nch = aud->channels, ch0 = aud->channel0+1;
1720 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
1721 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
1722 const char *fmt = av_get_sample_fmt_name(sample_fmt);
1723 report(" %s %d", fmt, aud->sample_rate);
1724 int sample_bits = av_get_bits_per_sample(codec_id);
1725 report(" %dbits\n", sample_bits);
1726 double secs = to_secs(st->duration, st->time_base);
1727 int64_t length = secs * aud->sample_rate + 0.5;
1728 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
1729 int64_t nudge = ofs * aud->sample_rate;
1730 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1731 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
1732 int hrs = secs/3600; secs -= hrs*3600;
1733 int mins = secs/60; secs -= mins*60;
1734 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
1736 if( fmt_ctx->nb_programs > 0 )
1737 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
1738 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
1739 report("program %d", i+1);
1740 AVProgram *pgrm = fmt_ctx->programs[i];
1741 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
1742 int idx = pgrm->stream_index[j];
1743 int vidx = ffvideo.size();
1744 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
1746 report(", vid%d", vidx);
1749 int aidx = ffaudio.size();
1750 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
1752 report(", aud%d", aidx);
1755 report(", (%d)", pgrm->stream_index[j]);
1760 AVDictionaryEntry *tag = 0;
1761 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
1762 report("%s=%s\n", tag->key, tag->value);
1771 int FFMPEG::init_decoder(const char *filename)
1773 ff_lock("FFMPEG::init_decoder");
1775 char file_opts[BCTEXTLEN];
1776 char *bp = strrchr(strcpy(file_opts, filename), '/');
1777 char *sp = strrchr(!bp ? file_opts : bp, '.');
1780 strcpy(sp, ".opts");
1781 fp = fopen(file_opts, "r");
1784 read_options(fp, file_opts, opts);
1788 load_options("decode.opts", opts);
1789 AVDictionary *fopts = 0;
1790 av_dict_copy(&fopts, opts, 0);
1791 int ret = avformat_open_input(&fmt_ctx, filename, NULL, &fopts);
1792 av_dict_free(&fopts);
1794 ret = avformat_find_stream_info(fmt_ctx, NULL);
1799 return !ret ? 0 : 1;
1802 int FFMPEG::open_decoder()
1805 if( stat(fmt_ctx->filename, &st) < 0 ) {
1806 eprintf(_("can't stat file: %s\n"), fmt_ctx->filename);
1810 int64_t file_bits = 8 * st.st_size;
1811 if( !fmt_ctx->bit_rate && opt_duration > 0 )
1812 fmt_ctx->bit_rate = file_bits / opt_duration;
1815 if( fmt_ctx->bit_rate > 0 ) {
1816 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
1817 AVStream *st = fmt_ctx->streams[i];
1818 if( st->duration != AV_NOPTS_VALUE ) continue;
1819 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
1820 st->duration = av_rescale(file_bits, st->time_base.den,
1821 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
1825 static int notified = 0;
1826 if( !notified && estimated ) {
1828 printf("FFMPEG::open_decoder: some stream times estimated\n");
1831 ff_lock("FFMPEG::open_decoder");
1832 int ret = 0, bad_time = 0;
1833 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
1834 AVStream *st = fmt_ctx->streams[i];
1835 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
1836 AVCodecParameters *avpar = st->codecpar;
1837 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
1838 if( !codec_desc ) continue;
1839 switch( avpar->codec_type ) {
1840 case AVMEDIA_TYPE_VIDEO: {
1841 if( avpar->width < 1 ) continue;
1842 if( avpar->height < 1 ) continue;
1843 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
1844 if( framerate.num < 1 ) continue;
1846 int vidx = ffvideo.size();
1847 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
1848 vstrm_index.append(ffidx(vidx, 0));
1849 ffvideo.append(vid);
1850 vid->width = avpar->width;
1851 vid->height = avpar->height;
1852 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
1853 double secs = to_secs(st->duration, st->time_base);
1854 vid->length = secs * vid->frame_rate;
1855 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
1856 vid->nudge = st->start_time;
1858 if( opt_video_filter )
1859 ret = vid->create_filter(opt_video_filter, avpar);
1861 case AVMEDIA_TYPE_AUDIO: {
1862 if( avpar->channels < 1 ) continue;
1863 if( avpar->sample_rate < 1 ) continue;
1865 int aidx = ffaudio.size();
1866 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
1867 ffaudio.append(aud);
1868 aud->channel0 = astrm_index.size();
1869 aud->channels = avpar->channels;
1870 for( int ch=0; ch<aud->channels; ++ch )
1871 astrm_index.append(ffidx(aidx, ch));
1872 aud->sample_rate = avpar->sample_rate;
1873 double secs = to_secs(st->duration, st->time_base);
1874 aud->length = secs * aud->sample_rate;
1875 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
1876 aud->nudge = st->start_time;
1878 if( opt_audio_filter )
1879 ret = aud->create_filter(opt_audio_filter, avpar);
1885 printf("FFMPEG::open_decoder: some stream have bad times\n");
1887 return ret < 0 ? -1 : 0;
1891 int FFMPEG::init_encoder(const char *filename)
1893 int fd = ::open(filename,O_WRONLY);
1894 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
1896 eprintf(_("bad file path: %s\n"), filename);
1900 int ret = get_file_format();
1902 eprintf(_("bad file format: %s\n"), filename);
1906 eprintf(_("mismatch audio/video file format: %s\n"), filename);
1909 ff_lock("FFMPEG::init_encoder");
1911 char format[BCSTRLEN];
1912 if( get_format(format, "format", file_format) )
1913 strcpy(format, file_format);
1914 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
1916 eprintf(_("failed: %s\n"), filename);
1921 load_options("encode.opts", opts);
1927 int FFMPEG::open_encoder(const char *type, const char *spec)
1930 Asset *asset = file_base->asset;
1931 char *filename = asset->path;
1932 AVDictionary *sopts = 0;
1933 av_dict_copy(&sopts, opts, 0);
1934 char option_path[BCTEXTLEN];
1935 set_option_path(option_path, "%s/%s.opts", type, type);
1936 read_options(option_path, sopts);
1937 get_option_path(option_path, type, spec);
1938 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
1939 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
1940 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
1944 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
1945 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
1946 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
1949 ff_lock("FFMPEG::open_encoder");
1952 AVCodecContext *ctx = 0;
1954 const AVCodecDescriptor *codec_desc = 0;
1955 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
1957 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
1961 codec_desc = avcodec_descriptor_get(codec->id);
1963 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
1968 st = avformat_new_stream(fmt_ctx, 0);
1970 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
1975 switch( codec_desc->type ) {
1976 case AVMEDIA_TYPE_AUDIO: {
1978 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
1982 if( scan_options(asset->ff_audio_options, sopts, st) ) {
1983 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
1988 ctx = avcodec_alloc_context3(codec);
1989 if( asset->ff_audio_bitrate > 0 ) {
1990 ctx->bit_rate = asset->ff_audio_bitrate;
1992 sprintf(arg, "%d", asset->ff_audio_bitrate);
1993 av_dict_set(&sopts, "b", arg, 0);
1995 else if( asset->ff_audio_quality >= 0 ) {
1996 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
1997 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
1998 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
1999 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2000 ctx->flags |= CODEC_FLAG_QSCALE;
2002 av_dict_set(&sopts, "flags", "+qscale", 0);
2003 sprintf(arg, "%d", asset->ff_audio_quality);
2004 av_dict_set(&sopts, "qscale", arg, 0);
2005 sprintf(arg, "%d", ctx->global_quality);
2006 av_dict_set(&sopts, "global_quality", arg, 0);
2008 int aidx = ffaudio.size();
2009 int fidx = aidx + ffvideo.size();
2010 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2011 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2012 aud->sample_rate = asset->sample_rate;
2013 ctx->channels = aud->channels = asset->channels;
2014 for( int ch=0; ch<aud->channels; ++ch )
2015 astrm_index.append(ffidx(aidx, ch));
2016 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2017 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2018 if( !ctx->sample_rate ) {
2019 eprintf(_("check_sample_rate failed %s\n"), filename);
2023 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2024 ctx->sample_fmt = codec->sample_fmts[0];
2025 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2026 aud->resample_context = swr_alloc_set_opts(NULL,
2027 layout, ctx->sample_fmt, aud->sample_rate,
2028 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2030 swr_init(aud->resample_context);
2033 case AVMEDIA_TYPE_VIDEO: {
2035 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2039 if( scan_options(asset->ff_video_options, sopts, st) ) {
2040 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2045 ctx = avcodec_alloc_context3(codec);
2046 if( asset->ff_video_bitrate > 0 ) {
2047 ctx->bit_rate = asset->ff_video_bitrate;
2049 sprintf(arg, "%d", asset->ff_video_bitrate);
2050 av_dict_set(&sopts, "b", arg, 0);
2052 else if( asset->ff_video_quality >= 0 ) {
2053 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2054 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2055 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2056 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2057 ctx->flags |= CODEC_FLAG_QSCALE;
2059 av_dict_set(&sopts, "flags", "+qscale", 0);
2060 sprintf(arg, "%d", asset->ff_video_quality);
2061 av_dict_set(&sopts, "qscale", arg, 0);
2062 sprintf(arg, "%d", ctx->global_quality);
2063 av_dict_set(&sopts, "global_quality", arg, 0);
2065 int vidx = ffvideo.size();
2066 int fidx = vidx + ffaudio.size();
2067 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2068 vstrm_index.append(ffidx(vidx, 0));
2069 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2070 vid->width = asset->width;
2071 vid->height = asset->height;
2072 vid->frame_rate = asset->frame_rate;
2073 AVPixelFormat pix_fmt = codec->pix_fmts ?
2074 codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2075 AVDictionaryEntry *tag = av_dict_get(sopts, "cin_pix_fmt", NULL, 0);
2077 int avfmt = av_get_pix_fmt(tag->value);
2079 eprintf(_("cin_pix_fmt unknown = %s\n"), tag->value);
2083 pix_fmt = (AVPixelFormat)avfmt;
2085 ctx->pix_fmt = pix_fmt;
2086 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2087 int mask_w = (1<<desc->log2_chroma_w)-1;
2088 ctx->width = (vid->width+mask_w) & ~mask_w;
2089 int mask_h = (1<<desc->log2_chroma_h)-1;
2090 ctx->height = (vid->height+mask_h) & ~mask_h;
2091 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2092 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2093 if( !frame_rate.num || !frame_rate.den ) {
2094 eprintf(_("check_frame_rate failed %s\n"), filename);
2098 av_reduce(&frame_rate.num, &frame_rate.den,
2099 frame_rate.num, frame_rate.den, INT_MAX);
2100 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2101 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2102 st->avg_frame_rate = frame_rate;
2103 st->time_base = ctx->time_base;
2105 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2106 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2107 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2110 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2115 AVDictionaryEntry *tag;
2116 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2117 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2118 fst->stats_filename = cstrcat(2, tag->value, suffix);
2120 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2121 int pass = fst->pass;
2122 char *cp = tag->value;
2124 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2125 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2126 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2127 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2128 if( bp < ep ) *bp++ = ch;
2130 if( !strcmp(id, "pass1") ) {
2131 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2133 else if( !strcmp(id, "pass2") ) {
2134 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2137 if( (fst->pass=pass) ) {
2138 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2139 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2145 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2146 ctx->flags |= CODEC_FLAG_GLOBAL_HEADER;
2147 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2148 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2151 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2152 av_dict_set(&sopts, "cin_quality", 0, 0);
2154 if( !av_dict_get(sopts, "threads", NULL, 0) )
2155 ctx->thread_count = ff_cpus();
2156 ret = avcodec_open2(ctx, codec, &sopts);
2158 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2160 fprintf(stderr, "Could not copy the stream parameters\n");
2163 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2164 ret = avcodec_copy_context(st->codec, ctx);
2165 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2167 fprintf(stderr, "Could not copy the stream context\n");
2170 ff_err(ret,"FFMPEG::open_encoder");
2171 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2177 if( !ret && fst && bsfilter[0] ) {
2178 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2180 ff_err(ret,"FFMPEG::open_encoder");
2181 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2192 av_dict_free(&sopts);
2196 int FFMPEG::close_encoder()
2199 if( encoding > 0 ) {
2200 av_write_trailer(fmt_ctx);
2201 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2202 avio_closep(&fmt_ctx->pb);
2208 int FFMPEG::decode_activate()
2210 if( decoding < 0 ) {
2212 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2213 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2214 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2215 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2216 // set nudges for each program stream set
2217 const int64_t min_nudge = INT64_MIN+1;
2218 int npgrms = fmt_ctx->nb_programs;
2219 for( int i=0; i<npgrms; ++i ) {
2220 AVProgram *pgrm = fmt_ctx->programs[i];
2221 // first start time video stream
2222 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2223 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2224 int fidx = pgrm->stream_index[j];
2225 AVStream *st = fmt_ctx->streams[fidx];
2226 AVCodecParameters *avpar = st->codecpar;
2227 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2228 if( st->start_time == AV_NOPTS_VALUE ) continue;
2229 if( vstart_time < st->start_time )
2230 vstart_time = st->start_time;
2233 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2234 if( st->start_time == AV_NOPTS_VALUE ) continue;
2235 if( astart_time < st->start_time )
2236 astart_time = st->start_time;
2240 //since frame rate is much more grainy than sample rate, it is better to
2241 // align using video, so that total absolute error is minimized.
2242 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2243 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2244 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2245 int fidx = pgrm->stream_index[j];
2246 AVStream *st = fmt_ctx->streams[fidx];
2247 AVCodecParameters *avpar = st->codecpar;
2248 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2249 for( int k=0; k<ffvideo.size(); ++k ) {
2250 if( ffvideo[k]->fidx != fidx ) continue;
2251 ffvideo[k]->nudge = nudge;
2255 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2256 for( int k=0; k<ffaudio.size(); ++k ) {
2257 if( ffaudio[k]->fidx != fidx ) continue;
2258 ffaudio[k]->nudge = nudge;
2264 // set nudges for any streams not yet set
2265 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2266 int nstreams = fmt_ctx->nb_streams;
2267 for( int i=0; i<nstreams; ++i ) {
2268 AVStream *st = fmt_ctx->streams[i];
2269 AVCodecParameters *avpar = st->codecpar;
2270 switch( avpar->codec_type ) {
2271 case AVMEDIA_TYPE_VIDEO: {
2272 if( st->start_time == AV_NOPTS_VALUE ) continue;
2273 int vidx = ffvideo.size();
2274 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2275 if( vidx < 0 ) continue;
2276 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2277 if( vstart_time < st->start_time )
2278 vstart_time = st->start_time;
2280 case AVMEDIA_TYPE_AUDIO: {
2281 if( st->start_time == AV_NOPTS_VALUE ) continue;
2282 int aidx = ffaudio.size();
2283 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2284 if( aidx < 0 ) continue;
2285 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2286 ffaudio[aidx]->frame_sz = avpar->frame_size;
2287 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2288 if( astart_time < st->start_time )
2289 astart_time = st->start_time;
2294 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2295 astart_time > min_nudge ? astart_time : 0;
2296 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2297 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2298 ffvideo[vidx]->nudge = nudge;
2300 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2301 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2302 ffaudio[aidx]->nudge = nudge;
2309 int FFMPEG::encode_activate()
2312 if( encoding < 0 ) {
2314 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2315 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->filename, AVIO_FLAG_WRITE)) < 0 ) {
2316 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2322 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2323 for( int i=0; i< ffvideo.size(); ++i )
2324 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2325 for( int i=0; i< ffaudio.size(); ++i )
2326 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2327 int pi = fmt_ctx->nb_programs;
2328 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2329 AVDictionary **meta = &prog->metadata;
2330 av_dict_set(meta, "service_provider", "cin5", 0);
2331 const char *path = fmt_ctx->filename, *bp = strrchr(path,'/');
2332 if( bp ) path = bp + 1;
2333 av_dict_set(meta, "title", path, 0);
2335 if( ffaudio.size() ) {
2336 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2337 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2338 static struct { const char lc[3], lng[4]; } lcode[] = {
2339 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2340 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2341 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2342 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2343 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2344 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2346 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2347 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2349 if( !ep ) ep = "und";
2351 strncpy(lang,ep,3); lang[3] = 0;
2352 AVStream *st = ffaudio[0]->st;
2353 av_dict_set(&st->metadata,"language",lang,0);
2356 AVDictionary *fopts = 0;
2357 char option_path[BCTEXTLEN];
2358 set_option_path(option_path, "format/%s", file_format);
2359 read_options(option_path, fopts, 1);
2360 ret = avformat_write_header(fmt_ctx, &fopts);
2362 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2366 av_dict_free(&fopts);
2373 int FFMPEG::audio_seek(int stream, int64_t pos)
2375 int aidx = astrm_index[stream].st_idx;
2376 FFAudioStream *aud = ffaudio[aidx];
2377 aud->audio_seek(pos);
2381 int FFMPEG::video_seek(int stream, int64_t pos)
2383 int vidx = vstrm_index[stream].st_idx;
2384 FFVideoStream *vid = ffvideo[vidx];
2385 vid->video_seek(pos);
2390 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2392 if( !has_audio || chn >= astrm_index.size() ) return -1;
2393 int aidx = astrm_index[chn].st_idx;
2394 FFAudioStream *aud = ffaudio[aidx];
2395 if( aud->load(pos, len) < len ) return -1;
2396 int ch = astrm_index[chn].st_ch;
2397 int ret = aud->read(samples,len,ch);
2401 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2403 if( !has_video || layer >= vstrm_index.size() ) return -1;
2404 int vidx = vstrm_index[layer].st_idx;
2405 FFVideoStream *vid = ffvideo[vidx];
2406 return vid->load(vframe, pos);
2410 int FFMPEG::encode(int stream, double **samples, int len)
2412 FFAudioStream *aud = ffaudio[stream];
2413 return aud->encode(samples, len);
2417 int FFMPEG::encode(int stream, VFrame *frame)
2419 FFVideoStream *vid = ffvideo[stream];
2420 return vid->encode(frame);
2423 void FFMPEG::start_muxer()
2431 void FFMPEG::stop_muxer()
2440 void FFMPEG::flow_off()
2443 flow_lock->lock("FFMPEG::flow_off");
2447 void FFMPEG::flow_on()
2451 flow_lock->unlock();
2454 void FFMPEG::flow_ctl()
2457 flow_lock->lock("FFMPEG::flow_ctl");
2458 flow_lock->unlock();
2462 int FFMPEG::mux_audio(FFrame *frm)
2464 FFStream *fst = frm->fst;
2465 AVCodecContext *ctx = fst->avctx;
2466 AVFrame *frame = *frm;
2467 AVRational tick_rate = {1, ctx->sample_rate};
2468 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2469 int ret = fst->encode_frame(frame);
2471 ff_err(ret, "FFMPEG::mux_audio");
2472 return ret >= 0 ? 0 : 1;
2475 int FFMPEG::mux_video(FFrame *frm)
2477 FFStream *fst = frm->fst;
2478 AVFrame *frame = *frm;
2479 frame->pts = frm->position;
2480 int ret = fst->encode_frame(frame);
2482 ff_err(ret, "FFMPEG::mux_video");
2483 return ret >= 0 ? 0 : 1;
2489 double atm = -1, vtm = -1;
2490 FFrame *afrm = 0, *vfrm = 0;
2492 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2493 FFStream *fst = ffaudio[i];
2494 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2495 FFrame *frm = fst->frms.first;
2496 if( !frm ) { if( !done ) return; continue; }
2497 double tm = to_secs(frm->position, fst->avctx->time_base);
2498 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2500 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2501 FFStream *fst = ffvideo[i];
2502 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2503 FFrame *frm = fst->frms.first;
2504 if( !frm ) { if( !done ) return; continue; }
2505 double tm = to_secs(frm->position, fst->avctx->time_base);
2506 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2508 if( !demand ) flow_off();
2509 if( !afrm && !vfrm ) break;
2510 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2511 vfrm->position, vfrm->fst->avctx->time_base,
2512 afrm->position, afrm->fst->avctx->time_base);
2513 FFrame *frm = v <= 0 ? vfrm : afrm;
2514 if( frm == afrm ) mux_audio(frm);
2515 if( frm == vfrm ) mux_video(frm);
2524 mux_lock->lock("FFMPEG::run");
2527 for( int i=0; i<ffaudio.size(); ++i )
2528 ffaudio[i]->drain();
2529 for( int i=0; i<ffvideo.size(); ++i )
2530 ffvideo[i]->drain();
2532 for( int i=0; i<ffaudio.size(); ++i )
2533 ffaudio[i]->flush();
2534 for( int i=0; i<ffvideo.size(); ++i )
2535 ffvideo[i]->flush();
2539 int FFMPEG::ff_total_audio_channels()
2541 return astrm_index.size();
2544 int FFMPEG::ff_total_astreams()
2546 return ffaudio.size();
2549 int FFMPEG::ff_audio_channels(int stream)
2551 return ffaudio[stream]->channels;
2554 int FFMPEG::ff_sample_rate(int stream)
2556 return ffaudio[stream]->sample_rate;
2559 const char* FFMPEG::ff_audio_format(int stream)
2561 AVStream *st = ffaudio[stream]->st;
2562 AVCodecID id = st->codecpar->codec_id;
2563 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2564 return desc ? desc->name : _("Unknown");
2567 int FFMPEG::ff_audio_pid(int stream)
2569 return ffaudio[stream]->st->id;
2572 int64_t FFMPEG::ff_audio_samples(int stream)
2574 return ffaudio[stream]->length;
2577 // find audio astream/channels with this program,
2578 // or all program audio channels (astream=-1)
2579 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2583 int vidx = ffvideo[vstream]->fidx;
2584 // find first program with this video stream
2585 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2586 AVProgram *pgrm = fmt_ctx->programs[i];
2587 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2588 int st_idx = pgrm->stream_index[j];
2589 AVStream *st = fmt_ctx->streams[st_idx];
2590 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2591 if( st_idx == vidx ) pidx = i;
2594 if( pidx < 0 ) return -1;
2596 int64_t channels = 0;
2597 AVProgram *pgrm = fmt_ctx->programs[pidx];
2598 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2599 int aidx = pgrm->stream_index[j];
2600 AVStream *st = fmt_ctx->streams[aidx];
2601 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2602 if( astream > 0 ) { --astream; continue; }
2604 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2605 if( ffaudio[i]->fidx == aidx ) astrm = i;
2607 if( ret < 0 ) ret = astrm;
2608 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2609 channels |= mask << ffaudio[astrm]->channel0;
2611 if( !astream ) break;
2613 channel_mask = channels;
2618 int FFMPEG::ff_total_video_layers()
2620 return vstrm_index.size();
2623 int FFMPEG::ff_total_vstreams()
2625 return ffvideo.size();
2628 int FFMPEG::ff_video_width(int stream)
2630 return ffvideo[stream]->width;
2633 int FFMPEG::ff_video_height(int stream)
2635 return ffvideo[stream]->height;
2638 int FFMPEG::ff_set_video_width(int stream, int width)
2640 int w = ffvideo[stream]->width;
2641 ffvideo[stream]->width = width;
2645 int FFMPEG::ff_set_video_height(int stream, int height)
2647 int h = ffvideo[stream]->height;
2648 ffvideo[stream]->height = height;
2652 int FFMPEG::ff_coded_width(int stream)
2654 return ffvideo[stream]->avctx->coded_width;
2657 int FFMPEG::ff_coded_height(int stream)
2659 return ffvideo[stream]->avctx->coded_height;
2662 float FFMPEG::ff_aspect_ratio(int stream)
2664 return ffvideo[stream]->aspect_ratio;
2667 const char* FFMPEG::ff_video_format(int stream)
2669 AVStream *st = ffvideo[stream]->st;
2670 AVCodecID id = st->codecpar->codec_id;
2671 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2672 return desc ? desc->name : _("Unknown");
2675 double FFMPEG::ff_frame_rate(int stream)
2677 return ffvideo[stream]->frame_rate;
2680 int64_t FFMPEG::ff_video_frames(int stream)
2682 return ffvideo[stream]->length;
2685 int FFMPEG::ff_video_pid(int stream)
2687 return ffvideo[stream]->st->id;
2690 int FFMPEG::ff_video_mpeg_color_range(int stream)
2692 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
2695 int FFMPEG::ff_cpus()
2697 return file_base->file->cpus;
2700 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2702 avfilter_register_all();
2703 const char *sp = filter_spec;
2704 char filter_name[BCSTRLEN], *np = filter_name;
2705 int i = sizeof(filter_name);
2706 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2708 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2709 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
2710 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
2713 filter_graph = avfilter_graph_alloc();
2714 AVFilter *buffersrc = avfilter_get_by_name("buffer");
2715 AVFilter *buffersink = avfilter_get_by_name("buffersink");
2717 int ret = 0; char args[BCTEXTLEN];
2718 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
2719 snprintf(args, sizeof(args),
2720 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
2721 avpar->width, avpar->height, (int)pix_fmt,
2722 st->time_base.num, st->time_base.den,
2723 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
2725 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2726 args, NULL, filter_graph);
2728 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2729 NULL, NULL, filter_graph);
2731 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
2732 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
2733 AV_OPT_SEARCH_CHILDREN);
2735 ff_err(ret, "FFVideoStream::create_filter");
2737 ret = FFStream::create_filter(filter_spec);
2738 return ret >= 0 ? 0 : -1;
2741 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
2743 avfilter_register_all();
2744 const char *sp = filter_spec;
2745 char filter_name[BCSTRLEN], *np = filter_name;
2746 int i = sizeof(filter_name);
2747 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
2749 AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
2750 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
2751 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
2754 filter_graph = avfilter_graph_alloc();
2755 AVFilter *buffersrc = avfilter_get_by_name("abuffer");
2756 AVFilter *buffersink = avfilter_get_by_name("abuffersink");
2757 int ret = 0; char args[BCTEXTLEN];
2758 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
2759 snprintf(args, sizeof(args),
2760 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
2761 st->time_base.num, st->time_base.den, avpar->sample_rate,
2762 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
2764 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
2765 args, NULL, filter_graph);
2767 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
2768 NULL, NULL, filter_graph);
2770 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
2771 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
2772 AV_OPT_SEARCH_CHILDREN);
2774 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
2775 (uint8_t*)&avpar->channel_layout,
2776 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
2778 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
2779 (uint8_t*)&sample_rate, sizeof(sample_rate),
2780 AV_OPT_SEARCH_CHILDREN);
2782 ff_err(ret, "FFAudioStream::create_filter");
2784 ret = FFStream::create_filter(filter_spec);
2785 return ret >= 0 ? 0 : -1;
2788 int FFStream::create_filter(const char *filter_spec)
2790 /* Endpoints for the filter graph. */
2791 AVFilterInOut *outputs = avfilter_inout_alloc();
2792 outputs->name = av_strdup("in");
2793 outputs->filter_ctx = buffersrc_ctx;
2794 outputs->pad_idx = 0;
2797 AVFilterInOut *inputs = avfilter_inout_alloc();
2798 inputs->name = av_strdup("out");
2799 inputs->filter_ctx = buffersink_ctx;
2800 inputs->pad_idx = 0;
2803 int ret = !outputs->name || !inputs->name ? -1 : 0;
2805 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
2806 &inputs, &outputs, NULL);
2808 ret = avfilter_graph_config(filter_graph, NULL);
2811 ff_err(ret, "FFStream::create_filter");
2812 avfilter_graph_free(&filter_graph);
2815 avfilter_inout_free(&inputs);
2816 avfilter_inout_free(&outputs);
2820 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
2823 av_init_packet(&pkt);
2824 AVFrame *frame = av_frame_alloc();
2826 fprintf(stderr,"FFMPEG::scan: ");
2827 fprintf(stderr,_("av_frame_alloc failed\n"));
2831 index_state->add_video_markers(ffvideo.size());
2832 index_state->add_audio_markers(ffaudio.size());
2834 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2836 AVDictionary *copts = 0;
2837 av_dict_copy(&copts, opts, 0);
2838 AVStream *st = fmt_ctx->streams[i];
2839 AVCodecID codec_id = st->codecpar->codec_id;
2840 AVCodec *decoder = avcodec_find_decoder(codec_id);
2841 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
2843 eprintf(_("cant allocate codec context\n"));
2844 ret = AVERROR(ENOMEM);
2847 avcodec_parameters_to_context(avctx, st->codecpar);
2848 if( !av_dict_get(copts, "threads", NULL, 0) )
2849 avctx->thread_count = ff_cpus();
2850 ret = avcodec_open2(avctx, decoder, &copts);
2852 av_dict_free(&copts);
2854 AVCodecParameters *avpar = st->codecpar;
2855 switch( avpar->codec_type ) {
2856 case AVMEDIA_TYPE_VIDEO: {
2857 int vidx = ffvideo.size();
2858 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2859 if( vidx < 0 ) break;
2860 ffvideo[vidx]->avctx = avctx;
2862 case AVMEDIA_TYPE_AUDIO: {
2863 int aidx = ffaudio.size();
2864 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2865 if( aidx < 0 ) break;
2866 ffaudio[aidx]->avctx = avctx;
2871 fprintf(stderr,"FFMPEG::scan: ");
2872 fprintf(stderr,_("codec open failed\n"));
2873 avcodec_free_context(&avctx);
2877 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2878 AVStream *st = fmt_ctx->streams[i];
2879 AVCodecParameters *avpar = st->codecpar;
2880 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2881 int64_t tstmp = st->start_time;
2882 if( tstmp == AV_NOPTS_VALUE ) continue;
2883 int aidx = ffaudio.size();
2884 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2885 if( aidx < 0 ) continue;
2886 FFAudioStream *aud = ffaudio[aidx];
2887 tstmp -= aud->nudge;
2888 double secs = to_secs(tstmp, st->time_base);
2889 aud->curr_pos = secs * aud->sample_rate + 0.5;
2893 for( int64_t count=0; !*canceled; ++count ) {
2894 av_packet_unref(&pkt);
2895 pkt.data = 0; pkt.size = 0;
2897 int ret = av_read_frame(fmt_ctx, &pkt);
2899 if( ret == AVERROR_EOF ) break;
2900 if( ++errs > 100 ) {
2901 ff_err(ret,_("over 100 read_frame errs\n"));
2906 if( !pkt.data ) continue;
2907 int i = pkt.stream_index;
2908 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
2909 AVStream *st = fmt_ctx->streams[i];
2910 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
2912 AVCodecParameters *avpar = st->codecpar;
2913 switch( avpar->codec_type ) {
2914 case AVMEDIA_TYPE_VIDEO: {
2915 int vidx = ffvideo.size();
2916 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
2917 if( vidx < 0 ) break;
2918 FFVideoStream *vid = ffvideo[vidx];
2919 if( !vid->avctx ) break;
2920 int64_t tstmp = pkt.dts;
2921 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
2922 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2923 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
2924 double secs = to_secs(tstmp, st->time_base);
2925 int64_t frm = secs * vid->frame_rate + 0.5;
2926 if( frm < 0 ) frm = 0;
2927 index_state->put_video_mark(vidx, frm, pkt.pos);
2930 ret = avcodec_send_packet(vid->avctx, pkt);
2931 if( ret < 0 ) break;
2932 while( (ret=vid->decode_frame(frame)) > 0 ) {}
2935 case AVMEDIA_TYPE_AUDIO: {
2936 int aidx = ffaudio.size();
2937 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
2938 if( aidx < 0 ) break;
2939 FFAudioStream *aud = ffaudio[aidx];
2940 if( !aud->avctx ) break;
2941 int64_t tstmp = pkt.pts;
2942 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
2943 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
2944 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
2945 double secs = to_secs(tstmp, st->time_base);
2946 int64_t sample = secs * aud->sample_rate + 0.5;
2948 index_state->put_audio_mark(aidx, sample, pkt.pos);
2950 ret = avcodec_send_packet(aud->avctx, &pkt);
2951 if( ret < 0 ) break;
2952 int ch = aud->channel0, nch = aud->channels;
2953 int64_t pos = index_state->pos(ch);
2954 if( pos != aud->curr_pos ) {
2955 if( abs(pos-aud->curr_pos) > 1 )
2956 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
2957 index_state->pad_data(ch, nch, aud->curr_pos);
2959 while( (ret=aud->decode_frame(frame)) > 0 ) {
2960 //if( frame->channels != nch ) break;
2961 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
2963 int len = aud->get_samples(samples,
2964 &frame->extended_data[0], frame->nb_samples);
2965 pos = aud->curr_pos;
2966 if( (aud->curr_pos += len) >= 0 ) {
2968 samples += -pos * nch;
2969 len = aud->curr_pos;
2971 for( int i=0; i<nch; ++i )
2972 index_state->put_data(ch+i,nch,samples+i,len);
2979 av_frame_free(&frame);
2983 void FFStream::load_markers(IndexMarks &marks, double rate)
2986 int64_t sz = marks.size();
2987 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
2988 int nb_ent = st->nb_index_entries;
2989 // some formats already have an index
2991 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
2992 int64_t tstmp = ep->timestamp;
2993 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
2994 double secs = ffmpeg->to_secs(tstmp, st->time_base);
2995 int64_t no = secs * rate;
2996 while( in < sz && marks[in].no <= no ) ++in;
2998 int64_t len = sz - in;
2999 int64_t count = max_entries - nb_ent;
3000 if( count > len ) count = len;
3001 for( int i=0; i<count; ++i ) {
3002 int k = in + i * len / count;
3003 int64_t no = marks[k].no, pos = marks[k].pos;
3004 double secs = (double)no / rate;
3005 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3006 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3007 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);