Statistics
| Branch: | Revision:

ffmpeg / libavformat / utils.c @ 3ba1438d

History | View | Annotate | Download (80.1 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 */
19
#include "avformat.h"
20

    
21
#undef NDEBUG
22
#include <assert.h>
23

    
24
AVInputFormat *first_iformat = NULL;
25
AVOutputFormat *first_oformat = NULL;
26
AVImageFormat *first_image_format = NULL;
27

    
28
void av_register_input_format(AVInputFormat *format)
29
{
30
    AVInputFormat **p;
31
    p = &first_iformat;
32
    while (*p != NULL) p = &(*p)->next;
33
    *p = format;
34
    format->next = NULL;
35
}
36

    
37
void av_register_output_format(AVOutputFormat *format)
38
{
39
    AVOutputFormat **p;
40
    p = &first_oformat;
41
    while (*p != NULL) p = &(*p)->next;
42
    *p = format;
43
    format->next = NULL;
44
}
45

    
46
int match_ext(const char *filename, const char *extensions)
47
{
48
    const char *ext, *p;
49
    char ext1[32], *q;
50

    
51
    if(!filename)
52
        return 0;
53
    
54
    ext = strrchr(filename, '.');
55
    if (ext) {
56
        ext++;
57
        p = extensions;
58
        for(;;) {
59
            q = ext1;
60
            while (*p != '\0' && *p != ',') 
61
                *q++ = *p++;
62
            *q = '\0';
63
            if (!strcasecmp(ext1, ext)) 
64
                return 1;
65
            if (*p == '\0') 
66
                break;
67
            p++;
68
        }
69
    }
70
    return 0;
71
}
72

    
73
AVOutputFormat *guess_format(const char *short_name, const char *filename, 
74
                             const char *mime_type)
75
{
76
    AVOutputFormat *fmt, *fmt_found;
77
    int score_max, score;
78

    
79
    /* specific test for image sequences */
80
    if (!short_name && filename && 
81
        filename_number_test(filename) >= 0 &&
82
        guess_image_format(filename)) {
83
        return guess_format("image", NULL, NULL);
84
    }
85

    
86
    /* find the proper file type */
87
    fmt_found = NULL;
88
    score_max = 0;
89
    fmt = first_oformat;
90
    while (fmt != NULL) {
91
        score = 0;
92
        if (fmt->name && short_name && !strcmp(fmt->name, short_name))
93
            score += 100;
94
        if (fmt->mime_type && mime_type && !strcmp(fmt->mime_type, mime_type))
95
            score += 10;
96
        if (filename && fmt->extensions && 
97
            match_ext(filename, fmt->extensions)) {
98
            score += 5;
99
        }
100
        if (score > score_max) {
101
            score_max = score;
102
            fmt_found = fmt;
103
        }
104
        fmt = fmt->next;
105
    }
106
    return fmt_found;
107
}   
108

    
109
AVOutputFormat *guess_stream_format(const char *short_name, const char *filename, 
110
                             const char *mime_type)
111
{
112
    AVOutputFormat *fmt = guess_format(short_name, filename, mime_type);
113

    
114
    if (fmt) {
115
        AVOutputFormat *stream_fmt;
116
        char stream_format_name[64];
117

    
118
        snprintf(stream_format_name, sizeof(stream_format_name), "%s_stream", fmt->name);
119
        stream_fmt = guess_format(stream_format_name, NULL, NULL);
120

    
121
        if (stream_fmt)
122
            fmt = stream_fmt;
123
    }
124

    
125
    return fmt;
126
}
127

    
128
AVInputFormat *av_find_input_format(const char *short_name)
129
{
130
    AVInputFormat *fmt;
131
    for(fmt = first_iformat; fmt != NULL; fmt = fmt->next) {
132
        if (!strcmp(fmt->name, short_name))
133
            return fmt;
134
    }
135
    return NULL;
136
}
137

    
138
/* memory handling */
139

    
140
/**
141
 * Default packet destructor 
142
 */
143
static void av_destruct_packet(AVPacket *pkt)
144
{
145
    av_free(pkt->data);
146
    pkt->data = NULL; pkt->size = 0;
147
}
148

    
149
/**
150
 * Allocate the payload of a packet and intialized its fields to default values.
151
 *
152
 * @param pkt packet
153
 * @param size wanted payload size
154
 * @return 0 if OK. AVERROR_xxx otherwise.
155
 */
156
int av_new_packet(AVPacket *pkt, int size)
157
{
158
    void *data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);
159
    if (!data)
160
        return AVERROR_NOMEM;
161
    memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
162

    
163
    av_init_packet(pkt);
164
    pkt->data = data; 
165
    pkt->size = size;
166
    pkt->destruct = av_destruct_packet;
167
    return 0;
168
}
169

    
170
/* This is a hack - the packet memory allocation stuff is broken. The
171
   packet is allocated if it was not really allocated */
172
int av_dup_packet(AVPacket *pkt)
173
{
174
    if (pkt->destruct != av_destruct_packet) {
175
        uint8_t *data;
176
        /* we duplicate the packet and don't forget to put the padding
177
           again */
178
        data = av_malloc(pkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
179
        if (!data) {
180
            return AVERROR_NOMEM;
181
        }
182
        memcpy(data, pkt->data, pkt->size);
183
        memset(data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
184
        pkt->data = data;
185
        pkt->destruct = av_destruct_packet;
186
    }
187
    return 0;
188
}
189

    
190
/* fifo handling */
191

    
192
int fifo_init(FifoBuffer *f, int size)
193
{
194
    f->buffer = av_malloc(size);
195
    if (!f->buffer)
196
        return -1;
197
    f->end = f->buffer + size;
198
    f->wptr = f->rptr = f->buffer;
199
    return 0;
200
}
201

    
202
void fifo_free(FifoBuffer *f)
203
{
204
    av_free(f->buffer);
205
}
206

    
207
int fifo_size(FifoBuffer *f, uint8_t *rptr)
208
{
209
    int size;
210

    
211
    if (f->wptr >= rptr) {
212
        size = f->wptr - rptr;
213
    } else {
214
        size = (f->end - rptr) + (f->wptr - f->buffer);
215
    }
216
    return size;
217
}
218

    
219
/* get data from the fifo (return -1 if not enough data) */
220
int fifo_read(FifoBuffer *f, uint8_t *buf, int buf_size, uint8_t **rptr_ptr)
221
{
222
    uint8_t *rptr = *rptr_ptr;
223
    int size, len;
224

    
225
    if (f->wptr >= rptr) {
226
        size = f->wptr - rptr;
227
    } else {
228
        size = (f->end - rptr) + (f->wptr - f->buffer);
229
    }
230
    
231
    if (size < buf_size)
232
        return -1;
233
    while (buf_size > 0) {
234
        len = f->end - rptr;
235
        if (len > buf_size)
236
            len = buf_size;
237
        memcpy(buf, rptr, len);
238
        buf += len;
239
        rptr += len;
240
        if (rptr >= f->end)
241
            rptr = f->buffer;
242
        buf_size -= len;
243
    }
244
    *rptr_ptr = rptr;
245
    return 0;
246
}
247

    
248
void fifo_write(FifoBuffer *f, uint8_t *buf, int size, uint8_t **wptr_ptr)
249
{
250
    int len;
251
    uint8_t *wptr;
252
    wptr = *wptr_ptr;
253
    while (size > 0) {
254
        len = f->end - wptr;
255
        if (len > size)
256
            len = size;
257
        memcpy(wptr, buf, len);
258
        wptr += len;
259
        if (wptr >= f->end)
260
            wptr = f->buffer;
261
        buf += len;
262
        size -= len;
263
    }
264
    *wptr_ptr = wptr;
265
}
266

    
267
/* get data from the fifo (return -1 if not enough data) */
268
int put_fifo(ByteIOContext *pb, FifoBuffer *f, int buf_size, uint8_t **rptr_ptr)
269
{
270
    uint8_t *rptr = *rptr_ptr;
271
    int size, len;
272

    
273
    if (f->wptr >= rptr) {
274
        size = f->wptr - rptr;
275
    } else {
276
        size = (f->end - rptr) + (f->wptr - f->buffer);
277
    }
278
    
279
    if (size < buf_size)
280
        return -1;
281
    while (buf_size > 0) {
282
        len = f->end - rptr;
283
        if (len > buf_size)
284
            len = buf_size;
285
        put_buffer(pb, rptr, len);
286
        rptr += len;
287
        if (rptr >= f->end)
288
            rptr = f->buffer;
289
        buf_size -= len;
290
    }
291
    *rptr_ptr = rptr;
292
    return 0;
293
}
294

    
295
int filename_number_test(const char *filename)
296
{
297
    char buf[1024];
298
    if(!filename)
299
        return -1;
300
    return get_frame_filename(buf, sizeof(buf), filename, 1);
301
}
302

    
303
/* guess file format */
304
AVInputFormat *av_probe_input_format(AVProbeData *pd, int is_opened)
305
{
306
    AVInputFormat *fmt1, *fmt;
307
    int score, score_max;
308

    
309
    fmt = NULL;
310
    score_max = 0;
311
    for(fmt1 = first_iformat; fmt1 != NULL; fmt1 = fmt1->next) {
312
        if (!is_opened && !(fmt1->flags & AVFMT_NOFILE))
313
            continue;
314
        score = 0;
315
        if (fmt1->read_probe) {
316
            score = fmt1->read_probe(pd);
317
        } else if (fmt1->extensions) {
318
            if (match_ext(pd->filename, fmt1->extensions)) {
319
                score = 50;
320
            }
321
        } 
322
        if (score > score_max) {
323
            score_max = score;
324
            fmt = fmt1;
325
        }
326
    }
327
    return fmt;
328
}
329

    
330
/************************************************************/
331
/* input media file */
332

    
333
/**
334
 * open a media file from an IO stream. 'fmt' must be specified.
335
 */
336

    
337
static const char* format_to_name(void* ptr)
338
{
339
    AVFormatContext* fc = (AVFormatContext*) ptr;
340
    if(fc->iformat) return fc->iformat->name;
341
    else if(fc->oformat) return fc->oformat->name;
342
    else return "NULL";
343
}
344

    
345
static const AVClass av_format_context_class = { "AVFormatContext", format_to_name };
346

    
347
AVFormatContext *av_alloc_format_context(void)
348
{
349
    AVFormatContext *ic;
350
    ic = av_mallocz(sizeof(AVFormatContext));
351
    if (!ic) return ic;
352
    ic->av_class = &av_format_context_class;
353
    return ic;
354
}
355

    
356
int av_open_input_stream(AVFormatContext **ic_ptr, 
357
                         ByteIOContext *pb, const char *filename, 
358
                         AVInputFormat *fmt, AVFormatParameters *ap)
359
{
360
    int err;
361
    AVFormatContext *ic;
362

    
363
    ic = av_alloc_format_context();
364
    if (!ic) {
365
        err = AVERROR_NOMEM;
366
        goto fail;
367
    }
368
    ic->iformat = fmt;
369
    if (pb)
370
        ic->pb = *pb;
371
    ic->duration = AV_NOPTS_VALUE;
372
    ic->start_time = AV_NOPTS_VALUE;
373
    pstrcpy(ic->filename, sizeof(ic->filename), filename);
374

    
375
    /* allocate private data */
376
    if (fmt->priv_data_size > 0) {
377
        ic->priv_data = av_mallocz(fmt->priv_data_size);
378
        if (!ic->priv_data) {
379
            err = AVERROR_NOMEM;
380
            goto fail;
381
        }
382
    } else {
383
        ic->priv_data = NULL;
384
    }
385

    
386
    err = ic->iformat->read_header(ic, ap);
387
    if (err < 0)
388
        goto fail;
389

    
390
    if (pb)
391
        ic->data_offset = url_ftell(&ic->pb);
392

    
393
    *ic_ptr = ic;
394
    return 0;
395
 fail:
396
    if (ic) {
397
        av_freep(&ic->priv_data);
398
    }
399
    av_free(ic);
400
    *ic_ptr = NULL;
401
    return err;
402
}
403

    
404
#define PROBE_BUF_SIZE 2048
405

    
406
/**
407
 * Open a media file as input. The codec are not opened. Only the file
408
 * header (if present) is read.
409
 *
410
 * @param ic_ptr the opened media file handle is put here
411
 * @param filename filename to open.
412
 * @param fmt if non NULL, force the file format to use
413
 * @param buf_size optional buffer size (zero if default is OK)
414
 * @param ap additionnal parameters needed when opening the file (NULL if default)
415
 * @return 0 if OK. AVERROR_xxx otherwise.
416
 */
417
int av_open_input_file(AVFormatContext **ic_ptr, const char *filename, 
418
                       AVInputFormat *fmt,
419
                       int buf_size,
420
                       AVFormatParameters *ap)
421
{
422
    int err, must_open_file, file_opened;
423
    uint8_t buf[PROBE_BUF_SIZE];
424
    AVProbeData probe_data, *pd = &probe_data;
425
    ByteIOContext pb1, *pb = &pb1;
426
    
427
    file_opened = 0;
428
    pd->filename = "";
429
    if (filename)
430
        pd->filename = filename;
431
    pd->buf = buf;
432
    pd->buf_size = 0;
433

    
434
    if (!fmt) {
435
        /* guess format if no file can be opened  */
436
        fmt = av_probe_input_format(pd, 0);
437
    }
438

    
439
    /* do not open file if the format does not need it. XXX: specific
440
       hack needed to handle RTSP/TCP */
441
    must_open_file = 1;
442
    if (fmt && (fmt->flags & AVFMT_NOFILE)) {
443
        must_open_file = 0;
444
        pb= NULL; //FIXME this or memset(pb, 0, sizeof(ByteIOContext)); otherwise its uninitalized
445
    }
446

    
447
    if (!fmt || must_open_file) {
448
        /* if no file needed do not try to open one */
449
        if (url_fopen(pb, filename, URL_RDONLY) < 0) {
450
            err = AVERROR_IO;
451
            goto fail;
452
        }
453
        file_opened = 1;
454
        if (buf_size > 0) {
455
            url_setbufsize(pb, buf_size);
456
        }
457
        if (!fmt) {
458
            /* read probe data */
459
            pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
460
            if (url_fseek(pb, 0, SEEK_SET) == (offset_t)-EPIPE) {
461
                url_fclose(pb);
462
                if (url_fopen(pb, filename, URL_RDONLY) < 0) {
463
                    err = AVERROR_IO;
464
                    goto fail;
465
                }
466
            }
467
        }
468
    }
469
    
470
    /* guess file format */
471
    if (!fmt) {
472
        fmt = av_probe_input_format(pd, 1);
473
    }
474

    
475
    /* if still no format found, error */
476
    if (!fmt) {
477
        err = AVERROR_NOFMT;
478
        goto fail;
479
    }
480
        
481
    /* XXX: suppress this hack for redirectors */
482
#ifdef CONFIG_NETWORK
483
    if (fmt == &redir_demux) {
484
        err = redir_open(ic_ptr, pb);
485
        url_fclose(pb);
486
        return err;
487
    }
488
#endif
489

    
490
    /* check filename in case of an image number is expected */
491
    if (fmt->flags & AVFMT_NEEDNUMBER) {
492
        if (filename_number_test(filename) < 0) { 
493
            err = AVERROR_NUMEXPECTED;
494
            goto fail;
495
        }
496
    }
497
    err = av_open_input_stream(ic_ptr, pb, filename, fmt, ap);
498
    if (err)
499
        goto fail;
500
    return 0;
501
 fail:
502
    if (file_opened)
503
        url_fclose(pb);
504
    *ic_ptr = NULL;
505
    return err;
506
    
507
}
508

    
509
/*******************************************************/
510

    
511
/**
512
 * Read a transport packet from a media file. This function is
513
 * absolete and should never be used. Use av_read_frame() instead.
514
 * 
515
 * @param s media file handle
516
 * @param pkt is filled 
517
 * @return 0 if OK. AVERROR_xxx if error.  
518
 */
519
int av_read_packet(AVFormatContext *s, AVPacket *pkt)
520
{
521
    return s->iformat->read_packet(s, pkt);
522
}
523

    
524
/**********************************************************/
525

    
526
/* get the number of samples of an audio frame. Return (-1) if error */
527
static int get_audio_frame_size(AVCodecContext *enc, int size)
528
{
529
    int frame_size;
530

    
531
    if (enc->frame_size <= 1) {
532
        /* specific hack for pcm codecs because no frame size is
533
           provided */
534
        switch(enc->codec_id) {
535
        case CODEC_ID_PCM_S16LE:
536
        case CODEC_ID_PCM_S16BE:
537
        case CODEC_ID_PCM_U16LE:
538
        case CODEC_ID_PCM_U16BE:
539
            if (enc->channels == 0)
540
                return -1;
541
            frame_size = size / (2 * enc->channels);
542
            break;
543
        case CODEC_ID_PCM_S8:
544
        case CODEC_ID_PCM_U8:
545
        case CODEC_ID_PCM_MULAW:
546
        case CODEC_ID_PCM_ALAW:
547
            if (enc->channels == 0)
548
                return -1;
549
            frame_size = size / (enc->channels);
550
            break;
551
        default:
552
            /* used for example by ADPCM codecs */
553
            if (enc->bit_rate == 0)
554
                return -1;
555
            frame_size = (size * 8 * enc->sample_rate) / enc->bit_rate;
556
            break;
557
        }
558
    } else {
559
        frame_size = enc->frame_size;
560
    }
561
    return frame_size;
562
}
563

    
564

    
565
/* return the frame duration in seconds, return 0 if not available */
566
static void compute_frame_duration(int *pnum, int *pden, AVStream *st, 
567
                                   AVCodecParserContext *pc, AVPacket *pkt)
568
{
569
    int frame_size;
570

    
571
    *pnum = 0;
572
    *pden = 0;
573
    switch(st->codec.codec_type) {
574
    case CODEC_TYPE_VIDEO:
575
        *pnum = st->codec.frame_rate_base;
576
        *pden = st->codec.frame_rate;
577
        if (pc && pc->repeat_pict) {
578
            *pden *= 2;
579
            *pnum = (*pnum) * (2 + pc->repeat_pict);
580
        }
581
        break;
582
    case CODEC_TYPE_AUDIO:
583
        frame_size = get_audio_frame_size(&st->codec, pkt->size);
584
        if (frame_size < 0)
585
            break;
586
        *pnum = frame_size;
587
        *pden = st->codec.sample_rate;
588
        break;
589
    default:
590
        break;
591
    }
592
}
593

    
594
static int64_t lsb2full(int64_t lsb, int64_t last_ts, int lsb_bits){
595
    int64_t mask = lsb_bits < 64 ? (1LL<<lsb_bits)-1 : -1LL;
596
    int64_t delta= last_ts - mask/2;
597
    return  ((lsb - delta)&mask) + delta;
598
}
599

    
600
static void compute_pkt_fields(AVFormatContext *s, AVStream *st, 
601
                               AVCodecParserContext *pc, AVPacket *pkt)
602
{
603
    int num, den, presentation_delayed;
604

    
605
    /* handle wrapping */
606
    if(st->cur_dts != AV_NOPTS_VALUE){
607
        if(pkt->pts != AV_NOPTS_VALUE)
608
            pkt->pts= lsb2full(pkt->pts, st->cur_dts, st->pts_wrap_bits);
609
        if(pkt->dts != AV_NOPTS_VALUE)
610
            pkt->dts= lsb2full(pkt->dts, st->cur_dts, st->pts_wrap_bits);
611
    }
612
    
613
    if (pkt->duration == 0) {
614
        compute_frame_duration(&num, &den, st, pc, pkt);
615
        if (den && num) {
616
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
617
        }
618
    }
619

    
620
    /* do we have a video B frame ? */
621
    presentation_delayed = 0;
622
    if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
623
        /* XXX: need has_b_frame, but cannot get it if the codec is
624
           not initialized */
625
        if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
626
             st->codec.codec_id == CODEC_ID_MPEG2VIDEO ||
627
             st->codec.codec_id == CODEC_ID_MPEG4 ||
628
             st->codec.codec_id == CODEC_ID_H264) && 
629
            pc && pc->pict_type != FF_B_TYPE)
630
            presentation_delayed = 1;
631
        /* this may be redundant, but it shouldnt hurt */
632
        if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)
