libavformat/ffmdec.c
85a6b01d
 /*
  * FFM (ffserver live feed) demuxer
406792e7
  * Copyright (c) 2001 Fabrice Bellard
85a6b01d
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
6a5d31ac
 #include "libavutil/intreadwrite.h"
3383a53e
 #include "libavutil/intfloat.h"
85a6b01d
 #include "avformat.h"
c3f9ebf7
 #include "internal.h"
85a6b01d
 #include "ffm.h"
e37f161e
 #include "avio_internal.h"
b250f9c6
 #if CONFIG_FFSERVER
85a6b01d
 #include <unistd.h>
 
bc5c918e
 int64_t ffm_read_write_index(int fd)
278f987a
 {
     uint8_t buf[8];
 
     lseek(fd, 8, SEEK_SET);
2dc91884
     if (read(fd, buf, 8) != 8)
         return AVERROR(EIO);
278f987a
     return AV_RB64(buf);
 }
 
6fcce4f9
 int ffm_write_write_index(int fd, int64_t pos)
278f987a
 {
     uint8_t buf[8];
     int i;
 
     for(i=0;i<8;i++)
         buf[i] = (pos >> (56 - i * 8)) & 0xff;
     lseek(fd, 8, SEEK_SET);
6fcce4f9
     if (write(fd, buf, 8) != 8)
         return AVERROR(EIO);
     return 8;
278f987a
 }
 
bc5c918e
 void ffm_set_write_index(AVFormatContext *s, int64_t pos, int64_t file_size)
278f987a
 {
     FFMContext *ffm = s->priv_data;
     ffm->write_index = pos;
     ffm->file_size = file_size;
 }
 #endif // CONFIG_FFSERVER
 
85a6b01d
 static int ffm_is_avail_data(AVFormatContext *s, int size)
 {
     FFMContext *ffm = s->priv_data;
bc5c918e
     int64_t pos, avail_size;
85a6b01d
     int len;
 
     len = ffm->packet_end - ffm->packet_ptr;
     if (size <= len)
         return 1;
384c9c2f
     pos = avio_tell(s->pb);
b9edbe99
     if (!ffm->write_index) {
21c6438f
         if (pos == ffm->file_size)
b9edbe99
             return AVERROR_EOF;
         avail_size = ffm->file_size - pos;
     } else {
85a6b01d
     if (pos == ffm->write_index) {
         /* exactly at the end of stream */
b9edbe99
         return AVERROR(EAGAIN);
85a6b01d
     } 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);
     }
b9edbe99
     }
85a6b01d
     avail_size = (avail_size / ffm->packet_size) * (ffm->packet_size - FFM_HEADER_SIZE) + len;
     if (size <= avail_size)
         return 1;
     else
b9edbe99
         return AVERROR(EAGAIN);
85a6b01d
 }
 
7c45723a
 static int ffm_resync(AVFormatContext *s, int state)
 {
     av_log(s, AV_LOG_ERROR, "resyncing\n");
     while (state != PACKET_ID) {
         if (url_feof(s->pb)) {
             av_log(s, AV_LOG_ERROR, "cannot find FFM syncword\n");
             return -1;
         }
e63a3628
         state = (state << 8) | avio_r8(s->pb);
7c45723a
     }
     return 0;
 }
 
85a6b01d
 /* first is true if we read the frame header */
 static int ffm_read_data(AVFormatContext *s,
b30bb535
                          uint8_t *buf, int size, int header)
