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"
36 #include "preferences.h"
42 #define av_register_all(s)
43 #define avfilter_register_all(s)
46 #define VIDEO_INBUF_SIZE 0x10000
47 #define AUDIO_INBUF_SIZE 0x10000
48 #define VIDEO_REFILL_THRESH 0
49 #define AUDIO_REFILL_THRESH 0x1000
50 #define AUDIO_MIN_FRAME_SZ 128
52 #define FF_ESTM_TIMES 0x0001
53 #define FF_BAD_TIMES 0x0002
55 Mutex FFMPEG::fflock("FFMPEG::fflock");
57 static void ff_err(int ret, const char *fmt, ...)
62 vsnprintf(msg, sizeof(msg), fmt, ap);
64 char errmsg[BCSTRLEN];
65 av_strerror(ret, errmsg, sizeof(errmsg));
66 fprintf(stderr,_("%s err: %s\n"),msg, errmsg);
72 pkt.data = 0; pkt.size = 0;
74 void FFPacket::finit()
76 av_packet_unref(&pkt);
79 FFrame::FFrame(FFStream *fst)
82 frm = av_frame_alloc();
83 init = fst->init_frame(frm);
91 void FFrame::queue(int64_t pos)
97 void FFrame::dequeue()
102 int FFAudioStream::read(float *fp, long len)
110 while( --k >= 0 ) *fp++ = *op++;
111 if( op >= lmt ) op = bfr;
116 void FFAudioStream::realloc(long nsz, int nch, long len)
118 long bsz = nsz * nch;
119 float *np = new float[bsz];
120 inp = np + read(np, len) * nch;
125 delete [] bfr; bfr = np;
128 void FFAudioStream::realloc(long nsz, int nch)
130 if( nsz > sz || this->nch != nch ) {
131 long len = this->nch != nch ? 0 : hpos;
132 if( len > sz ) len = sz;
134 realloc(nsz, nch, len);
138 void FFAudioStream::reserve(long nsz, int nch)
140 long len = (inp - outp) / nch;
142 if( nsz > sz || this->nch != nch ) {
143 if( this->nch != nch ) len = 0;
144 realloc(nsz, nch, len);
147 if( (len*=nch) > 0 && bfr != outp )
148 memmove(bfr, outp, len*sizeof(*bfr));
153 long FFAudioStream::used()
155 long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
158 long FFAudioStream::avail()
161 if( in1 >= lmt ) in1 = bfr;
162 long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
165 void FFAudioStream::reset_history()
169 memset(bfr, 0, lmt-bfr);
172 void FFAudioStream::iseek(int64_t ofs)
174 if( ofs > hpos ) ofs = hpos;
175 if( ofs > sz ) ofs = sz;
176 outp = inp - ofs*nch;
177 if( outp < bfr ) outp += sz*nch;
180 float *FFAudioStream::get_outp(int ofs)
187 int64_t FFAudioStream::put_inp(int ofs)
190 return (inp-outp) / nch;
193 int FFAudioStream::write(const float *fp, long len)
201 while( --k >= 0 ) *ip++ = *fp++;
202 if( ip >= lmt ) ip = bfr;
209 int FFAudioStream::zero(long len)
217 while( --k >= 0 ) *ip++ = 0;
218 if( ip >= lmt ) ip = bfr;
225 // does not advance outp
226 int FFAudioStream::read(double *dp, long len, int ch)
229 float *op = outp + ch;
230 float *lmt1 = lmt + nch-1;
232 int k = (lmt1 - op) / nch;
235 while( --k >= 0 ) { *dp++ = *op; op += nch; }
236 if( op >= lmt ) op -= sz*nch;
241 // load linear buffer, no wrapping allowed, does not advance inp
242 int FFAudioStream::write(const double *dp, long len, int ch)
245 float *ip = inp + ch;
246 while( --n >= 0 ) { *ip = *dp++; ip += nch; }
251 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
253 this->ffmpeg = ffmpeg;
256 frm_lock = new Mutex("FFStream::frm_lock");
263 nudge = AV_NOPTS_VALUE;
264 seek_pos = curr_pos = 0;
266 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 = ffmpeg->opt_hw_dev;
1005 if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1006 if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1007 if( hw_dev && *hw_dev && strcmp(_("none"), hw_dev) ) {
1008 type = av_hwdevice_find_type_by_name(hw_dev);
1009 if( type == AV_HWDEVICE_TYPE_NONE ) {
1010 fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1011 fprintf(stderr, "Available device types:");
1012 while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1013 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1014 fprintf(stderr, "\n");
1020 void FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1022 hw_pix_fmt = AV_PIX_FMT_NONE;
1023 for( int i=0; ; ++i ) {
1024 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1026 fprintf(stderr, "Decoder %s does not support device type %s.\n",
1027 decoder->name, av_hwdevice_get_type_name(type));
1030 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1031 config->device_type == type ) {
1032 hw_pix_fmt = config->pix_fmt;
1036 if( hw_pix_fmt >= 0 ) {
1037 hw_pixfmt = hw_pix_fmt;
1038 avctx->get_format = get_hw_format;
1039 int ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1041 avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1043 ff_err(ret, "Failed HW device create.\ndev:%s\n",
1044 av_hwdevice_get_type_name(type));
1048 int FFVideoStream::decode_frame(AVFrame *frame)
1050 int first_frame = seeked; seeked = 0;
1051 int ret = avcodec_receive_frame(avctx, frame);
1053 if( first_frame || ret == AVERROR(EAGAIN) ) return 0;
1054 if( ret == AVERROR(EAGAIN) ) return 0;
1055 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1056 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1057 ffmpeg->fmt_ctx->url);
1060 int64_t pkt_ts = frame->best_effort_timestamp;
1061 if( pkt_ts != AV_NOPTS_VALUE )
1062 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1066 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1068 int ret = video_seek(pos);
1069 if( ret < 0 ) return -1;
1070 if( !frame && !(frame=av_frame_alloc()) ) {
1071 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1074 int i = MAX_RETRY + pos - curr_pos;
1075 while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1076 ret = read_frame(frame);
1077 if( ret > 0 ) ++curr_pos;
1079 if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1082 ret = convert_cmodel(vframe, frame);
1084 ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1088 int FFVideoStream::video_seek(int64_t pos)
1090 if( decode_activate() <= 0 ) return -1;
1091 if( !st->codecpar ) return -1;
1092 if( pos == curr_pos-1 && !seeked ) return 0;
1093 // if close enough, just read up to current
1094 int gop = avctx->gop_size;
1095 if( gop < 4 ) gop = 4;
1096 if( gop > 64 ) gop = 64;
1097 int read_limit = curr_pos + 3*gop;
1098 if( pos >= curr_pos && pos <= read_limit ) return 0;
1099 // guarentee preload more than 2*gop frames
1100 if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1104 int FFVideoStream::init_frame(AVFrame *picture)
1106 picture->format = avctx->pix_fmt;
1107 picture->width = avctx->width;
1108 picture->height = avctx->height;
1109 int ret = av_frame_get_buffer(picture, 32);
1113 int FFVideoStream::encode(VFrame *vframe)
1115 if( encode_activate() <= 0 ) return -1;
1117 FFrame *picture = new FFrame(this);
1118 int ret = picture->initted();
1120 AVFrame *frame = *picture;
1121 frame->pts = curr_pos;
1122 ret = convert_pixfmt(vframe, frame);
1125 picture->queue(curr_pos);
1129 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1132 return ret >= 0 ? 0 : 1;
1135 int FFVideoStream::drain()
1140 int FFVideoStream::encode_frame(AVFrame *frame)
1143 frame->interlaced_frame = interlaced;
1144 frame->top_field_first = top_field_first;
1146 return FFStream::encode_frame(frame);
1149 int FFVideoStream::write_packet(FFPacket &pkt)
1151 if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1153 return FFStream::write_packet(pkt);
1156 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1158 switch( color_model ) {
1159 case BC_YUV422: return AV_PIX_FMT_YUYV422;
1160 case BC_RGB888: return AV_PIX_FMT_RGB24;
1161 case BC_RGBA8888: return AV_PIX_FMT_RGBA;
1162 case BC_BGR8888: return AV_PIX_FMT_BGR0;
1163 case BC_BGR888: return AV_PIX_FMT_BGR24;
1164 case BC_ARGB8888: return AV_PIX_FMT_ARGB;
1165 case BC_ABGR8888: return AV_PIX_FMT_ABGR;
1166 case BC_RGB8: return AV_PIX_FMT_RGB8;
1167 case BC_YUV420P: return AV_PIX_FMT_YUV420P;
1168 case BC_YUV422P: return AV_PIX_FMT_YUV422P;
1169 case BC_YUV444P: return AV_PIX_FMT_YUV444P;
1170 case BC_YUV411P: return AV_PIX_FMT_YUV411P;
1171 case BC_RGB565: return AV_PIX_FMT_RGB565;
1172 case BC_RGB161616: return AV_PIX_FMT_RGB48LE;
1173 case BC_RGBA16161616: return AV_PIX_FMT_RGBA64LE;
1174 case BC_AYUV16161616: return AV_PIX_FMT_AYUV64LE;
1175 case BC_GBRP: return AV_PIX_FMT_GBRP;
1179 return AV_PIX_FMT_NB;
1182 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1185 case AV_PIX_FMT_YUYV422: return BC_YUV422;
1186 case AV_PIX_FMT_RGB24: return BC_RGB888;
1187 case AV_PIX_FMT_RGBA: return BC_RGBA8888;
1188 case AV_PIX_FMT_BGR0: return BC_BGR8888;
1189 case AV_PIX_FMT_BGR24: return BC_BGR888;
1190 case AV_PIX_FMT_ARGB: return BC_ARGB8888;
1191 case AV_PIX_FMT_ABGR: return BC_ABGR8888;
1192 case AV_PIX_FMT_RGB8: return BC_RGB8;
1193 case AV_PIX_FMT_YUV420P: return BC_YUV420P;
1194 case AV_PIX_FMT_YUV422P: return BC_YUV422P;
1195 case AV_PIX_FMT_YUV444P: return BC_YUV444P;
1196 case AV_PIX_FMT_YUV411P: return BC_YUV411P;
1197 case AV_PIX_FMT_RGB565: return BC_RGB565;
1198 case AV_PIX_FMT_RGB48LE: return BC_RGB161616;
1199 case AV_PIX_FMT_RGBA64LE: return BC_RGBA16161616;
1200 case AV_PIX_FMT_AYUV64LE: return BC_AYUV16161616;
1201 case AV_PIX_FMT_GBRP: return BC_GBRP;
1208 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1210 AVFrame *ipic = av_frame_alloc();
1211 int ret = convert_picture_vframe(frame, ip, ipic);
1212 av_frame_free(&ipic);
1216 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1218 int cmodel = frame->get_color_model();
1219 AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1220 if( ofmt == AV_PIX_FMT_NB ) return -1;
1221 int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1222 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1223 if( size < 0 ) return -1;
1225 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1226 int ysz = bpp * frame->get_w(), usz = ysz;
1236 // override av_image_fill_arrays() for planar types
1237 ipic->data[0] = frame->get_y(); ipic->linesize[0] = ysz;
1238 ipic->data[1] = frame->get_u(); ipic->linesize[1] = usz;
1239 ipic->data[2] = frame->get_v(); ipic->linesize[2] = usz;
1242 ipic->data[0] = frame->get_data();
1243 ipic->linesize[0] = frame->get_bytes_per_line();
1247 AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1248 FFVideoStream *vid =(FFVideoStream *)this;
1249 if( pix_fmt == vid->hw_pixfmt ) {
1251 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1252 ret = AVERROR(ENOMEM);
1254 ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1256 pix_fmt = (AVPixelFormat)ip->format;
1259 eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1260 vid->ffmpeg->fmt_ctx->url);
1264 convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1265 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1266 if( !convert_ctx ) {
1267 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1268 " sws_getCachedContext() failed\n");
1271 int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1272 ipic->data, ipic->linesize);
1274 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1275 vid->ffmpeg->fmt_ctx->url);
1281 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1283 // try direct transfer
1284 if( !convert_picture_vframe(frame, ip) ) return 1;
1285 // use indirect transfer
1286 AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1287 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1289 for( int i = 0; i <desc->nb_components; ++i ) {
1290 int bits = desc->comp[i].depth;
1291 if( bits > max_bits ) max_bits = bits;
1293 int imodel = pix_fmt_to_color_model(ifmt);
1294 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1295 int cmodel = frame->get_color_model();
1296 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1297 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1298 imodel = cmodel_is_yuv ?
1299 (BC_CModels::has_alpha(cmodel) ?
1301 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1302 (BC_CModels::has_alpha(cmodel) ?
1303 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1304 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1306 VFrame vframe(ip->width, ip->height, imodel);
1307 if( convert_picture_vframe(&vframe, ip) ) return -1;
1308 frame->transfer_from(&vframe);
1312 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1314 int ret = convert_cmodel(frame, ifp);
1316 const AVDictionary *src = ifp->metadata;
1317 AVDictionaryEntry *t = NULL;
1318 BC_Hash *hp = frame->get_params();
1320 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1321 hp->update(t->key, t->value);
1326 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1328 AVFrame *opic = av_frame_alloc();
1329 int ret = convert_vframe_picture(frame, op, opic);
1330 av_frame_free(&opic);
1334 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1336 int cmodel = frame->get_color_model();
1337 AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1338 if( ifmt == AV_PIX_FMT_NB ) return -1;
1339 int size = av_image_fill_arrays(opic->data, opic->linesize,
1340 frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1341 if( size < 0 ) return -1;
1343 int bpp = BC_CModels::calculate_pixelsize(cmodel);
1344 int ysz = bpp * frame->get_w(), usz = ysz;
1354 // override av_image_fill_arrays() for planar types
1355 opic->data[0] = frame->get_y(); opic->linesize[0] = ysz;
1356 opic->data[1] = frame->get_u(); opic->linesize[1] = usz;
1357 opic->data[2] = frame->get_v(); opic->linesize[2] = usz;
1360 opic->data[0] = frame->get_data();
1361 opic->linesize[0] = frame->get_bytes_per_line();
1365 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1366 convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1367 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1368 if( !convert_ctx ) {
1369 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1370 " sws_getCachedContext() failed\n");
1373 int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1374 op->data, op->linesize);
1376 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1382 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1384 // try direct transfer
1385 if( !convert_vframe_picture(frame, op) ) return 1;
1386 // use indirect transfer
1387 int cmodel = frame->get_color_model();
1388 int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1389 max_bits /= BC_CModels::components(cmodel);
1390 AVPixelFormat ofmt = (AVPixelFormat)op->format;
1391 int imodel = pix_fmt_to_color_model(ofmt);
1392 int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1393 int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1394 if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1395 imodel = cmodel_is_yuv ?
1396 (BC_CModels::has_alpha(cmodel) ?
1398 (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1399 (BC_CModels::has_alpha(cmodel) ?
1400 (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1401 (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1403 VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1404 vframe.transfer_from(frame);
1405 if( !convert_vframe_picture(&vframe, op) ) return 1;
1409 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1411 int ret = convert_pixfmt(frame, ofp);
1413 BC_Hash *hp = frame->get_params();
1414 AVDictionary **dict = &ofp->metadata;
1415 //av_dict_free(dict);
1416 for( int i=0; i<hp->size(); ++i ) {
1417 char *key = hp->get_key(i), *val = hp->get_value(i);
1418 av_dict_set(dict, key, val, 0);
1424 void FFVideoStream::load_markers()
1426 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1427 if( !index_state || idx >= index_state->video_markers.size() ) return;
1428 FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1431 IndexMarks *FFVideoStream::get_markers()
1433 IndexState *index_state = ffmpeg->file_base->asset->index_state;
1434 if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1435 return !index_state ? 0 : index_state->video_markers[idx];
1439 FFMPEG::FFMPEG(FileBase *file_base)
1442 this->file_base = file_base;
1443 memset(file_format,0,sizeof(file_format));
1444 mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1445 flow_lock = new Condition(1,"FFStream::flow_lock",0);
1448 decoding = encoding = 0;
1449 has_audio = has_video = 0;
1452 opt_video_filter = 0;
1453 opt_audio_filter = 0;
1456 char option_path[BCTEXTLEN];
1457 set_option_path(option_path, "%s", "ffmpeg.opts");
1458 read_options(option_path, opts);
1463 ff_lock("FFMPEG::~FFMPEG()");
1465 ffaudio.remove_all_objects();
1466 ffvideo.remove_all_objects();
1467 if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1471 av_dict_free(&opts);
1472 delete [] opt_video_filter;
1473 delete [] opt_audio_filter;
1474 delete [] opt_hw_dev;
1477 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1479 const int *p = codec->supported_samplerates;
1480 if( !p ) return sample_rate;
1482 if( *p == sample_rate ) return *p;
1488 static inline AVRational std_frame_rate(int i)
1490 static const int m1 = 1001*12, m2 = 1000*12;
1491 static const int freqs[] = {
1492 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1493 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1495 int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1496 return (AVRational) { freq, 1001*12 };
1499 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1501 const AVRational *p = codec->supported_framerates;
1502 AVRational rate, best_rate = (AVRational) { 0, 0 };
1503 double max_err = 1.; int i = 0;
1504 while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1505 double framerate = (double) rate.num / rate.den;
1506 double err = fabs(frame_rate/framerate - 1.);
1507 if( err >= max_err ) continue;
1511 return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1514 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1517 double display_aspect = asset->width / (double)asset->height;
1518 double sample_aspect = display_aspect / asset->aspect_ratio;
1519 int width = 1000000, height = width * sample_aspect + 0.5;
1521 MWindow::create_aspect_ratio(w, h, width, height);
1522 return (AVRational){(int)w, (int)h};
1525 return (AVRational){1, 1};
1529 AVRational FFMPEG::to_time_base(int sample_rate)
1531 return (AVRational){1, sample_rate};
1534 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1537 int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1538 int src_planar = av_sample_fmt_is_planar(src_fmt);
1539 if( dst_planar != src_planar ) ++score;
1540 int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1541 int src_bytes = av_get_bytes_per_sample(src_fmt);
1542 score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1543 int src_packed = av_get_packed_sample_fmt(src_fmt);
1544 int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1545 if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1546 if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1550 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1551 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1553 AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1554 int best_score = get_fmt_score(best, src_fmt);
1555 for( int i=0; sample_fmts[i] >= 0; ++i ) {
1556 AVSampleFormat sample_fmt = sample_fmts[i];
1557 int score = get_fmt_score(sample_fmt, src_fmt);
1558 if( score >= best_score ) continue;
1559 best = sample_fmt; best_score = score;
1565 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1567 char *ep = path + BCTEXTLEN-1;
1568 strncpy(path, File::get_cindat_path(), ep-path);
1569 strncat(path, "/ffmpeg/", ep-path);
1570 path += strlen(path);
1573 path += vsnprintf(path, ep-path, fmt, ap);
1578 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1583 set_option_path(path, "%s/%s", type, spec);
1586 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1588 char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1589 get_option_path(option_path, path, spec);
1590 FILE *fp = fopen(option_path,"r");
1593 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1595 line[sizeof(line)-1] = 0;
1596 ret = scan_option_line(line, format, codec);
1602 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1604 char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1605 get_option_path(option_path, path, spec);
1606 FILE *fp = fopen(option_path,"r");
1609 if( !fgets(line, sizeof(line), fp) ) ret = 1;
1612 line[sizeof(line)-1] = 0;
1613 ret = scan_option_line(line, format, codec);
1616 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1617 while( vp < ep && *vp && *vp != '|' ) ++vp;
1618 if( *vp == '|' ) --vp;
1619 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1624 int FFMPEG::get_file_format()
1626 char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1627 char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1628 audio_muxer[0] = audio_format[0] = 0;
1629 video_muxer[0] = video_format[0] = 0;
1630 Asset *asset = file_base->asset;
1631 int ret = asset ? 0 : 1;
1632 if( !ret && asset->audio_data ) {
1633 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1634 if( get_format(audio_muxer, "format", audio_format) ) {
1635 strcpy(audio_muxer, audio_format);
1636 audio_format[0] = 0;
1640 if( !ret && asset->video_data ) {
1641 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1642 if( get_format(video_muxer, "format", video_format) ) {
1643 strcpy(video_muxer, video_format);
1644 video_format[0] = 0;
1648 if( !ret && !audio_muxer[0] && !video_muxer[0] )
1650 if( !ret && audio_muxer[0] && video_muxer[0] &&
1651 strcmp(audio_muxer, video_muxer) ) ret = -1;
1652 if( !ret && audio_format[0] && video_format[0] &&
1653 strcmp(audio_format, video_format) ) ret = -1;
1655 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1656 (audio_muxer[0] ? audio_muxer : video_muxer) :
1657 (audio_format[0] ? audio_format : video_format));
1661 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1663 while( *cp == ' ' || *cp == '\t' ) ++cp;
1664 const char *bp = cp;
1665 while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1667 if( !len || len > BCSTRLEN-1 ) return 1;
1668 while( bp < cp ) *tag++ = *bp++;
1670 while( *cp == ' ' || *cp == '\t' ) ++cp;
1671 if( *cp == '=' ) ++cp;
1672 while( *cp == ' ' || *cp == '\t' ) ++cp;
1674 while( *cp && *cp != '\n' ) ++cp;
1676 if( len > BCTEXTLEN-1 ) return 1;
1677 while( bp < cp ) *val++ = *bp++;
1682 int FFMPEG::can_render(const char *fformat, const char *type)
1685 char option_path[BCTEXTLEN];
1686 FFMPEG::set_option_path(option_path, type);
1687 fs.update(option_path);
1688 int total_files = fs.total_files();
1689 for( int i=0; i<total_files; ++i ) {
1690 const char *name = fs.get_entry(i)->get_name();
1691 const char *ext = strrchr(name,'.');
1692 if( !ext ) continue;
1693 if( !strcmp(fformat, ++ext) ) return 1;
1698 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1700 for( const char *cp=options; *cp!=0; ) {
1701 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1702 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1705 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1706 char key[BCSTRLEN], val[BCTEXTLEN];
1707 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1708 if( !strcmp(key, nm) ) {
1709 strncpy(value, val, BCSTRLEN);
1716 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1718 char cin_sample_fmt[BCSTRLEN];
1719 int cin_fmt = AV_SAMPLE_FMT_NONE;
1720 const char *options = asset->ff_audio_options;
1721 if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1722 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1724 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1725 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1726 avcodec_find_encoder_by_name(audio_codec) : 0;
1727 if( av_codec && av_codec->sample_fmts )
1728 cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1730 if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1731 const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1732 if( !name ) name = _("None");
1733 strcpy(asset->ff_sample_format, name);
1735 char value[BCSTRLEN];
1736 if( !get_ff_option("cin_bitrate", options, value) )
1737 asset->ff_audio_bitrate = atoi(value);
1738 if( !get_ff_option("cin_quality", options, value) )
1739 asset->ff_audio_quality = atoi(value);
1742 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1744 char options_path[BCTEXTLEN];
1745 set_option_path(options_path, "audio/%s", asset->acodec);
1746 if( !load_options(options_path,
1747 asset->ff_audio_options,
1748 sizeof(asset->ff_audio_options)) )
1749 scan_audio_options(asset, edl);
1752 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1754 char cin_pix_fmt[BCSTRLEN];
1755 int cin_fmt = AV_PIX_FMT_NONE;
1756 const char *options = asset->ff_video_options;
1757 if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1758 cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1760 char video_codec[BCSTRLEN]; video_codec[0] = 0;
1761 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1762 avcodec_find_encoder_by_name(video_codec) : 0;
1763 if( av_codec && av_codec->pix_fmts ) {
1764 if( 0 && edl ) { // frequently picks a bad answer
1765 int color_model = edl->session->color_model;
1766 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1767 max_bits /= BC_CModels::components(color_model);
1768 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1769 (BC_CModels::is_yuv(color_model) ?
1770 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1771 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1774 cin_fmt = av_codec->pix_fmts[0];
1777 if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1778 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1779 const char *name = desc ? desc->name : _("None");
1780 strcpy(asset->ff_pixel_format, name);
1782 char value[BCSTRLEN];
1783 if( !get_ff_option("cin_bitrate", options, value) )
1784 asset->ff_video_bitrate = atoi(value);
1785 if( !get_ff_option("cin_quality", options, value) )
1786 asset->ff_video_quality = atoi(value);
1789 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1791 char options_path[BCTEXTLEN];
1792 set_option_path(options_path, "video/%s", asset->vcodec);
1793 if( !load_options(options_path,
1794 asset->ff_video_options,
1795 sizeof(asset->ff_video_options)) )
1796 scan_video_options(asset, edl);
1799 int FFMPEG::load_defaults(const char *path, const char *type,
1800 char *codec, char *codec_options, int len)
1802 char default_file[BCTEXTLEN];
1803 set_option_path(default_file, "%s/%s.dfl", path, type);
1804 FILE *fp = fopen(default_file,"r");
1806 fgets(codec, BCSTRLEN, fp);
1808 while( *cp && *cp!='\n' ) ++cp;
1810 while( len > 0 && fgets(codec_options, len, fp) ) {
1811 int n = strlen(codec_options);
1812 codec_options += n; len -= n;
1815 set_option_path(default_file, "%s/%s", path, codec);
1816 return load_options(default_file, codec_options, len);
1819 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
1821 if( asset->format != FILE_FFMPEG ) return;
1822 if( text != asset->fformat )
1823 strcpy(asset->fformat, text);
1824 if( asset->audio_data && !asset->ff_audio_options[0] ) {
1825 if( !load_defaults("audio", text, asset->acodec,
1826 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
1827 scan_audio_options(asset, edl);
1829 asset->audio_data = 0;
1831 if( asset->video_data && !asset->ff_video_options[0] ) {
1832 if( !load_defaults("video", text, asset->vcodec,
1833 asset->ff_video_options, sizeof(asset->ff_video_options)) )
1834 scan_video_options(asset, edl);
1836 asset->video_data = 0;
1840 int FFMPEG::get_encoder(const char *options,
1841 char *format, char *codec, char *bsfilter)
1843 FILE *fp = fopen(options,"r");
1845 eprintf(_("options open failed %s\n"),options);
1848 char line[BCTEXTLEN];
1849 if( !fgets(line, sizeof(line), fp) ||
1850 scan_encoder(line, format, codec, bsfilter) )
1851 eprintf(_("format/codec not found %s\n"), options);
1856 int FFMPEG::scan_encoder(const char *line,
1857 char *format, char *codec, char *bsfilter)
1859 format[0] = codec[0] = bsfilter[0] = 0;
1860 if( scan_option_line(line, format, codec) ) return 1;
1862 while( *cp && *cp != '|' ) ++cp;
1863 if( !*cp ) return 0;
1865 do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1866 while( *++cp && (*cp==' ' || *cp == '\t') );
1868 for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
1873 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
1875 FILE *fp = fopen(options,"r");
1878 while( !ret && --skip >= 0 ) {
1880 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
1881 if( ch < 0 ) ret = 1;
1884 ret = read_options(fp, options, opts);
1889 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
1891 FILE *fp = fmemopen((void *)options,strlen(options),"r");
1893 int ret = read_options(fp, options, opts);
1895 AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
1896 if( tag ) st->id = strtol(tag->value,0,0);
1900 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
1902 int ret = 0, no = 0;
1903 char line[BCTEXTLEN];
1904 while( !ret && fgets(line, sizeof(line), fp) ) {
1905 line[sizeof(line)-1] = 0;
1906 if( line[0] == '#' ) continue;
1907 if( line[0] == '\n' ) continue;
1908 char key[BCSTRLEN], val[BCTEXTLEN];
1909 if( scan_option_line(line, key, val) ) {
1910 eprintf(_("err reading %s: line %d\n"), options, no);
1914 if( !strcmp(key, "duration") )
1915 opt_duration = strtod(val, 0);
1916 else if( !strcmp(key, "video_filter") )
1917 opt_video_filter = cstrdup(val);
1918 else if( !strcmp(key, "audio_filter") )
1919 opt_audio_filter = cstrdup(val);
1920 else if( !strcmp(key, "cin_hw_dev") )
1921 opt_hw_dev = cstrdup(val);
1922 else if( !strcmp(key, "loglevel") )
1925 av_dict_set(&opts, key, val, 0);
1931 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
1933 char option_path[BCTEXTLEN];
1934 set_option_path(option_path, "%s", options);
1935 return read_options(option_path, opts);
1938 int FFMPEG::load_options(const char *path, char *bfr, int len)
1941 FILE *fp = fopen(path, "r");
1943 fgets(bfr, len, fp); // skip hdr
1944 len = fread(bfr, 1, len-1, fp);
1945 if( len < 0 ) len = 0;
1951 void FFMPEG::set_loglevel(const char *ap)
1953 if( !ap || !*ap ) return;
1958 { "quiet" , AV_LOG_QUIET },
1959 { "panic" , AV_LOG_PANIC },
1960 { "fatal" , AV_LOG_FATAL },
1961 { "error" , AV_LOG_ERROR },
1962 { "warning", AV_LOG_WARNING },
1963 { "info" , AV_LOG_INFO },
1964 { "verbose", AV_LOG_VERBOSE },
1965 { "debug" , AV_LOG_DEBUG },
1967 for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
1968 if( !strcmp(log_levels[i].name, ap) ) {
1969 av_log_set_level(log_levels[i].level);
1973 av_log_set_level(atoi(ap));
1976 double FFMPEG::to_secs(int64_t time, AVRational time_base)
1978 double base_time = time == AV_NOPTS_VALUE ? 0 :
1979 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
1980 return base_time / AV_TIME_BASE;
1983 int FFMPEG::info(char *text, int len)
1985 if( len <= 0 ) return 0;
1987 #define report(s...) do { int n = snprintf(cp,len,s); cp += n; len -= n; } while(0)
1989 report("format: %s\n",fmt_ctx->iformat->name);
1990 if( ffvideo.size() > 0 )
1991 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
1992 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
1993 FFVideoStream *vid = ffvideo[vidx];
1994 AVStream *st = vid->st;
1995 AVCodecID codec_id = st->codecpar->codec_id;
1996 report(_("vid%d (%d), id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
1997 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
1998 report(" video%d %s", vidx+1, desc ? desc->name : " (unkn)");
1999 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2000 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2001 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2002 report(" pix %s\n", pfn ? pfn : "(unkn)");
2003 double secs = to_secs(st->duration, st->time_base);
2004 int64_t length = secs * vid->frame_rate + 0.5;
2005 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2006 int64_t nudge = ofs * vid->frame_rate;
2007 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2008 report(" %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2009 int hrs = secs/3600; secs -= hrs*3600;
2010 int mins = secs/60; secs -= mins*60;
2011 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2013 if( ffaudio.size() > 0 )
2014 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2015 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2016 FFAudioStream *aud = ffaudio[aidx];
2017 AVStream *st = aud->st;
2018 AVCodecID codec_id = st->codecpar->codec_id;
2019 report(_("aud%d (%d), id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2020 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2021 int nch = aud->channels, ch0 = aud->channel0+1;
2022 report(" audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2023 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2024 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2025 report(" %s %d", fmt, aud->sample_rate);
2026 int sample_bits = av_get_bits_per_sample(codec_id);
2027 report(" %dbits\n", sample_bits);
2028 double secs = to_secs(st->duration, st->time_base);
2029 int64_t length = secs * aud->sample_rate + 0.5;
2030 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2031 int64_t nudge = ofs * aud->sample_rate;
2032 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2033 report(" %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2034 int hrs = secs/3600; secs -= hrs*3600;
2035 int mins = secs/60; secs -= mins*60;
2036 report(" %d:%02d:%05.2f\n", hrs, mins, secs);
2038 if( fmt_ctx->nb_programs > 0 )
2039 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2040 for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2041 report("program %d", i+1);
2042 AVProgram *pgrm = fmt_ctx->programs[i];
2043 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2044 int idx = pgrm->stream_index[j];
2045 int vidx = ffvideo.size();
2046 while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2048 report(", vid%d", vidx);
2051 int aidx = ffaudio.size();
2052 while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2054 report(", aud%d", aidx);
2057 report(", (%d)", pgrm->stream_index[j]);
2062 AVDictionaryEntry *tag = 0;
2063 while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2064 report("%s=%s\n", tag->key, tag->value);
2073 int FFMPEG::init_decoder(const char *filename)
2075 ff_lock("FFMPEG::init_decoder");
2077 char file_opts[BCTEXTLEN];
2078 strcpy(file_opts, filename);
2079 char *bp = strrchr(file_opts, '/');
2080 if( !bp ) bp = file_opts;
2081 char *sp = strrchr(bp, '.');
2082 if( !sp ) sp = bp + strlen(bp);
2084 AVInputFormat *ifmt = 0;
2086 strcpy(sp, ".opts");
2087 fp = fopen(file_opts, "r");
2090 read_options(fp, file_opts, opts);
2092 AVDictionaryEntry *tag;
2093 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2094 ifmt = av_find_input_format(tag->value);
2098 load_options("decode.opts", opts);
2099 AVDictionary *fopts = 0;
2100 av_dict_copy(&fopts, opts, 0);
2101 int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2102 av_dict_free(&fopts);
2104 ret = avformat_find_stream_info(fmt_ctx, NULL);
2109 return !ret ? 0 : 1;
2112 int FFMPEG::open_decoder()
2115 if( stat(fmt_ctx->url, &st) < 0 ) {
2116 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2120 int64_t file_bits = 8 * st.st_size;
2121 if( !fmt_ctx->bit_rate && opt_duration > 0 )
2122 fmt_ctx->bit_rate = file_bits / opt_duration;
2125 if( fmt_ctx->bit_rate > 0 ) {
2126 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2127 AVStream *st = fmt_ctx->streams[i];
2128 if( st->duration != AV_NOPTS_VALUE ) continue;
2129 if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2130 st->duration = av_rescale(file_bits, st->time_base.den,
2131 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2135 if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2136 fflags |= FF_ESTM_TIMES;
2137 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2141 ff_lock("FFMPEG::open_decoder");
2142 int ret = 0, bad_time = 0;
2143 for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2144 AVStream *st = fmt_ctx->streams[i];
2145 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2146 AVCodecParameters *avpar = st->codecpar;
2147 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2148 if( !codec_desc ) continue;
2149 switch( avpar->codec_type ) {
2150 case AVMEDIA_TYPE_VIDEO: {
2151 if( avpar->width < 1 ) continue;
2152 if( avpar->height < 1 ) continue;
2153 AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2154 if( framerate.num < 1 ) continue;
2156 int vidx = ffvideo.size();
2157 FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2158 vstrm_index.append(ffidx(vidx, 0));
2159 ffvideo.append(vid);
2160 vid->width = avpar->width;
2161 vid->height = avpar->height;
2162 vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2163 double secs = to_secs(st->duration, st->time_base);
2164 vid->length = secs * vid->frame_rate;
2165 vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2166 vid->nudge = st->start_time;
2168 if( opt_video_filter )
2169 ret = vid->create_filter(opt_video_filter, avpar);
2171 case AVMEDIA_TYPE_AUDIO: {
2172 if( avpar->channels < 1 ) continue;
2173 if( avpar->sample_rate < 1 ) continue;
2175 int aidx = ffaudio.size();
2176 FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2177 ffaudio.append(aud);
2178 aud->channel0 = astrm_index.size();
2179 aud->channels = avpar->channels;
2180 for( int ch=0; ch<aud->channels; ++ch )
2181 astrm_index.append(ffidx(aidx, ch));
2182 aud->sample_rate = avpar->sample_rate;
2183 double secs = to_secs(st->duration, st->time_base);
2184 aud->length = secs * aud->sample_rate;
2185 aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2186 aud->nudge = st->start_time;
2188 if( opt_audio_filter )
2189 ret = aud->create_filter(opt_audio_filter, avpar);
2194 if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2195 fflags |= FF_BAD_TIMES;
2196 printf("FFMPEG::open_decoder: some stream have bad times: %s\n",
2200 return ret < 0 ? -1 : 0;
2204 int FFMPEG::init_encoder(const char *filename)
2206 // try access first for named pipes
2207 int ret = access(filename, W_OK);
2209 int fd = ::open(filename,O_WRONLY);
2210 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2211 if( fd >= 0 ) { close(fd); ret = 0; }
2214 eprintf(_("bad file path: %s\n"), filename);
2217 ret = get_file_format();
2219 eprintf(_("bad file format: %s\n"), filename);
2223 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2226 ff_lock("FFMPEG::init_encoder");
2228 char format[BCSTRLEN];
2229 if( get_format(format, "format", file_format) )
2230 strcpy(format, file_format);
2231 avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2233 eprintf(_("failed: %s\n"), filename);
2238 load_options("encode.opts", opts);
2244 int FFMPEG::open_encoder(const char *type, const char *spec)
2247 Asset *asset = file_base->asset;
2248 char *filename = asset->path;
2249 AVDictionary *sopts = 0;
2250 av_dict_copy(&sopts, opts, 0);
2251 char option_path[BCTEXTLEN];
2252 set_option_path(option_path, "%s/%s.opts", type, type);
2253 read_options(option_path, sopts);
2254 get_option_path(option_path, type, spec);
2255 char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2256 if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2257 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2262 if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2264 else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2265 else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2268 ff_lock("FFMPEG::open_encoder");
2271 AVCodecContext *ctx = 0;
2273 const AVCodecDescriptor *codec_desc = 0;
2274 AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2276 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2280 codec_desc = avcodec_descriptor_get(codec->id);
2282 eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2287 st = avformat_new_stream(fmt_ctx, 0);
2289 eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2294 switch( codec_desc->type ) {
2295 case AVMEDIA_TYPE_AUDIO: {
2297 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2301 if( scan_options(asset->ff_audio_options, sopts, st) ) {
2302 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2307 ctx = avcodec_alloc_context3(codec);
2308 if( asset->ff_audio_bitrate > 0 ) {
2309 ctx->bit_rate = asset->ff_audio_bitrate;
2311 sprintf(arg, "%d", asset->ff_audio_bitrate);
2312 av_dict_set(&sopts, "b", arg, 0);
2314 else if( asset->ff_audio_quality >= 0 ) {
2315 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2316 ctx->qmin = ctx->qmax = asset->ff_audio_quality;
2317 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2318 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2319 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2321 av_dict_set(&sopts, "flags", "+qscale", 0);
2322 sprintf(arg, "%d", asset->ff_audio_quality);
2323 av_dict_set(&sopts, "qscale", arg, 0);
2324 sprintf(arg, "%d", ctx->global_quality);
2325 av_dict_set(&sopts, "global_quality", arg, 0);
2327 int aidx = ffaudio.size();
2328 int fidx = aidx + ffvideo.size();
2329 FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2330 aud->avctx = ctx; ffaudio.append(aud); fst = aud;
2331 aud->sample_rate = asset->sample_rate;
2332 ctx->channels = aud->channels = asset->channels;
2333 for( int ch=0; ch<aud->channels; ++ch )
2334 astrm_index.append(ffidx(aidx, ch));
2335 ctx->channel_layout = av_get_default_channel_layout(ctx->channels);
2336 ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2337 if( !ctx->sample_rate ) {
2338 eprintf(_("check_sample_rate failed %s\n"), filename);
2342 ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2343 AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2344 if( sample_fmt == AV_SAMPLE_FMT_NONE )
2345 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2346 ctx->sample_fmt = sample_fmt;
2347 uint64_t layout = av_get_default_channel_layout(ctx->channels);
2348 aud->resample_context = swr_alloc_set_opts(NULL,
2349 layout, ctx->sample_fmt, aud->sample_rate,
2350 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2352 swr_init(aud->resample_context);
2355 case AVMEDIA_TYPE_VIDEO: {
2357 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2361 if( scan_options(asset->ff_video_options, sopts, st) ) {
2362 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2367 ctx = avcodec_alloc_context3(codec);
2368 if( asset->ff_video_bitrate > 0 ) {
2369 ctx->bit_rate = asset->ff_video_bitrate;
2371 sprintf(arg, "%d", asset->ff_video_bitrate);
2372 av_dict_set(&sopts, "b", arg, 0);
2374 else if( asset->ff_video_quality >= 0 ) {
2375 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2376 ctx->qmin = ctx->qmax = asset->ff_video_quality;
2377 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2378 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2379 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2381 av_dict_set(&sopts, "flags", "+qscale", 0);
2382 sprintf(arg, "%d", asset->ff_video_quality);
2383 av_dict_set(&sopts, "qscale", arg, 0);
2384 sprintf(arg, "%d", ctx->global_quality);
2385 av_dict_set(&sopts, "global_quality", arg, 0);
2387 int vidx = ffvideo.size();
2388 int fidx = vidx + ffaudio.size();
2389 FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2390 vstrm_index.append(ffidx(vidx, 0));
2391 vid->avctx = ctx; ffvideo.append(vid); fst = vid;
2392 vid->width = asset->width;
2393 vid->height = asset->height;
2394 vid->frame_rate = asset->frame_rate;
2396 AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2397 if( pix_fmt == AV_PIX_FMT_NONE )
2398 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2399 ctx->pix_fmt = pix_fmt;
2400 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2401 int mask_w = (1<<desc->log2_chroma_w)-1;
2402 ctx->width = (vid->width+mask_w) & ~mask_w;
2403 int mask_h = (1<<desc->log2_chroma_h)-1;
2404 ctx->height = (vid->height+mask_h) & ~mask_h;
2405 ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2406 AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2407 if( !frame_rate.num || !frame_rate.den ) {
2408 eprintf(_("check_frame_rate failed %s\n"), filename);
2412 av_reduce(&frame_rate.num, &frame_rate.den,
2413 frame_rate.num, frame_rate.den, INT_MAX);
2414 ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2415 ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2416 st->avg_frame_rate = frame_rate;
2417 st->time_base = ctx->time_base;
2419 vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2420 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2421 vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2424 eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2429 AVDictionaryEntry *tag;
2430 if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2431 char suffix[BCSTRLEN]; sprintf(suffix,"-%d.log",fst->fidx);
2432 fst->stats_filename = cstrcat(2, tag->value, suffix);
2434 if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2435 int pass = fst->pass;
2436 char *cp = tag->value;
2438 int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2439 if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2440 char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2441 for( *bp++=ch; isalnum(ch=*cp); ++cp )
2442 if( bp < ep ) *bp++ = ch;
2444 if( !strcmp(id, "pass1") ) {
2445 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2447 else if( !strcmp(id, "pass2") ) {
2448 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2451 if( (fst->pass=pass) ) {
2452 if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2453 if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2459 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2460 ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2461 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2462 eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2465 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2466 av_dict_set(&sopts, "cin_quality", 0, 0);
2468 if( !av_dict_get(sopts, "threads", NULL, 0) )
2469 ctx->thread_count = ff_cpus();
2470 ret = avcodec_open2(ctx, codec, &sopts);
2472 ret = avcodec_parameters_from_context(st->codecpar, ctx);
2474 fprintf(stderr, "Could not copy the stream parameters\n");
2477 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2478 ret = avcodec_copy_context(st->codec, ctx);
2479 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2481 fprintf(stderr, "Could not copy the stream context\n");
2484 ff_err(ret,"FFMPEG::open_encoder");
2485 eprintf(_("open failed %s:%s\n"), codec_name, filename);
2491 if( !ret && fst && bsfilter[0] ) {
2492 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2494 ff_err(ret,"FFMPEG::open_encoder");
2495 eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2506 av_dict_free(&sopts);
2510 int FFMPEG::close_encoder()
2513 if( encoding > 0 ) {
2514 av_write_trailer(fmt_ctx);
2515 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2516 avio_closep(&fmt_ctx->pb);
2522 int FFMPEG::decode_activate()
2524 if( decoding < 0 ) {
2526 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2527 ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2528 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2529 ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2530 // set nudges for each program stream set
2531 const int64_t min_nudge = INT64_MIN+1;
2532 int npgrms = fmt_ctx->nb_programs;
2533 for( int i=0; i<npgrms; ++i ) {
2534 AVProgram *pgrm = fmt_ctx->programs[i];
2535 // first start time video stream
2536 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2537 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2538 int fidx = pgrm->stream_index[j];
2539 AVStream *st = fmt_ctx->streams[fidx];
2540 AVCodecParameters *avpar = st->codecpar;
2541 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2542 if( st->start_time == AV_NOPTS_VALUE ) continue;
2543 if( vstart_time < st->start_time )
2544 vstart_time = st->start_time;
2547 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2548 if( st->start_time == AV_NOPTS_VALUE ) continue;
2549 if( astart_time < st->start_time )
2550 astart_time = st->start_time;
2554 //since frame rate is much more grainy than sample rate, it is better to
2555 // align using video, so that total absolute error is minimized.
2556 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2557 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2558 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2559 int fidx = pgrm->stream_index[j];
2560 AVStream *st = fmt_ctx->streams[fidx];
2561 AVCodecParameters *avpar = st->codecpar;
2562 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2563 for( int k=0; k<ffvideo.size(); ++k ) {
2564 if( ffvideo[k]->fidx != fidx ) continue;
2565 ffvideo[k]->nudge = nudge;
2569 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2570 for( int k=0; k<ffaudio.size(); ++k ) {
2571 if( ffaudio[k]->fidx != fidx ) continue;
2572 ffaudio[k]->nudge = nudge;
2578 // set nudges for any streams not yet set
2579 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2580 int nstreams = fmt_ctx->nb_streams;
2581 for( int i=0; i<nstreams; ++i ) {
2582 AVStream *st = fmt_ctx->streams[i];
2583 AVCodecParameters *avpar = st->codecpar;
2584 switch( avpar->codec_type ) {
2585 case AVMEDIA_TYPE_VIDEO: {
2586 if( st->start_time == AV_NOPTS_VALUE ) continue;
2587 int vidx = ffvideo.size();
2588 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2589 if( vidx < 0 ) continue;
2590 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2591 if( vstart_time < st->start_time )
2592 vstart_time = st->start_time;
2594 case AVMEDIA_TYPE_AUDIO: {
2595 if( st->start_time == AV_NOPTS_VALUE ) continue;
2596 int aidx = ffaudio.size();
2597 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2598 if( aidx < 0 ) continue;
2599 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2600 ffaudio[aidx]->frame_sz = avpar->frame_size;
2601 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2602 if( astart_time < st->start_time )
2603 astart_time = st->start_time;
2608 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2609 astart_time > min_nudge ? astart_time : 0;
2610 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2611 if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2612 ffvideo[vidx]->nudge = nudge;
2614 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2615 if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2616 ffaudio[aidx]->nudge = nudge;
2623 int FFMPEG::encode_activate()
2626 if( encoding < 0 ) {
2628 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2629 (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2630 ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2636 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2637 for( int i=0; i< ffvideo.size(); ++i )
2638 av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2639 for( int i=0; i< ffaudio.size(); ++i )
2640 av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2641 int pi = fmt_ctx->nb_programs;
2642 while( --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2643 AVDictionary **meta = &prog->metadata;
2644 av_dict_set(meta, "service_provider", "cin5", 0);
2645 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2646 if( bp ) path = bp + 1;
2647 av_dict_set(meta, "title", path, 0);
2649 if( ffaudio.size() ) {
2650 const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2651 if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2652 static struct { const char lc[3], lng[4]; } lcode[] = {
2653 { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2654 { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2655 { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2656 { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2657 { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2658 { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2660 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2661 if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2663 if( !ep ) ep = "und";
2665 strncpy(lang,ep,3); lang[3] = 0;
2666 AVStream *st = ffaudio[0]->st;
2667 av_dict_set(&st->metadata,"language",lang,0);
2670 AVDictionary *fopts = 0;
2671 char option_path[BCTEXTLEN];
2672 set_option_path(option_path, "format/%s", file_format);
2673 read_options(option_path, fopts, 1);
2674 ret = avformat_write_header(fmt_ctx, &fopts);
2676 ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2680 av_dict_free(&fopts);
2687 int FFMPEG::audio_seek(int stream, int64_t pos)
2689 int aidx = astrm_index[stream].st_idx;
2690 FFAudioStream *aud = ffaudio[aidx];
2691 aud->audio_seek(pos);
2695 int FFMPEG::video_seek(int stream, int64_t pos)
2697 int vidx = vstrm_index[stream].st_idx;
2698 FFVideoStream *vid = ffvideo[vidx];
2699 vid->video_seek(pos);
2704 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2706 if( !has_audio || chn >= astrm_index.size() ) return -1;
2707 int aidx = astrm_index[chn].st_idx;
2708 FFAudioStream *aud = ffaudio[aidx];
2709 if( aud->load(pos, len) < len ) return -1;
2710 int ch = astrm_index[chn].st_ch;
2711 int ret = aud->read(samples,len,ch);
2715 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2717 if( !has_video || layer >= vstrm_index.size() ) return -1;
2718 int vidx = vstrm_index[layer].st_idx;
2719 FFVideoStream *vid = ffvideo[vidx];
2720 return vid->load(vframe, pos);
2724 int FFMPEG::encode(int stream, double **samples, int len)
2726 FFAudioStream *aud = ffaudio[stream];
2727 return aud->encode(samples, len);
2731 int FFMPEG::encode(int stream, VFrame *frame)
2733 FFVideoStream *vid = ffvideo[stream];
2734 return vid->encode(frame);
2737 void FFMPEG::start_muxer()
2745 void FFMPEG::stop_muxer()
2754 void FFMPEG::flow_off()
2757 flow_lock->lock("FFMPEG::flow_off");
2761 void FFMPEG::flow_on()
2765 flow_lock->unlock();
2768 void FFMPEG::flow_ctl()
2771 flow_lock->lock("FFMPEG::flow_ctl");
2772 flow_lock->unlock();
2776 int FFMPEG::mux_audio(FFrame *frm)
2778 FFStream *fst = frm->fst;
2779 AVCodecContext *ctx = fst->avctx;
2780 AVFrame *frame = *frm;
2781 AVRational tick_rate = {1, ctx->sample_rate};
2782 frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2783 int ret = fst->encode_frame(frame);
2785 ff_err(ret, "FFMPEG::mux_audio");
2786 return ret >= 0 ? 0 : 1;
2789 int FFMPEG::mux_video(FFrame *frm)
2791 FFStream *fst = frm->fst;
2792 AVFrame *frame = *frm;
2793 frame->pts = frm->position;
2794 int ret = fst->encode_frame(frame);
2796 ff_err(ret, "FFMPEG::mux_video");
2797 return ret >= 0 ? 0 : 1;
2803 double atm = -1, vtm = -1;
2804 FFrame *afrm = 0, *vfrm = 0;
2806 for( int i=0; i<ffaudio.size(); ++i ) { // earliest audio
2807 FFStream *fst = ffaudio[i];
2808 if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2809 FFrame *frm = fst->frms.first;
2810 if( !frm ) { if( !done ) return; continue; }
2811 double tm = to_secs(frm->position, fst->avctx->time_base);
2812 if( atm < 0 || tm < atm ) { atm = tm; afrm = frm; }
2814 for( int i=0; i<ffvideo.size(); ++i ) { // earliest video
2815 FFStream *fst = ffvideo[i];
2816 if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
2817 FFrame *frm = fst->frms.first;
2818 if( !frm ) { if( !done ) return; continue; }
2819 double tm = to_secs(frm->position, fst->avctx->time_base);
2820 if( vtm < 0 || tm < vtm ) { vtm = tm; vfrm = frm; }
2822 if( !demand ) flow_off();
2823 if( !afrm && !vfrm ) break;
2824 int v = !afrm ? -1 : !vfrm ? 1 : av_compare_ts(
2825 vfrm->position, vfrm->fst->avctx->time_base,
2826 afrm->position, afrm->fst->avctx->time_base);
2827 FFrame *frm = v <= 0 ? vfrm : afrm;
2828 if( frm == afrm ) mux_audio(frm);
2829 if( frm == vfrm ) mux_video(frm);
2838 mux_lock->lock("FFMPEG::run");
2841 for( int i=0; i<ffaudio.size(); ++i )
2842 ffaudio[i]->drain();
2843 for( int i=0; i<ffvideo.size(); ++i )
2844 ffvideo[i]->drain();
2846 for( int i=0; i<ffaudio.size(); ++i )
2847 ffaudio[i]->flush();
2848 for( int i=0; i<ffvideo.size(); ++i )
2849 ffvideo[i]->flush();
2853 int FFMPEG::ff_total_audio_channels()
2855 return astrm_index.size();
2858 int FFMPEG::ff_total_astreams()
2860 return ffaudio.size();
2863 int FFMPEG::ff_audio_channels(int stream)
2865 return ffaudio[stream]->channels;
2868 int FFMPEG::ff_sample_rate(int stream)
2870 return ffaudio[stream]->sample_rate;
2873 const char* FFMPEG::ff_audio_format(int stream)
2875 AVStream *st = ffaudio[stream]->st;
2876 AVCodecID id = st->codecpar->codec_id;
2877 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2878 return desc ? desc->name : _("Unknown");
2881 int FFMPEG::ff_audio_pid(int stream)
2883 return ffaudio[stream]->st->id;
2886 int64_t FFMPEG::ff_audio_samples(int stream)
2888 return ffaudio[stream]->length;
2891 // find audio astream/channels with this program,
2892 // or all program audio channels (astream=-1)
2893 int FFMPEG::ff_audio_for_video(int vstream, int astream, int64_t &channel_mask)
2897 int vidx = ffvideo[vstream]->fidx;
2898 // find first program with this video stream
2899 for( int i=0; pidx<0 && i<(int)fmt_ctx->nb_programs; ++i ) {
2900 AVProgram *pgrm = fmt_ctx->programs[i];
2901 for( int j=0; pidx<0 && j<(int)pgrm->nb_stream_indexes; ++j ) {
2902 int st_idx = pgrm->stream_index[j];
2903 AVStream *st = fmt_ctx->streams[st_idx];
2904 if( st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO ) continue;
2905 if( st_idx == vidx ) pidx = i;
2908 if( pidx < 0 ) return -1;
2910 int64_t channels = 0;
2911 AVProgram *pgrm = fmt_ctx->programs[pidx];
2912 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2913 int aidx = pgrm->stream_index[j];
2914 AVStream *st = fmt_ctx->streams[aidx];
2915 if( st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
2916 if( astream > 0 ) { --astream; continue; }
2918 for( int i=0; astrm<0 && i<ffaudio.size(); ++i )
2919 if( ffaudio[i]->fidx == aidx ) astrm = i;
2921 if( ret < 0 ) ret = astrm;
2922 int64_t mask = (1 << ffaudio[astrm]->channels) - 1;
2923 channels |= mask << ffaudio[astrm]->channel0;
2925 if( !astream ) break;
2927 channel_mask = channels;
2932 int FFMPEG::ff_total_video_layers()
2934 return vstrm_index.size();
2937 int FFMPEG::ff_total_vstreams()
2939 return ffvideo.size();
2942 int FFMPEG::ff_video_width(int stream)
2944 return ffvideo[stream]->width;
2947 int FFMPEG::ff_video_height(int stream)
2949 return ffvideo[stream]->height;
2952 int FFMPEG::ff_set_video_width(int stream, int width)
2954 int w = ffvideo[stream]->width;
2955 ffvideo[stream]->width = width;
2959 int FFMPEG::ff_set_video_height(int stream, int height)
2961 int h = ffvideo[stream]->height;
2962 ffvideo[stream]->height = height;
2966 int FFMPEG::ff_coded_width(int stream)
2968 return ffvideo[stream]->avctx->coded_width;
2971 int FFMPEG::ff_coded_height(int stream)
2973 return ffvideo[stream]->avctx->coded_height;
2976 float FFMPEG::ff_aspect_ratio(int stream)
2978 return ffvideo[stream]->aspect_ratio;
2981 const char* FFMPEG::ff_video_format(int stream)
2983 AVStream *st = ffvideo[stream]->st;
2984 AVCodecID id = st->codecpar->codec_id;
2985 const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
2986 return desc ? desc->name : _("Unknown");
2989 double FFMPEG::ff_frame_rate(int stream)
2991 return ffvideo[stream]->frame_rate;
2994 int64_t FFMPEG::ff_video_frames(int stream)
2996 return ffvideo[stream]->length;
2999 int FFMPEG::ff_video_pid(int stream)
3001 return ffvideo[stream]->st->id;
3004 int FFMPEG::ff_video_mpeg_color_range(int stream)
3006 return ffvideo[stream]->st->codecpar->color_range == AVCOL_RANGE_MPEG ? 1 : 0;
3009 int FFMPEG::ff_cpus()
3011 return file_base->file->cpus;
3014 const char *FFMPEG::ff_hw_dev()
3016 return &file_base->file->preferences->use_hw_dev[0];
3019 int FFVideoStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3021 avfilter_register_all();
3022 const char *sp = filter_spec;
3023 char filter_name[BCSTRLEN], *np = filter_name;
3024 int i = sizeof(filter_name);
3025 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3027 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3028 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_VIDEO ) {
3029 ff_err(AVERROR(EINVAL), "FFVideoStream::create_filter: %s\n", filter_spec);
3032 filter_graph = avfilter_graph_alloc();
3033 const AVFilter *buffersrc = avfilter_get_by_name("buffer");
3034 const AVFilter *buffersink = avfilter_get_by_name("buffersink");
3036 int ret = 0; char args[BCTEXTLEN];
3037 AVPixelFormat pix_fmt = (AVPixelFormat)avpar->format;
3038 snprintf(args, sizeof(args),
3039 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
3040 avpar->width, avpar->height, (int)pix_fmt,
3041 st->time_base.num, st->time_base.den,
3042 avpar->sample_aspect_ratio.num, avpar->sample_aspect_ratio.den);
3044 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3045 args, NULL, filter_graph);
3047 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3048 NULL, NULL, filter_graph);
3050 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
3051 (uint8_t*)&pix_fmt, sizeof(pix_fmt),
3052 AV_OPT_SEARCH_CHILDREN);
3054 ff_err(ret, "FFVideoStream::create_filter");
3056 ret = FFStream::create_filter(filter_spec);
3057 return ret >= 0 ? 0 : -1;
3060 int FFAudioStream::create_filter(const char *filter_spec, AVCodecParameters *avpar)
3062 avfilter_register_all();
3063 const char *sp = filter_spec;
3064 char filter_name[BCSTRLEN], *np = filter_name;
3065 int i = sizeof(filter_name);
3066 while( --i>=0 && *sp!=0 && !strchr(" \t:=,",*sp) ) *np++ = *sp++;
3068 const AVFilter *filter = !filter_name[0] ? 0 : avfilter_get_by_name(filter_name);
3069 if( !filter || avfilter_pad_get_type(filter->inputs,0) != AVMEDIA_TYPE_AUDIO ) {
3070 ff_err(AVERROR(EINVAL), "FFAudioStream::create_filter: %s\n", filter_spec);
3073 filter_graph = avfilter_graph_alloc();
3074 const AVFilter *buffersrc = avfilter_get_by_name("abuffer");
3075 const AVFilter *buffersink = avfilter_get_by_name("abuffersink");
3076 int ret = 0; char args[BCTEXTLEN];
3077 AVSampleFormat sample_fmt = (AVSampleFormat)avpar->format;
3078 snprintf(args, sizeof(args),
3079 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%jx",
3080 st->time_base.num, st->time_base.den, avpar->sample_rate,
3081 av_get_sample_fmt_name(sample_fmt), avpar->channel_layout);
3083 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
3084 args, NULL, filter_graph);
3086 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
3087 NULL, NULL, filter_graph);
3089 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
3090 (uint8_t*)&sample_fmt, sizeof(sample_fmt),
3091 AV_OPT_SEARCH_CHILDREN);
3093 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
3094 (uint8_t*)&avpar->channel_layout,
3095 sizeof(avpar->channel_layout), AV_OPT_SEARCH_CHILDREN);
3097 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
3098 (uint8_t*)&sample_rate, sizeof(sample_rate),
3099 AV_OPT_SEARCH_CHILDREN);
3101 ff_err(ret, "FFAudioStream::create_filter");
3103 ret = FFStream::create_filter(filter_spec);
3104 return ret >= 0 ? 0 : -1;
3107 int FFStream::create_filter(const char *filter_spec)
3109 /* Endpoints for the filter graph. */
3110 AVFilterInOut *outputs = avfilter_inout_alloc();
3111 outputs->name = av_strdup("in");
3112 outputs->filter_ctx = buffersrc_ctx;
3113 outputs->pad_idx = 0;
3116 AVFilterInOut *inputs = avfilter_inout_alloc();
3117 inputs->name = av_strdup("out");
3118 inputs->filter_ctx = buffersink_ctx;
3119 inputs->pad_idx = 0;
3122 int ret = !outputs->name || !inputs->name ? -1 : 0;
3124 ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
3125 &inputs, &outputs, NULL);
3127 ret = avfilter_graph_config(filter_graph, NULL);
3130 ff_err(ret, "FFStream::create_filter");
3131 avfilter_graph_free(&filter_graph);
3134 avfilter_inout_free(&inputs);
3135 avfilter_inout_free(&outputs);
3139 int FFMPEG::scan(IndexState *index_state, int64_t *scan_position, int *canceled)
3142 av_init_packet(&pkt);
3143 AVFrame *frame = av_frame_alloc();
3145 fprintf(stderr,"FFMPEG::scan: ");
3146 fprintf(stderr,_("av_frame_alloc failed\n"));
3147 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3151 index_state->add_video_markers(ffvideo.size());
3152 index_state->add_audio_markers(ffaudio.size());
3154 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3156 AVDictionary *copts = 0;
3157 av_dict_copy(&copts, opts, 0);
3158 AVStream *st = fmt_ctx->streams[i];
3159 AVCodecID codec_id = st->codecpar->codec_id;
3160 AVCodec *decoder = avcodec_find_decoder(codec_id);
3161 AVCodecContext *avctx = avcodec_alloc_context3(decoder);
3163 eprintf(_("cant allocate codec context\n"));
3164 ret = AVERROR(ENOMEM);
3167 avcodec_parameters_to_context(avctx, st->codecpar);
3168 if( !av_dict_get(copts, "threads", NULL, 0) )
3169 avctx->thread_count = ff_cpus();
3170 ret = avcodec_open2(avctx, decoder, &copts);
3172 av_dict_free(&copts);
3174 AVCodecParameters *avpar = st->codecpar;
3175 switch( avpar->codec_type ) {
3176 case AVMEDIA_TYPE_VIDEO: {
3177 int vidx = ffvideo.size();
3178 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3179 if( vidx < 0 ) break;
3180 ffvideo[vidx]->avctx = avctx;
3182 case AVMEDIA_TYPE_AUDIO: {
3183 int aidx = ffaudio.size();
3184 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3185 if( aidx < 0 ) break;
3186 ffaudio[aidx]->avctx = avctx;
3191 fprintf(stderr,"FFMPEG::scan: ");
3192 fprintf(stderr,_("codec open failed\n"));
3193 fprintf(stderr,"FFMPEG::scan:file=%s\n", file_base->asset->path);
3194 avcodec_free_context(&avctx);
3198 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
3199 AVStream *st = fmt_ctx->streams[i];
3200 AVCodecParameters *avpar = st->codecpar;
3201 if( avpar->codec_type != AVMEDIA_TYPE_AUDIO ) continue;
3202 int64_t tstmp = st->start_time;
3203 if( tstmp == AV_NOPTS_VALUE ) continue;
3204 int aidx = ffaudio.size();
3205 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3206 if( aidx < 0 ) continue;
3207 FFAudioStream *aud = ffaudio[aidx];
3208 tstmp -= aud->nudge;
3209 double secs = to_secs(tstmp, st->time_base);
3210 aud->curr_pos = secs * aud->sample_rate + 0.5;
3214 for( int64_t count=0; !*canceled; ++count ) {
3215 av_packet_unref(&pkt);
3216 pkt.data = 0; pkt.size = 0;
3218 int ret = av_read_frame(fmt_ctx, &pkt);
3220 if( ret == AVERROR_EOF ) break;
3221 if( ++errs > 100 ) {
3222 ff_err(ret,_("over 100 read_frame errs\n"));
3227 if( !pkt.data ) continue;
3228 int i = pkt.stream_index;
3229 if( i < 0 || i >= (int)fmt_ctx->nb_streams ) continue;
3230 AVStream *st = fmt_ctx->streams[i];
3231 if( pkt.pos > *scan_position ) *scan_position = pkt.pos;
3233 AVCodecParameters *avpar = st->codecpar;
3234 switch( avpar->codec_type ) {
3235 case AVMEDIA_TYPE_VIDEO: {
3236 int vidx = ffvideo.size();
3237 while( --vidx>=0 && ffvideo[vidx]->fidx != i );
3238 if( vidx < 0 ) break;
3239 FFVideoStream *vid = ffvideo[vidx];
3240 if( !vid->avctx ) break;
3241 int64_t tstmp = pkt.dts;
3242 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.pts;
3243 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3244 if( vid->nudge != AV_NOPTS_VALUE ) tstmp -= vid->nudge;
3245 double secs = to_secs(tstmp, st->time_base);
3246 int64_t frm = secs * vid->frame_rate + 0.5;
3247 if( frm < 0 ) frm = 0;
3248 index_state->put_video_mark(vidx, frm, pkt.pos);
3251 ret = avcodec_send_packet(vid->avctx, pkt);
3252 if( ret < 0 ) break;
3253 while( (ret=vid->decode_frame(frame)) > 0 ) {}
3256 case AVMEDIA_TYPE_AUDIO: {
3257 int aidx = ffaudio.size();
3258 while( --aidx>=0 && ffaudio[aidx]->fidx != i );
3259 if( aidx < 0 ) break;
3260 FFAudioStream *aud = ffaudio[aidx];
3261 if( !aud->avctx ) break;
3262 int64_t tstmp = pkt.pts;
3263 if( tstmp == AV_NOPTS_VALUE ) tstmp = pkt.dts;
3264 if( tstmp != AV_NOPTS_VALUE && (pkt.flags & AV_PKT_FLAG_KEY) && pkt.pos > 0 ) {
3265 if( aud->nudge != AV_NOPTS_VALUE ) tstmp -= aud->nudge;
3266 double secs = to_secs(tstmp, st->time_base);
3267 int64_t sample = secs * aud->sample_rate + 0.5;
3269 index_state->put_audio_mark(aidx, sample, pkt.pos);
3271 ret = avcodec_send_packet(aud->avctx, &pkt);
3272 if( ret < 0 ) break;
3273 int ch = aud->channel0, nch = aud->channels;
3274 int64_t pos = index_state->pos(ch);
3275 if( pos != aud->curr_pos ) {
3276 if( abs(pos-aud->curr_pos) > 1 )
3277 printf("audio%d pad %jd %jd (%jd)\n", aud->idx, pos, aud->curr_pos, pos-aud->curr_pos);
3278 index_state->pad_data(ch, nch, aud->curr_pos);
3280 while( (ret=aud->decode_frame(frame)) > 0 ) {
3281 //if( frame->channels != nch ) break;
3282 aud->init_swr(frame->channels, frame->format, frame->sample_rate);
3284 int len = aud->get_samples(samples,
3285 &frame->extended_data[0], frame->nb_samples);
3286 pos = aud->curr_pos;
3287 if( (aud->curr_pos += len) >= 0 ) {
3289 samples += -pos * nch;
3290 len = aud->curr_pos;
3292 for( int i=0; i<nch; ++i )
3293 index_state->put_data(ch+i,nch,samples+i,len);
3300 av_frame_free(&frame);
3304 void FFStream::load_markers(IndexMarks &marks, double rate)
3307 int64_t sz = marks.size();
3308 int max_entries = fmt_ctx->max_index_size / sizeof(AVIndexEntry) - 1;
3309 int nb_ent = st->nb_index_entries;
3310 // some formats already have an index
3312 AVIndexEntry *ep = &st->index_entries[nb_ent-1];
3313 int64_t tstmp = ep->timestamp;
3314 if( nudge != AV_NOPTS_VALUE ) tstmp -= nudge;
3315 double secs = ffmpeg->to_secs(tstmp, st->time_base);
3316 int64_t no = secs * rate;
3317 while( in < sz && marks[in].no <= no ) ++in;
3319 int64_t len = sz - in;
3320 int64_t count = max_entries - nb_ent;
3321 if( count > len ) count = len;
3322 for( int i=0; i<count; ++i ) {
3323 int k = in + i * len / count;
3324 int64_t no = marks[k].no, pos = marks[k].pos;
3325 double secs = (double)no / rate;
3326 int64_t tstmp = secs * st->time_base.den / st->time_base.num;
3327 if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
3328 av_add_index_entry(st, pos, tstmp, 0, 0, AVINDEX_KEYFRAME);