633
            presentation_delayed = 1;
634
    }
635
    
636
    if(st->cur_dts == AV_NOPTS_VALUE){
637
        if(presentation_delayed) st->cur_dts = -pkt->duration;
638
        else                     st->cur_dts = 0;
639
    }
640

    
641
//    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);
642
    /* interpolate PTS and DTS if they are not present */
643
    if (presentation_delayed) {
644
        /* DTS = decompression time stamp */
645
        /* PTS = presentation time stamp */
646
        if (pkt->dts == AV_NOPTS_VALUE) {
647
            /* if we know the last pts, use it */
648
            if(st->last_IP_pts != AV_NOPTS_VALUE)
649
                st->cur_dts = pkt->dts = st->last_IP_pts;
650
            else
651
                pkt->dts = st->cur_dts;
652
        } else {
653
            st->cur_dts = pkt->dts;
654
        }
655
        /* this is tricky: the dts must be incremented by the duration
656
           of the frame we are displaying, i.e. the last I or P frame */
657
        if (st->last_IP_duration == 0)
658
            st->cur_dts += pkt->duration;
659
        else
660
            st->cur_dts += st->last_IP_duration;
661
        st->last_IP_duration  = pkt->duration;
662
        st->last_IP_pts= pkt->pts;
663
        /* cannot compute PTS if not present (we can compute it only
664
           by knowing the futur */
665
    } else {
666
        /* presentation is not delayed : PTS and DTS are the same */
667
        if (pkt->pts == AV_NOPTS_VALUE) {
668
            if (pkt->dts == AV_NOPTS_VALUE) {
669
                pkt->pts = st->cur_dts;
670
                pkt->dts = st->cur_dts;
671
            }
672
            else {
673
                st->cur_dts = pkt->dts;
674
                pkt->pts = pkt->dts;
675
            }
676
        } else {
677
            st->cur_dts = pkt->pts;
678
            pkt->dts = pkt->pts;
679
        }
680
        st->cur_dts += pkt->duration;
681
    }
682
//    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);
683
    
684
    /* update flags */
685
    if (pc) {
686
        pkt->flags = 0;
687
        /* key frame computation */
688
        switch(st->codec.codec_type) {
689
        case CODEC_TYPE_VIDEO:
690
            if (pc->pict_type == FF_I_TYPE)
691
                pkt->flags |= PKT_FLAG_KEY;
692
            break;
693
        case CODEC_TYPE_AUDIO:
694
            pkt->flags |= PKT_FLAG_KEY;
695
            break;
696
        default:
697
            break;
698
        }
699
    }
700

    
701
    /* convert the packet time stamp units */
702
    if(pkt->pts != AV_NOPTS_VALUE)
