repair vaapi encode_frame, fix segv on unreadable asset, update crop resource icon...
[goodguy/cinelerra.git] / cinelerra-5.1 / cinelerra / ffmpeg.C
1
2 #include <stdio.h>
3 #include <stdint.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <stdarg.h>
8 #include <fcntl.h>
9 #include <limits.h>
10 #include <ctype.h>
11
12 // work arounds (centos)
13 #include <lzma.h>
14 #ifndef INT64_MAX
15 #define INT64_MAX 9223372036854775807LL
16 #endif
17 #define MAX_RETRY 1000
18 // max pts/curr_pos drift allowed before correction (in seconds)
19 #define AUDIO_PTS_TOLERANCE 0.04
20
21 #include "asset.h"
22 #include "bccmodels.h"
23 #include "bchash.h"
24 #include "edl.h"
25 #include "edlsession.h"
26 #include "file.h"
27 #include "fileffmpeg.h"
28 #include "filesystem.h"
29 #include "ffmpeg.h"
30 #include "indexfile.h"
31 #include "interlacemodes.h"
32 #include "libdv.h"
33 #include "libmjpeg.h"
34 #include "mainerror.h"
35 #include "mwindow.h"
36 #include "preferences.h"
37 #include "vframe.h"
38
39 #ifdef FFMPEG3
40 #define url filename
41 #else
42 #define av_register_all(s)
43 #define avfilter_register_all(s)
44 #endif
45
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
51
52 #define FF_ESTM_TIMES 0x0001
53 #define FF_BAD_TIMES  0x0002
54
55 Mutex FFMPEG::fflock("FFMPEG::fflock");
56
57 static void ff_err(int ret, const char *fmt, ...)
58 {
59         char msg[BCTEXTLEN];
60         va_list ap;
61         va_start(ap, fmt);
62         vsnprintf(msg, sizeof(msg), fmt, ap);
63         va_end(ap);
64         char errmsg[BCSTRLEN];
65         av_strerror(ret, errmsg, sizeof(errmsg));
66         fprintf(stderr,_("%s  err: %s\n"),msg, errmsg);
67 }
68
69 void FFPacket::init()
70 {
71         av_init_packet(&pkt);
72         pkt.data = 0; pkt.size = 0;
73 }
74 void FFPacket::finit()
75 {
76         av_packet_unref(&pkt);
77 }
78
79 FFrame::FFrame(FFStream *fst)
80 {
81         this->fst = fst;
82         frm = av_frame_alloc();
83         init = fst->init_frame(frm);
84 }
85
86 FFrame::~FFrame()
87 {
88         av_frame_free(&frm);
89 }
90
91 void FFrame::queue(int64_t pos)
92 {
93         position = pos;
94         fst->queue(this);
95 }
96
97 void FFrame::dequeue()
98 {
99         fst->dequeue(this);
100 }
101
102 void FFrame::set_hw_frame(AVFrame *frame)
103 {
104         av_frame_free(&frm);
105         frm = frame;
106 }
107
108 int FFAudioStream::read(float *fp, long len)
109 {
110         long n = len * nch;
111         float *op = outp;
112         while( n > 0 ) {
113                 int k = lmt - op;
114                 if( k > n ) k = n;
115                 n -= k;
116                 while( --k >= 0 ) *fp++ = *op++;
117                 if( op >= lmt ) op = bfr;
118         }
119         return len;
120 }
121
122 void FFAudioStream::realloc(long nsz, int nch, long len)
123 {
124         long bsz = nsz * nch;
125         float *np = new float[bsz];
126         inp = np + read(np, len) * nch;
127         outp = np;
128         lmt = np + bsz;
129         this->nch = nch;
130         sz = nsz;
131         delete [] bfr;  bfr = np;
132 }
133
134 void FFAudioStream::realloc(long nsz, int nch)
135 {
136         if( nsz > sz || this->nch != nch ) {
137                 long len = this->nch != nch ? 0 : hpos;
138                 if( len > sz ) len = sz;
139                 iseek(len);
140                 realloc(nsz, nch, len);
141         }
142 }
143
144 void FFAudioStream::reserve(long nsz, int nch)
145 {
146         long len = (inp - outp) / nch;
147         nsz += len;
148         if( nsz > sz || this->nch != nch ) {
149                 if( this->nch != nch ) len = 0;
150                 realloc(nsz, nch, len);
151                 return;
152         }
153         if( (len*=nch) > 0 && bfr != outp )
154                 memmove(bfr, outp, len*sizeof(*bfr));
155         outp = bfr;
156         inp = bfr + len;
157 }
158
159 long FFAudioStream::used()
160 {
161         long len = inp>=outp ? inp-outp : inp-bfr + lmt-outp;
162         return len / nch;
163 }
164 long FFAudioStream::avail()
165 {
166         float *in1 = inp+1;
167         if( in1 >= lmt ) in1 = bfr;
168         long len = outp >= in1 ? outp-in1 : outp-bfr + lmt-in1;
169         return len / nch;
170 }
171 void FFAudioStream::reset_history()
172 {
173         inp = outp = bfr;
174         hpos = 0;
175         memset(bfr, 0, lmt-bfr);
176 }
177
178 void FFAudioStream::iseek(int64_t ofs)
179 {
180         if( ofs > hpos ) ofs = hpos;
181         if( ofs > sz ) ofs = sz;
182         outp = inp - ofs*nch;
183         if( outp < bfr ) outp += sz*nch;
184 }
185
186 float *FFAudioStream::get_outp(int ofs)
187 {
188         float *ret = outp;
189         outp += ofs*nch;
190         return ret;
191 }
192
193 int64_t FFAudioStream::put_inp(int ofs)
194 {
195         inp += ofs*nch;
196         return (inp-outp) / nch;
197 }
198
199 int FFAudioStream::write(const float *fp, long len)
200 {
201         long n = len * nch;
202         float *ip = inp;
203         while( n > 0 ) {
204                 int k = lmt - ip;
205                 if( k > n ) k = n;
206                 n -= k;
207                 while( --k >= 0 ) *ip++ = *fp++;
208                 if( ip >= lmt ) ip = bfr;
209         }
210         inp = ip;
211         hpos += len;
212         return len;
213 }
214
215 int FFAudioStream::zero(long len)
216 {
217         long n = len * nch;
218         float *ip = inp;
219         while( n > 0 ) {
220                 int k = lmt - ip;
221                 if( k > n ) k = n;
222                 n -= k;
223                 while( --k >= 0 ) *ip++ = 0;
224                 if( ip >= lmt ) ip = bfr;
225         }
226         inp = ip;
227         hpos += len;
228         return len;
229 }
230
231 // does not advance outp
232 int FFAudioStream::read(double *dp, long len, int ch)
233 {
234         long n = len;
235         float *op = outp + ch;
236         float *lmt1 = lmt + nch-1;
237         while( n > 0 ) {
238                 int k = (lmt1 - op) / nch;
239                 if( k > n ) k = n;
240                 n -= k;
241                 while( --k >= 0 ) { *dp++ = *op;  op += nch; }
242                 if( op >= lmt ) op -= sz*nch;
243         }
244         return len;
245 }
246
247 // load linear buffer, no wrapping allowed, does not advance inp
248 int FFAudioStream::write(const double *dp, long len, int ch)
249 {
250         long n = len;
251         float *ip = inp + ch;
252         while( --n >= 0 ) { *ip = *dp++;  ip += nch; }
253         return len;
254 }
255
256
257 FFStream::FFStream(FFMPEG *ffmpeg, AVStream *st, int fidx)
258 {
259         this->ffmpeg = ffmpeg;
260         this->st = st;
261         this->fidx = fidx;
262         frm_lock = new Mutex("FFStream::frm_lock");
263         fmt_ctx = 0;
264         avctx = 0;
265         filter_graph = 0;
266         buffersrc_ctx = 0;
267         buffersink_ctx = 0;
268         frm_count = 0;
269         nudge = AV_NOPTS_VALUE;
270         seek_pos = curr_pos = 0;
271         seeked = 1;  eof = 0;
272         reading = writing = 0;
273         hw_pixfmt = AV_PIX_FMT_NONE;
274         hw_device_ctx = 0;
275         flushed = 0;
276         need_packet = 1;
277         frame = fframe = 0;
278         bsfc = 0;
279         stats_fp = 0;
280         stats_filename = 0;
281         stats_in = 0;
282         pass = 0;
283 }
284
285 FFStream::~FFStream()
286 {
287         if( reading > 0 || writing > 0 ) avcodec_close(avctx);
288         if( avctx ) avcodec_free_context(&avctx);
289         if( fmt_ctx ) avformat_close_input(&fmt_ctx);
290         if( hw_device_ctx ) av_buffer_unref(&hw_device_ctx);
291         if( bsfc ) av_bsf_free(&bsfc);
292         while( frms.first ) frms.remove(frms.first);
293         if( filter_graph ) avfilter_graph_free(&filter_graph);
294         if( frame ) av_frame_free(&frame);
295         if( fframe ) av_frame_free(&fframe);
296         delete frm_lock;
297         if( stats_fp ) fclose(stats_fp);
298         if( stats_in ) av_freep(&stats_in);
299         delete [] stats_filename;
300 }
301
302 void FFStream::ff_lock(const char *cp)
303 {
304         FFMPEG::fflock.lock(cp);
305 }
306
307 void FFStream::ff_unlock()
308 {
309         FFMPEG::fflock.unlock();
310 }
311
312 void FFStream::queue(FFrame *frm)
313 {
314         frm_lock->lock("FFStream::queue");
315         frms.append(frm);
316         ++frm_count;
317         frm_lock->unlock();
318         ffmpeg->mux_lock->unlock();
319 }
320
321 void FFStream::dequeue(FFrame *frm)
322 {
323         frm_lock->lock("FFStream::dequeue");
324         --frm_count;
325         frms.remove_pointer(frm);
326         frm_lock->unlock();
327 }
328
329 int FFStream::encode_activate()
330 {
331         if( writing < 0 )
332                 writing = ffmpeg->encode_activate();
333         return writing;
334 }
335
336 static AVPixelFormat hw_pix_fmt = AV_PIX_FMT_NONE; // protected by ff_lock
337 static enum AVPixelFormat get_hw_format(AVCodecContext *ctx,
338                         const enum AVPixelFormat *pix_fmts)
339 {
340         for( const enum AVPixelFormat *p=pix_fmts; *p!=AV_PIX_FMT_NONE; ++p )
341                 if( *p == hw_pix_fmt ) return *p;
342         fprintf(stderr, "Failed to get HW surface format.\n");
343         return hw_pix_fmt = AV_PIX_FMT_NONE;
344 }
345
346
347 AVHWDeviceType FFStream::decode_hw_activate()
348 {
349         return AV_HWDEVICE_TYPE_NONE;
350 }
351
352 int FFStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
353 {
354         return 0;
355 }
356
357 int FFStream::decode_activate()
358 {
359         if( reading < 0 && (reading=ffmpeg->decode_activate()) > 0 ) {
360                 ff_lock("FFStream::decode_activate");
361                 reading = 0;
362                 AVDictionary *copts = 0;
363                 av_dict_copy(&copts, ffmpeg->opts, 0);
364                 int ret = 0;
365                 AVHWDeviceType hw_type = decode_hw_activate();
366
367                 // this should be avformat_copy_context(), but no copy avail
368                 ret = avformat_open_input(&fmt_ctx,
369                         ffmpeg->fmt_ctx->url, ffmpeg->fmt_ctx->iformat, &copts);
370                 if( ret >= 0 ) {
371                         ret = avformat_find_stream_info(fmt_ctx, 0);
372                         st = fmt_ctx->streams[fidx];
373                         load_markers();
374                 }
375                 while( ret >= 0 && st != 0 && !reading ) {
376                         AVCodecID codec_id = st->codecpar->codec_id;
377                         AVCodec *decoder = 0;
378                         if( is_video() ) {
379                                 if( ffmpeg->opt_video_decoder )
380                                         decoder = avcodec_find_decoder_by_name(ffmpeg->opt_video_decoder);
381                                 else
382                                         ffmpeg->video_codec_remaps.update(codec_id, decoder);
383                         }
384                         else if( is_audio() ) {
385                                 if( ffmpeg->opt_audio_decoder )
386                                         decoder = avcodec_find_decoder_by_name(ffmpeg->opt_audio_decoder);
387                                 else
388                                         ffmpeg->audio_codec_remaps.update(codec_id, decoder);
389                         }
390                         if( !decoder )
391                                 decoder = avcodec_find_decoder(codec_id);
392                         avctx = avcodec_alloc_context3(decoder);
393                         if( !avctx ) {
394                                 eprintf(_("cant allocate codec context\n"));
395                                 ret = AVERROR(ENOMEM);
396                         }
397                         if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
398                                 ret = decode_hw_format(decoder, hw_type);
399                                 if( !ret ) hw_type = AV_HWDEVICE_TYPE_NONE;
400                         }
401                         if( ret >= 0 ) {
402                                 avcodec_parameters_to_context(avctx, st->codecpar);
403                                 if( !av_dict_get(copts, "threads", NULL, 0) )
404                                         avctx->thread_count = ffmpeg->ff_cpus();
405                                 ret = avcodec_open2(avctx, decoder, &copts);
406                         }
407                         if( ret >= 0 && hw_type != AV_HWDEVICE_TYPE_NONE ) {
408                                 if( need_packet ) {
409                                         need_packet = 0;
410                                         ret = read_packet();
411                                 }
412                                 if( ret >= 0 ) {
413                                         AVPacket *pkt = (AVPacket*)ipkt;
414                                         ret = avcodec_send_packet(avctx, pkt);
415                                         if( ret < 0 || hw_pix_fmt == AV_PIX_FMT_NONE ) {
416                                                 ff_err(ret, "HW device init failed, using SW decode.\nfile:%s\n",
417                                                         ffmpeg->fmt_ctx->url);
418                                                 avcodec_close(avctx);
419                                                 avcodec_free_context(&avctx);
420                                                 av_buffer_unref(&hw_device_ctx);
421                                                 hw_device_ctx = 0;
422                                                 hw_type = AV_HWDEVICE_TYPE_NONE;
423                                                 int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
424                                                 int idx = st->index;
425                                                 av_seek_frame(fmt_ctx, idx, INT64_MIN, flags);
426                                                 need_packet = 1;  flushed = 0;
427                                                 seeked = 1;  st_eof(0);
428                                                 ret = 0;
429                                                 continue;
430                                         }
431                                 }
432                         }
433                         if( ret >= 0 ) {
434                                 reading = 1;
435                         }
436                         else
437                                 eprintf(_("open decoder failed\n"));
438                 }
439                 if( ret < 0 )
440                         eprintf(_("can't open input file: %s\n"), ffmpeg->fmt_ctx->url);
441                 av_dict_free(&copts);
442                 ff_unlock();
443         }
444         return reading;
445 }
446
447 int FFStream::read_packet()
448 {
449         av_packet_unref(ipkt);
450         int ret = av_read_frame(fmt_ctx, ipkt);
451         if( ret < 0 ) {
452                 st_eof(1);
453                 if( ret == AVERROR_EOF ) return 0;
454                 ff_err(ret, "FFStream::read_packet: av_read_frame failed\n");
455                 flushed = 1;
456                 return -1;
457         }
458         return 1;
459 }
460
461 int FFStream::decode(AVFrame *frame)
462 {
463         int ret = 0;
464         int retries = MAX_RETRY;
465
466         while( ret >= 0 && !flushed && --retries >= 0 ) {
467                 if( need_packet ) {
468                         if( (ret=read_packet()) < 0 ) break;
469                         AVPacket *pkt = ret > 0 ? (AVPacket*)ipkt : 0;
470                         if( pkt ) {
471                                 if( pkt->stream_index != st->index ) continue;
472                                 if( !pkt->data || !pkt->size ) continue;
473                         }
474                         if( (ret=avcodec_send_packet(avctx, pkt)) < 0 ) {
475                                 ff_err(ret, "FFStream::decode: avcodec_send_packet failed.\nfile:%s\n",
476                                                 ffmpeg->fmt_ctx->url);
477                                 break;
478                         }
479                         need_packet = 0;
480                         retries = MAX_RETRY;
481                 }
482                 if( (ret=decode_frame(frame)) > 0 ) break;
483                 if( !ret ) {
484                         need_packet = 1;
485                         flushed = st_eof();
486                 }
487         }
488
489         if( retries < 0 ) {
490                 fprintf(stderr, "FFStream::decode: Retry limit\n");
491                 ret = 0;
492         }
493         if( ret < 0 )
494                 fprintf(stderr, "FFStream::decode: failed\n");
495         return ret;
496 }
497
498 int FFStream::load_filter(AVFrame *frame)
499 {
500         int ret = av_buffersrc_add_frame_flags(buffersrc_ctx, frame, 0);
501         if( ret < 0 )
502                 eprintf(_("av_buffersrc_add_frame_flags failed\n"));
503         return ret;
504 }
505
506 int FFStream::read_filter(AVFrame *frame)
507 {
508         int ret = av_buffersink_get_frame(buffersink_ctx, frame);
509         if( ret < 0 ) {
510                 if( ret == AVERROR(EAGAIN) ) return 0;
511                 if( ret == AVERROR_EOF ) { st_eof(1); return -1; }
512                 ff_err(ret, "FFStream::read_filter: av_buffersink_get_frame failed\n");
513                 return ret;
514         }
515         return 1;
516 }
517
518 int FFStream::read_frame(AVFrame *frame)
519 {
520         av_frame_unref(frame);
521         if( !filter_graph || !buffersrc_ctx || !buffersink_ctx )
522                 return decode(frame);
523         if( !fframe && !(fframe=av_frame_alloc()) ) {
524                 fprintf(stderr, "FFStream::read_frame: av_frame_alloc failed\n");
525                 return -1;
526         }
527         int ret = -1;
528         while( !flushed && !(ret=read_filter(frame)) ) {
529                 if( (ret=decode(fframe)) < 0 ) break;
530                 if( ret > 0 && (ret=load_filter(fframe)) < 0 ) break;
531         }
532         return ret;
533 }
534
535 int FFStream::write_packet(FFPacket &pkt)
536 {
537         int ret = 0;
538         if( !bsfc ) {
539                 av_packet_rescale_ts(pkt, avctx->time_base, st->time_base);
540                 pkt->stream_index = st->index;
541                 ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, pkt);
542         }
543         else {
544                 ret = av_bsf_send_packet(bsfc, pkt);
545                 while( ret >= 0 ) {
546                         FFPacket bs;
547                         if( (ret=av_bsf_receive_packet(bsfc, bs)) < 0 ) {
548                                 if( ret == AVERROR(EAGAIN) ) return 0;
549                                 if( ret == AVERROR_EOF ) return -1;
550                                 break;
551                         }
552                         av_packet_rescale_ts(bs, avctx->time_base, st->time_base);
553                         bs->stream_index = st->index;
554                         ret = av_interleaved_write_frame(ffmpeg->fmt_ctx, bs);
555                 }
556         }
557         if( ret < 0 )
558                 ff_err(ret, "FFStream::write_packet: write packet failed.\nfile:%s\n",
559                                 ffmpeg->fmt_ctx->url);
560         return ret;
561 }
562
563 int FFStream::encode_frame(AVFrame *frame)
564 {
565         int pkts = 0, ret = 0;
566         for( int retry=MAX_RETRY; --retry>=0; ) {
567                 if( frame || !pkts )
568                         ret = avcodec_send_frame(avctx, frame);
569                 if( !ret && frame ) return pkts;
570                 if( ret < 0 && ret != AVERROR(EAGAIN) ) break;
571                 FFPacket opkt;
572                 ret = avcodec_receive_packet(avctx, opkt);
573                 if( !frame && ret == AVERROR_EOF ) return pkts;
574                 if( ret < 0 ) break;
575                 ret = write_packet(opkt);
576                 if( ret < 0 ) break;
577                 ++pkts;
578                 if( frame && stats_fp ) {
579                         ret = write_stats_file();
580                         if( ret < 0 ) break;
581                 }
582         }
583         ff_err(ret, "FFStream::encode_frame: encode failed.\nfile: %s\n",
584                                 ffmpeg->fmt_ctx->url);
585         return -1;
586 }
587
588 int FFStream::flush()
589 {
590         if( writing < 0 )
591                 return -1;
592         int ret = encode_frame(0);
593         if( ret >= 0 && stats_fp ) {
594                 ret = write_stats_file();
595                 close_stats_file();
596         }
597         if( ret < 0 )
598                 ff_err(ret, "FFStream::flush failed\n:file:%s\n",
599                                 ffmpeg->fmt_ctx->url);
600         return ret >= 0 ? 0 : 1;
601 }
602
603
604 int FFStream::open_stats_file()
605 {
606         stats_fp = fopen(stats_filename,"w");
607         return stats_fp ? 0 : AVERROR(errno);
608 }
609
610 int FFStream::close_stats_file()
611 {
612         if( stats_fp ) {
613                 fclose(stats_fp);  stats_fp = 0;
614         }
615         return 0;
616 }
617
618 int FFStream::read_stats_file()
619 {
620         int64_t len = 0;  struct stat stats_st;
621         int fd = open(stats_filename, O_RDONLY);
622         int ret = fd >= 0 ? 0: ENOENT;
623         if( !ret && fstat(fd, &stats_st) )
624                 ret = EINVAL;
625         if( !ret ) {
626                 len = stats_st.st_size;
627                 stats_in = (char *)av_malloc(len+1);
628                 if( !stats_in )
629                         ret = ENOMEM;
630         }
631         if( !ret && read(fd, stats_in, len+1) != len )
632                 ret = EIO;
633         if( !ret ) {
634                 stats_in[len] = 0;
635                 avctx->stats_in = stats_in;
636         }
637         if( fd >= 0 )
638                 close(fd);
639         return !ret ? 0 : AVERROR(ret);
640 }
641
642 int FFStream::write_stats_file()
643 {
644         int ret = 0;
645         if( avctx->stats_out && (ret=strlen(avctx->stats_out)) > 0 ) {
646                 int len = fwrite(avctx->stats_out, 1, ret, stats_fp);
647                 if( ret != len )
648                         ff_err(ret = AVERROR(errno), "FFStream::write_stats_file.\n%file:%s\n",
649                                 ffmpeg->fmt_ctx->url);
650         }
651         return ret;
652 }
653
654 int FFStream::init_stats_file()
655 {
656         int ret = 0;
657         if( (pass & 2) && (ret = read_stats_file()) < 0 )
658                 ff_err(ret, "stat file read: %s", stats_filename);
659         if( (pass & 1) && (ret=open_stats_file()) < 0 )
660                 ff_err(ret, "stat file open: %s", stats_filename);
661         return ret >= 0 ? 0 : ret;
662 }
663
664 int FFStream::seek(int64_t no, double rate)
665 {
666 // default ffmpeg native seek
667         int npkts = 1;
668         int64_t pos = no, pkt_pos = -1;
669         IndexMarks *index_markers = get_markers();
670         if( index_markers && index_markers->size() > 1 ) {
671                 IndexMarks &marks = *index_markers;
672                 int i = marks.find(pos);
673                 int64_t n = i < 0 ? (i=0) : marks[i].no;
674 // if indexed seek point not too far away (<30 secs), use index
675                 if( no-n < 30*rate ) {
676                         if( n < 0 ) n = 0;
677                         pos = n;
678                         if( i < marks.size() ) pkt_pos = marks[i].pos;
679                         npkts = MAX_RETRY;
680                 }
681         }
682         if( pos == curr_pos ) return 0;
683         double secs = pos < 0 ? 0. : pos / rate;
684         AVRational time_base = st->time_base;
685         int64_t tstmp = time_base.num > 0 ? secs * time_base.den/time_base.num : 0;
686         if( !tstmp ) {
687                 if( st->nb_index_entries > 0 ) tstmp = st->index_entries[0].timestamp;
688                 else if( st->start_time != AV_NOPTS_VALUE ) tstmp = st->start_time;
689                 else if( st->first_dts != AV_NOPTS_VALUE ) tstmp = st->first_dts;
690                 else tstmp = INT64_MIN+1;
691         }
692         else if( nudge != AV_NOPTS_VALUE ) tstmp += nudge;
693         int idx = st->index;
694 #if 0
695 // seek all streams using the default timebase.
696 //   this is how ffmpeg and ffplay work.  stream seeks are less tested.
697         tstmp = av_rescale_q(tstmp, time_base, AV_TIME_BASE_Q);
698         idx = -1;
699 #endif
700
701         avcodec_flush_buffers(avctx);
702         avformat_flush(fmt_ctx);
703 #if 0
704         int64_t seek = tstmp;
705         int flags = AVSEEK_FLAG_ANY;
706         if( !(fmt_ctx->iformat->flags & AVFMT_NO_BYTE_SEEK) && pkt_pos >= 0 ) {
707                 seek = pkt_pos;
708                 flags = AVSEEK_FLAG_BYTE;
709         }
710         int ret = avformat_seek_file(fmt_ctx, st->index, -INT64_MAX, seek, INT64_MAX, flags);
711 #else
712 // finds the first index frame below the target time
713         int flags = AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY;
714         int ret = av_seek_frame(fmt_ctx, idx, tstmp, flags);
715 #endif
716         int retry = MAX_RETRY;
717         while( ret >= 0 ) {
718                 need_packet = 0;  flushed = 0;
719                 seeked = 1;  st_eof(0);
720 // read up to retry packets, limited to npkts in stream, and not pkt.pos past pkt_pos
721                 while( --retry >= 0 ) {
722                         if( read_packet() <= 0 ) { ret = -1;  break; }
723                         if( ipkt->stream_index != st->index ) continue;
724                         if( !ipkt->data || !ipkt->size ) continue;
725                         if( pkt_pos >= 0 && ipkt->pos >= pkt_pos ) break;
726                         if( --npkts <= 0 ) break;
727                         int64_t pkt_ts = ipkt->dts != AV_NOPTS_VALUE ? ipkt->dts : ipkt->pts;
728                         if( pkt_ts == AV_NOPTS_VALUE ) continue;
729                         if( pkt_ts >= tstmp ) break;
730                 }
731                 if( retry < 0 ) {
732                         fprintf(stderr,"FFStream::seek: retry limit, pos=%jd tstmp=%jd\n",pos,tstmp);
733                         ret = -1;
734                 }
735                 if( ret < 0 ) break;
736                 ret = avcodec_send_packet(avctx, ipkt);
737                 if( !ret ) break;
738 //some codecs need more than one pkt to resync
739                 if( ret == AVERROR_INVALIDDATA ) ret = 0;
740                 if( ret < 0 ) {
741                         ff_err(ret, "FFStream::avcodec_send_packet failed.\nseek:%s\n",
742                                 ffmpeg->fmt_ctx->url);
743                         break;
744                 }
745         }
746         if( ret < 0 ) {
747 printf("** seek fail %jd, %jd\n", pos, tstmp);
748                 seeked = need_packet = 0;
749                 st_eof(flushed=1);
750                 return -1;
751         }
752 //printf("seeked pos = %ld, %ld\n", pos, tstmp);
753         seek_pos = curr_pos = pos;
754         return 0;
755 }
756
757 FFAudioStream::FFAudioStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
758  : FFStream(ffmpeg, strm, fidx)
759 {
760         this->idx = idx;
761         channel0 = channels = 0;
762         sample_rate = 0;
763         mbsz = 0;
764         frame_sz = AUDIO_MIN_FRAME_SZ;
765         length = 0;
766         resample_context = 0;
767         swr_ichs = swr_ifmt = swr_irate = 0;
768
769         aud_bfr_sz = 0;
770         aud_bfr = 0;
771
772 // history buffer
773         nch = 2;
774         sz = 0x10000;
775         long bsz = sz * nch;
776         bfr = new float[bsz];
777         lmt = bfr + bsz;
778         reset_history();
779 }
780
781 FFAudioStream::~FFAudioStream()
782 {
783         if( resample_context ) swr_free(&resample_context);
784         delete [] aud_bfr;
785         delete [] bfr;
786 }
787
788 void FFAudioStream::init_swr(int ichs, int ifmt, int irate)
789 {
790         if( resample_context ) {
791                 if( swr_ichs == ichs && swr_ifmt == ifmt && swr_irate == irate )
792                         return;
793                 swr_free(&resample_context);
794         }
795         swr_ichs = ichs;  swr_ifmt = ifmt;  swr_irate = irate;
796         if( ichs == channels && ifmt == AV_SAMPLE_FMT_FLT && irate == sample_rate )
797                 return;
798         uint64_t ilayout = av_get_default_channel_layout(ichs);
799         if( !ilayout ) ilayout = ((uint64_t)1<<ichs) - 1;
800         uint64_t olayout = av_get_default_channel_layout(channels);
801         if( !olayout ) olayout = ((uint64_t)1<<channels) - 1;
802         resample_context = swr_alloc_set_opts(NULL,
803                 olayout, AV_SAMPLE_FMT_FLT, sample_rate,
804                 ilayout, (AVSampleFormat)ifmt, irate,
805                 0, NULL);
806         if( resample_context )
807                 swr_init(resample_context);
808 }
809
810 int FFAudioStream::get_samples(float *&samples, uint8_t **data, int len)
811 {
812         samples = *(float **)data;
813         if( resample_context ) {
814                 if( len > aud_bfr_sz ) {
815                         delete [] aud_bfr;
816                         aud_bfr = 0;
817                 }
818                 if( !aud_bfr ) {
819                         aud_bfr_sz = len;
820                         aud_bfr = new float[aud_bfr_sz*channels];
821                 }
822                 int ret = swr_convert(resample_context,
823                         (uint8_t**)&aud_bfr, aud_bfr_sz, (const uint8_t**)data, len);
824                 if( ret < 0 ) {
825                         ff_err(ret, "FFAudioStream::get_samples: swr_convert failed\n");
826                         return -1;
827                 }
828                 samples = aud_bfr;
829                 len = ret;
830         }
831         return len;
832 }
833
834 int FFAudioStream::load_history(uint8_t **data, int len)
835 {
836         float *samples;
837         len = get_samples(samples, data, len);
838         if( len > 0 ) {
839                 // biggest user bfr since seek + frame
840                 realloc(mbsz + len + 1, channels);
841                 write(samples, len);
842         }
843         return len;
844 }
845
846 int FFAudioStream::decode_frame(AVFrame *frame)
847 {
848         int first_frame = seeked;  seeked = 0;
849         frame->best_effort_timestamp = AV_NOPTS_VALUE;
850         int ret = avcodec_receive_frame(avctx, frame);
851         if( ret < 0 ) {
852                 if( first_frame ) return 0;
853                 if( ret == AVERROR(EAGAIN) ) return 0;
854                 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
855                 ff_err(ret, "FFAudioStream::decode_frame: Could not read audio frame.\nfile:%s\n",
856                                 ffmpeg->fmt_ctx->url);
857                 return -1;
858         }
859         int64_t pkt_ts = frame->best_effort_timestamp;
860         if( pkt_ts != AV_NOPTS_VALUE ) {
861                 double ts = ffmpeg->to_secs(pkt_ts - nudge, st->time_base);
862                 double t = (double)curr_pos / sample_rate;
863 // some time_base clocks are very grainy, too grainy for audio (clicks, pops)
864                 if( fabs(ts - t) > AUDIO_PTS_TOLERANCE )
865                         curr_pos = ts * sample_rate + 0.5;
866         }
867         return 1;
868 }
869
870 int FFAudioStream::encode_activate()
871 {
872         if( writing >= 0 ) return writing;
873         if( !avctx->codec ) return writing = 0;
874         frame_sz = avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE ?
875                 10000 : avctx->frame_size;
876         return FFStream::encode_activate();
877 }
878
879 int64_t FFAudioStream::load_buffer(double ** const sp, int len)
880 {
881         reserve(len+1, st->codecpar->channels);
882         for( int ch=0; ch<nch; ++ch )
883                 write(sp[ch], len, ch);
884         return put_inp(len);
885 }
886
887 int FFAudioStream::in_history(int64_t pos)
888 {
889         if( pos > curr_pos ) return 0;
890         int64_t len = hpos;
891         if( len > sz ) len = sz;
892         if( pos < curr_pos - len ) return 0;
893         return 1;
894 }
895
896
897 int FFAudioStream::init_frame(AVFrame *frame)
898 {
899         frame->nb_samples = frame_sz;
900         frame->format = avctx->sample_fmt;
901         frame->channel_layout = avctx->channel_layout;
902         frame->sample_rate = avctx->sample_rate;
903         int ret = av_frame_get_buffer(frame, 0);
904         if (ret < 0)
905                 ff_err(ret, "FFAudioStream::init_frame: av_frame_get_buffer failed\n");
906         return ret;
907 }
908
909 int FFAudioStream::load(int64_t pos, int len)
910 {
911         if( audio_seek(pos) < 0 ) return -1;
912         if( !frame && !(frame=av_frame_alloc()) ) {
913                 fprintf(stderr, "FFAudioStream::load: av_frame_alloc failed\n");
914                 return -1;
915         }
916         if( mbsz < len ) mbsz = len;
917         int64_t end_pos = pos + len;
918         int ret = 0, i = len / frame_sz + MAX_RETRY;
919         while( ret>=0 && !flushed && curr_pos<end_pos && --i>=0 ) {
920                 ret = read_frame(frame);
921                 if( ret > 0 && frame->nb_samples > 0 ) {
922                         init_swr(frame->channels, frame->format, frame->sample_rate);
923                         load_history(&frame->extended_data[0], frame->nb_samples);
924                         curr_pos += frame->nb_samples;
925                 }
926         }
927         if( end_pos > curr_pos ) {
928                 zero(end_pos - curr_pos);
929                 curr_pos = end_pos;
930         }
931         len = curr_pos - pos;
932         iseek(len);
933         return len;
934 }
935
936 int FFAudioStream::audio_seek(int64_t pos)
937 {
938         if( decode_activate() <= 0 ) return -1;
939         if( !st->codecpar ) return -1;
940         if( in_history(pos) ) return 0;
941         if( pos == curr_pos ) return 0;
942         reset_history();  mbsz = 0;
943 // guarentee preload > 1sec samples
944         if( (pos-=sample_rate) < 0 ) pos = 0;
945         if( seek(pos, sample_rate) < 0 ) return -1;
946         return 1;
947 }
948
949 int FFAudioStream::encode(double **samples, int len)
950 {
951         if( encode_activate() <= 0 ) return -1;
952         ffmpeg->flow_ctl();
953         int ret = 0;
954         int64_t count = samples ? load_buffer(samples, len) : used();
955         int frame_sz1 = samples ? frame_sz-1 : 0;
956         FFrame *frm = 0;
957
958         while( ret >= 0 && count > frame_sz1 ) {
959                 frm = new FFrame(this);
960                 if( (ret=frm->initted()) < 0 ) break;
961                 AVFrame *frame = *frm;
962                 len = count >= frame_sz ? frame_sz : count;
963                 float *bfrp = get_outp(len);
964                 ret =  swr_convert(resample_context,
965                         (uint8_t **)frame->extended_data, len,
966                         (const uint8_t **)&bfrp, len);
967                 if( ret < 0 ) {
968                         ff_err(ret, "FFAudioStream::encode: swr_convert failed\n");
969                         break;
970                 }
971                 frame->nb_samples = len;
972                 frm->queue(curr_pos);
973                 frm = 0;
974                 curr_pos += len;
975                 count -= len;
976         }
977
978         delete frm;
979         return ret >= 0 ? 0 : 1;
980 }
981
982 int FFAudioStream::drain()
983 {
984         return encode(0,0);
985 }
986
987 int FFAudioStream::encode_frame(AVFrame *frame)
988 {
989         return FFStream::encode_frame(frame);
990 }
991
992 int FFAudioStream::write_packet(FFPacket &pkt)
993 {
994         return FFStream::write_packet(pkt);
995 }
996
997 void FFAudioStream::load_markers()
998 {
999         IndexState *index_state = ffmpeg->file_base->asset->index_state;
1000         if( !index_state || idx >= index_state->audio_markers.size() ) return;
1001         if( index_state->marker_status == MARKERS_NOTTESTED ) return;
1002         FFStream::load_markers(*index_state->audio_markers[idx], sample_rate);
1003 }
1004
1005 IndexMarks *FFAudioStream::get_markers()
1006 {
1007         IndexState *index_state = ffmpeg->file_base->asset->index_state;
1008         if( !index_state || idx >= index_state->audio_markers.size() ) return 0;
1009         return index_state->audio_markers[idx];
1010 }
1011
1012 FFVideoStream::FFVideoStream(FFMPEG *ffmpeg, AVStream *strm, int idx, int fidx)
1013  : FFStream(ffmpeg, strm, fidx)
1014 {
1015         this->idx = idx;
1016         width = height = 0;
1017         frame_rate = 0;
1018         aspect_ratio = 0;
1019         length = 0;
1020         interlaced = 0;
1021         top_field_first = 0;
1022 }
1023
1024 FFVideoStream::~FFVideoStream()
1025 {
1026 }
1027
1028 AVHWDeviceType FFVideoStream::decode_hw_activate()
1029 {
1030         AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1031         const char *hw_dev = ffmpeg->opt_hw_dev;
1032         if( !hw_dev ) hw_dev = getenv("CIN_HW_DEV");
1033         if( !hw_dev ) hw_dev = ffmpeg->ff_hw_dev();
1034         if( hw_dev && *hw_dev && strcmp(_("none"), hw_dev) ) {
1035                 type = av_hwdevice_find_type_by_name(hw_dev);
1036                 if( type == AV_HWDEVICE_TYPE_NONE ) {
1037                         fprintf(stderr, "Device type %s is not supported.\n", hw_dev);
1038                         fprintf(stderr, "Available device types:");
1039                         while( (type = av_hwdevice_iterate_types(type)) != AV_HWDEVICE_TYPE_NONE )
1040                                 fprintf(stderr, " %s", av_hwdevice_get_type_name(type));
1041                         fprintf(stderr, "\n");
1042                 }
1043         }
1044         return type;
1045 }
1046
1047 int FFVideoStream::decode_hw_format(AVCodec *decoder, AVHWDeviceType type)
1048 {
1049         int ret = 0;
1050         hw_pix_fmt = AV_PIX_FMT_NONE;
1051         for( int i=0; ; ++i ) {
1052                 const AVCodecHWConfig *config = avcodec_get_hw_config(decoder, i);
1053                 if( !config ) {
1054                         fprintf(stderr, "Decoder %s does not support device type %s.\n",
1055                                 decoder->name, av_hwdevice_get_type_name(type));
1056                         break;
1057                 }
1058                 if( (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX) != 0 &&
1059                     config->device_type == type ) {
1060                         hw_pix_fmt = config->pix_fmt;
1061                         break;
1062                 }
1063         }
1064         if( hw_pix_fmt >= 0 ) {
1065                 hw_pixfmt = hw_pix_fmt;
1066                 avctx->get_format  = get_hw_format;
1067                 ret = av_hwdevice_ctx_create(&hw_device_ctx, type, 0, 0, 0);
1068                 if( ret >= 0 ) {
1069                         avctx->hw_device_ctx = av_buffer_ref(hw_device_ctx);
1070                         ret = 1;
1071                 }
1072                 else
1073                         ff_err(ret, "Failed HW device create.\ndev:%s\n",
1074                                 av_hwdevice_get_type_name(type));
1075         }
1076         return ret;
1077 }
1078
1079 AVHWDeviceType FFVideoStream::encode_hw_activate(const char *hw_dev)
1080 {
1081         AVBufferRef *hw_device_ctx = 0;
1082         AVBufferRef *hw_frames_ref = 0;
1083         AVHWDeviceType type = AV_HWDEVICE_TYPE_NONE;
1084         if( strcmp(_("none"), hw_dev) ) {
1085                 type = av_hwdevice_find_type_by_name(hw_dev);
1086                 if( type != AV_HWDEVICE_TYPE_VAAPI ) {
1087                         fprintf(stderr, "currently, only vaapi hw encode is supported\n");
1088                         type = AV_HWDEVICE_TYPE_NONE;
1089                 }
1090         }
1091         if( type != AV_HWDEVICE_TYPE_NONE ) {
1092                 int ret = av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI, 0, 0, 0);
1093                 if( ret < 0 ) {
1094                         ff_err(ret, "Failed to create a HW device.\n");
1095                         type = AV_HWDEVICE_TYPE_NONE;
1096                 }
1097         }
1098         if( type != AV_HWDEVICE_TYPE_NONE ) {
1099                 hw_frames_ref = av_hwframe_ctx_alloc(hw_device_ctx);
1100                 if( !hw_frames_ref ) {
1101                         fprintf(stderr, "Failed to create HW frame context.\n");
1102                         type = AV_HWDEVICE_TYPE_NONE;
1103                 }
1104         }
1105         if( type != AV_HWDEVICE_TYPE_NONE ) {
1106                 AVHWFramesContext *frames_ctx = (AVHWFramesContext *)(hw_frames_ref->data);
1107                 frames_ctx->format = AV_PIX_FMT_VAAPI;
1108                 frames_ctx->sw_format = AV_PIX_FMT_NV12;
1109                 frames_ctx->width = width;
1110                 frames_ctx->height = height;
1111                 frames_ctx->initial_pool_size = 0; // 200;
1112                 int ret = av_hwframe_ctx_init(hw_frames_ref);
1113                 if( ret >= 0 ) {
1114                         avctx->hw_frames_ctx = av_buffer_ref(hw_frames_ref);
1115                         if( !avctx->hw_frames_ctx ) ret = AVERROR(ENOMEM);
1116                 }
1117                 if( ret < 0 ) {
1118                         ff_err(ret, "Failed to initialize HW frame context.\n");
1119                         type = AV_HWDEVICE_TYPE_NONE;
1120                 }
1121                 av_buffer_unref(&hw_frames_ref);
1122         }
1123         return type;
1124 }
1125
1126 int FFVideoStream::encode_hw_write(FFrame *picture)
1127 {
1128         int ret = 0;
1129         AVFrame *hw_frm = 0;
1130         switch( avctx->pix_fmt ) {
1131         case AV_PIX_FMT_VAAPI:
1132                 hw_frm = av_frame_alloc();
1133                 if( !hw_frm ) { ret = AVERROR(ENOMEM);  break; }
1134                 ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, hw_frm, 0);
1135                 if( ret < 0 ) break;
1136                 ret = av_hwframe_transfer_data(hw_frm, *picture, 0);
1137                 if( ret < 0 ) break;
1138                 picture->set_hw_frame(hw_frm);
1139                 return 0;
1140         default:
1141                 return 0;
1142         }
1143         av_frame_free(&hw_frm);
1144         ff_err(ret, "Error while transferring frame data to GPU.\n");
1145         return ret;
1146 }
1147
1148 int FFVideoStream::decode_frame(AVFrame *frame)
1149 {
1150         int first_frame = seeked;  seeked = 0;
1151         int ret = avcodec_receive_frame(avctx, frame);
1152         if( ret < 0 ) {
1153                 if( first_frame ) return 0;
1154                 if( ret == AVERROR(EAGAIN) ) return 0;
1155                 if( ret == AVERROR_EOF ) { st_eof(1); return 0; }
1156                 ff_err(ret, "FFVideoStream::decode_frame: Could not read video frame.\nfile:%s\n,",
1157                                 ffmpeg->fmt_ctx->url);
1158                 return -1;
1159         }
1160         int64_t pkt_ts = frame->best_effort_timestamp;
1161         if( pkt_ts != AV_NOPTS_VALUE )
1162                 curr_pos = ffmpeg->to_secs(pkt_ts - nudge, st->time_base) * frame_rate + 0.5;
1163         return 1;
1164 }
1165
1166 int FFVideoStream::load(VFrame *vframe, int64_t pos)
1167 {
1168         int ret = video_seek(pos);
1169         if( ret < 0 ) return -1;
1170         if( !frame && !(frame=av_frame_alloc()) ) {
1171                 fprintf(stderr, "FFVideoStream::load: av_frame_alloc failed\n");
1172                 return -1;
1173         }
1174         int i = MAX_RETRY + pos - curr_pos;
1175         while( ret>=0 && !flushed && curr_pos<=pos && --i>=0 ) {
1176                 ret = read_frame(frame);
1177                 if( ret > 0 ) ++curr_pos;
1178         }
1179         if( frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0 )
1180                 ret = -1;
1181         if( ret >= 0 ) {
1182                 ret = convert_cmodel(vframe, frame);
1183         }
1184         ret = ret > 0 ? 1 : ret < 0 ? -1 : 0;
1185         return ret;
1186 }
1187
1188 int FFVideoStream::video_seek(int64_t pos)
1189 {
1190         if( decode_activate() <= 0 ) return -1;
1191         if( !st->codecpar ) return -1;
1192         if( pos == curr_pos-1 && !seeked ) return 0;
1193 // if close enough, just read up to current
1194         int gop = avctx->gop_size;
1195         if( gop < 4 ) gop = 4;
1196         if( gop > 64 ) gop = 64;
1197         int read_limit = curr_pos + 3*gop;
1198         if( pos >= curr_pos && pos <= read_limit ) return 0;
1199 // guarentee preload more than 2*gop frames
1200         if( seek(pos - 3*gop, frame_rate) < 0 ) return -1;
1201         return 1;
1202 }
1203
1204 int FFVideoStream::init_frame(AVFrame *picture)
1205 {
1206         switch( avctx->pix_fmt ) {
1207         case AV_PIX_FMT_VAAPI:
1208                 picture->format = AV_PIX_FMT_NV12;
1209                 break;
1210         default:
1211                 picture->format = avctx->pix_fmt;
1212                 break;
1213         }
1214         picture->width  = avctx->width;
1215         picture->height = avctx->height;
1216         int ret = av_frame_get_buffer(picture, 32);
1217         return ret;
1218 }
1219
1220 int FFVideoStream::encode(VFrame *vframe)
1221 {
1222         if( encode_activate() <= 0 ) return -1;
1223         ffmpeg->flow_ctl();
1224         FFrame *picture = new FFrame(this);
1225         int ret = picture->initted();
1226         if( ret >= 0 ) {
1227                 AVFrame *frame = *picture;
1228                 frame->pts = curr_pos;
1229                 ret = convert_pixfmt(vframe, frame);
1230         }
1231         if( ret >= 0 && avctx->hw_frames_ctx )
1232                 encode_hw_write(picture);
1233         if( ret >= 0 ) {
1234                 picture->queue(curr_pos);
1235                 ++curr_pos;
1236         }
1237         else {
1238                 fprintf(stderr, "FFVideoStream::encode: encode failed\n");
1239                 delete picture;
1240         }
1241         return ret >= 0 ? 0 : 1;
1242 }
1243
1244 int FFVideoStream::drain()
1245 {
1246         return 0;
1247 }
1248
1249 int FFVideoStream::encode_frame(AVFrame *frame)
1250 {
1251         if( frame ) {
1252                 frame->interlaced_frame = interlaced;
1253                 frame->top_field_first = top_field_first;
1254         }
1255         if( frame && frame->format == AV_PIX_FMT_VAAPI ) { // ugly
1256                 int ret = avcodec_send_frame(avctx, frame);
1257                 for( int retry=MAX_RETRY; !ret && --retry>=0; ) {
1258                         FFPacket pkt;  av_init_packet(pkt);
1259                         pkt->data = NULL;  pkt->size = 0;
1260                         if( (ret=avcodec_receive_packet(avctx, pkt)) < 0 ) {
1261                                 if( ret == AVERROR(EAGAIN) ) ret = 0; // weird
1262                                 break;
1263                         }
1264                         ret = write_packet(pkt);
1265                         pkt->stream_index = 0;
1266                         av_packet_unref(pkt);
1267                 }
1268                 if( ret < 0 ) {
1269                         ff_err(ret, "FFStream::encode_frame: vaapi encode failed.\nfile: %s\n",
1270                                 ffmpeg->fmt_ctx->url);
1271                         return -1;
1272                 }
1273                 return 0;
1274         }
1275         return FFStream::encode_frame(frame);
1276 }
1277
1278 int FFVideoStream::write_packet(FFPacket &pkt)
1279 {
1280         if( !(ffmpeg->fmt_ctx->oformat->flags & AVFMT_VARIABLE_FPS) )
1281                 pkt->duration = 1;
1282         return FFStream::write_packet(pkt);
1283 }
1284
1285 AVPixelFormat FFVideoConvert::color_model_to_pix_fmt(int color_model)
1286 {
1287         switch( color_model ) {
1288         case BC_YUV422:         return AV_PIX_FMT_YUYV422;
1289         case BC_RGB888:         return AV_PIX_FMT_RGB24;
1290         case BC_RGBA8888:       return AV_PIX_FMT_RGBA;
1291         case BC_BGR8888:        return AV_PIX_FMT_BGR0;
1292         case BC_BGR888:         return AV_PIX_FMT_BGR24;
1293         case BC_ARGB8888:       return AV_PIX_FMT_ARGB;
1294         case BC_ABGR8888:       return AV_PIX_FMT_ABGR;
1295         case BC_RGB8:           return AV_PIX_FMT_RGB8;
1296         case BC_YUV420P:        return AV_PIX_FMT_YUV420P;
1297         case BC_YUV422P:        return AV_PIX_FMT_YUV422P;
1298         case BC_YUV444P:        return AV_PIX_FMT_YUV444P;
1299         case BC_YUV411P:        return AV_PIX_FMT_YUV411P;
1300         case BC_RGB565:         return AV_PIX_FMT_RGB565;
1301         case BC_RGB161616:      return AV_PIX_FMT_RGB48LE;
1302         case BC_RGBA16161616:   return AV_PIX_FMT_RGBA64LE;
1303         case BC_AYUV16161616:   return AV_PIX_FMT_AYUV64LE;
1304         case BC_GBRP:           return AV_PIX_FMT_GBRP;
1305         default: break;
1306         }
1307
1308         return AV_PIX_FMT_NB;
1309 }
1310
1311 int FFVideoConvert::pix_fmt_to_color_model(AVPixelFormat pix_fmt)
1312 {
1313         switch (pix_fmt) {
1314         case AV_PIX_FMT_YUYV422:        return BC_YUV422;
1315         case AV_PIX_FMT_RGB24:          return BC_RGB888;
1316         case AV_PIX_FMT_RGBA:           return BC_RGBA8888;
1317         case AV_PIX_FMT_BGR0:           return BC_BGR8888;
1318         case AV_PIX_FMT_BGR24:          return BC_BGR888;
1319         case AV_PIX_FMT_ARGB:           return BC_ARGB8888;
1320         case AV_PIX_FMT_ABGR:           return BC_ABGR8888;
1321         case AV_PIX_FMT_RGB8:           return BC_RGB8;
1322         case AV_PIX_FMT_YUV420P:        return BC_YUV420P;
1323         case AV_PIX_FMT_YUV422P:        return BC_YUV422P;
1324         case AV_PIX_FMT_YUV444P:        return BC_YUV444P;
1325         case AV_PIX_FMT_YUV411P:        return BC_YUV411P;
1326         case AV_PIX_FMT_RGB565:         return BC_RGB565;
1327         case AV_PIX_FMT_RGB48LE:        return BC_RGB161616;
1328         case AV_PIX_FMT_RGBA64LE:       return BC_RGBA16161616;
1329         case AV_PIX_FMT_AYUV64LE:       return BC_AYUV16161616;
1330         case AV_PIX_FMT_GBRP:           return BC_GBRP;
1331         default: break;
1332         }
1333
1334         return -1;
1335 }
1336
1337 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip)
1338 {
1339         AVFrame *ipic = av_frame_alloc();
1340         int ret = convert_picture_vframe(frame, ip, ipic);
1341         av_frame_free(&ipic);
1342         return ret;
1343 }
1344
1345 int FFVideoConvert::convert_picture_vframe(VFrame *frame, AVFrame *ip, AVFrame *ipic)
1346 {
1347         int cmodel = frame->get_color_model();
1348         AVPixelFormat ofmt = color_model_to_pix_fmt(cmodel);
1349         if( ofmt == AV_PIX_FMT_NB ) return -1;
1350         int size = av_image_fill_arrays(ipic->data, ipic->linesize,
1351                 frame->get_data(), ofmt, frame->get_w(), frame->get_h(), 1);
1352         if( size < 0 ) return -1;
1353
1354         int bpp = BC_CModels::calculate_pixelsize(cmodel);
1355         int ysz = bpp * frame->get_w(), usz = ysz;
1356         switch( cmodel ) {
1357         case BC_YUV410P:
1358         case BC_YUV411P:
1359                 usz /= 2;
1360         case BC_YUV420P:
1361         case BC_YUV422P:
1362                 usz /= 2;
1363         case BC_YUV444P:
1364         case BC_GBRP:
1365                 // override av_image_fill_arrays() for planar types
1366                 ipic->data[0] = frame->get_y();  ipic->linesize[0] = ysz;
1367                 ipic->data[1] = frame->get_u();  ipic->linesize[1] = usz;
1368                 ipic->data[2] = frame->get_v();  ipic->linesize[2] = usz;
1369                 break;
1370         default:
1371                 ipic->data[0] = frame->get_data();
1372                 ipic->linesize[0] = frame->get_bytes_per_line();
1373                 break;
1374         }
1375
1376         AVPixelFormat pix_fmt = (AVPixelFormat)ip->format;
1377         FFVideoStream *vid =(FFVideoStream *)this;
1378         if( pix_fmt == vid->hw_pixfmt ) {
1379                 int ret = 0;
1380                 if( !sw_frame && !(sw_frame=av_frame_alloc()) )
1381                         ret = AVERROR(ENOMEM);
1382                 if( !ret ) {
1383                         ret = av_hwframe_transfer_data(sw_frame, ip, 0);
1384                         ip = sw_frame;
1385                         pix_fmt = (AVPixelFormat)ip->format;
1386                 }
1387                 if( ret < 0 ) {
1388                         eprintf(_("Error retrieving data from GPU to CPU\nfile: %s\n"),
1389                                 vid->ffmpeg->fmt_ctx->url);
1390                         return -1;
1391                 }
1392         }
1393         convert_ctx = sws_getCachedContext(convert_ctx, ip->width, ip->height, pix_fmt,
1394                 frame->get_w(), frame->get_h(), ofmt, SWS_POINT, NULL, NULL, NULL);
1395         if( !convert_ctx ) {
1396                 fprintf(stderr, "FFVideoConvert::convert_picture_frame:"
1397                                 " sws_getCachedContext() failed\n");
1398                 return -1;
1399         }
1400         int ret = sws_scale(convert_ctx, ip->data, ip->linesize, 0, ip->height,
1401             ipic->data, ipic->linesize);
1402         if( ret < 0 ) {
1403                 ff_err(ret, "FFVideoConvert::convert_picture_frame: sws_scale() failed\nfile: %s\n",
1404                         vid->ffmpeg->fmt_ctx->url);
1405                 return -1;
1406         }
1407         return 0;
1408 }
1409
1410 int FFVideoConvert::convert_cmodel(VFrame *frame, AVFrame *ip)
1411 {
1412         // try direct transfer
1413         if( !convert_picture_vframe(frame, ip) ) return 1;
1414         // use indirect transfer
1415         AVPixelFormat ifmt = (AVPixelFormat)ip->format;
1416         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(ifmt);
1417         int max_bits = 0;
1418         for( int i = 0; i <desc->nb_components; ++i ) {
1419                 int bits = desc->comp[i].depth;
1420                 if( bits > max_bits ) max_bits = bits;
1421         }
1422         int imodel = pix_fmt_to_color_model(ifmt);
1423         int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1424         int cmodel = frame->get_color_model();
1425         int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1426         if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1427                 imodel = cmodel_is_yuv ?
1428                     (BC_CModels::has_alpha(cmodel) ?
1429                         BC_AYUV16161616 :
1430                         (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1431                     (BC_CModels::has_alpha(cmodel) ?
1432                         (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1433                         (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1434         }
1435         VFrame vframe(ip->width, ip->height, imodel);
1436         if( convert_picture_vframe(&vframe, ip) ) return -1;
1437         frame->transfer_from(&vframe);
1438         return 1;
1439 }
1440
1441 int FFVideoConvert::transfer_cmodel(VFrame *frame, AVFrame *ifp)
1442 {
1443         int ret = convert_cmodel(frame, ifp);
1444         if( ret > 0 ) {
1445                 const AVDictionary *src = ifp->metadata;
1446                 AVDictionaryEntry *t = NULL;
1447                 BC_Hash *hp = frame->get_params();
1448                 //hp->clear();
1449                 while( (t=av_dict_get(src, "", t, AV_DICT_IGNORE_SUFFIX)) )
1450                         hp->update(t->key, t->value);
1451         }
1452         return ret;
1453 }
1454
1455 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op)
1456 {
1457         AVFrame *opic = av_frame_alloc();
1458         int ret = convert_vframe_picture(frame, op, opic);
1459         av_frame_free(&opic);
1460         return ret;
1461 }
1462
1463 int FFVideoConvert::convert_vframe_picture(VFrame *frame, AVFrame *op, AVFrame *opic)
1464 {
1465         int cmodel = frame->get_color_model();
1466         AVPixelFormat ifmt = color_model_to_pix_fmt(cmodel);
1467         if( ifmt == AV_PIX_FMT_NB ) return -1;
1468         int size = av_image_fill_arrays(opic->data, opic->linesize,
1469                  frame->get_data(), ifmt, frame->get_w(), frame->get_h(), 1);
1470         if( size < 0 ) return -1;
1471
1472         int bpp = BC_CModels::calculate_pixelsize(cmodel);
1473         int ysz = bpp * frame->get_w(), usz = ysz;
1474         switch( cmodel ) {
1475         case BC_YUV410P:
1476         case BC_YUV411P:
1477                 usz /= 2;
1478         case BC_YUV420P:
1479         case BC_YUV422P:
1480                 usz /= 2;
1481         case BC_YUV444P:
1482         case BC_GBRP:
1483                 // override av_image_fill_arrays() for planar types
1484                 opic->data[0] = frame->get_y();  opic->linesize[0] = ysz;
1485                 opic->data[1] = frame->get_u();  opic->linesize[1] = usz;
1486                 opic->data[2] = frame->get_v();  opic->linesize[2] = usz;
1487                 break;
1488         default:
1489                 opic->data[0] = frame->get_data();
1490                 opic->linesize[0] = frame->get_bytes_per_line();
1491                 break;
1492         }
1493
1494         AVPixelFormat ofmt = (AVPixelFormat)op->format;
1495         convert_ctx = sws_getCachedContext(convert_ctx, frame->get_w(), frame->get_h(),
1496                 ifmt, op->width, op->height, ofmt, SWS_POINT, NULL, NULL, NULL);
1497         if( !convert_ctx ) {
1498                 fprintf(stderr, "FFVideoConvert::convert_frame_picture:"
1499                                 " sws_getCachedContext() failed\n");
1500                 return -1;
1501         }
1502         int ret = sws_scale(convert_ctx, opic->data, opic->linesize, 0, frame->get_h(),
1503                         op->data, op->linesize);
1504         if( ret < 0 ) {
1505                 ff_err(ret, "FFVideoConvert::convert_frame_picture: sws_scale() failed\n");
1506                 return -1;
1507         }
1508         return 0;
1509 }
1510
1511 int FFVideoConvert::convert_pixfmt(VFrame *frame, AVFrame *op)
1512 {
1513         // try direct transfer
1514         if( !convert_vframe_picture(frame, op) ) return 1;
1515         // use indirect transfer
1516         int cmodel = frame->get_color_model();
1517         int max_bits = BC_CModels::calculate_pixelsize(cmodel) * 8;
1518         max_bits /= BC_CModels::components(cmodel);
1519         AVPixelFormat ofmt = (AVPixelFormat)op->format;
1520         int imodel = pix_fmt_to_color_model(ofmt);
1521         int imodel_is_yuv = BC_CModels::is_yuv(imodel);
1522         int cmodel_is_yuv = BC_CModels::is_yuv(cmodel);
1523         if( imodel < 0 || imodel_is_yuv != cmodel_is_yuv ) {
1524                 imodel = cmodel_is_yuv ?
1525                     (BC_CModels::has_alpha(cmodel) ?
1526                         BC_AYUV16161616 :
1527                         (max_bits > 8 ? BC_AYUV16161616 : BC_YUV444P)) :
1528                     (BC_CModels::has_alpha(cmodel) ?
1529                         (max_bits > 8 ? BC_RGBA16161616 : BC_RGBA8888) :
1530                         (max_bits > 8 ? BC_RGB161616 : BC_RGB888)) ;
1531         }
1532         VFrame vframe(frame->get_w(), frame->get_h(), imodel);
1533         vframe.transfer_from(frame);
1534         if( !convert_vframe_picture(&vframe, op) ) return 1;
1535         return -1;
1536 }
1537
1538 int FFVideoConvert::transfer_pixfmt(VFrame *frame, AVFrame *ofp)
1539 {
1540         int ret = convert_pixfmt(frame, ofp);
1541         if( ret > 0 ) {
1542                 BC_Hash *hp = frame->get_params();
1543                 AVDictionary **dict = &ofp->metadata;
1544                 //av_dict_free(dict);
1545                 for( int i=0; i<hp->size(); ++i ) {
1546                         char *key = hp->get_key(i), *val = hp->get_value(i);
1547                         av_dict_set(dict, key, val, 0);
1548                 }
1549         }
1550         return ret;
1551 }
1552
1553 void FFVideoStream::load_markers()
1554 {
1555         IndexState *index_state = ffmpeg->file_base->asset->index_state;
1556         if( !index_state || idx >= index_state->video_markers.size() ) return;
1557         FFStream::load_markers(*index_state->video_markers[idx], frame_rate);
1558 }
1559
1560 IndexMarks *FFVideoStream::get_markers()
1561 {
1562         IndexState *index_state = ffmpeg->file_base->asset->index_state;
1563         if( !index_state || idx >= index_state->video_markers.size() ) return 0;
1564         return !index_state ? 0 : index_state->video_markers[idx];
1565 }
1566
1567
1568 FFMPEG::FFMPEG(FileBase *file_base)
1569 {
1570         fmt_ctx = 0;
1571         this->file_base = file_base;
1572         memset(file_format,0,sizeof(file_format));
1573         mux_lock = new Condition(0,"FFMPEG::mux_lock",0);
1574         flow_lock = new Condition(1,"FFStream::flow_lock",0);
1575         done = -1;
1576         flow = 1;
1577         decoding = encoding = 0;
1578         has_audio = has_video = 0;
1579         opts = 0;
1580         opt_duration = -1;
1581         opt_video_filter = 0;
1582         opt_audio_filter = 0;
1583         opt_hw_dev = 0;
1584         opt_video_decoder = 0;
1585         opt_audio_decoder = 0;
1586         fflags = 0;
1587         char option_path[BCTEXTLEN];
1588         set_option_path(option_path, "%s", "ffmpeg.opts");
1589         read_options(option_path, opts);
1590 }
1591
1592 FFMPEG::~FFMPEG()
1593 {
1594         ff_lock("FFMPEG::~FFMPEG()");
1595         close_encoder();
1596         ffaudio.remove_all_objects();
1597         ffvideo.remove_all_objects();
1598         if( fmt_ctx ) avformat_close_input(&fmt_ctx);
1599         ff_unlock();
1600         delete flow_lock;
1601         delete mux_lock;
1602         av_dict_free(&opts);
1603         delete [] opt_video_filter;
1604         delete [] opt_audio_filter;
1605         delete [] opt_hw_dev;
1606 }
1607
1608 int FFMPEG::check_sample_rate(AVCodec *codec, int sample_rate)
1609 {
1610         const int *p = codec->supported_samplerates;
1611         if( !p ) return sample_rate;
1612         while( *p != 0 ) {
1613                 if( *p == sample_rate ) return *p;
1614                 ++p;
1615         }
1616         return 0;
1617 }
1618
1619 static inline AVRational std_frame_rate(int i)
1620 {
1621         static const int m1 = 1001*12, m2 = 1000*12;
1622         static const int freqs[] = {
1623                 40*m1, 48*m1, 50*m1, 60*m1, 80*m1,120*m1, 240*m1,
1624                 24*m2, 30*m2, 60*m2, 12*m2, 15*m2, 48*m2, 0,
1625         };
1626         int freq = i<30*12 ? (i+1)*1001 : freqs[i-30*12];
1627         return (AVRational) { freq, 1001*12 };
1628 }
1629
1630 AVRational FFMPEG::check_frame_rate(AVCodec *codec, double frame_rate)
1631 {
1632         const AVRational *p = codec->supported_framerates;
1633         AVRational rate, best_rate = (AVRational) { 0, 0 };
1634         double max_err = 1.;  int i = 0;
1635         while( ((p ? (rate=*p++) : (rate=std_frame_rate(i++))), rate.num) != 0 ) {
1636                 double framerate = (double) rate.num / rate.den;
1637                 double err = fabs(frame_rate/framerate - 1.);
1638                 if( err >= max_err ) continue;
1639                 max_err = err;
1640                 best_rate = rate;
1641         }
1642         return max_err < 0.0001 ? best_rate : (AVRational) { 0, 0 };
1643 }
1644
1645 AVRational FFMPEG::to_sample_aspect_ratio(Asset *asset)
1646 {
1647 #if 1
1648         double display_aspect = asset->width / (double)asset->height;
1649         double sample_aspect = display_aspect / asset->aspect_ratio;
1650         int width = 1000000, height = width * sample_aspect + 0.5;
1651         float w, h;
1652         MWindow::create_aspect_ratio(w, h, width, height);
1653         return (AVRational){(int)w, (int)h};
1654 #else
1655 // square pixels
1656         return (AVRational){1, 1};
1657 #endif
1658 }
1659
1660 AVRational FFMPEG::to_time_base(int sample_rate)
1661 {
1662         return (AVRational){1, sample_rate};
1663 }
1664
1665 int FFMPEG::get_fmt_score(AVSampleFormat dst_fmt, AVSampleFormat src_fmt)
1666 {
1667         int score = 0;
1668         int dst_planar = av_sample_fmt_is_planar(dst_fmt);
1669         int src_planar = av_sample_fmt_is_planar(src_fmt);
1670         if( dst_planar != src_planar ) ++score;
1671         int dst_bytes = av_get_bytes_per_sample(dst_fmt);
1672         int src_bytes = av_get_bytes_per_sample(src_fmt);
1673         score += (src_bytes > dst_bytes ? 100 : -10) * (src_bytes - dst_bytes);
1674         int src_packed = av_get_packed_sample_fmt(src_fmt);
1675         int dst_packed = av_get_packed_sample_fmt(dst_fmt);
1676         if( dst_packed == AV_SAMPLE_FMT_S32 && src_packed == AV_SAMPLE_FMT_FLT ) score += 20;
1677         if( dst_packed == AV_SAMPLE_FMT_FLT && src_packed == AV_SAMPLE_FMT_S32 ) score += 2;
1678         return score;
1679 }
1680
1681 AVSampleFormat FFMPEG::find_best_sample_fmt_of_list(
1682                 const AVSampleFormat *sample_fmts, AVSampleFormat src_fmt)
1683 {
1684         AVSampleFormat best = AV_SAMPLE_FMT_NONE;
1685         int best_score = get_fmt_score(best, src_fmt);
1686         for( int i=0; sample_fmts[i] >= 0; ++i ) {
1687                 AVSampleFormat sample_fmt = sample_fmts[i];
1688                 int score = get_fmt_score(sample_fmt, src_fmt);
1689                 if( score >= best_score ) continue;
1690                 best = sample_fmt;  best_score = score;
1691         }
1692         return best;
1693 }
1694
1695
1696 void FFMPEG::set_option_path(char *path, const char *fmt, ...)
1697 {
1698         char *ep = path + BCTEXTLEN-1;
1699         strncpy(path, File::get_cindat_path(), ep-path);
1700         strncat(path, "/ffmpeg/", ep-path);
1701         path += strlen(path);
1702         va_list ap;
1703         va_start(ap, fmt);
1704         path += vsnprintf(path, ep-path, fmt, ap);
1705         va_end(ap);
1706         *path = 0;
1707 }
1708
1709 void FFMPEG::get_option_path(char *path, const char *type, const char *spec)
1710 {
1711         if( *spec == '/' )
1712                 strcpy(path, spec);
1713         else
1714                 set_option_path(path, "%s/%s", type, spec);
1715 }
1716
1717 int FFMPEG::get_format(char *format, const char *path, const char *spec)
1718 {
1719         char option_path[BCTEXTLEN], line[BCTEXTLEN], codec[BCTEXTLEN];
1720         get_option_path(option_path, path, spec);
1721         FILE *fp = fopen(option_path,"r");
1722         if( !fp ) return 1;
1723         int ret = 0;
1724         if( !fgets(line, sizeof(line), fp) ) ret = 1;
1725         if( !ret ) {
1726                 line[sizeof(line)-1] = 0;
1727                 ret = scan_option_line(line, format, codec);
1728         }
1729         fclose(fp);
1730         return ret;
1731 }
1732
1733 int FFMPEG::get_codec(char *codec, const char *path, const char *spec)
1734 {
1735         char option_path[BCTEXTLEN], line[BCTEXTLEN], format[BCTEXTLEN];
1736         get_option_path(option_path, path, spec);
1737         FILE *fp = fopen(option_path,"r");
1738         if( !fp ) return 1;
1739         int ret = 0;
1740         if( !fgets(line, sizeof(line), fp) ) ret = 1;
1741         fclose(fp);
1742         if( !ret ) {
1743                 line[sizeof(line)-1] = 0;
1744                 ret = scan_option_line(line, format, codec);
1745         }
1746         if( !ret ) {
1747                 char *vp = codec, *ep = vp+BCTEXTLEN-1;
1748                 while( vp < ep && *vp && *vp != '|' ) ++vp;
1749                 if( *vp == '|' ) --vp;
1750                 while( vp > codec && (*vp==' ' || *vp=='\t') ) *vp-- = 0;
1751         }
1752         return ret;
1753 }
1754
1755 int FFMPEG::get_file_format()
1756 {
1757         char audio_muxer[BCSTRLEN], video_muxer[BCSTRLEN];
1758         char audio_format[BCSTRLEN], video_format[BCSTRLEN];
1759         audio_muxer[0] = audio_format[0] = 0;
1760         video_muxer[0] = video_format[0] = 0;
1761         Asset *asset = file_base->asset;
1762         int ret = asset ? 0 : 1;
1763         if( !ret && asset->audio_data ) {
1764                 if( !(ret=get_format(audio_format, "audio", asset->acodec)) ) {
1765                         if( get_format(audio_muxer, "format", audio_format) ) {
1766                                 strcpy(audio_muxer, audio_format);
1767                                 audio_format[0] = 0;
1768                         }
1769                 }
1770         }
1771         if( !ret && asset->video_data ) {
1772                 if( !(ret=get_format(video_format, "video", asset->vcodec)) ) {
1773                         if( get_format(video_muxer, "format", video_format) ) {
1774                                 strcpy(video_muxer, video_format);
1775                                 video_format[0] = 0;
1776                         }
1777                 }
1778         }
1779         if( !ret && !audio_muxer[0] && !video_muxer[0] )
1780                 ret = 1;
1781         if( !ret && audio_muxer[0] && video_muxer[0] &&
1782             strcmp(audio_muxer, video_muxer) ) ret = -1;
1783         if( !ret && audio_format[0] && video_format[0] &&
1784             strcmp(audio_format, video_format) ) ret = -1;
1785         if( !ret )
1786                 strcpy(file_format, !audio_format[0] && !video_format[0] ?
1787                         (audio_muxer[0] ? audio_muxer : video_muxer) :
1788                         (audio_format[0] ? audio_format : video_format));
1789         return ret;
1790 }
1791
1792 int FFMPEG::scan_option_line(const char *cp, char *tag, char *val)
1793 {
1794         while( *cp == ' ' || *cp == '\t' ) ++cp;
1795         const char *bp = cp;
1796         while( *cp && *cp != ' ' && *cp != '\t' && *cp != '=' && *cp != '\n' ) ++cp;
1797         int len = cp - bp;
1798         if( !len || len > BCSTRLEN-1 ) return 1;
1799         while( bp < cp ) *tag++ = *bp++;
1800         *tag = 0;
1801         while( *cp == ' ' || *cp == '\t' ) ++cp;
1802         if( *cp == '=' ) ++cp;
1803         while( *cp == ' ' || *cp == '\t' ) ++cp;
1804         bp = cp;
1805         while( *cp && *cp != '\n' ) ++cp;
1806         len = cp - bp;
1807         if( len > BCTEXTLEN-1 ) return 1;
1808         while( bp < cp ) *val++ = *bp++;
1809         *val = 0;
1810         return 0;
1811 }
1812
1813 int FFMPEG::can_render(const char *fformat, const char *type)
1814 {
1815         FileSystem fs;
1816         char option_path[BCTEXTLEN];
1817         FFMPEG::set_option_path(option_path, type);
1818         fs.update(option_path);
1819         int total_files = fs.total_files();
1820         for( int i=0; i<total_files; ++i ) {
1821                 const char *name = fs.get_entry(i)->get_name();
1822                 const char *ext = strrchr(name,'.');
1823                 if( !ext ) continue;
1824                 if( !strcmp(fformat, ++ext) ) return 1;
1825         }
1826         return 0;
1827 }
1828
1829 int FFMPEG::get_ff_option(const char *nm, const char *options, char *value)
1830 {
1831         for( const char *cp=options; *cp!=0; ) {
1832                 char line[BCTEXTLEN], *bp = line, *ep = bp+sizeof(line)-1;
1833                 while( bp < ep && *cp && *cp!='\n' ) *bp++ = *cp++;
1834                 if( *cp ) ++cp;
1835                 *bp = 0;
1836                 if( !line[0] || line[0] == '#' || line[0] == ';' ) continue;
1837                 char key[BCSTRLEN], val[BCTEXTLEN];
1838                 if( FFMPEG::scan_option_line(line, key, val) ) continue;
1839                 if( !strcmp(key, nm) ) {
1840                         strncpy(value, val, BCSTRLEN);
1841                         return 0;
1842                 }
1843         }
1844         return 1;
1845 }
1846
1847 void FFMPEG::scan_audio_options(Asset *asset, EDL *edl)
1848 {
1849         char cin_sample_fmt[BCSTRLEN];
1850         int cin_fmt = AV_SAMPLE_FMT_NONE;
1851         const char *options = asset->ff_audio_options;
1852         if( !get_ff_option("cin_sample_fmt", options, cin_sample_fmt) )
1853                 cin_fmt = (int)av_get_sample_fmt(cin_sample_fmt);
1854         if( cin_fmt < 0 ) {
1855                 char audio_codec[BCSTRLEN]; audio_codec[0] = 0;
1856                 AVCodec *av_codec = !FFMPEG::get_codec(audio_codec, "audio", asset->acodec) ?
1857                         avcodec_find_encoder_by_name(audio_codec) : 0;
1858                 if( av_codec && av_codec->sample_fmts )
1859                         cin_fmt = find_best_sample_fmt_of_list(av_codec->sample_fmts, AV_SAMPLE_FMT_FLT);
1860         }
1861         if( cin_fmt < 0 ) cin_fmt = AV_SAMPLE_FMT_S16;
1862         const char *name = av_get_sample_fmt_name((AVSampleFormat)cin_fmt);
1863         if( !name ) name = _("None");
1864         strcpy(asset->ff_sample_format, name);
1865
1866         char value[BCSTRLEN];
1867         if( !get_ff_option("cin_bitrate", options, value) )
1868                 asset->ff_audio_bitrate = atoi(value);
1869         if( !get_ff_option("cin_quality", options, value) )
1870                 asset->ff_audio_quality = atoi(value);
1871 }
1872
1873 void FFMPEG::load_audio_options(Asset *asset, EDL *edl)
1874 {
1875         char options_path[BCTEXTLEN];
1876         set_option_path(options_path, "audio/%s", asset->acodec);
1877         if( !load_options(options_path,
1878                         asset->ff_audio_options,
1879                         sizeof(asset->ff_audio_options)) )
1880                 scan_audio_options(asset, edl);
1881 }
1882
1883 void FFMPEG::scan_video_options(Asset *asset, EDL *edl)
1884 {
1885         char cin_pix_fmt[BCSTRLEN];
1886         int cin_fmt = AV_PIX_FMT_NONE;
1887         const char *options = asset->ff_video_options;
1888         if( !get_ff_option("cin_pix_fmt", options, cin_pix_fmt) )
1889                         cin_fmt = (int)av_get_pix_fmt(cin_pix_fmt);
1890         if( cin_fmt < 0 ) {
1891                 char video_codec[BCSTRLEN];  video_codec[0] = 0;
1892                 AVCodec *av_codec = !get_codec(video_codec, "video", asset->vcodec) ?
1893                         avcodec_find_encoder_by_name(video_codec) : 0;
1894                 if( av_codec && av_codec->pix_fmts ) {
1895                         if( 0 && edl ) { // frequently picks a bad answer
1896                                 int color_model = edl->session->color_model;
1897                                 int max_bits = BC_CModels::calculate_pixelsize(color_model) * 8;
1898                                 max_bits /= BC_CModels::components(color_model);
1899                                 cin_fmt = avcodec_find_best_pix_fmt_of_list(av_codec->pix_fmts,
1900                                         (BC_CModels::is_yuv(color_model) ?
1901                                                 (max_bits > 8 ? AV_PIX_FMT_AYUV64LE : AV_PIX_FMT_YUV444P) :
1902                                                 (max_bits > 8 ? AV_PIX_FMT_RGB48LE : AV_PIX_FMT_RGB24)), 0, 0);
1903                         }
1904                         else
1905                                 cin_fmt = av_codec->pix_fmts[0];
1906                 }
1907         }
1908         if( cin_fmt < 0 ) cin_fmt = AV_PIX_FMT_YUV420P;
1909         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)cin_fmt);
1910         const char *name = desc ? desc->name : _("None");
1911         strcpy(asset->ff_pixel_format, name);
1912
1913         char value[BCSTRLEN];
1914         if( !get_ff_option("cin_bitrate", options, value) )
1915                 asset->ff_video_bitrate = atoi(value);
1916         if( !get_ff_option("cin_quality", options, value) )
1917                 asset->ff_video_quality = atoi(value);
1918 }
1919
1920 void FFMPEG::load_video_options(Asset *asset, EDL *edl)
1921 {
1922         char options_path[BCTEXTLEN];
1923         set_option_path(options_path, "video/%s", asset->vcodec);
1924         if( !load_options(options_path,
1925                         asset->ff_video_options,
1926                         sizeof(asset->ff_video_options)) )
1927                 scan_video_options(asset, edl);
1928 }
1929
1930 int FFMPEG::load_defaults(const char *path, const char *type,
1931                  char *codec, char *codec_options, int len)
1932 {
1933         char default_file[BCTEXTLEN];
1934         set_option_path(default_file, "%s/%s.dfl", path, type);
1935         FILE *fp = fopen(default_file,"r");
1936         if( !fp ) return 1;
1937         fgets(codec, BCSTRLEN, fp);
1938         char *cp = codec;
1939         while( *cp && *cp!='\n' ) ++cp;
1940         *cp = 0;
1941         while( len > 0 && fgets(codec_options, len, fp) ) {
1942                 int n = strlen(codec_options);
1943                 codec_options += n;  len -= n;
1944         }
1945         fclose(fp);
1946         set_option_path(default_file, "%s/%s", path, codec);
1947         return load_options(default_file, codec_options, len);
1948 }
1949
1950 void FFMPEG::set_asset_format(Asset *asset, EDL *edl, const char *text)
1951 {
1952         if( asset->format != FILE_FFMPEG ) return;
1953         if( text != asset->fformat )
1954                 strcpy(asset->fformat, text);
1955         if( asset->audio_data && !asset->ff_audio_options[0] ) {
1956                 if( !load_defaults("audio", text, asset->acodec,
1957                                 asset->ff_audio_options, sizeof(asset->ff_audio_options)) )
1958                         scan_audio_options(asset, edl);
1959                 else
1960                         asset->audio_data = 0;
1961         }
1962         if( asset->video_data && !asset->ff_video_options[0] ) {
1963                 if( !load_defaults("video", text, asset->vcodec,
1964                                 asset->ff_video_options, sizeof(asset->ff_video_options)) )
1965                         scan_video_options(asset, edl);
1966                 else
1967                         asset->video_data = 0;
1968         }
1969 }
1970
1971 int FFMPEG::get_encoder(const char *options,
1972                 char *format, char *codec, char *bsfilter)
1973 {
1974         FILE *fp = fopen(options,"r");
1975         if( !fp ) {
1976                 eprintf(_("options open failed %s\n"),options);
1977                 return 1;
1978         }
1979         char line[BCTEXTLEN];
1980         if( !fgets(line, sizeof(line), fp) ||
1981             scan_encoder(line, format, codec, bsfilter) )
1982                 eprintf(_("format/codec not found %s\n"), options);
1983         fclose(fp);
1984         return 0;
1985 }
1986
1987 int FFMPEG::scan_encoder(const char *line,
1988                 char *format, char *codec, char *bsfilter)
1989 {
1990         format[0] = codec[0] = bsfilter[0] = 0;
1991         if( scan_option_line(line, format, codec) ) return 1;
1992         char *cp = codec;
1993         while( *cp && *cp != '|' ) ++cp;
1994         if( !*cp ) return 0;
1995         char *bp = cp;
1996         do { *bp-- = 0; } while( bp>=codec && (*bp==' ' || *bp == '\t' ) );
1997         while( *++cp && (*cp==' ' || *cp == '\t') );
1998         bp = bsfilter;
1999         for( int i=BCTEXTLEN; --i>0 && *cp; ) *bp++ = *cp++;
2000         *bp = 0;
2001         return 0;
2002 }
2003
2004 int FFMPEG::read_options(const char *options, AVDictionary *&opts, int skip)
2005 {
2006         FILE *fp = fopen(options,"r");
2007         if( !fp ) return 1;
2008         int ret = 0;
2009         while( !ret && --skip >= 0 ) {
2010                 int ch = getc(fp);
2011                 while( ch >= 0 && ch != '\n' ) ch = getc(fp);
2012                 if( ch < 0 ) ret = 1;
2013         }
2014         if( !ret )
2015                 ret = read_options(fp, options, opts);
2016         fclose(fp);
2017         return ret;
2018 }
2019
2020 int FFMPEG::scan_options(const char *options, AVDictionary *&opts, AVStream *st)
2021 {
2022         FILE *fp = fmemopen((void *)options,strlen(options),"r");
2023         if( !fp ) return 0;
2024         int ret = read_options(fp, options, opts);
2025         fclose(fp);
2026         AVDictionaryEntry *tag = av_dict_get(opts, "id", NULL, 0);
2027         if( tag ) st->id = strtol(tag->value,0,0);
2028         return ret;
2029 }
2030
2031 FFCodecRemap::FFCodecRemap()
2032 {
2033         old_codec = 0;
2034         new_codec = 0;
2035 }
2036 FFCodecRemap::~FFCodecRemap()
2037 {
2038         delete [] old_codec;
2039         delete [] new_codec;
2040 }
2041
2042 int FFCodecRemaps::add(const char *val)
2043 {
2044         char old_codec[BCSTRLEN], new_codec[BCSTRLEN];
2045         if( sscanf(val, " %63[a-zA-z0-9_-] = %63[a-z0-9_-]",
2046                 &old_codec[0], &new_codec[0]) != 2 ) return 1;
2047         FFCodecRemap &remap = append();
2048         remap.old_codec = cstrdup(old_codec);
2049         remap.new_codec = cstrdup(new_codec);
2050         return 0;
2051 }
2052
2053
2054 int FFCodecRemaps::update(AVCodecID &codec_id, AVCodec *&decoder)
2055 {
2056         AVCodec *codec = avcodec_find_decoder(codec_id);
2057         if( !codec ) return -1;
2058         const char *name = codec->name;
2059         FFCodecRemaps &map = *this;
2060         int k = map.size();
2061         while( --k >= 0 && strcmp(map[k].old_codec, name) );
2062         if( k < 0 ) return 1;
2063         const char *new_codec = map[k].new_codec;
2064         codec = avcodec_find_decoder_by_name(new_codec);
2065         if( !codec ) return -1;
2066         decoder = codec;
2067         return 0;
2068 }
2069
2070 int FFMPEG::read_options(FILE *fp, const char *options, AVDictionary *&opts)
2071 {
2072         int ret = 0, no = 0;
2073         char line[BCTEXTLEN];
2074         while( !ret && fgets(line, sizeof(line), fp) ) {
2075                 line[sizeof(line)-1] = 0;
2076                 if( line[0] == '#' ) continue;
2077                 if( line[0] == '\n' ) continue;
2078                 char key[BCSTRLEN], val[BCTEXTLEN];
2079                 if( scan_option_line(line, key, val) ) {
2080                         eprintf(_("err reading %s: line %d\n"), options, no);
2081                         ret = 1;
2082                 }
2083                 if( !ret ) {
2084                         if( !strcmp(key, "duration") )
2085                                 opt_duration = strtod(val, 0);
2086                         else if( !strcmp(key, "video_decoder") )
2087                                 opt_video_decoder = cstrdup(val);
2088                         else if( !strcmp(key, "audio_decoder") )
2089                                 opt_audio_decoder = cstrdup(val);
2090                         else if( !strcmp(key, "remap_video_decoder") )
2091                                 video_codec_remaps.add(val);
2092                         else if( !strcmp(key, "remap_audio_decoder") )
2093                                 audio_codec_remaps.add(val);
2094                         else if( !strcmp(key, "video_filter") )
2095                                 opt_video_filter = cstrdup(val);
2096                         else if( !strcmp(key, "audio_filter") )
2097                                 opt_audio_filter = cstrdup(val);
2098                         else if( !strcmp(key, "cin_hw_dev") )
2099                                 opt_hw_dev = cstrdup(val);
2100                         else if( !strcmp(key, "loglevel") )
2101                                 set_loglevel(val);
2102                         else
2103                                 av_dict_set(&opts, key, val, 0);
2104                 }
2105         }
2106         return ret;
2107 }
2108
2109 int FFMPEG::load_options(const char *options, AVDictionary *&opts)
2110 {
2111         char option_path[BCTEXTLEN];
2112         set_option_path(option_path, "%s", options);
2113         return read_options(option_path, opts);
2114 }
2115
2116 int FFMPEG::load_options(const char *path, char *bfr, int len)
2117 {
2118         *bfr = 0;
2119         FILE *fp = fopen(path, "r");
2120         if( !fp ) return 1;
2121         fgets(bfr, len, fp); // skip hdr
2122         len = fread(bfr, 1, len-1, fp);
2123         if( len < 0 ) len = 0;
2124         bfr[len] = 0;
2125         fclose(fp);
2126         return 0;
2127 }
2128
2129 void FFMPEG::set_loglevel(const char *ap)
2130 {
2131         if( !ap || !*ap ) return;
2132         const struct {
2133                 const char *name;
2134                 int level;
2135         } log_levels[] = {
2136                 { "quiet"  , AV_LOG_QUIET   },
2137                 { "panic"  , AV_LOG_PANIC   },
2138                 { "fatal"  , AV_LOG_FATAL   },
2139                 { "error"  , AV_LOG_ERROR   },
2140                 { "warning", AV_LOG_WARNING },
2141                 { "info"   , AV_LOG_INFO    },
2142                 { "verbose", AV_LOG_VERBOSE },
2143                 { "debug"  , AV_LOG_DEBUG   },
2144         };
2145         for( int i=0; i<(int)(sizeof(log_levels)/sizeof(log_levels[0])); ++i ) {
2146                 if( !strcmp(log_levels[i].name, ap) ) {
2147                         av_log_set_level(log_levels[i].level);
2148                         return;
2149                 }
2150         }
2151         av_log_set_level(atoi(ap));
2152 }
2153
2154 double FFMPEG::to_secs(int64_t time, AVRational time_base)
2155 {
2156         double base_time = time == AV_NOPTS_VALUE ? 0 :
2157                 av_rescale_q(time, time_base, AV_TIME_BASE_Q);
2158         return base_time / AV_TIME_BASE;
2159 }
2160
2161 int FFMPEG::info(char *text, int len)
2162 {
2163         if( len <= 0 ) return 0;
2164         decode_activate();
2165 #define report(s...) do { int n = snprintf(cp,len,s); cp += n;  len -= n; } while(0)
2166         char *cp = text;
2167         report("format: %s\n",fmt_ctx->iformat->name);
2168         if( ffvideo.size() > 0 )
2169                 report("\n%d video stream%s\n",ffvideo.size(), ffvideo.size()!=1 ? "s" : "");
2170         for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2171                 FFVideoStream *vid = ffvideo[vidx];
2172                 AVStream *st = vid->st;
2173                 AVCodecID codec_id = st->codecpar->codec_id;
2174                 report(_("vid%d (%d),  id 0x%06x:\n"), vid->idx, vid->fidx, codec_id);
2175                 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2176                 report("  video%d %s", vidx+1, desc ? desc->name : " (unkn)");
2177                 report(" %dx%d %5.2f", vid->width, vid->height, vid->frame_rate);
2178                 AVPixelFormat pix_fmt = (AVPixelFormat)st->codecpar->format;
2179                 const char *pfn = av_get_pix_fmt_name(pix_fmt);
2180                 report(" pix %s\n", pfn ? pfn : "(unkn)");
2181                 double secs = to_secs(st->duration, st->time_base);
2182                 int64_t length = secs * vid->frame_rate + 0.5;
2183                 double ofs = to_secs((vid->nudge - st->start_time), st->time_base);
2184                 int64_t nudge = ofs * vid->frame_rate;
2185                 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2186                 report("    %jd%c%jd frms %0.2f secs", length,ch,nudge, secs);
2187                 int hrs = secs/3600;  secs -= hrs*3600;
2188                 int mins = secs/60;  secs -= mins*60;
2189                 report("  %d:%02d:%05.2f\n", hrs, mins, secs);
2190         }
2191         if( ffaudio.size() > 0 )
2192                 report("\n%d audio stream%s\n",ffaudio.size(), ffaudio.size()!=1 ? "s" : "");
2193         for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2194                 FFAudioStream *aud = ffaudio[aidx];
2195                 AVStream *st = aud->st;
2196                 AVCodecID codec_id = st->codecpar->codec_id;
2197                 report(_("aud%d (%d),  id 0x%06x:\n"), aud->idx, aud->fidx, codec_id);
2198                 const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
2199                 int nch = aud->channels, ch0 = aud->channel0+1;
2200                 report("  audio%d-%d %s", ch0, ch0+nch-1, desc ? desc->name : " (unkn)");
2201                 AVSampleFormat sample_fmt = (AVSampleFormat)st->codecpar->format;
2202                 const char *fmt = av_get_sample_fmt_name(sample_fmt);
2203                 report(" %s %d", fmt, aud->sample_rate);
2204                 int sample_bits = av_get_bits_per_sample(codec_id);
2205                 report(" %dbits\n", sample_bits);
2206                 double secs = to_secs(st->duration, st->time_base);
2207                 int64_t length = secs * aud->sample_rate + 0.5;
2208                 double ofs = to_secs((aud->nudge - st->start_time), st->time_base);
2209                 int64_t nudge = ofs * aud->sample_rate;
2210                 int ch = nudge >= 0 ? '+' : (nudge=-nudge, '-');
2211                 report("    %jd%c%jd smpl %0.2f secs", length,ch,nudge, secs);
2212                 int hrs = secs/3600;  secs -= hrs*3600;
2213                 int mins = secs/60;  secs -= mins*60;
2214                 report("  %d:%02d:%05.2f\n", hrs, mins, secs);
2215         }
2216         if( fmt_ctx->nb_programs > 0 )
2217                 report("\n%d program%s\n",fmt_ctx->nb_programs, fmt_ctx->nb_programs!=1 ? "s" : "");
2218         for( int i=0; i<(int)fmt_ctx->nb_programs; ++i ) {
2219                 report("program %d", i+1);
2220                 AVProgram *pgrm = fmt_ctx->programs[i];
2221                 for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2222                         int idx = pgrm->stream_index[j];
2223                         int vidx = ffvideo.size();
2224                         while( --vidx>=0 && ffvideo[vidx]->fidx != idx );
2225                         if( vidx >= 0 ) {
2226                                 report(", vid%d", vidx);
2227                                 continue;
2228                         }
2229                         int aidx = ffaudio.size();
2230                         while( --aidx>=0 && ffaudio[aidx]->fidx != idx );
2231                         if( aidx >= 0 ) {
2232                                 report(", aud%d", aidx);
2233                                 continue;
2234                         }
2235                         report(", (%d)", pgrm->stream_index[j]);
2236                 }
2237                 report("\n");
2238         }
2239         report("\n");
2240         AVDictionaryEntry *tag = 0;
2241         while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
2242                 report("%s=%s\n", tag->key, tag->value);
2243
2244         if( !len ) --cp;
2245         *cp = 0;
2246         return cp - text;
2247 #undef report
2248 }
2249
2250
2251 int FFMPEG::init_decoder(const char *filename)
2252 {
2253         ff_lock("FFMPEG::init_decoder");
2254         av_register_all();
2255         char file_opts[BCTEXTLEN];
2256         strcpy(file_opts, filename);
2257         char *bp = strrchr(file_opts, '/');
2258         if( !bp ) bp = file_opts;
2259         char *sp = strrchr(bp, '.');
2260         if( !sp ) sp = bp + strlen(bp);
2261         FILE *fp = 0;
2262         AVInputFormat *ifmt = 0;
2263         if( sp ) {
2264                 strcpy(sp, ".opts");
2265                 fp = fopen(file_opts, "r");
2266         }
2267         if( fp ) {
2268                 read_options(fp, file_opts, opts);
2269                 fclose(fp);
2270                 AVDictionaryEntry *tag;
2271                 if( (tag=av_dict_get(opts, "format", NULL, 0)) != 0 ) {
2272                         ifmt = av_find_input_format(tag->value);
2273                 }
2274         }
2275         else
2276                 load_options("decode.opts", opts);
2277         AVDictionary *fopts = 0;
2278         av_dict_copy(&fopts, opts, 0);
2279         int ret = avformat_open_input(&fmt_ctx, filename, ifmt, &fopts);
2280         av_dict_free(&fopts);
2281         if( ret >= 0 )
2282                 ret = avformat_find_stream_info(fmt_ctx, NULL);
2283         if( !ret ) {
2284                 decoding = -1;
2285         }
2286         ff_unlock();
2287         return !ret ? 0 : 1;
2288 }
2289
2290 int FFMPEG::open_decoder()
2291 {
2292         struct stat st;
2293         if( stat(fmt_ctx->url, &st) < 0 ) {
2294                 eprintf(_("can't stat file: %s\n"), fmt_ctx->url);
2295                 return 1;
2296         }
2297
2298         int64_t file_bits = 8 * st.st_size;
2299         if( !fmt_ctx->bit_rate && opt_duration > 0 )
2300                 fmt_ctx->bit_rate = file_bits / opt_duration;
2301
2302         int estimated = 0;
2303         if( fmt_ctx->bit_rate > 0 ) {
2304                 for( int i=0; i<(int)fmt_ctx->nb_streams; ++i ) {
2305                         AVStream *st = fmt_ctx->streams[i];
2306                         if( st->duration != AV_NOPTS_VALUE ) continue;
2307                         if( st->time_base.num > INT64_MAX / fmt_ctx->bit_rate ) continue;
2308                         st->duration = av_rescale(file_bits, st->time_base.den,
2309                                 fmt_ctx->bit_rate * (int64_t) st->time_base.num);
2310                         estimated = 1;
2311                 }
2312         }
2313         if( estimated && !(fflags & FF_ESTM_TIMES) ) {
2314                 fflags |= FF_ESTM_TIMES;
2315                 printf("FFMPEG::open_decoder: some stream times estimated: %s\n",
2316                         fmt_ctx->url);
2317         }
2318
2319         ff_lock("FFMPEG::open_decoder");
2320         int ret = 0, bad_time = 0;
2321         for( int i=0; !ret && i<(int)fmt_ctx->nb_streams; ++i ) {
2322                 AVStream *st = fmt_ctx->streams[i];
2323                 if( st->duration == AV_NOPTS_VALUE ) bad_time = 1;
2324                 AVCodecParameters *avpar = st->codecpar;
2325                 const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(avpar->codec_id);
2326                 if( !codec_desc ) continue;
2327                 switch( avpar->codec_type ) {
2328                 case AVMEDIA_TYPE_VIDEO: {
2329                         if( avpar->width < 1 ) continue;
2330                         if( avpar->height < 1 ) continue;
2331                         AVRational framerate = av_guess_frame_rate(fmt_ctx, st, 0);
2332                         if( framerate.num < 1 ) continue;
2333                         has_video = 1;
2334                         int vidx = ffvideo.size();
2335                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, i);
2336                         vstrm_index.append(ffidx(vidx, 0));
2337                         ffvideo.append(vid);
2338                         vid->width = avpar->width;
2339                         vid->height = avpar->height;
2340                         vid->frame_rate = !framerate.den ? 0 : (double)framerate.num / framerate.den;
2341                         double secs = to_secs(st->duration, st->time_base);
2342                         vid->length = secs * vid->frame_rate;
2343                         vid->aspect_ratio = (double)st->sample_aspect_ratio.num / st->sample_aspect_ratio.den;
2344                         vid->nudge = st->start_time;
2345                         vid->reading = -1;
2346                         if( opt_video_filter )
2347                                 ret = vid->create_filter(opt_video_filter, avpar);
2348                         break; }
2349                 case AVMEDIA_TYPE_AUDIO: {
2350                         if( avpar->channels < 1 ) continue;
2351                         if( avpar->sample_rate < 1 ) continue;
2352                         has_audio = 1;
2353                         int aidx = ffaudio.size();
2354                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, i);
2355                         ffaudio.append(aud);
2356                         aud->channel0 = astrm_index.size();
2357                         aud->channels = avpar->channels;
2358                         for( int ch=0; ch<aud->channels; ++ch )
2359                                 astrm_index.append(ffidx(aidx, ch));
2360                         aud->sample_rate = avpar->sample_rate;
2361                         double secs = to_secs(st->duration, st->time_base);
2362                         aud->length = secs * aud->sample_rate;
2363                         aud->init_swr(aud->channels, avpar->format, aud->sample_rate);
2364                         aud->nudge = st->start_time;
2365                         aud->reading = -1;
2366                         if( opt_audio_filter )
2367                                 ret = aud->create_filter(opt_audio_filter, avpar);
2368                         break; }
2369                 default: break;
2370                 }
2371         }
2372         if( bad_time && !(fflags & FF_BAD_TIMES) ) {
2373                 fflags |= FF_BAD_TIMES;
2374                 printf("FFMPEG::open_decoder: some stream have bad times: %s\n",
2375                         fmt_ctx->url);
2376         }
2377         ff_unlock();
2378         return ret < 0 ? -1 : 0;
2379 }
2380
2381
2382 int FFMPEG::init_encoder(const char *filename)
2383 {
2384 // try access first for named pipes
2385         int ret = access(filename, W_OK);
2386         if( ret ) {
2387                 int fd = ::open(filename,O_WRONLY);
2388                 if( fd < 0 ) fd = open(filename,O_WRONLY+O_CREAT,0666);
2389                 if( fd >= 0 ) { close(fd);  ret = 0; }
2390         }
2391         if( ret ) {
2392                 eprintf(_("bad file path: %s\n"), filename);
2393                 return 1;
2394         }
2395         ret = get_file_format();
2396         if( ret > 0 ) {
2397                 eprintf(_("bad file format: %s\n"), filename);
2398                 return 1;
2399         }
2400         if( ret < 0 ) {
2401                 eprintf(_("mismatch audio/video file format: %s\n"), filename);
2402                 return 1;
2403         }
2404         ff_lock("FFMPEG::init_encoder");
2405         av_register_all();
2406         char format[BCSTRLEN];
2407         if( get_format(format, "format", file_format) )
2408                 strcpy(format, file_format);
2409         avformat_alloc_output_context2(&fmt_ctx, 0, format, filename);
2410         if( !fmt_ctx ) {
2411                 eprintf(_("failed: %s\n"), filename);
2412                 ret = 1;
2413         }
2414         if( !ret ) {
2415                 encoding = -1;
2416                 load_options("encode.opts", opts);
2417         }
2418         ff_unlock();
2419         return ret;
2420 }
2421
2422 int FFMPEG::open_encoder(const char *type, const char *spec)
2423 {
2424
2425         Asset *asset = file_base->asset;
2426         char *filename = asset->path;
2427         AVDictionary *sopts = 0;
2428         av_dict_copy(&sopts, opts, 0);
2429         char option_path[BCTEXTLEN];
2430         set_option_path(option_path, "%s/%s.opts", type, type);
2431         read_options(option_path, sopts);
2432         get_option_path(option_path, type, spec);
2433         char format_name[BCSTRLEN], codec_name[BCTEXTLEN], bsfilter[BCTEXTLEN];
2434         if( get_encoder(option_path, format_name, codec_name, bsfilter) ) {
2435                 eprintf(_("get_encoder failed %s:%s\n"), option_path, filename);
2436                 return 1;
2437         }
2438
2439 #ifdef HAVE_DV
2440         if( !strcmp(codec_name, CODEC_TAG_DVSD) ) strcpy(codec_name, "dv");
2441 #endif
2442         else if( !strcmp(codec_name, CODEC_TAG_MJPEG) ) strcpy(codec_name, "mjpeg");
2443         else if( !strcmp(codec_name, CODEC_TAG_JPEG) ) strcpy(codec_name, "jpeg");
2444
2445         int ret = 0;
2446         ff_lock("FFMPEG::open_encoder");
2447         FFStream *fst = 0;
2448         AVStream *st = 0;
2449         AVCodecContext *ctx = 0;
2450
2451         const AVCodecDescriptor *codec_desc = 0;
2452         AVCodec *codec = avcodec_find_encoder_by_name(codec_name);
2453         if( !codec ) {
2454                 eprintf(_("cant find codec %s:%s\n"), codec_name, filename);
2455                 ret = 1;
2456         }
2457         if( !ret ) {
2458                 codec_desc = avcodec_descriptor_get(codec->id);
2459                 if( !codec_desc ) {
2460                         eprintf(_("unknown codec %s:%s\n"), codec_name, filename);
2461                         ret = 1;
2462                 }
2463         }
2464         if( !ret ) {
2465                 st = avformat_new_stream(fmt_ctx, 0);
2466                 if( !st ) {
2467                         eprintf(_("cant create stream %s:%s\n"), codec_name, filename);
2468                         ret = 1;
2469                 }
2470         }
2471         if( !ret ) {
2472                 switch( codec_desc->type ) {
2473                 case AVMEDIA_TYPE_AUDIO: {
2474                         if( has_audio ) {
2475                                 eprintf(_("duplicate audio %s:%s\n"), codec_name, filename);
2476                                 ret = 1;
2477                                 break;
2478                         }
2479                         if( scan_options(asset->ff_audio_options, sopts, st) ) {
2480                                 eprintf(_("bad audio options %s:%s\n"), codec_name, filename);
2481                                 ret = 1;
2482                                 break;
2483                         }
2484                         has_audio = 1;
2485                         ctx = avcodec_alloc_context3(codec);
2486                         if( asset->ff_audio_bitrate > 0 ) {
2487                                 ctx->bit_rate = asset->ff_audio_bitrate;
2488                                 char arg[BCSTRLEN];
2489                                 sprintf(arg, "%d", asset->ff_audio_bitrate);
2490                                 av_dict_set(&sopts, "b", arg, 0);
2491                         }
2492                         else if( asset->ff_audio_quality >= 0 ) {
2493                                 ctx->global_quality = asset->ff_audio_quality * FF_QP2LAMBDA;
2494                                 ctx->qmin    = ctx->qmax =  asset->ff_audio_quality;
2495                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2496                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2497                                 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2498                                 char arg[BCSTRLEN];
2499                                 av_dict_set(&sopts, "flags", "+qscale", 0);
2500                                 sprintf(arg, "%d", asset->ff_audio_quality);
2501                                 av_dict_set(&sopts, "qscale", arg, 0);
2502                                 sprintf(arg, "%d", ctx->global_quality);
2503                                 av_dict_set(&sopts, "global_quality", arg, 0);
2504                         }
2505                         int aidx = ffaudio.size();
2506                         int fidx = aidx + ffvideo.size();
2507                         FFAudioStream *aud = new FFAudioStream(this, st, aidx, fidx);
2508                         aud->avctx = ctx;  ffaudio.append(aud);  fst = aud;
2509                         aud->sample_rate = asset->sample_rate;
2510                         ctx->channels = aud->channels = asset->channels;
2511                         for( int ch=0; ch<aud->channels; ++ch )
2512                                 astrm_index.append(ffidx(aidx, ch));
2513                         ctx->channel_layout =  av_get_default_channel_layout(ctx->channels);
2514                         ctx->sample_rate = check_sample_rate(codec, asset->sample_rate);
2515                         if( !ctx->sample_rate ) {
2516                                 eprintf(_("check_sample_rate failed %s\n"), filename);
2517                                 ret = 1;
2518                                 break;
2519                         }
2520                         ctx->time_base = st->time_base = (AVRational){1, aud->sample_rate};
2521                         AVSampleFormat sample_fmt = av_get_sample_fmt(asset->ff_sample_format);
2522                         if( sample_fmt == AV_SAMPLE_FMT_NONE )
2523                                 sample_fmt = codec->sample_fmts ? codec->sample_fmts[0] : AV_SAMPLE_FMT_S16;
2524                         ctx->sample_fmt = sample_fmt;
2525                         uint64_t layout = av_get_default_channel_layout(ctx->channels);
2526                         aud->resample_context = swr_alloc_set_opts(NULL,
2527                                 layout, ctx->sample_fmt, aud->sample_rate,
2528                                 layout, AV_SAMPLE_FMT_FLT, ctx->sample_rate,
2529                                 0, NULL);
2530                         swr_init(aud->resample_context);
2531                         aud->writing = -1;
2532                         break; }
2533                 case AVMEDIA_TYPE_VIDEO: {
2534                         if( has_video ) {
2535                                 eprintf(_("duplicate video %s:%s\n"), codec_name, filename);
2536                                 ret = 1;
2537                                 break;
2538                         }
2539                         if( scan_options(asset->ff_video_options, sopts, st) ) {
2540                                 eprintf(_("bad video options %s:%s\n"), codec_name, filename);
2541                                 ret = 1;
2542                                 break;
2543                         }
2544                         has_video = 1;
2545                         ctx = avcodec_alloc_context3(codec);
2546                         if( asset->ff_video_bitrate > 0 ) {
2547                                 ctx->bit_rate = asset->ff_video_bitrate;
2548                                 char arg[BCSTRLEN];
2549                                 sprintf(arg, "%d", asset->ff_video_bitrate);
2550                                 av_dict_set(&sopts, "b", arg, 0);
2551                         }
2552                         else if( asset->ff_video_quality >= 0 ) {
2553                                 ctx->global_quality = asset->ff_video_quality * FF_QP2LAMBDA;
2554                                 ctx->qmin    = ctx->qmax =  asset->ff_video_quality;
2555                                 ctx->mb_lmin = ctx->qmin * FF_QP2LAMBDA;
2556                                 ctx->mb_lmax = ctx->qmax * FF_QP2LAMBDA;
2557                                 ctx->flags |= AV_CODEC_FLAG_QSCALE;
2558                                 char arg[BCSTRLEN];
2559                                 av_dict_set(&sopts, "flags", "+qscale", 0);
2560                                 sprintf(arg, "%d", asset->ff_video_quality);
2561                                 av_dict_set(&sopts, "qscale", arg, 0);
2562                                 sprintf(arg, "%d", ctx->global_quality);
2563                                 av_dict_set(&sopts, "global_quality", arg, 0);
2564                         }
2565                         int vidx = ffvideo.size();
2566                         int fidx = vidx + ffaudio.size();
2567                         FFVideoStream *vid = new FFVideoStream(this, st, vidx, fidx);
2568                         vstrm_index.append(ffidx(vidx, 0));
2569                         vid->avctx = ctx;  ffvideo.append(vid);  fst = vid;
2570                         vid->width = asset->width;
2571                         vid->height = asset->height;
2572                         vid->frame_rate = asset->frame_rate;
2573
2574                         AVPixelFormat pix_fmt = av_get_pix_fmt(asset->ff_pixel_format);
2575                         if( opt_hw_dev != 0 ) {
2576                                 AVHWDeviceType hw_type = vid->encode_hw_activate(opt_hw_dev);
2577                                 switch( hw_type ) {
2578                                 case AV_HWDEVICE_TYPE_VAAPI:
2579                                         pix_fmt = AV_PIX_FMT_VAAPI;
2580                                         break;
2581                                 case AV_HWDEVICE_TYPE_NONE:
2582                                 default: break;
2583                                 }
2584                         }
2585                         if( pix_fmt == AV_PIX_FMT_NONE )
2586                                 pix_fmt = codec->pix_fmts ? codec->pix_fmts[0] : AV_PIX_FMT_YUV420P;
2587                         ctx->pix_fmt = pix_fmt;
2588
2589                         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
2590                         int mask_w = (1<<desc->log2_chroma_w)-1;
2591                         ctx->width = (vid->width+mask_w) & ~mask_w;
2592                         int mask_h = (1<<desc->log2_chroma_h)-1;
2593                         ctx->height = (vid->height+mask_h) & ~mask_h;
2594                         ctx->sample_aspect_ratio = to_sample_aspect_ratio(asset);
2595                         AVRational frame_rate = check_frame_rate(codec, vid->frame_rate);
2596                         if( !frame_rate.num || !frame_rate.den ) {
2597                                 eprintf(_("check_frame_rate failed %s\n"), filename);
2598                                 ret = 1;
2599                                 break;
2600                         }
2601                         av_reduce(&frame_rate.num, &frame_rate.den,
2602                                 frame_rate.num, frame_rate.den, INT_MAX);
2603                         ctx->framerate = (AVRational) { frame_rate.num, frame_rate.den };
2604                         ctx->time_base = (AVRational) { frame_rate.den, frame_rate.num };
2605                         st->avg_frame_rate = frame_rate;
2606                         st->time_base = ctx->time_base;
2607                         vid->writing = -1;
2608                         vid->interlaced = asset->interlace_mode == ILACE_MODE_TOP_FIRST ||
2609                                 asset->interlace_mode == ILACE_MODE_BOTTOM_FIRST ? 1 : 0;
2610                         vid->top_field_first = asset->interlace_mode == ILACE_MODE_TOP_FIRST ? 1 : 0;
2611                         break; }
2612                 default:
2613                         eprintf(_("not audio/video, %s:%s\n"), codec_name, filename);
2614                         ret = 1;
2615                 }
2616
2617                 if( ctx ) {
2618                         AVDictionaryEntry *tag;
2619                         if( (tag=av_dict_get(sopts, "cin_stats_filename", NULL, 0)) != 0 ) {
2620                                 char suffix[BCSTRLEN];  sprintf(suffix,"-%d.log",fst->fidx);
2621                                 fst->stats_filename = cstrcat(2, tag->value, suffix);
2622                         }
2623                         if( (tag=av_dict_get(sopts, "flags", NULL, 0)) != 0 ) {
2624                                 int pass = fst->pass;
2625                                 char *cp = tag->value;
2626                                 while( *cp ) {
2627                                         int ch = *cp++, pfx = ch=='-' ? -1 : ch=='+' ? 1 : 0;
2628                                         if( !isalnum(!pfx ? ch : (ch=*cp++)) ) continue;
2629                                         char id[BCSTRLEN], *bp = id, *ep = bp+sizeof(id)-1;
2630                                         for( *bp++=ch; isalnum(ch=*cp); ++cp )
2631                                                 if( bp < ep ) *bp++ = ch;
2632                                         *bp = 0;
2633                                         if( !strcmp(id, "pass1") ) {
2634                                                 pass = pfx<0 ? (pass&~1) : pfx>0 ? (pass|1) : 1;
2635                                         }
2636                                         else if( !strcmp(id, "pass2") ) {
2637                                                 pass = pfx<0 ? (pass&~2) : pfx>0 ? (pass|2) : 2;
2638                                         }
2639                                 }
2640                                 if( (fst->pass=pass) ) {
2641                                         if( pass & 1 ) ctx->flags |= AV_CODEC_FLAG_PASS1;
2642                                         if( pass & 2 ) ctx->flags |= AV_CODEC_FLAG_PASS2;
2643                                 }
2644                         }
2645                 }
2646         }
2647         if( !ret ) {
2648                 if( fmt_ctx->oformat->flags & AVFMT_GLOBALHEADER )
2649                         ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
2650                 if( fst->stats_filename && (ret=fst->init_stats_file()) )
2651                         eprintf(_("error: stats file = %s\n"), fst->stats_filename);
2652         }
2653         if( !ret ) {
2654                 av_dict_set(&sopts, "cin_bitrate", 0, 0);
2655                 av_dict_set(&sopts, "cin_quality", 0, 0);
2656
2657                 if( !av_dict_get(sopts, "threads", NULL, 0) )
2658                         ctx->thread_count = ff_cpus();
2659                 ret = avcodec_open2(ctx, codec, &sopts);
2660                 if( ret >= 0 ) {
2661                         ret = avcodec_parameters_from_context(st->codecpar, ctx);
2662                         if( ret < 0 )
2663                                 fprintf(stderr, "Could not copy the stream parameters\n");
2664                 }
2665                 if( ret >= 0 ) {
2666 _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
2667                         ret = avcodec_copy_context(st->codec, ctx);
2668 _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"")
2669                         if( ret < 0 )
2670                                 fprintf(stderr, "Could not copy the stream context\n");
2671                 }
2672                 if( ret < 0 ) {
2673                         ff_err(ret,"FFMPEG::open_encoder");
2674                         eprintf(_("open failed %s:%s\n"), codec_name, filename);
2675                         ret = 1;
2676                 }
2677                 else
2678                         ret = 0;
2679         }
2680         if( !ret && fst && bsfilter[0] ) {
2681                 ret = av_bsf_list_parse_str(bsfilter, &fst->bsfc);
2682                 if( ret < 0 ) {
2683                         ff_err(ret,"FFMPEG::open_encoder");
2684                         eprintf(_("bitstream filter failed %s:\n%s\n"), filename, bsfilter);
2685                         ret = 1;
2686                 }
2687                 else
2688                         ret = 0;
2689         }
2690
2691         if( !ret )
2692                 start_muxer();
2693
2694         ff_unlock();
2695         av_dict_free(&sopts);
2696         return ret;
2697 }
2698
2699 int FFMPEG::close_encoder()
2700 {
2701         stop_muxer();
2702         if( encoding > 0 ) {
2703                 av_write_trailer(fmt_ctx);
2704                 if( !(fmt_ctx->flags & AVFMT_NOFILE) )
2705                         avio_closep(&fmt_ctx->pb);
2706         }
2707         encoding = 0;
2708         return 0;
2709 }
2710
2711 int FFMPEG::decode_activate()
2712 {
2713         if( decoding < 0 ) {
2714                 decoding = 0;
2715                 for( int vidx=0; vidx<ffvideo.size(); ++vidx )
2716                         ffvideo[vidx]->nudge = AV_NOPTS_VALUE;
2717                 for( int aidx=0; aidx<ffaudio.size(); ++aidx )
2718                         ffaudio[aidx]->nudge = AV_NOPTS_VALUE;
2719                 // set nudges for each program stream set
2720                 const int64_t min_nudge = INT64_MIN+1;
2721                 int npgrms = fmt_ctx->nb_programs;
2722                 for( int i=0; i<npgrms; ++i ) {
2723                         AVProgram *pgrm = fmt_ctx->programs[i];
2724                         // first start time video stream
2725                         int64_t vstart_time = min_nudge, astart_time = min_nudge;
2726                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2727                                 int fidx = pgrm->stream_index[j];
2728                                 AVStream *st = fmt_ctx->streams[fidx];
2729                                 AVCodecParameters *avpar = st->codecpar;
2730                                 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2731                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
2732                                         if( vstart_time < st->start_time )
2733                                                 vstart_time = st->start_time;
2734                                         continue;
2735                                 }
2736                                 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2737                                         if( st->start_time == AV_NOPTS_VALUE ) continue;
2738                                         if( astart_time < st->start_time )
2739                                                 astart_time = st->start_time;
2740                                         continue;
2741                                 }
2742                         }
2743                         //since frame rate is much more grainy than sample rate, it is better to
2744                         // align using video, so that total absolute error is minimized.
2745                         int64_t nudge = vstart_time > min_nudge ? vstart_time :
2746                                 astart_time > min_nudge ? astart_time : AV_NOPTS_VALUE;
2747                         for( int j=0; j<(int)pgrm->nb_stream_indexes; ++j ) {
2748                                 int fidx = pgrm->stream_index[j];
2749                                 AVStream *st = fmt_ctx->streams[fidx];
2750                                 AVCodecParameters *avpar = st->codecpar;
2751                                 if( avpar->codec_type == AVMEDIA_TYPE_VIDEO ) {
2752                                         for( int k=0; k<ffvideo.size(); ++k ) {
2753                                                 if( ffvideo[k]->fidx != fidx ) continue;
2754                                                 ffvideo[k]->nudge = nudge;
2755                                         }
2756                                         continue;
2757                                 }
2758                                 if( avpar->codec_type == AVMEDIA_TYPE_AUDIO ) {
2759                                         for( int k=0; k<ffaudio.size(); ++k ) {
2760                                                 if( ffaudio[k]->fidx != fidx ) continue;
2761                                                 ffaudio[k]->nudge = nudge;
2762                                         }
2763                                         continue;
2764                                 }
2765                         }
2766                 }
2767                 // set nudges for any streams not yet set
2768                 int64_t vstart_time = min_nudge, astart_time = min_nudge;
2769                 int nstreams = fmt_ctx->nb_streams;
2770                 for( int i=0; i<nstreams; ++i ) {
2771                         AVStream *st = fmt_ctx->streams[i];
2772                         AVCodecParameters *avpar = st->codecpar;
2773                         switch( avpar->codec_type ) {
2774                         case AVMEDIA_TYPE_VIDEO: {
2775                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
2776                                 int vidx = ffvideo.size();
2777                                 while( --vidx >= 0 && ffvideo[vidx]->fidx != i );
2778                                 if( vidx < 0 ) continue;
2779                                 if( ffvideo[vidx]->nudge != AV_NOPTS_VALUE ) continue;
2780                                 if( vstart_time < st->start_time )
2781                                         vstart_time = st->start_time;
2782                                 break; }
2783                         case AVMEDIA_TYPE_AUDIO: {
2784                                 if( st->start_time == AV_NOPTS_VALUE ) continue;
2785                                 int aidx = ffaudio.size();
2786                                 while( --aidx >= 0 && ffaudio[aidx]->fidx != i );
2787                                 if( aidx < 0 ) continue;
2788                                 if( ffaudio[aidx]->frame_sz < avpar->frame_size )
2789                                         ffaudio[aidx]->frame_sz = avpar->frame_size;
2790                                 if( ffaudio[aidx]->nudge != AV_NOPTS_VALUE ) continue;
2791                                 if( astart_time < st->start_time )
2792                                         astart_time = st->start_time;
2793                                 break; }
2794                         default: break;
2795                         }
2796                 }
2797                 int64_t nudge = vstart_time > min_nudge ? vstart_time :
2798                         astart_time > min_nudge ? astart_time : 0;
2799                 for( int vidx=0; vidx<ffvideo.size(); ++vidx ) {
2800                         if( ffvideo[vidx]->nudge == AV_NOPTS_VALUE )
2801                                 ffvideo[vidx]->nudge = nudge;
2802                 }
2803                 for( int aidx=0; aidx<ffaudio.size(); ++aidx ) {
2804                         if( ffaudio[aidx]->nudge == AV_NOPTS_VALUE )
2805                                 ffaudio[aidx]->nudge = nudge;
2806                 }
2807                 decoding = 1;
2808         }
2809         return decoding;
2810 }
2811
2812 int FFMPEG::encode_activate()
2813 {
2814         int ret = 0;
2815         if( encoding < 0 ) {
2816                 encoding = 0;
2817                 if( !(fmt_ctx->flags & AVFMT_NOFILE) &&
2818                     (ret=avio_open(&fmt_ctx->pb, fmt_ctx->url, AVIO_FLAG_WRITE)) < 0 ) {
2819                         ff_err(ret, "FFMPEG::encode_activate: err opening : %s\n",
2820                                 fmt_ctx->url);
2821                         return -1;
2822                 }
2823
2824                 int prog_id = 1;
2825                 AVProgram *prog = av_new_program(fmt_ctx, prog_id);
2826                 for( int i=0; i< ffvideo.size(); ++i )
2827                         av_program_add_stream_index(fmt_ctx, prog_id, ffvideo[i]->fidx);
2828                 for( int i=0; i< ffaudio.size(); ++i )
2829                         av_program_add_stream_index(fmt_ctx, prog_id, ffaudio[i]->fidx);
2830                 int pi = fmt_ctx->nb_programs;
2831                 while(  --pi >= 0 && fmt_ctx->programs[pi]->id != prog_id );
2832                 AVDictionary **meta = &prog->metadata;
2833                 av_dict_set(meta, "service_provider", "cin5", 0);
2834                 const char *path = fmt_ctx->url, *bp = strrchr(path,'/');
2835                 if( bp ) path = bp + 1;
2836                 av_dict_set(meta, "title", path, 0);
2837
2838                 if( ffaudio.size() ) {
2839                         const char *ep = getenv("CIN_AUDIO_LANG"), *lp = 0;
2840                         if( !ep && (lp=getenv("LANG")) ) { // some are guesses
2841                                 static struct { const char lc[3], lng[4]; } lcode[] = {
2842                                         { "en", "eng" }, { "de", "ger" }, { "es", "spa" },
2843                                         { "eu", "bas" }, { "fr", "fre" }, { "el", "gre" },
2844                                         { "hi", "hin" }, { "it", "ita" }, { "ja", "jap" },
2845                                         { "ko", "kor" }, { "du", "dut" }, { "pl", "pol" },
2846                                         { "pt", "por" }, { "ru", "rus" }, { "sl", "slv" },
2847                                         { "uk", "ukr" }, { "vi", "vie" }, { "zh", "chi" },
2848                                 };
2849                                 for( int i=sizeof(lcode)/sizeof(lcode[0]); --i>=0 && !ep; )
2850                                         if( !strncmp(lcode[i].lc,lp,2) ) ep = lcode[i].lng;
2851                         }
2852                         if( !ep ) ep = "und";
2853                         char lang[5];
2854                         strncpy(lang,ep,3);  lang[3] = 0;
2855                         AVStream *st = ffaudio[0]->st;
2856                         av_dict_set(&st->metadata,"language",lang,0);
2857                 }
2858
2859                 AVDictionary *fopts = 0;
2860                 char option_path[BCTEXTLEN];
2861                 set_option_path(option_path, "format/%s", file_format);
2862                 read_options(option_path, fopts, 1);
2863                 ret = avformat_write_header(fmt_ctx, &fopts);
2864                 if( ret < 0 ) {
2865                         ff_err(ret, "FFMPEG::encode_activate: write header failed %s\n",
2866                                 fmt_ctx->url);
2867                         return -1;
2868                 }
2869                 av_dict_free(&fopts);
2870                 encoding = 1;
2871         }
2872         return encoding;
2873 }
2874
2875
2876 int FFMPEG::audio_seek(int stream, int64_t pos)
2877 {
2878         int aidx = astrm_index[stream].st_idx;
2879         FFAudioStream *aud = ffaudio[aidx];
2880         aud->audio_seek(pos);
2881         return 0;
2882 }
2883
2884 int FFMPEG::video_seek(int stream, int64_t pos)
2885 {
2886         int vidx = vstrm_index[stream].st_idx;
2887         FFVideoStream *vid = ffvideo[vidx];
2888         vid->video_seek(pos);
2889         return 0;
2890 }
2891
2892
2893 int FFMPEG::decode(int chn, int64_t pos, double *samples, int len)
2894 {
2895         if( !has_audio || chn >= astrm_index.size() ) return -1;
2896         int aidx = astrm_index[chn].st_idx;
2897         FFAudioStream *aud = ffaudio[aidx];
2898         if( aud->load(pos, len) < len ) return -1;
2899         int ch = astrm_index[chn].st_ch;
2900         int ret = aud->read(samples,len,ch);
2901         return ret;
2902 }
2903
2904 int FFMPEG::decode(int layer, int64_t pos, VFrame *vframe)
2905 {
2906         if( !has_video || layer >= vstrm_index.size() ) return -1;
2907         int vidx = vstrm_index[layer].st_idx;
2908         FFVideoStream *vid = ffvideo[vidx];
2909         return vid->load(vframe, pos);
2910 }
2911
2912
2913 int FFMPEG::encode(int stream, double **samples, int len)
2914 {
2915         FFAudioStream *aud = ffaudio[stream];
2916         return aud->encode(samples, len);
2917 }
2918
2919
2920 int FFMPEG::encode(int stream, VFrame *frame)
2921 {
2922         FFVideoStream *vid = ffvideo[stream];
2923         return vid->encode(frame);
2924 }
2925
2926 void FFMPEG::start_muxer()
2927 {
2928         if( !running() ) {
2929                 done = 0;
2930                 start();
2931         }
2932 }
2933
2934 void FFMPEG::stop_muxer()
2935 {
2936         if( running() ) {
2937                 done = 1;
2938                 mux_lock->unlock();
2939         }
2940         join();
2941 }
2942
2943 void FFMPEG::flow_off()
2944 {
2945         if( !flow ) return;
2946         flow_lock->lock("FFMPEG::flow_off");
2947         flow = 0;
2948 }
2949
2950 void FFMPEG::flow_on()
2951 {
2952         if( flow ) return;
2953         flow = 1;
2954         flow_lock->unlock();
2955 }
2956
2957 void FFMPEG::flow_ctl()
2958 {
2959         while( !flow ) {
2960                 flow_lock->lock("FFMPEG::flow_ctl");
2961                 flow_lock->unlock();
2962         }
2963 }
2964
2965 int FFMPEG::mux_audio(FFrame *frm)
2966 {
2967         FFStream *fst = frm->fst;
2968         AVCodecContext *ctx = fst->avctx;
2969         AVFrame *frame = *frm;
2970         AVRational tick_rate = {1, ctx->sample_rate};
2971         frame->pts = av_rescale_q(frm->position, tick_rate, ctx->time_base);
2972         int ret = fst->encode_frame(frame);
2973         if( ret < 0 )
2974                 ff_err(ret, "FFMPEG::mux_audio");
2975         return ret >= 0 ? 0 : 1;
2976 }
2977
2978 int FFMPEG::mux_video(FFrame *frm)
2979 {
2980         FFStream *fst = frm->fst;
2981         AVFrame *frame = *frm;
2982         frame->pts = frm->position;
2983         int ret = fst->encode_frame(frame);
2984         if( ret < 0 )
2985                 ff_err(ret, "FFMPEG::mux_video");
2986         return ret >= 0 ? 0 : 1;
2987 }
2988
2989 void FFMPEG::mux()
2990 {
2991         for(;;) {
2992                 double atm = -1, vtm = -1;
2993                 FFrame *afrm = 0, *vfrm = 0;
2994                 int demand = 0;
2995                 for( int i=0; i<ffaudio.size(); ++i ) {  // earliest audio
2996                         FFStream *fst = ffaudio[i];
2997                         if( fst->frm_count < 3 ) { demand = 1; flow_on(); }
2998                         FFrame *frm = fst->frms.first;
2999                         if( !frm ) { if( !done ) return; continue; }
3000                         double tm = to_secs(frm->position, fst->avctx->time_base);
3001                         if( atm < 0 || tm < atm ) { atm = tm;  afrm = frm; }
3002                 }
3003                 for( int i=0; i<ffvideo.size(); ++i ) {  // earliest video
3004                         FFStream *fst = ffvideo[i];
3005                         if( fst->frm_count < 2 ) { demand = 1; flow_on(); }
3006                         FFrame *frm = fst->frms.first;
3007                         if( !frm ) { if( !done ) return; continue; }
3008                         double tm = to_secs(frm->position, fst->avctx->time_base);
3009                         if( vtm < 0 || tm < vtm ) { vtm = tm;  vfrm = frm; }
3010                 }
3011                 if( !demand ) flow_off();
3012                 if( !afrm && !vfrm ) break;