1/*
2 * FFM (avserver live feed) demuxer
3 * Copyright (c) 2001 Fabrice Bellard
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "libavutil/intreadwrite.h"
23#include "libavutil/intfloat.h"
24#include "avformat.h"
25#include "internal.h"
26#include "ffm.h"
27#if CONFIG_AVSERVER
28#include <unistd.h>
29
30int64_t ffm_read_write_index(int fd)
31{
32    uint8_t buf[8];
33
34    lseek(fd, 8, SEEK_SET);
35    if (read(fd, buf, 8) != 8)
36        return AVERROR(EIO);
37    return AV_RB64(buf);
38}
39
40int ffm_write_write_index(int fd, int64_t pos)
41{
42    uint8_t buf[8];
43    int i;
44
45    for(i=0;i<8;i++)
46        buf[i] = (pos >> (56 - i * 8)) & 0xff;
47    lseek(fd, 8, SEEK_SET);
48    if (write(fd, buf, 8) != 8)
49        return AVERROR(EIO);
50    return 8;
51}
52
53void ffm_set_write_index(AVFormatContext *s, int64_t pos, int64_t file_size)
54{
55    FFMContext *ffm = s->priv_data;
56    ffm->write_index = pos;
57    ffm->file_size = file_size;
58}
59#endif // CONFIG_AVSERVER
60
61static int ffm_is_avail_data(AVFormatContext *s, int size)
62{
63    FFMContext *ffm = s->priv_data;
64    int64_t pos, avail_size;
65    int len;
66
67    len = ffm->packet_end - ffm->packet_ptr;
68    if (size <= len)
69        return 1;
70    pos = avio_tell(s->pb);
71    if (!ffm->write_index) {
72        if (pos == ffm->file_size)
73            return AVERROR_EOF;
74        avail_size = ffm->file_size - pos;
75    } else {
76    if (pos == ffm->write_index) {
77        /* exactly at the end of stream */
78        return AVERROR(EAGAIN);
79    } else if (pos < ffm->write_index) {
80        avail_size = ffm->write_index - pos;
81    } else {
82        avail_size = (ffm->file_size - pos) + (ffm->write_index - FFM_PACKET_SIZE);
83    }
84    }
85    avail_size = (avail_size / ffm->packet_size) * (ffm->packet_size - FFM_HEADER_SIZE) + len;
86    if (size <= avail_size)
87        return 1;
88    else
89        return AVERROR(EAGAIN);
90}
91
92static int ffm_resync(AVFormatContext *s, int state)
93{
94    av_log(s, AV_LOG_ERROR, "resyncing\n");
95    while (state != PACKET_ID) {
96        if (s->pb->eof_reached) {
97            av_log(s, AV_LOG_ERROR, "cannot find FFM syncword\n");
98            return -1;
99        }
100        state = (state << 8) | avio_r8(s->pb);
101    }
102    return 0;
103}
104
105/* first is true if we read the frame header */
106static int ffm_read_data(AVFormatContext *s,
107                         uint8_t *buf, int size, int header)
108{
109    FFMContext *ffm = s->priv_data;
110    AVIOContext *pb = s->pb;
111    int len, fill_size, size1, frame_offset, id;
112
113    size1 = size;
114    while (size > 0) {
115    redo:
116        len = ffm->packet_end - ffm->packet_ptr;
117        if (len < 0)
118            return -1;
119        if (len > size)
120            len = size;
121        if (len == 0) {
122            if (avio_tell(pb) == ffm->file_size)
123                avio_seek(pb, ffm->packet_size, SEEK_SET);
124    retry_read:
125            id = avio_rb16(pb); /* PACKET_ID */
126            if (id != PACKET_ID)
127                if (ffm_resync(s, id) < 0)
128                    return -1;
129            fill_size = avio_rb16(pb);
130            ffm->dts = avio_rb64(pb);
131            frame_offset = avio_rb16(pb);
132            avio_read(pb, ffm->packet, ffm->packet_size - FFM_HEADER_SIZE);
133            ffm->packet_end = ffm->packet + (ffm->packet_size - FFM_HEADER_SIZE - fill_size);
134            if (ffm->packet_end < ffm->packet || frame_offset < 0)
135                return -1;
136            /* if first packet or resynchronization packet, we must
137               handle it specifically */
138            if (ffm->first_packet || (frame_offset & 0x8000)) {
139                if (!frame_offset) {
140                    /* This packet has no frame headers in it */
141                    if (avio_tell(pb) >= ffm->packet_size * 3) {
142                        avio_seek(pb, -ffm->packet_size * 2, SEEK_CUR);
143                        goto retry_read;
144                    }
145                    /* This is bad, we cannot find a valid frame header */
146                    return 0;
147                }
148                ffm->first_packet = 0;
149                if ((frame_offset & 0x7fff) < FFM_HEADER_SIZE)
150                    return -1;
151                ffm->packet_ptr = ffm->packet + (frame_offset & 0x7fff) - FFM_HEADER_SIZE;
152                if (!header)
153                    break;
154            } else {
155                ffm->packet_ptr = ffm->packet;
156            }
157            goto redo;
158        }
159        memcpy(buf, ffm->packet_ptr, len);
160        buf += len;
161        ffm->packet_ptr += len;
162        size -= len;
163        header = 0;
164    }
165    return size1 - size;
166}
167
168/* ensure that acutal seeking happens between FFM_PACKET_SIZE
169   and file_size - FFM_PACKET_SIZE */
170static void ffm_seek1(AVFormatContext *s, int64_t pos1)
171{
172    FFMContext *ffm = s->priv_data;
173    AVIOContext *pb = s->pb;
174    int64_t pos;
175
176    pos = FFMIN(pos1, ffm->file_size - FFM_PACKET_SIZE);
177    pos = FFMAX(pos, FFM_PACKET_SIZE);
178    av_dlog(s, "seek to %"PRIx64" -> %"PRIx64"\n", pos1, pos);
179    avio_seek(pb, pos, SEEK_SET);
180}
181
182static int64_t get_dts(AVFormatContext *s, int64_t pos)
183{
184    AVIOContext *pb = s->pb;
185    int64_t dts;
186
187    ffm_seek1(s, pos);
188    avio_skip(pb, 4);
189    dts = avio_rb64(pb);
190    av_dlog(s, "dts=%0.6f\n", dts / 1000000.0);
191    return dts;
192}
193
194static void adjust_write_index(AVFormatContext *s)
195{
196    FFMContext *ffm = s->priv_data;
197    AVIOContext *pb = s->pb;
198    int64_t pts;
199    //int64_t orig_write_index = ffm->write_index;
200    int64_t pos_min, pos_max;
201    int64_t pts_start;
202    int64_t ptr = avio_tell(pb);
203
204
205    pos_min = 0;
206    pos_max = ffm->file_size - 2 * FFM_PACKET_SIZE;
207
208    pts_start = get_dts(s, pos_min);
209
210    pts = get_dts(s, pos_max);
211
212    if (pts - 100000 > pts_start)
213        goto end;
214
215    ffm->write_index = FFM_PACKET_SIZE;
216
217    pts_start = get_dts(s, pos_min);
218
219    pts = get_dts(s, pos_max);
220
221    if (pts - 100000 <= pts_start) {
222        while (1) {
223            int64_t newpos;
224            int64_t newpts;
225
226            newpos = ((pos_max + pos_min) / (2 * FFM_PACKET_SIZE)) * FFM_PACKET_SIZE;
227
228            if (newpos == pos_min)
229                break;
230
231            newpts = get_dts(s, newpos);
232
233            if (newpts - 100000 <= pts) {
234                pos_max = newpos;
235                pts = newpts;
236            } else {
237                pos_min = newpos;
238            }
239        }
240        ffm->write_index += pos_max;
241    }
242
243    //printf("Adjusted write index from %"PRId64" to %"PRId64": pts=%0.6f\n", orig_write_index, ffm->write_index, pts / 1000000.);
244    //printf("pts range %0.6f - %0.6f\n", get_dts(s, 0) / 1000000. , get_dts(s, ffm->file_size - 2 * FFM_PACKET_SIZE) / 1000000. );
245
246 end:
247    avio_seek(pb, ptr, SEEK_SET);
248}
249
250
251static int ffm_close(AVFormatContext *s)
252{
253    int i;
254
255    for (i = 0; i < s->nb_streams; i++)
256        av_freep(&s->streams[i]->codec->rc_eq);
257
258    return 0;
259}
260
261
262static int ffm_read_header(AVFormatContext *s, AVFormatParameters *ap)
263{
264    FFMContext *ffm = s->priv_data;
265    AVStream *st;
266    AVIOContext *pb = s->pb;
267    AVCodecContext *codec;
268    int i, nb_streams;
269    uint32_t tag;
270
271    /* header */
272    tag = avio_rl32(pb);
273    if (tag != MKTAG('F', 'F', 'M', '1'))
274        goto fail;
275    ffm->packet_size = avio_rb32(pb);
276    if (ffm->packet_size != FFM_PACKET_SIZE)
277        goto fail;
278    ffm->write_index = avio_rb64(pb);
279    /* get also filesize */
280    if (pb->seekable) {
281        ffm->file_size = avio_size(pb);
282        if (ffm->write_index)
283            adjust_write_index(s);
284    } else {
285        ffm->file_size = (UINT64_C(1) << 63) - 1;
286    }
287
288    nb_streams = avio_rb32(pb);
289    avio_rb32(pb); /* total bitrate */
290    /* read each stream */
291    for(i=0;i<nb_streams;i++) {
292        char rc_eq_buf[128];
293
294        st = avformat_new_stream(s, NULL);
295        if (!st)
296            goto fail;
297
298        avpriv_set_pts_info(st, 64, 1, 1000000);
299
300        codec = st->codec;
301        /* generic info */
302        codec->codec_id = avio_rb32(pb);
303        codec->codec_type = avio_r8(pb); /* codec_type */
304        codec->bit_rate = avio_rb32(pb);
305        codec->flags = avio_rb32(pb);
306        codec->flags2 = avio_rb32(pb);
307        codec->debug = avio_rb32(pb);
308        /* specific info */
309        switch(codec->codec_type) {
310        case AVMEDIA_TYPE_VIDEO:
311            codec->time_base.num = avio_rb32(pb);
312            codec->time_base.den = avio_rb32(pb);
313            codec->width = avio_rb16(pb);
314            codec->height = avio_rb16(pb);
315            codec->gop_size = avio_rb16(pb);
316            codec->pix_fmt = avio_rb32(pb);
317            codec->qmin = avio_r8(pb);
318            codec->qmax = avio_r8(pb);
319            codec->max_qdiff = avio_r8(pb);
320            codec->qcompress = avio_rb16(pb) / 10000.0;
321            codec->qblur = avio_rb16(pb) / 10000.0;
322            codec->bit_rate_tolerance = avio_rb32(pb);
323            avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));
324            codec->rc_eq = av_strdup(rc_eq_buf);
325            codec->rc_max_rate = avio_rb32(pb);
326            codec->rc_min_rate = avio_rb32(pb);
327            codec->rc_buffer_size = avio_rb32(pb);
328            codec->i_quant_factor = av_int2double(avio_rb64(pb));
329            codec->b_quant_factor = av_int2double(avio_rb64(pb));
330            codec->i_quant_offset = av_int2double(avio_rb64(pb));
331            codec->b_quant_offset = av_int2double(avio_rb64(pb));
332            codec->dct_algo = avio_rb32(pb);
333            codec->strict_std_compliance = avio_rb32(pb);
334            codec->max_b_frames = avio_rb32(pb);
335            codec->luma_elim_threshold = avio_rb32(pb);
336            codec->chroma_elim_threshold = avio_rb32(pb);
337            codec->mpeg_quant = avio_rb32(pb);
338            codec->intra_dc_precision = avio_rb32(pb);
339            codec->me_method = avio_rb32(pb);
340            codec->mb_decision = avio_rb32(pb);
341            codec->nsse_weight = avio_rb32(pb);
342            codec->frame_skip_cmp = avio_rb32(pb);
343            codec->rc_buffer_aggressivity = av_int2double(avio_rb64(pb));
344            codec->codec_tag = avio_rb32(pb);
345            codec->thread_count = avio_r8(pb);
346            codec->coder_type = avio_rb32(pb);
347            codec->me_cmp = avio_rb32(pb);
348            codec->me_subpel_quality = avio_rb32(pb);
349            codec->me_range = avio_rb32(pb);
350            codec->keyint_min = avio_rb32(pb);
351            codec->scenechange_threshold = avio_rb32(pb);
352            codec->b_frame_strategy = avio_rb32(pb);
353            codec->qcompress = av_int2double(avio_rb64(pb));
354            codec->qblur = av_int2double(avio_rb64(pb));
355            codec->max_qdiff = avio_rb32(pb);
356            codec->refs = avio_rb32(pb);
357            break;
358        case AVMEDIA_TYPE_AUDIO:
359            codec->sample_rate = avio_rb32(pb);
360            codec->channels = avio_rl16(pb);
361            codec->frame_size = avio_rl16(pb);
362            codec->sample_fmt = (int16_t) avio_rl16(pb);
363            break;
364        default:
365            goto fail;
366        }
367        if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {
368            codec->extradata_size = avio_rb32(pb);
369            codec->extradata = av_malloc(codec->extradata_size);
370            if (!codec->extradata)
371                return AVERROR(ENOMEM);
372            avio_read(pb, codec->extradata, codec->extradata_size);
373        }
374    }
375
376    /* get until end of block reached */
377    while ((avio_tell(pb) % ffm->packet_size) != 0)
378        avio_r8(pb);
379
380    /* init packet demux */
381    ffm->packet_ptr = ffm->packet;
382    ffm->packet_end = ffm->packet;
383    ffm->frame_offset = 0;
384    ffm->dts = 0;
385    ffm->read_state = READ_HEADER;
386    ffm->first_packet = 1;
387    return 0;
388 fail:
389    ffm_close(s);
390    return -1;
391}
392
393/* return < 0 if eof */
394static int ffm_read_packet(AVFormatContext *s, AVPacket *pkt)
395{
396    int size;
397    FFMContext *ffm = s->priv_data;
398    int duration, ret;
399
400    switch(ffm->read_state) {
401    case READ_HEADER:
402        if ((ret = ffm_is_avail_data(s, FRAME_HEADER_SIZE+4)) < 0)
403            return ret;
404
405        av_dlog(s, "pos=%08"PRIx64" spos=%"PRIx64", write_index=%"PRIx64" size=%"PRIx64"\n",
406               avio_tell(s->pb), s->pb->pos, ffm->write_index, ffm->file_size);
407        if (ffm_read_data(s, ffm->header, FRAME_HEADER_SIZE, 1) !=
408            FRAME_HEADER_SIZE)
409            return -1;
410        if (ffm->header[1] & FLAG_DTS)
411            if (ffm_read_data(s, ffm->header+16, 4, 1) != 4)
412                return -1;
413        ffm->read_state = READ_DATA;
414        /* fall thru */
415    case READ_DATA:
416        size = AV_RB24(ffm->header + 2);
417        if ((ret = ffm_is_avail_data(s, size)) < 0)
418            return ret;
419
420        duration = AV_RB24(ffm->header + 5);
421
422        av_new_packet(pkt, size);
423        pkt->stream_index = ffm->header[0];
424        if ((unsigned)pkt->stream_index >= s->nb_streams) {
425            av_log(s, AV_LOG_ERROR, "invalid stream index %d\n", pkt->stream_index);
426            av_free_packet(pkt);
427            ffm->read_state = READ_HEADER;
428            return -1;
429        }
430        pkt->pos = avio_tell(s->pb);
431        if (ffm->header[1] & FLAG_KEY_FRAME)
432            pkt->flags |= AV_PKT_FLAG_KEY;
433
434        ffm->read_state = READ_HEADER;
435        if (ffm_read_data(s, pkt->data, size, 0) != size) {
436            /* bad case: desynchronized packet. we cancel all the packet loading */
437            av_free_packet(pkt);
438            return -1;
439        }
440        pkt->pts = AV_RB64(ffm->header+8);
441        if (ffm->header[1] & FLAG_DTS)
442            pkt->dts = pkt->pts - AV_RB32(ffm->header+16);
443        else
444            pkt->dts = pkt->pts;
445        pkt->duration = duration;
446        break;
447    }
448    return 0;
449}
450
451/* seek to a given time in the file. The file read pointer is
452   positioned at or before pts. XXX: the following code is quite
453   approximative */
454static int ffm_seek(AVFormatContext *s, int stream_index, int64_t wanted_pts, int flags)
455{
456    FFMContext *ffm = s->priv_data;
457    int64_t pos_min, pos_max, pos;
458    int64_t pts_min, pts_max, pts;
459    double pos1;
460
461    av_dlog(s, "wanted_pts=%0.6f\n", wanted_pts / 1000000.0);
462    /* find the position using linear interpolation (better than
463       dichotomy in typical cases) */
464    pos_min = FFM_PACKET_SIZE;
465    pos_max = ffm->file_size - FFM_PACKET_SIZE;
466    while (pos_min <= pos_max) {
467        pts_min = get_dts(s, pos_min);
468        pts_max = get_dts(s, pos_max);
469        /* linear interpolation */
470        pos1 = (double)(pos_max - pos_min) * (double)(wanted_pts - pts_min) /
471            (double)(pts_max - pts_min);
472        pos = (((int64_t)pos1) / FFM_PACKET_SIZE) * FFM_PACKET_SIZE;
473        if (pos <= pos_min)
474            pos = pos_min;
475        else if (pos >= pos_max)
476            pos = pos_max;
477        pts = get_dts(s, pos);
478        /* check if we are lucky */
479        if (pts == wanted_pts) {
480            goto found;
481        } else if (pts > wanted_pts) {
482            pos_max = pos - FFM_PACKET_SIZE;
483        } else {
484            pos_min = pos + FFM_PACKET_SIZE;
485        }
486    }
487    pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
488
489 found:
490    ffm_seek1(s, pos);
491
492    /* reset read state */
493    ffm->read_state = READ_HEADER;
494    ffm->packet_ptr = ffm->packet;
495    ffm->packet_end = ffm->packet;
496    ffm->first_packet = 1;
497
498    return 0;
499}
500
501static int ffm_probe(AVProbeData *p)
502{
503    if (
504        p->buf[0] == 'F' && p->buf[1] == 'F' && p->buf[2] == 'M' &&
505        p->buf[3] == '1')
506        return AVPROBE_SCORE_MAX + 1;
507    return 0;
508}
509
510AVInputFormat ff_ffm_demuxer = {
511    .name           = "ffm",
512    .long_name      = NULL_IF_CONFIG_SMALL("FFM (AVserver live feed) format"),
513    .priv_data_size = sizeof(FFMContext),
514    .read_probe     = ffm_probe,
515    .read_header    = ffm_read_header,
516    .read_packet    = ffm_read_packet,
517    .read_close     = ffm_close,
518    .read_seek      = ffm_seek,
519};
520