703
        pkt->pts = av_rescale(pkt->pts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
704
    if(pkt->dts != AV_NOPTS_VALUE)
705
        pkt->dts = av_rescale(pkt->dts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
706

    
707
    /* duration field */
708
    pkt->duration = av_rescale(pkt->duration, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
709
}
710

    
711
void av_destruct_packet_nofree(AVPacket *pkt)
712
{
713
    pkt->data = NULL; pkt->size = 0;
714
}
715

    
716
static int av_read_frame_internal(AVFormatContext *s, AVPacket *pkt)
717
{
718
    AVStream *st;
719
    int len, ret, i;
720

    
721
    for(;;) {
722
        /* select current input stream component */
723
        st = s->cur_st;
724
        if (st) {
725
            if (!st->parser) {
726
                /* no parsing needed: we just output the packet as is */
727
                /* raw data support */
728
                *pkt = s->cur_pkt;
729
                compute_pkt_fields(s, st, NULL, pkt);
730
                s->cur_st = NULL;
731
                return 0;
732
            } else if (s->cur_len > 0) {
733
                len = av_parser_parse(st->parser, &st->codec, &pkt->data, &pkt->size, 
734
                                      s->cur_ptr, s->cur_len,
735
                                      s->cur_pkt.pts, s->cur_pkt.dts);
736
                s->cur_pkt.pts = AV_NOPTS_VALUE;
737
                s->cur_pkt.dts = AV_NOPTS_VALUE;
738
                /* increment read pointer */
739
                s->cur_ptr += len;
740
                s->cur_len -= len;
741
                
742
                /* return packet if any */
743
                if (pkt->size) {
744
                got_packet:
745
                    pkt->duration = 0;
746
                    pkt->stream_index = st->index;
747
                    pkt->pts = st->parser->pts;
748
                    pkt->dts = st->parser->dts;
749
                    pkt->destruct = av_destruct_packet_nofree;
750
                    compute_pkt_fields(s, st, st->parser, pkt);
751
                    return 0;
752
                }
753
            } else {
754
                /* free packet */
755
                av_free_packet(&s->cur_pkt); 
756
                s->cur_st = NULL;
757
            }
758
        } else {
759
            /* read next packet */
760
            ret = av_read_packet(s, &s->cur_pkt);
761
            if (ret < 0) {
762
                if (ret == -EAGAIN)
763
                    return ret;
764
                /* return the last frames, if any */
765
                for(i = 0; i < s->nb_streams; i++) {
766
                    st = s->streams[i];
767
                    if (st->parser) {
768
                        av_parser_parse(st->parser, &st->codec, 
769
                                        &pkt->data, &pkt->size, 
770
                                        NULL, 0, 
771
                                        AV_NOPTS_VALUE, AV_NOPTS_VALUE);
772
                        if (pkt->size)
773
                            goto got_packet;
774
                    }
775
                }
776
                /* no more packets: really terminates parsing */
777
                return ret;
778
            }
779
            
780
            st = s->streams[s->cur_pkt.stream_index];
781

    
782
            s->cur_st = st;
783
            s->cur_ptr = s->cur_pkt.data;
784
            s->cur_len = s->cur_pkt.size;
785
            if (st->need_parsing && !st->parser) {
786
                st->parser = av_parser_init(st->codec.codec_id);
787
                if (!st->parser) {
788
                    /* no parser available : just output the raw packets */
789
                    st->need_parsing = 0;
790
                }
791
            }
792
        }
793
    }
794
}
795

    
796
/**
797
 * Return the next frame of a stream. The returned packet is valid
798
 * until the next av_read_frame() or until av_close_input_file() and
799
 * must be freed with av_free_packet. For video, the packet contains
800
 * exactly one frame. For audio, it contains an integer number of
801
 * frames if each frame has a known fixed size (e.g. PCM or ADPCM
802
 * data). If the audio frames have a variable size (e.g. MPEG audio),
803
 * then it contains one frame.
804
 * 
805
 * pkt->pts, pkt->dts and pkt->duration are always set to correct
806
 * values in AV_TIME_BASE unit (and guessed if the format cannot
807
 * provided them). pkt->pts can be AV_NOPTS_VALUE if the video format
808
 * has B frames, so it is better to rely on pkt->dts if you do not
809
 * decompress the payload.
810
 * 
811
 * Return 0 if OK, < 0 if error or end of file.  
812
 */
813
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
814
{
815
    AVPacketList *pktl;
816

    
817
    pktl = s->packet_buffer;
818
    if (pktl) {
819
        /* read packet from packet buffer, if there is data */
820
        *pkt = pktl->pkt;
821
        s->packet_buffer = pktl->next;
822
        av_free(pktl);
823
        return 0;
824
    } else {
825
        return av_read_frame_internal(s, pkt);
826
    }
827
}
828

    
829
/* XXX: suppress the packet queue */
830
static void flush_packet_queue(AVFormatContext *s)
831
{
832
    AVPacketList *pktl;
833

    
834
    for(;;) {
835
        pktl = s->packet_buffer;
836
        if (!pktl) 
837
            break;
838
        s->packet_buffer = pktl->next;
839
        av_free_packet(&pktl->pkt);
840
        av_free(pktl);
841
    }
842
}
843

    
844
/*******************************************************/
845
/* seek support */
846

    
847
int av_find_default_stream_index(AVFormatContext *s)
848
{
849
    int i;
850
    AVStream *st;
851

    
852
    if (s->nb_streams <= 0)
853
        return -1;
854
    for(i = 0; i < s->nb_streams; i++) {
855
        st = s->streams[i];
856
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
857
            return i;
858
        }
859
    }
860
    return 0;
861
}
862

    
863
/* flush the frame reader */
864
static void av_read_frame_flush(AVFormatContext *s)
865
{
866
    AVStream *st;
867
    int i;
868

    
869
    flush_packet_queue(s);
870

    
871
    /* free previous packet */
872
    if (s->cur_st) {
873
        if (s->cur_st->parser)
874
            av_free_packet(&s->cur_pkt);
875
        s->cur_st = NULL;
876
    }
877
    /* fail safe */
878
    s->cur_ptr = NULL;
879
    s->cur_len = 0;
880
    
881
    /* for each stream, reset read state */
882
    for(i = 0; i < s->nb_streams; i++) {
883
        st = s->streams[i];
884
        
885
        if (st->parser) {
886
            av_parser_close(st->parser);
887
            st->parser = NULL;
888
        }
889
        st->last_IP_pts = AV_NOPTS_VALUE;
890
        st->cur_dts = 0; /* we set the current DTS to an unspecified origin */
891
    }
892
}
893

    
894
/**
895
 * add a index entry into a sorted list updateing if it is already there.
896
 * @param timestamp timestamp in the timebase of the given stream
897
 */
898
int av_add_index_entry(AVStream *st,
899
                            int64_t pos, int64_t timestamp, int distance, int flags)
900
{
901
    AVIndexEntry *entries, *ie;
902
    int index;
903
    
904
    entries = av_fast_realloc(st->index_entries,
905
                              &st->index_entries_allocated_size,
906
                              (st->nb_index_entries + 1) * 
907
                              sizeof(AVIndexEntry));
908
    st->index_entries= entries;
909

    
910
    index= av_index_search_timestamp(st, timestamp, 0);
911

    
912
    if(index<0){
913
        index= st->nb_index_entries++;
914
        ie= &entries[index];
915
        assert(index==0 || ie[-1].timestamp < timestamp);
916
    }else{
917
        ie= &entries[index];
918
        if(ie->timestamp != timestamp){
919
            assert(ie->timestamp > timestamp);
920
            memmove(entries + index + 1, entries + index, sizeof(AVIndexEntry)*(st->nb_index_entries - index));
921
            st->nb_index_entries++;
922
        }else if(ie->pos == pos && distance < ie->min_distance) //dont reduce the distance
923
            distance= ie->min_distance;
924
    }
925

    
926
    ie->pos = pos;
927
    ie->timestamp = timestamp;
928
    ie->min_distance= distance;
929
    ie->flags = flags;
930
    
931
    return index;
932
}
933

    
934
/* build an index for raw streams using a parser */
935
static void av_build_index_raw(AVFormatContext *s)
936
{
937
    AVPacket pkt1, *pkt = &pkt1;
938
    int ret;
939
    AVStream *st;
940

    
941
    st = s->streams[0];
942
    av_read_frame_flush(s);
943
    url_fseek(&s->pb, s->data_offset, SEEK_SET);
944

    
945
    for(;;) {
946
        ret = av_read_frame(s, pkt);
947
        if (ret < 0)
948
            break;
949
        if (pkt->stream_index == 0 && st->parser &&
950
            (pkt->flags & PKT_FLAG_KEY)) {
951
            int64_t dts= av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE*(int64_t)st->time_base.num);
952
            av_add_index_entry(st, st->parser->frame_offset, dts, 
953
                            0, AVINDEX_KEYFRAME);
954
        }
955
        av_free_packet(pkt);
956
    }
957
}
958

    
959
/* return TRUE if we deal with a raw stream (raw codec data and
960
   parsing needed) */
961
static int is_raw_stream(AVFormatContext *s)
962
{
963
    AVStream *st;
964

    
965
    if (s->nb_streams != 1)
966
        return 0;
967
    st = s->streams[0];
968
    if (!st->need_parsing)
969
        return 0;
970
    return 1;
971
}
972

    
973
/**
974
 * gets the index for a specific timestamp.
975
 * @param backward if non zero then the returned index will correspond to 
976
 *                 the timestamp which is <= the requested one, if backward is 0 
977
 *                 then it will be >=
978
 * @return < 0 if no such timestamp could be found
979
 */
980
int av_index_search_timestamp(AVStream *st, int wanted_timestamp, int backward)
981
{
982
    AVIndexEntry *entries= st->index_entries;
983
    int nb_entries= st->nb_index_entries;
984
    int a, b, m;
985
    int64_t timestamp;
986

    
987
    a = - 1;
988
    b = nb_entries;
989

    
990
    while (b - a > 1) {
991
        m = (a + b) >> 1;
992
        timestamp = entries[m].timestamp;
993
        if(timestamp >= wanted_timestamp)
994
            b = m;
995
        if(timestamp <= wanted_timestamp)
996
            a = m;
997
    }
998
    m= backward ? a : b;
999

    
1000
    if(m == nb_entries) 
1001
        return -1;
1002
    return  m;
1003
}
1004

    
1005
#define DEBUG_SEEK
1006

    
1007
/**
1008
 * Does a binary search using av_index_search_timestamp() and AVCodec.read_timestamp().
1009
 * this isnt supposed to be called directly by a user application, but by demuxers
1010
 * @param target_ts target timestamp in the time base of the given stream
1011
 * @param stream_index stream number
1012
 */
1013
int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1014
    AVInputFormat *avif= s->iformat;
1015
    int64_t pos_min, pos_max, pos, pos_limit;
1016
    int64_t ts_min, ts_max, ts;
1017
    int64_t start_pos;
1018
    int index, no_change, i;
1019
    AVStream *st;
1020

    
1021
    if (stream_index < 0)
1022
        return -1;
1023
    
1024
#ifdef DEBUG_SEEK
1025
    av_log(s, AV_LOG_DEBUG, "read_seek: %d %lld\n", stream_index, target_ts);
1026
#endif
1027

    
1028
    ts_max=
1029
    ts_min= AV_NOPTS_VALUE;
1030
    pos_limit= -1; //gcc falsely says it may be uninitalized
1031

    
1032
    st= s->streams[stream_index];
1033
    if(st->index_entries){
1034
        AVIndexEntry *e;
1035

    
1036
        index= av_index_search_timestamp(st, target_ts, 1);
1037
        index= FFMAX(index, 0);
1038
        e= &st->index_entries[index];
1039

    
1040
        if(e->timestamp <= target_ts || e->pos == e->min_distance){
1041
            pos_min= e->pos;
1042
            ts_min= e->timestamp;
1043
#ifdef DEBUG_SEEK
1044
        av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%llx dts_min=%lld\n", 
1045
               pos_min,ts_min);
1046
#endif
1047
        }else{
1048
            assert(index==0);
1049
        }
1050
        index++;
1051
        if(index < st->nb_index_entries){
1052
            e= &st->index_entries[index];
1053
            assert(e->timestamp >= target_ts);
1054
            pos_max= e->pos;
1055
            ts_max= e->timestamp;
1056
            pos_limit= pos_max - e->min_distance;
1057
#ifdef DEBUG_SEEK
1058
        av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%llx pos_limit=0x%llx dts_max=%lld\n", 
1059
               pos_max,pos_limit, ts_max);
1060
#endif
1061
        }
1062
    }
1063

    
1064
    if(ts_min == AV_NOPTS_VALUE){
1065
        pos_min = s->data_offset;
1066
        ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1067
        if (ts_min == AV_NOPTS_VALUE)
1068
            return -1;
1069
    }
1070

    
1071
    if(ts_max == AV_NOPTS_VALUE){
1072
        int step= 1024;
1073
        pos_max = url_filesize(url_fileno(&s->pb)) - 1;
1074
        do{
1075
            pos_max -= step;
1076
            ts_max = avif->read_timestamp(s, stream_index, &pos_max, pos_max + step);
1077
            step += step;
1078
        }while(ts_max == AV_NOPTS_VALUE && pos_max >= step);
1079
        if (ts_max == AV_NOPTS_VALUE)
1080
            return -1;
1081
        
1082
        for(;;){
1083
            int64_t tmp_pos= pos_max + 1;
1084
            int64_t tmp_ts= avif->read_timestamp(s, stream_index, &tmp_pos, INT64_MAX);
1085
            if(tmp_ts == AV_NOPTS_VALUE)
1086
                break;
1087
            ts_max= tmp_ts;
1088
            pos_max= tmp_pos;
1089
        }
1090
        pos_limit= pos_max;
1091
    }
1092

    
1093
    no_change=0;
1094
    while (pos_min < pos_limit) {
1095
#ifdef DEBUG_SEEK
1096
        av_log(s, AV_LOG_DEBUG, "pos_min=0x%llx pos_max=0x%llx dts_min=%lld dts_max=%lld\n", 
1097
               pos_min, pos_max,
1098
               ts_min, ts_max);
1099
#endif
1100
        assert(pos_limit <= pos_max);
1101

    
1102
        if(no_change==0){
1103
            int64_t approximate_keyframe_distance= pos_max - pos_limit;
1104
            // interpolate position (better than dichotomy)
1105
            pos = av_rescale(target_ts - ts_min, pos_max - pos_min, ts_max - ts_min)
1106
                + pos_min - approximate_keyframe_distance;
1107
        }else if(no_change==1){
1108
            // bisection, if interpolation failed to change min or max pos last time
1109
            pos = (pos_min + pos_limit)>>1;
1110
        }else{
1111
            // linear search if bisection failed, can only happen if there are very few or no keframes between min/max
1112
            pos=pos_min;
1113
        }
1114
        if(pos <= pos_min)
1115
            pos= pos_min + 1;
1116
        else if(pos > pos_limit)
1117
            pos= pos_limit;
1118
        start_pos= pos;
1119

    
1120
        ts = avif->read_timestamp(s, stream_index, &pos, INT64_MAX); //may pass pos_limit instead of -1
1121
        if(pos == pos_max)
1122
            no_change++;
1123
        else
1124
            no_change=0;
1125
#ifdef DEBUG_SEEK
1126
av_log(s, AV_LOG_DEBUG, "%Ld %Ld %Ld / %Ld %Ld %Ld target:%Ld limit:%Ld start:%Ld noc:%d\n", pos_min, pos, pos_max, ts_min, ts, ts_max, target_ts, pos_limit, start_pos, no_change);
1127
#endif
1128
        assert(ts != AV_NOPTS_VALUE);
1129
        if (target_ts <= ts) {
1130
            pos_limit = start_pos - 1;
1131
            pos_max = pos;
1132
            ts_max = ts;
1133
        }
1134
        if (target_ts >= ts) {
1135
            pos_min = pos;
1136
            ts_min = ts;
1137
        }
1138
    }
