Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
4349 Serge 1
/*
2
 * Copyright (c) 2000-2003 Fabrice Bellard
3
 *
4
 * This file is part of FFmpeg.
5
 *
6
 * FFmpeg is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU Lesser General Public
8
 * License as published by the Free Software Foundation; either
9
 * version 2.1 of the License, or (at your option) any later version.
10
 *
11
 * FFmpeg is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
 * Lesser General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with FFmpeg; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
 */
20
 
21
/**
22
 * @file
23
 * multimedia converter based on the FFmpeg libraries
24
 */
25
 
26
#include "config.h"
27
#include 
28
#include 
29
#include 
30
#include 
31
#include 
32
#include 
33
#if HAVE_ISATTY
34
#if HAVE_IO_H
35
#include 
36
#endif
37
#if HAVE_UNISTD_H
38
#include 
39
#endif
40
#endif
41
#include "libavformat/avformat.h"
42
#include "libavdevice/avdevice.h"
43
#include "libswscale/swscale.h"
44
#include "libswresample/swresample.h"
45
#include "libavutil/opt.h"
46
#include "libavutil/channel_layout.h"
47
#include "libavutil/parseutils.h"
48
#include "libavutil/samplefmt.h"
49
#include "libavutil/fifo.h"
50
#include "libavutil/intreadwrite.h"
51
#include "libavutil/dict.h"
52
#include "libavutil/mathematics.h"
53
#include "libavutil/pixdesc.h"
54
#include "libavutil/avstring.h"
55
#include "libavutil/libm.h"
56
#include "libavutil/imgutils.h"
57
#include "libavutil/timestamp.h"
58
#include "libavutil/bprint.h"
59
#include "libavutil/time.h"
60
#include "libavformat/os_support.h"
61
 
62
#include "libavformat/ffm.h" // not public API
63
 
64
# include "libavfilter/avcodec.h"
65
# include "libavfilter/avfilter.h"
66
# include "libavfilter/buffersrc.h"
67
# include "libavfilter/buffersink.h"
68
 
69
#if HAVE_SYS_RESOURCE_H
70
#include 
71
#include 
72
#include 
73
#elif HAVE_GETPROCESSTIMES
74
#include 
75
#endif
76
#if HAVE_GETPROCESSMEMORYINFO
77
#include 
78
#include 
79
#endif
80
 
81
#if HAVE_SYS_SELECT_H
82
#include 
83
#endif
84
 
85
#if HAVE_TERMIOS_H
86
#include 
87
#include 
88
#include 
89
#include 
90
#elif HAVE_KBHIT
91
#include 
92
#endif
93
 
94
#if HAVE_PTHREADS
95
#include 
96
#endif
97
 
98
#include 
99
 
100
#include "ffmpeg.h"
101
#include "cmdutils.h"
102
 
103
#include "libavutil/avassert.h"
104
 
105
const char program_name[] = "ffmpeg";
106
const int program_birth_year = 2000;
107
 
108
static FILE *vstats_file;
109
 
110
const char *const forced_keyframes_const_names[] = {
111
    "n",
112
    "n_forced",
113
    "prev_forced_n",
114
    "prev_forced_t",
115
    "t",
116
    NULL
117
};
118
 
119
static void do_video_stats(OutputStream *ost, int frame_size);
120
static int64_t getutime(void);
121
static int64_t getmaxrss(void);
122
 
123
static int run_as_daemon  = 0;
124
static int64_t video_size = 0;
125
static int64_t audio_size = 0;
126
static int64_t subtitle_size = 0;
127
static int64_t extra_size = 0;
128
static int nb_frames_dup = 0;
129
static int nb_frames_drop = 0;
130
static int64_t decode_error_stat[2];
131
 
132
static int current_time;
133
AVIOContext *progress_avio = NULL;
134
 
135
static uint8_t *subtitle_out;
136
 
137
#if HAVE_PTHREADS
138
/* signal to input threads that they should exit; set by the main thread */
139
static int transcoding_finished;
140
#endif
141
 
142
#define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
143
 
144
InputStream **input_streams = NULL;
145
int        nb_input_streams = 0;
146
InputFile   **input_files   = NULL;
147
int        nb_input_files   = 0;
148
 
149
OutputStream **output_streams = NULL;
150
int         nb_output_streams = 0;
151
OutputFile   **output_files   = NULL;
152
int         nb_output_files   = 0;
153
 
154
FilterGraph **filtergraphs;
155
int        nb_filtergraphs;
156
 
157
#if HAVE_TERMIOS_H
158
 
159
/* init terminal so that we can grab keys */
160
static struct termios oldtty;
161
static int restore_tty;
162
#endif
163
 
164
static void free_input_threads(void);
165
 
166
 
167
/* sub2video hack:
168
   Convert subtitles to video with alpha to insert them in filter graphs.
169
   This is a temporary solution until libavfilter gets real subtitles support.
170
 */
171
 
172
static int sub2video_get_blank_frame(InputStream *ist)
173
{
174
    int ret;
175
    AVFrame *frame = ist->sub2video.frame;
176
 
177
    av_frame_unref(frame);
178
    ist->sub2video.frame->width  = ist->sub2video.w;
179
    ist->sub2video.frame->height = ist->sub2video.h;
180
    ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
181
    if ((ret = av_frame_get_buffer(frame, 32)) < 0)
182
        return ret;
183
    memset(frame->data[0], 0, frame->height * frame->linesize[0]);
184
    return 0;
185
}
186
 
187
static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
188
                                AVSubtitleRect *r)
189
{
190
    uint32_t *pal, *dst2;
191
    uint8_t *src, *src2;
192
    int x, y;
193
 
194
    if (r->type != SUBTITLE_BITMAP) {
195
        av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
196
        return;
197
    }
198
    if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
199
        av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
200
        return;
201
    }
202
 
203
    dst += r->y * dst_linesize + r->x * 4;
204
    src = r->pict.data[0];
205
    pal = (uint32_t *)r->pict.data[1];
206
    for (y = 0; y < r->h; y++) {
207
        dst2 = (uint32_t *)dst;
208
        src2 = src;
209
        for (x = 0; x < r->w; x++)
210
            *(dst2++) = pal[*(src2++)];
211
        dst += dst_linesize;
212
        src += r->pict.linesize[0];
213
    }
214
}
215
 
216
static void sub2video_push_ref(InputStream *ist, int64_t pts)
217
{
218
    AVFrame *frame = ist->sub2video.frame;
219
    int i;
220
 
221
    av_assert1(frame->data[0]);
222
    ist->sub2video.last_pts = frame->pts = pts;
223
    for (i = 0; i < ist->nb_filters; i++)
224
        av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
225
                                     AV_BUFFERSRC_FLAG_KEEP_REF |
226
                                     AV_BUFFERSRC_FLAG_PUSH);
227
}
228
 
229
static void sub2video_update(InputStream *ist, AVSubtitle *sub)
230
{
231
    int w = ist->sub2video.w, h = ist->sub2video.h;
232
    AVFrame *frame = ist->sub2video.frame;
233
    int8_t *dst;
234
    int     dst_linesize;
235
    int num_rects, i;
236
    int64_t pts, end_pts;
237
 
238
    if (!frame)
239
        return;
240
    if (sub) {
241
        pts       = av_rescale_q(sub->pts + sub->start_display_time * 1000,
242
                                 AV_TIME_BASE_Q, ist->st->time_base);
243
        end_pts   = av_rescale_q(sub->pts + sub->end_display_time   * 1000,
244
                                 AV_TIME_BASE_Q, ist->st->time_base);
245
        num_rects = sub->num_rects;
246
    } else {
247
        pts       = ist->sub2video.end_pts;
248
        end_pts   = INT64_MAX;
249
        num_rects = 0;
250
    }
251
    if (sub2video_get_blank_frame(ist) < 0) {
252
        av_log(ist->st->codec, AV_LOG_ERROR,
253
               "Impossible to get a blank canvas.\n");
254
        return;
255
    }
256
    dst          = frame->data    [0];
257
    dst_linesize = frame->linesize[0];
258
    for (i = 0; i < num_rects; i++)
259
        sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
260
    sub2video_push_ref(ist, pts);
261
    ist->sub2video.end_pts = end_pts;
262
}
263
 
264
static void sub2video_heartbeat(InputStream *ist, int64_t pts)
265
{
266
    InputFile *infile = input_files[ist->file_index];
267
    int i, j, nb_reqs;
268
    int64_t pts2;
269
 
270
    /* When a frame is read from a file, examine all sub2video streams in
271
       the same file and send the sub2video frame again. Otherwise, decoded
272
       video frames could be accumulating in the filter graph while a filter
273
       (possibly overlay) is desperately waiting for a subtitle frame. */
274
    for (i = 0; i < infile->nb_streams; i++) {
275
        InputStream *ist2 = input_streams[infile->ist_index + i];
276
        if (!ist2->sub2video.frame)
277
            continue;
278
        /* subtitles seem to be usually muxed ahead of other streams;
279
           if not, substracting a larger time here is necessary */
280
        pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
281
        /* do not send the heartbeat frame if the subtitle is already ahead */
282
        if (pts2 <= ist2->sub2video.last_pts)
283
            continue;
284
        if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
285
            sub2video_update(ist2, NULL);
286
        for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
287
            nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
288
        if (nb_reqs)
289
            sub2video_push_ref(ist2, pts2);
290
    }
291
}
292
 
293
static void sub2video_flush(InputStream *ist)
294
{
295
    int i;
296
 
297
    for (i = 0; i < ist->nb_filters; i++)
298
        av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
299
}
300
 
301
/* end of sub2video hack */
302
 
303
void term_exit(void)
304
{
305
    av_log(NULL, AV_LOG_QUIET, "%s", "");
306
#if HAVE_TERMIOS_H
307
    if(restore_tty)
308
        tcsetattr (0, TCSANOW, &oldtty);
309
#endif
310
}
311
 
312
static volatile int received_sigterm = 0;
313
static volatile int received_nb_signals = 0;
314
 
315
static void
316
sigterm_handler(int sig)
317
{
318
    received_sigterm = sig;
319
    received_nb_signals++;
320
    term_exit();
321
    if(received_nb_signals > 3)
322
        exit_program(123);
323
}
324
 
325
void term_init(void)
326
{
327
#if HAVE_TERMIOS_H
328
    if(!run_as_daemon){
329
        struct termios tty;
330
        int istty = 1;
331
#if HAVE_ISATTY
332
        istty = isatty(0) && isatty(2);
333
#endif
334
        if (istty && tcgetattr (0, &tty) == 0) {
335
            oldtty = tty;
336
            restore_tty = 1;
337
 
338
            tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
339
                             |INLCR|IGNCR|ICRNL|IXON);
340
            tty.c_oflag |= OPOST;
341
            tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
342
            tty.c_cflag &= ~(CSIZE|PARENB);
343
            tty.c_cflag |= CS8;
344
            tty.c_cc[VMIN] = 1;
345
            tty.c_cc[VTIME] = 0;
346
 
347
            tcsetattr (0, TCSANOW, &tty);
348
        }
349
        signal(SIGQUIT, sigterm_handler); /* Quit (POSIX).  */
350
    }
351
#endif
352
    avformat_network_deinit();
353
 
354
    signal(SIGINT , sigterm_handler); /* Interrupt (ANSI).    */
355
    signal(SIGTERM, sigterm_handler); /* Termination (ANSI).  */
356
#ifdef SIGXCPU
357
    signal(SIGXCPU, sigterm_handler);
358
#endif
359
}
360
 
361
/* read a key without blocking */
362
static int read_key(void)
363
{
364
    unsigned char ch;
365
#if HAVE_TERMIOS_H
366
    int n = 1;
367
    struct timeval tv;
368
    fd_set rfds;
369
 
370
    FD_ZERO(&rfds);
371
    FD_SET(0, &rfds);
372
    tv.tv_sec = 0;
373
    tv.tv_usec = 0;
374
    n = select(1, &rfds, NULL, NULL, &tv);
375
    if (n > 0) {
376
        n = read(0, &ch, 1);
377
        if (n == 1)
378
            return ch;
379
 
380
        return n;
381
    }
382
#elif HAVE_KBHIT
383
#    if HAVE_PEEKNAMEDPIPE
384
    static int is_pipe;
385
    static HANDLE input_handle;
386
    DWORD dw, nchars;
387
    if(!input_handle){
388
        input_handle = GetStdHandle(STD_INPUT_HANDLE);
389
        is_pipe = !GetConsoleMode(input_handle, &dw);
390
    }
391
 
392
    if (stdin->_cnt > 0) {
393
        read(0, &ch, 1);
394
        return ch;
395
    }
396
    if (is_pipe) {
397
        /* When running under a GUI, you will end here. */
398
        if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
399
            // input pipe may have been closed by the program that ran ffmpeg
400
            return -1;
401
        }
402
        //Read it
403
        if(nchars != 0) {
404
            read(0, &ch, 1);
405
            return ch;
406
        }else{
407
            return -1;
408
        }
409
    }
410
#    endif
411
    if(kbhit())
412
        return(getch());
413
#endif
414
    return -1;
415
}
416
 
417
static int decode_interrupt_cb(void *ctx)
418
{
419
    return received_nb_signals > 1;
420
}
421
 
422
const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
423
 
424
static void ffmpeg_cleanup(int ret)
425
{
426
    int i, j;
427
 
428
    if (do_benchmark) {
429
        int maxrss = getmaxrss() / 1024;
430
        printf("bench: maxrss=%ikB\n", maxrss);
431
    }
432
 
433
    for (i = 0; i < nb_filtergraphs; i++) {
434
        avfilter_graph_free(&filtergraphs[i]->graph);
435
        for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
436
            av_freep(&filtergraphs[i]->inputs[j]->name);
437
            av_freep(&filtergraphs[i]->inputs[j]);
438
        }
439
        av_freep(&filtergraphs[i]->inputs);
440
        for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
441
            av_freep(&filtergraphs[i]->outputs[j]->name);
442
            av_freep(&filtergraphs[i]->outputs[j]);
443
        }
444
        av_freep(&filtergraphs[i]->outputs);
445
        av_freep(&filtergraphs[i]->graph_desc);
446
        av_freep(&filtergraphs[i]);
447
    }
448
    av_freep(&filtergraphs);
449
 
450
    av_freep(&subtitle_out);
451
 
452
    /* close files */
453
    for (i = 0; i < nb_output_files; i++) {
454
        AVFormatContext *s = output_files[i]->ctx;
455
        if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)
456
            avio_close(s->pb);
457
        avformat_free_context(s);
458
        av_dict_free(&output_files[i]->opts);
459
        av_freep(&output_files[i]);