85a6b01d
 {
     FFMContext *ffm = s->priv_data;
471fe57e
     AVIOContext *pb = s->pb;
7c45723a
     int len, fill_size, size1, frame_offset, id;
85a6b01d
 
     size1 = size;
     while (size > 0) {
     redo:
         len = ffm->packet_end - ffm->packet_ptr;
e5ece183
         if (len < 0)
             return -1;
85a6b01d
         if (len > size)
             len = size;
         if (len == 0) {
384c9c2f
             if (avio_tell(pb) == ffm->file_size)
f59d8ff8
                 avio_seek(pb, ffm->packet_size, SEEK_SET);
85a6b01d
     retry_read:
8ba987bf
             if (pb->buffer_size != ffm->packet_size) {
                 int64_t tell = avio_tell(pb);
e37f161e
                 ffio_set_buf_size(pb, ffm->packet_size);
8ba987bf
                 avio_seek(pb, tell, SEEK_SET);
             }
e63a3628
             id = avio_rb16(pb); /* PACKET_ID */
7c45723a
             if (id != PACKET_ID)
                 if (ffm_resync(s, id) < 0)
                     return -1;
e63a3628
             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);
85a6b01d
             ffm->packet_end = ffm->packet + (ffm->packet_size - FFM_HEADER_SIZE - fill_size);
eea2f032
             if (ffm->packet_end < ffm->packet || frame_offset < 0)
85a6b01d
                 return -1;
             /* if first packet or resynchronization packet, we must
                handle it specifically */
             if (ffm->first_packet || (frame_offset & 0x8000)) {
                 if (!frame_offset) {
                     /* This packet has no frame headers in it */
384c9c2f
                     if (avio_tell(pb) >= ffm->packet_size * 3) {
f59d8ff8
                         avio_seek(pb, -ffm->packet_size * 2, SEEK_CUR);
85a6b01d
                         goto retry_read;
                     }
                     /* This is bad, we cannot find a valid frame header */
                     return 0;
                 }
                 ffm->first_packet = 0;
a077f3bc
                 if ((frame_offset & 0x7fff) < FFM_HEADER_SIZE)
85a6b01d
                     return -1;
                 ffm->packet_ptr = ffm->packet + (frame_offset & 0x7fff) - FFM_HEADER_SIZE;
b30bb535
                 if (!header)
85a6b01d
                     break;
             } else {
                 ffm->packet_ptr = ffm->packet;
             }
             goto redo;
         }
         memcpy(buf, ffm->packet_ptr, len);
         buf += len;
         ffm->packet_ptr += len;
         size -= len;
b30bb535
         header = 0;
85a6b01d
     }
     return size1 - size;
 }
 
92a0f338
 /* ensure that acutal seeking happens between FFM_PACKET_SIZE
    and file_size - FFM_PACKET_SIZE */
928cfc7e
 static int64_t ffm_seek1(AVFormatContext *s, int64_t pos1)
a1e01307
 {
     FFMContext *ffm = s->priv_data;
471fe57e
     AVIOContext *pb = s->pb;
bc5c918e
     int64_t pos;
a1e01307
 
92a0f338
     pos = FFMIN(pos1, ffm->file_size - FFM_PACKET_SIZE);
     pos = FFMAX(pos, FFM_PACKET_SIZE);
919d7a34
     av_dlog(s, "seek to %"PRIx64" -> %"PRIx64"\n", pos1, pos);
928cfc7e
     return avio_seek(pb, pos, SEEK_SET);
a1e01307
 }
 
bc5c918e
 static int64_t get_dts(AVFormatContext *s, int64_t pos)
979b1a06
 {
471fe57e
     AVIOContext *pb = s->pb;
fabb990e
     int64_t dts;
979b1a06
 
     ffm_seek1(s, pos);
45a8a02a
     avio_skip(pb, 4);
e63a3628
     dts = avio_rb64(pb);
919d7a34
     av_dlog(s, "dts=%0.6f\n", dts / 1000000.0);
fabb990e
     return dts;
979b1a06
 }