1139
    
1140
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
1141
    ts  = (flags & AVSEEK_FLAG_BACKWARD) ?  ts_min :  ts_max;
1142
#ifdef DEBUG_SEEK
1143
    pos_min = pos;
1144
    ts_min = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1145
    pos_min++;
1146
    ts_max = avif->read_timestamp(s, stream_index, &pos_min, INT64_MAX);
1147
    av_log(s, AV_LOG_DEBUG, "pos=0x%llx %lld<=%lld<=%lld\n", 
1148
           pos, ts_min, target_ts, ts_max);
1149
#endif
1150
    /* do the seek */
1151
    url_fseek(&s->pb, pos, SEEK_SET);
1152

    
1153
    for(i = 0; i < s->nb_streams; i++) {
1154
        AVStream *st2 = s->streams[i];
1155

    
1156
        st->cur_dts = av_rescale(ts, 
1157
                                 st2->time_base.den * (int64_t)st ->time_base.num,
1158
                                 st ->time_base.den * (int64_t)st2->time_base.num);
1159
    }
1160

    
1161
    return 0;
1162
}
1163

    
1164
static int av_seek_frame_byte(AVFormatContext *s, int stream_index, int64_t pos, int flags){
1165
    AVInputFormat *avif= s->iformat;
1166
    int64_t pos_min, pos_max;
1167
#if 0
1168
    AVStream *st;
1169

1170
    if (stream_index < 0)
1171
        return -1;
1172

1173
    st= s->streams[stream_index];
1174
#endif
1175

    
1176
    pos_min = s->data_offset;
1177
    pos_max = url_filesize(url_fileno(&s->pb)) - 1;
1178

    
1179
    if     (pos < pos_min) pos= pos_min;
1180
    else if(pos > pos_max) pos= pos_max;
1181

    
1182
    url_fseek(&s->pb, pos, SEEK_SET);
1183

    
1184
#if 0
1185
    for(i = 0; i < s->nb_streams; i++) {
1186
        st2 = s->streams[i];
1187

1188
        st->cur_dts = av_rescale(ie->timestamp, 
1189
                                 st2->time_base.den * (int64_t)st ->time_base.num,
1190
                                 st ->time_base.den * (int64_t)st2->time_base.num);
1191
    }
1192
#endif
1193
    return 0;
1194
}
1195

    
1196
static int av_seek_frame_generic(AVFormatContext *s, 
1197
                                 int stream_index, int64_t timestamp, int flags)
1198
{
1199
    int index, i;
1200
    AVStream *st;
1201
    AVIndexEntry *ie;
1202

    
1203
    if (!s->index_built) {
1204
        if (is_raw_stream(s)) {
1205
            av_build_index_raw(s);
1206
        } else {
1207
            return -1;
1208
        }
1209
        s->index_built = 1;
1210
    }
1211

    
1212
    st = s->streams[stream_index];
1213
    index = av_index_search_timestamp(st, timestamp, flags & AVSEEK_FLAG_BACKWARD);
1214
    if (index < 0)
1215
        return -1;
1216

    
1217
    /* now we have found the index, we can seek */
1218
    ie = &st->index_entries[index];
1219
    av_read_frame_flush(s);
1220
    url_fseek(&s->pb, ie->pos, SEEK_SET);
1221

    
1222
    for(i = 0; i < s->nb_streams; i++) {
1223
        AVStream *st2 = s->streams[i];
1224

    
1225
        st->cur_dts = av_rescale(ie->timestamp, 
1226
                                 st2->time_base.den * (int64_t)st ->time_base.num,
1227
                                 st ->time_base.den * (int64_t)st2->time_base.num);
1228
    }
1229

    
1230
    return 0;
1231
}
1232

    
1233
/**
1234
 * Seek to the key frame at timestamp.
1235
 * 'timestamp' in 'stream_index'.
1236
 * @param stream_index If stream_index is (-1), a default
1237
 * stream is selected
1238
 * @param timestamp timestamp in AVStream.time_base units
1239
 * @param flags flags which select direction and seeking mode
1240
 * @return >= 0 on success
1241
 */