460
    }
461
    for (i = 0; i < nb_output_streams; i++) {
462
        AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
463
        while (bsfc) {
464
            AVBitStreamFilterContext *next = bsfc->next;
465
            av_bitstream_filter_close(bsfc);
466
            bsfc = next;
467
        }
468
        output_streams[i]->bitstream_filters = NULL;
469
        avcodec_free_frame(&output_streams[i]->filtered_frame);
470
 
471
        av_freep(&output_streams[i]->forced_keyframes);
472
        av_expr_free(output_streams[i]->forced_keyframes_pexpr);
473
        av_freep(&output_streams[i]->avfilter);
474
        av_freep(&output_streams[i]->logfile_prefix);
475
        av_freep(&output_streams[i]);
476
    }
477
#if HAVE_PTHREADS
478
    free_input_threads();
479
#endif
480
    for (i = 0; i < nb_input_files; i++) {
481
        avformat_close_input(&input_files[i]->ctx);
482
        av_freep(&input_files[i]);
483
    }
484
    for (i = 0; i < nb_input_streams; i++) {
485
        av_frame_free(&input_streams[i]->decoded_frame);
486
        av_frame_free(&input_streams[i]->filter_frame);
487
        av_dict_free(&input_streams[i]->opts);
488
        avsubtitle_free(&input_streams[i]->prev_sub.subtitle);
489
        av_frame_free(&input_streams[i]->sub2video.frame);
490
        av_freep(&input_streams[i]->filters);
491
        av_freep(&input_streams[i]);
492
    }
493
 
494
    if (vstats_file)
495
        fclose(vstats_file);
496
    av_free(vstats_filename);
497
 
498
    av_freep(&input_streams);
499
    av_freep(&input_files);
500
    av_freep(&output_streams);
501
    av_freep(&output_files);
502
 
503
    uninit_opts();
504
 
505
    avformat_network_deinit();
506
 
507
    if (received_sigterm) {
508
        av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
509
               (int) received_sigterm);
510
    }
511
    term_exit();
512
}
513
 
514
void assert_avoptions(AVDictionary *m)
515
{
516
    AVDictionaryEntry *t;
517
    if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
518
        av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
519
        exit_program(1);
520
    }
521
}
522
 
523
static void abort_codec_experimental(AVCodec *c, int encoder)
524
{
525
    exit_program(1);
526
}
527
 
528
static void update_benchmark(const char *fmt, ...)
529
{
530
    if (do_benchmark_all) {
531
        int64_t t = getutime();
532
        va_list va;
533
        char buf[1024];
534
 
535
        if (fmt) {
536
            va_start(va, fmt);
537
            vsnprintf(buf, sizeof(buf), fmt, va);
538
            va_end(va);
539
            printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
540
        }
541
        current_time = t;
542
    }
543
}
544
 
545
static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
546
{
547
    AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
548
    AVCodecContext          *avctx = ost->st->codec;
549
    int ret;
550
 
551
    if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
552
        (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
553
        pkt->pts = pkt->dts = AV_NOPTS_VALUE;
554
 
555
    /*
556
     * Audio encoders may split the packets --  #frames in != #packets out.
557
     * But there is no reordering, so we can limit the number of output packets
558
     * by simply dropping them here.
559
     * Counting encoded video frames needs to be done separately because of
560
     * reordering, see do_video_out()
561
     */
562
    if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
563
        if (ost->frame_number >= ost->max_frames) {
564
            av_free_packet(pkt);
565
            return;
566
        }
567
        ost->frame_number++;
568
    }
569
 
570
    while (bsfc) {
571
        AVPacket new_pkt = *pkt;
572
        int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
573
                                           &new_pkt.data, &new_pkt.size,
574
                                           pkt->data, pkt->size,
575
                                           pkt->flags & AV_PKT_FLAG_KEY);
576
        if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
577
            uint8_t *t = av_malloc(new_pkt.size + FF_INPUT_BUFFER_PADDING_SIZE); //the new should be a subset of the old so cannot overflow
578
            if(t) {
579
                memcpy(t, new_pkt.data, new_pkt.size);
580
                memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
581
                new_pkt.data = t;
582
                new_pkt.buf = NULL;
583
                a = 1;
584
            } else
585
                a = AVERROR(ENOMEM);
586
        }
587
        if (a > 0) {
588
            av_free_packet(pkt);
589
            new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
590
                                           av_buffer_default_free, NULL, 0);
591
            if (!new_pkt.buf)
592
                exit_program(1);
593
        } else if (a < 0) {
594
            av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
595
                   bsfc->filter->name, pkt->stream_index,
596
                   avctx->codec ? avctx->codec->name : "copy");
597
            print_error("", a);
598
            if (exit_on_error)
599
                exit_program(1);
600
        }
601
        *pkt = new_pkt;
602
 
603
        bsfc = bsfc->next;
604
    }
605
 
606
    if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
607
        (avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) &&
608
        pkt->dts != AV_NOPTS_VALUE &&
609
        ost->last_mux_dts != AV_NOPTS_VALUE) {
610
      int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
611
      if (pkt->dts < max) {
612
        int loglevel = max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
613
        av_log(s, loglevel, "Non-monotonous DTS in output stream "
614
               "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
615
               ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
616
        if (exit_on_error) {
617
            av_log(NULL, AV_LOG_FATAL, "aborting.\n");
618
            exit_program(1);
619
        }
620
        av_log(s, loglevel, "changing to %"PRId64". This may result "
621
               "in incorrect timestamps in the output file.\n",
622
               max);
623
        if(pkt->pts >= pkt->dts)
624
            pkt->pts = FFMAX(pkt->pts, max);
625
        pkt->dts = max;
626
      }
627
    }
628
    ost->last_mux_dts = pkt->dts;
629
 
630
    pkt->stream_index = ost->index;
631
 
632
    if (debug_ts) {
633
        av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
634
                "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
635
                av_get_media_type_string(ost->st->codec->codec_type),
636
                av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
637
                av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
638
                pkt->size
639
              );
640
    }
641
 
642
    ret = av_interleaved_write_frame(s, pkt);
643
    if (ret < 0) {
644
        print_error("av_interleaved_write_frame()", ret);
645
        exit_program(1);
646
    }
647
}
648
 
649
static void close_output_stream(OutputStream *ost)
650
{
651
    OutputFile *of = output_files[ost->file_index];
652
 
653
    ost->finished = 1;
654
    if (of->shortest) {
655
        int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, AV_TIME_BASE_Q);
656
        of->recording_time = FFMIN(of->recording_time, end);
657
    }
658
}
659
 
660
static int check_recording_time(OutputStream *ost)
661
{
662
    OutputFile *of = output_files[ost->file_index];
663
 
664
    if (of->recording_time != INT64_MAX &&
665
        av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
666
                      AV_TIME_BASE_Q) >= 0) {
667
        close_output_stream(ost);
668
        return 0;
669
    }
670
    return 1;
671
}
672
 
673
static void do_audio_out(AVFormatContext *s, OutputStream *ost,
674
                         AVFrame *frame)
675
{
676
    AVCodecContext *enc = ost->st->codec;
677
    AVPacket pkt;
678
    int got_packet = 0;
679
 
680
    av_init_packet(&pkt);
681
    pkt.data = NULL;
682
    pkt.size = 0;
683
 
684
    if (!check_recording_time(ost))
685
        return;
686
 
687
    if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
688
        frame->pts = ost->sync_opts;
689
    ost->sync_opts = frame->pts + frame->nb_samples;
690
 
691
    av_assert0(pkt.size || !pkt.data);
692
    update_benchmark(NULL);
693
    if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
694
        av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
695
        exit_program(1);
696
    }
697
    update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
698
 
699
    if (got_packet) {
700
        if (pkt.pts != AV_NOPTS_VALUE)
701
            pkt.pts      = av_rescale_q(pkt.pts,      enc->time_base, ost->st->time_base);
702
        if (pkt.dts != AV_NOPTS_VALUE)
703
            pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);
704
        if (pkt.duration > 0)
705
            pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
706
 
707
        if (debug_ts) {
708
            av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
709
                   "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
710
                   av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
711
                   av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
712
        }
713
 
714
        audio_size += pkt.size;
715
        write_frame(s, &pkt, ost);
716
 
717
        av_free_packet(&pkt);
718
    }
719
}
720
 
721
static void do_subtitle_out(AVFormatContext *s,
722
                            OutputStream *ost,
723
                            InputStream *ist,
724
                            AVSubtitle *sub)
725
{
726
    int subtitle_out_max_size = 1024 * 1024;
727
    int subtitle_out_size, nb, i;
728
    AVCodecContext *enc;
729
    AVPacket pkt;
730
    int64_t pts;
731
 
732
    if (sub->pts == AV_NOPTS_VALUE) {
733
        av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
734
        if (exit_on_error)
735
            exit_program(1);
736
        return;
737
    }
738
 
739
    enc = ost->st->codec;
740
 
741
    if (!subtitle_out) {
742
        subtitle_out = av_malloc(subtitle_out_max_size);
743
    }
744
 
745
    /* Note: DVB subtitle need one packet to draw them and one other
746
       packet to clear them */
747
    /* XXX: signal it in the codec context ? */
748
    if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
749
        nb = 2;
750
    else
751
        nb = 1;
752
 
753
    /* shift timestamp to honor -ss and make check_recording_time() work with -t */
754
    pts = sub->pts;
755
    if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
756
        pts -= output_files[ost->file_index]->start_time;
757
    for (i = 0; i < nb; i++) {
758
        ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
759
        if (!check_recording_time(ost))
760
            return;
761
 
762
        sub->pts = pts;
763
        // start_display_time is required to be 0
764
        sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
765
        sub->end_display_time  -= sub->start_display_time;
766
        sub->start_display_time = 0;
767
        if (i == 1)
768
            sub->num_rects = 0;
769
        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
770
                                                    subtitle_out_max_size, sub);
771
        if (subtitle_out_size < 0) {
772
            av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
773
            exit_program(1);
774
        }
775
 
776
        av_init_packet(&pkt);
777
        pkt.data = subtitle_out;
778
        pkt.size = subtitle_out_size;
779
        pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
780
        pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
781
        if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
782
            /* XXX: the pts correction is handled here. Maybe handling
783
               it in the codec would be better */
784
            if (i == 0)
785
                pkt.pts += 90 * sub->start_display_time;
786
            else
787
                pkt.pts += 90 * sub->end_display_time;
788
        }
789
        subtitle_size += pkt.size;
790
        write_frame(s, &pkt, ost);
791
    }
792
}
793
 
794
static void do_video_out(AVFormatContext *s,
795
                         OutputStream *ost,
796
                         AVFrame *in_picture)
797
{
798
    int ret, format_video_sync;
799
    AVPacket pkt;
800
    AVCodecContext *enc = ost->st->codec;
801
    int nb_frames, i;
802
    double sync_ipts, delta;
803
    double duration = 0;
804
    int frame_size = 0;
805
    InputStream *ist = NULL;
806
 
807
    if (ost->source_index >= 0)
808
        ist = input_streams[ost->source_index];
809
 
810
    if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
811
        duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
812
 
813
    sync_ipts = in_picture->pts;
814
    delta = sync_ipts - ost->sync_opts + duration;
815
 
816
    /* by default, we output a single frame */
817
    nb_frames = 1;
818
 
819
    format_video_sync = video_sync_method;
820
    if (format_video_sync == VSYNC_AUTO) {
821
        format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
822
        if (   ist
823
            && format_video_sync == VSYNC_CFR
824
            && input_files[ist->file_index]->ctx->nb_streams == 1
825
            && input_files[ist->file_index]->input_ts_offset == 0) {
826
            format_video_sync = VSYNC_VSCFR;
827
        }
828
    }
829
 
830
    switch (format_video_sync) {
831
    case VSYNC_VSCFR:
832
        if (ost->frame_number == 0 && delta - duration >= 0.5) {
833
            av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta - duration));
834
            delta = duration;
835
            ost->sync_opts = lrint(sync_ipts);
836
        }
837
    case VSYNC_CFR:
838
        // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
839
        if (delta < -1.1)
840
            nb_frames = 0;
841
        else if (delta > 1.1)
842
            nb_frames = lrintf(delta);
843
        break;
844
    case VSYNC_VFR:
845
        if (delta <= -0.6)
846
            nb_frames = 0;
847
        else if (delta > 0.6)
848
            ost->sync_opts = lrint(sync_ipts);
849
        break;
850
    case VSYNC_DROP:
851
    case VSYNC_PASSTHROUGH:
852
        ost->sync_opts = lrint(sync_ipts);
853
        break;
854
    default:
855
        av_assert0(0);
856
    }
857
 
858
    nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
859
    if (nb_frames == 0) {
860
        nb_frames_drop++;
861
        av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
862
        return;
863
    } else if (nb_frames > 1) {
864
        if (nb_frames > dts_error_threshold * 30) {
865
            av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
866
            nb_frames_drop++;
867
            return;
868
        }
869
        nb_frames_dup += nb_frames - 1;
870
        av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
871
    }
872
 
873
  /* duplicates frame if needed */
874
  for (i = 0; i < nb_frames; i++) {
875
    av_init_packet(&pkt);
876
    pkt.data = NULL;
877
    pkt.size = 0;
878
 
879
    in_picture->pts = ost->sync_opts;
880
 
881
#if 1
882
    if (!check_recording_time(ost))
883
#else
884
    if (ost->frame_number >= ost->max_frames)
885
#endif
886
        return;
887
 
888
    if (s->oformat->flags & AVFMT_RAWPICTURE &&
889
        enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
890
        /* raw pictures are written as AVPicture structure to
891
           avoid any copies. We support temporarily the older
892
           method. */
893
        enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
894
        enc->coded_frame->top_field_first  = in_picture->top_field_first;
895
        if (enc->coded_frame->interlaced_frame)
896
            enc->field_order = enc->coded_frame->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
897
        else
898
            enc->field_order = AV_FIELD_PROGRESSIVE;
899
        pkt.data   = (uint8_t *)in_picture;
900
        pkt.size   =  sizeof(AVPicture);
901
        pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
902
        pkt.flags |= AV_PKT_FLAG_KEY;
903
 
904
        video_size += pkt.size;
905
        write_frame(s, &pkt, ost);
906
    } else {
907
        int got_packet, forced_keyframe = 0;
908
        double pts_time;
909
 
910
        if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&
911
            ost->top_field_first >= 0)
912
            in_picture->top_field_first = !!ost->top_field_first;
913
 
914
        if (in_picture->interlaced_frame) {
915
            if (enc->codec->id == AV_CODEC_ID_MJPEG)
916
                enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
917
            else
918
                enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
919
        } else
920
            enc->field_order = AV_FIELD_PROGRESSIVE;
921
 
922
        in_picture->quality = ost->st->codec->global_quality;
923
        if (!enc->me_threshold)
924
            in_picture->pict_type = 0;
925
 
926
        pts_time = in_picture->pts != AV_NOPTS_VALUE ?
927
            in_picture->pts * av_q2d(enc->time_base) : NAN;
928
        if (ost->forced_kf_index < ost->forced_kf_count &&
929
            in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
930
            ost->forced_kf_index++;
931
            forced_keyframe = 1;
932
        } else if (ost->forced_keyframes_pexpr) {
933
            double res;
934
            ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
935
            res = av_expr_eval(ost->forced_keyframes_pexpr,
936
                               ost->forced_keyframes_expr_const_values, NULL);
937
            av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
938
                    ost->forced_keyframes_expr_const_values[FKF_N],
939
                    ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
940
                    ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
941
                    ost->forced_keyframes_expr_const_values[FKF_T],
942
                    ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
943
                    res);
944
            if (res) {
945
                forced_keyframe = 1;
946
                ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
947
                    ost->forced_keyframes_expr_const_values[FKF_N];
948
                ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
949
                    ost->forced_keyframes_expr_const_values[FKF_T];
950
                ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
951
            }
952
 
953
            ost->forced_keyframes_expr_const_values[FKF_N] += 1;
954
        }
