Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 4ff8fcef

History | View | Annotate | Download (96.7 KB)

1
/*
2
 * Various utilities for ffmpeg system
3
 * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
4
 *
5
 * This library is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU Lesser General Public
7
 * License as published by the Free Software Foundation; either
8
 * version 2 of the License, or (at your option) any later version.
9
 *
10
 * This library is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
 * Lesser General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Lesser General Public
16
 * License along with this library; if not, write to the Free Software
17
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
 */
19
#include "avformat.h"
20
#include "allformats.h"
21
#include "opt.h"
22

    
23
#undef NDEBUG
24
#include <assert.h>
25

    
26
/**
27
 * @file libavformat/utils.c
28
 * Various utility functions for using ffmpeg library.
29
 */
30

    
31
static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den);
32
static void av_frac_add(AVFrac *f, int64_t incr);
33
static void av_frac_set(AVFrac *f, int64_t val);
34

    
35
/** head of registered input format linked list. */
36
AVInputFormat *first_iformat = NULL;
37
/** head of registered output format linked list. */
38
AVOutputFormat *first_oformat = NULL;
39
/** head of registered image format linked list. */
40
AVImageFormat *first_image_format = NULL;
41

    
42
void av_register_input_format(AVInputFormat *format)
43
{
44
    AVInputFormat **p;
45
    p = &first_iformat;
46
    while (*p != NULL) p = &(*p)->next;
47
    *p = format;
48
    format->next = NULL;
49
}
50

    
51
void av_register_output_format(AVOutputFormat *format)
52
{
53
    AVOutputFormat **p;
54
    p = &first_oformat;
55
    while (*p != NULL) p = &(*p)->next;
56
    *p = format;
57
    format->next = NULL;
58
}
59

    
60
int match_ext(const char *filename, const char *extensions)
61
{
62
    const char *ext, *p;
63
    char ext1[32], *q;
64

    
65
    if(!filename)
66
        return 0;
67

    
68
    ext = strrchr(filename, '.');
69
    if (ext) {
70
        ext++;
71
        p = extensions;
72
        for(;;) {
73
            q = ext1;
74
            while (*p != '\0' && *p != ',' && q-ext1<sizeof(ext1)-1)
75
                *q++ = *p++;
76
            *q = '\0';
77
            if (!strcasecmp(ext1, ext))
78
                return 1;
79
            if (*p == '\0')
80
                break;
81
            p++;
82
        }
83
    }
84
    return 0;
85
}
86

    
87
AVOutputFormat *guess_format(const char *short_name, const char *filename,
88
                             const char *mime_type)
89
{
90
    AVOutputFormat *fmt, *fmt_found;
91
    int score_max, score;
92

    
93
    /* specific test for image sequences */
94
#ifdef CONFIG_IMAGE2_MUXER
95
    if (!short_name && filename &&
96
        av_filename_number_test(filename) &&
97
        av_guess_image2_codec(filename) != CODEC_ID_NONE) {
98
        return guess_format("image2", NULL, NULL);
99
    }
100
#endif
101
    if (!short_name && filename &&
102
        av_filename_number_test(filename) &&
103
        guess_image_format(filename)) {
104
        return guess_format("image", NULL, NULL);
105
    }
106

    
107
    /* find the proper file type */
108
    fmt_found = NULL;
109
    score_max = 0;
110
    fmt = first_oformat;
111
    while (fmt != NULL) {
112
        score = 0;
113
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
114
            score += 100;
115
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
116
            score += 10;
117
        if (filename && fmt->extensions &&
118
            match_ext(filename, fmt->extensions)) {
119
            score += 5;
120
        }
121
        if (score > score_max) {
122
            score_max = score;
123
            fmt_found = fmt;
124
        }
125
        fmt = fmt->next;
126
    }
127
    return fmt_found;
128
}
129

    
130
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename,
131
                             const char *mime_type)
132
{
133
    AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
134

    
135
    if (fmt) {
136
        AVOutputFormat *stream_fmt;
137
        char stream_format_name[64];
138

    
139
        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
140
        stream_fmt = guess_format(stream_format_name, NULL, NULL);
141

    
142
        if (stream_fmt)
143
            fmt = stream_fmt;
144
    }
145

    
146
    return fmt;
147
}
148

    
149
/**
150
 * Guesses the codec id based upon muxer and filename.
151
 */
152
enum CodecID av_guess_codec(AVOutputFormat *fmt, const char *short_name,
153
                            const char *filename, const char *mime_type, enum CodecType type){
154
    if(type == CODEC_TYPE_VIDEO){
155
        enum CodecID codec_id= CODEC_ID_NONE;
156

    
157
#ifdef CONFIG_IMAGE2_MUXER
158
        if(!strcmp(fmt->name, "image2") || !strcmp(fmt->name, "image2pipe")){
159
            codec_id= av_guess_image2_codec(filename);
160
        }
161
#endif
162
        if(codec_id == CODEC_ID_NONE)
163
            codec_id= fmt->video_codec;
164
        return codec_id;
165
    }else if(type == CODEC_TYPE_AUDIO)
166
        return fmt->audio_codec;
167
    else
168
        return CODEC_ID_NONE;
169
}
170

    
171
/**
172
 * finds AVInputFormat based on input format's short name.
173
 */
174
AVInputFormat *av_find_input_format(const char *short_name)
175
{
176
    AVInputFormat *fmt;
177
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
178
        if (!strcmp(fmt->name, short_name))
179
            return fmt;
180
    }
181
    return NULL;
182
}
183

    
184
/* memory handling */
185

    
186
/**
187
 * Default packet destructor.
188
 */
189
void av_destruct_packet(AVPacket *pkt)
190
{
191
    av_free(pkt->data);
192
    pkt->data = NULL; pkt->size = 0;
193
}
194

    
195
/**
196
 * Allocate the payload of a packet and intialized its fields to default values.
197
 *
198
 * @param pkt packet
199
 * @param size wanted payload size
200
 * @return 0 if OK. AVERROR_xxx otherwise.
201
 */
202
int av_new_packet(AVPacket *pkt, int size)
203
{
204
    void *data;
205
    if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)
206
        return AVERROR_NOMEM;
207
    data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
208
    if (!data)
209
        return AVERROR_NOMEM;
210
    memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
211

    
212
    av_init_packet(pkt);
213
    pkt->data = data;
214
    pkt->size = size;
215
    pkt->destruct = av_destruct_packet;
216
    return 0;
217
}
218

    
219
/**
220
 * Allocate and read the payload of a packet and intialized its fields to default values.
221
 *
222
 * @param pkt packet
223
 * @param size wanted payload size
224
 * @return >0 (read size) if OK. AVERROR_xxx otherwise.
225
 */
226
int av_get_packet(ByteIOContext *s, AVPacket *pkt, int size)
227
{
228
    int ret= av_new_packet(pkt, size);
229

    
230
    if(ret<0)
231
        return ret;
232

    
233
    pkt->pos= url_ftell(s);
234

    
235
    ret= get_buffer(s, pkt->data, size);
236
    if(ret<=0)
237
        av_free_packet(pkt);
238
    else
239
        pkt->size= ret;
240

    
241
    return ret;
242
}
243

    
244
/* This is a hack - the packet memory allocation stuff is broken. The
245
   packet is allocated if it was not really allocated */
246
int av_dup_packet(AVPacket *pkt)
247
{
248
    if (pkt->destruct != av_destruct_packet) {
249
        uint8_t *data;
250
        /* we duplicate the packet and don't forget to put the padding
251
           again */
252
        if((unsigned)pkt->size > (unsigned)pkt->size + FF_INPUT_BUFFER_PADDING_SIZE)
253
            return AVERROR_NOMEM;
254
        data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
255
        if (!data) {
256
            return AVERROR_NOMEM;
257
        }
258
        memcpy(data, pkt->data, pkt->size);
259
        memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
260
        pkt->data = data;
261
        pkt->destruct = av_destruct_packet;
262
    }
263
    return 0;
264
}
265

    
266
/* fifo handling */
267

    
268
int fifo_init(FifoBuffer *f, int size)
269
{
270
    f->buffer = av_malloc(size);
271
    if (!f->buffer)
272
        return -1;
273
    f->end = f->buffer + size;
274
    f->wptr = f->rptr = f->buffer;
275
    return 0;
276
}
277

    
278
void fifo_free(FifoBuffer *f)
279
{
280
    av_free(f->buffer);
281
}
282

    
283
int fifo_size(FifoBuffer *f, uint8_t *rptr)
284
{
285
    int size;
286

    
287
    if(!rptr)
288
        rptr= f->rptr;
289

    
290
    if (f->wptr >= rptr) {
291
        size = f->wptr - rptr;
292
    } else {
293
        size = (f->end - rptr) + (f->wptr - f->buffer);
294
    }
295
    return size;
296
}
297

    
298
/**
299
 * Get data from the fifo (returns -1 if not enough data).
300
 */
301
int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
302
{
303
    uint8_t *rptr;
304
    int size, len;
305

    
306
    if(!rptr_ptr)
307
        rptr_ptr= &f->rptr;
308
    rptr = *rptr_ptr;
309

    
310
    if (f->wptr >= rptr) {
311
        size = f->wptr - rptr;
312
    } else {
313
        size = (f->end - rptr) + (f->wptr - f->buffer);
314
    }
315

    
316
    if (size < buf_size)
317
        return -1;
318
    while (buf_size > 0) {
319
        len = f->end - rptr;
320
        if (len > buf_size)
321
            len = buf_size;
322
        memcpy(buf, rptr, len);
323
        buf += len;
324
        rptr += len;
325
        if (rptr >= f->end)
326
            rptr = f->buffer;
327
        buf_size -= len;
328
    }
329
    *rptr_ptr = rptr;
330
    return 0;
331
}
332

    
333
/**
334
 * Resizes a FIFO.
335
 */
336
void fifo_realloc(FifoBuffer *f, unsigned int new_size){
337
    unsigned int old_size= f->end - f->buffer;
338

    
339
    if(old_size < new_size){
340
        uint8_t *old= f->buffer;
341

    
342
        f->buffer= av_realloc(f->buffer, new_size);
343

    
344
        f->rptr += f->buffer - old;
345
        f->wptr += f->buffer - old;
346

    
347
        if(f->wptr < f->rptr){
348
            memmove(f->rptr + new_size - old_size, f->rptr, f->buffer + old_size - f->rptr);
349
            f->rptr += new_size - old_size;
350
        }
351
        f->end= f->buffer + new_size;
352
    }
353
}
354

    
355
void fifo_write(FifoBuffer *f, const uint8_t *buf, int size, uint8_t **wptr_ptr)
356
{
357
    int len;
358
    uint8_t *wptr;
359

    
360
    if(!wptr_ptr)
361
        wptr_ptr= &f->wptr;
362
    wptr = *wptr_ptr;
363

    
364
    while (size > 0) {
365
        len = f->end - wptr;
366
        if (len > size)
367
            len = size;
368
        memcpy(wptr, buf, len);
369
        wptr += len;
370
        if (wptr >= f->end)
371
            wptr = f->buffer;
372
        buf += len;
373
        size -= len;
374
    }
375
    *wptr_ptr = wptr;
376
}
377

    
378
/* get data from the fifo (return -1 if not enough data) */
379
int put_fifo(ByteIOContext *pb, FifoBuffer *f, int buf_size, uint8_t **rptr_ptr)
380
{
381
    uint8_t *rptr = *rptr_ptr;
382
    int size, len;
383

    
384
    if (f->wptr >= rptr) {
385
        size = f->wptr - rptr;
386
    } else {
387
        size = (f->end - rptr) + (f->wptr - f->buffer);
388
    }
389

    
390
    if (size < buf_size)
391
        return -1;
392
    while (buf_size > 0) {
393
        len = f->end - rptr;
394
        if (len > buf_size)
395
            len = buf_size;
396
        put_buffer(pb, rptr, len);
397
        rptr += len;
398
        if (rptr >= f->end)
399
            rptr = f->buffer;
400
        buf_size -= len;
401
    }
402
    *rptr_ptr = rptr;
403
    return 0;
404
}
405

    
406
/**
407
 * Allocate the payload of a packet and intialized its fields to default values.
408
 *
409
 * @param filename possible numbered sequence string
410
 * @return 1 if a valid numbered sequence string, 0 otherwise.
411
 */
412
int av_filename_number_test(const char *filename)
413
{
414
    char buf[1024];
415
    return filename && (av_get_frame_filename(buf, sizeof(buf), filename, 1)>=0);
416
}
417

    
418
/**
419
 * Guess file format.
420
 */
421
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
422
{
423
    AVInputFormat *fmt1, *fmt;
424
    int score, score_max;
425

    
426
    fmt = NULL;
427
    score_max = 0;
428
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
429
        if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
430
            continue;
431
        score = 0;
432
        if (fmt1->read_probe) {
433
            score = fmt1->read_probe(pd);
434
        } else if (fmt1->extensions) {
435
            if (match_ext(pd->filename, fmt1->extensions)) {
436
                score = 50;
437
            }
438
        }
439
        if (score > score_max) {
440
            score_max = score;
441
            fmt = fmt1;
442
        }
443
    }
444
    return fmt;
445
}
446

    
447
/************************************************************/
448
/* input media file */
449

    
450
/**
451
 * Open a media file from an IO stream. 'fmt' must be specified.
452
 */