85a6b01d
 
 static void adjust_write_index(AVFormatContext *s)
 {
     FFMContext *ffm = s->priv_data;
471fe57e
     AVIOContext *pb = s->pb;
85a6b01d
     int64_t pts;
bc5c918e
     //int64_t orig_write_index = ffm->write_index;
     int64_t pos_min, pos_max;
85a6b01d
     int64_t pts_start;
384c9c2f
     int64_t ptr = avio_tell(pb);
85a6b01d
 
 
     pos_min = 0;
     pos_max = ffm->file_size - 2 * FFM_PACKET_SIZE;
 
fabb990e
     pts_start = get_dts(s, pos_min);
85a6b01d
 
fabb990e
     pts = get_dts(s, pos_max);
85a6b01d
 
     if (pts - 100000 > pts_start)
         goto end;
 
     ffm->write_index = FFM_PACKET_SIZE;
 
fabb990e
     pts_start = get_dts(s, pos_min);
85a6b01d
 
fabb990e
     pts = get_dts(s, pos_max);
85a6b01d
 
     if (pts - 100000 <= pts_start) {
         while (1) {
bc5c918e
             int64_t newpos;
85a6b01d
             int64_t newpts;
 
             newpos = ((pos_max + pos_min) / (2 * FFM_PACKET_SIZE)) * FFM_PACKET_SIZE;
 
             if (newpos == pos_min)
                 break;
 
fabb990e
             newpts = get_dts(s, newpos);
85a6b01d
 
             if (newpts - 100000 <= pts) {
                 pos_max = newpos;
                 pts = newpts;
             } else {
                 pos_min = newpos;
             }
         }
         ffm->write_index += pos_max;
     }
 
     //printf("Adjusted write index from %"PRId64" to %"PRId64": pts=%0.6f\n", orig_write_index, ffm->write_index, pts / 1000000.);
fabb990e
     //printf("pts range %0.6f - %0.6f\n", get_dts(s, 0) / 1000000. , get_dts(s, ffm->file_size - 2 * FFM_PACKET_SIZE) / 1000000. );
85a6b01d
 
  end:
f59d8ff8
     avio_seek(pb, ptr, SEEK_SET);
85a6b01d
 }
 
 
e36a3906
 static int ffm_close(AVFormatContext *s)
 {
     int i;
 
     for (i = 0; i < s->nb_streams; i++)
         av_freep(&s->streams[i]->codec->rc_eq);
 
     return 0;
 }
 
527b46ba
 
6e9651d1
 static int ffm_read_header(AVFormatContext *s)
85a6b01d
 {
     FFMContext *ffm = s->priv_data;
     AVStream *st;
471fe57e
     AVIOContext *pb = s->pb;
85a6b01d
     AVCodecContext *codec;
     int i, nb_streams;
     uint32_t tag;
 
     /* header */
e63a3628
     tag = avio_rl32(pb);
85a6b01d
     if (tag != MKTAG('F', 'F', 'M', '1'))
         goto fail;
e63a3628
     ffm->packet_size = avio_rb32(pb);
85a6b01d
     if (ffm->packet_size != FFM_PACKET_SIZE)
         goto fail;
e63a3628
     ffm->write_index = avio_rb64(pb);
85a6b01d
     /* get also filesize */
8978feda
     if (pb->seekable) {
db44ea96
         ffm->file_size = avio_size(pb);
16b9156b
         if (ffm->write_index && 0)
b9edbe99
             adjust_write_index(s);
85a6b01d
     } else {
         ffm->file_size = (UINT64_C(1) << 63) - 1;
     }
 
e63a3628
     nb_streams = avio_rb32(pb);
     avio_rb32(pb); /* total bitrate */
85a6b01d
     /* read each stream */
     for(i=0;i<nb_streams;i++) {
         char rc_eq_buf[128];
 
3b3bbdd3
         st = avformat_new_stream(s, NULL);
85a6b01d
         if (!st)
             goto fail;
 
c3f9ebf7
         avpriv_set_pts_info(st, 64, 1, 1000000);
85a6b01d
 
         codec = st->codec;
         /* generic info */
e63a3628
         codec->codec_id = avio_rb32(pb);
         codec->codec_type = avio_r8(pb); /* codec_type */
         codec->bit_rate = avio_rb32(pb);
         codec->flags = avio_rb32(pb);
         codec->flags2 = avio_rb32(pb);
         codec->debug = avio_rb32(pb);
85a6b01d
         /* specific info */
         switch(codec->codec_type) {
72415b2a
         case AVMEDIA_TYPE_VIDEO:
e63a3628
             codec->time_base.num = avio_rb32(pb);
             codec->time_base.den = avio_rb32(pb);
             codec->width = avio_rb16(pb);
             codec->height = avio_rb16(pb);
             codec->gop_size = avio_rb16(pb);
             codec->pix_fmt = avio_rb32(pb);
             codec->qmin = avio_r8(pb);
             codec->qmax = avio_r8(pb);
             codec->max_qdiff = avio_r8(pb);
             codec->qcompress = avio_rb16(pb) / 10000.0;
             codec->qblur = avio_rb16(pb) / 10000.0;
             codec->bit_rate_tolerance = avio_rb32(pb);
68134502
             avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));
             codec->rc_eq = av_strdup(rc_eq_buf);
e63a3628
             codec->rc_max_rate = avio_rb32(pb);
             codec->rc_min_rate = avio_rb32(pb);
             codec->rc_buffer_size = avio_rb32(pb);
3383a53e
             codec->i_quant_factor = av_int2double(avio_rb64(pb));
             codec->b_quant_factor = av_int2double(avio_rb64(pb));
             codec->i_quant_offset = av_int2double(avio_rb64(pb));
             codec->b_quant_offset = av_int2double(avio_rb64(pb));
e63a3628
             codec->dct_algo = avio_rb32(pb);
             codec->strict_std_compliance = avio_rb32(pb);
             codec->max_b_frames = avio_rb32(pb);
             codec->mpeg_quant = avio_rb32(pb);
             codec->intra_dc_precision = avio_rb32(pb);
             codec->me_method = avio_rb32(pb);
             codec->mb_decision = avio_rb32(pb);
             codec->nsse_weight = avio_rb32(pb);
             codec->frame_skip_cmp = avio_rb32(pb);
3383a53e
             codec->rc_buffer_aggressivity = av_int2double(avio_rb64(pb));
e63a3628
             codec->codec_tag = avio_rb32(pb);
             codec->thread_count = avio_r8(pb);
             codec->coder_type = avio_rb32(pb);
             codec->me_cmp = avio_rb32(pb);
             codec->me_subpel_quality = avio_rb32(pb);
             codec->me_range = avio_rb32(pb);
             codec->keyint_min = avio_rb32(pb);
             codec->scenechange_threshold = avio_rb32(pb);
             codec->b_frame_strategy = avio_rb32(pb);
3383a53e
             codec->qcompress = av_int2double(avio_rb64(pb));
             codec->qblur = av_int2double(avio_rb64(pb));
e63a3628
             codec->max_qdiff = avio_rb32(pb);
             codec->refs = avio_rb32(pb);
85a6b01d
             break;
72415b2a
         case AVMEDIA_TYPE_AUDIO:
e63a3628
             codec->sample_rate = avio_rb32(pb);
             codec->channels = avio_rl16(pb);
             codec->frame_size = avio_rl16(pb);
             codec->sample_fmt = (int16_t) avio_rl16(pb);
85a6b01d
             break;
         default:
             goto fail;
         }