955
        if (forced_keyframe) {
956
            in_picture->pict_type = AV_PICTURE_TYPE_I;
957
            av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
958
        }
959
 
960
        update_benchmark(NULL);
961
        ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
962
        update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
963
        if (ret < 0) {
964
            av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
965
            exit_program(1);
966
        }
967
 
968
        if (got_packet) {
969
            if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
970
                pkt.pts = ost->sync_opts;
971
 
972
            if (pkt.pts != AV_NOPTS_VALUE)
973
                pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
974
            if (pkt.dts != AV_NOPTS_VALUE)
975
                pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
976
 
977
            if (debug_ts) {
978
                av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
979
                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
980
                    av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
981
                    av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
982
            }
983
 
984
            frame_size = pkt.size;
985
            video_size += pkt.size;
986
            write_frame(s, &pkt, ost);
987
            av_free_packet(&pkt);
988
 
989
            /* if two pass, output log */
990
            if (ost->logfile && enc->stats_out) {
991
                fprintf(ost->logfile, "%s", enc->stats_out);
992
            }
993
        }
994
    }
995
    ost->sync_opts++;
996
    /*
997
     * For video, number of frames in == number of packets out.
998
     * But there may be reordering, so we can't throw away frames on encoder
999
     * flush, we need to limit them here, before they go into encoder.
1000
     */
1001
    ost->frame_number++;
1002
 
1003
    if (vstats_filename && frame_size)
1004
        do_video_stats(ost, frame_size);
1005
  }
1006
}
1007
 
1008
static double psnr(double d)
1009
{
1010
    return -10.0 * log(d) / log(10.0);
1011
}
1012
 
1013
static void do_video_stats(OutputStream *ost, int frame_size)
1014
{
1015
    AVCodecContext *enc;
1016
    int frame_number;
1017
    double ti1, bitrate, avg_bitrate;
1018
 
1019
    /* this is executed just the first time do_video_stats is called */
1020
    if (!vstats_file) {
1021
        vstats_file = fopen(vstats_filename, "w");
1022
        if (!vstats_file) {
1023
            perror("fopen");
1024
            exit_program(1);
1025
        }
1026
    }
1027
 
1028
    enc = ost->st->codec;
1029
    if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1030
        frame_number = ost->st->nb_frames;
1031
        fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1032
        if (enc->flags&CODEC_FLAG_PSNR)
1033
            fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1034
 
1035
        fprintf(vstats_file,"f_size= %6d ", frame_size);
1036
        /* compute pts value */
1037
        ti1 = ost->st->pts.val * av_q2d(enc->time_base);
1038
        if (ti1 < 0.01)
1039
            ti1 = 0.01;
1040
 
1041
        bitrate     = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1042
        avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1043
        fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1044
               (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1045
        fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1046
    }
1047
}
1048
 
1049
/**
1050
 * Get and encode new output from any of the filtergraphs, without causing
1051
 * activity.
1052
 *
1053
 * @return  0 for success, <0 for severe errors
1054
 */
1055
static int reap_filters(void)
1056
{
1057
    AVFrame *filtered_frame = NULL;
1058
    int i;
1059
    int64_t frame_pts;
1060
 
1061
    /* Reap all buffers present in the buffer sinks */
1062
    for (i = 0; i < nb_output_streams; i++) {
1063
        OutputStream *ost = output_streams[i];
1064
        OutputFile    *of = output_files[ost->file_index];
1065
        int ret = 0;
1066
 
1067
        if (!ost->filter)
1068
            continue;
1069
 
1070
        if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
1071
            return AVERROR(ENOMEM);
1072
        } else
1073
            avcodec_get_frame_defaults(ost->filtered_frame);
1074
        filtered_frame = ost->filtered_frame;
1075
 
1076
        while (1) {
1077
            ret = av_buffersink_get_frame_flags(ost->filter->filter, filtered_frame,
1078
                                               AV_BUFFERSINK_FLAG_NO_REQUEST);
1079
            if (ret < 0) {
1080
                if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
1081
                    av_log(NULL, AV_LOG_WARNING,
1082
                           "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
1083
                }
1084
                break;
1085
            }
1086
            frame_pts = AV_NOPTS_VALUE;
1087
            if (filtered_frame->pts != AV_NOPTS_VALUE) {
1088
                int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1089
                filtered_frame->pts = frame_pts = av_rescale_q(filtered_frame->pts,
1090
                                                ost->filter->filter->inputs[0]->time_base,
1091
                                                ost->st->codec->time_base) -
1092
                                    av_rescale_q(start_time,
1093
                                                AV_TIME_BASE_Q,
1094
                                                ost->st->codec->time_base);
1095
            }
1096
            //if (ost->source_index >= 0)
1097
            //    *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
1098
 
1099
 
1100
            switch (ost->filter->filter->inputs[0]->type) {
1101
            case AVMEDIA_TYPE_VIDEO:
1102
                filtered_frame->pts = frame_pts;
1103
                if (!ost->frame_aspect_ratio.num)
1104
                    ost->st->codec->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1105
 
1106
                do_video_out(of->ctx, ost, filtered_frame);
1107
                break;
1108
            case AVMEDIA_TYPE_AUDIO:
1109
                filtered_frame->pts = frame_pts;
1110
                if (!(ost->st->codec->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
1111
                    ost->st->codec->channels != av_frame_get_channels(filtered_frame)) {
1112
                    av_log(NULL, AV_LOG_ERROR,
1113
                           "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1114
                    break;
1115
                }
1116
                do_audio_out(of->ctx, ost, filtered_frame);
1117
                break;
1118
            default:
1119
                // TODO support subtitle filters
1120
                av_assert0(0);
1121
            }
1122
 
1123
            av_frame_unref(filtered_frame);
1124
        }
1125
    }
1126
 
1127
    return 0;
1128
}
1129
 
1130
static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
1131
{
1132
    char buf[1024];
1133
    AVBPrint buf_script;
1134
    OutputStream *ost;
1135
    AVFormatContext *oc;
1136
    int64_t total_size;
1137
    AVCodecContext *enc;
1138
    int frame_number, vid, i;
1139
    double bitrate;
1140
    int64_t pts = INT64_MIN;
1141
    static int64_t last_time = -1;
1142
    static int qp_histogram[52];
1143
    int hours, mins, secs, us;
1144
 
1145
    if (!print_stats && !is_last_report && !progress_avio)
1146
        return;
1147
 
1148
    if (!is_last_report) {
1149
        if (last_time == -1) {
1150
            last_time = cur_time;
1151
            return;
1152
        }
1153
        if ((cur_time - last_time) < 500000)
1154
            return;
1155
        last_time = cur_time;
1156
    }
1157
 
1158
 
1159
    oc = output_files[0]->ctx;
1160
 
1161
    total_size = avio_size(oc->pb);
1162
    if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
1163
        total_size = avio_tell(oc->pb);
1164
 
1165
    buf[0] = '\0';
1166
    vid = 0;
1167
    av_bprint_init(&buf_script, 0, 1);
1168
    for (i = 0; i < nb_output_streams; i++) {
1169
        float q = -1;
1170
        ost = output_streams[i];
1171
        enc = ost->st->codec;
1172
        if (!ost->stream_copy && enc->coded_frame)
1173
            q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1174
        if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1175
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1176
            av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1177
                       ost->file_index, ost->index, q);
1178
        }
1179
        if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1180
            float fps, t = (cur_time-timer_start) / 1000000.0;
1181
 
1182
            frame_number = ost->frame_number;
1183
            fps = t > 1 ? frame_number / t : 0;
1184
            snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
1185
                     frame_number, fps < 9.95, fps, q);
1186
            av_bprintf(&buf_script, "frame=%d\n", frame_number);
1187
            av_bprintf(&buf_script, "fps=%.1f\n", fps);
1188
            av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1189
                       ost->file_index, ost->index, q);
1190
            if (is_last_report)
1191
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1192
            if (qp_hist) {
1193
                int j;
1194
                int qp = lrintf(q);
1195
                if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1196
                    qp_histogram[qp]++;
1197
                for (j = 0; j < 32; j++)
1198
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
1199
            }
1200
            if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
1201
                int j;
1202
                double error, error_sum = 0;
1203
                double scale, scale_sum = 0;
1204
                double p;
1205
                char type[3] = { 'Y','U','V' };
1206
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1207
                for (j = 0; j < 3; j++) {
1208
                    if (is_last_report) {
1209
                        error = enc->error[j];
1210
                        scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1211
                    } else {
1212
                        error = enc->coded_frame->error[j];
1213
                        scale = enc->width * enc->height * 255.0 * 255.0;
1214
                    }
1215
                    if (j)
1216
                        scale /= 4;
1217
                    error_sum += error;
1218
                    scale_sum += scale;
1219
                    p = psnr(error / scale);
1220
                    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
1221
                    av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
1222
                               ost->file_index, ost->index, type[j] | 32, p);
1223
                }
1224
                p = psnr(error_sum / scale_sum);
1225
                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1226
                av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
1227
                           ost->file_index, ost->index, p);
1228
            }
1229
            vid = 1;
1230
        }
1231
        /* compute min output value */
1232
        if ((is_last_report || !ost->finished) && ost->st->pts.val != AV_NOPTS_VALUE)
1233
            pts = FFMAX(pts, av_rescale_q(ost->st->pts.val,
1234
                                          ost->st->time_base, AV_TIME_BASE_Q));
1235
    }
1236
 
1237
    secs = pts / AV_TIME_BASE;
1238
    us = pts % AV_TIME_BASE;
1239
    mins = secs / 60;
1240
    secs %= 60;
1241
    hours = mins / 60;
1242
    mins %= 60;
1243
 
1244
    bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
1245
 
1246
    if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1247
                                 "size=N/A time=");
1248
    else                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1249
                                 "size=%8.0fkB time=", total_size / 1024.0);
1250
    snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1251
             "%02d:%02d:%02d.%02d ", hours, mins, secs,
1252
             (100 * us) / AV_TIME_BASE);
1253
    if (bitrate < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1254
                              "bitrate=N/A");
1255
    else             snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1256
                              "bitrate=%6.1fkbits/s", bitrate);
1257
    if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
1258
    else                av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
1259
    av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
1260
    av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
1261
               hours, mins, secs, us);
1262
 
1263
    if (nb_frames_dup || nb_frames_drop)
1264
        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1265
                nb_frames_dup, nb_frames_drop);
1266
    av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
1267
    av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
1268
 
1269
    if (print_stats || is_last_report) {
1270
        if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
1271
            fprintf(stderr, "%s    \r", buf);
1272
        } else
1273
            av_log(NULL, AV_LOG_INFO, "%s    \r", buf);
1274
 
1275
    fflush(stderr);
1276
    }
1277
 
1278
    if (progress_avio) {
1279
        av_bprintf(&buf_script, "progress=%s\n",
1280
                   is_last_report ? "end" : "continue");
1281
        avio_write(progress_avio, buf_script.str,
1282
                   FFMIN(buf_script.len, buf_script.size - 1));
1283
        avio_flush(progress_avio);
1284
        av_bprint_finalize(&buf_script, NULL);
1285
        if (is_last_report) {
1286
            avio_close(progress_avio);
1287
            progress_avio = NULL;
1288
        }
1289
    }
1290
 
1291
    if (is_last_report) {
1292
        int64_t raw= audio_size + video_size + subtitle_size + extra_size;
1293
        av_log(NULL, AV_LOG_INFO, "\n");
1294
        av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
1295
               video_size / 1024.0,
1296
               audio_size / 1024.0,
1297
               subtitle_size / 1024.0,
1298
               extra_size / 1024.0,
1299
               100.0 * (total_size - raw) / raw
1300
        );
1301
        if(video_size + audio_size + subtitle_size + extra_size == 0){
1302
            av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
1303
        }
1304
    }
1305
}
1306
 
1307
static void flush_encoders(void)
1308
{
1309
    int i, ret;
1310
 
1311
    for (i = 0; i < nb_output_streams; i++) {
1312
        OutputStream   *ost = output_streams[i];
1313
        AVCodecContext *enc = ost->st->codec;
1314
        AVFormatContext *os = output_files[ost->file_index]->ctx;
1315
        int stop_encoding = 0;
1316
 
1317
        if (!ost->encoding_needed)
1318
            continue;
1319
 
1320
        if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1321
            continue;
1322
        if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
1323
            continue;
1324
 
1325
        for (;;) {
1326
            int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1327
            const char *desc;
1328
            int64_t *size;
1329
 
1330
            switch (ost->st->codec->codec_type) {
1331
            case AVMEDIA_TYPE_AUDIO:
1332
                encode = avcodec_encode_audio2;
1333
                desc   = "Audio";
1334
                size   = &audio_size;
1335
                break;
1336
            case AVMEDIA_TYPE_VIDEO:
1337
                encode = avcodec_encode_video2;
1338
                desc   = "Video";
1339
                size   = &video_size;
1340
                break;
1341
            default:
1342
                stop_encoding = 1;
1343
            }
1344
 
1345
            if (encode) {
1346
                AVPacket pkt;
1347
                int got_packet;
1348
                av_init_packet(&pkt);
1349
                pkt.data = NULL;
1350
                pkt.size = 0;
1351
 
1352
                update_benchmark(NULL);
1353
                ret = encode(enc, &pkt, NULL, &got_packet);
1354
                update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
1355
                if (ret < 0) {
1356
                    av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1357
                    exit_program(1);
1358
                }
1359
                *size += pkt.size;
1360
                if (ost->logfile && enc->stats_out) {
1361
                    fprintf(ost->logfile, "%s", enc->stats_out);
1362
                }
1363
                if (!got_packet) {
1364
                    stop_encoding = 1;
1365
                    break;
1366
                }
1367
                if (pkt.pts != AV_NOPTS_VALUE)
1368
                    pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1369
                if (pkt.dts != AV_NOPTS_VALUE)
1370
                    pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1371
                if (pkt.duration > 0)
1372
                    pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1373
                write_frame(os, &pkt, ost);
1374
                if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
1375
                    do_video_stats(ost, pkt.size);
1376
                }
1377
            }
1378
 
1379
            if (stop_encoding)
1380
                break;
1381
        }
1382
    }