1242
int av_seek_frame(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
1243
{
1244
    int ret;
1245
    AVStream *st;
1246
    
1247
    av_read_frame_flush(s);
1248
    
1249
    if(flags & AVSEEK_FLAG_BYTE)
1250
        return av_seek_frame_byte(s, stream_index, timestamp, flags);
1251
    
1252
    if(stream_index < 0){
1253
        stream_index= av_find_default_stream_index(s);
1254
        if(stream_index < 0)
1255
            return -1;
1256
            
1257
        st= s->streams[stream_index];
1258
        timestamp = av_rescale(timestamp, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1259
    }
1260
    st= s->streams[stream_index];
1261

    
1262
    /* first, we try the format specific seek */
1263
    if (s->iformat->read_seek)
1264
        ret = s->iformat->read_seek(s, stream_index, timestamp, flags);
1265
    else
1266
        ret = -1;
1267
    if (ret >= 0) {
1268
        return 0;
1269
    }
1270

    
1271
    if(s->iformat->read_timestamp)
1272
        return av_seek_frame_binary(s, stream_index, timestamp, flags);
1273
    else
1274
        return av_seek_frame_generic(s, stream_index, timestamp, flags);
1275
}
1276

    
1277
/*******************************************************/
1278

    
1279
/* return TRUE if the stream has accurate timings for at least one component */
1280
static int av_has_timings(AVFormatContext *ic)
1281
{
1282
    int i;
1283
    AVStream *st;
1284

    
1285
    for(i = 0;i < ic->nb_streams; i++) {
1286
        st = ic->streams[i];
1287
        if (st->start_time != AV_NOPTS_VALUE &&
1288
            st->duration != AV_NOPTS_VALUE)
1289
            return 1;
1290
    }
1291
    return 0;
1292
}
1293

    
1294
/* estimate the stream timings from the one of each components. Also
1295
   compute the global bitrate if possible */
1296
static void av_update_stream_timings(AVFormatContext *ic)
1297
{
1298
    int64_t start_time, end_time, end_time1;
1299
    int i;
1300
    AVStream *st;
1301

    
1302
    start_time = MAXINT64;
1303
    end_time = MININT64;
1304
    for(i = 0;i < ic->nb_streams; i++) {
1305
        st = ic->streams[i];
1306
        if (st->start_time != AV_NOPTS_VALUE) {
1307
            if (st->start_time < start_time)
1308
                start_time = st->start_time;
1309
            if (st->duration != AV_NOPTS_VALUE) {
1310
                end_time1 = st->start_time + st->duration;
1311
                if (end_time1 > end_time)
1312
                    end_time = end_time1;
1313
            }
1314
        }
1315
    }
1316
    if (start_time != MAXINT64) {
1317
        ic->start_time = start_time;
1318
        if (end_time != MAXINT64) {
1319
            ic->duration = end_time - start_time;
1320
            if (ic->file_size > 0) {
1321
                /* compute the bit rate */
1322
                ic->bit_rate = (double)ic->file_size * 8.0 * AV_TIME_BASE / 
1323
                    (double)ic->duration;
1324
            }
1325
        }
1326
    }
1327

    
1328
}
1329

    
1330
static void fill_all_stream_timings(AVFormatContext *ic)
1331
{
1332
    int i;
1333
    AVStream *st;
1334

    
1335
    av_update_stream_timings(ic);
1336
    for(i = 0;i < ic->nb_streams; i++) {
1337
        st = ic->streams[i];
1338
        if (st->start_time == AV_NOPTS_VALUE) {
1339
            st->start_time = ic->start_time;
1340
            st->duration = ic->duration;
1341
        }
1342
    }
1343
}
1344

    
1345
static void av_estimate_timings_from_bit_rate(AVFormatContext *ic)
1346
{
1347
    int64_t filesize, duration;
1348
    int bit_rate, i;
1349
    AVStream *st;
1350

    
1351
    /* if bit_rate is already set, we believe it */
1352
    if (ic->bit_rate == 0) {
1353
        bit_rate = 0;
1354
        for(i=0;i<ic->nb_streams;i++) {
1355
            st = ic->streams[i];
1356
            bit_rate += st->codec.bit_rate;
1357
        }
1358
        ic->bit_rate = bit_rate;
1359
    }
1360

    
1361
    /* if duration is already set, we believe it */
1362
    if (ic->duration == AV_NOPTS_VALUE && 
1363
        ic->bit_rate != 0 && 
1364
        ic->file_size != 0)  {
1365
        filesize = ic->file_size;
1366
        if (filesize > 0) {
1367
            duration = (int64_t)((8 * AV_TIME_BASE * (double)filesize) / (double)ic->bit_rate);
1368
            for(i = 0; i < ic->nb_streams; i++) {
1369
                st = ic->streams[i];
1370
                if (st->start_time == AV_NOPTS_VALUE ||
1371
                    st->duration == AV_NOPTS_VALUE) {
1372
                    st->start_time = 0;
1373
                    st->duration = duration;
1374
                }
1375
            }
1376
        }
1377
    }
1378
}
1379

    
1380
#define DURATION_MAX_READ_SIZE 250000
1381

    
1382
/* only usable for MPEG-PS streams */
1383
static void av_estimate_timings_from_pts(AVFormatContext *ic)
1384
{
1385
    AVPacket pkt1, *pkt = &pkt1;
1386
    AVStream *st;
1387
    int read_size, i, ret;
1388
    int64_t start_time, end_time, end_time1;
1389
    int64_t filesize, offset, duration;
1390
    
1391
    /* free previous packet */
1392
    if (ic->cur_st && ic->cur_st->parser)
1393
        av_free_packet(&ic->cur_pkt); 
1394
    ic->cur_st = NULL;
1395

    
1396
    /* flush packet queue */
1397
    flush_packet_queue(ic);
1398

    
1399
    for(i=0;i<ic->nb_streams;i++) {
1400
        st = ic->streams[i];
1401
        if (st->parser) {
1402
            av_parser_close(st->parser);
1403
            st->parser= NULL;
1404
        }
1405
    }
1406
    
1407
    /* we read the first packets to get the first PTS (not fully
1408
       accurate, but it is enough now) */
1409
    url_fseek(&ic->pb, 0, SEEK_SET);
1410
    read_size = 0;
1411
    for(;;) {
1412
        if (read_size >= DURATION_MAX_READ_SIZE)
1413
            break;
1414
        /* if all info is available, we can stop */
1415
        for(i = 0;i < ic->nb_streams; i++) {
1416
            st = ic->streams[i];
1417
            if (st->start_time == AV_NOPTS_VALUE)
1418
                break;
1419
        }
1420
        if (i == ic->nb_streams)
1421
            break;
1422

    
1423
        ret = av_read_packet(ic, pkt);
1424
        if (ret != 0)
1425
            break;
1426
        read_size += pkt->size;
1427
        st = ic->streams[pkt->stream_index];
1428
        if (pkt->pts != AV_NOPTS_VALUE) {
1429
            if (st->start_time == AV_NOPTS_VALUE)
1430
                st->start_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
1431
        }
1432
        av_free_packet(pkt);
1433
    }
1434

    
1435
    /* we compute the minimum start_time and use it as default */
1436
    start_time = MAXINT64;
1437
    for(i = 0; i < ic->nb_streams; i++) {
1438
        st = ic->streams[i];
1439
        if (st->start_time != AV_NOPTS_VALUE &&
1440
            st->start_time < start_time)
1441
            start_time = st->start_time;
1442
    }
1443
    if (start_time != MAXINT64)
1444
        ic->start_time = start_time;
1445
    
1446
    /* estimate the end time (duration) */
1447
    /* XXX: may need to support wrapping */
1448
    filesize = ic->file_size;
1449
    offset = filesize - DURATION_MAX_READ_SIZE;
1450
    if (offset < 0)
1451
        offset = 0;
1452

    
1453
    url_fseek(&ic->pb, offset, SEEK_SET);
1454
    read_size = 0;
1455
    for(;;) {
1456
        if (read_size >= DURATION_MAX_READ_SIZE)
1457
            break;
1458
        /* if all info is available, we can stop */
1459
        for(i = 0;i < ic->nb_streams; i++) {
1460
            st = ic->streams[i];
1461
            if (st->duration == AV_NOPTS_VALUE)
1462
                break;
1463
        }
1464
        if (i == ic->nb_streams)
1465
            break;
1466
        
1467
        ret = av_read_packet(ic, pkt);
1468
        if (ret != 0)
1469
            break;
1470
        read_size += pkt->size;
1471
        st = ic->streams[pkt->stream_index];
1472
        if (pkt->pts != AV_NOPTS_VALUE) {
1473
            end_time = av_rescale(pkt->pts, st->time_base.num * (int64_t)AV_TIME_BASE, st->time_base.den);
1474
            duration = end_time - st->start_time;
1475
            if (duration > 0) {
1476
                if (st->duration == AV_NOPTS_VALUE ||
1477
                    st->duration < duration)
1478
                    st->duration = duration;
1479
            }
1480
        }
1481
        av_free_packet(pkt);
1482
    }
1483
    
1484
    /* estimate total duration */
1485
    end_time = MININT64;
1486
    for(i = 0;i < ic->nb_streams; i++) {
1487
        st = ic->streams[i];
1488
        if (st->duration != AV_NOPTS_VALUE) {
1489
            end_time1 = st->start_time + st->duration;
1490
            if (end_time1 > end_time)
1491
                end_time = end_time1;
1492
        }
1493
    }
1494
    
1495
    /* update start_time (new stream may have been created, so we do
1496
       it at the end */
1497
    if (ic->start_time != AV_NOPTS_VALUE) {
1498
        for(i = 0; i < ic->nb_streams; i++) {
1499
            st = ic->streams[i];
1500
            if (st->start_time == AV_NOPTS_VALUE)
1501
                st->start_time = ic->start_time;
1502
        }
1503
    }
1504

    
1505
    if (end_time != MININT64) {
1506
        /* put dummy values for duration if needed */
1507
        for(i = 0;i < ic->nb_streams; i++) {
1508
            st = ic->streams[i];
1509
            if (st->duration == AV_NOPTS_VALUE && 
1510
                st->start_time != AV_NOPTS_VALUE)
1511
                st->duration = end_time - st->start_time;
1512
        }
1513
        ic->duration = end_time - ic->start_time;
1514
    }
1515

    
1516
    url_fseek(&ic->pb, 0, SEEK_SET);
1517
}
1518

    
1519
static void av_estimate_timings(AVFormatContext *ic)
1520
{
1521
    URLContext *h;
1522
    int64_t file_size;
1523

    
1524
    /* get the file size, if possible */
1525
    if (ic->iformat->flags & AVFMT_NOFILE) {
1526
        file_size = 0;
1527
    } else {
1528
        h = url_fileno(&ic->pb);
1529
        file_size = url_filesize(h);
1530
        if (file_size < 0)
1531
            file_size = 0;
1532
    }
1533
    ic->file_size = file_size;
1534

    
1535
    if (ic->iformat == &mpegps_demux) {
1536
        /* get accurate estimate from the PTSes */
1537
        av_estimate_timings_from_pts(ic);
1538
    } else if (av_has_timings(ic)) {
1539
        /* at least one components has timings - we use them for all
1540
           the components */
1541
        fill_all_stream_timings(ic);
1542
    } else {
1543
        /* less precise: use bit rate info */
1544
        av_estimate_timings_from_bit_rate(ic);
1545
    }
1546
    av_update_stream_timings(ic);
1547

    
1548
#if 0
1549
    {
1550
        int i;
1551
        AVStream *st;
1552
        for(i = 0;i < ic->nb_streams; i++) {
1553
            st = ic->streams[i];
1554
        printf("%d: start_time: %0.3f duration: %0.3f\n", 
1555
               i, (double)st->start_time / AV_TIME_BASE, 
1556
               (double)st->duration / AV_TIME_BASE);
1557
        }
1558
        printf("stream: start_time: %0.3f duration: %0.3f bitrate=%d kb/s\n", 
1559
               (double)ic->start_time / AV_TIME_BASE, 
1560
               (double)ic->duration / AV_TIME_BASE,
1561
               ic->bit_rate / 1000);
1562
    }
1563
#endif
1564
}
1565

    
1566
static int has_codec_parameters(AVCodecContext *enc)
1567
{
1568
    int val;
1569
    switch(enc->codec_type) {
1570
    case CODEC_TYPE_AUDIO:
1571
        val = enc->sample_rate;
1572
        break;
1573
    case CODEC_TYPE_VIDEO:
1574
        val = enc->width;
1575
        break;
1576
    default:
1577
        val = 1;
1578
        break;
1579
    }
1580
    return (val != 0);
1581
}
1582

    
1583
static int try_decode_frame(AVStream *st, const uint8_t *data, int size)
1584
{
1585
    int16_t *samples;
1586
    AVCodec *codec;
1587
    int got_picture, ret;
1588
    AVFrame picture;
1589
    
1590
    codec = avcodec_find_decoder(st->codec.codec_id);
1591
    if (!codec)
1592
        return -1;
1593
    ret = avcodec_open(&st->codec, codec);
1594
    if (ret < 0)
1595
        return ret;
1596
    switch(st->codec.codec_type) {
1597
    case CODEC_TYPE_VIDEO:
1598
        ret = avcodec_decode_video(&st->codec, &picture, 
1599
                                   &got_picture, (uint8_t *)data, size);
1600
        break;
1601
    case CODEC_TYPE_AUDIO:
1602
        samples = av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1603
        if (!samples)
1604
            goto fail;
1605
        ret = avcodec_decode_audio(&st->codec, samples, 
1606
                                   &got_picture, (uint8_t *)data, size);
1607
        av_free(samples);
1608
        break;
1609
    default:
1610
        break;
1611
    }
1612
 fail:
1613
    avcodec_close(&st->codec);
1614
    return ret;
1615
}
1616

    
1617
/* absolute maximum size we read until we abort */
1618
#define MAX_READ_SIZE        5000000
1619

    
1620
/* maximum duration until we stop analysing the stream */
1621
#define MAX_STREAM_DURATION  ((int)(AV_TIME_BASE * 1.0))
1622

    
1623
/**
1624
 * Read the beginning of a media file to get stream information. This
1625
 * is useful for file formats with no headers such as MPEG. This
1626
 * function also compute the real frame rate in case of mpeg2 repeat
1627
 * frame mode.
1628
 *
1629
 * @param ic media file handle
1630
 * @return >=0 if OK. AVERROR_xxx if error.  
1631
 */
1632
int av_find_stream_info(AVFormatContext *ic)
1633
{
1634
    int i, count, ret, read_size;
1635
    AVStream *st;
1636
    AVPacket pkt1, *pkt;
1637
    AVPacketList *pktl=NULL, **ppktl;
1638

    
1639
    count = 0;
1640
    read_size = 0;
1641
    ppktl = &ic->packet_buffer;
1642
    for(;;) {
1643
        /* check if one codec still needs to be handled */
1644
        for(i=0;i<ic->nb_streams;i++) {
1645
            st = ic->streams[i];
1646
            if (!has_codec_parameters(&st->codec))
1647
                break;
1648
        }
1649
        if (i == ic->nb_streams) {
1650
            /* NOTE: if the format has no header, then we need to read
1651
               some packets to get most of the streams, so we cannot
1652
               stop here */
1653
            if (!(ic->ctx_flags & AVFMTCTX_NOHEADER)) {
1654
                /* if we found the info for all the codecs, we can stop */
1655
                ret = count;
1656
                break;
1657
            }
1658
        } else {
1659
            /* we did not get all the codec info, but we read too much data */
1660
            if (read_size >= MAX_READ_SIZE) {
1661
                ret = count;
1662
                break;
1663
            }
1664
        }
1665

    
1666
        /* NOTE: a new stream can be added there if no header in file
1667
           (AVFMTCTX_NOHEADER) */
1668
        ret = av_read_frame_internal(ic, &pkt1);
1669
        if (ret < 0) {
1670
            /* EOF or error */
1671
            ret = -1; /* we could not have all the codec parameters before EOF */
1672
            if ((ic->ctx_flags & AVFMTCTX_NOHEADER) &&
1673
                i == ic->nb_streams)
1674
                ret = 0;
1675
            break;
1676
        }
1677

    
1678
        pktl = av_mallocz(sizeof(AVPacketList));
1679
        if (!pktl) {
1680
            ret = AVERROR_NOMEM;
1681
            break;
1682
        }
1683

    
1684
        /* add the packet in the buffered packet list */
1685
        *ppktl = pktl;
1686
        ppktl = &pktl->next;
1687

    
1688
        pkt = &pktl->pkt;
1689
        *pkt = pkt1;
1690
        
1691
        /* duplicate the packet */
1692
        if (av_dup_packet(pkt) < 0) {
1693
                ret = AVERROR_NOMEM;
1694
                break;
1695
        }
1696

    
1697
        read_size += pkt->size;
1698

    
1699
        st = ic->streams[pkt->stream_index];
1700
        st->codec_info_duration += pkt->duration;
1701
        if (pkt->duration != 0)
1702
            st->codec_info_nb_frames++;
1703

    
1704
        /* if still no information, we try to open the codec and to
1705
           decompress the frame. We try to avoid that in most cases as
1706
           it takes longer and uses more memory. For MPEG4, we need to
1707
           decompress for Quicktime. */
1708
        if (!has_codec_parameters(&st->codec) &&
1709
            (st->codec.codec_id == CODEC_ID_FLV1 ||
1710
             st->codec.codec_id == CODEC_ID_H264 ||
1711
             st->codec.codec_id == CODEC_ID_H263 ||
1712
             st->codec.codec_id == CODEC_ID_VORBIS ||
1713
             st->codec.codec_id == CODEC_ID_MJPEG ||
1714
             (st->codec.codec_id == CODEC_ID_MPEG4 && !st->need_parsing)))
1715
            try_decode_frame(st, pkt->data, pkt->size);
1716
        
1717
        if (st->codec_info_duration >= MAX_STREAM_DURATION) {
1718
            break;
1719
        }
1720
        count++;
1721
    }
1722

    
1723
    /* set real frame rate info */
1724
    for(i=0;i<ic->nb_streams;i++) {
1725
        st = ic->streams[i];
1726
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
1727
            /* compute the real frame rate for telecine */
1728
            if ((st->codec.codec_id == CODEC_ID_MPEG1VIDEO ||
1729
                 st->codec.codec_id == CODEC_ID_MPEG2VIDEO) &&
1730
                st->codec.sub_id == 2) {
1731
                if (st->codec_info_nb_frames >= 20) {
1732
                    float coded_frame_rate, est_frame_rate;
1733
                    est_frame_rate = ((double)st->codec_info_nb_frames * AV_TIME_BASE) / 
1734
                        (double)st->codec_info_duration ;
1735
                    coded_frame_rate = (double)st->codec.frame_rate /
1736
                        (double)st->codec.frame_rate_base;
1737
#if 0
1738
                    printf("telecine: coded_frame_rate=%0.3f est_frame_rate=%0.3f\n", 
1739
                           coded_frame_rate, est_frame_rate);
1740
#endif
1741
                    /* if we detect that it could be a telecine, we
1742
                       signal it. It would be better to do it at a
1743
                       higher level as it can change in a film */
1744
                    if (coded_frame_rate >= 24.97 && 
1745
                        (est_frame_rate >= 23.5 && est_frame_rate < 24.5)) {
1746
                        st->r_frame_rate = 24024;
1747
                        st->r_frame_rate_base = 1001;
1748
                    }
1749
                }
1750
            }
1751
            /* if no real frame rate, use the codec one */
1752
            if (!st->r_frame_rate){
1753
                st->r_frame_rate      = st->codec.frame_rate;
1754
                st->r_frame_rate_base = st->codec.frame_rate_base;
1755
            }
1756
        }
1757
    }
1758

    
1759
    av_estimate_timings(ic);
1760
#if 0
1761
    /* correct DTS for b frame streams with no timestamps */
1762
    for(i=0;i<ic->nb_streams;i++) {
1763
        st = ic->streams[i];
1764
        if (st->codec.codec_type == CODEC_TYPE_VIDEO) {
1765
            if(b-frames){
1766
                ppktl = &ic->packet_buffer;
1767
                while(ppkt1){
1768
                    if(ppkt1->stream_index != i)
1769
                        continue;
1770
                    if(ppkt1->pkt->dts < 0)
1771
                        break;
1772
                    if(ppkt1->pkt->pts != AV_NOPTS_VALUE)
1773
                        break;
1774
                    ppkt1->pkt->dts -= delta;
1775
                    ppkt1= ppkt1->next;
1776
                }
1777
                if(ppkt1)
1778
                    continue;
1779
                st->cur_dts -= delta;
1780
            }
1781
        }
1782
    }
1783
#endif
1784
    return ret;
1785
}
1786

    
1787
/*******************************************************/
1788

    
1789
/**
1790
 * start playing a network based stream (e.g. RTSP stream) at the
1791
 * current position 
1792
 */
1793
int av_read_play(AVFormatContext *s)
1794
{
1795
    if (!s->iformat->read_play)
1796
        return AVERROR_NOTSUPP;
1797
    return s->iformat->read_play(s);
1798
}
1799

    
1800
/**
1801
 * pause a network based stream (e.g. RTSP stream). Use av_read_play()
1802
 * to resume it.
1803
 */
1804
int av_read_pause(AVFormatContext *s)
1805
{
1806
    if (!s->iformat->read_pause)
1807
        return AVERROR_NOTSUPP;
1808
    return s->iformat->read_pause(s);
1809
}
1810

    
1811
/**
1812
 * Close a media file (but not its codecs)
1813
 *
1814
 * @param s media file handle
1815
 */
1816
void av_close_input_file(AVFormatContext *s)
1817
{
1818
    int i, must_open_file;
1819
    AVStream *st;
1820

    
1821
    /* free previous packet */
1822
    if (s->cur_st && s->cur_st->parser)
1823
        av_free_packet(&s->cur_pkt); 
1824

    
1825
    if (s->iformat->read_close)
1826
        s->iformat->read_close(s);
1827
    for(i=0;i<s->nb_streams;i++) {
1828
        /* free all data in a stream component */
1829
        st = s->streams[i];
1830
        if (st->parser) {
1831
            av_parser_close(st->parser);
1832
        }
1833
        av_free(st->index_entries);
1834
        av_free(st);
1835
    }
1836
    flush_packet_queue(s);
1837
    must_open_file = 1;
1838
    if (s->iformat->flags & AVFMT_NOFILE) {
1839
        must_open_file = 0;
1840
    }
1841
    if (must_open_file) {
1842
        url_fclose(&s->pb);
1843
    }
1844
    av_freep(&s->priv_data);
1845
    av_free(s);
1846
}
1847

    
1848
/**
1849
 * Add a new stream to a media file. Can only be called in the
1850
 * read_header function. If the flag AVFMTCTX_NOHEADER is in the
1851
 * format context, then new streams can be added in read_packet too.
1852
 *
1853
 *
1854
 * @param s media file handle
1855
 * @param id file format dependent stream id 
1856
 */
1857
AVStream *av_new_stream(AVFormatContext *s, int id)
1858
{
1859
    AVStream *st;
1860

    
1861
    if (s->nb_streams >= MAX_STREAMS)
1862
        return NULL;
1863

    
1864
    st = av_mallocz(sizeof(AVStream));
1865
    if (!st)
1866
        return NULL;
1867
    avcodec_get_context_defaults(&st->codec);
1868
    if (s->iformat) {
1869
        /* no default bitrate if decoding */
1870
        st->codec.bit_rate = 0;
1871
    }
1872
    st->index = s->nb_streams;
1873
    st->id = id;
1874
    st->start_time = AV_NOPTS_VALUE;
1875
    st->duration = AV_NOPTS_VALUE;
1876
    st->cur_dts = AV_NOPTS_VALUE;
1877

    
1878
    /* default pts settings is MPEG like */
1879
    av_set_pts_info(st, 33, 1, 90000);
1880
    st->last_IP_pts = AV_NOPTS_VALUE;
1881

    
1882
    s->streams[s->nb_streams++] = st;
1883
    return st;
1884
}
1885

    
1886
/************************************************************/
1887
/* output media file */
1888

    
1889
int av_set_parameters(AVFormatContext *s, AVFormatParameters *ap)
1890
{
1891
    int ret;
1892
    
1893
    if (s->oformat->priv_data_size > 0) {
1894
        s->priv_data = av_mallocz(s->oformat->priv_data_size);
1895
        if (!s->priv_data)
1896
            return AVERROR_NOMEM;
1897
    } else
1898
        s->priv_data = NULL;
1899
        
1900
    if (s->oformat->set_parameters) {
1901
        ret = s->oformat->set_parameters(s, ap);
1902
        if (ret < 0)
1903
            return ret;
1904
    }
1905
    return 0;
1906
}
1907

    
1908
/**
1909
 * allocate the stream private data and write the stream header to an
1910
 * output media file
1911
 *
1912
 * @param s media file handle
1913
 * @return 0 if OK. AVERROR_xxx if error.  
1914
 */
1915
int av_write_header(AVFormatContext *s)
1916
{
1917
    int ret, i;
1918
    AVStream *st;
1919

    
1920
    ret = s->oformat->write_header(s);
1921
    if (ret < 0)
1922
        return ret;
1923

    
1924
    /* init PTS generation */
1925
    for(i=0;i<s->nb_streams;i++) {
1926
        st = s->streams[i];
1927

    
1928
        switch (st->codec.codec_type) {
1929
        case CODEC_TYPE_AUDIO:
1930
            av_frac_init(&st->pts, 0, 0, 
1931
                         (int64_t)st->time_base.num * st->codec.sample_rate);
1932
            break;
1933
        case CODEC_TYPE_VIDEO:
1934
            av_frac_init(&st->pts, 0, 0, 
1935
                         (int64_t)st->time_base.num * st->codec.frame_rate);
1936
            break;
1937
        default:
1938
            break;
1939
        }
1940
    }
1941
    return 0;
1942
}
1943

    
1944
//FIXME merge with compute_pkt_fields
1945
static void compute_pkt_fields2(AVStream *st, AVPacket *pkt){
1946
    int b_frames = FFMAX(st->codec.has_b_frames, st->codec.max_b_frames);
1947
    int num, den, frame_size;
1948

    
1949
//    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, b_frames, pkt->size, pkt->stream_index);
1950
    
1951
/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)
1952
        return -1;*/
1953
            
1954
    if(pkt->pts != AV_NOPTS_VALUE)
1955
        pkt->pts = av_rescale(pkt->pts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1956
    if(pkt->dts != AV_NOPTS_VALUE)
1957
        pkt->dts = av_rescale(pkt->dts, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1958

    
1959
    /* duration field */
1960
    pkt->duration = av_rescale(pkt->duration, st->time_base.den, AV_TIME_BASE * (int64_t)st->time_base.num);
1961
    if (pkt->duration == 0) {
1962
        compute_frame_duration(&num, &den, st, NULL, pkt);
1963
        if (den && num) {
1964
            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num);
1965
        }
1966
    }
1967

    
1968
    //XXX/FIXME this is a temporary hack until all encoders output pts
1969
    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !b_frames){
1970
        pkt->dts=
1971
//        pkt->pts= st->cur_dts;
1972
        pkt->pts= st->pts.val;
1973
    }
1974

    
1975
    //calculate dts from pts    
1976
    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE){
1977
        if(b_frames){
1978
            if(st->last_IP_pts == AV_NOPTS_VALUE){
1979
                st->last_IP_pts= -pkt->duration;
1980
            }
1981
            if(st->last_IP_pts < pkt->pts){
1982
                pkt->dts= st->last_IP_pts;
1983
                st->last_IP_pts= pkt->pts;
1984
            }else
1985
                pkt->dts= pkt->pts;
1986
        }else
1987
            pkt->dts= pkt->pts;
1988
    }
