ffmdec.c 30 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
/*
Baptiste Coudurier's avatar
Baptiste Coudurier committed
2
 * FFM (ffserver live feed) demuxer
3
 * Copyright (c) 2001 Fabrice Bellard
Fabrice Bellard's avatar
Fabrice Bellard committed
4
 *
5 6 7
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with FFmpeg; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Fabrice Bellard's avatar
Fabrice Bellard committed
20
 */
Baptiste Coudurier's avatar
Baptiste Coudurier committed
21

22 23
#include <stdint.h>

24
#include "libavutil/imgutils.h"
25
#include "libavutil/internal.h"
26
#include "libavutil/intreadwrite.h"
27
#include "libavutil/intfloat.h"
28
#include "libavutil/opt.h"
29 30
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
31
#include "libavutil/pixdesc.h"
32
#include "libavcodec/internal.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
33
#include "avformat.h"
34
#include "internal.h"
Baptiste Coudurier's avatar
Baptiste Coudurier committed
35
#include "ffm.h"
36
#include "avio_internal.h"
37

Fabrice Bellard's avatar
Fabrice Bellard committed
38 39 40
static int ffm_is_avail_data(AVFormatContext *s, int size)
{
    FFMContext *ffm = s->priv_data;
41
    int64_t pos, avail_size;
42
    ptrdiff_t len;
Fabrice Bellard's avatar
Fabrice Bellard committed
43 44

    len = ffm->packet_end - ffm->packet_ptr;
45 46
    if (size <= len)
        return 1;
47
    pos = avio_tell(s->pb);
48
    if (!ffm->write_index) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
49
        if (pos == ffm->file_size)
50 51 52
            return AVERROR_EOF;
        avail_size = ffm->file_size - pos;
    } else {
Fabrice Bellard's avatar
Fabrice Bellard committed
53 54
    if (pos == ffm->write_index) {
        /* exactly at the end of stream */
55 56 57 58
        if (ffm->server_attached)
            return AVERROR(EAGAIN);
        else
            return AVERROR_INVALIDDATA;
Fabrice Bellard's avatar
Fabrice Bellard committed
59 60 61 62 63
    } else if (pos < ffm->write_index) {
        avail_size = ffm->write_index - pos;
    } else {
        avail_size = (ffm->file_size - pos) + (ffm->write_index - FFM_PACKET_SIZE);
    }
64
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
65 66 67
    avail_size = (avail_size / ffm->packet_size) * (ffm->packet_size - FFM_HEADER_SIZE) + len;
    if (size <= avail_size)
        return 1;
68
    else if (ffm->server_attached)
69
        return AVERROR(EAGAIN);
70 71
    else
        return AVERROR_INVALIDDATA;
Fabrice Bellard's avatar
Fabrice Bellard committed
72 73
}