1383
}
1384
 
1385
/*
1386
 * Check whether a packet from ist should be written into ost at this time
1387
 */
1388
static int check_output_constraints(InputStream *ist, OutputStream *ost)
1389
{
1390
    OutputFile *of = output_files[ost->file_index];
1391
    int ist_index  = input_files[ist->file_index]->ist_index + ist->st->index;
1392
 
1393
    if (ost->source_index != ist_index)
1394
        return 0;
1395
 
1396
    if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
1397
        return 0;
1398
 
1399
    return 1;
1400
}
1401
 
1402
static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1403
{
1404
    OutputFile *of = output_files[ost->file_index];
1405
    InputFile   *f = input_files [ist->file_index];
1406
    int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1407
    int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
1408
    int64_t ist_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ist->st->time_base);
1409
    AVPicture pict;
1410
    AVPacket opkt;
1411
 
1412
    av_init_packet(&opkt);
1413
 
1414
    if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1415
        !ost->copy_initial_nonkeyframes)
1416
        return;
1417
 
1418
    if (pkt->pts == AV_NOPTS_VALUE) {
1419
        if (!ost->frame_number && ist->pts < start_time &&
1420
            !ost->copy_prior_start)
1421
            return;
1422
    } else {
1423
        if (!ost->frame_number && pkt->pts < ist_tb_start_time &&
1424
            !ost->copy_prior_start)
1425
            return;
1426
    }
1427
 
1428
    if (of->recording_time != INT64_MAX &&
1429
        ist->pts >= of->recording_time + start_time) {
1430
        close_output_stream(ost);
1431
        return;
1432
    }
1433
 
1434
    if (f->recording_time != INT64_MAX) {
1435
        start_time = f->ctx->start_time;
1436
        if (f->start_time != AV_NOPTS_VALUE)
1437
            start_time += f->start_time;
1438
        if (ist->pts >= f->recording_time + start_time) {
1439
            close_output_stream(ost);
1440
            return;
1441
        }
1442
    }
1443
 
1444
    /* force the input stream PTS */
1445
    if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1446
        audio_size += pkt->size;
1447
    else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1448
        video_size += pkt->size;
1449
        ost->sync_opts++;
1450
    } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1451
        subtitle_size += pkt->size;
1452
    }
1453
 
1454
    if (pkt->pts != AV_NOPTS_VALUE)
1455
        opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1456
    else
1457
        opkt.pts = AV_NOPTS_VALUE;
1458
 
1459
    if (pkt->dts == AV_NOPTS_VALUE)
1460
        opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
1461
    else
1462
        opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1463
    opkt.dts -= ost_tb_start_time;
1464
 
1465
    if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
1466
        int duration = av_get_audio_frame_duration(ist->st->codec, pkt->size);
1467
        if(!duration)
1468
            duration = ist->st->codec->frame_size;
1469
        opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
1470
                                               (AVRational){1, ist->st->codec->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
1471
                                               ost->st->time_base) - ost_tb_start_time;
1472
    }
1473
 
1474
    opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1475
    opkt.flags    = pkt->flags;
1476
 
1477
    // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1478
    if (  ost->st->codec->codec_id != AV_CODEC_ID_H264
1479
       && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
1480
       && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
1481
       && ost->st->codec->codec_id != AV_CODEC_ID_VC1
1482
       ) {
1483
        if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY)) {
1484
            opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
1485
            if (!opkt.buf)
1486
                exit_program(1);
1487
        }
1488
    } else {
1489
        opkt.data = pkt->data;
1490
        opkt.size = pkt->size;
1491
    }
1492
 
1493
    if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
1494
        /* store AVPicture in AVPacket, as expected by the output format */
1495
        avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1496
        opkt.data = (uint8_t *)&pict;
1497
        opkt.size = sizeof(AVPicture);
1498
        opkt.flags |= AV_PKT_FLAG_KEY;
1499
    }
1500
 
1501
    write_frame(of->ctx, &opkt, ost);
1502
    ost->st->codec->frame_number++;
1503
}
1504
 
1505
int guess_input_channel_layout(InputStream *ist)
1506
{
1507
    AVCodecContext *dec = ist->st->codec;
1508
 
1509
    if (!dec->channel_layout) {
1510
        char layout_name[256];
1511
 
1512
        if (dec->channels > ist->guess_layout_max)
1513
            return 0;
1514
        dec->channel_layout = av_get_default_channel_layout(dec->channels);
1515
        if (!dec->channel_layout)
1516
            return 0;
1517
        av_get_channel_layout_string(layout_name, sizeof(layout_name),
1518
                                     dec->channels, dec->channel_layout);
1519
        av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for  Input Stream "
1520
               "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1521
    }
1522
    return 1;
1523
}
1524
 
1525
static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1526
{
1527
    AVFrame *decoded_frame, *f;
1528
    AVCodecContext *avctx = ist->st->codec;
1529
    int i, ret, err = 0, resample_changed;
1530
    AVRational decoded_frame_tb;
1531
 
1532
    if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1533
        return AVERROR(ENOMEM);
1534
    if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1535
        return AVERROR(ENOMEM);
1536
    decoded_frame = ist->decoded_frame;
1537
 
1538
    update_benchmark(NULL);
1539
    ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1540
    update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
1541
 
1542
    if (ret >= 0 && avctx->sample_rate <= 0) {
1543
        av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
1544
        ret = AVERROR_INVALIDDATA;
1545
    }
1546
 
1547
    if (*got_output || ret<0 || pkt->size)
1548
        decode_error_stat[ret<0] ++;
1549
 
1550
    if (!*got_output || ret < 0) {
1551
        if (!pkt->size) {
1552
            for (i = 0; i < ist->nb_filters; i++)
1553
#if 1
1554
                av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
1555
#else
1556
                av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
1557
#endif
1558
        }
1559
        return ret;
1560
    }
1561
 
1562
#if 1
1563
    /* increment next_dts to use for the case where the input stream does not
1564
       have timestamps or there are multiple frames in the packet */
1565
    ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1566
                     avctx->sample_rate;
1567
    ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1568
                     avctx->sample_rate;
1569
#endif
1570
 
1571
    resample_changed = ist->resample_sample_fmt     != decoded_frame->format         ||
1572
                       ist->resample_channels       != avctx->channels               ||
1573
                       ist->resample_channel_layout != decoded_frame->channel_layout ||
1574
                       ist->resample_sample_rate    != decoded_frame->sample_rate;
1575
    if (resample_changed) {
1576
        char layout1[64], layout2[64];
1577
 
1578
        if (!guess_input_channel_layout(ist)) {
1579
            av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1580
                   "layout for Input Stream #%d.%d\n", ist->file_index,
1581
                   ist->st->index);
1582
            exit_program(1);
1583
        }
1584
        decoded_frame->channel_layout = avctx->channel_layout;
1585
 
1586
        av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1587
                                     ist->resample_channel_layout);
1588
        av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1589
                                     decoded_frame->channel_layout);
1590
 
1591
        av_log(NULL, AV_LOG_INFO,
1592
               "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
1593
               ist->file_index, ist->st->index,
1594
               ist->resample_sample_rate,  av_get_sample_fmt_name(ist->resample_sample_fmt),
1595
               ist->resample_channels, layout1,
1596
               decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1597
               avctx->channels, layout2);
1598
 
1599
        ist->resample_sample_fmt     = decoded_frame->format;
1600
        ist->resample_sample_rate    = decoded_frame->sample_rate;
1601
        ist->resample_channel_layout = decoded_frame->channel_layout;
1602
        ist->resample_channels       = avctx->channels;
1603
 
1604
        for (i = 0; i < nb_filtergraphs; i++)
1605
            if (ist_in_filtergraph(filtergraphs[i], ist)) {
1606
                FilterGraph *fg = filtergraphs[i];
1607
                int j;
1608
                if (configure_filtergraph(fg) < 0) {
1609
                    av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1610
                    exit_program(1);
1611
                }
1612
                for (j = 0; j < fg->nb_outputs; j++) {
1613
                    OutputStream *ost = fg->outputs[j]->ost;
1614
                    if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1615
                        !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
1616
                        av_buffersink_set_frame_size(ost->filter->filter,
1617
                                                     ost->st->codec->frame_size);
1618
                }
1619
            }
1620
    }
1621
 
1622
    /* if the decoder provides a pts, use it instead of the last packet pts.
1623
       the decoder could be delaying output by a packet or more. */
1624
    if (decoded_frame->pts != AV_NOPTS_VALUE) {
1625
        ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
1626
        decoded_frame_tb   = avctx->time_base;
1627
    } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
1628
        decoded_frame->pts = decoded_frame->pkt_pts;
1629
        pkt->pts           = AV_NOPTS_VALUE;
1630
        decoded_frame_tb   = ist->st->time_base;
1631
    } else if (pkt->pts != AV_NOPTS_VALUE) {
1632
        decoded_frame->pts = pkt->pts;
1633
        pkt->pts           = AV_NOPTS_VALUE;
1634
        decoded_frame_tb   = ist->st->time_base;
1635
    }else {
1636
        decoded_frame->pts = ist->dts;
1637
        decoded_frame_tb   = AV_TIME_BASE_Q;
1638
    }
1639
    if (decoded_frame->pts != AV_NOPTS_VALUE)
1640
        decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
1641
                                              (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
1642
                                              (AVRational){1, ist->st->codec->sample_rate});
1643
    for (i = 0; i < ist->nb_filters; i++) {
1644
        if (i < ist->nb_filters - 1) {
1645
            f = ist->filter_frame;
1646
            err = av_frame_ref(f, decoded_frame);
1647
            if (err < 0)
1648
                break;
1649
        } else
1650
            f = decoded_frame;
1651
        err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
1652
                                     AV_BUFFERSRC_FLAG_PUSH);
1653
        if (err == AVERROR_EOF)
1654
            err = 0; /* ignore */
1655
        if (err < 0)
1656
            break;
1657
    }
1658
    decoded_frame->pts = AV_NOPTS_VALUE;
1659
 
1660
    av_frame_unref(ist->filter_frame);
1661
    av_frame_unref(decoded_frame);
1662
    return err < 0 ? err : ret;
1663
}
1664
 
1665
static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
1666
{
1667
    AVFrame *decoded_frame, *f;
1668
    void *buffer_to_free = NULL;
1669
    int i, ret = 0, err = 0, resample_changed;
1670
    int64_t best_effort_timestamp;
1671
    AVRational *frame_sample_aspect;
1672
 
1673
    if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1674
        return AVERROR(ENOMEM);
1675
    if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1676
        return AVERROR(ENOMEM);
1677
    decoded_frame = ist->decoded_frame;
1678
    pkt->dts  = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
1679
 
1680
    update_benchmark(NULL);
1681
    ret = avcodec_decode_video2(ist->st->codec,
1682
                                decoded_frame, got_output, pkt);
1683
    update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
1684
 
1685
    if (*got_output || ret<0 || pkt->size)
1686
        decode_error_stat[ret<0] ++;
1687
 
1688
    if (!*got_output || ret < 0) {
1689
        if (!pkt->size) {
1690
            for (i = 0; i < ist->nb_filters; i++)
1691
#if 1
1692
                av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
1693
#else
1694
                av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
1695
#endif
1696
        }
1697
        return ret;
1698
    }
1699
 
1700
    if(ist->top_field_first>=0)
1701
        decoded_frame->top_field_first = ist->top_field_first;
1702
 
1703
    best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
1704
    if(best_effort_timestamp != AV_NOPTS_VALUE)
1705
        ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
1706
 
1707
    if (debug_ts) {
1708
        av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
1709
                "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
1710
                ist->st->index, av_ts2str(decoded_frame->pts),
1711
                av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
1712
                best_effort_timestamp,
1713
                av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
1714
                decoded_frame->key_frame, decoded_frame->pict_type);
1715
    }
1716
 
1717
    pkt->size = 0;
1718
 
1719
    if (ist->st->sample_aspect_ratio.num)
1720
        decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1721
 
1722
    resample_changed = ist->resample_width   != decoded_frame->width  ||
1723
                       ist->resample_height  != decoded_frame->height ||
1724
                       ist->resample_pix_fmt != decoded_frame->format;
1725
    if (resample_changed) {
1726
        av_log(NULL, AV_LOG_INFO,
1727
               "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1728
               ist->file_index, ist->st->index,
1729
               ist->resample_width,  ist->resample_height,  av_get_pix_fmt_name(ist->resample_pix_fmt),
1730
               decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
1731
 
1732
        ist->resample_width   = decoded_frame->width;
1733
        ist->resample_height  = decoded_frame->height;
1734
        ist->resample_pix_fmt = decoded_frame->format;
1735
 
1736
        for (i = 0; i < nb_filtergraphs; i++) {
1737
            if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
1738
                configure_filtergraph(filtergraphs[i]) < 0) {
1739
                av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1740
                exit_program(1);
1741
            }
1742
        }
1743
    }
1744
 
1745
    frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
1746
    for (i = 0; i < ist->nb_filters; i++) {
1747
        if (!frame_sample_aspect->num)
1748
            *frame_sample_aspect = ist->st->sample_aspect_ratio;
1749
 
1750
        if (i < ist->nb_filters - 1) {
1751
            f = ist->filter_frame;
1752
            err = av_frame_ref(f, decoded_frame);
1753
            if (err < 0)
1754
                break;
1755
        } else
1756
            f = decoded_frame;
1757
        ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f, AV_BUFFERSRC_FLAG_PUSH);
1758
        if (ret == AVERROR_EOF) {
1759
            ret = 0; /* ignore */
1760
        } else if (ret < 0) {
1761
            av_log(NULL, AV_LOG_FATAL,
1762
                   "Failed to inject frame into filter network: %s\n", av_err2str(ret));
1763
            exit_program(1);
1764
        }