7080cbe2
         if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {
e63a3628
             codec->extradata_size = avio_rb32(pb);
7080cbe2
             codec->extradata = av_malloc(codec->extradata_size);
             if (!codec->extradata)
                 return AVERROR(ENOMEM);
e63a3628
             avio_read(pb, codec->extradata, codec->extradata_size);
7080cbe2
         }
85a6b01d
     }
 
     /* get until end of block reached */
384c9c2f
     while ((avio_tell(pb) % ffm->packet_size) != 0)
e63a3628
         avio_r8(pb);
85a6b01d
 
     /* init packet demux */
     ffm->packet_ptr = ffm->packet;
     ffm->packet_end = ffm->packet;
     ffm->frame_offset = 0;
fabb990e
     ffm->dts = 0;
85a6b01d
     ffm->read_state = READ_HEADER;
     ffm->first_packet = 1;
     return 0;
  fail:
527b46ba
     ffm_close(s);
85a6b01d
     return -1;
 }
 
 /* return < 0 if eof */
 static int ffm_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
     int size;
     FFMContext *ffm = s->priv_data;
b9edbe99
     int duration, ret;
eee99eb3
 
85a6b01d
     switch(ffm->read_state) {
     case READ_HEADER:
b9edbe99
         if ((ret = ffm_is_avail_data(s, FRAME_HEADER_SIZE+4)) < 0)
             return ret;
 
9ef5a9de
         av_dlog(s, "pos=%08"PRIx64" spos=%"PRIx64", write_index=%"PRIx64" size=%"PRIx64"\n",
384c9c2f
                avio_tell(s->pb), s->pb->pos, ffm->write_index, ffm->file_size);
85a6b01d
         if (ffm_read_data(s, ffm->header, FRAME_HEADER_SIZE, 1) !=
             FRAME_HEADER_SIZE)
b9edbe99
             return -1;
3c6a9f66
         if (ffm->header[1] & FLAG_DTS)
             if (ffm_read_data(s, ffm->header+16, 4, 1) != 4)
b9edbe99
                 return -1;
85a6b01d
         ffm->read_state = READ_DATA;
         /* fall thru */
     case READ_DATA:
         size = AV_RB24(ffm->header + 2);
b9edbe99
         if ((ret = ffm_is_avail_data(s, size)) < 0)
             return ret;
85a6b01d
 
         duration = AV_RB24(ffm->header + 5);
 
         av_new_packet(pkt, size);
         pkt->stream_index = ffm->header[0];
         if ((unsigned)pkt->stream_index >= s->nb_streams) {
             av_log(s, AV_LOG_ERROR, "invalid stream index %d\n", pkt->stream_index);
             av_free_packet(pkt);
             ffm->read_state = READ_HEADER;
b9edbe99
             return -1;
85a6b01d
         }
384c9c2f
         pkt->pos = avio_tell(s->pb);
85a6b01d
         if (ffm->header[1] & FLAG_KEY_FRAME)
cc947f04
             pkt->flags |= AV_PKT_FLAG_KEY;
85a6b01d
 
         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 */
             av_free_packet(pkt);
b9edbe99
             return -1;
85a6b01d
         }