453
static const char* format_to_name(void* ptr)
454
{
455
    AVFormatContext* fc = (AVFormatContext*) ptr;
456
    if(fc->iformat) return fc->iformat->name;
457
    else if(fc->oformat) return fc->oformat->name;
458
    else return "NULL";
459
}
460

    
461
#define OFFSET(x) offsetof(AVFormatContext,x)
462
#define DEFAULT 0 //should be NAN but it doesnt work as its not a constant in glibc as required by ANSI/ISO C
463
//these names are too long to be readable
464
#define E AV_OPT_FLAG_ENCODING_PARAM
465
#define D AV_OPT_FLAG_DECODING_PARAM
466

    
467
static const AVOption options[]={
468
{"probesize", NULL, OFFSET(probesize), FF_OPT_TYPE_INT, 32000, 32, INT_MAX, D}, /* 32000 from mpegts.c: 1.0 second at 24Mbit/s */
469
{"muxrate", "set mux rate", OFFSET(mux_rate), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
470
{"packetsize", "set packet size", OFFSET(packet_size), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
471
{"fflags", NULL, OFFSET(flags), FF_OPT_TYPE_FLAGS, DEFAULT, INT_MIN, INT_MAX, D, "fflags"},
472
{"ignidx", "ignore index", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_IGNIDX, INT_MIN, INT_MAX, D, "fflags"},
473
{"genpts", "generate pts", 0, FF_OPT_TYPE_CONST, AVFMT_FLAG_GENPTS, INT_MIN, INT_MAX, D, "fflags"},
474
{"track", " set the track number", OFFSET(track), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, E},
475
{"year", "set the year", OFFSET(year), FF_OPT_TYPE_INT, DEFAULT, INT_MIN, INT_MAX, E},
476
{NULL},
477
};
478

    
479
#undef E
480
#undef D
481
#undef DEFAULT
482

    
483
static const AVClass av_format_context_class = { "AVFormatContext", format_to_name, options };
484

    
485
#if LIBAVCODEC_VERSION_INT > ((52<<16)+(0<<8)+0)
486
static
487
#endif
488
void avformat_get_context_defaults(AVFormatContext *s){
489
    memset(s, 0, sizeof(AVFormatContext));
490

    
491
    s->av_class = &av_format_context_class;
492

    
493
    av_opt_set_defaults(s);
494
}
495

    
496
AVFormatContext *av_alloc_format_context(void)
497
{
498
    AVFormatContext *ic;
499
    ic = av_malloc(sizeof(AVFormatContext));
500
    if (!ic) return ic;
501
    avformat_get_context_defaults(ic);
502
    ic->av_class = &av_format_context_class;
503
    return ic;
504
}
505

    
506
/**
507
 * Allocates all the structures needed to read an input stream.
508
 *        This does not open the needed codecs for decoding the stream[s].
509
 */
510
int av_open_input_stream(AVFormatContext **ic_ptr,
511
                         ByteIOContext *pb, const char *filename,
512
                         AVInputFormat *fmt, AVFormatParameters *ap)
513
{
514
    int err;
515
    AVFormatContext *ic;
516
    AVFormatParameters default_ap;
517

    
518
    if(!ap){
519
        ap=&default_ap;
520
        memset(ap, 0, sizeof(default_ap));
521
    }
522

    
523
    if(!ap->prealloced_context)
524
        ic = av_alloc_format_context();
525
    else
526
        ic = *ic_ptr;
527
    if (!ic) {
528
        err = AVERROR_NOMEM;
529
        goto fail;
530
    }
531
    ic->iformat = fmt;
532
    if (pb)
533
        ic->pb = *pb;
534
    ic->duration = AV_NOPTS_VALUE;
535
    ic->start_time = AV_NOPTS_VALUE;
536
    pstrcpy(ic->filename, sizeof(ic->filename), filename);
537

    
538
    /* allocate private data */
539
    if (fmt->priv_data_size > 0) {
540
        ic->priv_data = av_mallocz(fmt->priv_data_size);
541
        if (!ic->priv_data) {
542
            err = AVERROR_NOMEM;
543
            goto fail;
544
        }
545
    } else {
546
        ic->priv_data = NULL;
547
    }
548

    
549
    err = ic->iformat->read_header(ic, ap);
550
    if (err < 0)
551
        goto fail;
552

    
553
    if (pb)
554
        ic->data_offset = url_ftell(&ic->pb);
555

    
556
    *ic_ptr = ic;
557
    return 0;
558
 fail:
559
    if (ic) {
560
        av_freep(&ic->priv_data);
561
    }
562
    av_free(ic);
563
    *ic_ptr = NULL;
564
    return err;
565
}
566

    
567
/** Size of probe buffer, for guessing file type from file contents. */
568
#define PROBE_BUF_MIN 2048
569
#define PROBE_BUF_MAX (1<<20)
570

    
571
/**
572
 * Open a media file as input. The codec are not opened. Only the file
573
 * header (if present) is read.
574
 *
575
 * @param ic_ptr the opened media file handle is put here
576
 * @param filename filename to open.
577
 * @param fmt if non NULL, force the file format to use
578
 * @param buf_size optional buffer size (zero if default is OK)
579
 * @param ap additionnal parameters needed when opening the file (NULL if default)
580
 * @return 0 if OK. AVERROR_xxx otherwise.
581
 */
582
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename,
583
                       AVInputFormat *fmt,
584
                       int buf_size,
585
                       AVFormatParameters *ap)
586
{
587
    int err, must_open_file, file_opened, probe_size;
588
    AVProbeData probe_data, *pd = &probe_data;
589
    ByteIOContext pb1, *pb = &pb1;
590

    
591
    file_opened = 0;
592
    pd->filename = "";
593
    if (filename)
594
        pd->filename = filename;
595
    pd->buf = NULL;
596
    pd->buf_size = 0;
597

    
598
    if (!fmt) {
599
        /* guess format if no file can be opened  */
600
        fmt = av_probe_input_format(pd, 0);
601
    }
602

    
603
    /* do not open file if the format does not need it. XXX: specific
604
       hack needed to handle RTSP/TCP */
605
    must_open_file = 1;
606
    if (fmt && (fmt->flags & AVFMT_NOFILE)) {
607
        must_open_file = 0;
608
        pb= NULL; //FIXME this or memset(pb, 0, sizeof(ByteIOContext)); otherwise its uninitalized
609
    }
610

    
611
    if (!fmt || must_open_file) {
612
        /* if no file needed do not try to open one */
613
        if (url_fopen(pb, filename, URL_RDONLY) < 0) {
614
            err = AVERROR_IO;
615
            goto fail;
616
        }
617
        file_opened = 1;
618
        if (buf_size > 0) {
619
            url_setbufsize(pb, buf_size);
620
        }
621

    
622
        for(probe_size= PROBE_BUF_MIN; probe_size<=PROBE_BUF_MAX && !fmt; probe_size<<=1){
623
            /* read probe data */
624
            pd->buf= av_realloc(pd->buf, probe_size);
625
            pd->buf_size = get_buffer(pb, pd->buf, probe_size);
626
            if (url_fseek(pb, 0, SEEK_SET) == (offset_t)-EPIPE) {
627
                url_fclose(pb);
628
                if (url_fopen(pb, filename, URL_RDONLY) < 0) {
629
                    file_opened = 0;
630
                    err = AVERROR_IO;
631
                    goto fail;
632
                }
633
            }
634
            /* guess file format */
635
            fmt = av_probe_input_format(pd, 1);
636
        }
637
        av_freep(&pd->buf);
638
    }
639

    
640
    /* if still no format found, error */
641
    if (!fmt) {
642
        err = AVERROR_NOFMT;
643
        goto fail;
644
    }
645

    
646
    /* XXX: suppress this hack for redirectors */
647
#ifdef CONFIG_NETWORK
648
    if (fmt == &redir_demuxer) {
649
        err = redir_open(ic_ptr, pb);
650
        url_fclose(pb);
651
        return err;
652
    }
653
#endif
654

    
655
    /* check filename in case of an image number is expected */
656
    if (fmt->flags & AVFMT_NEEDNUMBER) {
657
        if (!av_filename_number_test(filename)) {
658
            err = AVERROR_NUMEXPECTED;
659
            goto fail;
660
        }
661
    }
662
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
663
    if (err)
664
        goto fail;
665
    return 0;
666
 fail:
667
    av_freep(&pd->buf);
668
    if (file_opened)
669
        url_fclose(pb);
670
    *ic_ptr = NULL;
671
    return err;
672

    
673
}
674

    
675
/*******************************************************/
676

    
677
/**
678
 * Read a transport packet from a media file.
679
 *
680
 * This function is absolete and should never be used.
681
 * Use av_read_frame() instead.
682
 *
683
 * @param s media file handle
684
 * @param pkt is filled
685
 * @return 0 if OK. AVERROR_xxx if error.
686
 */
687
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
688
{
689
    return s->iformat->read_packet(s, pkt);
690
}
691

    
692
/**********************************************************/
693

    
694
/**
695
 * Get the number of samples of an audio frame. Return (-1) if error.
696
 */
697
static int get_audio_frame_size(AVCodecContext *enc, int size)
698
{
699
    int frame_size;
700

    
701
    if (enc->frame_size <= 1) {
702
        int bits_per_sample = av_get_bits_per_sample(enc->codec_id);
703

    
704
        if (bits_per_sample) {
705
            if (enc->channels == 0)
706
                return -1;
707
            frame_size = (size << 3) / (bits_per_sample * enc->channels);
708
        } else {
709
            /* used for example by ADPCM codecs */
710
            if (enc->bit_rate == 0)
711
                return -1;
712
            frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
713
        }
714
    } else {
715
        frame_size = enc->frame_size;
716
    }
717
    return frame_size;
718
}
719

    
720

    
721
/**
722
 * Return the frame duration in seconds, return 0 if not available.
723
 */
724
static void compute_frame_duration(int *pnum, int *pden, AVStream *st,
725
                                   AVCodecParserContext *pc, AVPacket *pkt)
726
{
727
    int frame_size;
728

    
729
    *pnum = 0;
730
    *pden = 0;
731
    switch(st->codec->codec_type) {
732
    case CODEC_TYPE_VIDEO:
733
        if(st->time_base.num*1000LL > st->time_base.den){
734
            *pnum = st->time_base.num;
735
            *pden = st->time_base.den;
736
        }else if(st->codec->time_base.num*1000LL > st->codec->time_base.den){
737
            *pnum = st->codec->time_base.num;
738
            *pden = st->codec->time_base.den;
739
            if (pc && pc->repeat_pict) {
740
                *pden *= 2;
741
                *pnum = (*pnum) * (2 + pc->repeat_pict);
742
            }
743
        }
744
        break;
745
    case CODEC_TYPE_AUDIO:
746
        frame_size = get_audio_frame_size(st->codec, pkt->size);
747
        if (frame_size < 0)
748
            break;
749
        *pnum = frame_size;
750
        *pden = st->codec->sample_rate;
751
        break;
752
    default:
753
        break;
754
    }
755
}
756

    
757
static int is_intra_only(AVCodecContext *enc){
758
    if(enc->codec_type == CODEC_TYPE_AUDIO){
759
        return 1;
760
    }else if(enc->codec_type == CODEC_TYPE_VIDEO){
761
        switch(enc->codec_id){
762
        case CODEC_ID_MJPEG:
763
        case CODEC_ID_MJPEGB:
764
        case CODEC_ID_LJPEG:
765
        case CODEC_ID_RAWVIDEO:
766
        case CODEC_ID_DVVIDEO:
767
        case CODEC_ID_HUFFYUV:
768
        case CODEC_ID_FFVHUFF:
769
        case CODEC_ID_ASV1:
770
        case CODEC_ID_ASV2:
771
        case CODEC_ID_VCR1:
772
            return 1;
773
        default: break;
774
        }
775
    }
776
    return 0;
777
}
778

    
779
static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
780
    int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
781
    int64_t delta= last_ts - mask/2;
782
    return  ((lsb - delta)&mask) + delta;
783
}
784

    
785
static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
786
                               AVCodecParserContext *pc, AVPacket *pkt)
787
{
788
    int num, den, presentation_delayed;
789
    /* handle wrapping */
790
    if(st->cur_dts != AV_NOPTS_VALUE){
791
        if(pkt->pts != AV_NOPTS_VALUE)
792
            pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
793
        if(pkt->dts != AV_NOPTS_VALUE)
794
            pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
795
    }
796

    
797
    if (pkt->duration == 0) {
798
        compute_frame_duration(&num, &den, st, pc, pkt);
799
        if (den && num) {
800
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
801
        }
802
    }
803

    
804
    if(is_intra_only(st->codec))
805
        pkt->flags |= PKT_FLAG_KEY;
806

    
807
    /* do we have a video B frame ? */
808
    presentation_delayed = 0;
809
    if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
810
        /* XXX: need has_b_frame, but cannot get it if the codec is
811
           not initialized */
812
        if ((   st->codec->codec_id == CODEC_ID_H264
813
             || st->codec->has_b_frames) &&
814
            pc && pc->pict_type != FF_B_TYPE)
815
            presentation_delayed = 1;
816
        /* this may be redundant, but it shouldnt hurt */
817
        if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
818
            presentation_delayed = 1;
819
    }
820

    
821
    if(st->cur_dts == AV_NOPTS_VALUE){
822
        if(presentation_delayed) st->cur_dts = -pkt->duration;
823
        else                     st->cur_dts = 0;
824
    }
825

    
826
//    av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%lld, dts:%lld cur_dts:%lld st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);
827
    /* interpolate PTS and DTS if they are not present */
828
    if (presentation_delayed) {
829
        /* DTS = decompression time stamp */
830
        /* PTS = presentation time stamp */
831
        if (pkt->dts == AV_NOPTS_VALUE) {
832
            /* if we know the last pts, use it */
833
            if(st->last_IP_pts != AV_NOPTS_VALUE)
834
                st->cur_dts = pkt->dts = st->last_IP_pts;
835
            else
836
                pkt->dts = st->cur_dts;
837
        } else {
838
            st->cur_dts = pkt->dts;
839
        }
840
        /* this is tricky: the dts must be incremented by the duration
841
           of the frame we are displaying, i.e. the last I or P frame */
842
        if (st->last_IP_duration == 0)
843
            st->cur_dts += pkt->duration;
844
        else
845
            st->cur_dts += st->last_IP_duration;
846
        st->last_IP_duration  = pkt->duration;
847
        st->last_IP_pts= pkt->pts;
848
        /* cannot compute PTS if not present (we can compute it only
849
           by knowing the futur */
850
    } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){
851
        if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){
852
            int64_t old_diff= ABS(st->cur_dts - pkt->duration - pkt->pts);
853
            int64_t new_diff= ABS(st->cur_dts - pkt->pts);
854
            if(old_diff < new_diff && old_diff < (pkt->duration>>3)){
855
                pkt->pts += pkt->duration;
856
//                av_log(NULL, AV_LOG_DEBUG, "id:%d old:%Ld new:%Ld dur:%d cur:%Ld size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);
857
            }
858
        }
859

    
860
        /* presentation is not delayed : PTS and DTS are the same */
861
        if (pkt->pts == AV_NOPTS_VALUE) {
862
            if (pkt->dts == AV_NOPTS_VALUE) {
863
                pkt->pts = st->cur_dts;
864
                pkt->dts = st->cur_dts;
865
            }
866
            else {
867
                st->cur_dts = pkt->dts;
868
                pkt->pts = pkt->dts;
869
            }
870
        } else {
871
            st->cur_dts = pkt->pts;
872
            pkt->dts = pkt->pts;
873
        }
874
        st->cur_dts += pkt->duration;
875
    }