1989
    
1990
//    av_log(NULL, AV_LOG_DEBUG, "av_write_frame: pts2:%lld dts2:%lld\n", pkt->pts, pkt->dts);
1991
    st->cur_dts= pkt->dts;
1992
    st->pts.val= pkt->dts;
1993

    
1994
    /* update pts */
1995
    switch (st->codec.codec_type) {
1996
    case CODEC_TYPE_AUDIO:
1997
        frame_size = get_audio_frame_size(&st->codec, pkt->size);
1998

    
1999
        /* HACK/FIXME, we skip the initial 0-size packets as they are most likely equal to the encoder delay,
2000
           but it would be better if we had the real timestamps from the encoder */
2001
        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {
2002
            av_frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);
2003
        }
2004
        break;
2005
    case CODEC_TYPE_VIDEO:
2006
        av_frac_add(&st->pts, (int64_t)st->time_base.den * st->codec.frame_rate_base);
2007
        break;
2008
    default:
2009
        break;
2010
    }
2011
}
2012

    
2013
static void truncate_ts(AVStream *st, AVPacket *pkt){
2014
    int64_t pts_mask = (2LL << (st->pts_wrap_bits-1)) - 1;
2015
    
2016
//    if(pkt->dts < 0)
2017
//        pkt->dts= 0;  //this happens for low_delay=0 and b frames, FIXME, needs further invstigation about what we should do here
2018
    
2019
    pkt->pts &= pts_mask;
2020
    pkt->dts &= pts_mask;
2021
}
2022

    
2023
/**
2024
 * Write a packet to an output media file. The packet shall contain
2025
 * one audio or video frame.
2026
 *
2027
 * @param s media file handle
2028
 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2029
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2030
 */
2031
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
2032
{
2033
    int ret;
2034

    
2035
    compute_pkt_fields2(s->streams[pkt->stream_index], pkt);
2036
    
2037
    truncate_ts(s->streams[pkt->stream_index], pkt);
2038

    
2039
    ret= s->oformat->write_packet(s, pkt);
2040
    if(!ret)
2041
        ret= url_ferror(&s->pb);
2042
    return ret;
2043
}
2044

    
2045
/**
2046
 * interleave_packet implementation which will interleave per DTS.
2047
 */
2048
static int av_interleave_packet_per_dts(AVFormatContext *s, AVPacket *out, AVPacket *pkt, int flush){
2049
    AVPacketList *pktl, **next_point, *this_pktl;
2050
    int stream_count=0;
2051
    int streams[MAX_STREAMS];
2052

    
2053
    if(pkt){
2054
        AVStream *st= s->streams[ pkt->stream_index];
2055

    
2056
        assert(pkt->destruct != av_destruct_packet); //FIXME
2057

    
2058
        this_pktl = av_mallocz(sizeof(AVPacketList));
2059
        this_pktl->pkt= *pkt;
2060
        av_dup_packet(&this_pktl->pkt);
2061

    
2062
        next_point = &s->packet_buffer;
2063
        while(*next_point){
2064
            AVStream *st2= s->streams[ (*next_point)->pkt.stream_index];
2065
            int64_t left=  st2->time_base.num * (int64_t)st ->time_base.den;
2066
            int64_t right= st ->time_base.num * (int64_t)st2->time_base.den;
2067
            if((*next_point)->pkt.dts * left > pkt->dts * right) //FIXME this can overflow
2068
                break;
2069
            next_point= &(*next_point)->next;
2070
        }
2071
        this_pktl->next= *next_point;
2072
        *next_point= this_pktl;
2073
    }
2074
    
2075
    memset(streams, 0, sizeof(streams));
2076
    pktl= s->packet_buffer;
2077
    while(pktl){
2078
//av_log(s, AV_LOG_DEBUG, "show st:%d dts:%lld\n", pktl->pkt.stream_index, pktl->pkt.dts);
2079
        if(streams[ pktl->pkt.stream_index ] == 0)
2080
            stream_count++;
2081
        streams[ pktl->pkt.stream_index ]++;
2082
        pktl= pktl->next;
2083
    }
2084
    
2085
    if(s->nb_streams == stream_count || (flush && stream_count)){
2086
        pktl= s->packet_buffer;
2087
        *out= pktl->pkt;
2088
        
2089
        s->packet_buffer= pktl->next;        
2090
        av_freep(&pktl);
2091
        return 1;
2092
    }else{
2093
        av_init_packet(out);
2094
        return 0;
2095
    }
2096
}
2097

    
2098
/**
2099
 * Interleaves a AVPacket correctly so it can be muxed.
2100
 * @param out the interleaved packet will be output here
2101
 * @param in the input packet
2102
 * @param flush 1 if no further packets are available as input and all
2103
 *              remaining packets should be output
2104
 * @return 1 if a packet was output, 0 if no packet could be output, 
2105
 *         < 0 if an error occured
2106
 */
2107
static int av_interleave_packet(AVFormatContext *s, AVPacket *out, AVPacket *in, int flush){
2108
    if(s->oformat->interleave_packet)
2109
        return s->oformat->interleave_packet(s, out, in, flush);
2110
    else
2111
        return av_interleave_packet_per_dts(s, out, in, flush);
2112
}
2113

    
2114
/**
2115
 * Writes a packet to an output media file ensuring correct interleaving. 
2116
 * The packet shall contain one audio or video frame.
2117
 * If the packets are already correctly interleaved the application should
2118
 * call av_write_frame() instead as its slightly faster, its also important
2119
 * to keep in mind that completly non interleaved input will need huge amounts
2120
 * of memory to interleave with this, so its prefereable to interleave at the
2121
 * demuxer level
2122
 *
2123
 * @param s media file handle
2124
 * @param pkt the packet, which contains the stream_index, buf/buf_size, dts/pts, ...
2125
 * @return < 0 if error, = 0 if OK, 1 if end of stream wanted.
2126
 */