74
static int ffm_resync(AVFormatContext *s, uint32_t state)
75 76 77
{
    av_log(s, AV_LOG_ERROR, "resyncing\n");
    while (state != PACKET_ID) {
78
        if (avio_feof(s->pb)) {
79 80 81
            av_log(s, AV_LOG_ERROR, "cannot find FFM syncword\n");
            return -1;
        }
82
        state = (state << 8) | avio_r8(s->pb);
83 84 85 86
    }
    return 0;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
87
/* first is true if we read the frame header */
88
static int ffm_read_data(AVFormatContext *s,
89
                         uint8_t *buf, int size, int header)
Fabrice Bellard's avatar
Fabrice Bellard committed
90 91
{
    FFMContext *ffm = s->priv_data;
92
    AVIOContext *pb = s->pb;
93
    int fill_size, size1, frame_offset;
94
    uint32_t id;
95
    ptrdiff_t len;
96
    int64_t last_pos = -1;
Fabrice Bellard's avatar
Fabrice Bellard committed
97 98 99 100 101

    size1 = size;
    while (size > 0) {
    redo:
        len = ffm->packet_end - ffm->packet_ptr;
102 103
        if (len < 0)
            return -1;
Fabrice Bellard's avatar
Fabrice Bellard committed
104 105 106
        if (len > size)
            len = size;
        if (len == 0) {
107 108
            if (avio_tell(pb) == ffm->file_size) {
                if (ffm->server_attached) {
109
                    avio_seek(pb, ffm->packet_size, SEEK_SET);
110
                } else
111
                    return AVERROR_EOF;
112
            }
113
    retry_read:
114 115
            if (pb->buffer_size != ffm->packet_size) {
                int64_t tell = avio_tell(pb);
116 117 118
                int ret = ffio_set_buf_size(pb, ffm->packet_size);
                if (ret < 0)
                    return ret;
119 120
                avio_seek(pb, tell, SEEK_SET);
            }
121
            id = avio_rb16(pb); /* PACKET_ID */
122
            if (id != PACKET_ID) {
123 124
                if (ffm_resync(s, id) < 0)
                    return -1;
125 126
                last_pos = avio_tell(pb);
            }
127 128 129 130
            fill_size = avio_rb16(pb);
            ffm->dts = avio_rb64(pb);
            frame_offset = avio_rb16(pb);
            avio_read(pb, ffm->packet, ffm->packet_size - FFM_HEADER_SIZE);
131
            if (ffm->packet_size < FFM_HEADER_SIZE + fill_size || frame_offset < 0) {
132
                return -1;
133 134
            }
            ffm->packet_end = ffm->packet + (ffm->packet_size - FFM_HEADER_SIZE - fill_size);
Fabrice Bellard's avatar
Fabrice Bellard committed
135 136 137
            /* if first packet or resynchronization packet, we must
               handle it specifically */
            if (ffm->first_packet || (frame_offset & 0x8000)) {
138 139
                if (!frame_offset) {
                    /* This packet has no frame headers in it */
140
                    if (avio_tell(pb) >= ffm->packet_size * 3LL) {
141 142 143
                        int64_t seekback = FFMIN(ffm->packet_size * 2LL, avio_tell(pb) - last_pos);
                        seekback = FFMAX(seekback, 0);
                        avio_seek(pb, -seekback, SEEK_CUR);
144 145 146 147 148
                        goto retry_read;
                    }
                    /* This is bad, we cannot find a valid frame header */
                    return 0;
                }
Fabrice Bellard's avatar
Fabrice Bellard committed
149
                ffm->first_packet = 0;
150 151
                if ((frame_offset & 0x7fff) < FFM_HEADER_SIZE) {
                    ffm->packet_end = ffm->packet_ptr;
152
                    return -1;
153
                }
Fabrice Bellard's avatar
Fabrice Bellard committed
154
                ffm->packet_ptr = ffm->packet + (frame_offset & 0x7fff) - FFM_HEADER_SIZE;
155
                if (!header)
Fabrice Bellard's avatar
Fabrice Bellard committed
156 157 158 159 160 161 162 163 164 165
                    break;
            } else {
                ffm->packet_ptr = ffm->packet;
            }
            goto redo;
        }
        memcpy(buf, ffm->packet_ptr, len);
        buf += len;
        ffm->packet_ptr += len;
        size -= len;
166
        header = 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
167 168 169 170
    }
    return size1 - size;
}

171
/* ensure that actual seeking happens between FFM_PACKET_SIZE
172
   and file_size - FFM_PACKET_SIZE */
173
static int64_t ffm_seek1(AVFormatContext *s, int64_t pos1)
174 175
{
    FFMContext *ffm = s->priv_data;
176
    AVIOContext *pb = s->pb;
177
    int64_t pos;
178

179 180
    pos = FFMIN(pos1, ffm->file_size - FFM_PACKET_SIZE);
    pos = FFMAX(pos, FFM_PACKET_SIZE);
181
    ff_dlog(s, "seek to %"PRIx64" -> %"PRIx64"\n", pos1, pos);
182
    return avio_seek(pb, pos, SEEK_SET);
183 184
}

185
static int64_t get_dts(AVFormatContext *s, int64_t pos)
186
{
187
    AVIOContext *pb = s->pb;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
188
    int64_t dts;
189 190

    ffm_seek1(s, pos);
191
    avio_skip(pb, 4);
192
    dts = avio_rb64(pb);
193
    ff_dlog(s, "dts=%0.6f\n", dts / 1000000.0);
Baptiste Coudurier's avatar
Baptiste Coudurier committed
194
    return dts;
195
}
Fabrice Bellard's avatar
Fabrice Bellard committed
196

197 198 199
static void adjust_write_index(AVFormatContext *s)
{
    FFMContext *ffm = s->priv_data;
200
    AVIOContext *pb = s->pb;
201
    int64_t pts;
202 203
    //int64_t orig_write_index = ffm->write_index;
    int64_t pos_min, pos_max;
204
    int64_t pts_start;
205
    int64_t ptr = avio_tell(pb);
206 207 208 209 210


    pos_min = 0;
    pos_max = ffm->file_size - 2 * FFM_PACKET_SIZE;

Baptiste Coudurier's avatar
Baptiste Coudurier committed
211
    pts_start = get_dts(s, pos_min);
212

Baptiste Coudurier's avatar
Baptiste Coudurier committed
213
    pts = get_dts(s, pos_max);
214

215
    if (pts - 100000 > pts_start)
216
        goto end;
217 218 219

    ffm->write_index = FFM_PACKET_SIZE;

Baptiste Coudurier's avatar
Baptiste Coudurier committed
220
    pts_start = get_dts(s, pos_min);
221

Baptiste Coudurier's avatar
Baptiste Coudurier committed
222
    pts = get_dts(s, pos_max);
223 224 225

    if (pts - 100000 <= pts_start) {
        while (1) {
226
            int64_t newpos;
227 228 229 230 231 232 233
            int64_t newpts;

            newpos = ((pos_max + pos_min) / (2 * FFM_PACKET_SIZE)) * FFM_PACKET_SIZE;

            if (newpos == pos_min)
                break;

Baptiste Coudurier's avatar
Baptiste Coudurier committed
234
            newpts = get_dts(s, newpos);
235 236 237 238 239 240 241 242 243 244 245

            if (newpts - 100000 <= pts) {
                pos_max = newpos;
                pts = newpts;
            } else {
                pos_min = newpos;
            }
        }
        ffm->write_index += pos_max;
    }

246
 end:
247
    avio_seek(pb, ptr, SEEK_SET);
248 249 250
}


251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
static int ffm_append_recommended_configuration(AVStream *st, char **conf)
{
    int ret;
    size_t newsize;
    av_assert0(conf && st);
    if (!*conf)
        return 0;
    if (!st->recommended_encoder_configuration) {
        st->recommended_encoder_configuration = *conf;
        *conf = 0;
        return 0;
    }
    newsize = strlen(*conf) + strlen(st->recommended_encoder_configuration) + 2;
    if ((ret = av_reallocp(&st->recommended_encoder_configuration, newsize)) < 0)
        return ret;
    av_strlcat(st->recommended_encoder_configuration, ",", newsize);
    av_strlcat(st->recommended_encoder_configuration, *conf, newsize);
    av_freep(conf);
    return 0;
}

272 273
#define VALIDATE_PARAMETER(parameter, name, check) {                              \
    if (check) {                                                                  \
274
        av_log(s, AV_LOG_ERROR, "Invalid " name " %d\n", codecpar->parameter);   \
275 276 277 278 279
        ret = AVERROR_INVALIDDATA;                                                \
        goto fail;                                                                \
    }                                                                             \
}