876
//    av_log(NULL, AV_LOG_DEBUG, "OUTdelayed:%d pts:%lld, dts:%lld cur_dts:%lld\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts);
877

    
878
    /* update flags */
879
    if (pc) {
880
        pkt->flags = 0;
881
        /* key frame computation */
882
        switch(st->codec->codec_type) {
883
        case CODEC_TYPE_VIDEO:
884
            if (pc->pict_type == FF_I_TYPE)
885
                pkt->flags |= PKT_FLAG_KEY;
886
            break;
887
        case CODEC_TYPE_AUDIO:
888
            pkt->flags |= PKT_FLAG_KEY;
889
            break;
890
        default:
891
            break;
892
        }
893
    }
894
}
895

    
896
void av_destruct_packet_nofree(AVPacket *pkt)
897
{
898
    pkt->data = NULL; pkt->size = 0;
899
}
900

    
901
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
902
{
903
    AVStream *st;
904
    int len, ret, i;
905

    
906
    for(;;) {
907
        /* select current input stream component */
908
        st = s->cur_st;
909
        if (st) {
910
            if (!st->need_parsing || !st->parser) {
911
                /* no parsing needed: we just output the packet as is */
912
                /* raw data support */
913
                *pkt = s->cur_pkt;
914
                compute_pkt_fields(s, st, NULL, pkt);
915
                s->cur_st = NULL;
916
                break;
917
            } else if (s->cur_len > 0 && st->discard < AVDISCARD_ALL) {
918
                len = av_parser_parse(st->parser, st->codec, &pkt->data, &pkt->size,
919
                                      s->cur_ptr, s->cur_len,
920
                                      s->cur_pkt.pts, s->cur_pkt.dts);
921
                s->cur_pkt.pts = AV_NOPTS_VALUE;
922
                s->cur_pkt.dts = AV_NOPTS_VALUE;
923
                /* increment read pointer */
924
                s->cur_ptr += len;
925
                s->cur_len -= len;
926

    
927
                /* return packet if any */
928
                if (pkt->size) {
929
                got_packet:
930
                    pkt->duration = 0;
931
                    pkt->stream_index = st->index;
932
                    pkt->pts = st->parser->pts;
933
                    pkt->dts = st->parser->dts;
934
                    pkt->destruct = av_destruct_packet_nofree;
935
                    compute_pkt_fields(s, st, st->parser, pkt);
936
                    break;
937
                }
938
            } else {
939
                /* free packet */
940
                av_free_packet(&s->cur_pkt);
941
                s->cur_st = NULL;
942
            }
943
        } else {
944
            /* read next packet */
945
            ret = av_read_packet(s, &s->cur_pkt);
946
            if (ret < 0) {
947
                if (ret == -EAGAIN)
948
                    return ret;
949
                /* return the last frames, if any */
950
                for(i = 0; i < s->nb_streams; i++) {
951
                    st = s->streams[i];
952
                    if (st->parser && st->need_parsing) {
953
                        av_parser_parse(st->parser, st->codec,
954
                                        &pkt->data, &pkt->size,
955
                                        NULL, 0,
956
                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE);
957
                        if (pkt->size)
958
                            goto got_packet;
959
                    }
960
                }
961
                /* no more packets: really terminates parsing */
962
                return ret;
963
            }
964

    
965
            st = s->streams[s->cur_pkt.stream_index];
966
            if(st->codec->debug & FF_DEBUG_PTS)
967
                av_log(s, AV_LOG_DEBUG, "av_read_packet stream=%d, pts=%lld, dts=%lld, size=%d\n",
968
                    s->cur_pkt.stream_index,
969
                    s->cur_pkt.pts,
970
                    s->cur_pkt.dts,
971
                    s->cur_pkt.size);
972

    
973
            s->cur_st = st;
974
            s->cur_ptr = s->cur_pkt.data;
975
            s->cur_len = s->cur_pkt.size;
976
            if (st->need_parsing && !st->parser) {
977
                st->parser = av_parser_init(st->codec->codec_id);
978
                if (!st->parser) {
979
                    /* no parser available : just output the raw packets */
980
                    st->need_parsing = 0;
981
                }else if(st->need_parsing == 2){
982
                    st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
983
                }
984
            }
985
        }
986
    }
987
    if(st->codec->debug & FF_DEBUG_PTS)
988
        av_log(s, AV_LOG_DEBUG, "av_read_frame_internal stream=%d, pts=%lld, dts=%lld, size=%d\n",
989
            pkt->stream_index,
990
            pkt->pts,
991
            pkt->dts,
992
            pkt->size);
993

    
994
    return 0;
995
}
996

    
997
/**
998
 * Return the next frame of a stream.
999
 *
1000
 * The returned packet is valid
1001
 * until the next av_read_frame() or until av_close_input_file() and
1002
 * must be freed with av_free_packet. For video, the packet contains
1003
 * exactly one frame. For audio, it contains an integer number of
1004
 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
1005
 * data). If the audio frames have a variable size (e.g. MPEG audio),
1006
 * then it contains one frame.
1007
 *
1008
 * pkt->pts, pkt->dts and pkt->duration are always set to correct
1009
 * values in AV_TIME_BASE unit (and guessed if the format cannot
1010
 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
1011
 * has B frames, so it is better to rely on pkt->dts if you do not
1012
 * decompress the payload.
1013
 *
1014
 * @return 0 if OK, < 0 if error or end of file.
1015
 */
1016
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
1017
{
1018
    AVPacketList *pktl;
1019
    int eof=0;
1020
    const int genpts= s->flags & AVFMT_FLAG_GENPTS;
1021

    
1022
    for(;;){
1023
        pktl = s->packet_buffer;
1024
        if (pktl) {
1025
            AVPacket *next_pkt= &pktl->pkt;
1026

    
1027
            if(genpts && next_pkt->dts != AV_NOPTS_VALUE){
1028
                while(pktl && next_pkt->pts == AV_NOPTS_VALUE){
1029
                    if(   pktl->pkt.stream_index == next_pkt->stream_index
1030
                       && next_pkt->dts < pktl->pkt.dts
1031
                       && pktl->pkt.pts != pktl->pkt.dts //not b frame
1032
                       /*&& pktl->pkt.dts != AV_NOPTS_VALUE*/){
1033
                        next_pkt->pts= pktl->pkt.dts;
1034
                    }
1035
                    pktl= pktl->next;
1036
                }
1037
                pktl = s->packet_buffer;
1038
            }
1039

    
1040
            if(   next_pkt->pts != AV_NOPTS_VALUE
1041
               || next_pkt->dts == AV_NOPTS_VALUE
1042
               || !genpts || eof){
1043
                /* read packet from packet buffer, if there is data */
1044
                *pkt = *next_pkt;
1045
                s->packet_buffer = pktl->next;
1046
                av_free(pktl);
1047
                return 0;
1048
            }
1049
        }
1050
        if(genpts){
1051
            AVPacketList **plast_pktl= &s->packet_buffer;
1052
            int ret= av_read_frame_internal(s, pkt);
1053
            if(ret<0){
1054
                if(pktl && ret != -EAGAIN){
1055
                    eof=1;
1056
                    continue;
1057
                }else
1058
                    return ret;
1059
            }
1060

    
1061
            /* duplicate the packet */
1062
            if (av_dup_packet(pkt) < 0)
1063
                return AVERROR_NOMEM;
1064

    
1065
            while(*plast_pktl) plast_pktl= &(*plast_pktl)->next; //FIXME maybe maintain pointer to the last?
1066

    
1067
            pktl = av_mallocz(sizeof(AVPacketList));
1068
            if (!pktl)
1069
                return AVERROR_NOMEM;
1070

    
1071
            /* add the packet in the buffered packet list */
1072
            *plast_pktl = pktl;
1073
            pktl->pkt= *pkt;
1074
        }else{
1075
            assert(!s->packet_buffer);
1076
            return av_read_frame_internal(s, pkt);
1077
        }
1078
    }
1079
}
1080

    
1081
/* XXX: suppress the packet queue */
1082
static void flush_packet_queue(AVFormatContext *s)
1083
{
1084
    AVPacketList *pktl;
1085

    
1086
    for(;;) {
1087
        pktl = s->packet_buffer;
1088
        if (!pktl)
1089
            break;
1090
        s->packet_buffer = pktl->next;
1091
        av_free_packet(&pktl->pkt);
1092
        av_free(pktl);
1093
    }
1094
}
1095

    
1096
/*******************************************************/
1097
/* seek support */
1098

    
1099
int av_find_default_stream_index(AVFormatContext *s)
1100
{
1101
    int i;
1102
    AVStream *st;
1103

    
1104
    if (s->nb_streams <= 0)
1105
        return -1;
1106
    for(i = 0; i < s->nb_streams; i++) {
1107
        st = s->streams[i];
1108
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
1109
            return i;
1110
        }
1111
    }
1112
    return 0;
1113
}
1114

    
1115
/**
1116
 * Flush the frame reader.
1117
 */
1118
static void av_read_frame_flush(AVFormatContext *s)
1119
{
1120
    AVStream *st;
1121
    int i;
1122

    
1123
    flush_packet_queue(s);
1124

    
1125
    /* free previous packet */
1126
    if (s->cur_st) {
1127
        if (s->cur_st->parser)
1128
            av_free_packet(&s->cur_pkt);
1129
        s->cur_st = NULL;
1130
    }
1131
    /* fail safe */
1132
    s->cur_ptr = NULL;
1133
    s->cur_len = 0;
1134

    
1135
    /* for each stream, reset read state */
1136
    for(i = 0; i < s->nb_streams; i++) {
1137
        st = s->streams[i];
1138

    
1139
        if (st->parser) {
1140
            av_parser_close(st->parser);
1141
            st->parser = NULL;
1142
        }
1143
        st->last_IP_pts = AV_NOPTS_VALUE;
1144
        st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
1145
    }
1146
}
1147

    
1148
/**
1149
 * Updates cur_dts of all streams based on given timestamp and AVStream.
1150
 *
1151
 * Stream ref_st unchanged, others set cur_dts in their native timebase
1152
 * only needed for timestamp wrapping or if (dts not set and pts!=dts)
1153
 * @param timestamp new dts expressed in time_base of param ref_st
1154
 * @param ref_st reference stream giving time_base of param timestamp
1155
 */
1156
void av_update_cur_dts(AVFormatContext *s, AVStream *ref_st, int64_t timestamp){
1157
    int i;
1158

    
1159
    for(i = 0; i < s->nb_streams; i++) {
1160
        AVStream *st = s->streams[i];
1161

    
1162
        st->cur_dts = av_rescale(timestamp,
1163
                                 st->time_base.den * (int64_t)ref_st->time_base.num,
1164
                                 st->time_base.num * (int64_t)ref_st->time_base.den);
1165
    }
1166
}
1167

    
1168
/**
1169
 * Add a index entry into a sorted list updateing if it is already there.
1170
 *
1171
 * @param timestamp timestamp in the timebase of the given stream
1172
 */
1173
int av_add_index_entry(AVStream *st,
1174
                            int64_t pos, int64_t timestamp, int size, int distance, int flags)
1175
{
1176
    AVIndexEntry *entries, *ie;
1177
    int index;
1178

    
1179
    if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry))
1180
        return -1;
1181

    
1182
    entries = av_fast_realloc(st->index_entries,
1183
                              &st->index_entries_allocated_size,
1184
                              (st->nb_index_entries + 1) *
1185
                              sizeof(AVIndexEntry));
1186
    if(!entries)
1187
        return -1;
1188

    
1189
    st->index_entries= entries;
1190

    
1191
    index= av_index_search_timestamp(st, timestamp, AVSEEK_FLAG_ANY);
1192

    
1193
    if(index<0){
1194
        index= st->nb_index_entries++;
1195
        ie= &entries[index];
1196
        assert(index==0 || ie[-1].timestamp < timestamp);
1197
    }else{
1198
        ie= &entries[index];
1199
        if(ie->timestamp != timestamp){
1200
            if(ie->timestamp <= timestamp)
1201
                return -1;
1202
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
1203
            st->nb_index_entries++;
1204
        }else if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
1205
            distance= ie->min_distance;
1206
    }
1207

    
1208
    ie->pos = pos;
1209
    ie->timestamp = timestamp;
1210
    ie->min_distance= distance;
1211
    ie->size= size;
1212
    ie->flags = flags;
1213

    
1214
    return index;
1215
}
1216

    
1217
/**
1218
 * build an index for raw streams using a parser.
1219
 */
1220
static void av_build_index_raw(AVFormatContext *s)
1221
{
1222
    AVPacket pkt1, *pkt = &pkt1;
1223
    int ret;
1224
    AVStream *st;
1225

    
1226
    st = s->streams[0];
1227
    av_read_frame_flush(s);
1228
    url_fseek(&s->pb, s->data_offset, SEEK_SET);
1229

    
1230
    for(;;) {
1231
        ret = av_read_frame(s, pkt);
1232
        if (ret < 0)
1233
            break;
1234
        if (pkt->stream_index == 0 && st->parser &&
1235
            (pkt->flags & PKT_FLAG_KEY)) {
1236
            av_add_index_entry(st, st->parser->frame_offset, pkt->dts,
1237
                            0, 0, AVINDEX_KEYFRAME);
1238
        }
1239
        av_free_packet(pkt);
1240
    }
1241
}
1242

    
1243
/**
1244
 * Returns TRUE if we deal with a raw stream.
1245
 *
1246
 * Raw codec data and parsing needed.
1247
 */
1248
static int is_raw_stream(AVFormatContext *s)
1249
{
1250
    AVStream *st;
1251

    
1252
    if (s->nb_streams != 1)
1253
        return 0;
1254
    st = s->streams[0];
1255
    if (!st->need_parsing)
1256
        return 0;
1257
    return 1;
1258
}
1259

    
1260
/**
1261
 * Gets the index for a specific timestamp.
1262
 * @param flags if AVSEEK_FLAG_BACKWARD then the returned index will correspond to
1263
 *                 the timestamp which is <= the requested one, if backward is 0
1264
 *                 then it will be >=
1265
 *              if AVSEEK_FLAG_ANY seek to any frame, only keyframes otherwise
1266
 * @return < 0 if no such timestamp could be found
1267
 */
1268
int av_index_search_timestamp(AVStream *st, int64_t wanted_timestamp,
1269
                              int flags)