2127
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
2128
    AVStream *st= s->streams[ pkt->stream_index];
2129

    
2130
    compute_pkt_fields2(st, pkt);
2131
    
2132
    //FIXME/XXX/HACK drop zero sized packets
2133
    if(st->codec.codec_type == CODEC_TYPE_AUDIO && pkt->size==0)
2134
        return 0;
2135
    
2136
    if(pkt->dts == AV_NOPTS_VALUE)
2137
        return -1;
2138

    
2139
    for(;;){
2140
        AVPacket opkt;
2141
        int ret= av_interleave_packet(s, &opkt, pkt, 0);
2142
        if(ret<=0) //FIXME cleanup needed for ret<0 ?
2143
            return ret;
2144
        
2145
        truncate_ts(s->streams[opkt.stream_index], &opkt);
2146
        ret= s->oformat->write_packet(s, &opkt);
2147
        
2148
        av_free_packet(&opkt);
2149
        pkt= NULL;
2150
        
2151
        if(ret<0)
2152
            return ret;
2153
        if(url_ferror(&s->pb))
2154
            return url_ferror(&s->pb);
2155
    }
2156
}
2157

    
2158
/**
2159
 * write the stream trailer to an output media file and and free the
2160
 * file private data.
2161
 *
2162
 * @param s media file handle
2163
 * @return 0 if OK. AVERROR_xxx if error.  */
2164
int av_write_trailer(AVFormatContext *s)
2165
{
2166
    int ret, i;
2167
    
2168
    for(;;){
2169
        AVPacket pkt;
2170
        ret= av_interleave_packet(s, &pkt, NULL, 1);
2171
        if(ret<0) //FIXME cleanup needed for ret<0 ?
2172
            goto fail;
2173
        if(!ret)
2174
            break;
2175
        
2176
        truncate_ts(s->streams[pkt.stream_index], &pkt);
2177
        ret= s->oformat->write_packet(s, &pkt);
2178
        
2179
        av_free_packet(&pkt);
2180
        
2181
        if(ret<0)
2182
            goto fail;
2183
        if(url_ferror(&s->pb))
2184
            goto fail;
2185
    }
2186

    
2187
    ret = s->oformat->write_trailer(s);
2188
fail:
2189
    if(ret == 0)
2190
       ret=url_ferror(&s->pb);
2191
    for(i=0;i<s->nb_streams;i++)
2192
        av_freep(&s->streams[i]->priv_data);
2193
    av_freep(&s->priv_data);
2194
    return ret;
2195
}
2196

    
2197
/* "user interface" functions */
2198

    
2199
void dump_format(AVFormatContext *ic,
2200
                 int index, 
2201
                 const char *url,
2202
                 int is_output)
2203
{
2204
    int i, flags;
2205
    char buf[256];
2206

    
2207
    av_log(NULL, AV_LOG_DEBUG, "%s #%d, %s, %s '%s':\n", 
2208
            is_output ? "Output" : "Input",
2209
            index, 
2210
            is_output ? ic->oformat->name : ic->iformat->name, 
2211
            is_output ? "to" : "from", url);
2212
    if (!is_output) {
2213
        av_log(NULL, AV_LOG_DEBUG, "  Duration: ");
2214
        if (ic->duration != AV_NOPTS_VALUE) {
2215
            int hours, mins, secs, us;
2216
            secs = ic->duration / AV_TIME_BASE;
2217
            us = ic->duration % AV_TIME_BASE;
2218
            mins = secs / 60;
2219
            secs %= 60;
2220
            hours = mins / 60;
2221
            mins %= 60;
2222
            av_log(NULL, AV_LOG_DEBUG, "%02d:%02d:%02d.%01d", hours, mins, secs, 
2223
                   (10 * us) / AV_TIME_BASE);
2224
        } else {
2225
            av_log(NULL, AV_LOG_DEBUG, "N/A");
2226
        }
2227
        av_log(NULL, AV_LOG_DEBUG, ", bitrate: ");
2228
        if (ic->bit_rate) {
2229
            av_log(NULL, AV_LOG_DEBUG,"%d kb/s", ic->bit_rate / 1000);
2230
        } else {
2231
            av_log(NULL, AV_LOG_DEBUG, "N/A");
2232
        }
2233
        av_log(NULL, AV_LOG_DEBUG, "\n");
2234
    }
2235
    for(i=0;i<ic->nb_streams;i++) {
2236
        AVStream *st = ic->streams[i];
2237
        avcodec_string(buf, sizeof(buf), &st->codec, is_output);
2238
        av_log(NULL, AV_LOG_DEBUG, "  Stream #%d.%d", index, i);
2239
        /* the pid is an important information, so we display it */
2240
        /* XXX: add a generic system */
2241
        if (is_output)
2242
            flags = ic->oformat->flags;
2243
        else
2244
            flags = ic->iformat->flags;
2245
        if (flags & AVFMT_SHOW_IDS) {
2246
            av_log(NULL, AV_LOG_DEBUG, "[0x%x]", st->id);
2247
        }
2248
        av_log(NULL, AV_LOG_DEBUG, ": %s\n", buf);
2249
    }
2250
}
2251

    
2252
typedef struct {
2253
    const char *abv;
2254
    int width, height;
2255
    int frame_rate, frame_rate_base;
2256
} AbvEntry;
2257

    
2258
static AbvEntry frame_abvs[] = {
2259
    { "ntsc",      720, 480, 30000, 1001 },
2260
    { "pal",       720, 576,    25,    1 },
2261
    { "qntsc",     352, 240, 30000, 1001 }, /* VCD compliant ntsc */
2262
    { "qpal",      352, 288,    25,    1 }, /* VCD compliant pal */
2263
    { "sntsc",     640, 480, 30000, 1001 }, /* square pixel ntsc */
2264
    { "spal",      768, 576,    25,    1 }, /* square pixel pal */
2265
    { "film",      352, 240,    24,    1 },
2266
    { "ntsc-film", 352, 240, 24000, 1001 },
2267
    { "sqcif",     128,  96,     0,    0 },
2268
    { "qcif",      176, 144,     0,    0 },
2269
    { "cif",       352, 288,     0,    0 },
2270
    { "4cif",      704, 576,     0,    0 },
2271
};
2272

    
2273
int parse_image_size(int *width_ptr, int *height_ptr, const char *str)
2274
{
2275
    int i;
2276
    int n = sizeof(frame_abvs) / sizeof(AbvEntry);
2277
    const char *p;
2278
    int frame_width = 0, frame_height = 0;
2279

    
2280
    for(i=0;i<n;i++) {
2281
        if (!strcmp(frame_abvs[i].abv, str)) {
2282
            frame_width = frame_abvs[i].width;
2283
            frame_height = frame_abvs[i].height;
2284
            break;
2285
        }
2286
    }
2287
    if (i == n) {
2288
        p = str;
2289
        frame_width = strtol(p, (char **)&p, 10);
2290
        if (*p)
2291
            p++;
2292
        frame_height = strtol(p, (char **)&p, 10);
2293
    }
2294
    if (frame_width <= 0 || frame_height <= 0)
2295
        return -1;
2296
    *width_ptr = frame_width;
2297
    *height_ptr = frame_height;
2298
    return 0;
2299
}
2300

    
2301
int parse_frame_rate(int *frame_rate, int *frame_rate_base, const char *arg)
2302
{
2303
    int i;
2304
    char* cp;
2305
   
2306
    /* First, we check our abbreviation table */
2307
    for (i = 0; i < sizeof(frame_abvs)/sizeof(*frame_abvs); ++i)
2308
         if (!strcmp(frame_abvs[i].abv, arg)) {
2309
             *frame_rate = frame_abvs[i].frame_rate;
2310
             *frame_rate_base = frame_abvs[i].frame_rate_base;
2311
             return 0;
2312
         }
2313

    
2314
    /* Then, we try to parse it as fraction */
2315
    cp = strchr(arg, '/');
2316
    if (cp) {
2317
        char* cpp;
2318
        *frame_rate = strtol(arg, &cpp, 10);
2319
        if (cpp != arg || cpp == cp) 
2320
            *frame_rate_base = strtol(cp+1, &cpp, 10);
2321
        else
2322
           *frame_rate = 0;
2323
    } 
2324
    else {
2325
        /* Finally we give up and parse it as double */
2326
        *frame_rate_base = DEFAULT_FRAME_RATE_BASE; //FIXME use av_d2q()
2327
        *frame_rate = (int)(strtod(arg, 0) * (*frame_rate_base) + 0.5);
2328
    }
2329
    if (!*frame_rate || !*frame_rate_base)
2330
        return -1;
2331
    else
2332
        return 0;
2333
}
2334

    
2335
/* Syntax:
2336
 * - If not a duration:
2337
 *  [{YYYY-MM-DD|YYYYMMDD}]{T| }{HH[:MM[:SS[.m...]]][Z]|HH[MM[SS[.m...]]][Z]}
2338
 * Time is localtime unless Z is suffixed to the end. In this case GMT
2339
 * Return the date in micro seconds since 1970 
2340
 * - If duration:
2341
 *  HH[:MM[:SS[.m...]]]
2342
 *  S+[.m...]
2343
 */
2344
int64_t parse_date(const char *datestr, int duration)
2345
{
2346
    const char *p;
2347
    int64_t t;
2348
    struct tm dt;
2349
    int i;
2350
    static const char *date_fmt[] = {
2351
        "%Y-%m-%d",
2352
        "%Y%m%d",
2353
    };
2354
    static const char *time_fmt[] = {
2355
        "%H:%M:%S",
2356
        "%H%M%S",
2357
    };
2358
    const char *q;
2359
    int is_utc, len;
2360
    char lastch;
2361
    int negative = 0;
2362

    
2363
#undef time
2364
    time_t now = time(0);
2365

    
2366
    len = strlen(datestr);
2367
    if (len > 0)
2368
        lastch = datestr[len - 1];
2369
    else
2370
        lastch = '\0';
2371
    is_utc = (lastch == 'z' || lastch == 'Z');
2372

    
2373
    memset(&dt, 0, sizeof(dt));
2374

    
2375
    p = datestr;
2376
    q = NULL;
2377
    if (!duration) {
2378
        for (i = 0; i < sizeof(date_fmt) / sizeof(date_fmt[0]); i++) {
2379
            q = small_strptime(p, date_fmt[i], &dt);
2380
            if (q) {
2381
                break;
2382
            }
2383
        }
2384

    
2385
        if (!q) {
2386
            if (is_utc) {
2387
                dt = *gmtime(&now);
2388
            } else {
2389
                dt = *localtime(&now);
2390
            }
2391
            dt.tm_hour = dt.tm_min = dt.tm_sec = 0;
2392
        } else {
2393
            p = q;
2394
        }
2395

    
2396
        if (*p == 'T' || *p == 't' || *p == ' ')
2397
            p++;
2398

    
2399
        for (i = 0; i < sizeof(time_fmt) / sizeof(time_fmt[0]); i++) {
2400
            q = small_strptime(p, time_fmt[i], &dt);
2401
            if (q) {
2402
                break;
2403
            }
2404
        }
2405
    } else {
2406
        if (p[0] == '-') {
2407
            negative = 1;
2408
            ++p;
2409
        }
2410
        q = small_strptime(p, time_fmt[0], &dt);
2411
        if (!q) {
2412
            dt.tm_sec = strtol(p, (char **)&q, 10);
2413
            dt.tm_min = 0;
2414
            dt.tm_hour = 0;
2415
        }
2416
    }
2417

    
2418
    /* Now we have all the fields that we can get */
2419
    if (!q) {
2420
        if (duration)
2421
            return 0;
2422
        else
2423
            return now * int64_t_C(1000000);
2424
    }
2425

    
2426
    if (duration) {
2427
        t = dt.tm_hour * 3600 + dt.tm_min * 60 + dt.tm_sec;
2428
    } else {
2429
        dt.tm_isdst = -1;       /* unknown */
2430
        if (is_utc) {
2431
            t = mktimegm(&dt);
2432
        } else {
2433
            t = mktime(&dt);
2434
        }
2435
    }
2436

    
2437
    t *= 1000000;
2438

    
2439
    if (*q == '.') {
2440
        int val, n;
2441
        q++;
2442
        for (val = 0, n = 100000; n >= 1; n /= 10, q++) {
2443
            if (!isdigit(*q)) 
2444
                break;
2445
            val += n * (*q - '0');
2446
        }
2447
        t += val;
2448
    }
2449
    return negative ? -t : t;
2450
}
2451

    
2452
/* syntax: '?tag1=val1&tag2=val2...'. Little URL decoding is done. Return
2453
   1 if found */
