12 // work arounds (centos)
15 #define INT64_MAX 9223372036854775807LL
17 #define MAX_RETRY 1000
18 // max pts/curr_pos drift allowed before correction (in seconds)
19 #define AUDIO_PTS_TOLERANCE 0.04
22 #include "bccmodels.h"
25 #include "edlsession.h"
27 #include "fileffmpeg.h"
28 #include "filesystem.h"
30 #include "indexfile.h"
31 #include "interlacemodes.h"
34 #include "mainerror.h"
41 #define av_register_all(s)
42 #define avfilter_register_all(s)
45 #define VIDEO_INBUF_SIZE 0x10000
46 #define AUDIO_INBUF_SIZE 0x10000
47 #define VIDEO_REFILL_THRESH 0
48 #define AUDIO_REFILL_THRESH 0x1000
49 #define AUDIO_MIN_FRAME_SZ 128
51 #define FF_ESTM_TIMES 0x0001
52 #define FF_BAD_TIMES 0x0002
54 Mutex FFMPEG::fflock("FFMPEG::fflock");
56 static void ff_err(int ret, const char *fmt, ...)
61 vsnprintf(msg, sizeof(msg), fmt, ap);
63 char errmsg[BCSTRLEN];
64 av_strerror(ret, errmsg, sizeof(errmsg));
65 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
71 pkt.data = 0; pkt.size = 0;
73 void FFPacket::finit()
75 av_packet_unref(&pkt);
78 FFrame::FFrame(FFStream *fst)
81 frm = av_frame_alloc();
82 init = fst->init_frame(frm);
90 void FFrame::queue(int64_t pos)
96 void FFrame::dequeue()
101 int FFAudioStream::read(float *fp, long len)
109 while( --k >= 0 ) *fp++ = *op++;
110 if( op >= lmt ) op = bfr;
115 void FFAudioStream::realloc(long nsz, int nch, long len)
117 long bsz = nsz * nch;
118 float *np = new float[bsz];
119 inp = np + read(np, len) * nch;
124 delete [] bfr; bfr = np;
127 void FFAudioStream::realloc(long nsz, int nch)
129 if( nsz > sz || this->nch != nch ) {
130 long len = this->nch != nch ? 0 : hpos;
131 if( len > sz ) len = sz;
133 realloc(nsz, nch, len);
137 void FFAudioStream::reserve(long nsz, int nch)
139 long len = (inp - outp) / nch;
141 if( nsz > sz || this->nch != nch ) {
142 if( this->nch != nch ) len = 0;
143 realloc(nsz, nch, len);
146 if( (len*=nch) > 0 && bfr != outp )
147 memmove(bfr, outp, len*sizeof(*bfr));
152 long FFAudioStream::used()
154 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
157 long FFAudioStream::avail()
160 if( in1 >= lmt ) in1 = bfr;
161 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
164 void FFAudioStream::reset_history()
168 memset(bfr, 0, lmt-bfr);
171 void FFAudioStream::iseek(int64_t ofs)
173 if( ofs > hpos ) ofs = hpos;
174 if( ofs > sz ) ofs = sz;
175 outp = inp - ofs*nch;
176 if( outp < bfr ) outp += sz*nch;
179 float *FFAudioStream::get_outp(int ofs)
186 int64_t FFAudioStream::put_inp(int ofs)
189 return (inp-outp) / nch;
192 int FFAudioStream::write(const float *fp, long len)
200 while( --k >= 0 ) *ip++ = *fp++;
201 if( ip >= lmt ) ip = bfr;
208 int FFAudioStream::zero(long len)
216 while( --k >= 0 ) *ip++ = 0;
217 if( ip >= lmt ) ip = bfr;
224 // does not advance outp
225 int FFAudioStream::read(double *dp, long len, int ch)
228 float *op = outp + ch;
229 float *lmt1 = lmt + nch-1;
231 int k = (lmt1 - op) / nch;
234 while( --k >= 0 ) { *dp++ = *op; op += nch; }
235 if( op >= lmt ) op -= sz*nch;
240 // load linear buffer, no wrapping allowed, does not advance inp
241 int FFAudioStream::write(const double *dp, long len, int ch)
244 float *ip = inp + ch;
245 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
250 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
252 this->ffmpeg = ffmpeg;
255 frm_lock = new Mutex("FFStream::frm_lock");
262 nudge = AV_NOPTS_VALUE;
263 seek_pos = curr_pos = 0;
265 reading = writing = 0;
267 hw_pixfmt = AV_PIX_FMT_NONE;
279 FFStream::~FFStream()
281 if( reading > 0 || writing > 0 ) avcodec_close(avctx);
282 if( avctx ) avcodec_free_context(&avctx);
283 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
284 if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
285 if( bsfc ) av_bsf_free(&bsfc);
286 while( frms.first ) frms.remove(frms.first);
287 if( filter_graph ) avfilter_graph_free(&filter_graph);
288 if( frame ) av_frame_free(&frame);
289 if( fframe ) av_frame_free(&fframe);
291 if( stats_fp ) fclose(stats_fp);
292 if( stats_in ) av_freep(&stats_in);
293 delete [] stats_filename;
296 void FFStream::ff_lock(const char *cp)
298 FFMPEG::fflock.lock(cp);
301 void FFStream::ff_unlock()
303 FFMPEG::fflock.unlock();
306 void FFStream::queue(FFrame *frm)
308 frm_lock->lock("FFStream::queue");
312 ffmpeg->mux_lock->unlock();
315 void FFStream::dequeue(FFrame *frm)
317 frm_lock->lock("FFStream::dequeue");
319 frms.remove_pointer(frm);
323 int FFStream::encode_activate()
326 writing = ffmpeg->encode_activate();
330 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
331 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
332 const enum AVPixelFormat *pix_fmts)
334 for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p )
335 if( *p == hw_pix_fmt ) return *p;
336 fprintf(stderr, "Failed to get HW surface format.\n");
337 return hw_pix_fmt = AV_PIX_FMT_NONE;
341 AVHWDeviceType FFStream::decode_hw_activate()
343 return AV_HWDEVICE_TYPE_NONE;
346 void FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
350 int FFStream::decode_activate()
352 if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
353 ff_lock("FFStream::decode_activate");
355 AVDictionary *copts = 0;
356 av_dict_copy(&copts, ffmpeg->opts, 0);
358 AVHWDeviceType hw_type = decode_hw_activate();
360 // this should be avformat_copy_context(), but no copy avail
361 ret = avformat_open_input(&fmt_ctx,
362 ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
364 ret = avformat_find_stream_info(fmt_ctx, 0);
365 st = fmt_ctx->streams[fidx];
368 while( ret >= 0 && st != 0 && !reading ) {
369 AVCodecID codec_id = st->codecpar->codec_id;
370 AVCodec *decoder = avcodec_find_decoder(codec_id);
371 avctx = avcodec_alloc_context3(decoder);
373 eprintf(_("cant allocate codec context\n"));
374 ret = AVERROR(ENOMEM);
376 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE )
377 decode_hw_format(decoder, hw_type);
380 avcodec_parameters_to_context(avctx, st->codecpar);
381 if( !av_dict_get(copts, "threads", NULL, 0) )
382 avctx->thread_count = ffmpeg->ff_cpus();
383 ret = avcodec_open2(avctx, decoder, &copts);
385 if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
388 AVPacket *pkt = (AVPacket*)ipkt;
390 ret = avcodec_send_packet(avctx, pkt);
391 if( ret < 0 || hw_pix_fmt == AV_PIX_FMT_NONE ) {
392 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
393 ffmpeg->fmt_ctx->url);
394 avcodec_close(avctx);
395 avcodec_free_context(&avctx);
396 av_buffer_unref(&hw_device_ctx);
398 hw_type = AV_HWDEVICE_TYPE_NONE;
411 eprintf(_("open decoder failed\n"));
414 eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
415 av_dict_free(&copts);
421 int FFStream::read_packet()
423 av_packet_unref(ipkt);
424 int ret = av_read_frame(fmt_ctx, ipkt);
427 if( ret == AVERROR_EOF ) return 0;
428 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
435 int FFStream::decode(AVFrame *frame)
438 int retries = MAX_RETRY;
440 while( ret >= 0 && !flushed && --retries >= 0 ) {
442 if( (ret=read_packet()) < 0 ) break;
443 AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
445 if( pkt->stream_index != st->index ) continue;
446 if( !pkt->data | !pkt->size ) continue;
448 if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
449 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
450 ffmpeg->fmt_ctx->url);
456 if( (ret=decode_frame(frame)) > 0 ) break;
464 fprintf(stderr, "FFStream::decode: Retry limit\n");
468 fprintf(stderr, "FFStream::decode: failed\n");
472 int FFStream::load_filter(AVFrame *frame)
474 int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
476 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
480 int FFStream::read_filter(AVFrame *frame)
482 int ret = av_buffersink_get_frame(buffersink_ctx, frame);
484 if( ret == AVERROR(EAGAIN) ) return 0;
485 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
486 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
492 int FFStream::read_frame(AVFrame *frame)
494 av_frame_unref(frame);
495 if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
496 return decode(frame);
497 if( !fframe && !(fframe=av_frame_alloc()) ) {
498 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
502 while( !flushed && !(ret=read_filter(frame)) ) {
503 if( (ret=decode(fframe)) < 0 ) break;
504 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
509 int FFStream::write_packet(FFPacket &pkt)
513 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
514 pkt->stream_index = st->index;
515 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
518 ret = av_bsf_send_packet(bsfc, pkt);
521 if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
522 if( ret == AVERROR(EAGAIN) ) return 0;
523 if( ret == AVERROR_EOF ) return -1;
526 av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
527 bs->stream_index = st->index;
528 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
532 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
533 ffmpeg->fmt_ctx->url);
537 int FFStream::encode_frame(AVFrame *frame)
539 int pkts = 0, ret = 0;
540 for( int retry=MAX_RETRY; --retry>=0; ) {
542 ret = avcodec_send_frame(avctx, frame);
543 if( !ret && frame ) return pkts;
544 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
546 ret = avcodec_receive_packet(avctx, opkt);
547 if( !frame && ret == AVERROR_EOF ) return pkts;
549 ret = write_packet(opkt);
552 if( frame && stats_fp ) {
553 ret = write_stats_file();
557 ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
558 ffmpeg->fmt_ctx->url);
562 int FFStream::flush()
566 int ret = encode_frame(0);
567 if( ret >= 0 && stats_fp ) {
568 ret = write_stats_file();
572 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
573 ffmpeg->fmt_ctx->url);
574 return ret >= 0 ? 0 : 1;
578 int FFStream::open_stats_file()
580 stats_fp = fopen(stats_filename,"w");
581 return stats_fp ? 0 : AVERROR(errno);
584 int FFStream::close_stats_file()
587 fclose(stats_fp); stats_fp = 0;
592 int FFStream::read_stats_file()
594 int64_t len = 0; struct stat stats_st;
595 int fd = open(stats_filename, O_RDONLY);
596 int ret = fd >= 0 ? 0: ENOENT;
597 if( !ret && fstat(fd, &stats_st) )
600 len = stats_st.st_size;
601 stats_in = (char *)av_malloc(len+1);
605 if( !ret && read(fd, stats_in, len+1) != len )
609 avctx->stats_in = stats_in;
613 return !ret ? 0 : AVERROR(ret);
616 int FFStream::write_stats_file()
619 if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
620 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
622 ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
623 ffmpeg->fmt_ctx->url);
628 int FFStream::init_stats_file()
631 if( (pass & 2) && (ret = read_stats_file()) < 0 )
632 ff_err(ret, "stat file read: %s", stats_filename);
633 if( (pass & 1) && (ret=open_stats_file()) < 0 )
634 ff_err(ret, "stat file open: %s", stats_filename);
635 return ret >= 0 ? 0 : ret;
638 int FFStream::seek(int64_t no, double rate)
640 // default ffmpeg native seek
642 int64_t pos = no, pkt_pos = -1;
643 IndexMarks *index_markers = get_markers();
644 if( index_markers && index_markers->size() > 1 ) {
645 IndexMarks &marks = *index_markers;
646 int i = marks.find(pos);
647 int64_t n = i < 0 ? (i=0) : marks[i].no;
648 // if indexed seek point not too far away (<30 secs), use index
649 if( no-n < 30*rate ) {
652 if( i < marks.size() ) pkt_pos = marks[i].pos;
656 if( pos == curr_pos ) return 0;
657 double secs = pos < 0 ? 0. : pos / rate;
658 AVRational time_base = st->time_base;
659 int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
661 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
662 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
663 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
664 else tstmp = INT64_MIN+1;
666 else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
669 // seek all streams using the default timebase.
670 // this is how ffmpeg and ffplay work. stream seeks are less tested.
671 tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
675 avcodec_flush_buffers(avctx);
676 avformat_flush(fmt_ctx);
678 int64_t seek = tstmp;
679 int flags = AVSEEK_FLAG_ANY;
680 if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
682 flags = AVSEEK_FLAG_BYTE;
684 int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
686 // finds the first index frame below the target time
687 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
688 int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
690 int retry = MAX_RETRY;
692 need_packet = 0; flushed = 0;
693 seeked = 1; st_eof(0);
694 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
695 while( --retry >= 0 ) {
696 if( read_packet() <= 0 ) { ret = -1; break; }
697 if( ipkt->stream_index != st->index ) continue;
698 if( !ipkt->data || !ipkt->size ) continue;
699 if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
700 if( --npkts <= 0 ) break;
701 int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
702 if( pkt_ts == AV_NOPTS_VALUE ) continue;
703 if( pkt_ts >= tstmp ) break;
706 fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
710 ret = avcodec_send_packet(avctx, ipkt);
712 //some codecs need more than one pkt to resync
713 if( ret == AVERROR_INVALIDDATA ) ret = 0;
715 ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
716 ffmpeg->fmt_ctx->url);
721 printf("** seek fail %jd, %jd\n", pos, tstmp);
722 seeked = need_packet = 0;
726 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
727 seek_pos = curr_pos = pos;
731 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
732 : FFStream(ffmpeg, strm, fidx)
735 channel0 = channels = 0;
738 frame_sz = AUDIO_MIN_FRAME_SZ;
740 resample_context = 0;
741 swr_ichs = swr_ifmt = swr_irate = 0;
750 bfr = new float[bsz];
755 FFAudioStream::~FFAudioStream()
757 if( resample_context ) swr_free(&resample_context);
762 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
764 if( resample_context ) {
765 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
767 swr_free(&resample_context);
769 swr_ichs = ichs; swr_ifmt = ifmt; swr_irate = irate;
770 if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
772 uint64_t ilayout = av_get_default_channel_layout(ichs);
773 if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
774 uint64_t olayout = av_get_default_channel_layout(channels);
775 if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
776 resample_context = swr_alloc_set_opts(NULL,
777 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
778 ilayout, (AVSampleFormat)ifmt, irate,
780 if( resample_context )
781 swr_init(resample_context);
784 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
786 samples = *(float **)data;
787 if( resample_context ) {
788 if( len > aud_bfr_sz ) {
794 aud_bfr = new float[aud_bfr_sz*channels];
796 int ret = swr_convert(resample_context,
797 (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
799 ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
808 int FFAudioStream::load_history(uint8_t **data, int len)
811 len = get_samples(samples, data, len);
813 // biggest user bfr since seek + frame
814 realloc(mbsz + len + 1, channels);
820 int FFAudioStream::decode_frame(AVFrame *frame)
822 int first_frame = seeked; seeked = 0;
823 frame->best_effort_timestamp = AV_NOPTS_VALUE;
824 int ret = avcodec_receive_frame(avctx, frame);
826 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
827 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
828 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
829 ffmpeg->fmt_ctx->url);
832 int64_t pkt_ts = frame->best_effort_timestamp;
833 if( pkt_ts != AV_NOPTS_VALUE ) {
834 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
835 double t = (double)curr_pos / sample_rate;
836 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
837 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
838 curr_pos = ts * sample_rate + 0.5;
843 int FFAudioStream::encode_activate()
845 if( writing >= 0 ) return writing;
846 if( !avctx->codec ) return writing = 0;
847 frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
848 10000 : avctx->frame_size;
849 return FFStream::encode_activate();
852 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
854 reserve(len+1, st->codecpar->channels);
855 for( int ch=0; ch<nch; ++ch )
856 write(sp[ch], len, ch);
860 int FFAudioStream::in_history(int64_t pos)
862 if( pos > curr_pos ) return 0;
864 if( len > sz ) len = sz;
865 if( pos < curr_pos - len ) return 0;
870 int FFAudioStream::init_frame(AVFrame *frame)
872 frame->nb_samples = frame_sz;
873 frame->format = avctx->sample_fmt;
874 frame->channel_layout = avctx->channel_layout;
875 frame->sample_rate = avctx->sample_rate;
876 int ret = av_frame_get_buffer(frame, 0);
878 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
882 int FFAudioStream::load(int64_t pos, int len)
884 if( audio_seek(pos) < 0 ) return -1;
885 if( !frame && !(frame=av_frame_alloc()) ) {
886 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
889 if( mbsz < len ) mbsz = len;
890 int64_t end_pos = pos + len;
891 int ret = 0, i = len / frame_sz + MAX_RETRY;
892 while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
893 ret = read_frame(frame);
894 if( ret > 0 && frame->nb_samples > 0 ) {
895 init_swr(frame->channels, frame->format, frame->sample_rate);
896 load_history(&frame->extended_data[0], frame->nb_samples);
897 curr_pos += frame->nb_samples;
900 if( end_pos > curr_pos ) {
901 zero(end_pos - curr_pos);
904 len = curr_pos - pos;
909 int FFAudioStream::audio_seek(int64_t pos)
911 if( decode_activate() <= 0 ) return -1;
912 if( !st->codecpar ) return -1;
913 if( in_history(pos) ) return 0;
914 if( pos == curr_pos ) return 0;
915 reset_history(); mbsz = 0;
916 // guarentee preload > 1sec samples
917 if( (pos-=sample_rate) < 0 ) pos = 0;
918 if( seek(pos, sample_rate) < 0 ) return -1;
922 int FFAudioStream::encode(double **samples, int len)
924 if( encode_activate() <= 0 ) return -1;
927 int64_t count = samples ? load_buffer(samples, len) : used();
928 int frame_sz1 = samples ? frame_sz-1 : 0;
931 while( ret >= 0 && count > frame_sz1 ) {
932 frm = new FFrame(this);
933 if( (ret=frm->initted()) < 0 ) break;
934 AVFrame *frame = *frm;
935 len = count >= frame_sz ? frame_sz : count;
936 float *bfrp = get_outp(len);
937 ret = swr_convert(resample_context,
938 (uint8_t **)frame->extended_data, len,
939 (const uint8_t **)&bfrp, len);
941 ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
944 frame->nb_samples = len;
945 frm->queue(curr_pos);
952 return ret >= 0 ? 0 : 1;
955 int FFAudioStream::drain()
960 int FFAudioStream::encode_frame(AVFrame *frame)
962 return FFStream::encode_frame(frame);
965 int FFAudioStream::write_packet(FFPacket &pkt)
967 return FFStream::write_packet(pkt);
970 void FFAudioStream::load_markers()
972 IndexState *index_state = ffmpeg->file_base->asset->index_state;
973 if( !index_state || idx >= index_state->audio_markers.size() ) return;
974 if( index_state->marker_status == MARKERS_NOTTESTED ) return;
975 FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
978 IndexMarks *FFAudioStream::get_markers()
980 IndexState *index_state = ffmpeg->file_base->asset->index_state;
981 if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
982 return index_state->audio_markers[idx];
985 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
986 : FFStream(ffmpeg, strm, fidx)
997 FFVideoStream::~FFVideoStream()
1001 AVHWDeviceType FFVideoStream::decode_hw_activate()
1003 AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1004 const char *hw_dev = getenv("CIN_HW_DEV");
1006 type = av_hwdevice_find_type_by_name(hw_dev);
1007 if( type == AV_HWDEVICE_TYPE_NONE ) {
1008 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1009 fprintf(stderr, "Available device types:");
1010 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1011 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1012 fprintf(stderr, "\n");
1018 void FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1020 hw_pix_fmt = AV_PIX_FMT_NONE;
1021 for( int i=0; ; ++i ) {
1022 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1024 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1025 decoder->name, av_hwdevice_get_type_name(type));
1028 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1029 config->device_type == type ) {
1030 hw_pix_fmt = config->pix_fmt;
1034 if( hw_pix_fmt >= 0 ) {
1035 hw_pixfmt = hw_pix_fmt;
1036 avctx->get_format = get_hw_format;
1037 int ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1039 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1041 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1042 av_hwdevice_get_type_name(type));
1046 int FFVideoStream::decode_frame(AVFrame *frame)
1048 int first_frame = seeked; seeked = 0;
1049 int ret = avcodec_receive_frame(avctx, frame);
1051 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
1052 if( ret == AVERROR(EAGAIN) ) return 0;
1053 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1054 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1055 ffmpeg->fmt_ctx->url);
1058 int64_t pkt_ts = frame->best_effort_timestamp;
1059 if( pkt_ts != AV_NOPTS_VALUE )
1060 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1064 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1066 int ret = video_seek(pos);
1067 if( ret < 0 ) return -1;
1068 if( !frame && !(frame=av_frame_alloc()) ) {
1069 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1072 int i = MAX_RETRY + pos - curr_pos;
1073 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1074 ret = read_frame(frame);
1075 if( ret > 0 ) ++curr_pos;
1077 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1080 ret = convert_cmodel(vframe, frame);
1082 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1086 int FFVideoStream::video_seek(int64_t pos)
1088 if( decode_activate() <= 0 ) return -1;
1089 if( !st->codecpar ) return -1;
1090 if( pos == curr_pos-1 && !seeked ) return 0;
1091 // if close enough, just read up to current
1092 int gop = avctx->gop_size;
1093 if( gop < 4 ) gop = 4;
1094 if( gop > 64 ) gop = 64;
1095 int read_limit = curr_pos + 3*gop;
1096 if( pos >= curr_pos && pos <= read_limit ) return 0;
1097 // guarentee preload more than 2*gop frames
1098 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1102 int FFVideoStream::init_frame(AVFrame *picture)
1104 picture->format = avctx->pix_fmt;
1105 picture->width = avctx->width;
1106 picture->height = avctx->height;
1107 int ret = av_frame_get_buffer(picture, 32);
1111 int FFVideoStream::encode(VFrame *vframe)
1113 if( encode_activate() <= 0 ) return -1;
1115 FFrame *picture = new FFrame(this);
1116 int ret = picture->initted();
1118 AVFrame *frame = *picture;
1119 frame->pts = curr_pos;
1120 ret = convert_pixfmt(vframe, frame);
1123 picture->queue(curr_pos);
1127 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1130 return ret >= 0 ? 0 : 1;
1133 int FFVideoStream::drain()
1138 int FFVideoStream::encode_frame(AVFrame *frame)
1141 frame->interlaced_frame = interlaced;
1142 frame->top_field_first = top_field_first;
1144 return FFStream::encode_frame(frame);
1147 int FFVideoStream::write_packet(FFPacket &pkt)
1149 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1151 return FFStream::write_packet(pkt);
1154 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1156 switch( color_model ) {
1157 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1158 case BC_RGB888: return AV_PIX_FMT_RGB24;
1159 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1160 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1161 case BC_BGR888: return AV_PIX_FMT_BGR24;
1162 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1163 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1164 case BC_RGB8: return AV_PIX_FMT_RGB8;
1165 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1166 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1167 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1168 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1169 case BC_RGB565: return AV_PIX_FMT_RGB565;
1170 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1171 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1172 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1173 case BC_GBRP: return AV_PIX_FMT_GBRP;
1177 return AV_PIX_FMT_NB;
1180 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1183 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1184 case AV_PIX_FMT_RGB24: return BC_RGB888;
1185 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1186 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1187 case AV_PIX_FMT_BGR24: return BC_BGR888;
1188 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1189 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1190 case AV_PIX_FMT_RGB8: return BC_RGB8;
1191 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1192 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1193 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1194 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1195 case AV_PIX_FMT_RGB565: return BC_RGB565;
1196 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1197 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1198 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1199 case AV_PIX_FMT_GBRP: return BC_GBRP;
1206 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1208 AVFrame *ipic = av_frame_alloc();
1209 int ret = convert_picture_vframe(frame, ip, ipic);
1210 av_frame_free(&ipic);
1214 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1216 int cmodel = frame->get_color_model();
1217 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1218 if( ofmt == AV_PIX_FMT_NB ) return -1;
1219 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1220 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1221 if( size < 0 ) return -1;
1223 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1224 int ysz = bpp * frame->get_w(), usz = ysz;
1234 // override av_image_fill_arrays() for planar types
1235 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1236 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1237 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1240 ipic->data[0] = frame->get_data();
1241 ipic->linesize[0] = frame->get_bytes_per_line();
1245 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1246 if( pix_fmt == ((FFVideoStream *)this)->hw_pixfmt ) {
1248 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1249 ret = AVERROR(ENOMEM);
1251 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1253 pix_fmt = (AVPixelFormat)ip->format;
1256 ff_err(ret, "Error retrieving data from GPU to CPU\n");
1260 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1261 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1262 if( !convert_ctx ) {
1263 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1264 " sws_getCachedContext() failed\n");
1267 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1268 ipic->data, ipic->linesize);
1270 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\n");
1276 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1278 // try direct transfer
1279 if( !convert_picture_vframe(frame, ip) ) return 1;
1280 // use indirect transfer
1281 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1282 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1284 for( int i = 0; i <desc->nb_components; ++i ) {
1285 int bits = desc->comp[i].depth;
1286 if( bits > max_bits ) max_bits = bits;
1288 int imodel = pix_fmt_to_color_model(ifmt);
1289 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1290 int cmodel = frame->get_color_model();
1291 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1292 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1293 imodel = cmodel_is_yuv ?
1294 (BC_CModels::has_alpha(cmodel) ?
1296 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1297 (BC_CModels::has_alpha(cmodel) ?
1298 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1299 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1301 VFrame vframe(ip->width, ip->height, imodel);
1302 if( convert_picture_vframe(&vframe, ip) ) return -1;
1303 frame->transfer_from(&vframe);
1307 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1309 int ret = convert_cmodel(frame, ifp);
1311 const AVDictionary *src = ifp->metadata;
1312 AVDictionaryEntry *t = NULL;
1313 BC_Hash *hp = frame->get_params();
1315 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1316 hp->update(t->key, t->value);
1321 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1323 AVFrame *opic = av_frame_alloc();
1324 int ret = convert_vframe_picture(frame, op, opic);
1325 av_frame_free(&opic);
1329 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1331 int cmodel = frame->get_color_model();
1332 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1333 if( ifmt == AV_PIX_FMT_NB ) return -1;
1334 int size = av_image_fill_arrays(opic->data, opic->linesize,
1335 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1336 if( size < 0 ) return -1;
1338 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1339 int ysz = bpp * frame->get_w(), usz = ysz;
1349 // override av_image_fill_arrays() for planar types
1350 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1351 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1352 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1355 opic->data[0] = frame->get_data();
1356 opic->linesize[0] = frame->get_bytes_per_line();
1360 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1361 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1362 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1363 if( !convert_ctx ) {
1364 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1365 " sws_getCachedContext() failed\n");
1368 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1369 op->data, op->linesize);
1371 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1377 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1379 // try direct transfer
1380 if( !convert_vframe_picture(frame, op) ) return 1;
1381 // use indirect transfer
1382 int cmodel = frame->get_color_model();
1383 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1384 max_bits /= BC_CModels::components(cmodel);
1385 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1386 int imodel = pix_fmt_to_color_model(ofmt);
1387 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1388 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1389 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1390 imodel = cmodel_is_yuv ?
1391 (BC_CModels::has_alpha(cmodel) ?
1393 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1394 (BC_CModels::has_alpha(cmodel) ?
1395 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1396 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1398 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1399 vframe.transfer_from(frame);
1400 if( !convert_vframe_picture(&vframe, op) ) return 1;
1404 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1406 int ret = convert_pixfmt(frame, ofp);
1408 BC_Hash *hp = frame->get_params();
1409 AVDictionary **dict = &ofp->metadata;
1410 //av_dict_free(dict);
1411 for( int i=0; i<hp->size(); ++i ) {
1412 char *key = hp->get_key(i), *val = hp->get_value(i);
1413 av_dict_set(dict, key, val, 0);
1419 void FFVideoStream::load_markers()
1421 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1422 if( !index_state || idx >= index_state->video_markers.size() ) return;
1423 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1426 IndexMarks *FFVideoStream::get_markers()
1428 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1429 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1430 return !index_state ? 0 : index_state->video_markers[idx];
1434 FFMPEG::FFMPEG(FileBase *file_base)
1437 this->file_base = file_base;
1438 memset(file_format,0,sizeof(file_format));
1439 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1440 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1443 decoding = encoding = 0;
1444 has_audio = has_video = 0;
1447 opt_video_filter = 0;
1448 opt_audio_filter = 0;
1450 char option_path[BCTEXTLEN];
1451 set_option_path(option_path, "%s", "ffmpeg.opts");
1452 read_options(option_path, opts);
1457 ff_lock("FFMPEG::~FFMPEG()");
1459 ffaudio.remove_all_objects();
1460 ffvideo.remove_all_objects();
1461 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1465 av_dict_free(&opts);
1466 delete [] opt_video_filter;
1467 delete [] opt_audio_filter;
1470 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1472 const int *p = codec->supported_samplerates;
1473 if( !p ) return sample_rate;
1475 if( *p == sample_rate ) return *p;
1481 static inline AVRational std_frame_rate(int i)
1483 static const int m1 = 1001*12, m2 = 1000*12;
1484 static const int freqs[] = {
1485 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1486 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1488 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1489 return (AVRational) { freq, 1001*12 };
1492 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1494 const AVRational *p = codec->supported_framerates;
1495 AVRational rate, best_rate = (AVRational) { 0, 0 };
1496 double max_err = 1.; int i = 0;
1497 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1498 double framerate = (double) rate.num / rate.den;
1499 double err = fabs(frame_rate/framerate - 1.);
1500 if( err >= max_err ) continue;
1504 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1507 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1510 double display_aspect = asset->width / (double)asset->height;
1511 double sample_aspect = display_aspect / asset->aspect_ratio;
1512 int width = 1000000, height = width * sample_aspect + 0.5;
1514 MWindow::create_aspect_ratio(w, h, width, height);
1515 return (AVRational){(int)w, (int)h};
1518 return (AVRational){1, 1};
1522 AVRational FFMPEG::to_time_base(int sample_rate)
1524 return (AVRational){1, sample_rate};
1527 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1530 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1531 int src_planar = av_sample_fmt_is_planar(src_fmt);
1532 if( dst_planar != src_planar ) ++score;
1533 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1534 int src_bytes = av_get_bytes_per_sample(src_fmt);
1535 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1536 int src_packed = av_get_packed_sample_fmt(src_fmt);
1537 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1538 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1539 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1543 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1544 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1546 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1547 int best_score = get_fmt_score(best, src_fmt);
1548 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1549 AVSampleFormat sample_fmt = sample_fmts[i];
1550 int score = get_fmt_score(sample_fmt, src_fmt);
1551 if( score >= best_score ) continue;
1552 best = sample_fmt; best_score = score;
1558 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1560 char *ep = path + BCTEXTLEN-1;
1561 strncpy(path, File::get_cindat_path(), ep-path);
1562 strncat(path, "/ffmpeg/", ep-path);
1563 path += strlen(path);
1566 path += vsnprintf(path, ep-path, fmt, ap);
1571 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1576 set_option_path(path, "%s/%s", type, spec);
1579 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1581 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1582 get_option_path(option_path, path, spec);
1583 FILE *fp = fopen(option_path,"r");
1586 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1588 line[sizeof(line)-1] = 0;
1589 ret = scan_option_line(line, format, codec);
1595 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1597 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1598 get_option_path(option_path, path, spec);
1599 FILE *fp = fopen(option_path,"r");
1602 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1605 line[sizeof(line)-1] = 0;
1606 ret = scan_option_line(line, format, codec);
1609 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1610 while( vp < ep && *vp && *vp != '|' ) ++vp;
1611 if( *vp == '|' ) --vp;
1612 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1617 int FFMPEG::get_file_format()
1619 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1620 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1621 audio_muxer[0] = audio_format[0] = 0;
1622 video_muxer[0] = video_format[0] = 0;
1623 Asset *asset = file_base->asset;
1624 int ret = asset ? 0 : 1;
1625 if( !ret && asset->audio_data ) {
1626 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1627 if( get_format(audio_muxer, "format", audio_format) ) {
1628 strcpy(audio_muxer, audio_format);
1629 audio_format[0] = 0;
1633 if( !ret && asset->video_data ) {
1634 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1635 if( get_format(video_muxer, "format", video_format) ) {
1636 strcpy(video_muxer, video_format);
1637 video_format[0] = 0;
1641 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1643 if( !ret && audio_muxer[0] && video_muxer[0] &&
1644 strcmp(audio_muxer, video_muxer) ) ret = -1;
1645 if( !ret && audio_format[0] && video_format[0] &&
1646 strcmp(audio_format, video_format) ) ret = -1;
1648 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1649 (audio_muxer[0] ? audio_muxer : video_muxer) :
1650 (audio_format[0] ? audio_format : video_format));
1654 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1656 while( *cp == ' ' || *cp == '\t' ) ++cp;
1657 const char *bp = cp;
1658 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1660 if( !len || len > BCSTRLEN-1 ) return 1;
1661 while( bp < cp ) *tag++ = *bp++;
1663 while( *cp == ' ' || *cp == '\t' ) ++cp;
1664 if( *cp == '=' ) ++cp;
1665 while( *cp == ' ' || *cp == '\t' ) ++cp;
1667 while( *cp && *cp != '\n' ) ++cp;
1669 if( len > BCTEXTLEN-1 ) return 1;
1670 while( bp < cp ) *val++ = *bp++;
1675 int FFMPEG::can_render(const char *fformat, const char *type)
1678 char option_path[BCTEXTLEN];
1679 FFMPEG::set_option_path(option_path, type);
1680 fs.update(option_path);
1681 int total_files = fs.total_files();
1682 for( int i=0; i<total_files; ++i ) {
1683 const char *name = fs.get_entry(i)->get_name();
1684 const char *ext = strrchr(name,'.');
1685 if( !ext ) continue;
1686 if( !strcmp(fformat, ++ext) ) return 1;
1691 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1693 for( const char *cp=options; *cp!=0; ) {
1694 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1695 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1698 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1699 char key[BCSTRLEN], val[BCTEXTLEN];
1700 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1701 if( !strcmp(key, nm) ) {
1702 strncpy(value, val, BCSTRLEN);
1709 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1711 char cin_sample_fmt[BCSTRLEN];
1712 int cin_fmt = AV_SAMPLE_FMT_NONE;
1713 const char *options = asset->ff_audio_options;
1714 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1715 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1717 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1718 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1719 avcodec_find_encoder_by_name(audio_codec) : 0;
1720 if( av_codec && av_codec->sample_fmts )
1721 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1723 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1724 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1725 if( !name ) name = _("None");
1726 strcpy(asset->ff_sample_format, name);
1728 char value[BCSTRLEN];
1729 if( !get_ff_option("cin_bitrate", options, value) )
1730 asset->ff_audio_bitrate = atoi(value);
1731 if( !get_ff_option("cin_quality", options, value) )
1732 asset->ff_audio_quality = atoi(value);
1735 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1737 char options_path[BCTEXTLEN];
1738 set_option_path(options_path, "audio/%s", asset->acodec);
1739 if( !load_options(options_path,
1740 asset->ff_audio_options,
1741 sizeof(asset->ff_audio_options)) )
1742 scan_audio_options(asset, edl);
1745 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1747 char cin_pix_fmt[BCSTRLEN];
1748 int cin_fmt = AV_PIX_FMT_NONE;
1749 const char *options = asset->ff_video_options;
1750 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1751 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1753 char video_codec[BCSTRLEN]; video_codec[0] = 0;
1754 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1755 avcodec_find_encoder_by_name(video_codec) : 0;
1756 if( av_codec && av_codec->pix_fmts ) {
1757 if( 0 && edl ) { // frequently picks a bad answer
1758 int color_model = edl->session->color_model;
1759 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1760 max_bits /= BC_CModels::components(color_model);
1761 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1762 (BC_CModels::is_yuv(color_model) ?
1763 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1764 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1767 cin_fmt = av_codec->pix_fmts[0];
1770 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1771 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1772 const char *name = desc ? desc->name : _("None");
1773 strcpy(asset->ff_pixel_format, name);
1775 char value[BCSTRLEN];
1776 if( !get_ff_option("cin_bitrate", options, value) )
1777 asset->ff_video_bitrate = atoi(value);
1778 if( !get_ff_option("cin_quality", options, value) )
1779 asset->ff_video_quality = atoi(value);
1782 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1784 char options_path[BCTEXTLEN];
1785 set_option_path(options_path, "video/%s", asset->vcodec);
1786 if( !load_options(options_path,
1787 asset->ff_video_options,
1788 sizeof(asset->ff_video_options)) )
1789 scan_video_options(asset, edl);
1792 int FFMPEG::load_defaults(const char *path, const char *type,
1793 char *codec, char *codec_options, int len)
1795 char default_file[BCTEXTLEN];
1796 set_option_path(default_file, "%s/%s.dfl", path, type);
1797 FILE *fp = fopen(default_file,"r");
1799 fgets(codec, BCSTRLEN, fp);
1801 while( *cp && *cp!='\n' ) ++cp;
1803 while( len > 0 && fgets(codec_options, len, fp) ) {
1804 int n = strlen(codec_options);
1805 codec_options += n; len -= n;
1808 set_option_path(default_file, "%s/%s", path, codec);
1809 return load_options(default_file, codec_options, len);
1812 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
1814 if( asset->format != FILE_FFMPEG ) return;
1815 if( text != asset->fformat )
1816 strcpy(asset->fformat, text);
1817 if( asset->audio_data && !asset->ff_audio_options[0] ) {
1818 if( !load_defaults("audio", text, asset->acodec,
1819 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
1820 scan_audio_options(asset, edl);
1822 asset->audio_data = 0;
1824 if( asset->video_data && !asset->ff_video_options[0] ) {
1825 if( !load_defaults("video", text, asset->vcodec,
1826 asset->ff_video_options, sizeof(asset->ff_video_options)) )
1827 scan_video_options(asset, edl);
1829 asset->video_data = 0;
1833 int FFMPEG::get_encoder(const char *options,
1834 char *format, char *codec, char *bsfilter)
1836 FILE *fp = fopen(options,"r");
1838 eprintf(_("options open failed %s\n"),options);
1841 char line[BCTEXTLEN];
1842 if( !fgets(line, sizeof(line), fp) ||
1843 scan_encoder(line, format, codec, bsfilter) )
1844 eprintf(_("format/codec not found %s\n"), options);
1849 int FFMPEG::scan_encoder(const char *line,
1850 char *format, char *codec, char *bsfilter)
1852 format[0] = codec[0] = bsfilter[0] = 0;
1853 if( scan_option_line(line, format, codec) ) return 1;
1855 while( *cp && *cp != '|' ) ++cp;
1856 if( !*cp ) return 0;
1858 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1859 while( *++cp && (*cp==' ' || *cp == '\t') );
1861 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1866 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1868 FILE *fp = fopen(options,"r");
1871 while( !ret && --skip >= 0 ) {
1873 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1874 if( ch < 0 ) ret = 1;
1877 ret = read_options(fp, options, opts);
1882 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1884 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1886 int ret = read_options(fp, options, opts);
1888 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1889 if( tag ) st->id = strtol(tag->value,0,0);
1893 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1895 int ret = 0, no = 0;
1896 char line[BCTEXTLEN];
1897 while( !ret && fgets(line, sizeof(line), fp) ) {
1898 line[sizeof(line)-1] = 0;
1899 if( line[0] == '#' ) continue;
1900 if( line[0] == '\n' ) continue;
1901 char key[BCSTRLEN], val[BCTEXTLEN];
1902 if( scan_option_line(line, key, val) ) {
1903 eprintf(_("err reading %s: line %d\n"), options, no);
1907 if( !strcmp(key, "duration") )
1908 opt_duration = strtod(val, 0);
1909 else if( !strcmp(key, "video_filter") )
1910 opt_video_filter = cstrdup(val);
1911 else if( !strcmp(key, "audio_filter") )
1912 opt_audio_filter = cstrdup(val);
1913 else if( !strcmp(key, "loglevel") )
1916 av_dict_set(&opts, key, val, 0);
1922 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1924 char option_path[BCTEXTLEN];
1925 set_option_path(option_path, "%s", options);
1926 return read_options(option_path, opts);
1929 int FFMPEG::load_options(const char *path, char *bfr, int len)
1932 FILE *fp = fopen(path, "r");
1934 fgets(bfr, len, fp); // skip hdr
1935 len = fread(bfr, 1, len-1, fp);
1936 if( len < 0 ) len = 0;
1942 void FFMPEG::set_loglevel(const char *ap)
1944 if( !ap || !*ap ) return;
1949 { "quiet" , AV_LOG_QUIET },
1950 { "panic" , AV_LOG_PANIC },
1951 { "fatal" , AV_LOG_FATAL },
1952 { "error" , AV_LOG_ERROR },
1953 { "warning", AV_LOG_WARNING },
1954 { "info" , AV_LOG_INFO },
1955 { "verbose", AV_LOG_VERBOSE },
1956 { "debug" , AV_LOG_DEBUG },
1958 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1959 if( !strcmp(log_levels[i].name, ap) ) {
1960 av_log_set_level(log_levels[i].level);
1964 av_log_set_level(atoi(ap));
1967 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1969 double base_time = time == AV_NOPTS_VALUE ? 0 :
1970 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1971 return base_time / AV_TIME_BASE;
1974 int FFMPEG::info(char *text, int len)
1976 if( len <= 0 ) return 0;
1978 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1980 report("format: %s\n",fmt_ctx->iformat->name);
1981 if( ffvideo.size() > 0 )
1982 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1983 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1984 FFVideoStream *vid = ffvideo[vidx];
1985 AVStream *st = vid->st;
1986 AVCodecID codec_id = st->codecpar->codec_id;
1987 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1988 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1989 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1990 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
1991 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
1992 const char *pfn = av_get_pix_fmt_name(pix_fmt);
1993 report(" pix %s\n", pfn ? pfn : "(unkn)");
1994 double secs = to_secs(st->duration, st->time_base);
1995 int64_t length = secs * vid->frame_rate + 0.5;
1996 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
1997 int64_t nudge = ofs * vid->frame_rate;
1998 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
1999 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2000 int hrs = secs/3600; secs -= hrs*3600;
2001 int mins = secs/60; secs -= mins*60;
2002 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2004 if( ffaudio.size() > 0 )
2005 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2006 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2007 FFAudioStream *aud = ffaudio[aidx];
2008 AVStream *st = aud->st;
2009 AVCodecID codec_id = st->codecpar->codec_id;
2010 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2011 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2012 int nch = aud->channels, ch0 = aud->channel0+1;
2013 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2014 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2015 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2016 report(" %s %d", fmt, aud->sample_rate);
2017 int sample_bits = av_get_bits_per_sample(codec_id);
2018 report(" %dbits\n", sample_bits);
2019 double secs = to_secs(st->duration, st->time_base);
2020 int64_t length = secs * aud->sample_rate + 0.5;
2021 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2022 int64_t nudge = ofs * aud->sample_rate;
2023 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2024 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2025 int hrs = secs/3600; secs -= hrs*3600;
2026 int mins = secs/60; secs -= mins*60;
2027 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2029 if( fmt_ctx->nb_programs > 0 )
2030 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2031 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2032 report("program %d", i+1);
2033 AVProgram *pgrm = fmt_ctx->programs[i];
2034 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2035 int idx = pgrm->stream_index[j];
2036 int vidx = ffvideo.size();
2037 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2039 report(", vid%d", vidx);
2042 int aidx = ffaudio.size();
2043 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2045 report(", aud%d", aidx);
2048 report(", (%d)", pgrm->stream_index[j]);
2053 AVDictionaryEntry *tag = 0;
2054 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2055 report("%s=%s\n", tag->key, tag->value);
2064 int FFMPEG::init_decoder(const char *filename)
2066 ff_lock("FFMPEG::init_decoder");
2068 char file_opts[BCTEXTLEN];
2069 strcpy(file_opts, filename);
2070 char *bp = strrchr(file_opts, '/');
2071 if( !bp ) bp = file_opts;
2072 char *sp = strrchr(bp, '.');
2073 if( !sp ) sp = bp + strlen(bp);
2075 AVInputFormat *ifmt = 0;
2077 strcpy(sp, ".opts");
2078 fp = fopen(file_opts, "r");
2081 read_options(fp, file_opts, opts);
2083 AVDictionaryEntry *tag;
2084 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2085 ifmt = av_find_input_format(tag->value);
2089 load_options("decode.opts", opts);
2090 AVDictionary *fopts = 0;
2091 av_dict_copy(&fopts, opts, 0);
2092 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2093 av_dict_free(&fopts);
2095 ret = avformat_find_stream_info(fmt_ctx, NULL);
2100 return !ret ? 0 : 1;
2103 int FFMPEG::open_decoder()
2106 if( stat(fmt_ctx->url, &st) < 0 ) {
2107 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2111 int64_t file_bits = 8 * st.st_size;
2112 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2113 fmt_ctx->bit_rate = file_bits / opt_duration;
2116 if( fmt_ctx->bit_rate > 0 ) {
2117 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2118 AVStream *st = fmt_ctx->streams[i];
2119 if( st->duration != AV_NOPTS_VALUE ) continue;
2120 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2121 st->duration = av_rescale(file_bits, st->time_base.den,
2122 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2126 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2127 fflags |= FF_ESTM_TIMES;
2128 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2132 ff_lock("FFMPEG::open_decoder");
2133 int ret = 0, bad_time = 0;
2134 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2135 AVStream *st = fmt_ctx->streams[i];
2136 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2137 AVCodecParameters *avpar = st->codecpar;
2138 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2139 if( !codec_desc ) continue;
2140 switch( avpar->codec_type ) {
2141 case AVMEDIA_TYPE_VIDEO: {
2142 if( avpar->width < 1 ) continue;
2143 if( avpar->height < 1 ) continue;
2144 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2145 if( framerate.num < 1 ) continue;
2147 int vidx = ffvideo.size();
2148 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2149 vstrm_index.append(ffidx(vidx, 0));
2150 ffvideo.append(vid);
2151 vid->width = avpar->width;
2152 vid->height = avpar->height;
2153 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2154 double secs = to_secs(st->duration, st->time_base);
2155 vid->length = secs * vid->frame_rate;
2156 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2157 vid->nudge = st->start_time;
2159 if( opt_video_filter )
2160 ret = vid->create_filter(opt_video_filter, avpar);
2162 case AVMEDIA_TYPE_AUDIO: {
2163 if( avpar->channels < 1 ) continue;
2164 if( avpar->sample_rate < 1 ) continue;
2166 int aidx = ffaudio.size();
2167 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2168 ffaudio.append(aud);
2169 aud->channel0 = astrm_index.size();
2170 aud->channels = avpar->channels;
2171 for( int ch=0; ch<aud->channels; ++ch )
2172 astrm_index.append(ffidx(aidx, ch));
2173 aud->sample_rate = avpar->sample_rate;
2174 double secs = to_secs(st->duration, st->time_base);
2175 aud->length = secs * aud->sample_rate;
2176 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2177 aud->nudge = st->start_time;
2179 if( opt_audio_filter )
2180 ret = aud->create_filter(opt_audio_filter, avpar);
2185 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2186 fflags |= FF_BAD_TIMES;
2187 printf("FFMPEG::open_decoder: some stream have bad times: %s\n",
2191 return ret < 0 ? -1 : 0;
2195 int FFMPEG::init_encoder(const char *filename)
2197 // try access first for named pipes
2198 int ret = access(filename, W_OK);
2200 int fd = ::open(filename,O_WRONLY);
2201 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2202 if( fd >= 0 ) { close(fd); ret = 0; }
2205 eprintf(_("bad file path: %s\n"), filename);
2208 ret = get_file_format();
2210 eprintf(_("bad file format: %s\n"), filename);
2214 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2217 ff_lock("FFMPEG::init_encoder");
2219 char format[BCSTRLEN];
2220 if( get_format(format, "format", file_format) )
2221 strcpy(format, file_format);
2222 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2224 eprintf(_("failed: %s\n"), filename);
2229 load_options("encode.opts", opts);
2235 int FFMPEG::open_encoder(const char *type, const char *spec)
2238 Asset *asset = file_base->asset;
2239 char *filename = asset->path;
2240 AVDictionary *sopts = 0;
2241 av_dict_copy(&sopts, opts, 0);
2242 char option_path[BCTEXTLEN];
2243 set_option_path(option_path, "%s/%s.opts", type, type);
2244 read_options(option_path, sopts);
2245 get_option_path(option_path, type, spec);
2246 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2247 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2248 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2253 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2255 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2256 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2259 ff_lock("FFMPEG::open_encoder");
2262 AVCodecContext *ctx = 0;
2264 const AVCodecDescriptor *codec_desc = 0;
2265 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2267 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2271 codec_desc = avcodec_descriptor_get(codec->id);
2273 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2278 st = avformat_new_stream(fmt_ctx, 0);
2280 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2285 switch( codec_desc->type ) {
2286 case AVMEDIA_TYPE_AUDIO: {
2288 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2292 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2293 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2298 ctx = avcodec_alloc_context3(codec);
2299 if( asset->ff_audio_bitrate > 0 ) {
2300 ctx->bit_rate = asset->ff_audio_bitrate;
2302 sprintf(arg, "%d", asset->ff_audio_bitrate);
2303 av_dict_set(&sopts, "b", arg, 0);
2305 else if( asset->ff_audio_quality >= 0 ) {
2306 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2307 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2308 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2309 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2310 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2312 av_dict_set(&sopts, "flags", "+qscale", 0);
2313 sprintf(arg, "%d", asset->ff_audio_quality);
2314 av_dict_set(&sopts, "qscale", arg, 0);
2315 sprintf(arg, "%d", ctx->global_quality);
2316 av_dict_set(&sopts, "global_quality", arg, 0);
2318 int aidx = ffaudio.size();
2319 int fidx = aidx + ffvideo.size();
2320 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2321 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2322 aud->sample_rate = asset->sample_rate;
2323 ctx->channels = aud->channels = asset->channels;
2324 for( int ch=0; ch<aud->channels; ++ch )
2325 astrm_index.append(ffidx(aidx, ch));
2326 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2327 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2328 if( !ctx->sample_rate ) {
2329 eprintf(_("check_sample_rate failed %s\n"), filename);
2333 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2334 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2335 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2336 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2337 ctx->sample_fmt = sample_fmt;
2338 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2339 aud->resample_context = swr_alloc_set_opts(NULL,
2340 layout, ctx->sample_fmt, aud->sample_rate,
2341 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2343 swr_init(aud->resample_context);
2346 case AVMEDIA_TYPE_VIDEO: {
2348 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2352 if( scan_options(asset->ff_video_options, sopts, st) ) {
2353 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2358 ctx = avcodec_alloc_context3(codec);
2359 if( asset->ff_video_bitrate > 0 ) {
2360 ctx->bit_rate = asset->ff_video_bitrate;
2362 sprintf(arg, "%d", asset->ff_video_bitrate);
2363 av_dict_set(&sopts, "b", arg, 0);
2365 else if( asset->ff_video_quality >= 0 ) {
2366 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2367 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2368 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2369 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2370 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2372 av_dict_set(&sopts, "flags", "+qscale", 0);
2373 sprintf(arg, "%d", asset->ff_video_quality);
2374 av_dict_set(&sopts, "qscale", arg, 0);
2375 sprintf(arg, "%d", ctx->global_quality);
2376 av_dict_set(&sopts, "global_quality", arg, 0);
2378 int vidx = ffvideo.size();
2379 int fidx = vidx + ffaudio.size();
2380 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2381 vstrm_index.append(ffidx(vidx, 0));
2382 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2383 vid->width = asset->width;
2384 vid->height = asset->height;
2385 vid->frame_rate = asset->frame_rate;
2387 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2388 if( pix_fmt == AV_PIX_FMT_NONE )
2389 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2390 ctx->pix_fmt = pix_fmt;
2391 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2392 int mask_w = (1<<desc->log2_chroma_w)-1;
2393 ctx->width = (vid->width+mask_w) & ~mask_w;
2394 int mask_h = (1<<desc->log2_chroma_h)-1;
2395 ctx->height = (vid->height+mask_h) & ~mask_h;
2396 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2397 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2398 if( !frame_rate.num || !frame_rate.den ) {
2399 eprintf(_("check_frame_rate failed %s\n"), filename);
2403 av_reduce(&frame_rate.num, &frame_rate.den,
2404 frame_rate.num, frame_rate.den, INT_MAX);
2405 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2406 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2407 st->avg_frame_rate = frame_rate;
2408 st->time_base = ctx->time_base;
2410 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2411 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2412 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2415 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2420 AVDictionaryEntry *tag;
2421 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2422 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2423 fst->stats_filename = cstrcat(2, tag->value, suffix);
2425 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2426 int pass = fst->pass;
2427 char *cp = tag->value;
2429 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2430 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2431 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2432 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2433 if( bp < ep ) *bp++ = ch;
2435 if( !strcmp(id, "pass1") ) {
2436 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2438 else if( !strcmp(id, "pass2") ) {
2439 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2442 if( (fst->pass=pass) ) {
2443 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2444 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2450 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2451 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2452 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2453 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2456 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2457 av_dict_set(&sopts, "cin_quality", 0, 0);
2459 if( !av_dict_get(sopts, "threads", NULL, 0) )
2460 ctx->thread_count = ff_cpus();
2461 ret = avcodec_open2(ctx, codec, &sopts);
2463 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2465 fprintf(stderr, "Could not copy the stream parameters\n");
2468 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2469 ret = avcodec_copy_context(st->codec, ctx);
2470 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2472 fprintf(stderr, "Could not copy the stream context\n");
2475 ff_err(ret,"FFMPEG::open_encoder");
2476 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2482 if( !ret && fst && bsfilter[0] ) {
2483 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2485 ff_err(ret,"FFMPEG::open_encoder");
2486 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2497 av_dict_free(&sopts);
2501 int FFMPEG::close_encoder()
2504 if( encoding > 0 ) {
2505 av_write_trailer(fmt_ctx);
2506 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2507 avio_closep(&fmt_ctx->pb);
2513 int FFMPEG::decode_activate()
2515 if( decoding < 0 ) {
2517 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2518 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2519 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2520 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2521 // set nudges for each program stream set
2522 const int64_t min_nudge = INT64_MIN+1;
2523 int npgrms = fmt_ctx->nb_programs;
2524 for( int i=0; i<npgrms; ++i ) {
2525 AVProgram *pgrm = fmt_ctx->programs[i];
2526 // first start time video stream
2527 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2528 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2529 int fidx = pgrm->stream_index[j];
2530 AVStream *st = fmt_ctx->streams[fidx];
2531 AVCodecParameters *avpar = st->codecpar;
2532 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2533 if( st->start_time == AV_NOPTS_VALUE ) continue;
2534 if( vstart_time < st->start_time )
2535 vstart_time = st->start_time;
2538 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2539 if( st->start_time == AV_NOPTS_VALUE ) continue;
2540 if( astart_time < st->start_time )
2541 astart_time = st->start_time;
2545 //since frame rate is much more grainy than sample rate, it is better to
2546 // align using video, so that total absolute error is minimized.
2547 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2548 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2549 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2550 int fidx = pgrm->stream_index[j];
2551 AVStream *st = fmt_ctx->streams[fidx];
2552 AVCodecParameters *avpar = st->codecpar;
2553 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2554 for( int k=0; k<ffvideo.size(); ++k ) {
2555 if( ffvideo[k]->fidx != fidx ) continue;
2556 ffvideo[k]->nudge = nudge;
2560 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2561 for( int k=0; k<ffaudio.size(); ++k ) {
2562 if( ffaudio[k]->fidx != fidx ) continue;
2563 ffaudio[k]->nudge = nudge;
2569 // set nudges for any streams not yet set
2570 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2571 int nstreams = fmt_ctx->nb_streams;
2572 for( int i=0; i<nstreams; ++i ) {
2573 AVStream *st = fmt_ctx->streams[i];
2574 AVCodecParameters *avpar = st->codecpar;
2575 switch( avpar->codec_type ) {
2576 case AVMEDIA_TYPE_VIDEO: {
2577 if( st->start_time == AV_NOPTS_VALUE ) continue;
2578 int vidx = ffvideo.size();
2579 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2580 if( vidx < 0 ) continue;
2581 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2582 if( vstart_time < st->start_time )
2583 vstart_time = st->start_time;
2585 case AVMEDIA_TYPE_AUDIO: {
2586 if( st->start_time == AV_NOPTS_VALUE ) continue;
2587 int aidx = ffaudio.size();
2588 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2589 if( aidx < 0 ) continue;
2590 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2591 ffaudio[aidx]->frame_sz = avpar->frame_size;
2592 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2593 if( astart_time < st->start_time )
2594 astart_time = st->start_time;
2599 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2600 astart_time > min_nudge ? astart_time : 0;
2601 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2602 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2603 ffvideo[vidx]->nudge = nudge;
2605 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2606 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2607 ffaudio[aidx]->nudge = nudge;
2614 int FFMPEG::encode_activate()
2617 if( encoding < 0 ) {
2619 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2620 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2621 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2627 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2628 for( int i=0; i< ffvideo.size(); ++i )
2629 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2630 for( int i=0; i< ffaudio.size(); ++i )
2631 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2632 int pi = fmt_ctx->nb_programs;
2633 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2634 AVDictionary **meta = &prog->metadata;
2635 av_dict_set(meta, "service_provider", "cin5", 0);
2636 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2637 if( bp ) path = bp + 1;
2638 av_dict_set(meta, "title", path, 0);
2640 if( ffaudio.size() ) {
2641 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2642 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2643 static struct { const char lc[3], lng[4]; } lcode[] = {
2644 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2645 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2646 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2647 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2648 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2649 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2651 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2652 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2654 if( !ep ) ep = "und";
2656 strncpy(lang,ep,3); lang[3] = 0;
2657 AVStream *st = ffaudio[0]->st;
2658 av_dict_set(&st->metadata,"language",lang,0);
2661 AVDictionary *fopts = 0;
2662 char option_path[BCTEXTLEN];
2663 set_option_path(option_path, "format/%s", file_format);
2664 read_options(option_path, fopts, 1);
2665 ret = avformat_write_header(fmt_ctx, &fopts);
2667 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2671 av_dict_free(&fopts);
2678 int FFMPEG::audio_seek(int stream, int64_t pos)
2680 int aidx = astrm_index[stream].st_idx;
2681 FFAudioStream *aud = ffaudio[aidx];
2682 aud->audio_seek(pos);
2686 int FFMPEG::video_seek(int stream, int64_t pos)
2688 int vidx = vstrm_index[stream].st_idx;
2689 FFVideoStream *vid = ffvideo[vidx];
2690 vid->video_seek(pos);
2695 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2697 if( !has_audio || chn >= astrm_index.size() ) return -1;
2698 int aidx = astrm_index[chn].st_idx;
2699 FFAudioStream *aud = ffaudio[aidx];
2700 if( aud->load(pos, len) < len ) return -1;
2701 int ch = astrm_index[chn].st_ch;
2702 int ret = aud->read(samples,len,ch);
2706 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2708 if( !has_video || layer >= vstrm_index.size() ) return -1;
2709 int vidx = vstrm_index[layer].st_idx;
2710 FFVideoStream *vid = ffvideo[vidx];
2711 return vid->load(vframe, pos);
2715 int FFMPEG::encode(int stream, double **samples, int len)
2717 FFAudioStream *aud = ffaudio[stream];
2718 return aud->encode(samples, len);
2722 int FFMPEG::encode(int stream, VFrame *frame)
2724 FFVideoStream *vid = ffvideo[stream];
2725 return vid->encode(frame);
2728 void FFMPEG::start_muxer()
2736 void FFMPEG::stop_muxer()
2745 void FFMPEG::flow_off()
2748 flow_lock->lock("FFMPEG::flow_off");
2752 void FFMPEG::flow_on()
2756 flow_lock->unlock();
2759 void FFMPEG::flow_ctl()
2762 flow_lock->lock("FFMPEG::flow_ctl");
2763 flow_lock->unlock();
2767 int FFMPEG::mux_audio(FFrame *frm)
2769 FFStream *fst = frm->fst;
2770 AVCodecContext *ctx = fst->avctx;
2771 AVFrame *frame = *frm;
2772 AVRational tick_rate = {1, ctx->sample_rate};
2773 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2774 int ret = fst->encode_frame(frame);
2776 ff_err(ret, "FFMPEG::mux_audio");
2777 return ret >= 0 ? 0 : 1;
2780 int FFMPEG::mux_video(FFrame *frm)
2782 FFStream *fst = frm->fst;
2783 AVFrame *frame = *frm;
2784 frame->pts = frm->position;
2785 int ret = fst->encode_frame(frame);
2787 ff_err(ret, "FFMPEG::mux_video");
2788 return ret >= 0 ? 0 : 1;
2794 double atm = -1, vtm = -1;
2795 FFrame *afrm = 0, *vfrm = 0;
2797 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2798 FFStream *fst = ffaudio[i];
2799 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2800 FFrame *frm = fst->frms.first;
2801 if( !frm ) { if( !done ) return; continue; }
2802 double tm = to_secs(frm->position, fst->avctx->time_base);
2803 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2805 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2806 FFStream *fst = ffvideo[i];
2807 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2808 FFrame *frm = fst->frms.first;
2809 if( !frm ) { if( !done ) return; continue; }
2810 double tm = to_secs(frm->position, fst->avctx->time_base);
2811 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2813 if( !demand ) flow_off();
2814 if( !afrm && !vfrm ) break;
2815 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2816 vfrm->position, vfrm->fst->avctx->time_base,
2817 afrm->position, afrm->fst->avctx->time_base);
2818 FFrame *frm = v <= 0 ? vfrm : afrm;
2819 if( frm == afrm ) mux_audio(frm);
2820 if( frm == vfrm ) mux_video(frm);
2829 mux_lock->lock("FFMPEG::run");
2832 for( int i=0; i<ffaudio.size(); ++i )
2833 ffaudio[i]->drain();
2834 for( int i=0; i<ffvideo.size(); ++i )
2835 ffvideo[i]->drain();
2837 for( int i=0; i<ffaudio.size(); ++i )
2838 ffaudio[i]->flush();
2839 for( int i=0; i<ffvideo.size(); ++i )
2840 ffvideo[i]->flush();
2844 int FFMPEG::ff_total_audio_channels()
2846 return astrm_index.size();
2849 int FFMPEG::ff_total_astreams()
2851 return ffaudio.size();
2854 int FFMPEG::ff_audio_channels(int stream)
2856 return ffaudio[stream]->channels;
2859 int FFMPEG::ff_sample_rate(int stream)
2861 return ffaudio[stream]->sample_rate;
2864 const char* FFMPEG::ff_audio_format(int stream)
2866 AVStream *st = ffaudio[stream]->st;
2867 AVCodecID id = st->codecpar->codec_id;
2868 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2869 return desc ? desc->name : _("Unknown");
2872 int FFMPEG::ff_audio_pid(int stream)
2874 return ffaudio[stream]->st->id;
2877 int64_t FFMPEG::ff_audio_samples(int stream)
2879 return ffaudio[stream]->length;
2882 // find audio astream/channels with this program,
2883 // or all program audio channels (astream=-1)
2884 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2888 int vidx = ffvideo[vstream]->fidx;
2889 // find first program with this video stream
2890 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2891 AVProgram *pgrm = fmt_ctx->programs[i];
2892 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2893 int st_idx = pgrm->stream_index[j];
2894 AVStream *st = fmt_ctx->streams[st_idx];
2895 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2896 if( st_idx == vidx ) pidx = i;
2899 if( pidx < 0 ) return -1;
2901 int64_t channels = 0;
2902 AVProgram *pgrm = fmt_ctx->programs[pidx];
2903 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2904 int aidx = pgrm->stream_index[j];
2905 AVStream *st = fmt_ctx->streams[aidx];
2906 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2907 if( astream > 0 ) { --astream; continue; }
2909 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2910 if( ffaudio[i]->fidx == aidx ) astrm = i;
2912 if( ret < 0 ) ret = astrm;
2913 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2914 channels |= mask << ffaudio[astrm]->channel0;
2916 if( !astream ) break;
2918 channel_mask = channels;
2923 int FFMPEG::ff_total_video_layers()
2925 return vstrm_index.size();
2928 int FFMPEG::ff_total_vstreams()
2930 return ffvideo.size();
2933 int FFMPEG::ff_video_width(int stream)
2935 return ffvideo[stream]->width;
2938 int FFMPEG::ff_video_height(int stream)
2940 return ffvideo[stream]->height;
2943 int FFMPEG::ff_set_video_width(int stream, int width)
2945 int w = ffvideo[stream]->width;
2946 ffvideo[stream]->width = width;
2950 int FFMPEG::ff_set_video_height(int stream, int height)
2952 int h = ffvideo[stream]->height;
2953 ffvideo[stream]->height = height;
2957 int FFMPEG::ff_coded_width(int stream)
2959 return ffvideo[stream]->avctx->coded_width;
2962 int FFMPEG::ff_coded_height(int stream)
2964 return ffvideo[stream]->avctx->coded_height;
2967 float FFMPEG::ff_aspect_ratio(int stream)
2969 return ffvideo[stream]->aspect_ratio;
2972 const char* FFMPEG::ff_video_format(int stream)
2974 AVStream *st = ffvideo[stream]->st;
2975 AVCodecID id = st->codecpar->codec_id;
2976 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2977 return desc ? desc->name : _("Unknown");
2980 double FFMPEG::ff_frame_rate(int stream)
2982 return ffvideo[stream]->frame_rate;
2985 int64_t FFMPEG::ff_video_frames(int stream)
2987 return ffvideo[stream]->length;
2990 int FFMPEG::ff_video_pid(int stream)
2992 return ffvideo[stream]->st->id;
2995 int FFMPEG::ff_video_mpeg_color_range(int stream)
2997 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3000 int FFMPEG::ff_cpus()
3002 return file_base->file->cpus;
3005 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3007 avfilter_register_all();
3008 const char *sp = filter_spec;
3009 char filter_name[BCSTRLEN], *np = filter_name;
3010 int i = sizeof(filter_name);
3011 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3013 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3014 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3015 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3018 filter_graph = avfilter_graph_alloc();
3019 const AVFilter *buffersrc = avfilter_get_by_name("buffer");
3020 const AVFilter *buffersink = avfilter_get_by_name("buffersink");
3022 int ret = 0; char args[BCTEXTLEN];
3023 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3024 snprintf(args, sizeof(args),
3025 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3026 avpar->width, avpar->height, (int)pix_fmt,
3027 st->time_base.num, st->time_base.den,
3028 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
3030 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3031 args, NULL, filter_graph);
3033 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3034 NULL, NULL, filter_graph);
3036 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3037 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3038 AV_OPT_SEARCH_CHILDREN);
3040 ff_err(ret, "FFVideoStream::create_filter");
3042 ret = FFStream::create_filter(filter_spec);
3043 return ret >= 0 ? 0 : -1;
3046 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3048 avfilter_register_all();
3049 const char *sp = filter_spec;
3050 char filter_name[BCSTRLEN], *np = filter_name;
3051 int i = sizeof(filter_name);
3052 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3054 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3055 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3056 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3059 filter_graph = avfilter_graph_alloc();
3060 const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
3061 const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
3062 int ret = 0; char args[BCTEXTLEN];
3063 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3064 snprintf(args, sizeof(args),
3065 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3066 st->time_base.num, st->time_base.den, avpar->sample_rate,
3067 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3069 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3070 args, NULL, filter_graph);
3072 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3073 NULL, NULL, filter_graph);
3075 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3076 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3077 AV_OPT_SEARCH_CHILDREN);
3079 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3080 (uint8_t*)&avpar->channel_layout,
3081 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3083 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3084 (uint8_t*)&sample_rate, sizeof(sample_rate),
3085 AV_OPT_SEARCH_CHILDREN);
3087 ff_err(ret, "FFAudioStream::create_filter");
3089 ret = FFStream::create_filter(filter_spec);
3090 return ret >= 0 ? 0 : -1;
3093 int FFStream::create_filter(const char *filter_spec)
3095 /* Endpoints for the filter graph. */
3096 AVFilterInOut *outputs = avfilter_inout_alloc();
3097 outputs->name = av_strdup("in");
3098 outputs->filter_ctx = buffersrc_ctx;
3099 outputs->pad_idx = 0;
3102 AVFilterInOut *inputs = avfilter_inout_alloc();
3103 inputs->name = av_strdup("out");
3104 inputs->filter_ctx = buffersink_ctx;
3105 inputs->pad_idx = 0;
3108 int ret = !outputs->name || !inputs->name ? -1 : 0;
3110 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
3111 &inputs, &outputs, NULL);
3113 ret = avfilter_graph_config(filter_graph, NULL);
3116 ff_err(ret, "FFStream::create_filter");
3117 avfilter_graph_free(&filter_graph);
3120 avfilter_inout_free(&inputs);
3121 avfilter_inout_free(&outputs);
3125 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3128 av_init_packet(&pkt);
3129 AVFrame *frame = av_frame_alloc();
3131 fprintf(stderr,"FFMPEG::scan: ");
3132 fprintf(stderr,_("av_frame_alloc failed\n"));
3133 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3137 index_state->add_video_markers(ffvideo.size());
3138 index_state->add_audio_markers(ffaudio.size());
3140 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3142 AVDictionary *copts = 0;
3143 av_dict_copy(&copts, opts, 0);
3144 AVStream *st = fmt_ctx->streams[i];
3145 AVCodecID codec_id = st->codecpar->codec_id;
3146 AVCodec *decoder = avcodec_find_decoder(codec_id);
3147 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3149 eprintf(_("cant allocate codec context\n"));
3150 ret = AVERROR(ENOMEM);
3153 avcodec_parameters_to_context(avctx, st->codecpar);
3154 if( !av_dict_get(copts, "threads", NULL, 0) )
3155 avctx->thread_count = ff_cpus();
3156 ret = avcodec_open2(avctx, decoder, &copts);
3158 av_dict_free(&copts);
3160 AVCodecParameters *avpar = st->codecpar;
3161 switch( avpar->codec_type ) {
3162 case AVMEDIA_TYPE_VIDEO: {
3163 int vidx = ffvideo.size();
3164 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3165 if( vidx < 0 ) break;
3166 ffvideo[vidx]->avctx = avctx;
3168 case AVMEDIA_TYPE_AUDIO: {
3169 int aidx = ffaudio.size();
3170 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3171 if( aidx < 0 ) break;
3172 ffaudio[aidx]->avctx = avctx;
3177 fprintf(stderr,"FFMPEG::scan: ");
3178 fprintf(stderr,_("codec open failed\n"));
3179 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3180 avcodec_free_context(&avctx);
3184 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3185 AVStream *st = fmt_ctx->streams[i];
3186 AVCodecParameters *avpar = st->codecpar;
3187 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3188 int64_t tstmp = st->start_time;
3189 if( tstmp == AV_NOPTS_VALUE ) continue;
3190 int aidx = ffaudio.size();
3191 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3192 if( aidx < 0 ) continue;
3193 FFAudioStream *aud = ffaudio[aidx];
3194 tstmp -= aud->nudge;
3195 double secs = to_secs(tstmp, st->time_base);
3196 aud->curr_pos = secs * aud->sample_rate + 0.5;
3200 for( int64_t count=0; !*canceled; ++count ) {
3201 av_packet_unref(&pkt);
3202 pkt.data = 0; pkt.size = 0;
3204 int ret = av_read_frame(fmt_ctx, &pkt);
3206 if( ret == AVERROR_EOF ) break;
3207 if( ++errs > 100 ) {
3208 ff_err(ret,_("over 100 read_frame errs\n"));
3213 if( !pkt.data ) continue;
3214 int i = pkt.stream_index;
3215 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3216 AVStream *st = fmt_ctx->streams[i];
3217 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3219 AVCodecParameters *avpar = st->codecpar;
3220 switch( avpar->codec_type ) {
3221 case AVMEDIA_TYPE_VIDEO: {
3222 int vidx = ffvideo.size();
3223 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3224 if( vidx < 0 ) break;
3225 FFVideoStream *vid = ffvideo[vidx];
3226 if( !vid->avctx ) break;
3227 int64_t tstmp = pkt.dts;
3228 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3229 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3230 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3231 double secs = to_secs(tstmp, st->time_base);
3232 int64_t frm = secs * vid->frame_rate + 0.5;
3233 if( frm < 0 ) frm = 0;
3234 index_state->put_video_mark(vidx, frm, pkt.pos);
3237 ret = avcodec_send_packet(vid->avctx, pkt);
3238 if( ret < 0 ) break;
3239 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3242 case AVMEDIA_TYPE_AUDIO: {
3243 int aidx = ffaudio.size();
3244 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3245 if( aidx < 0 ) break;
3246 FFAudioStream *aud = ffaudio[aidx];
3247 if( !aud->avctx ) break;
3248 int64_t tstmp = pkt.pts;
3249 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3250 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3251 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3252 double secs = to_secs(tstmp, st->time_base);
3253 int64_t sample = secs * aud->sample_rate + 0.5;
3255 index_state->put_audio_mark(aidx, sample, pkt.pos);
3257 ret = avcodec_send_packet(aud->avctx, &pkt);
3258 if( ret < 0 ) break;
3259 int ch = aud->channel0, nch = aud->channels;
3260 int64_t pos = index_state->pos(ch);
3261 if( pos != aud->curr_pos ) {
3262 if( abs(pos-aud->curr_pos) > 1 )
3263 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3264 index_state->pad_data(ch, nch, aud->curr_pos);
3266 while( (ret=aud->decode_frame(frame)) > 0 ) {
3267 //if( frame->channels != nch ) break;
3268 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3270 int len = aud->get_samples(samples,
3271 &frame->extended_data[0], frame->nb_samples);
3272 pos = aud->curr_pos;
3273 if( (aud->curr_pos += len) >= 0 ) {
3275 samples += -pos * nch;
3276 len = aud->curr_pos;
3278 for( int i=0; i<nch; ++i )
3279 index_state->put_data(ch+i,nch,samples+i,len);
3286 av_frame_free(&frame);
3290 void FFStream::load_markers(IndexMarks &marks, double rate)
3293 int64_t sz = marks.size();
3294 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3295 int nb_ent = st->nb_index_entries;
3296 // some formats already have an index
3298 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3299 int64_t tstmp = ep->timestamp;
3300 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3301 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3302 int64_t no = secs * rate;
3303 while( in < sz && marks[in].no <= no ) ++in;
3305 int64_t len = sz - in;
3306 int64_t count = max_entries - nb_ent;
3307 if( count > len ) count = len;
3308 for( int i=0; i<count; ++i ) {
3309 int k = in + i * len / count;
3310 int64_t no = marks[k].no, pos = marks[k].pos;
3311 double secs = (double)no / rate;
3312 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3313 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3314 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);