1270
{
1271
    AVIndexEntry *entries= st->index_entries;
1272
    int nb_entries= st->nb_index_entries;
1273
    int a, b, m;
1274
    int64_t timestamp;
1275

    
1276
    a = - 1;
1277
    b = nb_entries;
1278

    
1279
    while (b - a > 1) {
1280
        m = (a + b) >> 1;
1281
        timestamp = entries[m].timestamp;
1282
        if(timestamp >= wanted_timestamp)
1283
            b = m;
1284
        if(timestamp <= wanted_timestamp)
1285
            a = m;
1286
    }
1287
    m= (flags & AVSEEK_FLAG_BACKWARD) ? a : b;
1288

    
1289
    if(!(flags & AVSEEK_FLAG_ANY)){
1290
        while(m>=0 && m<nb_entries && !(entries[m].flags & AVINDEX_KEYFRAME)){
1291
            m += (flags & AVSEEK_FLAG_BACKWARD) ? -1 : 1;
1292
        }
1293
    }
1294

    
1295
    if(m == nb_entries)
1296
        return -1;
1297
    return  m;
1298
}
1299

    
1300
#define DEBUG_SEEK
1301

    
1302
/**
1303
 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
1304
 * this isnt supposed to be called directly by a user application, but by demuxers
1305
 * @param target_ts target timestamp in the time base of the given stream
1306
 * @param stream_index stream number
1307
 */
1308
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1309
    AVInputFormat *avif= s->iformat;
1310
    int64_t pos_min, pos_max, pos, pos_limit;
1311
    int64_t ts_min, ts_max, ts;
1312
    int64_t start_pos, filesize;
1313
    int index, no_change;
1314
    AVStream *st;
1315

    
1316
    if (stream_index < 0)
1317
        return -1;
1318

    
1319
#ifdef DEBUG_SEEK
1320
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);
1321
#endif
1322

    
1323
    ts_max=
1324
    ts_min= AV_NOPTS_VALUE;
1325
    pos_limit= -1; //gcc falsely says it may be uninitalized
1326

    
1327
    st= s->streams[stream_index];
1328
    if(st->index_entries){
1329
        AVIndexEntry *e;
1330

    
1331
        index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non keyframe entries in index case, especially read_timestamp()
1332
        index= FFMAX(index, 0);
1333
        e= &st->index_entries[index];
1334

    
1335
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1336
            pos_min= e->pos;
1337
            ts_min= e->timestamp;
1338
#ifdef DEBUG_SEEK
1339
        av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",
1340
               pos_min,ts_min);
1341
#endif
1342
        }else{
1343
            assert(index==0);
1344
        }
1345

    
1346
        index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);
1347
        assert(index < st->nb_index_entries);
1348
        if(index >= 0){
1349
            e= &st->index_entries[index];
1350
            assert(e->timestamp >= target_ts);
1351
            pos_max= e->pos;
1352
            ts_max= e->timestamp;
1353
            pos_limit= pos_max - e->min_distance;
1354
#ifdef DEBUG_SEEK
1355
        av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",
1356
               pos_max,pos_limit, ts_max);
1357
#endif
1358
        }
1359
    }
1360

    
1361
    if(ts_min == AV_NOPTS_VALUE){
1362
        pos_min = s->data_offset;
1363
        ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1364
        if (ts_min == AV_NOPTS_VALUE)
1365
            return -1;
1366
    }
1367

    
1368
    if(ts_max == AV_NOPTS_VALUE){
1369
        int step= 1024;
1370
        filesize = url_fsize(&s->pb);
1371
        pos_max = filesize - 1;
1372
        do{
1373
            pos_max -= step;
1374
            ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1375
            step += step;
1376
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1377
        if (ts_max == AV_NOPTS_VALUE)
1378
            return -1;
1379

    
1380
        for(;;){
1381
            int64_t tmp_pos= pos_max + 1;
1382
            int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1383
            if(tmp_ts == AV_NOPTS_VALUE)
1384
                break;
1385
            ts_max= tmp_ts;
1386
            pos_max= tmp_pos;
1387
            if(tmp_pos >= filesize)
1388
                break;
1389
        }
1390
        pos_limit= pos_max;
1391
    }
1392

    
1393
    if(ts_min > ts_max){
1394
        return -1;
1395
    }else if(ts_min == ts_max){
1396
        pos_limit= pos_min;
1397
    }
1398

    
1399
    no_change=0;
1400
    while (pos_min < pos_limit) {
1401
#ifdef DEBUG_SEEK
1402
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%"PRIx64" pos_max=0x%"PRIx64" dts_min=%"PRId64" dts_max=%"PRId64"\n",
1403
               pos_min, pos_max,
1404
               ts_min, ts_max);
1405
#endif
1406
        assert(pos_limit <= pos_max);
1407

    
1408
        if(no_change==0){
1409
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1410
            // interpolate position (better than dichotomy)
1411
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1412
                + pos_min - approximate_keyframe_distance;
1413
        }else if(no_change==1){
1414
            // bisection, if interpolation failed to change min or max pos last time
1415
            pos = (pos_min + pos_limit)>>1;
1416
        }else{
1417
            // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1418
            pos=pos_min;
1419
        }
1420
        if(pos <= pos_min)
1421
            pos= pos_min + 1;
1422
        else if(pos > pos_limit)
1423
            pos= pos_limit;
1424
        start_pos= pos;
1425

    
1426
        ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1427
        if(pos == pos_max)
1428
            no_change++;
1429
        else
1430
            no_change=0;
1431
#ifdef DEBUG_SEEK
1432
av_log(s, AV_LOG_DEBUG, "%"PRId64" %"PRId64" %"PRId64" / %"PRId64" %"PRId64" %"PRId64" target:%"PRId64" limit:%"PRId64" start:%"PRId64" noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1433
#endif
1434
        assert(ts != AV_NOPTS_VALUE);
1435
        if (target_ts <= ts) {
1436
            pos_limit = start_pos - 1;
1437
            pos_max = pos;
1438
            ts_max = ts;
1439
        }
1440
        if (target_ts >= ts) {
1441
            pos_min = pos;
1442
            ts_min = ts;
1443
        }
1444
    }
1445

    
1446
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1447
    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1448
#ifdef DEBUG_SEEK
1449
    pos_min = pos;
1450
    ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1451
    pos_min++;
1452
    ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1453
    av_log(s, AV_LOG_DEBUG, "pos=0x%"PRIx64" %"PRId64"<=%"PRId64"<=%"PRId64"\n",
1454
           pos, ts_min, target_ts, ts_max);
1455
#endif
1456
    /* do the seek */
1457
    url_fseek(&s->pb, pos, SEEK_SET);
1458

    
1459
    av_update_cur_dts(s, st, ts);
1460

    
1461
    return 0;
1462
}
1463

    
1464
static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1465
    int64_t pos_min, pos_max;
1466
#if 0
1467
    AVStream *st;
1468

1469
    if (stream_index < 0)
1470
        return -1;
1471

1472
    st= s->streams[stream_index];
1473
#endif
1474

    
1475
    pos_min = s->data_offset;
1476
    pos_max = url_fsize(&s->pb) - 1;
1477

    
1478
    if     (pos < pos_min) pos= pos_min;
1479
    else if(pos > pos_max) pos= pos_max;
1480

    
1481
    url_fseek(&s->pb, pos, SEEK_SET);
1482

    
1483
#if 0
1484
    av_update_cur_dts(s, st, ts);
1485
#endif
1486
    return 0;
1487
}
1488

    
1489
static int av_seek_frame_generic(AVFormatContext *s,
1490
                                 int stream_index, int64_t timestamp, int flags)
1491
{
1492
    int index;
1493
    AVStream *st;
1494
    AVIndexEntry *ie;
1495

    
1496
    if (!s->index_built) {
1497
        if (is_raw_stream(s)) {
1498
            av_build_index_raw(s);
1499
        } else {
1500
            return -1;
1501
        }
1502
        s->index_built = 1;
1503
    }
1504

    
1505
    st = s->streams[stream_index];
1506
    index = av_index_search_timestamp(st, timestamp, flags);
1507
    if (index < 0)
1508
        return -1;
1509

    
1510
    /* now we have found the index, we can seek */
1511
    ie = &st->index_entries[index];
1512
    av_read_frame_flush(s);
1513
    url_fseek(&s->pb, ie->pos, SEEK_SET);
1514

    
1515
    av_update_cur_dts(s, st, ie->timestamp);
1516

    
1517
    return 0;
1518
}
1519

    
1520
/**
1521
 * Seek to the key frame at timestamp.
1522
 * 'timestamp' in 'stream_index'.
1523
 * @param stream_index If stream_index is (-1), a default
1524
 * stream is selected, and timestamp is automatically converted
1525
 * from AV_TIME_BASE units to the stream specific time_base.
1526
 * @param timestamp timestamp in AVStream.time_base units
1527
 *        or if there is no stream specified then in AV_TIME_BASE units
1528
 * @param flags flags which select direction and seeking mode
1529
 * @return >= 0 on success
1530
 */
1531
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1532
{
1533
    int ret;
1534
    AVStream *st;
1535

    
1536
    av_read_frame_flush(s);
1537

    
1538
    if(flags & AVSEEK_FLAG_BYTE)
1539
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1540

    
1541
    if(stream_index < 0){
1542
        stream_index= av_find_default_stream_index(s);
1543
        if(stream_index < 0)
1544
            return -1;
1545

    
1546
        st= s->streams[stream_index];
1547
       /* timestamp for default must be expressed in AV_TIME_BASE units */
1548
        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1549
    }
1550
    st= s->streams[stream_index];
1551

    
1552
    /* first, we try the format specific seek */
1553
    if (s->iformat->read_seek)
1554
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1555
    else
1556
        ret = -1;
1557
    if (ret >= 0) {
1558
        return 0;
1559
    }
1560

    
1561
    if(s->iformat->read_timestamp)
1562
        return av_seek_frame_binary(s, stream_index, timestamp, flags);
1563
    else
1564
        return av_seek_frame_generic(s, stream_index, timestamp, flags);
1565
}
1566

    
1567
/*******************************************************/
1568

    
1569
/**
1570
 * Returns TRUE if the stream has accurate timings in any stream.
1571
 *
1572
 * @return TRUE if the stream has accurate timings for at least one component.
1573
 */
1574
static int av_has_timings(AVFormatContext *ic)
1575
{
1576
    int i;
1577
    AVStream *st;
1578

    
1579
    for(i = 0;i < ic->nb_streams; i++) {
1580
        st = ic->streams[i];
1581
        if (st->start_time != AV_NOPTS_VALUE &&
1582
            st->duration != AV_NOPTS_VALUE)
1583
            return 1;
1584
    }
1585
    return 0;
1586
}
1587

    
1588
/**
1589
 * Estimate the stream timings from the one of each components.
1590
 *
1591
 * Also computes the global bitrate if possible.
1592
 */
1593
static void av_update_stream_timings(AVFormatContext *ic)
1594
{
1595
    int64_t start_time, start_time1, end_time, end_time1;
1596
    int i;
1597
    AVStream *st;
1598

    
1599
    start_time = MAXINT64;
1600
    end_time = MININT64;
1601
    for(i = 0;i < ic->nb_streams; i++) {
1602
        st = ic->streams[i];
1603
        if (st->start_time != AV_NOPTS_VALUE) {
1604
            start_time1= av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q);
1605
            if (start_time1 < start_time)
1606
                start_time = start_time1;
1607
            if (st->duration != AV_NOPTS_VALUE) {
1608
                end_time1 = start_time1
1609
                          + av_rescale_q(st->duration, st->time_base, AV_TIME_BASE_Q);
1610
                if (end_time1 > end_time)
1611
                    end_time = end_time1;
1612
            }
1613
        }
1614
    }
1615
    if (start_time != MAXINT64) {
1616
        ic->start_time = start_time;
1617
        if (end_time != MININT64) {
1618
            ic->duration = end_time - start_time;
1619
            if (ic->file_size > 0) {
1620
                /* compute the bit rate */
1621
                ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE /
1622
                    (double)ic->duration;
1623
            }
1624
        }
1625
    }