280 281 282
static int ffm2_read_header(AVFormatContext *s)
{
    FFMContext *ffm = s->priv_data;
283
    AVStream *st = NULL;
284
    AVIOContext *pb = s->pb;
285
    AVCodecContext *dummy_codec = NULL;
286
    AVCodecParameters *codecpar = NULL;
287
    const AVCodecDescriptor *codec_desc;
288
    int ret;
289
    int f_main = 0, f_cprv = -1, f_stvi = -1, f_stau = -1;
290
    AVCodec *enc;
291
    char *buffer;
292 293

    ffm->packet_size = avio_rb32(pb);
294 295 296 297
    if (ffm->packet_size != FFM_PACKET_SIZE) {
        av_log(s, AV_LOG_ERROR, "Invalid packet size %d, expected size was %d\n",
               ffm->packet_size, FFM_PACKET_SIZE);
        ret = AVERROR_INVALIDDATA;
298
        goto fail;
299 300
    }

301 302
    ffm->write_index = avio_rb64(pb);
    /* get also filesize */
James Almer's avatar
James Almer committed
303
    if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
304 305 306 307 308 309
        ffm->file_size = avio_size(pb);
        if (ffm->write_index && 0)
            adjust_write_index(s);
    } else {
        ffm->file_size = (UINT64_C(1) << 63) - 1;
    }
310
    dummy_codec = avcodec_alloc_context3(NULL);
311