1765
    }
1766
 
1767
    av_frame_unref(ist->filter_frame);
1768
    av_frame_unref(decoded_frame);
1769
    av_free(buffer_to_free);
1770
    return err < 0 ? err : ret;
1771
}
1772
 
1773
static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1774
{
1775
    AVSubtitle subtitle;
1776
    int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1777
                                          &subtitle, got_output, pkt);
1778
 
1779
    if (*got_output || ret<0 || pkt->size)
1780
        decode_error_stat[ret<0] ++;
1781
 
1782
    if (ret < 0 || !*got_output) {
1783
        if (!pkt->size)
1784
            sub2video_flush(ist);
1785
        return ret;
1786
    }
1787
 
1788
    if (ist->fix_sub_duration) {
1789
        if (ist->prev_sub.got_output) {
1790
            int end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
1791
                                 1000, AV_TIME_BASE);
1792
            if (end < ist->prev_sub.subtitle.end_display_time) {
1793
                av_log(ist->st->codec, AV_LOG_DEBUG,
1794
                       "Subtitle duration reduced from %d to %d\n",
1795
                       ist->prev_sub.subtitle.end_display_time, end);
1796
                ist->prev_sub.subtitle.end_display_time = end;
1797
            }
1798
        }
1799
        FFSWAP(int,        *got_output, ist->prev_sub.got_output);
1800
        FFSWAP(int,        ret,         ist->prev_sub.ret);
1801
        FFSWAP(AVSubtitle, subtitle,    ist->prev_sub.subtitle);
1802
    }
1803
 
1804
    sub2video_update(ist, &subtitle);
1805
 
1806
    if (!*got_output || !subtitle.num_rects)
1807
        return ret;
1808
 
1809
    for (i = 0; i < nb_output_streams; i++) {
1810
        OutputStream *ost = output_streams[i];
1811
 
1812
        if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1813
            continue;
1814
 
1815
        do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
1816
    }
1817
 
1818
    avsubtitle_free(&subtitle);
1819
    return ret;
1820
}
1821
 
1822
/* pkt = NULL means EOF (needed to flush decoder buffers) */
1823
static int output_packet(InputStream *ist, const AVPacket *pkt)
1824
{
1825
    int ret = 0, i;
1826
    int got_output = 0;
1827
 
1828
    AVPacket avpkt;
1829
    if (!ist->saw_first_ts) {
1830
        ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
1831
        ist->pts = 0;
1832
        if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
1833
            ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1834
            ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
1835
        }
1836
        ist->saw_first_ts = 1;
1837
    }
1838
 
1839
    if (ist->next_dts == AV_NOPTS_VALUE)
1840
        ist->next_dts = ist->dts;
1841
    if (ist->next_pts == AV_NOPTS_VALUE)
1842
        ist->next_pts = ist->pts;
1843
 
1844
    if (pkt == NULL) {
1845
        /* EOF handling */
1846
        av_init_packet(&avpkt);
1847
        avpkt.data = NULL;
1848
        avpkt.size = 0;
1849
        goto handle_eof;
1850
    } else {
1851
        avpkt = *pkt;
1852
    }
1853
 
1854
    if (pkt->dts != AV_NOPTS_VALUE) {
1855
        ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1856
        if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
1857
            ist->next_pts = ist->pts = ist->dts;
1858
    }
1859
 
1860
    // while we have more to decode or while the decoder did output something on EOF
1861
    while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1862
        int duration;
1863
    handle_eof:
1864
 
1865
        ist->pts = ist->next_pts;
1866
        ist->dts = ist->next_dts;
1867
 
1868
        if (avpkt.size && avpkt.size != pkt->size) {
1869
            av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
1870
                   "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1871
            ist->showed_multi_packet_warning = 1;
1872
        }
1873
 
1874
        switch (ist->st->codec->codec_type) {
1875
        case AVMEDIA_TYPE_AUDIO:
1876
            ret = decode_audio    (ist, &avpkt, &got_output);
1877
            break;
1878
        case AVMEDIA_TYPE_VIDEO:
1879
            ret = decode_video    (ist, &avpkt, &got_output);
1880
            if (avpkt.duration) {
1881
                duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
1882
            } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
1883
                int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1884
                duration = ((int64_t)AV_TIME_BASE *
1885
                                ist->st->codec->time_base.num * ticks) /
1886
                                ist->st->codec->time_base.den;
1887
            } else
1888
                duration = 0;
1889
 
1890
            if(ist->dts != AV_NOPTS_VALUE && duration) {
1891
                ist->next_dts += duration;
1892
            }else
1893
                ist->next_dts = AV_NOPTS_VALUE;
1894
 
1895
            if (got_output)
1896
                ist->next_pts += duration; //FIXME the duration is not correct in some cases
1897
            break;
1898
        case AVMEDIA_TYPE_SUBTITLE:
1899
            ret = transcode_subtitles(ist, &avpkt, &got_output);
1900
            break;
1901
        default:
1902
            return -1;
1903
        }
1904
 
1905
        if (ret < 0)
1906
            return ret;
1907
 
1908
        avpkt.dts=
1909
        avpkt.pts= AV_NOPTS_VALUE;
1910
 
1911
        // touch data and size only if not EOF
1912
        if (pkt) {
1913
            if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
1914
                ret = avpkt.size;
1915
            avpkt.data += ret;
1916
            avpkt.size -= ret;
1917
        }
1918
        if (!got_output) {
1919
            continue;
1920
        }
1921
    }
1922
 
1923
    /* handle stream copy */
1924
    if (!ist->decoding_needed) {
1925
        ist->dts = ist->next_dts;
1926
        switch (ist->st->codec->codec_type) {
1927
        case AVMEDIA_TYPE_AUDIO:
1928
            ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1929
                             ist->st->codec->sample_rate;
1930
            break;
1931
        case AVMEDIA_TYPE_VIDEO:
1932
            if (ist->framerate.num) {
1933
                // TODO: Remove work-around for c99-to-c89 issue 7
1934
                AVRational time_base_q = AV_TIME_BASE_Q;
1935
                int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
1936
                ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
1937
            } else if (pkt->duration) {
1938
                ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1939
            } else if(ist->st->codec->time_base.num != 0) {
1940
                int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
1941
                ist->next_dts += ((int64_t)AV_TIME_BASE *
1942
                                  ist->st->codec->time_base.num * ticks) /
1943
                                  ist->st->codec->time_base.den;
1944
            }
1945
            break;
1946
        }
1947
        ist->pts = ist->dts;
1948
        ist->next_pts = ist->next_dts;
1949
    }
1950
    for (i = 0; pkt && i < nb_output_streams; i++) {
1951
        OutputStream *ost = output_streams[i];
1952
 
1953
        if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1954
            continue;
1955
 
1956
        do_streamcopy(ist, ost, pkt);
1957
    }
1958
 
1959
    return 0;
1960
}
1961
 
1962
static void print_sdp(void)
1963
{
1964
    char sdp[16384];
1965
    int i;
1966
    AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
1967
 
1968
    if (!avc)
1969
        exit_program(1);
1970
    for (i = 0; i < nb_output_files; i++)
1971
        avc[i] = output_files[i]->ctx;
1972
 
1973
    av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
1974
    printf("SDP:\n%s\n", sdp);
1975
    fflush(stdout);
1976
    av_freep(&avc);
1977
}
1978
 
1979
static int init_input_stream(int ist_index, char *error, int error_len)
1980
{
1981
    int ret;
1982
    InputStream *ist = input_streams[ist_index];
1983
 
1984
    if (ist->decoding_needed) {
1985
        AVCodec *codec = ist->dec;
1986
        if (!codec) {
1987
            snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
1988
                    avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
1989
            return AVERROR(EINVAL);
1990
        }
1991
 
1992
        av_opt_set_int(ist->st->codec, "refcounted_frames", 1, 0);
1993
 
1994
        if (!av_dict_get(ist->opts, "threads", NULL, 0))
1995
            av_dict_set(&ist->opts, "threads", "auto", 0);
1996
        if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
1997
            char errbuf[128];
1998
            if (ret == AVERROR_EXPERIMENTAL)
1999
                abort_codec_experimental(codec, 0);
2000
 
2001
            av_strerror(ret, errbuf, sizeof(errbuf));
2002
 
2003
            snprintf(error, error_len,
2004
                     "Error while opening decoder for input stream "
2005
                     "#%d:%d : %s",
2006
                     ist->file_index, ist->st->index, errbuf);
2007
            return ret;
2008
        }
2009
        assert_avoptions(ist->opts);
2010
    }
2011
 
2012
    ist->next_pts = AV_NOPTS_VALUE;
2013
    ist->next_dts = AV_NOPTS_VALUE;
2014
    ist->is_start = 1;
2015
 
2016
    return 0;
2017
}
2018
 
2019
static InputStream *get_input_stream(OutputStream *ost)
2020
{
2021
    if (ost->source_index >= 0)
2022
        return input_streams[ost->source_index];
2023
    return NULL;
2024
}
2025
 
2026
static int compare_int64(const void *a, const void *b)
2027
{
2028
    int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
2029
    return va < vb ? -1 : va > vb ? +1 : 0;
2030
}
2031
 
2032
static void parse_forced_key_frames(char *kf, OutputStream *ost,
2033
                                    AVCodecContext *avctx)
2034
{
2035
    char *p;
2036
    int n = 1, i, size, index = 0;
2037
    int64_t t, *pts;
2038
 
2039
    for (p = kf; *p; p++)
2040
        if (*p == ',')
2041
            n++;
2042
    size = n;
2043
    pts = av_malloc(sizeof(*pts) * size);
2044
    if (!pts) {
2045
        av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
2046
        exit_program(1);
2047
    }
2048
 
2049
    p = kf;
2050
    for (i = 0; i < n; i++) {
2051
        char *next = strchr(p, ',');
2052
 
2053
        if (next)
2054
            *next++ = 0;
2055
 
2056
        if (!memcmp(p, "chapters", 8)) {
2057
 
2058
            AVFormatContext *avf = output_files[ost->file_index]->ctx;
2059
            int j;
2060
 
2061
            if (avf->nb_chapters > INT_MAX - size ||
2062
                !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
2063
                                     sizeof(*pts)))) {
2064
                av_log(NULL, AV_LOG_FATAL,
2065
                       "Could not allocate forced key frames array.\n");
2066
                exit_program(1);
2067
            }
2068
            t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
2069
            t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2070
 
2071
            for (j = 0; j < avf->nb_chapters; j++) {
2072
                AVChapter *c = avf->chapters[j];
2073
                av_assert1(index < size);
2074
                pts[index++] = av_rescale_q(c->start, c->time_base,
2075
                                            avctx->time_base) + t;
2076
            }
2077
 
2078
        } else {
2079
 
2080
            t = parse_time_or_die("force_key_frames", p, 1);
2081
            av_assert1(index < size);
2082
            pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2083
 
2084
        }
2085
 
2086
        p = next;
2087
    }
2088
 
2089
    av_assert0(index == size);
2090
    qsort(pts, size, sizeof(*pts), compare_int64);
2091
    ost->forced_kf_count = size;
2092
    ost->forced_kf_pts   = pts;
2093
}
2094
 