1626

    
1627
}
1628

    
1629
static void fill_all_stream_timings(AVFormatContext *ic)
1630
{
1631
    int i;
1632
    AVStream *st;
1633

    
1634
    av_update_stream_timings(ic);
1635
    for(i = 0;i < ic->nb_streams; i++) {
1636
        st = ic->streams[i];
1637
        if (st->start_time == AV_NOPTS_VALUE) {
1638
            if(ic->start_time != AV_NOPTS_VALUE)
1639
                st->start_time = av_rescale_q(ic->start_time, AV_TIME_BASE_Q, st->time_base);
1640
            if(ic->duration != AV_NOPTS_VALUE)
1641
                st->duration = av_rescale_q(ic->duration, AV_TIME_BASE_Q, st->time_base);
1642
        }
1643
    }
1644
}
1645

    
1646
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1647
{
1648
    int64_t filesize, duration;
1649
    int bit_rate, i;
1650
    AVStream *st;
1651

    
1652
    /* if bit_rate is already set, we believe it */
1653
    if (ic->bit_rate == 0) {
1654
        bit_rate = 0;
1655
        for(i=0;i<ic->nb_streams;i++) {
1656
            st = ic->streams[i];
1657
            bit_rate += st->codec->bit_rate;
1658
        }
1659
        ic->bit_rate = bit_rate;
1660
    }
1661

    
1662
    /* if duration is already set, we believe it */
1663
    if (ic->duration == AV_NOPTS_VALUE &&
1664
        ic->bit_rate != 0 &&
1665
        ic->file_size != 0)  {
1666
        filesize = ic->file_size;
1667
        if (filesize > 0) {
1668
            for(i = 0; i < ic->nb_streams; i++) {
1669
                st = ic->streams[i];
1670
                duration= av_rescale(8*filesize, st->time_base.den, ic->bit_rate*(int64_t)st->time_base.num);
1671
                if (st->start_time == AV_NOPTS_VALUE ||
1672
                    st->duration == AV_NOPTS_VALUE) {
1673
                    st->start_time = 0;
1674
                    st->duration = duration;
1675
                }
1676
            }
1677
        }
1678
    }
1679
}
1680

    
1681
#define DURATION_MAX_READ_SIZE 250000
1682

    
1683
/* only usable for MPEG-PS streams */
1684
static void av_estimate_timings_from_pts(AVFormatContext *ic)
1685
{
1686
    AVPacket pkt1, *pkt = &pkt1;
1687
    AVStream *st;
1688
    int read_size, i, ret;
1689
    int64_t end_time;
1690
    int64_t filesize, offset, duration;
1691

    
1692
    /* free previous packet */
1693
    if (ic->cur_st && ic->cur_st->parser)
1694
        av_free_packet(&ic->cur_pkt);
1695
    ic->cur_st = NULL;
1696

    
1697
    /* flush packet queue */
1698
    flush_packet_queue(ic);
1699

    
1700
    for(i=0;i<ic->nb_streams;i++) {
1701
        st = ic->streams[i];
1702
        if (st->parser) {
1703
            av_parser_close(st->parser);
1704
            st->parser= NULL;
1705
        }
1706
    }
1707

    
1708
    /* we read the first packets to get the first PTS (not fully
1709
       accurate, but it is enough now) */
1710
    url_fseek(&ic->pb, 0, SEEK_SET);
1711
    read_size = 0;
1712
    for(;;) {
1713
        if (read_size >= DURATION_MAX_READ_SIZE)
1714
            break;
1715
        /* if all info is available, we can stop */
1716
        for(i = 0;i < ic->nb_streams; i++) {
1717
            st = ic->streams[i];
1718
            if (st->start_time == AV_NOPTS_VALUE)
1719
                break;
1720
        }
1721
        if (i == ic->nb_streams)
1722
            break;
1723

    
1724
        ret = av_read_packet(ic, pkt);
1725
        if (ret != 0)
1726
            break;
1727
        read_size += pkt->size;
1728
        st = ic->streams[pkt->stream_index];
1729
        if (pkt->pts != AV_NOPTS_VALUE) {
1730
            if (st->start_time == AV_NOPTS_VALUE)
1731
                st->start_time = pkt->pts;
1732
        }
1733
        av_free_packet(pkt);
1734
    }
1735

    
1736
    /* estimate the end time (duration) */
1737
    /* XXX: may need to support wrapping */
1738
    filesize = ic->file_size;
1739
    offset = filesize - DURATION_MAX_READ_SIZE;
1740
    if (offset < 0)
1741
        offset = 0;
1742

    
1743
    url_fseek(&ic->pb, offset, SEEK_SET);
1744
    read_size = 0;
1745
    for(;;) {
1746
        if (read_size >= DURATION_MAX_READ_SIZE)
1747
            break;
1748
        /* if all info is available, we can stop */
1749
        for(i = 0;i < ic->nb_streams; i++) {
1750
            st = ic->streams[i];
1751
            if (st->duration == AV_NOPTS_VALUE)
1752
                break;
1753
        }
1754
        if (i == ic->nb_streams)
1755
            break;
1756

    
1757
        ret = av_read_packet(ic, pkt);
1758
        if (ret != 0)
1759
            break;
1760
        read_size += pkt->size;
1761
        st = ic->streams[pkt->stream_index];
1762
        if (pkt->pts != AV_NOPTS_VALUE) {
1763
            end_time = pkt->pts;
1764
            duration = end_time - st->start_time;
1765
            if (duration > 0) {
1766
                if (st->duration == AV_NOPTS_VALUE ||
1767
                    st->duration < duration)
1768
                    st->duration = duration;
1769
            }
1770
        }
1771
        av_free_packet(pkt);
1772
    }
1773

    
1774
    fill_all_stream_timings(ic);
1775

    
1776
    url_fseek(&ic->pb, 0, SEEK_SET);
1777
}
1778

    
1779
static void av_estimate_timings(AVFormatContext *ic)
1780
{
1781
    int64_t file_size;
1782

    
1783
    /* get the file size, if possible */
1784
    if (ic->iformat->flags & AVFMT_NOFILE) {
1785
        file_size = 0;
1786
    } else {
1787
        file_size = url_fsize(&ic->pb);
1788
        if (file_size < 0)
1789
            file_size = 0;
1790
    }
1791
    ic->file_size = file_size;
1792

    
1793
    if ((!strcmp(ic->iformat->name, "mpeg") ||
1794
         !strcmp(ic->iformat->name, "mpegts")) &&
1795
        file_size && !ic->pb.is_streamed) {
1796
        /* get accurate estimate from the PTSes */
1797
        av_estimate_timings_from_pts(ic);
1798
    } else if (av_has_timings(ic)) {
1799
        /* at least one components has timings - we use them for all
1800
           the components */
1801
        fill_all_stream_timings(ic);
1802
    } else {
1803
        /* less precise: use bit rate info */
1804
        av_estimate_timings_from_bit_rate(ic);
1805
    }
1806
    av_update_stream_timings(ic);
1807

    
1808
#if 0
1809
    {
1810
        int i;
1811
        AVStream *st;
1812
        for(i = 0;i < ic->nb_streams; i++) {
1813
            st = ic->streams[i];
1814
        printf("%d: start_time: %0.3f duration: %0.3f\n",
1815
               i, (double)st->start_time / AV_TIME_BASE,
1816
               (double)st->duration / AV_TIME_BASE);
1817
        }
1818
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n",
1819
               (double)ic->start_time / AV_TIME_BASE,
1820
               (double)ic->duration / AV_TIME_BASE,
1821
               ic->bit_rate / 1000);
1822
    }
1823
#endif
1824
}
1825

    
1826
static int has_codec_parameters(AVCodecContext *enc)
1827
{
1828
    int val;
1829
    switch(enc->codec_type) {
1830
    case CODEC_TYPE_AUDIO:
1831
        val = enc->sample_rate;
1832
        break;
1833
    case CODEC_TYPE_VIDEO:
1834
        val = enc->width && enc->pix_fmt != PIX_FMT_NONE;
1835
        break;
1836
    default:
1837
        val = 1;
1838
        break;
1839
    }
1840
    return (val != 0);
1841
}
1842

    
1843
static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1844
{
1845
    int16_t *samples;
1846
    AVCodec *codec;
1847
    int got_picture, ret=0;
1848
    AVFrame picture;
1849

    
1850
  if(!st->codec->codec){
1851
    codec = avcodec_find_decoder(st->codec->codec_id);
1852
    if (!codec)
1853
        return -1;
1854
    ret = avcodec_open(st->codec, codec);
1855
    if (ret < 0)
1856
        return ret;
1857
  }
1858

    
1859
  if(!has_codec_parameters(st->codec)){
1860
    switch(st->codec->codec_type) {
1861
    case CODEC_TYPE_VIDEO:
1862
        ret = avcodec_decode_video(st->codec, &picture,
1863
                                   &got_picture, (uint8_t *)data, size);
1864
        break;
1865
    case CODEC_TYPE_AUDIO:
1866
        samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1867
        if (!samples)
1868
            goto fail;
1869
        ret = avcodec_decode_audio(st->codec, samples,
1870
                                   &got_picture, (uint8_t *)data, size);
1871
        av_free(samples);
1872
        break;
1873
    default:
1874
        break;
1875
    }
1876
  }
1877
 fail:
1878
    return ret;
1879
}
1880

    
1881
/* absolute maximum size we read until we abort */
1882
#define MAX_READ_SIZE        5000000
1883

    
1884
/* maximum duration until we stop analysing the stream */
1885
#define MAX_STREAM_DURATION  ((int)(AV_TIME_BASE * 3.0))
1886

    
1887
/**
1888
 * Read the beginning of a media file to get stream information. This
1889
 * is useful for file formats with no headers such as MPEG. This
1890
 * function also compute the real frame rate in case of mpeg2 repeat
1891
 * frame mode.
1892
 *
1893
 * @param ic media file handle
1894
 * @return >=0 if OK. AVERROR_xxx if error.
1895
 * @todo let user decide somehow what information is needed so we dont waste time geting stuff the user doesnt need
1896
 */
1897
int av_find_stream_info(AVFormatContext *ic)
1898
{
1899
    int i, count, ret, read_size, j;
1900
    AVStream *st;
1901
    AVPacket pkt1, *pkt;
1902
    AVPacketList *pktl=NULL, **ppktl;
1903
    int64_t last_dts[MAX_STREAMS];
1904
    int64_t duration_sum[MAX_STREAMS];
1905
    int duration_count[MAX_STREAMS]={0};
1906

    
1907
    for(i=0;i<ic->nb_streams;i++) {
1908
        st = ic->streams[i];
1909
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1910
/*            if(!st->time_base.num)
1911
                st->time_base= */
1912
            if(!st->codec->time_base.num)
1913
                st->codec->time_base= st->time_base;
1914
        }
1915
        //only for the split stuff
1916
        if (!st->parser) {
1917
            st->parser = av_parser_init(st->codec->codec_id);
1918
            if(st->need_parsing == 2 && st->parser){
1919
                st->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
1920
            }
1921
        }
1922
    }
1923

    
1924
    for(i=0;i<MAX_STREAMS;i++){
1925
        last_dts[i]= AV_NOPTS_VALUE;
1926
        duration_sum[i]= INT64_MAX;
1927
    }
1928

    
1929
    count = 0;
1930
    read_size = 0;
1931
    ppktl = &ic->packet_buffer;
1932
    for(;;) {
1933
        /* check if one codec still needs to be handled */
1934
        for(i=0;i<ic->nb_streams;i++) {
1935
            st = ic->streams[i];
1936
            if (!has_codec_parameters(st->codec))
1937
                break;
1938
            /* variable fps and no guess at the real fps */
1939
            if(   st->codec->time_base.den >= 101LL*st->codec->time_base.num
1940
               && duration_count[i]<20 && st->codec->codec_type == CODEC_TYPE_VIDEO)
1941
                break;
1942
            if(st->parser && st->parser->parser->split && !st->codec->extradata)
1943
                break;
1944
        }
1945
        if (i == ic->nb_streams) {
1946
            /* NOTE: if the format has no header, then we need to read
1947
               some packets to get most of the streams, so we cannot
1948
               stop here */
1949
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
1950
                /* if we found the info for all the codecs, we can stop */
1951
                ret = count;
1952
                break;
1953
            }
1954
        } else {
1955
            /* we did not get all the codec info, but we read too much data */
1956
            if (read_size >= MAX_READ_SIZE) {
1957
                ret = count;
1958
                break;
1959
            }
1960
        }
1961

    
1962
        /* NOTE: a new stream can be added there if no header in file
1963
           (AVFMTCTX_NOHEADER) */
1964
        ret = av_read_frame_internal(ic, &pkt1);
1965
        if (ret < 0) {
1966
            /* EOF or error */
1967
            ret = -1; /* we could not have all the codec parameters before EOF */
1968
            for(i=0;i<ic->nb_streams;i++) {
1969
                st = ic->streams[i];
1970
                if (!has_codec_parameters(st->codec)){
1971
                    char buf[256];
1972
                    avcodec_string(buf, sizeof(buf), st->codec, 0);
1973
                    av_log(ic, AV_LOG_INFO, "Could not find codec parameters (%s)\n", buf);
1974
                } else {
1975
                    ret = 0;
1976
                }
1977
            }
1978
            break;
1979
        }
1980

    
1981
        pktl = av_mallocz(sizeof(AVPacketList));
1982
        if (!pktl) {
1983
            ret = AVERROR_NOMEM;
1984
            break;
1985
        }
1986

    
1987
        /* add the packet in the buffered packet list */
1988
        *ppktl = pktl;
1989
        ppktl = &pktl->next;
1990

    
1991
        pkt = &pktl->pkt;
1992
        *pkt = pkt1;
1993

    
1994
        /* duplicate the packet */
1995
        if (av_dup_packet(pkt) < 0) {
1996
                ret = AVERROR_NOMEM;
1997
                break;
1998
        }
1999

    
2000
        read_size += pkt->size;
2001

    
2002
        st = ic->streams[pkt->stream_index];
2003
        st->codec_info_duration += pkt->duration;
2004
        if (pkt->duration != 0)
2005
            st->codec_info_nb_frames++;
2006

    
2007
        {
2008
            int index= pkt->stream_index;
2009
            int64_t last= last_dts[index];
2010
            int64_t duration= pkt->dts - last;
2011

    
2012
            if(pkt->dts != AV_NOPTS_VALUE && last != AV_NOPTS_VALUE && duration>0){
2013
                if(duration*duration_count[index]*10/9 < duration_sum[index]){
2014
                    duration_sum[index]= duration;
2015
                    duration_count[index]=1;
2016
                }else{
2017
                    int factor= av_rescale(duration, duration_count[index], duration_sum[index]);
2018
                    duration_sum[index] += duration;
2019
                    duration_count[index]+= factor;
2020
                }
2021
                if(st->codec_info_nb_frames == 0 && 0)
2022
                    st->codec_info_duration += duration;
2023
            }
2024
            last_dts[pkt->stream_index]= pkt->dts;
2025
        }
2026
        if(st->parser && st->parser->parser->split && !st->codec->extradata){
2027
            int i= st->parser->parser->split(st->codec, pkt->data, pkt->size);
2028
            if(i){
2029
                st->codec->extradata_size= i;
2030
                st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
2031
                memcpy(st->codec->extradata, pkt->data, st->codec->extradata_size);
2032
                memset(st->codec->extradata + i, 0, FF_INPUT_BUFFER_PADDING_SIZE);
2033
            }
2034
        }
2035

    
2036
        /* if still no information, we try to open the codec and to
2037
           decompress the frame. We try to avoid that in most cases as
2038
           it takes longer and uses more memory. For MPEG4, we need to
2039
           decompress for Quicktime. */
2040
        if (!has_codec_parameters(st->codec) /*&&
2041
            (st->codec->codec_id == CODEC_ID_FLV1 ||
2042
             st->codec->codec_id == CODEC_ID_H264 ||
2043
             st->codec->codec_id == CODEC_ID_H263 ||
2044
             st->codec->codec_id == CODEC_ID_H261 ||
2045
             st->codec->codec_id == CODEC_ID_VORBIS ||
2046
             st->codec->codec_id == CODEC_ID_MJPEG ||
2047
             st->codec->codec_id == CODEC_ID_PNG ||
2048
             st->codec->codec_id == CODEC_ID_PAM ||
2049
             st->codec->codec_id == CODEC_ID_PGM ||
2050
             st->codec->codec_id == CODEC_ID_PGMYUV ||
2051
             st->codec->codec_id == CODEC_ID_PBM ||
2052
             st->codec->codec_id == CODEC_ID_PPM ||
2053
             st->codec->codec_id == CODEC_ID_SHORTEN ||
2054
             (st->codec->codec_id == CODEC_ID_MPEG4 && !st->need_parsing))*/)
2055
            try_decode_frame(st, pkt->data, pkt->size);
2056

    
2057
        if (av_rescale_q(st->codec_info_duration, st->time_base, AV_TIME_BASE_Q) >= MAX_STREAM_DURATION) {
2058
            break;
2059
        }
2060
        count++;
2061
    }
2062

    
2063
    // close codecs which where opened in try_decode_frame()