312
    while(!avio_feof(pb)) {
313 314 315 316
        unsigned id = avio_rb32(pb);
        unsigned size = avio_rb32(pb);
        int64_t next = avio_tell(pb) + size;
        char rc_eq_buf[128];
317
        int flags;
318 319 320 321 322 323

        if(!id)
            break;

        switch(id) {
        case MKBETAG('M', 'A', 'I', 'N'):
324 325 326 327
            if (f_main++) {
                ret = AVERROR(EINVAL);
                goto fail;
            }
328 329 330 331
            avio_rb32(pb); /* nb_streams */
            avio_rb32(pb); /* total bitrate */
            break;
        case MKBETAG('C', 'O', 'M', 'M'):
332
            f_cprv = f_stvi = f_stau = 0;
333
            st = avformat_new_stream(s, NULL);
334 335
            if (!st) {
                ret = AVERROR(ENOMEM);
336
                goto fail;
337
            }
338 339 340

            avpriv_set_pts_info(st, 64, 1, 1000000);

341
            codecpar = st->codecpar;
342
            /* generic info */
343 344
            codecpar->codec_id = avio_rb32(pb);
            codec_desc = avcodec_descriptor_get(codecpar->codec_id);
345
            if (!codec_desc) {
346 347
                av_log(s, AV_LOG_ERROR, "Invalid codec id: %d\n", codecpar->codec_id);
                codecpar->codec_id = AV_CODEC_ID_NONE;
348
                ret = AVERROR_INVALIDDATA;
349 350
                goto fail;
            }
351 352
            codecpar->codec_type = avio_r8(pb);
            if (codecpar->codec_type != codec_desc->type) {
353
                av_log(s, AV_LOG_ERROR, "Codec type mismatch: expected %d, found %d\n",
354 355 356
                       codec_desc->type, codecpar->codec_type);
                codecpar->codec_id = AV_CODEC_ID_NONE;
                codecpar->codec_type = AVMEDIA_TYPE_UNKNOWN;
357
                ret = AVERROR_INVALIDDATA;
358 359
                goto fail;
            }
360 361
            codecpar->bit_rate = avio_rb32(pb);
            if (codecpar->bit_rate < 0) {
362
                av_log(s, AV_LOG_ERROR, "Invalid bit rate %"PRId64"\n", codecpar->bit_rate);
363 364 365
                ret = AVERROR_INVALIDDATA;
                goto fail;
            }
366 367 368 369 370 371
            flags = avio_rb32(pb);
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
            st->codec->flags = flags;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
372 373
            avio_rb32(pb); // flags2
            avio_rb32(pb); // debug
374
            if (flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
375
                int size = avio_rb32(pb);
376 377 378 379 380
                if (size < 0 || size >= FF_MAX_EXTRADATA_SIZE) {
                    av_log(s, AV_LOG_ERROR, "Invalid extradata size %d\n", size);
                    ret = AVERROR_INVALIDDATA;
                    goto fail;
                }
381
                codecpar->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
382 383 384 385
                if (!codecpar->extradata) {
                    ret = AVERROR(ENOMEM);
                    goto fail;
                }
386 387
                codecpar->extradata_size = size;
                avio_read(pb, codecpar->extradata, size);
388
            }
389
            break;
390
        case MKBETAG('S', 'T', 'V', 'I'):
391
            if (f_stvi++ || codecpar->codec_type != AVMEDIA_TYPE_VIDEO) {
392 393 394
                ret = AVERROR(EINVAL);
                goto fail;
            }
395 396
            avio_rb32(pb); // time_base.num
            avio_rb32(pb); // time_base.den
397 398 399
            codecpar->width = avio_rb16(pb);
            codecpar->height = avio_rb16(pb);
            ret = av_image_check_size(codecpar->width, codecpar->height, 0, s);
400 401
            if (ret < 0)
                goto fail;
402
            avio_rb16(pb); // gop_size
403 404 405 406
            codecpar->format = avio_rb32(pb);
            if (!av_pix_fmt_desc_get(codecpar->format)) {
                av_log(s, AV_LOG_ERROR, "Invalid pix fmt id: %d\n", codecpar->format);
                codecpar->format = AV_PIX_FMT_NONE;
407
                ret = AVERROR_INVALIDDATA;
408 409
                goto fail;
            }
410 411 412 413 414 415
            avio_r8(pb);   // qmin
            avio_r8(pb);   // qmax
            avio_r8(pb);   // max_qdiff
            avio_rb16(pb); // qcompress / 10000.0
            avio_rb16(pb); // qblur / 10000.0
            avio_rb32(pb); // bit_rate_tolerance
416
            avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

            avio_rb32(pb); // rc_max_rate
            avio_rb32(pb); // rc_min_rate
            avio_rb32(pb); // rc_buffer_size
            avio_rb64(pb); // i_quant_factor
            avio_rb64(pb); // b_quant_factor
            avio_rb64(pb); // i_quant_offset
            avio_rb64(pb); // b_quant_offset
            avio_rb32(pb); // dct_algo
            avio_rb32(pb); // strict_std_compliance
            avio_rb32(pb); // max_b_frames
            avio_rb32(pb); // mpeg_quant
            avio_rb32(pb); // intra_dc_precision
            avio_rb32(pb); // me_method
            avio_rb32(pb); // mb_decision
            avio_rb32(pb); // nsse_weight
            avio_rb32(pb); // frame_skip_cmp
            avio_rb64(pb); // rc_buffer_aggressivity
435
            codecpar->codec_tag = avio_rb32(pb);
436 437 438 439 440 441 442 443 444 445 446 447
            avio_r8(pb);   // thread_count
            avio_rb32(pb); // coder_type
            avio_rb32(pb); // me_cmp
            avio_rb32(pb); // me_subpel_quality
            avio_rb32(pb); // me_range
            avio_rb32(pb); // keyint_min
            avio_rb32(pb); // scenechange_threshold
            avio_rb32(pb); // b_frame_strategy
            avio_rb64(pb); // qcompress
            avio_rb64(pb); // qblur
            avio_rb32(pb); // max_qdiff
            avio_rb32(pb); // refs
448 449
            break;
        case MKBETAG('S', 'T', 'A', 'U'):
450
            if (f_stau++ || codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
451 452 453
                ret = AVERROR(EINVAL);
                goto fail;
            }
454 455 456 457 458 459
            codecpar->sample_rate = avio_rb32(pb);
            VALIDATE_PARAMETER(sample_rate, "sample rate",        codecpar->sample_rate < 0)
            codecpar->channels = avio_rl16(pb);
            VALIDATE_PARAMETER(channels,    "number of channels", codecpar->channels < 0)
            codecpar->frame_size = avio_rl16(pb);
            VALIDATE_PARAMETER(frame_size,  "frame size",         codecpar->frame_size < 0)
460
            break;
461 462 463 464 465
        case MKBETAG('C', 'P', 'R', 'V'):
            if (f_cprv++) {
                ret = AVERROR(EINVAL);
                goto fail;
            }
466
            enc = avcodec_find_encoder(codecpar->codec_id);
467
            if (enc && enc->priv_data_size && enc->priv_class) {
468 469
                buffer = av_malloc(size + 1);
                if (!buffer) {
470 471 472
                    ret = AVERROR(ENOMEM);
                    goto fail;
                }
473 474 475
                avio_get_str(pb, size, buffer, size + 1);
                if ((ret = ffm_append_recommended_configuration(st, &buffer)) < 0)
                    goto fail;
476 477
            }
            break;
478
        case MKBETAG('S', '2', 'V', 'I'):
479
            if (f_stvi++ || !size || codecpar->codec_type != AVMEDIA_TYPE_VIDEO) {
480 481 482 483 484 485 486 487 488
                ret = AVERROR(EINVAL);
                goto fail;
            }
            buffer = av_malloc(size);
            if (!buffer) {
                ret = AVERROR(ENOMEM);
                goto fail;
            }
            avio_get_str(pb, INT_MAX, buffer, size);
489 490 491 492
            // The lack of AVOptions support in AVCodecParameters makes this back and forth copying needed
            avcodec_parameters_to_context(dummy_codec, codecpar);
            av_set_options_string(dummy_codec, buffer, "=", ",");
            avcodec_parameters_from_context(codecpar, dummy_codec);
493 494
            if ((ret = ffm_append_recommended_configuration(st, &buffer)) < 0)
                goto fail;
495 496
            break;
        case MKBETAG('S', '2', 'A', 'U'):
497
            if (f_stau++ || !size || codecpar->codec_type != AVMEDIA_TYPE_AUDIO) {
498 499 500 501 502 503 504 505 506
                ret = AVERROR(EINVAL);
                goto fail;
            }
            buffer = av_malloc(size);
            if (!buffer) {
                ret = AVERROR(ENOMEM);
                goto fail;
            }
            avio_get_str(pb, INT_MAX, buffer, size);
507 508 509 510
            // The lack of AVOptions support in AVCodecParameters makes this back and forth copying needed
            avcodec_parameters_to_context(dummy_codec, codecpar);
            av_set_options_string(dummy_codec, buffer, "=", ",");
            avcodec_parameters_from_context(codecpar, dummy_codec);
511 512
            if ((ret = ffm_append_recommended_configuration(st, &buffer)) < 0)
                goto fail;
513
            break;
514 515 516 517 518
        }
        avio_seek(pb, next, SEEK_SET);
    }

    /* get until end of block reached */