2095
static void report_new_stream(int input_index, AVPacket *pkt)
2096
{
2097
    InputFile *file = input_files[input_index];
2098
    AVStream *st = file->ctx->streams[pkt->stream_index];
2099
 
2100
    if (pkt->stream_index < file->nb_streams_warn)
2101
        return;
2102
    av_log(file->ctx, AV_LOG_WARNING,
2103
           "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
2104
           av_get_media_type_string(st->codec->codec_type),
2105
           input_index, pkt->stream_index,
2106
           pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
2107
    file->nb_streams_warn = pkt->stream_index + 1;
2108
}
2109
 
2110
static int transcode_init(void)
2111
{
2112
    int ret = 0, i, j, k;
2113
    AVFormatContext *oc;
2114
    AVCodecContext *codec;
2115
    OutputStream *ost;
2116
    InputStream *ist;
2117
    char error[1024];
2118
    int want_sdp = 1;
2119
 
2120
    for (i = 0; i < nb_filtergraphs; i++) {
2121
        FilterGraph *fg = filtergraphs[i];
2122
        for (j = 0; j < fg->nb_outputs; j++) {
2123
            OutputFilter *ofilter = fg->outputs[j];
2124
            if (!ofilter->ost || ofilter->ost->source_index >= 0)
2125
                continue;
2126
            if (fg->nb_inputs != 1)
2127
                continue;
2128
            for (k = nb_input_streams-1; k >= 0 ; k--)
2129
                if (fg->inputs[0]->ist == input_streams[k])
2130
                    break;
2131
            ofilter->ost->source_index = k;
2132
        }
2133
    }
2134
 
2135
    /* init framerate emulation */
2136
    for (i = 0; i < nb_input_files; i++) {
2137
        InputFile *ifile = input_files[i];
2138
        if (ifile->rate_emu)
2139
            for (j = 0; j < ifile->nb_streams; j++)
2140
                input_streams[j + ifile->ist_index]->start = av_gettime();
2141
    }
2142
 
2143
    /* output stream init */
2144
    for (i = 0; i < nb_output_files; i++) {
2145
        oc = output_files[i]->ctx;
2146
        if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2147
            av_dump_format(oc, i, oc->filename, 1);
2148
            av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2149
            return AVERROR(EINVAL);
2150
        }
2151
    }
2152
 
2153
    /* init complex filtergraphs */
2154
    for (i = 0; i < nb_filtergraphs; i++)
2155
        if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2156
            return ret;
2157
 
2158
    /* for each output stream, we compute the right encoding parameters */
2159
    for (i = 0; i < nb_output_streams; i++) {
2160
        AVCodecContext *icodec = NULL;
2161
        ost = output_streams[i];
2162
        oc  = output_files[ost->file_index]->ctx;
2163
        ist = get_input_stream(ost);
2164
 
2165
        if (ost->attachment_filename)
2166
            continue;
2167
 
2168
        codec  = ost->st->codec;
2169
 
2170
        if (ist) {
2171
            icodec = ist->st->codec;
2172
 
2173
            ost->st->disposition          = ist->st->disposition;
2174
            codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;
2175
            codec->chroma_sample_location = icodec->chroma_sample_location;
2176
        } else {
2177
            for (j=0; jnb_streams; j++) {
2178
                AVStream *st = oc->streams[j];
2179
                if (st != ost->st && st->codec->codec_type == codec->codec_type)
2180
                    break;
2181
            }
2182
            if (j == oc->nb_streams)
2183
                if (codec->codec_type == AVMEDIA_TYPE_AUDIO || codec->codec_type == AVMEDIA_TYPE_VIDEO)
2184
                    ost->st->disposition = AV_DISPOSITION_DEFAULT;
2185
        }
2186
 
2187
        if (ost->stream_copy) {
2188
            AVRational sar;
2189
            uint64_t extra_size;
2190
 
2191
            av_assert0(ist && !ost->filter);
2192
 
2193
            extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2194
 
2195
            if (extra_size > INT_MAX) {
2196
                return AVERROR(EINVAL);
2197
            }
2198
 
2199
            /* if stream_copy is selected, no need to decode or encode */
2200
            codec->codec_id   = icodec->codec_id;
2201
            codec->codec_type = icodec->codec_type;
2202
 
2203
            if (!codec->codec_tag) {
2204
                unsigned int codec_tag;
2205
                if (!oc->oformat->codec_tag ||
2206
                     av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2207
                     !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
2208
                    codec->codec_tag = icodec->codec_tag;
2209
            }
2210
 
2211
            codec->bit_rate       = icodec->bit_rate;
2212
            codec->rc_max_rate    = icodec->rc_max_rate;
2213
            codec->rc_buffer_size = icodec->rc_buffer_size;
2214
            codec->field_order    = icodec->field_order;
2215
            codec->extradata      = av_mallocz(extra_size);
2216
            if (!codec->extradata) {
2217
                return AVERROR(ENOMEM);
2218
            }
2219
            memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2220
            codec->extradata_size= icodec->extradata_size;
2221
            codec->bits_per_coded_sample  = icodec->bits_per_coded_sample;
2222
 
2223
            codec->time_base = ist->st->time_base;
2224
            /*
2225
             * Avi is a special case here because it supports variable fps but
2226
             * having the fps and timebase differe significantly adds quite some
2227
             * overhead
2228
             */
2229
            if(!strcmp(oc->oformat->name, "avi")) {
2230
                if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
2231
                               && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
2232
                               && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
2233
                               && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
2234
                     || copy_tb==2){
2235
                    codec->time_base.num = ist->st->r_frame_rate.den;
2236
                    codec->time_base.den = 2*ist->st->r_frame_rate.num;
2237
                    codec->ticks_per_frame = 2;
2238
                } else if (   copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2239
                                 && av_q2d(ist->st->time_base) < 1.0/500
2240
                    || copy_tb==0){
2241
                    codec->time_base = icodec->time_base;
2242
                    codec->time_base.num *= icodec->ticks_per_frame;
2243
                    codec->time_base.den *= 2;
2244
                    codec->ticks_per_frame = 2;
2245
                }
2246
            } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2247
                      && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2248
                      && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2249
                      && strcmp(oc->oformat->name, "f4v")
2250
            ) {
2251
                if(   copy_tb<0 && icodec->time_base.den
2252
                                && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
2253
                                && av_q2d(ist->st->time_base) < 1.0/500
2254
                   || copy_tb==0){
2255
                    codec->time_base = icodec->time_base;
2256
                    codec->time_base.num *= icodec->ticks_per_frame;
2257
                }
2258
            }
2259
            if (   codec->codec_tag == AV_RL32("tmcd")
2260
                && icodec->time_base.num < icodec->time_base.den
2261
                && icodec->time_base.num > 0
2262
                && 121LL*icodec->time_base.num > icodec->time_base.den) {
2263
                codec->time_base = icodec->time_base;
2264
            }
2265
 
2266
            if (ist && !ost->frame_rate.num)
2267
                ost->frame_rate = ist->framerate;
2268
            if(ost->frame_rate.num)
2269
                codec->time_base = av_inv_q(ost->frame_rate);
2270
 
2271
            av_reduce(&codec->time_base.num, &codec->time_base.den,
2272
                        codec->time_base.num, codec->time_base.den, INT_MAX);
2273
 
2274
            switch (codec->codec_type) {
2275
            case AVMEDIA_TYPE_AUDIO:
2276
                if (audio_volume != 256) {
2277
                    av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2278
                    exit_program(1);
2279
                }
2280
                codec->channel_layout     = icodec->channel_layout;
2281
                codec->sample_rate        = icodec->sample_rate;
2282
                codec->channels           = icodec->channels;
2283
                codec->frame_size         = icodec->frame_size;
2284
                codec->audio_service_type = icodec->audio_service_type;
2285
                codec->block_align        = icodec->block_align;
2286
                if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
2287
                    codec->block_align= 0;
2288
                if(codec->codec_id == AV_CODEC_ID_AC3)
2289
                    codec->block_align= 0;
2290
                break;
2291
            case AVMEDIA_TYPE_VIDEO:
2292
                codec->pix_fmt            = icodec->pix_fmt;
2293
                codec->width              = icodec->width;
2294
                codec->height             = icodec->height;
2295
                codec->has_b_frames       = icodec->has_b_frames;
2296
                if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
2297
                    sar =
2298
                        av_mul_q(ost->frame_aspect_ratio,
2299
                                 (AVRational){ codec->height, codec->width });
2300
                    av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
2301
                           "with stream copy may produce invalid files\n");
2302
                }
2303
                else if (ist->st->sample_aspect_ratio.num)
2304
                    sar = ist->st->sample_aspect_ratio;
2305
                else
2306
                    sar = icodec->sample_aspect_ratio;
2307
                ost->st->sample_aspect_ratio = codec->sample_aspect_ratio = sar;
2308
                ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2309
                break;
2310
            case AVMEDIA_TYPE_SUBTITLE:
2311
                codec->width  = icodec->width;
2312
                codec->height = icodec->height;
2313
                break;
2314
            case AVMEDIA_TYPE_DATA:
2315
            case AVMEDIA_TYPE_ATTACHMENT:
2316
                break;
2317
            default:
2318
                abort();
2319
            }
2320
        } else {
2321
            if (!ost->enc)
2322
                ost->enc = avcodec_find_encoder(codec->codec_id);
2323
            if (!ost->enc) {
2324
                /* should only happen when a default codec is not present. */
2325
                snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
2326
                         avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
2327
                ret = AVERROR(EINVAL);
2328
                goto dump_format;
2329
            }
2330
 
2331
            if (ist)
2332
                ist->decoding_needed++;
2333
            ost->encoding_needed = 1;
2334
 
2335
            if (!ost->filter &&
2336
                (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2337
                 codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
2338
                    FilterGraph *fg;
2339
                    fg = init_simple_filtergraph(ist, ost);
2340
                    if (configure_filtergraph(fg)) {
2341
                        av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2342
                        exit_program(1);
2343
                    }
2344
            }
2345
 
2346
            if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2347
                if (ost->filter && !ost->frame_rate.num)
2348
                    ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
2349
                if (ist && !ost->frame_rate.num)
2350
                    ost->frame_rate = ist->framerate;
2351
                if (ist && !ost->frame_rate.num)
2352
                    ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
2353
//                    ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
2354
                if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2355
                    int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
2356
                    ost->frame_rate = ost->enc->supported_framerates[idx];
2357
                }
2358
            }
2359
 
2360
            switch (codec->codec_type) {
2361
            case AVMEDIA_TYPE_AUDIO:
2362
                codec->sample_fmt     = ost->filter->filter->inputs[0]->format;
2363
                codec->sample_rate    = ost->filter->filter->inputs[0]->sample_rate;
2364
                codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2365
                codec->channels       = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
2366
                codec->time_base      = (AVRational){ 1, codec->sample_rate };
2367
                break;
2368
            case AVMEDIA_TYPE_VIDEO:
2369
                codec->time_base = av_inv_q(ost->frame_rate);
2370
                if (ost->filter && !(codec->time_base.num && codec->time_base.den))
2371
                    codec->time_base = ost->filter->filter->inputs[0]->time_base;
2372
                if (   av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
2373
                   && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
2374
                    av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
2375
                                               "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
2376
                }
2377
                for (j = 0; j < ost->forced_kf_count; j++)
2378
                    ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
2379
                                                         AV_TIME_BASE_Q,
2380
                                                         codec->time_base);
2381
 
2382
                codec->width  = ost->filter->filter->inputs[0]->w;
2383
                codec->height = ost->filter->filter->inputs[0]->h;
2384
                codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2385
                    ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
2386
                    av_mul_q(ost->frame_aspect_ratio, (AVRational){ codec->height, codec->width }) :
2387
                    ost->filter->filter->inputs[0]->sample_aspect_ratio;
2388
                if (!strncmp(ost->enc->name, "libx264", 7) &&
2389
                    codec->pix_fmt == AV_PIX_FMT_NONE &&
2390
                    ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
2391
                    av_log(NULL, AV_LOG_WARNING,
2392
                           "No pixel format specified, %s for H.264 encoding chosen.\n"
2393
                           "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
2394
                           av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
2395
                if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
2396
                    codec->pix_fmt == AV_PIX_FMT_NONE &&
2397
                    ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
2398
                    av_log(NULL, AV_LOG_WARNING,
2399
                           "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
2400
                           "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
2401
                           av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
2402
                codec->pix_fmt = ost->filter->filter->inputs[0]->format;
2403
 
2404
                if (!icodec ||
2405
                    codec->width   != icodec->width  ||
2406
                    codec->height  != icodec->height ||
2407
                    codec->pix_fmt != icodec->pix_fmt) {
2408
                    codec->bits_per_raw_sample = frame_bits_per_raw_sample;
2409
                }
2410
 
2411
                if (ost->forced_keyframes) {
2412
                    if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
2413
                        ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
2414
                                            forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
2415
                        if (ret < 0) {
2416
                            av_log(NULL, AV_LOG_ERROR,
2417
                                   "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
2418
                            return ret;
2419
                        }
2420
                        ost->forced_keyframes_expr_const_values[FKF_N] = 0;
2421
                        ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
2422
                        ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
2423
                        ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
2424
                    } else {
2425
                        parse_forced_key_frames(ost->forced_keyframes, ost, ost->st->codec);
2426
                    }
2427
                }
2428
                break;
2429
            case AVMEDIA_TYPE_SUBTITLE:
2430
                codec->time_base = (AVRational){1, 1000};
2431
                if (!codec->width) {
2432
                    codec->width     = input_streams[ost->source_index]->st->codec->width;
2433
                    codec->height    = input_streams[ost->source_index]->st->codec->height;
2434
                }
2435
                break;
2436
            default:
2437
                abort();
2438
                break;
2439
            }
2440
            /* two pass mode */
2441
            if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
2442
                char logfilename[1024];
2443
                FILE *f;
2444
 
2445
                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2446
                         ost->logfile_prefix ? ost->logfile_prefix :
2447
                                               DEFAULT_PASS_LOGFILENAME_PREFIX,
2448
                         i);
2449
                if (!strcmp(ost->enc->name, "libx264")) {
2450
                    av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2451
                } else {
2452
                    if (codec->flags & CODEC_FLAG_PASS2) {
2453
                        char  *logbuffer;
2454
                        size_t logbuffer_size;
2455
                        if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2456
                            av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2457
                                   logfilename);
2458
                            exit_program(1);
2459
                        }
2460
                        codec->stats_in = logbuffer;
2461
                    }
2462
                    if (codec->flags & CODEC_FLAG_PASS1) {
2463
                        f = fopen(logfilename, "wb");
2464
                        if (!f) {
2465
                            av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2466
                                logfilename, strerror(errno));
2467
                            exit_program(1);
2468
                        }
2469
                        ost->logfile = f;
2470
                    }
2471
                }
2472
            }
2473
        }
2474
    }
2475
 
2476
    /* open each encoder */
2477
    for (i = 0; i < nb_output_streams; i++) {
2478
        ost = output_streams[i];
2479
        if (ost->encoding_needed) {
2480
            AVCodec      *codec = ost->enc;
2481
            AVCodecContext *dec = NULL;
2482
 
2483
            if ((ist = get_input_stream(ost)))
2484
                dec = ist->st->codec;
2485
            if (dec && dec->subtitle_header) {
2486
                /* ASS code assumes this buffer is null terminated so add extra byte. */
2487
                ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
2488
                if (!ost->st->codec->subtitle_header) {
2489
                    ret = AVERROR(ENOMEM);
2490
                    goto dump_format;
2491
                }
2492
                memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2493
                ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2494
            }
2495
            if (!av_dict_get(ost->opts, "threads", NULL, 0))
2496
                av_dict_set(&ost->opts, "threads", "auto", 0);
2497
            if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
2498
                if (ret == AVERROR_EXPERIMENTAL)
2499
                    abort_codec_experimental(codec, 1);
2500
                snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2501
                        ost->file_index, ost->index);
2502
                goto dump_format;
2503
            }
2504
            if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
2505
                !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
2506
                av_buffersink_set_frame_size(ost->filter->filter,
2507
                                             ost->st->codec->frame_size);
2508
            assert_avoptions(ost->opts);
2509
            if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2510
                av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2511
                                             " It takes bits/s as argument, not kbits/s\n");
2512
            extra_size += ost->st->codec->extradata_size;
2513
 
2514
            if (ost->st->codec->me_threshold)
2515
                input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
2516
        } else {
2517
            av_opt_set_dict(ost->st->codec, &ost->opts);
2518
        }
2519
    }
2520
 
2521
    /* init input streams */
2522
    for (i = 0; i < nb_input_streams; i++)
2523
        if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
2524
            for (i = 0; i < nb_output_streams; i++) {
2525
                ost = output_streams[i];
2526
                avcodec_close(ost->st->codec);
2527
            }
2528
            goto dump_format;
2529
        }
2530
 
2531
    /* discard unused programs */
2532
    for (i = 0; i < nb_input_files; i++) {
2533
        InputFile *ifile = input_files[i];
2534
        for (j = 0; j < ifile->ctx->nb_programs; j++) {
2535
            AVProgram *p = ifile->ctx->programs[j];
2536
            int discard  = AVDISCARD_ALL;
2537
 
2538
            for (k = 0; k < p->nb_stream_indexes; k++)
2539
                if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2540
                    discard = AVDISCARD_DEFAULT;
2541
                    break;
2542
                }
2543
            p->discard = discard;
2544
        }
2545
    }
2546
 
2547
    /* open files and write file headers */
2548
    for (i = 0; i < nb_output_files; i++) {
2549
        oc = output_files[i]->ctx;
2550
        oc->interrupt_callback = int_cb;
2551
        if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
2552
            char errbuf[128];
2553
            av_strerror(ret, errbuf, sizeof(errbuf));
2554
            snprintf(error, sizeof(error),
2555
                     "Could not write header for output file #%d "
2556
                     "(incorrect codec parameters ?): %s",
2557
                     i, errbuf);
2558
            ret = AVERROR(EINVAL);
2559
            goto dump_format;
2560
        }