2064
    for(i=0;i<ic->nb_streams;i++) {
2065
        st = ic->streams[i];
2066
        if(st->codec->codec)
2067
            avcodec_close(st->codec);
2068
    }
2069
    for(i=0;i<ic->nb_streams;i++) {
2070
        st = ic->streams[i];
2071
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2072
            if(st->codec->codec_id == CODEC_ID_RAWVIDEO && !st->codec->codec_tag && !st->codec->bits_per_sample)
2073
                st->codec->codec_tag= avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
2074

    
2075
            if(duration_count[i] && st->codec->time_base.num*101LL <= st->codec->time_base.den &&
2076
               st->time_base.num*duration_sum[i]/duration_count[i]*101LL > st->time_base.den){
2077
                int64_t num, den, error, best_error;
2078

    
2079
                num= st->time_base.den*duration_count[i];
2080
                den= st->time_base.num*duration_sum[i];
2081

    
2082
                best_error= INT64_MAX;
2083
                for(j=1; j<60*12; j++){
2084
                    error= ABS(1001*12*num - 1001*j*den);
2085
                    if(error < best_error){
2086
                        best_error= error;
2087
                        av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j, 12, INT_MAX);
2088
                    }
2089
                }
2090
                for(j=24; j<=30; j+=6){
2091
                    error= ABS(1001*12*num - 1000*12*j*den);
2092
                    if(error < best_error){
2093
                        best_error= error;
2094
                        av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, j*1000, 1001, INT_MAX);
2095
                    }
2096
                }
2097
            }
2098

    
2099
            /* set real frame rate info */
2100
            /* compute the real frame rate for telecine */
2101
            if ((st->codec->codec_id == CODEC_ID_MPEG1VIDEO ||
2102
                 st->codec->codec_id == CODEC_ID_MPEG2VIDEO) &&
2103
                st->codec->sub_id == 2) {
2104
                if (st->codec_info_nb_frames >= 20) {
2105
                    float coded_frame_rate, est_frame_rate;
2106
                    est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) /
2107
                        (double)st->codec_info_duration ;
2108
                    coded_frame_rate = 1.0/av_q2d(st->codec->time_base);
2109
#if 0
2110
                    printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n",
2111
                           coded_frame_rate, est_frame_rate);
2112
#endif
2113
                    /* if we detect that it could be a telecine, we
2114
                       signal it. It would be better to do it at a
2115
                       higher level as it can change in a film */
2116
                    if (coded_frame_rate >= 24.97 &&
2117
                        (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
2118
                        st->r_frame_rate = (AVRational){24000, 1001};
2119
                    }
2120
                }
2121
            }
2122
            /* if no real frame rate, use the codec one */
2123
            if (!st->r_frame_rate.num){
2124
                st->r_frame_rate.num = st->codec->time_base.den;
2125
                st->r_frame_rate.den = st->codec->time_base.num;
2126
            }
2127
        }
2128
    }
2129

    
2130
    av_estimate_timings(ic);
2131
#if 0
2132
    /* correct DTS for b frame streams with no timestamps */
2133
    for(i=0;i<ic->nb_streams;i++) {
2134
        st = ic->streams[i];
2135
        if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
2136
            if(b-frames){
2137
                ppktl = &ic->packet_buffer;
2138
                while(ppkt1){
2139
                    if(ppkt1->stream_index != i)
2140
                        continue;
2141
                    if(ppkt1->pkt->dts < 0)
2142
                        break;
2143
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
2144
                        break;
2145
                    ppkt1->pkt->dts -= delta;
2146
                    ppkt1= ppkt1->next;
2147
                }
2148
                if(ppkt1)
2149
                    continue;
2150
                st->cur_dts -= delta;
2151
            }
2152
        }
2153
    }
2154
#endif
2155
    return ret;
2156
}
2157

    
2158
/*******************************************************/
2159

    
2160
/**
2161
 * start playing a network based stream (e.g. RTSP stream) at the
2162
 * current position
2163
 */
2164
int av_read_play(AVFormatContext *s)
2165
{
2166
    if (!s->iformat->read_play)
2167
        return AVERROR_NOTSUPP;
2168
    return s->iformat->read_play(s);
2169
}
2170

    
2171
/**
2172
 * Pause a network based stream (e.g. RTSP stream).
2173
 *
2174
 * Use av_read_play() to resume it.
2175
 */
2176
int av_read_pause(AVFormatContext *s)
2177
{
2178
    if (!s->iformat->read_pause)
2179
        return AVERROR_NOTSUPP;
2180
    return s->iformat->read_pause(s);
2181
}
2182

    
2183
/**
2184
 * Close a media file (but not its codecs).
2185
 *
2186
 * @param s media file handle
2187
 */
2188
void av_close_input_file(AVFormatContext *s)
2189
{
2190
    int i, must_open_file;
2191
    AVStream *st;
2192

    
2193
    /* free previous packet */
2194
    if (s->cur_st && s->cur_st->parser)
2195
        av_free_packet(&s->cur_pkt);
2196

    
2197
    if (s->iformat->read_close)
2198
        s->iformat->read_close(s);
2199
    for(i=0;i<s->nb_streams;i++) {
2200
        /* free all data in a stream component */
2201
        st = s->streams[i];
2202
        if (st->parser) {
2203
            av_parser_close(st->parser);
2204
        }
2205
        av_free(st->index_entries);
2206
        av_free(st->codec->extradata);
2207
        av_free(st->codec);
2208
        av_free(st);
2209
    }
2210
    flush_packet_queue(s);
2211
    must_open_file = 1;
2212
    if (s->iformat->flags & AVFMT_NOFILE) {
2213
        must_open_file = 0;
2214
    }
2215
    if (must_open_file) {
2216
        url_fclose(&s->pb);
2217
    }
2218
    av_freep(&s->priv_data);
2219
    av_free(s);
2220
}
2221

    
2222
/**
2223
 * Add a new stream to a media file.
2224
 *
2225
 * Can only be called in the read_header() function. If the flag
2226
 * AVFMTCTX_NOHEADER is in the format context, then new streams
2227
 * can be added in read_packet too.
2228
 *
2229
 * @param s media file handle
2230
 * @param id file format dependent stream id
2231
 */
2232
AVStream *av_new_stream(AVFormatContext *s, int id)
2233
{
2234
    AVStream *st;
2235
    int i;
2236

    
2237
    if (s->nb_streams >= MAX_STREAMS)
2238
        return NULL;
2239

    
2240
    st = av_mallocz(sizeof(AVStream));
2241
    if (!st)
2242
        return NULL;
2243

    
2244
    st->codec= avcodec_alloc_context();
2245
    if (s->iformat) {
2246
        /* no default bitrate if decoding */
2247
        st->codec->bit_rate = 0;
2248
    }
2249
    st->index = s->nb_streams;
2250
    st->id = id;
2251
    st->start_time = AV_NOPTS_VALUE;
2252
    st->duration = AV_NOPTS_VALUE;
2253
    st->cur_dts = AV_NOPTS_VALUE;
2254

    
2255
    /* default pts settings is MPEG like */
2256
    av_set_pts_info(st, 33, 1, 90000);
2257
    st->last_IP_pts = AV_NOPTS_VALUE;
2258
    for(i=0; i<MAX_REORDER_DELAY+1; i++)
2259
        st->pts_buffer[i]= AV_NOPTS_VALUE;
2260

    
2261
    s->streams[s->nb_streams++] = st;
2262
    return st;
2263
}
2264

    
2265
/************************************************************/
2266
/* output media file */
2267

    
2268
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
2269
{
2270
    int ret;
2271

    
2272
    if (s->oformat->priv_data_size > 0) {
2273
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
2274
        if (!s->priv_data)
2275
            return AVERROR_NOMEM;
2276
    } else
2277
        s->priv_data = NULL;
2278

    
2279
    if (s->oformat->set_parameters) {
2280
        ret = s->oformat->set_parameters(s, ap);
2281
        if (ret < 0)
2282
            return ret;
2283
    }
2284
    return 0;
2285
}
2286

    
2287
/**
2288
 * allocate the stream private data and write the stream header to an
2289
 * output media file
2290
 *
2291
 * @param s media file handle
2292
 * @return 0 if OK. AVERROR_xxx if error.
2293
 */
2294
int av_write_header(AVFormatContext *s)
2295
{
2296
    int ret, i;
2297
    AVStream *st;
2298

    
2299
    // some sanity checks
2300
    for(i=0;i<s->nb_streams;i++) {
2301
        st = s->streams[i];
2302

    
2303
        switch (st->codec->codec_type) {
2304
        case CODEC_TYPE_AUDIO:
2305
            if(st->codec->sample_rate<=0){
2306
                av_log(s, AV_LOG_ERROR, "sample rate not set\n");
2307
                return -1;
2308
            }
2309
            break;
2310
        case CODEC_TYPE_VIDEO:
2311
            if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?
2312
                av_log(s, AV_LOG_ERROR, "time base not set\n");
2313
                return -1;
2314
            }
2315
            if(st->codec->width<=0 || st->codec->height<=0){
2316
                av_log(s, AV_LOG_ERROR, "dimensions not set\n");
2317
                return -1;
2318
            }
2319
            break;
2320
        }
2321
    }
2322

    
2323
    if(s->oformat->write_header){
2324
        ret = s->oformat->write_header(s);
2325
        if (ret < 0)
2326
            return ret;
2327
    }
2328

    
2329
    /* init PTS generation */
2330
    for(i=0;i<s->nb_streams;i++) {
2331
        int64_t den = AV_NOPTS_VALUE;
2332
        st = s->streams[i];
2333

    
2334
        switch (st->codec->codec_type) {
2335
        case CODEC_TYPE_AUDIO:
2336
            den = (int64_t)st->time_base.num * st->codec->sample_rate;
2337
            break;
2338
        case CODEC_TYPE_VIDEO:
2339
            den = (int64_t)st->time_base.num * st->codec->time_base.den;
2340
            break;
2341
        default:
2342
            break;
2343
        }
2344
        if (den != AV_NOPTS_VALUE) {
2345
            if (den <= 0)
2346
                return AVERROR_INVALIDDATA;
2347
            av_frac_init(&st->pts, 0, 0, den);
2348
        }
2349
    }
2350
    return 0;
2351
}
2352

    
2353
//FIXME merge with compute_pkt_fields
2354
static int compute_pkt_fields2(AVStream *st, AVPacket *pkt){
2355
    int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);
2356
    int num, den, frame_size, i;
2357

    
2358
//    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts:%lld dts:%lld cur_dts:%lld b:%d size:%d st:%d\n", pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);
2359

    
2360
/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
2361
        return -1;*/
2362

    
2363
    /* duration field */
2364
    if (pkt->duration == 0) {
2365
        compute_frame_duration(&num, &den, st, NULL, pkt);
2366
        if (den && num) {
2367
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
2368
        }
2369
    }
2370

    
2371
    //XXX/FIXME this is a temporary hack until all encoders output pts
2372
    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){
2373
        pkt->dts=
2374
//        pkt->pts= st->cur_dts;
2375
        pkt->pts= st->pts.val;
2376
    }
2377

    
2378
    //calculate dts from pts
2379
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
2380
        st->pts_buffer[0]= pkt->pts;
2381
        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)
2382
            st->pts_buffer[i]= (i-delay-1) * pkt->duration;
2383
        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)
2384
            SWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);
2385

    
2386
        pkt->dts= st->pts_buffer[0];
2387
    }
2388

    
2389
    if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && st->cur_dts >= pkt->dts){
2390
        av_log(NULL, AV_LOG_ERROR, "error, non monotone timestamps %"PRId64" >= %"PRId64"\n", st->cur_dts, pkt->dts);
2391
        return -1;
2392
    }
2393
    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){
2394
        av_log(NULL, AV_LOG_ERROR, "error, pts < dts\n");
2395
        return -1;
2396
    }
2397

    
2398
//    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
2399
    st->cur_dts= pkt->dts;
2400
    st->pts.val= pkt->dts;
2401

    
2402
    /* update pts */
2403
    switch (st->codec->codec_type) {
2404
    case CODEC_TYPE_AUDIO:
2405
        frame_size = get_audio_frame_size(st->codec, pkt->size);
2406

    
2407
        /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
2408
           but it would be better if we had the real timestamps from the encoder */
2409
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2410
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2411
        }
2412
        break;
2413
    case CODEC_TYPE_VIDEO:
2414
        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);
2415
        break;
2416
    default:
2417
        break;
2418
    }
2419
    return 0;
2420
}
2421

    
2422
static void truncate_ts(AVStream *st, AVPacket *pkt){
2423
    int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2424

    
2425
//    if(pkt->dts < 0)
2426
//        pkt->dts= 0;  //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
2427

    
2428
    pkt->pts &= pts_mask;
2429
    pkt->dts &= pts_mask;
2430
}
2431

    
2432
/**
2433
 * Write a packet to an output media file.
2434
 *
2435
 * The packet shall contain one audio or video frame.
2436
 *
2437
 * @param s media file handle
2438
 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2439
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2440
 */