3c6a9f66
         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;
85a6b01d
         pkt->duration = duration;
         break;
     }
     return 0;
 }
 
 /* seek to a given time in the file. The file read pointer is
    positioned at or before pts. XXX: the following code is quite
    approximative */
 static int ffm_seek(AVFormatContext *s, int stream_index, int64_t wanted_pts, int flags)
 {
     FFMContext *ffm = s->priv_data;
bc5c918e
     int64_t pos_min, pos_max, pos;
85a6b01d
     int64_t pts_min, pts_max, pts;
     double pos1;
 
919d7a34
     av_dlog(s, "wanted_pts=%0.6f\n", wanted_pts / 1000000.0);
85a6b01d
     /* find the position using linear interpolation (better than
        dichotomy in typical cases) */
0b99e858
     if (ffm->write_index && ffm->write_index < ffm->file_size) {
59810f83
         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;
     }
85a6b01d
     while (pos_min <= pos_max) {
fabb990e
         pts_min = get_dts(s, pos_min);
         pts_max = get_dts(s, pos_max);
59810f83
         if (pts_min > wanted_pts || pts_max < wanted_pts) {
             pos = pts_min > wanted_pts ? pos_min : pos_max;
             goto found;
         }
85a6b01d
         /* linear interpolation */
         pos1 = (double)(pos_max - pos_min) * (double)(wanted_pts - pts_min) /
             (double)(pts_max - pts_min);
         pos = (((int64_t)pos1) / FFM_PACKET_SIZE) * FFM_PACKET_SIZE;
         if (pos <= pos_min)
             pos = pos_min;
         else if (pos >= pos_max)
             pos = pos_max;
fabb990e
         pts = get_dts(s, pos);
85a6b01d
         /* 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;
         }
     }
     pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
92a0f338
 
85a6b01d
  found:
928cfc7e
     if (ffm_seek1(s, pos) < 0)
         return -1;
c07d64c8
 
     /* reset read state */
     ffm->read_state = READ_HEADER;
     ffm->packet_ptr = ffm->packet;
     ffm->packet_end = ffm->packet;
     ffm->first_packet = 1;
 
85a6b01d
     return 0;
 }
 
 static int ffm_probe(AVProbeData *p)
 {
     if (
         p->buf[0] == 'F' && p->buf[1] == 'F' && p->buf[2] == 'M' &&
         p->buf[3] == '1')
         return AVPROBE_SCORE_MAX + 1;
     return 0;
 }
 
66355be3
 AVInputFormat ff_ffm_demuxer = {
dfc2c4d9
     .name           = "ffm",
b5da7d4c
     .long_name      = NULL_IF_CONFIG_SMALL("FFM (FFserver live feed)"),
dfc2c4d9
     .priv_data_size = sizeof(FFMContext),
     .read_probe     = ffm_probe,
     .read_header    = ffm_read_header,
     .read_packet    = ffm_read_packet,
     .read_close     = ffm_close,
     .read_seek      = ffm_seek,
85a6b01d
 };