2561
//         assert_avoptions(output_files[i]->opts);
2562
        if (strcmp(oc->oformat->name, "rtp")) {
2563
            want_sdp = 0;
2564
        }
2565
    }
2566
 
2567
 dump_format:
2568
    /* dump the file output parameters - cannot be done before in case
2569
       of stream copy */
2570
    for (i = 0; i < nb_output_files; i++) {
2571
        av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
2572
    }
2573
 
2574
    /* dump the stream mapping */
2575
    av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2576
    for (i = 0; i < nb_input_streams; i++) {
2577
        ist = input_streams[i];
2578
 
2579
        for (j = 0; j < ist->nb_filters; j++) {
2580
            if (ist->filters[j]->graph->graph_desc) {
2581
                av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",
2582
                       ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2583
                       ist->filters[j]->name);
2584
                if (nb_filtergraphs > 1)
2585
                    av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2586
                av_log(NULL, AV_LOG_INFO, "\n");
2587
            }
2588
        }
2589
    }
2590
 
2591
    for (i = 0; i < nb_output_streams; i++) {
2592
        ost = output_streams[i];
2593
 
2594
        if (ost->attachment_filename) {
2595
            /* an attached file */
2596
            av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",
2597
                   ost->attachment_filename, ost->file_index, ost->index);
2598
            continue;
2599
        }
2600
 
2601
        if (ost->filter && ost->filter->graph->graph_desc) {
2602
            /* output from a complex graph */
2603
            av_log(NULL, AV_LOG_INFO, "  %s", ost->filter->name);
2604
            if (nb_filtergraphs > 1)
2605
                av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2606
 
2607
            av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2608
                   ost->index, ost->enc ? ost->enc->name : "?");
2609
            continue;
2610
        }
2611
 
2612
        av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",
2613
               input_streams[ost->source_index]->file_index,
2614
               input_streams[ost->source_index]->st->index,
2615
               ost->file_index,
2616
               ost->index);
2617
        if (ost->sync_ist != input_streams[ost->source_index])
2618
            av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2619
                   ost->sync_ist->file_index,
2620
                   ost->sync_ist->st->index);
2621
        if (ost->stream_copy)
2622
            av_log(NULL, AV_LOG_INFO, " (copy)");
2623
        else
2624
            av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2625
                   input_streams[ost->source_index]->dec->name : "?",
2626
                   ost->enc ? ost->enc->name : "?");
2627
        av_log(NULL, AV_LOG_INFO, "\n");
2628
    }
2629
 
2630
    if (ret) {
2631
        av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2632
        return ret;
2633
    }
2634
 
2635
    if (want_sdp) {
2636
        print_sdp();
2637
    }
2638
 
2639
    return 0;
2640
}
2641
 
2642
/* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
2643
static int need_output(void)
2644
{
2645
    int i;
2646
 
2647
    for (i = 0; i < nb_output_streams; i++) {
2648
        OutputStream *ost    = output_streams[i];
2649
        OutputFile *of       = output_files[ost->file_index];
2650
        AVFormatContext *os  = output_files[ost->file_index]->ctx;
2651
 
2652
        if (ost->finished ||
2653
            (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2654
            continue;
2655
        if (ost->frame_number >= ost->max_frames) {
2656
            int j;
2657
            for (j = 0; j < of->ctx->nb_streams; j++)
2658
                close_output_stream(output_streams[of->ost_index + j]);
2659
            continue;
2660
        }
2661
 
2662
        return 1;
2663
    }
2664
 
2665
    return 0;
2666
}
2667
 
2668
/**
2669
 * Select the output stream to process.
2670
 *
2671
 * @return  selected output stream, or NULL if none available
2672
 */
2673
static OutputStream *choose_output(void)
2674
{
2675
    int i;
2676
    int64_t opts_min = INT64_MAX;
2677
    OutputStream *ost_min = NULL;
2678
 
2679
    for (i = 0; i < nb_output_streams; i++) {
2680
        OutputStream *ost = output_streams[i];
2681
        int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
2682
                                    AV_TIME_BASE_Q);
2683
        if (!ost->unavailable && !ost->finished && opts < opts_min) {
2684
            opts_min = opts;
2685
            ost_min  = ost;
2686
        }
2687
    }
2688
    return ost_min;
2689
}
2690
 
2691
static int check_keyboard_interaction(int64_t cur_time)
2692
{
2693
    int i, ret, key;
2694
    static int64_t last_time;
2695
    if (received_nb_signals)
2696
        return AVERROR_EXIT;
2697
    /* read_key() returns 0 on EOF */
2698
    if(cur_time - last_time >= 100000 && !run_as_daemon){
2699
        key =  read_key();
2700
        last_time = cur_time;
2701
    }else
2702
        key = -1;
2703
    if (key == 'q')
2704
        return AVERROR_EXIT;
2705
    if (key == '+') av_log_set_level(av_log_get_level()+10);
2706
    if (key == '-') av_log_set_level(av_log_get_level()-10);
2707
    if (key == 's') qp_hist     ^= 1;
2708
    if (key == 'h'){
2709
        if (do_hex_dump){
2710
            do_hex_dump = do_pkt_dump = 0;
2711
        } else if(do_pkt_dump){
2712
            do_hex_dump = 1;
2713
        } else
2714
            do_pkt_dump = 1;
2715
        av_log_set_level(AV_LOG_DEBUG);
2716
    }
2717
    if (key == 'c' || key == 'C'){
2718
        char buf[4096], target[64], command[256], arg[256] = {0};
2719
        double time;
2720
        int k, n = 0;
2721
        fprintf(stderr, "\nEnter command: |all 
2722
        i = 0;
2723
        while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
2724
            if (k > 0)
2725
                buf[i++] = k;
2726
        buf[i] = 0;
2727
        if (k > 0 &&
2728
            (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
2729
            av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
2730
                   target, time, command, arg);
2731
            for (i = 0; i < nb_filtergraphs; i++) {
2732
                FilterGraph *fg = filtergraphs[i];
2733
                if (fg->graph) {
2734
                    if (time < 0) {
2735
                        ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
2736
                                                          key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
2737
                        fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
2738
                    } else if (key == 'c') {
2739
                        fprintf(stderr, "Queing commands only on filters supporting the specific command is unsupported\n");
2740
                        ret = AVERROR_PATCHWELCOME;
2741
                    } else {
2742
                        ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
2743
                    }
2744
                }
2745
            }
2746
        } else {
2747
            av_log(NULL, AV_LOG_ERROR,
2748
                   "Parse error, at least 3 arguments were expected, "
2749
                   "only %d given in string '%s'\n", n, buf);
2750
        }
2751
    }
2752
    if (key == 'd' || key == 'D'){
2753
        int debug=0;
2754
        if(key == 'D') {
2755
            debug = input_streams[0]->st->codec->debug<<1;
2756
            if(!debug) debug = 1;
2757
            while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2758
                debug += debug;
2759
        }else
2760
            if(scanf("%d", &debug)!=1)
2761
                fprintf(stderr,"error parsing debug value\n");
2762
        for(i=0;i
2763
            input_streams[i]->st->codec->debug = debug;
2764
        }
2765
        for(i=0;i
2766
            OutputStream *ost = output_streams[i];
2767
            ost->st->codec->debug = debug;
2768
        }
2769
        if(debug) av_log_set_level(AV_LOG_DEBUG);
2770
        fprintf(stderr,"debug=%d\n", debug);
2771
    }
2772
    if (key == '?'){
2773
        fprintf(stderr, "key    function\n"
2774
                        "?      show this help\n"
2775
                        "+      increase verbosity\n"
2776
                        "-      decrease verbosity\n"
2777
                        "c      Send command to first matching filter supporting it\n"
2778
                        "C      Send/Que command to all matching filters\n"
2779
                        "D      cycle through available debug modes\n"
2780
                        "h      dump packets/hex press to cycle through the 3 states\n"
2781
                        "q      quit\n"
2782
                        "s      Show QP histogram\n"
2783
        );
2784
    }
2785
    return 0;
2786
}
2787
 
2788
#if HAVE_PTHREADS
2789
static void *input_thread(void *arg)
2790
{
2791
    InputFile *f = arg;
2792
    int ret = 0;
2793
 
2794
    while (!transcoding_finished && ret >= 0) {
2795
        AVPacket pkt;
2796
        ret = av_read_frame(f->ctx, &pkt);
2797
 
2798
        if (ret == AVERROR(EAGAIN)) {
2799
            av_usleep(10000);
2800
            ret = 0;
2801
            continue;
2802
        } else if (ret < 0)
2803
            break;
2804
 
2805
        pthread_mutex_lock(&f->fifo_lock);
2806
        while (!av_fifo_space(f->fifo))
2807
            pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2808
 
2809
        av_dup_packet(&pkt);
2810
        av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2811
 
2812
        pthread_mutex_unlock(&f->fifo_lock);
2813
    }
2814
 
2815
    f->finished = 1;
2816
    return NULL;
2817
}
2818
 
2819
static void free_input_threads(void)
2820
{
2821
    int i;
2822
 
2823
    if (nb_input_files == 1)
2824
        return;
2825
 
2826
    transcoding_finished = 1;
2827
 
2828
    for (i = 0; i < nb_input_files; i++) {
2829
        InputFile *f = input_files[i];
2830
        AVPacket pkt;
2831
 
2832
        if (!f->fifo || f->joined)
2833
            continue;
2834
 
2835
        pthread_mutex_lock(&f->fifo_lock);
2836
        while (av_fifo_size(f->fifo)) {
2837
            av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2838
            av_free_packet(&pkt);
2839
        }
2840
        pthread_cond_signal(&f->fifo_cond);
2841
        pthread_mutex_unlock(&f->fifo_lock);
2842
 
2843
        pthread_join(f->thread, NULL);
2844
        f->joined = 1;
2845
 
2846
        while (av_fifo_size(f->fifo)) {
2847
            av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2848
            av_free_packet(&pkt);
2849
        }
2850
        av_fifo_free(f->fifo);
2851
    }
2852
}
2853
 
2854
static int init_input_threads(void)
2855
{
2856
    int i, ret;
2857
 
2858
    if (nb_input_files == 1)
2859
        return 0;
2860
 
2861
    for (i = 0; i < nb_input_files; i++) {
2862
        InputFile *f = input_files[i];
2863
 
2864
        if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2865
            return AVERROR(ENOMEM);
2866
 
2867
        pthread_mutex_init(&f->fifo_lock, NULL);
2868
        pthread_cond_init (&f->fifo_cond, NULL);
2869
 
2870
        if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2871
            return AVERROR(ret);
2872
    }
2873
    return 0;
2874
}
2875
 
2876
static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2877
{
2878
    int ret = 0;
2879
 
2880
    pthread_mutex_lock(&f->fifo_lock);
2881
 
2882
    if (av_fifo_size(f->fifo)) {
2883
        av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2884
        pthread_cond_signal(&f->fifo_cond);
2885
    } else {
2886
        if (f->finished)
2887
            ret = AVERROR_EOF;
2888
        else
2889
            ret = AVERROR(EAGAIN);
2890
    }
2891
 
2892
    pthread_mutex_unlock(&f->fifo_lock);
2893
 
2894
    return ret;
2895
}
2896
#endif
2897
 
2898
static int get_input_packet(InputFile *f, AVPacket *pkt)
2899
{
2900
    if (f->rate_emu) {
2901
        int i;
2902
        for (i = 0; i < f->nb_streams; i++) {
2903
            InputStream *ist = input_streams[f->ist_index + i];
2904
            int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
2905
            int64_t now = av_gettime() - ist->start;
2906
            if (pts > now)
2907
                return AVERROR(EAGAIN);
2908
        }
2909
    }
2910
 
2911
#if HAVE_PTHREADS
2912
    if (nb_input_files > 1)
2913
        return get_input_packet_mt(f, pkt);
2914
#endif
2915
    return av_read_frame(f->ctx, pkt);
2916
}
2917
 
2918
static int got_eagain(void)
2919
{
2920
    int i;
2921
    for (i = 0; i < nb_output_streams; i++)
2922
        if (output_streams[i]->unavailable)
2923
            return 1;
2924
    return 0;
2925
}
2926
 
2927
static void reset_eagain(void)
2928
{
2929
    int i;
2930
    for (i = 0; i < nb_input_files; i++)
2931
        input_files[i]->eagain = 0;
2932
    for (i = 0; i < nb_output_streams; i++)
2933
        output_streams[i]->unavailable = 0;
2934
}
2935
 
2936
/*
2937
 * Return
2938
 * - 0 -- one packet was read and processed
2939
 * - AVERROR(EAGAIN) -- no packets were available for selected file,
2940
 *   this function should be called again
2941
 * - AVERROR_EOF -- this function should not be called again
2942
 */
2943
static int process_input(int file_index)
2944
{
2945
    InputFile *ifile = input_files[file_index];
2946
    AVFormatContext *is;
2947
    InputStream *ist;
2948
    AVPacket pkt;
2949
    int ret, i, j;
2950
 
2951
    is  = ifile->ctx;
2952
    ret = get_input_packet(ifile, &pkt);
2953
 
2954
    if (ret == AVERROR(EAGAIN)) {
2955
        ifile->eagain = 1;
2956
        return ret;
2957
    }
2958
    if (ret < 0) {
2959
        if (ret != AVERROR_EOF) {
2960
            print_error(is->filename, ret);
2961
            if (exit_on_error)
2962
                exit_program(1);
2963
        }
2964
        ifile->eof_reached = 1;
2965
 
2966
        for (i = 0; i < ifile->nb_streams; i++) {
2967
            ist = input_streams[ifile->ist_index + i];
2968
            if (ist->decoding_needed)
2969
                output_packet(ist, NULL);
2970
 
2971
            /* mark all outputs that don't go through lavfi as finished */
2972
            for (j = 0; j < nb_output_streams; j++) {
2973
                OutputStream *ost = output_streams[j];
2974
 
2975
                if (ost->source_index == ifile->ist_index + i &&
2976
                    (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
2977
                    close_output_stream(ost);
2978
            }
2979
        }
2980
 
2981
        return AVERROR(EAGAIN);
2982
    }
2983
 
2984
    reset_eagain();
2985
 
2986
    if (do_pkt_dump) {
2987
        av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2988
                         is->streams[pkt.stream_index]);
2989
    }
2990
    /* the following test is needed in case new streams appear
2991
       dynamically in stream : we ignore them */
2992
    if (pkt.stream_index >= ifile->nb_streams) {
2993
        report_new_stream(file_index, &pkt);
2994
        goto discard_packet;
2995
    }
2996
 
2997
    ist = input_streams[ifile->ist_index + pkt.stream_index];
2998
    if (ist->discard)
2999
        goto discard_packet;
3000
 
3001
    if (debug_ts) {
3002
        av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3003
               "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
3004
               ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
3005
               av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
3006
               av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
3007
               av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3008
               av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3009
               av_ts2str(input_files[ist->file_index]->ts_offset),
3010
               av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3011
    }
3012
 
3013
    if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
3014
        int64_t stime, stime2;
3015
        // Correcting starttime based on the enabled streams
3016
        // FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.
3017
        //       so we instead do it here as part of discontinuity handling
3018
        if (   ist->next_dts == AV_NOPTS_VALUE
3019
            && ifile->ts_offset == -is->start_time
3020
            && (is->iformat->flags & AVFMT_TS_DISCONT)) {
3021
            int64_t new_start_time = INT64_MAX;
3022
            for (i=0; inb_streams; i++) {
3023
                AVStream *st = is->streams[i];
3024
                if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
3025
                    continue;
3026
                new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
3027
            }
3028
            if (new_start_time > is->start_time) {
3029
                av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
3030
                ifile->ts_offset = -new_start_time;
3031
            }
3032
        }
3033
 
3034
        stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
3035
        stime2= stime + (1ULL<st->pts_wrap_bits);
3036
        ist->wrap_correction_done = 1;
3037
 
3038
        if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
3039
            pkt.dts -= 1ULL<st->pts_wrap_bits;
3040
            ist->wrap_correction_done = 0;
3041
        }
3042
        if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
3043
            pkt.pts -= 1ULL<st->pts_wrap_bits;
3044
            ist->wrap_correction_done = 0;
3045
        }
3046
    }