2441
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2442
{
2443
    int ret;
2444

    
2445
    ret=compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2446
    if(ret<0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2447
        return ret;
2448

    
2449
    truncate_ts(s->streams[pkt->stream_index], pkt);
2450

    
2451
    ret= s->oformat->write_packet(s, pkt);
2452
    if(!ret)
2453
        ret= url_ferror(&s->pb);
2454
    return ret;
2455
}
2456

    
2457
/**
2458
 * Interleave a packet per DTS in an output media file.
2459
 *
2460
 * Packets with pkt->destruct == av_destruct_packet will be freed inside this function,
2461
 * so they cannot be used after it, note calling av_free_packet() on them is still safe.
2462
 *
2463
 * @param s media file handle
2464
 * @param out the interleaved packet will be output here
2465
 * @param in the input packet
2466
 * @param flush 1 if no further packets are available as input and all
2467
 *              remaining packets should be output
2468
 * @return 1 if a packet was output, 0 if no packet could be output,
2469
 *         < 0 if an error occured
2470
 */
2471
int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2472
    AVPacketList *pktl, **next_point, *this_pktl;
2473
    int stream_count=0;
2474
    int streams[MAX_STREAMS];
2475

    
2476
    if(pkt){
2477
        AVStream *st= s->streams[ pkt->stream_index];
2478

    
2479
//        assert(pkt->destruct != av_destruct_packet); //FIXME
2480

    
2481
        this_pktl = av_mallocz(sizeof(AVPacketList));
2482
        this_pktl->pkt= *pkt;
2483
        if(pkt->destruct == av_destruct_packet)
2484
            pkt->destruct= NULL; // non shared -> must keep original from being freed
2485
        else
2486
            av_dup_packet(&this_pktl->pkt);  //shared -> must dup
2487

    
2488
        next_point = &s->packet_buffer;
2489
        while(*next_point){
2490
            AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2491
            int64_t left=  st2->time_base.num * (int64_t)st ->time_base.den;
2492
            int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2493
            if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2494
                break;
2495
            next_point= &(*next_point)->next;
2496
        }
2497
        this_pktl->next= *next_point;
2498
        *next_point= this_pktl;
2499
    }
2500

    
2501
    memset(streams, 0, sizeof(streams));
2502
    pktl= s->packet_buffer;
2503
    while(pktl){
2504
//av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2505
        if(streams[ pktl->pkt.stream_index ] == 0)
2506
            stream_count++;
2507
        streams[ pktl->pkt.stream_index ]++;
2508
        pktl= pktl->next;
2509
    }
2510

    
2511
    if(s->nb_streams == stream_count || (flush && stream_count)){
2512
        pktl= s->packet_buffer;
2513
        *out= pktl->pkt;
2514

    
2515
        s->packet_buffer= pktl->next;
2516
        av_freep(&pktl);
2517
        return 1;
2518
    }else{
2519
        av_init_packet(out);
2520
        return 0;
2521
    }
2522
}
2523

    
2524
/**
2525
 * Interleaves a AVPacket correctly so it can be muxed.
2526
 * @param out the interleaved packet will be output here
2527
 * @param in the input packet
2528
 * @param flush 1 if no further packets are available as input and all
2529
 *              remaining packets should be output
2530
 * @return 1 if a packet was output, 0 if no packet could be output,
2531
 *         < 0 if an error occured
2532
 */
2533
static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2534
    if(s->oformat->interleave_packet)
2535
        return s->oformat->interleave_packet(s, out, in, flush);
2536
    else
2537
        return av_interleave_packet_per_dts(s, out, in, flush);
2538
}
2539

    
2540
/**
2541
 * Writes a packet to an output media file ensuring correct interleaving.
2542
 *
2543
 * The packet must contain one audio or video frame.
2544
 * If the packets are already correctly interleaved the application should
2545
 * call av_write_frame() instead as its slightly faster, its also important
2546
 * to keep in mind that completly non interleaved input will need huge amounts
2547
 * of memory to interleave with this, so its prefereable to interleave at the
2548
 * demuxer level
2549
 *
2550
 * @param s media file handle
2551
 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2552
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2553
 */
2554
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2555
    AVStream *st= s->streams[ pkt->stream_index];
2556

    
2557
    //FIXME/XXX/HACK drop zero sized packets
2558
    if(st->codec->codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2559
        return 0;
2560

    
2561
//av_log(NULL, AV_LOG_DEBUG, "av_interleaved_write_frame %d %Ld %Ld\n", pkt->size, pkt->dts, pkt->pts);
2562
    if(compute_pkt_fields2(st, pkt) < 0 && !(s->oformat->flags & AVFMT_NOTIMESTAMPS))
2563
        return -1;
2564

    
2565
    if(pkt->dts == AV_NOPTS_VALUE)
2566
        return -1;
2567

    
2568
    for(;;){
2569
        AVPacket opkt;
2570
        int ret= av_interleave_packet(s, &opkt, pkt, 0);
2571
        if(ret<=0) //FIXME cleanup needed for ret<0 ?
2572
            return ret;
2573

    
2574
        truncate_ts(s->streams[opkt.stream_index], &opkt);
2575
        ret= s->oformat->write_packet(s, &opkt);
2576

    
2577
        av_free_packet(&opkt);
2578
        pkt= NULL;
2579

    
2580
        if(ret<0)
2581
            return ret;
2582
        if(url_ferror(&s->pb))
2583
            return url_ferror(&s->pb);
2584
    }
2585
}
2586

    
2587
/**
2588
 * @brief Write the stream trailer to an output media file and
2589
 *        free the file private data.
2590
 *
2591
 * @param s media file handle
2592
 * @return 0 if OK. AVERROR_xxx if error.
2593
 */
2594
int av_write_trailer(AVFormatContext *s)
2595
{
2596
    int ret, i;
2597

    
2598
    for(;;){
2599
        AVPacket pkt;
2600
        ret= av_interleave_packet(s, &pkt, NULL, 1);
2601
        if(ret<0) //FIXME cleanup needed for ret<0 ?
2602
            goto fail;
2603
        if(!ret)
2604
            break;
2605

    
2606
        truncate_ts(s->streams[pkt.stream_index], &pkt);
2607
        ret= s->oformat->write_packet(s, &pkt);
2608

    
2609
        av_free_packet(&pkt);
2610

    
2611
        if(ret<0)
2612
            goto fail;
2613
        if(url_ferror(&s->pb))
2614
            goto fail;
2615
    }
2616

    
2617
    if(s->oformat->write_trailer)
2618
        ret = s->oformat->write_trailer(s);
2619
fail:
2620
    if(ret == 0)
2621
       ret=url_ferror(&s->pb);
2622
    for(i=0;i<s->nb_streams;i++)
2623
        av_freep(&s->streams[i]->priv_data);
2624
    av_freep(&s->priv_data);
2625
    return ret;
2626
}
2627

    
2628
/* "user interface" functions */
2629

    
2630
void dump_format(AVFormatContext *ic,
2631
                 int index,
2632
                 const char *url,
2633
                 int is_output)
2634
{
2635
    int i, flags;
2636
    char buf[256];
2637

    
2638
    av_log(NULL, AV_LOG_INFO, "%s #%d, %s, %s '%s':\n",
2639
            is_output ? "Output" : "Input",
2640
            index,
2641
            is_output ? ic->oformat->name : ic->iformat->name,
2642
            is_output ? "to" : "from", url);
2643
    if (!is_output) {
2644
        av_log(NULL, AV_LOG_INFO, "  Duration: ");
2645
        if (ic->duration != AV_NOPTS_VALUE) {
2646
            int hours, mins, secs, us;
2647
            secs = ic->duration / AV_TIME_BASE;
2648
            us = ic->duration % AV_TIME_BASE;
2649
            mins = secs / 60;
2650
            secs %= 60;
2651
            hours = mins / 60;
2652
            mins %= 60;
2653
            av_log(NULL, AV_LOG_INFO, "%02d:%02d:%02d.%01d", hours, mins, secs,
2654
                   (10 * us) / AV_TIME_BASE);
2655
        } else {
2656
            av_log(NULL, AV_LOG_INFO, "N/A");
2657
        }
2658
        if (ic->start_time != AV_NOPTS_VALUE) {
2659
            int secs, us;
2660
            av_log(NULL, AV_LOG_INFO, ", start: ");
2661
            secs = ic->start_time / AV_TIME_BASE;
2662
            us = ic->start_time % AV_TIME_BASE;
2663
            av_log(NULL, AV_LOG_INFO, "%d.%06d",
2664
                   secs, (int)av_rescale(us, 1000000, AV_TIME_BASE));
2665
        }
2666
        av_log(NULL, AV_LOG_INFO, ", bitrate: ");
2667
        if (ic->bit_rate) {
2668
            av_log(NULL, AV_LOG_INFO,"%d kb/s", ic->bit_rate / 1000);
2669
        } else {
2670
            av_log(NULL, AV_LOG_INFO, "N/A");
2671
        }
2672
        av_log(NULL, AV_LOG_INFO, "\n");
2673
    }
2674
    for(i=0;i<ic->nb_streams;i++) {
2675
        AVStream *st = ic->streams[i];
2676
        int g= ff_gcd(st->time_base.num, st->time_base.den);
2677
        avcodec_string(buf, sizeof(buf), st->codec, is_output);
2678
        av_log(NULL, AV_LOG_INFO, "  Stream #%d.%d", index, i);
2679
        /* the pid is an important information, so we display it */
2680
        /* XXX: add a generic system */
2681
        if (is_output)
2682
            flags = ic->oformat->flags;
2683
        else
2684
            flags = ic->iformat->flags;
2685
        if (flags & AVFMT_SHOW_IDS) {
2686
            av_log(NULL, AV_LOG_INFO, "[0x%x]", st->id);
2687
        }
2688
        if (strlen(st->language) > 0) {
2689
            av_log(NULL, AV_LOG_INFO, "(%s)", st->language);
2690
        }
2691
        av_log(NULL, AV_LOG_DEBUG, ", %d/%d", st->time_base.num/g, st->time_base.den/g);
2692
        av_log(NULL, AV_LOG_INFO, ": %s", buf);
2693
        if(st->codec->codec_type == CODEC_TYPE_VIDEO){
2694
            if(st->r_frame_rate.den && st->r_frame_rate.num)
2695
                av_log(NULL, AV_LOG_INFO, ", %5.2f fps(r)", av_q2d(st->r_frame_rate));
2696
/*            else if(st->time_base.den && st->time_base.num)
2697
                av_log(NULL, AV_LOG_INFO, ", %5.2f fps(m)", 1/av_q2d(st->time_base));*/
2698
            else
2699
                av_log(NULL, AV_LOG_INFO, ", %5.2f fps(c)", 1/av_q2d(st->codec->time_base));
2700
        }
2701
        av_log(NULL, AV_LOG_INFO, "\n");
2702
    }
2703
}
2704

    
2705
typedef struct {
2706
    const char *abv;
2707
    int width, height;
2708
    int frame_rate, frame_rate_base;
2709
} AbvEntry;
2710

    
2711
static AbvEntry frame_abvs[] = {
2712
    { "ntsc",      720, 480, 30000, 1001 },
2713
    { "pal",       720, 576,    25,    1 },
2714
    { "qntsc",     352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2715
    { "qpal",      352, 288,    25,    1 }, /* VCD compliant pal */
2716
    { "sntsc",     640, 480, 30000, 1001 }, /* square pixel ntsc */
2717
    { "spal",      768, 576,    25,    1 }, /* square pixel pal */
2718
    { "film",      352, 240,    24,    1 },
2719
    { "ntsc-film", 352, 240, 24000, 1001 },
2720
    { "sqcif",     128,  96,     0,    0 },
2721
    { "qcif",      176, 144,     0,    0 },
2722
    { "cif",       352, 288,     0,    0 },
2723
    { "4cif",      704, 576,     0,    0 },
2724
};
2725

    
2726
/**
2727
 * parses width and height out of string str.
2728
 */
2729
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2730
{
2731
    int i;
2732
    int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2733
    const char *p;
2734
    int frame_width = 0, frame_height = 0;
2735

    
2736
    for(i=0;i<n;i++) {
2737
        if (!strcmp(frame_abvs[i].abv, str)) {
2738
            frame_width = frame_abvs[i].width;
2739
            frame_height = frame_abvs[i].height;
2740
            break;
2741
        }
2742
    }
2743
    if (i == n) {
2744
        p = str;
2745
        frame_width = strtol(p, (char **)&p, 10);
2746
        if (*p)
2747
            p++;
2748
        frame_height = strtol(p, (char **)&p, 10);
2749
    }
2750
    if (frame_width <= 0 || frame_height <= 0)
2751
        return -1;
2752
    *width_ptr = frame_width;
2753
    *height_ptr = frame_height;
2754
    return 0;
2755
}
2756

    
2757
/**
2758
 * Converts frame rate from string to a fraction.
2759
 *
2760
 * First we try to get an exact integer or fractional frame rate.
2761
 * If this fails we convert the frame rate to a double and return
2762
 * an approximate fraction using the DEFAULT_FRAME_RATE_BASE.
2763
 */
2764
int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2765
{
2766
    int i;
2767
    char* cp;
2768

    
2769
    /* First, we check our abbreviation table */
2770
    for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2771
         if (!strcmp(frame_abvs[i].abv, arg)) {
2772
             *frame_rate = frame_abvs[i].frame_rate;
2773
             *frame_rate_base = frame_abvs[i].frame_rate_base;
2774
             return 0;
2775
         }
2776

    
2777
    /* Then, we try to parse it as fraction */
2778
    cp = strchr(arg, '/');
2779
    if (!cp)
2780
        cp = strchr(arg, ':');
2781
    if (cp) {
2782
        char* cpp;
2783
        *frame_rate = strtol(arg, &cpp, 10);
2784
        if (cpp != arg || cpp == cp)
2785
            *frame_rate_base = strtol(cp+1, &cpp, 10);
2786
        else
2787
           *frame_rate = 0;
2788
    }
2789
    else {
2790
        /* Finally we give up and parse it as double */
2791
        AVRational time_base = av_d2q(strtod(arg, 0), DEFAULT_FRAME_RATE_BASE);
2792
        *frame_rate_base = time_base.den;
2793
        *frame_rate = time_base.num;
2794
    }
2795
    if (!*frame_rate || !*frame_rate_base)
2796
        return -1;
2797
    else
2798
        return 0;
2799
}
2800

    
2801
/**
2802
 * Converts date string to number of seconds since Jan 1st, 1970.
2803
 *
2804
 * @code
2805
 * Syntax:
2806
 * - If not a duration:
2807
 *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2808
 * Time is localtime unless Z is suffixed to the end. In this case GMT
2809
 * Return the date in micro seconds since 1970
2810
 *
2811
 * - If a duration:
2812
 *  HH[:MM[:SS[.m...]]]
2813
 *  S+[.m...]
2814
 * @endcode
2815
 */
2816
#ifndef CONFIG_WINCE
2817
int64_t parse_date(const char *datestr, int duration)
2818
{
2819
    const char *p;
2820
    int64_t t;
2821
    struct tm dt;
2822
    int i;
2823
    static const char *date_fmt[] = {
2824
        "%Y-%m-%d",
2825
        "%Y%m%d",
2826
    };
2827
    static const char *time_fmt[] = {
2828
        "%H:%M:%S",
2829
        "%H%M%S",
2830
    };
2831
    const char *q;
2832
    int is_utc, len;
2833
    char lastch;
2834
    int negative = 0;
2835

    
2836
#undef time
2837
    time_t now = time(0);
2838

    
2839
    len = strlen(datestr);
2840
    if (len > 0)
2841
        lastch = datestr[len - 1];
2842
    else
2843
        lastch = '\0';
2844
    is_utc = (lastch == 'z' || lastch == 'Z');
2845

    
2846
    memset(&dt, 0, sizeof(dt));
2847

    
2848
    p = datestr;
2849
    q = NULL;
2850
    if (!duration) {
2851
        for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2852
            q = small_strptime(p, date_fmt[i], &dt);
2853
            if (q) {
2854
                break;
2855
            }
2856
        }
2857

    
2858
        if (!q) {
2859
            if (is_utc) {
2860
                dt = *gmtime(&now);
2861
            } else {
2862
                dt = *localtime(&now);
2863
            }
2864
            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2865
        } else {
2866
            p = q;
2867
        }
2868

    
2869
        if (*p == 'T' || *p == 't' || *p == ' ')
2870
            p++;
2871

    
2872
        for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2873
            q = small_strptime(p, time_fmt[i], &dt);
2874
            if (q) {
2875
                break;
2876
            }
2877
        }
2878
    } else {
2879
        if (p[0] == '-') {
2880
            negative = 1;
2881
            ++p;
2882
        }
2883
        q = small_strptime(p, time_fmt[0], &dt);
2884
        if (!q) {
2885
            dt.tm_sec = strtol(p, (char **)&q, 10);
2886
            dt.tm_min = 0;
2887
            dt.tm_hour = 0;
2888
        }
2889
    }