2454
int find_info_tag(char *arg, int arg_size, const char *tag1, const char *info)
2455
{
2456
    const char *p;
2457
    char tag[128], *q;
2458

    
2459
    p = info;
2460
    if (*p == '?')
2461
        p++;
2462
    for(;;) {
2463
        q = tag;
2464
        while (*p != '\0' && *p != '=' && *p != '&') {
2465
            if ((q - tag) < sizeof(tag) - 1)
2466
                *q++ = *p;
2467
            p++;
2468
        }
2469
        *q = '\0';
2470
        q = arg;
2471
        if (*p == '=') {
2472
            p++;
2473
            while (*p != '&' && *p != '\0') {
2474
                if ((q - arg) < arg_size - 1) {
2475
                    if (*p == '+')
2476
                        *q++ = ' ';
2477
                    else
2478
                        *q++ = *p;
2479
                }
2480
                p++;
2481
            }
2482
            *q = '\0';
2483
        }
2484
        if (!strcmp(tag, tag1)) 
2485
            return 1;
2486
        if (*p != '&')
2487
            break;
2488
        p++;
2489
    }
2490
    return 0;
2491
}
2492

    
2493
/* Return in 'buf' the path with '%d' replaced by number. Also handles
2494
   the '%0nd' format where 'n' is the total number of digits and
2495
   '%%'. Return 0 if OK, and -1 if format error */
2496
int get_frame_filename(char *buf, int buf_size,
2497
                       const char *path, int number)
2498
{
2499
    const char *p;
2500
    char *q, buf1[20], c;
2501
    int nd, len, percentd_found;
2502

    
2503
    q = buf;
2504
    p = path;
2505
    percentd_found = 0;
2506
    for(;;) {
2507
        c = *p++;
2508
        if (c == '\0')
2509
            break;
2510
        if (c == '%') {
2511
            do {
2512
                nd = 0;
2513
                while (isdigit(*p)) {
2514
                    nd = nd * 10 + *p++ - '0';
2515
                }
2516
                c = *p++;
2517
            } while (isdigit(c));
2518

    
2519
            switch(c) {
2520
            case '%':
2521
                goto addchar;
2522
            case 'd':
2523
                if (percentd_found)
2524
                    goto fail;
2525
                percentd_found = 1;
2526
                snprintf(buf1, sizeof(buf1), "%0*d", nd, number);
2527
                len = strlen(buf1);
2528
                if ((q - buf + len) > buf_size - 1)
2529
                    goto fail;
2530
                memcpy(q, buf1, len);
2531
                q += len;
2532
                break;
2533
            default:
2534
                goto fail;
2535
            }
2536
        } else {
2537
        addchar:
2538
            if ((q - buf) < buf_size - 1)
2539
                *q++ = c;
2540
        }
2541
    }
2542
    if (!percentd_found)
2543
        goto fail;
2544
    *q = '\0';
2545
    return 0;
2546
 fail:
2547
    *q = '\0';
2548
    return -1;
2549
}
2550

    
2551
/**
2552
 * Print  nice hexa dump of a buffer
2553
 * @param f stream for output
2554
 * @param buf buffer
2555
 * @param size buffer size
2556
 */
2557
void av_hex_dump(FILE *f, uint8_t *buf, int size)
2558
{
2559
    int len, i, j, c;
2560

    
2561
    for(i=0;i<size;i+=16) {
2562
        len = size - i;
2563
        if (len > 16)
2564
            len = 16;
2565
        fprintf(f, "%08x ", i);
2566
        for(j=0;j<16;j++) {
2567
            if (j < len)
2568
                fprintf(f, " %02x", buf[i+j]);
2569
            else
2570
                fprintf(f, "   ");
2571
        }
2572
        fprintf(f, " ");
2573
        for(j=0;j<len;j++) {
2574
            c = buf[i+j];
2575
            if (c < ' ' || c > '~')
2576
                c = '.';
2577
            fprintf(f, "%c", c);
2578
        }
2579
        fprintf(f, "\n");
2580
    }
2581
}
2582

    
2583
/**
2584
 * Print on 'f' a nice dump of a packet
2585
 * @param f stream for output
2586
 * @param pkt packet to dump
2587
 * @param dump_payload true if the payload must be displayed too
2588
 */
2589
void av_pkt_dump(FILE *f, AVPacket *pkt, int dump_payload)
2590
{
2591
    fprintf(f, "stream #%d:\n", pkt->stream_index);
2592
    fprintf(f, "  keyframe=%d\n", ((pkt->flags & PKT_FLAG_KEY) != 0));
2593
    fprintf(f, "  duration=%0.3f\n", (double)pkt->duration / AV_TIME_BASE);
2594
    /* DTS is _always_ valid after av_read_frame() */
2595
    fprintf(f, "  dts=");
2596
    if (pkt->dts == AV_NOPTS_VALUE)
2597
        fprintf(f, "N/A");
2598
    else
2599
        fprintf(f, "%0.3f", (double)pkt->dts / AV_TIME_BASE);
2600
    /* PTS may be not known if B frames are present */
2601
    fprintf(f, "  pts=");
2602
    if (pkt->pts == AV_NOPTS_VALUE)
2603
        fprintf(f, "N/A");
2604
    else
2605
        fprintf(f, "%0.3f", (double)pkt->pts / AV_TIME_BASE);
2606
    fprintf(f, "\n");
2607
    fprintf(f, "  size=%d\n", pkt->size);
2608
    if (dump_payload)
2609
        av_hex_dump(f, pkt->data, pkt->size);
2610
}
2611

    
2612
void url_split(char *proto, int proto_size,
2613
               char *authorization, int authorization_size,
2614
               char *hostname, int hostname_size,
2615
               int *port_ptr,
2616
               char *path, int path_size,
2617
               const char *url)
2618
{
2619
    const char *p;
2620
    char *q;
2621
    int port;
2622

    
2623
    port = -1;
2624

    
2625
    p = url;
2626
    q = proto;
2627
    while (*p != ':' && *p != '\0') {
2628
        if ((q - proto) < proto_size - 1)
2629
            *q++ = *p;
2630
        p++;
2631
    }
2632
    if (proto_size > 0)
2633
        *q = '\0';
2634
    if (authorization_size > 0)
2635
        authorization[0] = '\0';
2636
    if (*p == '\0') {
2637
        if (proto_size > 0)
2638
            proto[0] = '\0';
2639
        if (hostname_size > 0)
2640
            hostname[0] = '\0';
2641
        p = url;
2642
    } else {
2643
        char *at,*slash; // PETR: position of '@' character and '/' character
2644

    
2645
        p++;
2646
        if (*p == '/')
2647
            p++;
2648
        if (*p == '/')
2649
            p++;
2650
        at = strchr(p,'@'); // PETR: get the position of '@'
2651
        slash = strchr(p,'/');  // PETR: get position of '/' - end of hostname
2652
        if (at && slash && at > slash) at = NULL; // PETR: not interested in '@' behind '/'
2653

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

    
2656
         while ((at || *p != ':') && *p != '/' && *p != '?' && *p != '\0') { // PETR:
2657
            if (*p == '@') {    // PETR: passed '@'
2658
              if (authorization_size > 0)
2659
                  *q = '\0';
2660
              q = hostname;
2661
              at = NULL;
2662
            } else if (!at) {   // PETR: hostname
2663
              if ((q - hostname) < hostname_size - 1)
2664
                  *q++ = *p;
2665
            } else {
2666
              if ((q - authorization) < authorization_size - 1)
2667
                *q++ = *p;
2668
            }
2669
            p++;
2670
        }
2671
        if (hostname_size > 0)
2672
            *q = '\0';
2673
        if (*p == ':') {
2674
            p++;
2675
            port = strtoul(p, (char **)&p, 10);
2676
        }
2677
    }
2678
    if (port_ptr)
2679
        *port_ptr = port;
2680
    pstrcpy(path, path_size, p);
2681
}
2682

    
2683
/**
2684
 * Set the pts for a given stream
2685
 * @param s stream 
2686
 * @param pts_wrap_bits number of bits effectively used by the pts
2687
 *        (used for wrap control, 33 is the value for MPEG) 
2688
 * @param pts_num numerator to convert to seconds (MPEG: 1) 
2689
 * @param pts_den denominator to convert to seconds (MPEG: 90000)
2690
 */
2691
void av_set_pts_info(AVStream *s, int pts_wrap_bits,
2692
                     int pts_num, int pts_den)
2693
{
2694
    s->pts_wrap_bits = pts_wrap_bits;
2695
    s->time_base.num = pts_num;
2696
    s->time_base.den = pts_den;
2697
}
2698

    
2699
/* fraction handling */
2700

    
2701
/**
2702
 * f = val + (num / den) + 0.5. 'num' is normalized so that it is such
2703
 * as 0 <= num < den.
2704
 *
2705
 * @param f fractional number
2706
 * @param val integer value
2707
 * @param num must be >= 0
2708
 * @param den must be >= 1 
2709
 */
2710
void av_frac_init(AVFrac *f, int64_t val, int64_t num, int64_t den)
2711
{
2712
    num += (den >> 1);
2713
    if (num >= den) {
2714
        val += num / den;
2715
        num = num % den;
2716
    }
2717
    f->val = val;
2718
    f->num = num;
2719
    f->den = den;
2720
}
2721

    
2722
/* set f to (val + 0.5) */
2723
void av_frac_set(AVFrac *f, int64_t val)
2724
{
2725
    f->val = val;
2726
    f->num = f->den >> 1;
2727
}
2728

    
2729
/**
2730
 * Fractionnal addition to f: f = f + (incr / f->den)
2731
 *
2732
 * @param f fractional number
2733
 * @param incr increment, can be positive or negative
2734
 */
2735
void av_frac_add(AVFrac *f, int64_t incr)
2736
{
2737
    int64_t num, den;
2738

    
2739
    num = f->num + incr;
2740
    den = f->den;
2741
    if (num < 0) {
2742
        f->val += num / den;
2743
        num = num % den;
2744
        if (num < 0) {
2745
            num += den;
2746
            f->val--;
2747
        }
2748
    } else if (num >= den) {
2749
        f->val += num / den;
2750
        num = num % den;
2751
    }
2752
    f->num = num;
2753
}
2754

    
2755
/**
2756
 * register a new image format
2757
 * @param img_fmt Image format descriptor
2758
 */
2759
void av_register_image_format(AVImageFormat *img_fmt)
2760
{
2761
    AVImageFormat **p;
2762

    
2763
    p = &first_image_format;
2764
    while (*p != NULL) p = &(*p)->next;
2765
    *p = img_fmt;
2766
    img_fmt->next = NULL;
2767
}
2768

    
2769
/* guess image format */
2770
AVImageFormat *av_probe_image_format(AVProbeData *pd)
2771
{
2772
    AVImageFormat *fmt1, *fmt;
2773
    int score, score_max;
2774

    
2775
    fmt = NULL;
2776
    score_max = 0;
2777
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2778
        if (fmt1->img_probe) {
2779
            score = fmt1->img_probe(pd);
2780
            if (score > score_max) {
2781
                score_max = score;
2782
                fmt = fmt1;
2783
            }
2784
        }
2785
    }
2786
    return fmt;
2787
}
2788

    
2789
AVImageFormat *guess_image_format(const char *filename)
2790
{
2791
    AVImageFormat *fmt1;
2792

    
2793
    for(fmt1 = first_image_format; fmt1 != NULL; fmt1 = fmt1->next) {
2794
        if (fmt1->extensions && match_ext(filename, fmt1->extensions))
2795
            return fmt1;
2796
    }
2797
    return NULL;
2798
}
2799

    
2800
/**
2801
 * Read an image from a stream. 
2802
 * @param gb byte stream containing the image
2803
 * @param fmt image format, NULL if probing is required
2804
 */
2805
int av_read_image(ByteIOContext *pb, const char *filename,
2806
                  AVImageFormat *fmt,
2807
                  int (*alloc_cb)(void *, AVImageInfo *info), void *opaque)
2808
{
2809
    char buf[PROBE_BUF_SIZE];
2810
    AVProbeData probe_data, *pd = &probe_data;
2811
    offset_t pos;
2812
    int ret;
2813

    
2814
    if (!fmt) {
2815
        pd->filename = filename;
2816
        pd->buf = buf;
2817
        pos = url_ftell(pb);
2818
        pd->buf_size = get_buffer(pb, buf, PROBE_BUF_SIZE);
2819
        url_fseek(pb, pos, SEEK_SET);
2820
        fmt = av_probe_image_format(pd);
2821
    }
2822
    if (!fmt)
2823
        return AVERROR_NOFMT;
2824
    ret = fmt->img_read(pb, alloc_cb, opaque);
2825
    return ret;
2826
}
2827

    
2828
/**
2829
 * Write an image to a stream.
2830
 * @param pb byte stream for the image output
2831
 * @param fmt image format
2832
 * @param img image data and informations
2833
 */
2834
int av_write_image(ByteIOContext *pb, AVImageFormat *fmt, AVImageInfo *img)
2835
{
2836
    return fmt->img_write(pb, img);
2837
}
2838