519
    while ((avio_tell(pb) % ffm->packet_size) != 0 && !pb->eof_reached)
520 521 522 523 524 525 526 527 528
        avio_r8(pb);

    /* init packet demux */
    ffm->packet_ptr = ffm->packet;
    ffm->packet_end = ffm->packet;
    ffm->frame_offset = 0;
    ffm->dts = 0;
    ffm->read_state = READ_HEADER;
    ffm->first_packet = 1;
529
    avcodec_free_context(&dummy_codec);
530 531
    return 0;
 fail:
532
    avcodec_free_context(&dummy_codec);
533
    return ret;
534
}
535

536
static int ffm_read_header(AVFormatContext *s)
Fabrice Bellard's avatar
Fabrice Bellard committed
537
{
Fabrice Bellard's avatar
Fabrice Bellard committed
538
    FFMContext *ffm = s->priv_data;
Fabrice Bellard's avatar
Fabrice Bellard committed
539
    AVStream *st;
540
    AVIOContext *pb = s->pb;
541
    AVCodecContext *dummy_codec = NULL;
542
    AVCodecParameters *codecpar;
543
    const AVCodecDescriptor *codec_desc;
544
    int i, nb_streams, ret;
545
    uint32_t tag;
Fabrice Bellard's avatar
Fabrice Bellard committed
546 547

    /* header */
548
    tag = avio_rl32(pb);
549 550
    if (tag == MKTAG('F', 'F', 'M', '2'))
        return ffm2_read_header(s);
551 552
    if (tag != MKTAG('F', 'F', 'M', '1')) {
        ret = AVERROR_INVALIDDATA;
Fabrice Bellard's avatar
Fabrice Bellard committed
553
        goto fail;
554
    }
555
    ffm->packet_size = avio_rb32(pb);
556 557
    if (ffm->packet_size != FFM_PACKET_SIZE) {
        ret = AVERROR_INVALIDDATA;
Fabrice Bellard's avatar
Fabrice Bellard committed
558
        goto fail;
559
    }
560
    ffm->write_index = avio_rb64(pb);
Fabrice Bellard's avatar
Fabrice Bellard committed
561
    /* get also filesize */
James Almer's avatar
James Almer committed
562
    if (pb->seekable & AVIO_SEEKABLE_NORMAL) {
563
        ffm->file_size = avio_size(pb);
564
        if (ffm->write_index && 0)
565
            adjust_write_index(s);
Fabrice Bellard's avatar
Fabrice Bellard committed
566
    } else {
567
        ffm->file_size = (UINT64_C(1) << 63) - 1;
Fabrice Bellard's avatar
Fabrice Bellard committed
568
    }
569
    dummy_codec = avcodec_alloc_context3(NULL);
Fabrice Bellard's avatar
Fabrice Bellard committed
570

571 572
    nb_streams = avio_rb32(pb);
    avio_rb32(pb); /* total bitrate */
Fabrice Bellard's avatar
Fabrice Bellard committed
573
    /* read each stream */
574
    for(i=0;i<nb_streams;i++) {
575
        char rc_eq_buf[128];
576
        int flags;
577

578
        st = avformat_new_stream(s, NULL);
579 580
        if (!st) {
            ret = AVERROR(ENOMEM);
Fabrice Bellard's avatar
Fabrice Bellard committed
581
            goto fail;
582
        }
583

584
        avpriv_set_pts_info(st, 64, 1, 1000000);
585

586
        codecpar = st->codecpar;
Fabrice Bellard's avatar
Fabrice Bellard committed
587
        /* generic info */
588 589
        codecpar->codec_id = avio_rb32(pb);
        codec_desc = avcodec_descriptor_get(codecpar->codec_id);
590
        if (!codec_desc) {
591 592
            av_log(s, AV_LOG_ERROR, "Invalid codec id: %d\n", codecpar->codec_id);
            codecpar->codec_id = AV_CODEC_ID_NONE;
593
            ret = AVERROR_INVALIDDATA;
594 595
            goto fail;
        }
596 597
        codecpar->codec_type = avio_r8(pb); /* codec_type */
        if (codecpar->codec_type != codec_desc->type) {
598
            av_log(s, AV_LOG_ERROR, "Codec type mismatch: expected %d, found %d\n",
599 600 601
                   codec_desc->type, codecpar->codec_type);
            codecpar->codec_id = AV_CODEC_ID_NONE;
            codecpar->codec_type = AVMEDIA_TYPE_UNKNOWN;
602
            ret = AVERROR_INVALIDDATA;
603 604
            goto fail;
        }
605 606
        codecpar->bit_rate = avio_rb32(pb);
        if (codecpar->bit_rate < 0) {
607
            av_log(s, AV_LOG_WARNING, "Invalid bit rate %"PRId64"\n", codecpar->bit_rate);
608
            ret = AVERROR_INVALIDDATA;
609 610
            goto fail;
        }
611 612 613 614 615 616
        flags = avio_rb32(pb);
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
            st->codec->flags = flags;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
617 618
        avio_rb32(pb); // flags2
        avio_rb32(pb); // debug
Fabrice Bellard's avatar
Fabrice Bellard committed
619
        /* specific info */
620
        switch(codecpar->codec_type) {
621
        case AVMEDIA_TYPE_VIDEO:
622 623
            avio_rb32(pb); // time_base.num
            avio_rb32(pb); // time_base.den
624 625
            codecpar->width = avio_rb16(pb);
            codecpar->height = avio_rb16(pb);
626
            if ((ret = av_image_check_size(codecpar->width, codecpar->height, 0, s)) < 0)
627
                goto fail;
628
            avio_rb16(pb); // gop_size
629 630 631 632
            codecpar->format = avio_rb32(pb);
            if (!av_pix_fmt_desc_get(codecpar->format)) {
                av_log(s, AV_LOG_ERROR, "Invalid pix fmt id: %d\n", codecpar->format);
                codecpar->format = AV_PIX_FMT_NONE;
633
                ret = AVERROR_INVALIDDATA;
634 635
                goto fail;
            }
636 637 638 639 640 641
            avio_r8(pb);   // qmin
            avio_r8(pb);   // qmax
            avio_r8(pb);   // max_qdiff
            avio_rb16(pb); // qcompress / 10000.0
            avio_rb16(pb); // qblur / 10000.0
            avio_rb32(pb); // bit_rate_tolerance
642
            avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660

            avio_rb32(pb); // rc_max_rate
            avio_rb32(pb); // rc_min_rate
            avio_rb32(pb); // rc_buffer_size
            avio_rb64(pb); // i_quant_factor
            avio_rb64(pb); // b_quant_factor
            avio_rb64(pb); // i_quant_offset
            avio_rb64(pb); // b_quant_offset
            avio_rb32(pb); // dct_algo
            avio_rb32(pb); // strict_std_compliance
            avio_rb32(pb); // max_b_frames
            avio_rb32(pb); // mpeg_quant
            avio_rb32(pb); // intra_dc_precision
            avio_rb32(pb); // me_method
            avio_rb32(pb); // mb_decision
            avio_rb32(pb); // nsse_weight
            avio_rb32(pb); // frame_skip_cmp
            avio_rb64(pb); // rc_buffer_aggressivity
661
            codecpar->codec_tag = avio_rb32(pb);
662 663 664 665 666 667 668 669 670 671 672 673
            avio_r8(pb);   // thread_count
            avio_rb32(pb); // coder_type
            avio_rb32(pb); // me_cmp
            avio_rb32(pb); // me_subpel_quality
            avio_rb32(pb); // me_range
            avio_rb32(pb); // keyint_min
            avio_rb32(pb); // scenechange_threshold
            avio_rb32(pb); // b_frame_strategy
            avio_rb64(pb); // qcompress
            avio_rb64(pb); // qblur
            avio_rb32(pb); // max_qdiff
            avio_rb32(pb); // refs
Fabrice Bellard's avatar
Fabrice Bellard committed
674
            break;
675
        case AVMEDIA_TYPE_AUDIO:
676 677 678 679 680 681
            codecpar->sample_rate = avio_rb32(pb);
            VALIDATE_PARAMETER(sample_rate, "sample rate",        codecpar->sample_rate < 0)
            codecpar->channels = avio_rl16(pb);
            VALIDATE_PARAMETER(channels,    "number of channels", codecpar->channels < 0)
            codecpar->frame_size = avio_rl16(pb);
            VALIDATE_PARAMETER(frame_size,  "frame size",         codecpar->frame_size < 0)
Fabrice Bellard's avatar
Fabrice Bellard committed
682
            break;
683
        default:
684
            ret = AVERROR_INVALIDDATA;
685
            goto fail;
Fabrice Bellard's avatar
Fabrice Bellard committed
686
        }
687
        if (flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
688
            int size = avio_rb32(pb);
689 690
            if (size < 0 || size >= FF_MAX_EXTRADATA_SIZE) {
                av_log(s, AV_LOG_ERROR, "Invalid extradata size %d\n", size);
691
                ret = AVERROR_INVALIDDATA;
692 693
                goto fail;
            }
694
            codecpar->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
695 696 697 698
            if (!codecpar->extradata) {
                ret = AVERROR(ENOMEM);
                goto fail;
            }
699 700
            codecpar->extradata_size = size;
            avio_read(pb, codecpar->extradata, size);
701
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
702 703 704
    }

    /* get until end of block reached */
705
    while ((avio_tell(pb) % ffm->packet_size) != 0 && !pb->eof_reached)
706
        avio_r8(pb);
Fabrice Bellard's avatar
Fabrice Bellard committed
707 708 709 710 711

    /* init packet demux */
    ffm->packet_ptr = ffm->packet;
    ffm->packet_end = ffm->packet;
    ffm->frame_offset = 0;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
712
    ffm->dts = 0;
Fabrice Bellard's avatar
Fabrice Bellard committed
713 714
    ffm->read_state = READ_HEADER;
    ffm->first_packet = 1;
715
    avcodec_free_context(&dummy_codec);
Fabrice Bellard's avatar
Fabrice Bellard committed
716 717
    return 0;
 fail:
718
    avcodec_free_context(&dummy_codec);
719
    return ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
720 721 722 723 724 725 726
}

/* return < 0 if eof */
static int ffm_read_packet(AVFormatContext *s, AVPacket *pkt)
{
    int size;
    FFMContext *ffm = s->priv_data;
727
    int duration, ret;
728

Fabrice Bellard's avatar
Fabrice Bellard committed
729 730
    switch(ffm->read_state) {
    case READ_HEADER:
731 732 733
        if ((ret = ffm_is_avail_data(s, FRAME_HEADER_SIZE+4)) < 0)
            return ret;

734
        ff_dlog(s, "pos=%08"PRIx64" spos=%"PRIx64", write_index=%"PRIx64" size=%"PRIx64"\n",
735
               avio_tell(s->pb), s->pb->pos, ffm->write_index, ffm->file_size);
736
        if (ffm_read_data(s, ffm->header, FRAME_HEADER_SIZE, 1) !=
737
            FRAME_HEADER_SIZE)
738
            return -1;
739 740
        if (ffm->header[1] & FLAG_DTS)
            if (ffm_read_data(s, ffm->header+16, 4, 1) != 4)
741
                return -1;
Fabrice Bellard's avatar
Fabrice Bellard committed
742
        ffm->read_state = READ_DATA;
Lou Logan's avatar
Lou Logan committed
743
        /* fall through */
Fabrice Bellard's avatar
Fabrice Bellard committed
744
    case READ_DATA:
745
        size = AV_RB24(ffm->header + 2);
746 747
        if ((ret = ffm_is_avail_data(s, size)) < 0)
            return ret;
Fabrice Bellard's avatar
Fabrice Bellard committed
748

749
        duration = AV_RB24(ffm->header + 5);
750

751 752 753
        if (av_new_packet(pkt, size) < 0) {
            return AVERROR(ENOMEM);
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
754
        pkt->stream_index = ffm->header[0];
755 756
        if ((unsigned)pkt->stream_index >= s->nb_streams) {
            av_log(s, AV_LOG_ERROR, "invalid stream index %d\n", pkt->stream_index);
757
            av_packet_unref(pkt);
758
            ffm->read_state = READ_HEADER;
759
            return -1;
760
        }
761
        pkt->pos = avio_tell(s->pb);
Fabrice Bellard's avatar
Fabrice Bellard committed
762
        if (ffm->header[1] & FLAG_KEY_FRAME)
763
            pkt->flags |= AV_PKT_FLAG_KEY;
764

Fabrice Bellard's avatar
Fabrice Bellard committed
765 766 767
        ffm->read_state = READ_HEADER;
        if (ffm_read_data(s, pkt->data, size, 0) != size) {
            /* bad case: desynchronized packet. we cancel all the packet loading */
768
            av_packet_unref(pkt);
769
            return -1;
Fabrice Bellard's avatar
Fabrice Bellard committed
770
        }
771 772 773 774 775
        pkt->pts = AV_RB64(ffm->header+8);
        if (ffm->header[1] & FLAG_DTS)
            pkt->dts = pkt->pts - AV_RB32(ffm->header+16);
        else
            pkt->dts = pkt->pts;
776
        pkt->duration = duration;
Fabrice Bellard's avatar
Fabrice Bellard committed
777 778 779 780 781 782
        break;
    }
    return 0;
}

/* seek to a given time in the file. The file read pointer is
Diego Biurrun's avatar
Diego Biurrun committed
783
   positioned at or before pts. XXX: the following code is quite
Fabrice Bellard's avatar
Fabrice Bellard committed
784
   approximative */
785
static int ffm_seek(AVFormatContext *s, int stream_index, int64_t wanted_pts, int flags)
Fabrice Bellard's avatar
Fabrice Bellard committed
786 787
{
    FFMContext *ffm = s->priv_data;
788
    int64_t pos_min, pos_max, pos;
789
    int64_t pts_min, pts_max, pts;
Fabrice Bellard's avatar
Fabrice Bellard committed
790 791
    double pos1;

792
    ff_dlog(s, "wanted_pts=%0.6f\n", wanted_pts / 1000000.0);
Fabrice Bellard's avatar
Fabrice Bellard committed
793 794
    /* find the position using linear interpolation (better than
       dichotomy in typical cases) */
795
    if (ffm->write_index && ffm->write_index < ffm->file_size) {
796 797 798 799 800 801 802 803 804 805 806
        if (get_dts(s, FFM_PACKET_SIZE) < wanted_pts) {
            pos_min = FFM_PACKET_SIZE;
            pos_max = ffm->write_index - FFM_PACKET_SIZE;
        } else {
            pos_min = ffm->write_index;
            pos_max = ffm->file_size - FFM_PACKET_SIZE;
        }
    } else {
        pos_min = FFM_PACKET_SIZE;
        pos_max = ffm->file_size - FFM_PACKET_SIZE;
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
807
    while (pos_min <= pos_max) {
Baptiste Coudurier's avatar
Baptiste Coudurier committed
808 809
        pts_min = get_dts(s, pos_min);
        pts_max = get_dts(s, pos_max);
810
        if (pts_min > wanted_pts || pts_max <= wanted_pts) {
811 812 813
            pos = pts_min > wanted_pts ? pos_min : pos_max;
            goto found;
        }
Fabrice Bellard's avatar
Fabrice Bellard committed
814
        /* linear interpolation */
815
        pos1 = (double)(pos_max - pos_min) * (double)(wanted_pts - pts_min) /
Fabrice Bellard's avatar
Fabrice Bellard committed
816
            (double)(pts_max - pts_min);
817
        pos = (((int64_t)pos1) / FFM_PACKET_SIZE) * FFM_PACKET_SIZE;
Fabrice Bellard's avatar
Fabrice Bellard committed
818 819 820 821
        if (pos <= pos_min)
            pos = pos_min;
        else if (pos >= pos_max)
            pos = pos_max;
Baptiste Coudurier's avatar
Baptiste Coudurier committed
822
        pts = get_dts(s, pos);
Fabrice Bellard's avatar
Fabrice Bellard committed
823 824 825 826 827 828 829 830 831
        /* check if we are lucky */
        if (pts == wanted_pts) {
            goto found;
        } else if (pts > wanted_pts) {
            pos_max = pos - FFM_PACKET_SIZE;
        } else {
            pos_min = pos + FFM_PACKET_SIZE;
        }
    }
832
    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
833

Fabrice Bellard's avatar
Fabrice Bellard committed
834
 found:
835 836
    if (ffm_seek1(s, pos) < 0)
        return -1;
837 838 839 840 841 842 843

    /* reset read state */
    ffm->read_state = READ_HEADER;
    ffm->packet_ptr = ffm->packet;
    ffm->packet_end = ffm->packet;
    ffm->first_packet = 1;

Fabrice Bellard's avatar
Fabrice Bellard committed
844 845 846
    return 0;
}

847 848
static int ffm_probe(AVProbeData *p)
{
849
    if (
850
        p->buf[0] == 'F' && p->buf[1] == 'F' && p->buf[2] == 'M' &&
851
        (p->buf[3] == '1' || p->buf[3] == '2'))
852 853 854 855
        return AVPROBE_SCORE_MAX + 1;
    return 0;
}

856 857
static const AVOption options[] = {
    {"server_attached", NULL, offsetof(FFMContext, server_attached), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_EXPORT },
858 859
    {"ffm_write_index", NULL, offsetof(FFMContext, write_index), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, AV_OPT_FLAG_EXPORT },
    {"ffm_file_size", NULL, offsetof(FFMContext, file_size), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, AV_OPT_FLAG_EXPORT },
860 861 862 863 864 865 866 867 868
    { NULL },
};

static const AVClass ffm_class = {
    .class_name = "ffm demuxer",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};
869
AVInputFormat ff_ffm_demuxer = {
870
    .name           = "ffm",
871
    .long_name      = NULL_IF_CONFIG_SMALL("FFM (FFserver live feed)"),
872 873 874 875 876
    .priv_data_size = sizeof(FFMContext),
    .read_probe     = ffm_probe,
    .read_header    = ffm_read_header,
    .read_packet    = ffm_read_packet,
    .read_seek      = ffm_seek,
877
    .priv_class     = &ffm_class,
Fabrice Bellard's avatar
Fabrice Bellard committed
878
};