2890

    
2891
    /* Now we have all the fields that we can get */
2892
    if (!q) {
2893
        if (duration)
2894
            return 0;
2895
        else
2896
            return now * int64_t_C(1000000);
2897
    }
2898

    
2899
    if (duration) {
2900
        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2901
    } else {
2902
        dt.tm_isdst = -1;       /* unknown */
2903
        if (is_utc) {
2904
            t = mktimegm(&dt);
2905
        } else {
2906
            t = mktime(&dt);
2907
        }
2908
    }
2909

    
2910
    t *= 1000000;
2911

    
2912
    if (*q == '.') {
2913
        int val, n;
2914
        q++;
2915
        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2916
            if (!isdigit(*q))
2917
                break;
2918
            val += n * (*q - '0');
2919
        }
2920
        t += val;
2921
    }
2922
    return negative ? -t : t;
2923
}
2924
#endif /* CONFIG_WINCE */
2925

    
2926
/**
2927
 * Attempts to find a specific tag in a URL.
2928
 *
2929
 * syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done.
2930
 * Return 1 if found.
2931
 */
2932
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2933
{
2934
    const char *p;
2935
    char tag[128], *q;
2936

    
2937
    p = info;
2938
    if (*p == '?')
2939
        p++;
2940
    for(;;) {
2941
        q = tag;
2942
        while (*p != '\0' && *p != '=' && *p != '&') {
2943
            if ((q - tag) < sizeof(tag) - 1)
2944
                *q++ = *p;
2945
            p++;
2946
        }
2947
        *q = '\0';
2948
        q = arg;
2949
        if (*p == '=') {
2950
            p++;
2951
            while (*p != '&' && *p != '\0') {
2952
                if ((q - arg) < arg_size - 1) {
2953
                    if (*p == '+')
2954
                        *q++ = ' ';
2955
                    else
2956
                        *q++ = *p;
2957
                }
2958
                p++;
2959
            }
2960
            *q = '\0';
2961
        }
2962
        if (!strcmp(tag, tag1))
2963
            return 1;
2964
        if (*p != '&')
2965
            break;
2966
        p++;
2967
    }
2968
    return 0;
2969
}
2970

    
2971
/**
2972
 * Returns in 'buf' the path with '%d' replaced by number.
2973

2974
 * Also handles the '%0nd' format where 'n' is the total number
2975
 * of digits and '%%'.
2976
 *
2977
 * @param buf destination buffer
2978
 * @param buf_size destination buffer size
2979
 * @param path numbered sequence string
2980
 * @number frame number
2981
 * @return 0 if OK, -1 if format error.
2982
 */
2983
int av_get_frame_filename(char *buf, int buf_size,
2984
                          const char *path, int number)
2985
{
2986
    const char *p;
2987
    char *q, buf1[20], c;
2988
    int nd, len, percentd_found;
2989

    
2990
    q = buf;
2991
    p = path;
2992
    percentd_found = 0;
2993
    for(;;) {
2994
        c = *p++;
2995
        if (c == '\0')
2996
            break;
2997
        if (c == '%') {
2998
            do {
2999
                nd = 0;
3000
                while (isdigit(*p)) {
3001
                    nd = nd * 10 + *p++ - '0';
3002
                }
3003
                c = *p++;
3004
            } while (isdigit(c));
3005

    
3006
            switch(c) {
3007
            case '%':
3008
                goto addchar;
3009
            case 'd':
3010
                if (percentd_found)
3011
                    goto fail;
3012
                percentd_found = 1;
3013
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
3014
                len = strlen(buf1);
3015
                if ((q - buf + len) > buf_size - 1)
3016
                    goto fail;
3017
                memcpy(q, buf1, len);
3018
                q += len;
3019
                break;
3020
            default:
3021
                goto fail;
3022
            }
3023
        } else {
3024
        addchar:
3025
            if ((q - buf) < buf_size - 1)
3026
                *q++ = c;
3027
        }
3028
    }
3029
    if (!percentd_found)
3030
        goto fail;
3031
    *q = '\0';
3032
    return 0;
3033
 fail:
3034
    *q = '\0';
3035
    return -1;
3036
}
3037

    
3038
/**
3039
 * Print  nice hexa dump of a buffer
3040
 * @param f stream for output
3041
 * @param buf buffer
3042
 * @param size buffer size
3043
 */
3044
void av_hex_dump(FILE *f, uint8_t *buf, int size)
3045
{
3046
    int len, i, j, c;
3047

    
3048
    for(i=0;i<size;i+=16) {
3049
        len = size - i;
3050
        if (len > 16)
3051
            len = 16;
3052
        fprintf(f, "%08x ", i);
3053
        for(j=0;j<16;j++) {
3054
            if (j < len)
3055
                fprintf(f, " %02x", buf[i+j]);
3056
            else
3057
                fprintf(f, "   ");
3058
        }
3059
        fprintf(f, " ");
3060
        for(j=0;j<len;j++) {
3061
            c = buf[i+j];
3062
            if (c < ' ' || c > '~')
3063
                c = '.';
3064
            fprintf(f, "%c", c);
3065
        }
3066
        fprintf(f, "\n");
3067
    }
3068
}
3069

    
3070
/**
3071
 * Print on 'f' a nice dump of a packet
3072
 * @param f stream for output
3073
 * @param pkt packet to dump
3074
 * @param dump_payload true if the payload must be displayed too
3075
 */
3076
 //FIXME needs to know the time_base
3077
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
3078
{
3079
    fprintf(f, "stream #%d:\n", pkt->stream_index);
3080
    fprintf(f, "  keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
3081
    fprintf(f, "  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
3082
    /* DTS is _always_ valid after av_read_frame() */
3083
    fprintf(f, "  dts=");
3084
    if (pkt->dts == AV_NOPTS_VALUE)
3085
        fprintf(f, "N/A");
3086
    else
3087
        fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
3088
    /* PTS may be not known if B frames are present */
3089
    fprintf(f, "  pts=");
3090
    if (pkt->pts == AV_NOPTS_VALUE)
3091
        fprintf(f, "N/A");
3092
    else
3093
        fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
3094
    fprintf(f, "\n");
3095
    fprintf(f, "  size=%d\n", pkt->size);
3096
    if (dump_payload)
3097
        av_hex_dump(f, pkt->data, pkt->size);
3098
}
3099

    
3100
void url_split(char *proto, int proto_size,
3101
               char *authorization, int authorization_size,
3102
               char *hostname, int hostname_size,
3103
               int *port_ptr,
3104
               char *path, int path_size,
3105
               const char *url)
3106
{
3107
    const char *p;
3108
    char *q;
3109
    int port;
3110

    
3111
    port = -1;
3112

    
3113
    p = url;
3114
    q = proto;
3115
    while (*p != ':' && *p != '\0') {
3116
        if ((q - proto) < proto_size - 1)
3117
            *q++ = *p;
3118
        p++;
3119
    }
3120
    if (proto_size > 0)
3121
        *q = '\0';
3122
    if (authorization_size > 0)
3123
        authorization[0] = '\0';
3124
    if (*p == '\0') {
3125
        if (proto_size > 0)
3126
            proto[0] = '\0';
3127
        if (hostname_size > 0)
3128
            hostname[0] = '\0';
3129
        p = url;
3130
    } else {
3131
        char *at,*slash; // PETR: position of '@' character and '/' character
3132

    
3133
        p++;
3134
        if (*p == '/')
3135
            p++;
3136
        if (*p == '/')
3137
            p++;
3138
        at = strchr(p,'@'); // PETR: get the position of '@'
3139
        slash = strchr(p,'/');  // PETR: get position of '/' - end of hostname
3140
        if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
3141

    
3142
        q = at ? authorization : hostname;  // PETR: if '@' exists starting with auth.
3143

    
3144
         while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
3145
            if (*p == '@') {    // PETR: passed '@'
3146
              if (authorization_size > 0)
3147
                  *q = '\0';
3148
              q = hostname;
3149
              at = NULL;
3150
            } else if (!at) {   // PETR: hostname
3151
              if ((q - hostname) < hostname_size - 1)
3152
                  *q++ = *p;
3153
            } else {
3154
              if ((q - authorization) < authorization_size - 1)
3155
                *q++ = *p;
3156
            }
3157
            p++;
3158
        }
3159
        if (hostname_size > 0)
3160
            *q = '\0';
3161
        if (*p == ':') {
3162
            p++;
3163
            port = strtoul(p, (char **)&p, 10);
3164
        }
3165
    }
3166
    if (port_ptr)
3167
        *port_ptr = port;
3168
    pstrcpy(path, path_size, p);
3169
}
3170

    
3171
/**
3172
 * Set the pts for a given stream.
3173
 *
3174
 * @param s stream
3175
 * @param pts_wrap_bits number of bits effectively used by the pts
3176
 *        (used for wrap control, 33 is the value for MPEG)
3177
 * @param pts_num numerator to convert to seconds (MPEG: 1)
3178
 * @param pts_den denominator to convert to seconds (MPEG: 90000)
3179
 */
3180
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
3181
                     int pts_num, int pts_den)
3182
{
3183
    s->pts_wrap_bits = pts_wrap_bits;
3184
    s->time_base.num = pts_num;
3185
    s->time_base.den = pts_den;
3186
}
3187

    
3188
/* fraction handling */
3189

    
3190
/**
3191
 * f = val + (num / den) + 0.5.
3192
 *
3193
 * 'num' is normalized so that it is such as 0 <= num < den.
3194
 *
3195
 * @param f fractional number
3196
 * @param val integer value
3197
 * @param num must be >= 0
3198
 * @param den must be >= 1
3199
 */
3200
static void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
3201
{
3202
    num += (den >> 1);
3203
    if (num >= den) {
3204
        val += num / den;
3205
        num = num % den;
3206
    }
3207
    f->val = val;
3208
    f->num = num;
3209
    f->den = den;
3210
}
3211

    
3212
/**
3213
 * Set f to (val + 0.5).
3214
 */
3215
static void av_frac_set(AVFrac *f, int64_t val)
3216
{
3217
    f->val = val;
3218
    f->num = f->den >> 1;
3219
}
3220

    
3221
/**
3222
 * Fractionnal addition to f: f = f + (incr / f->den).
3223
 *
3224
 * @param f fractional number
3225
 * @param incr increment, can be positive or negative
3226
 */
3227
static void av_frac_add(AVFrac *f, int64_t incr)
3228
{
3229
    int64_t num, den;
3230

    
3231
    num = f->num + incr;
3232
    den = f->den;
3233
    if (num < 0) {
3234
        f->val += num / den;
3235
        num = num % den;
3236
        if (num < 0) {
3237
            num += den;
3238
            f->val--;
3239
        }
3240
    } else if (num >= den) {
3241
        f->val += num / den;
3242
        num = num % den;
3243
    }
3244
    f->num = num;
3245
}
3246

    
3247
/**
3248
 * register a new image format
3249
 * @param img_fmt Image format descriptor
3250
 */
3251
void av_register_image_format(AVImageFormat *img_fmt)
3252
{
3253
    AVImageFormat **p;
3254

    
3255
    p = &first_image_format;
3256
    while (*p != NULL) p = &(*p)->next;
3257
    *p = img_fmt;
3258
    img_fmt->next = NULL;
3259
}
3260

    
3261
/**
3262
 * Guesses image format based on data in the image.
3263
 */
3264
AVImageFormat *av_probe_image_format(AVProbeData *pd)
3265
{
3266
    AVImageFormat *fmt1, *fmt;
3267
    int score, score_max;
3268

    
3269
    fmt = NULL;
3270
    score_max = 0;
3271
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3272
        if (fmt1->img_probe) {
3273
            score = fmt1->img_probe(pd);
3274
            if (score > score_max) {
3275
                score_max = score;
3276
                fmt = fmt1;
3277
            }
3278
        }
3279
    }
3280
    return fmt;
3281
}
3282

    
3283
/**
3284
 * Guesses image format based on file name extensions.
3285
 */
3286
AVImageFormat *guess_image_format(const char *filename)
3287
{
3288
    AVImageFormat *fmt1;
3289

    
3290
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
3291
        if (fmt1->extensions && match_ext(filename, fmt1->extensions))
3292
            return fmt1;
3293
    }
3294
    return NULL;
3295
}
3296

    
3297
/**
3298
 * Read an image from a stream.
3299
 * @param gb byte stream containing the image
3300
 * @param fmt image format, NULL if probing is required
3301
 */
3302
int av_read_image(ByteIOContext *pb, const char *filename,
3303
                  AVImageFormat *fmt,
3304
                  int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
3305
{
3306
    uint8_t buf[PROBE_BUF_MIN];
3307
    AVProbeData probe_data, *pd = &probe_data;
3308
    offset_t pos;
3309
    int ret;
3310

    
3311
    if (!fmt) {
3312
        pd->filename = filename;
3313
        pd->buf = buf;
3314
        pos = url_ftell(pb);
3315
        pd->buf_size = get_buffer(pb, buf, PROBE_BUF_MIN);
3316
        url_fseek(pb, pos, SEEK_SET);
3317
        fmt = av_probe_image_format(pd);
3318
    }
3319
    if (!fmt)
3320
        return AVERROR_NOFMT;
3321
    ret = fmt->img_read(pb, alloc_cb, opaque);
3322
    return ret;
3323
}
3324

    
3325
/**
3326
 * Write an image to a stream.
3327
 * @param pb byte stream for the image output
3328
 * @param fmt image format
3329
 * @param img image data and informations
3330
 */
3331
int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
3332
{
3333
    return fmt->img_write(pb, img);
3334
}
3335