3047
 
3048
    if (pkt.dts != AV_NOPTS_VALUE)
3049
        pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3050
    if (pkt.pts != AV_NOPTS_VALUE)
3051
        pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3052
 
3053
    if (pkt.pts != AV_NOPTS_VALUE)
3054
        pkt.pts *= ist->ts_scale;
3055
    if (pkt.dts != AV_NOPTS_VALUE)
3056
        pkt.dts *= ist->ts_scale;
3057
 
3058
    if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
3059
        && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
3060
        int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3061
        int64_t delta   = pkt_dts - ifile->last_ts;
3062
        if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3063
            (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3064
                ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)){
3065
            ifile->ts_offset -= delta;
3066
            av_log(NULL, AV_LOG_DEBUG,
3067
                   "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3068
                   delta, ifile->ts_offset);
3069
            pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3070
            if (pkt.pts != AV_NOPTS_VALUE)
3071
                pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3072
        }
3073
    }
3074
 
3075
    if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
3076
        !copy_ts) {
3077
        int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3078
        int64_t delta   = pkt_dts - ist->next_dts;
3079
        if (is->iformat->flags & AVFMT_TS_DISCONT) {
3080
        if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3081
            (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3082
                ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
3083
            pkt_dts + AV_TIME_BASE/10 < ist->pts){
3084
            ifile->ts_offset -= delta;
3085
            av_log(NULL, AV_LOG_DEBUG,
3086
                   "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3087
                   delta, ifile->ts_offset);
3088
            pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3089
            if (pkt.pts != AV_NOPTS_VALUE)
3090
                pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3091
        }
3092
        } else {
3093
            if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3094
                (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
3095
               ) {
3096
                av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3097
                pkt.dts = AV_NOPTS_VALUE;
3098
            }
3099
            if (pkt.pts != AV_NOPTS_VALUE){
3100
                int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3101
                delta   = pkt_pts - ist->next_dts;
3102
                if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3103
                    (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
3104
                   ) {
3105
                    av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3106
                    pkt.pts = AV_NOPTS_VALUE;
3107
                }
3108
            }
3109
        }
3110
    }
3111
 
3112
    if (pkt.dts != AV_NOPTS_VALUE)
3113
        ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3114
 
3115
    if (debug_ts) {
3116
        av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
3117
               ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
3118
               av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3119
               av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3120
               av_ts2str(input_files[ist->file_index]->ts_offset),
3121
               av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3122
    }
3123
 
3124
    sub2video_heartbeat(ist, pkt.pts);
3125
 
3126
    ret = output_packet(ist, &pkt);
3127
    if (ret < 0) {
3128
        char buf[128];
3129
        av_strerror(ret, buf, sizeof(buf));
3130
        av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
3131
                ist->file_index, ist->st->index, buf);
3132
        if (exit_on_error)
3133
            exit_program(1);
3134
    }
3135
 
3136
discard_packet:
3137
    av_free_packet(&pkt);
3138
 
3139
    return 0;
3140
}
3141
 
3142
/**
3143
 * Perform a step of transcoding for the specified filter graph.
3144
 *
3145
 * @param[in]  graph     filter graph to consider
3146
 * @param[out] best_ist  input stream where a frame would allow to continue
3147
 * @return  0 for success, <0 for error
3148
 */
3149
static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
3150
{
3151
    int i, ret;
3152
    int nb_requests, nb_requests_max = 0;
3153
    InputFilter *ifilter;
3154
    InputStream *ist;
3155
 
3156
    *best_ist = NULL;
3157
    ret = avfilter_graph_request_oldest(graph->graph);
3158
    if (ret >= 0)
3159
        return reap_filters();
3160
 
3161
    if (ret == AVERROR_EOF) {
3162
        ret = reap_filters();
3163
        for (i = 0; i < graph->nb_outputs; i++)
3164
            close_output_stream(graph->outputs[i]->ost);
3165
        return ret;
3166
    }
3167
    if (ret != AVERROR(EAGAIN))
3168
        return ret;
3169
 
3170
    for (i = 0; i < graph->nb_inputs; i++) {
3171
        ifilter = graph->inputs[i];
3172
        ist = ifilter->ist;
3173
        if (input_files[ist->file_index]->eagain ||
3174
            input_files[ist->file_index]->eof_reached)
3175
            continue;
3176
        nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
3177
        if (nb_requests > nb_requests_max) {
3178
            nb_requests_max = nb_requests;
3179
            *best_ist = ist;
3180
        }
3181
    }
3182
 
3183
    if (!*best_ist)
3184
        for (i = 0; i < graph->nb_outputs; i++)
3185
            graph->outputs[i]->ost->unavailable = 1;
3186
 
3187
    return 0;
3188
}
3189
 
3190
/**
3191
 * Run a single step of transcoding.
3192
 *
3193
 * @return  0 for success, <0 for error
3194
 */
3195
static int transcode_step(void)
3196
{
3197
    OutputStream *ost;
3198
    InputStream  *ist;
3199
    int ret;
3200
 
3201
    ost = choose_output();
3202
    if (!ost) {
3203
        if (got_eagain()) {
3204
            reset_eagain();
3205
            av_usleep(10000);
3206
            return 0;
3207
        }
3208
        av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
3209
        return AVERROR_EOF;
3210
    }
3211
 
3212
    if (ost->filter) {
3213
        if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
3214
            return ret;
3215
        if (!ist)
3216
            return 0;
3217
    } else {
3218
        av_assert0(ost->source_index >= 0);
3219
        ist = input_streams[ost->source_index];
3220
    }
3221
 
3222
    ret = process_input(ist->file_index);
3223
    if (ret == AVERROR(EAGAIN)) {
3224
        if (input_files[ist->file_index]->eagain)
3225
            ost->unavailable = 1;
3226
        return 0;
3227
    }
3228
    if (ret < 0)
3229
        return ret == AVERROR_EOF ? 0 : ret;
3230
 
3231
    return reap_filters();
3232
}
3233
 
3234
/*
3235
 * The following code is the main loop of the file converter
3236
 */
3237
static int transcode(void)
3238
{
3239
    int ret, i;
3240
    AVFormatContext *os;
3241
    OutputStream *ost;
3242
    InputStream *ist;
3243
    int64_t timer_start;
3244
 
3245
    ret = transcode_init();
3246
    if (ret < 0)
3247
        goto fail;
3248
 
3249
    if (stdin_interaction) {
3250
        av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3251
    }
3252
 
3253
    timer_start = av_gettime();
3254
 
3255
#if HAVE_PTHREADS
3256
    if ((ret = init_input_threads()) < 0)
3257
        goto fail;
3258
#endif
3259
 
3260
    while (!received_sigterm) {
3261
        int64_t cur_time= av_gettime();
3262
 
3263
        /* if 'q' pressed, exits */
3264
        if (stdin_interaction)
3265
            if (check_keyboard_interaction(cur_time) < 0)
3266
                break;
3267
 
3268
        /* check if there's any stream where output is still needed */
3269
        if (!need_output()) {
3270
            av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
3271
            break;
3272
        }
3273
 
3274
        ret = transcode_step();
3275
        if (ret < 0) {
3276
            if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
3277
                continue;
3278
 
3279
            av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
3280
            break;
3281
        }
3282
 
3283
        /* dump report by using the output first video and audio streams */
3284
        print_report(0, timer_start, cur_time);
3285
    }
3286
#if HAVE_PTHREADS
3287
    free_input_threads();
3288
#endif
3289
 
3290
    /* at the end of stream, we must flush the decoder buffers */
3291
    for (i = 0; i < nb_input_streams; i++) {
3292
        ist = input_streams[i];
3293
        if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3294
            output_packet(ist, NULL);
3295
        }
3296
    }
3297
    flush_encoders();
3298
 
3299
    term_exit();
3300
 
3301
    /* write the trailer if needed and close file */
3302
    for (i = 0; i < nb_output_files; i++) {
3303
        os = output_files[i]->ctx;
3304
        av_write_trailer(os);
3305
    }
3306
 
3307
    /* dump report by using the first video and audio streams */
3308
    print_report(1, timer_start, av_gettime());
3309
 
3310
    /* close each encoder */
3311
    for (i = 0; i < nb_output_streams; i++) {
3312
        ost = output_streams[i];
3313
        if (ost->encoding_needed) {
3314
            av_freep(&ost->st->codec->stats_in);
3315
            avcodec_close(ost->st->codec);
3316
        }
3317
    }
3318
 
3319
    /* close each decoder */
3320
    for (i = 0; i < nb_input_streams; i++) {
3321
        ist = input_streams[i];
3322
        if (ist->decoding_needed) {
3323
            avcodec_close(ist->st->codec);
3324
        }
3325
    }
3326
 
3327
    /* finished ! */
3328
    ret = 0;
3329
 
3330
 fail:
3331
#if HAVE_PTHREADS
3332
    free_input_threads();
3333
#endif
3334
 
3335
    if (output_streams) {
3336
        for (i = 0; i < nb_output_streams; i++) {
3337
            ost = output_streams[i];
3338
            if (ost) {
3339
                if (ost->stream_copy)
3340
                    av_freep(&ost->st->codec->extradata);
3341
                if (ost->logfile) {
3342
                    fclose(ost->logfile);
3343
                    ost->logfile = NULL;
3344
                }
3345
                av_freep(&ost->st->codec->subtitle_header);
3346
                av_freep(&ost->forced_kf_pts);
3347
                av_freep(&ost->apad);
3348
                av_dict_free(&ost->opts);
3349
                av_dict_free(&ost->swr_opts);
3350
                av_dict_free(&ost->resample_opts);
3351
            }
3352
        }
3353
    }
3354
    return ret;
3355
}
3356
 
3357
 
3358
static int64_t getutime(void)
3359
{
3360
#if HAVE_GETRUSAGE
3361
    struct rusage rusage;
3362
 
3363
    getrusage(RUSAGE_SELF, &rusage);
3364
    return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3365
#elif HAVE_GETPROCESSTIMES
3366
    HANDLE proc;
3367
    FILETIME c, e, k, u;
3368
    proc = GetCurrentProcess();
3369
    GetProcessTimes(proc, &c, &e, &k, &u);
3370
    return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3371
#else
3372
    return av_gettime();
3373
#endif
3374
}
3375
 
3376
static int64_t getmaxrss(void)
3377
{
3378
#if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3379
    struct rusage rusage;
3380
    getrusage(RUSAGE_SELF, &rusage);
3381
    return (int64_t)rusage.ru_maxrss * 1024;
3382
#elif HAVE_GETPROCESSMEMORYINFO
3383
    HANDLE proc;
3384
    PROCESS_MEMORY_COUNTERS memcounters;
3385
    proc = GetCurrentProcess();
3386
    memcounters.cb = sizeof(memcounters);
3387
    GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3388
    return memcounters.PeakPagefileUsage;
3389
#else
3390
    return 0;
3391
#endif
3392
}
3393
 
3394
static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
3395
{
3396
}
3397
 
3398
int main(int argc, char **argv)
3399
{
3400
    int ret;
3401
    int64_t ti;
3402
 
3403
    register_exit(ffmpeg_cleanup);
3404
 
3405
    setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
3406
 
3407
    av_log_set_flags(AV_LOG_SKIP_REPEATED);
3408
    parse_loglevel(argc, argv, options);
3409
 
3410
    if(argc>1 && !strcmp(argv[1], "-d")){
3411
        run_as_daemon=1;
3412
        av_log_set_callback(log_callback_null);
3413
        argc--;
3414
        argv++;
3415
    }
3416
 
3417
    avcodec_register_all();
3418
#if CONFIG_AVDEVICE
3419
    avdevice_register_all();
3420
#endif
3421
    avfilter_register_all();
3422
    av_register_all();
3423
    avformat_network_init();
3424
 
3425
    show_banner(argc, argv, options);
3426
 
3427
    term_init();
3428
 
3429
    /* parse options and open all input/output files */
3430
    ret = ffmpeg_parse_options(argc, argv);
3431
    if (ret < 0)
3432
        exit_program(1);
3433
 
3434
    if (nb_output_files <= 0 && nb_input_files == 0) {
3435
        show_usage();
3436
        av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
3437
        exit_program(1);
3438
    }
3439
 
3440
    /* file converter / grab */
3441
    if (nb_output_files <= 0) {
3442
        av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
3443
        exit_program(1);
3444
    }
3445
 
3446
//     if (nb_input_files == 0) {
3447
//         av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
3448
//         exit_program(1);
3449
//     }
3450
 
3451
    current_time = ti = getutime();
3452
    if (transcode() < 0)
3453
        exit_program(1);
3454
    ti = getutime() - ti;
3455
    if (do_benchmark) {
3456
        printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3457
    }
3458
    av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
3459
           decode_error_stat[0], decode_error_stat[1]);
3460
    if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
3461
        exit_program(69);
3462
 
3463
    exit_program(received_nb_signals ? 255 : 0);
3464
    return 0;
3465
}