]> git.sesse.net Git - ffmpeg/blob - libavformat/ffmdec.c
7f31d14445424a2dd842b5d230a25c11a165ad6d
[ffmpeg] / libavformat / ffmdec.c
1 /*
2  * FFM (ffserver live feed) demuxer
3  * Copyright (c) 2001 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <stdint.h>
23
24 #include "libavutil/internal.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/intfloat.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "avformat.h"
31 #include "internal.h"
32 #include "ffm.h"
33 #include "avio_internal.h"
34
35 static int ffm_is_avail_data(AVFormatContext *s, int size)
36 {
37     FFMContext *ffm = s->priv_data;
38     int64_t pos, avail_size;
39     int len;
40
41     len = ffm->packet_end - ffm->packet_ptr;
42     if (size <= len)
43         return 1;
44     pos = avio_tell(s->pb);
45     if (!ffm->write_index) {
46         if (pos == ffm->file_size)
47             return AVERROR_EOF;
48         avail_size = ffm->file_size - pos;
49     } else {
50     if (pos == ffm->write_index) {
51         /* exactly at the end of stream */
52         if (ffm->server_attached)
53             return AVERROR(EAGAIN);
54         else
55             return AVERROR_INVALIDDATA;
56     } else if (pos < ffm->write_index) {
57         avail_size = ffm->write_index - pos;
58     } else {
59         avail_size = (ffm->file_size - pos) + (ffm->write_index - FFM_PACKET_SIZE);
60     }
61     }
62     avail_size = (avail_size / ffm->packet_size) * (ffm->packet_size - FFM_HEADER_SIZE) + len;
63     if (size <= avail_size)
64         return 1;
65     else if (ffm->server_attached)
66         return AVERROR(EAGAIN);
67     else
68         return AVERROR_INVALIDDATA;
69 }
70
71 static int ffm_resync(AVFormatContext *s, uint32_t state)
72 {
73     av_log(s, AV_LOG_ERROR, "resyncing\n");
74     while (state != PACKET_ID) {
75         if (avio_feof(s->pb)) {
76             av_log(s, AV_LOG_ERROR, "cannot find FFM syncword\n");
77             return -1;
78         }
79         state = (state << 8) | avio_r8(s->pb);
80     }
81     return 0;
82 }
83
84 /* first is true if we read the frame header */
85 static int ffm_read_data(AVFormatContext *s,
86                          uint8_t *buf, int size, int header)
87 {
88     FFMContext *ffm = s->priv_data;
89     AVIOContext *pb = s->pb;
90     int len, fill_size, size1, frame_offset;
91     uint32_t id;
92     int64_t last_pos = -1;
93
94     size1 = size;
95     while (size > 0) {
96     redo:
97         len = ffm->packet_end - ffm->packet_ptr;
98         if (len < 0)
99             return -1;
100         if (len > size)
101             len = size;
102         if (len == 0) {
103             if (avio_tell(pb) == ffm->file_size)
104                 if (ffm->server_attached)
105                     avio_seek(pb, ffm->packet_size, SEEK_SET);
106                 else
107                     return AVERROR_EOF;
108     retry_read:
109             if (pb->buffer_size != ffm->packet_size) {
110                 int64_t tell = avio_tell(pb);
111                 int ret = ffio_set_buf_size(pb, ffm->packet_size);
112                 if (ret < 0)
113                     return ret;
114                 avio_seek(pb, tell, SEEK_SET);
115             }
116             id = avio_rb16(pb); /* PACKET_ID */
117             if (id != PACKET_ID) {
118                 if (ffm_resync(s, id) < 0)
119                     return -1;
120                 last_pos = avio_tell(pb);
121             }
122             fill_size = avio_rb16(pb);
123             ffm->dts = avio_rb64(pb);
124             frame_offset = avio_rb16(pb);
125             avio_read(pb, ffm->packet, ffm->packet_size - FFM_HEADER_SIZE);
126             ffm->packet_end = ffm->packet + (ffm->packet_size - FFM_HEADER_SIZE - fill_size);
127             if (ffm->packet_end < ffm->packet || frame_offset < 0)
128                 return -1;
129             /* if first packet or resynchronization packet, we must
130                handle it specifically */
131             if (ffm->first_packet || (frame_offset & 0x8000)) {
132                 if (!frame_offset) {
133                     /* This packet has no frame headers in it */
134                     if (avio_tell(pb) >= ffm->packet_size * 3LL) {
135                         int64_t seekback = FFMIN(ffm->packet_size * 2LL, avio_tell(pb) - last_pos);
136                         seekback = FFMAX(seekback, 0);
137                         avio_seek(pb, -seekback, SEEK_CUR);
138                         goto retry_read;
139                     }
140                     /* This is bad, we cannot find a valid frame header */
141                     return 0;
142                 }
143                 ffm->first_packet = 0;
144                 if ((frame_offset & 0x7fff) < FFM_HEADER_SIZE)
145                     return -1;
146                 ffm->packet_ptr = ffm->packet + (frame_offset & 0x7fff) - FFM_HEADER_SIZE;
147                 if (!header)
148                     break;
149             } else {
150                 ffm->packet_ptr = ffm->packet;
151             }
152             goto redo;
153         }
154         memcpy(buf, ffm->packet_ptr, len);
155         buf += len;
156         ffm->packet_ptr += len;
157         size -= len;
158         header = 0;
159     }
160     return size1 - size;
161 }
162
163 /* ensure that actual seeking happens between FFM_PACKET_SIZE
164    and file_size - FFM_PACKET_SIZE */
165 static int64_t ffm_seek1(AVFormatContext *s, int64_t pos1)
166 {
167     FFMContext *ffm = s->priv_data;
168     AVIOContext *pb = s->pb;
169     int64_t pos;
170
171     pos = FFMIN(pos1, ffm->file_size - FFM_PACKET_SIZE);
172     pos = FFMAX(pos, FFM_PACKET_SIZE);
173     ff_dlog(s, "seek to %"PRIx64" -> %"PRIx64"\n", pos1, pos);
174     return avio_seek(pb, pos, SEEK_SET);
175 }
176
177 static int64_t get_dts(AVFormatContext *s, int64_t pos)
178 {
179     AVIOContext *pb = s->pb;
180     int64_t dts;
181
182     ffm_seek1(s, pos);
183     avio_skip(pb, 4);
184     dts = avio_rb64(pb);
185     ff_dlog(s, "dts=%0.6f\n", dts / 1000000.0);
186     return dts;
187 }
188
189 static void adjust_write_index(AVFormatContext *s)
190 {
191     FFMContext *ffm = s->priv_data;
192     AVIOContext *pb = s->pb;
193     int64_t pts;
194     //int64_t orig_write_index = ffm->write_index;
195     int64_t pos_min, pos_max;
196     int64_t pts_start;
197     int64_t ptr = avio_tell(pb);
198
199
200     pos_min = 0;
201     pos_max = ffm->file_size - 2 * FFM_PACKET_SIZE;
202
203     pts_start = get_dts(s, pos_min);
204
205     pts = get_dts(s, pos_max);
206
207     if (pts - 100000 > pts_start)
208         goto end;
209
210     ffm->write_index = FFM_PACKET_SIZE;
211
212     pts_start = get_dts(s, pos_min);
213
214     pts = get_dts(s, pos_max);
215
216     if (pts - 100000 <= pts_start) {
217         while (1) {
218             int64_t newpos;
219             int64_t newpts;
220
221             newpos = ((pos_max + pos_min) / (2 * FFM_PACKET_SIZE)) * FFM_PACKET_SIZE;
222
223             if (newpos == pos_min)
224                 break;
225
226             newpts = get_dts(s, newpos);
227
228             if (newpts - 100000 <= pts) {
229                 pos_max = newpos;
230                 pts = newpts;
231             } else {
232                 pos_min = newpos;
233             }
234         }
235         ffm->write_index += pos_max;
236     }
237
238  end:
239     avio_seek(pb, ptr, SEEK_SET);
240 }
241
242
243 static int ffm_close(AVFormatContext *s)
244 {
245     int i;
246
247     for (i = 0; i < s->nb_streams; i++)
248         av_freep(&s->streams[i]->codec->rc_eq);
249
250     return 0;
251 }
252
253 static int ffm_append_recommended_configuration(AVStream *st, char **conf)
254 {
255     int ret;
256     size_t newsize;
257     av_assert0(conf && st);
258     if (!*conf)
259         return 0;
260     if (!st->recommended_encoder_configuration) {
261         st->recommended_encoder_configuration = *conf;
262         *conf = 0;
263         return 0;
264     }
265     newsize = strlen(*conf) + strlen(st->recommended_encoder_configuration) + 2;
266     if ((ret = av_reallocp(&st->recommended_encoder_configuration, newsize)) < 0)
267         return ret;
268     av_strlcat(st->recommended_encoder_configuration, ",", newsize);
269     av_strlcat(st->recommended_encoder_configuration, *conf, newsize);
270     av_freep(conf);
271     return 0;
272 }
273
274 static int ffm2_read_header(AVFormatContext *s)
275 {
276     FFMContext *ffm = s->priv_data;
277     AVStream *st;
278     AVIOContext *pb = s->pb;
279     AVCodecContext *codec;
280     const AVCodecDescriptor *codec_desc;
281     int ret;
282     int f_main = 0, f_cprv = -1, f_stvi = -1, f_stau = -1;
283     AVCodec *enc;
284     char *buffer;
285
286     ffm->packet_size = avio_rb32(pb);
287     if (ffm->packet_size != FFM_PACKET_SIZE) {
288         av_log(s, AV_LOG_ERROR, "Invalid packet size %d, expected size was %d\n",
289                ffm->packet_size, FFM_PACKET_SIZE);
290         ret = AVERROR_INVALIDDATA;
291         goto fail;
292     }
293
294     ffm->write_index = avio_rb64(pb);
295     /* get also filesize */
296     if (pb->seekable) {
297         ffm->file_size = avio_size(pb);
298         if (ffm->write_index && 0)
299             adjust_write_index(s);
300     } else {
301         ffm->file_size = (UINT64_C(1) << 63) - 1;
302     }
303
304     while(!avio_feof(pb)) {
305         unsigned id = avio_rb32(pb);
306         unsigned size = avio_rb32(pb);
307         int64_t next = avio_tell(pb) + size;
308         char rc_eq_buf[128];
309
310         if(!id)
311             break;
312
313         switch(id) {
314         case MKBETAG('M', 'A', 'I', 'N'):
315             if (f_main++) {
316                 ret = AVERROR(EINVAL);
317                 goto fail;
318             }
319             avio_rb32(pb); /* nb_streams */
320             avio_rb32(pb); /* total bitrate */
321             break;
322         case MKBETAG('C', 'O', 'M', 'M'):
323             f_cprv = f_stvi = f_stau = 0;
324             st = avformat_new_stream(s, NULL);
325             if (!st) {
326                 ret = AVERROR(ENOMEM);
327                 goto fail;
328             }
329
330             avpriv_set_pts_info(st, 64, 1, 1000000);
331
332             codec = st->codec;
333             /* generic info */
334             codec->codec_id = avio_rb32(pb);
335             codec_desc = avcodec_descriptor_get(codec->codec_id);
336             if (!codec_desc) {
337                 av_log(s, AV_LOG_ERROR, "Invalid codec id: %d\n", codec->codec_id);
338                 codec->codec_id = AV_CODEC_ID_NONE;
339                 goto fail;
340             }
341             codec->codec_type = avio_r8(pb);
342             if (codec->codec_type != codec_desc->type) {
343                 av_log(s, AV_LOG_ERROR, "Codec type mismatch: expected %d, found %d\n",
344                        codec_desc->type, codec->codec_type);
345                 codec->codec_id = AV_CODEC_ID_NONE;
346                 codec->codec_type = AVMEDIA_TYPE_UNKNOWN;
347                 goto fail;
348             }
349             codec->bit_rate = avio_rb32(pb);
350             codec->flags = avio_rb32(pb);
351             codec->flags2 = avio_rb32(pb);
352             codec->debug = avio_rb32(pb);
353             if (codec->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
354                 if (ff_get_extradata(codec, pb, avio_rb32(pb)) < 0)
355                     return AVERROR(ENOMEM);
356             }
357             break;
358         case MKBETAG('S', 'T', 'V', 'I'):
359             if (f_stvi++) {
360                 ret = AVERROR(EINVAL);
361                 goto fail;
362             }
363             codec->time_base.num = avio_rb32(pb);
364             codec->time_base.den = avio_rb32(pb);
365             if (codec->time_base.num <= 0 || codec->time_base.den <= 0) {
366                 av_log(s, AV_LOG_ERROR, "Invalid time base %d/%d\n",
367                        codec->time_base.num, codec->time_base.den);
368                 ret = AVERROR_INVALIDDATA;
369                 goto fail;
370             }
371             codec->width = avio_rb16(pb);
372             codec->height = avio_rb16(pb);
373             codec->gop_size = avio_rb16(pb);
374             codec->pix_fmt = avio_rb32(pb);
375             codec->qmin = avio_r8(pb);
376             codec->qmax = avio_r8(pb);
377             codec->max_qdiff = avio_r8(pb);
378             codec->qcompress = avio_rb16(pb) / 10000.0;
379             codec->qblur = avio_rb16(pb) / 10000.0;
380             codec->bit_rate_tolerance = avio_rb32(pb);
381             avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));
382             codec->rc_eq = av_strdup(rc_eq_buf);
383             codec->rc_max_rate = avio_rb32(pb);
384             codec->rc_min_rate = avio_rb32(pb);
385             codec->rc_buffer_size = avio_rb32(pb);
386             codec->i_quant_factor = av_int2double(avio_rb64(pb));
387             codec->b_quant_factor = av_int2double(avio_rb64(pb));
388             codec->i_quant_offset = av_int2double(avio_rb64(pb));
389             codec->b_quant_offset = av_int2double(avio_rb64(pb));
390             codec->dct_algo = avio_rb32(pb);
391             codec->strict_std_compliance = avio_rb32(pb);
392             codec->max_b_frames = avio_rb32(pb);
393             codec->mpeg_quant = avio_rb32(pb);
394             codec->intra_dc_precision = avio_rb32(pb);
395             codec->me_method = avio_rb32(pb);
396             codec->mb_decision = avio_rb32(pb);
397             codec->nsse_weight = avio_rb32(pb);
398             codec->frame_skip_cmp = avio_rb32(pb);
399             codec->rc_buffer_aggressivity = av_int2double(avio_rb64(pb));
400             codec->codec_tag = avio_rb32(pb);
401             codec->thread_count = avio_r8(pb);
402             codec->coder_type = avio_rb32(pb);
403             codec->me_cmp = avio_rb32(pb);
404             codec->me_subpel_quality = avio_rb32(pb);
405             codec->me_range = avio_rb32(pb);
406             codec->keyint_min = avio_rb32(pb);
407             codec->scenechange_threshold = avio_rb32(pb);
408             codec->b_frame_strategy = avio_rb32(pb);
409             codec->qcompress = av_int2double(avio_rb64(pb));
410             codec->qblur = av_int2double(avio_rb64(pb));
411             codec->max_qdiff = avio_rb32(pb);
412             codec->refs = avio_rb32(pb);
413             break;
414         case MKBETAG('S', 'T', 'A', 'U'):
415             if (f_stau++) {
416                 ret = AVERROR(EINVAL);
417                 goto fail;
418             }
419             codec->sample_rate = avio_rb32(pb);
420             codec->channels = avio_rl16(pb);
421             codec->frame_size = avio_rl16(pb);
422             break;
423         case MKBETAG('C', 'P', 'R', 'V'):
424             if (f_cprv++) {
425                 ret = AVERROR(EINVAL);
426                 goto fail;
427             }
428             enc = avcodec_find_encoder(codec->codec_id);
429             if (enc && enc->priv_data_size && enc->priv_class) {
430                 buffer = av_malloc(size + 1);
431                 if (!buffer) {
432                     ret = AVERROR(ENOMEM);
433                     goto fail;
434                 }
435                 avio_get_str(pb, size, buffer, size + 1);
436                 if ((ret = ffm_append_recommended_configuration(st, &buffer)) < 0)
437                     goto fail;
438             }
439             break;
440         case MKBETAG('S', '2', 'V', 'I'):
441             if (f_stvi++ || !size) {
442                 ret = AVERROR(EINVAL);
443                 goto fail;
444             }
445             buffer = av_malloc(size);
446             if (!buffer) {
447                 ret = AVERROR(ENOMEM);
448                 goto fail;
449             }
450             avio_get_str(pb, INT_MAX, buffer, size);
451             av_set_options_string(codec, buffer, "=", ",");
452             if ((ret = ffm_append_recommended_configuration(st, &buffer)) < 0)
453                 goto fail;
454             break;
455         case MKBETAG('S', '2', 'A', 'U'):
456             if (f_stau++ || !size) {
457                 ret = AVERROR(EINVAL);
458                 goto fail;
459             }
460             buffer = av_malloc(size);
461             if (!buffer) {
462                 ret = AVERROR(ENOMEM);
463                 goto fail;
464             }
465             avio_get_str(pb, INT_MAX, buffer, size);
466             av_set_options_string(codec, buffer, "=", ",");
467             if ((ret = ffm_append_recommended_configuration(st, &buffer)) < 0)
468                 goto fail;
469             break;
470         }
471         avio_seek(pb, next, SEEK_SET);
472     }
473
474     /* get until end of block reached */
475     while ((avio_tell(pb) % ffm->packet_size) != 0 && !pb->eof_reached)
476         avio_r8(pb);
477
478     /* init packet demux */
479     ffm->packet_ptr = ffm->packet;
480     ffm->packet_end = ffm->packet;
481     ffm->frame_offset = 0;
482     ffm->dts = 0;
483     ffm->read_state = READ_HEADER;
484     ffm->first_packet = 1;
485     return 0;
486  fail:
487     ffm_close(s);
488     return ret;
489 }
490
491 static int ffm_read_header(AVFormatContext *s)
492 {
493     FFMContext *ffm = s->priv_data;
494     AVStream *st;
495     AVIOContext *pb = s->pb;
496     AVCodecContext *codec;
497     const AVCodecDescriptor *codec_desc;
498     int i, nb_streams;
499     uint32_t tag;
500
501     /* header */
502     tag = avio_rl32(pb);
503     if (tag == MKTAG('F', 'F', 'M', '2'))
504         return ffm2_read_header(s);
505     if (tag != MKTAG('F', 'F', 'M', '1'))
506         goto fail;
507     ffm->packet_size = avio_rb32(pb);
508     if (ffm->packet_size != FFM_PACKET_SIZE)
509         goto fail;
510     ffm->write_index = avio_rb64(pb);
511     /* get also filesize */
512     if (pb->seekable) {
513         ffm->file_size = avio_size(pb);
514         if (ffm->write_index && 0)
515             adjust_write_index(s);
516     } else {
517         ffm->file_size = (UINT64_C(1) << 63) - 1;
518     }
519
520     nb_streams = avio_rb32(pb);
521     avio_rb32(pb); /* total bitrate */
522     /* read each stream */
523     for(i=0;i<nb_streams;i++) {
524         char rc_eq_buf[128];
525
526         st = avformat_new_stream(s, NULL);
527         if (!st)
528             goto fail;
529
530         avpriv_set_pts_info(st, 64, 1, 1000000);
531
532         codec = st->codec;
533         /* generic info */
534         codec->codec_id = avio_rb32(pb);
535         codec_desc = avcodec_descriptor_get(codec->codec_id);
536         if (!codec_desc) {
537             av_log(s, AV_LOG_ERROR, "Invalid codec id: %d\n", codec->codec_id);
538             codec->codec_id = AV_CODEC_ID_NONE;
539             goto fail;
540         }
541         codec->codec_type = avio_r8(pb); /* codec_type */
542         if (codec->codec_type != codec_desc->type) {
543             av_log(s, AV_LOG_ERROR, "Codec type mismatch: expected %d, found %d\n",
544                    codec_desc->type, codec->codec_type);
545             codec->codec_id = AV_CODEC_ID_NONE;
546             codec->codec_type = AVMEDIA_TYPE_UNKNOWN;
547             goto fail;
548         }
549         codec->bit_rate = avio_rb32(pb);
550         codec->flags = avio_rb32(pb);
551         codec->flags2 = avio_rb32(pb);
552         codec->debug = avio_rb32(pb);
553         /* specific info */
554         switch(codec->codec_type) {
555         case AVMEDIA_TYPE_VIDEO:
556             codec->time_base.num = avio_rb32(pb);
557             codec->time_base.den = avio_rb32(pb);
558             if (codec->time_base.num <= 0 || codec->time_base.den <= 0) {
559                 av_log(s, AV_LOG_ERROR, "Invalid time base %d/%d\n",
560                        codec->time_base.num, codec->time_base.den);
561                 goto fail;
562             }
563             codec->width = avio_rb16(pb);
564             codec->height = avio_rb16(pb);
565             codec->gop_size = avio_rb16(pb);
566             codec->pix_fmt = avio_rb32(pb);
567             codec->qmin = avio_r8(pb);
568             codec->qmax = avio_r8(pb);
569             codec->max_qdiff = avio_r8(pb);
570             codec->qcompress = avio_rb16(pb) / 10000.0;
571             codec->qblur = avio_rb16(pb) / 10000.0;
572             codec->bit_rate_tolerance = avio_rb32(pb);
573             avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));
574             codec->rc_eq = av_strdup(rc_eq_buf);
575             codec->rc_max_rate = avio_rb32(pb);
576             codec->rc_min_rate = avio_rb32(pb);
577             codec->rc_buffer_size = avio_rb32(pb);
578             codec->i_quant_factor = av_int2double(avio_rb64(pb));
579             codec->b_quant_factor = av_int2double(avio_rb64(pb));
580             codec->i_quant_offset = av_int2double(avio_rb64(pb));
581             codec->b_quant_offset = av_int2double(avio_rb64(pb));
582             codec->dct_algo = avio_rb32(pb);
583             codec->strict_std_compliance = avio_rb32(pb);
584             codec->max_b_frames = avio_rb32(pb);
585             codec->mpeg_quant = avio_rb32(pb);
586             codec->intra_dc_precision = avio_rb32(pb);
587             codec->me_method = avio_rb32(pb);
588             codec->mb_decision = avio_rb32(pb);
589             codec->nsse_weight = avio_rb32(pb);
590             codec->frame_skip_cmp = avio_rb32(pb);
591             codec->rc_buffer_aggressivity = av_int2double(avio_rb64(pb));
592             codec->codec_tag = avio_rb32(pb);
593             codec->thread_count = avio_r8(pb);
594             codec->coder_type = avio_rb32(pb);
595             codec->me_cmp = avio_rb32(pb);
596             codec->me_subpel_quality = avio_rb32(pb);
597             codec->me_range = avio_rb32(pb);
598             codec->keyint_min = avio_rb32(pb);
599             codec->scenechange_threshold = avio_rb32(pb);
600             codec->b_frame_strategy = avio_rb32(pb);
601             codec->qcompress = av_int2double(avio_rb64(pb));
602             codec->qblur = av_int2double(avio_rb64(pb));
603             codec->max_qdiff = avio_rb32(pb);
604             codec->refs = avio_rb32(pb);
605             break;
606         case AVMEDIA_TYPE_AUDIO:
607             codec->sample_rate = avio_rb32(pb);
608             codec->channels = avio_rl16(pb);
609             codec->frame_size = avio_rl16(pb);
610             break;
611         default:
612             goto fail;
613         }
614         if (codec->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
615             if (ff_get_extradata(codec, pb, avio_rb32(pb)) < 0)
616                 return AVERROR(ENOMEM);
617         }
618     }
619
620     /* get until end of block reached */
621     while ((avio_tell(pb) % ffm->packet_size) != 0 && !pb->eof_reached)
622         avio_r8(pb);
623
624     /* init packet demux */
625     ffm->packet_ptr = ffm->packet;
626     ffm->packet_end = ffm->packet;
627     ffm->frame_offset = 0;
628     ffm->dts = 0;
629     ffm->read_state = READ_HEADER;
630     ffm->first_packet = 1;
631     return 0;
632  fail:
633     ffm_close(s);
634     return -1;
635 }
636
637 /* return < 0 if eof */
638 static int ffm_read_packet(AVFormatContext *s, AVPacket *pkt)
639 {
640     int size;
641     FFMContext *ffm = s->priv_data;
642     int duration, ret;
643
644     switch(ffm->read_state) {
645     case READ_HEADER:
646         if ((ret = ffm_is_avail_data(s, FRAME_HEADER_SIZE+4)) < 0)
647             return ret;
648
649         ff_dlog(s, "pos=%08"PRIx64" spos=%"PRIx64", write_index=%"PRIx64" size=%"PRIx64"\n",
650                avio_tell(s->pb), s->pb->pos, ffm->write_index, ffm->file_size);
651         if (ffm_read_data(s, ffm->header, FRAME_HEADER_SIZE, 1) !=
652             FRAME_HEADER_SIZE)
653             return -1;
654         if (ffm->header[1] & FLAG_DTS)
655             if (ffm_read_data(s, ffm->header+16, 4, 1) != 4)
656                 return -1;
657         ffm->read_state = READ_DATA;
658         /* fall through */
659     case READ_DATA:
660         size = AV_RB24(ffm->header + 2);
661         if ((ret = ffm_is_avail_data(s, size)) < 0)
662             return ret;
663
664         duration = AV_RB24(ffm->header + 5);
665
666         if (av_new_packet(pkt, size) < 0) {
667             return AVERROR(ENOMEM);
668         }
669         pkt->stream_index = ffm->header[0];
670         if ((unsigned)pkt->stream_index >= s->nb_streams) {
671             av_log(s, AV_LOG_ERROR, "invalid stream index %d\n", pkt->stream_index);
672             av_packet_unref(pkt);
673             ffm->read_state = READ_HEADER;
674             return -1;
675         }
676         pkt->pos = avio_tell(s->pb);
677         if (ffm->header[1] & FLAG_KEY_FRAME)
678             pkt->flags |= AV_PKT_FLAG_KEY;
679
680         ffm->read_state = READ_HEADER;
681         if (ffm_read_data(s, pkt->data, size, 0) != size) {
682             /* bad case: desynchronized packet. we cancel all the packet loading */
683             av_packet_unref(pkt);
684             return -1;
685         }
686         pkt->pts = AV_RB64(ffm->header+8);
687         if (ffm->header[1] & FLAG_DTS)
688             pkt->dts = pkt->pts - AV_RB32(ffm->header+16);
689         else
690             pkt->dts = pkt->pts;
691         pkt->duration = duration;
692         break;
693     }
694     return 0;
695 }
696
697 /* seek to a given time in the file. The file read pointer is
698    positioned at or before pts. XXX: the following code is quite
699    approximative */
700 static int ffm_seek(AVFormatContext *s, int stream_index, int64_t wanted_pts, int flags)
701 {
702     FFMContext *ffm = s->priv_data;
703     int64_t pos_min, pos_max, pos;
704     int64_t pts_min, pts_max, pts;
705     double pos1;
706
707     ff_dlog(s, "wanted_pts=%0.6f\n", wanted_pts / 1000000.0);
708     /* find the position using linear interpolation (better than
709        dichotomy in typical cases) */
710     if (ffm->write_index && ffm->write_index < ffm->file_size) {
711         if (get_dts(s, FFM_PACKET_SIZE) < wanted_pts) {
712             pos_min = FFM_PACKET_SIZE;
713             pos_max = ffm->write_index - FFM_PACKET_SIZE;
714         } else {
715             pos_min = ffm->write_index;
716             pos_max = ffm->file_size - FFM_PACKET_SIZE;
717         }
718     } else {
719         pos_min = FFM_PACKET_SIZE;
720         pos_max = ffm->file_size - FFM_PACKET_SIZE;
721     }
722     while (pos_min <= pos_max) {
723         pts_min = get_dts(s, pos_min);
724         pts_max = get_dts(s, pos_max);
725         if (pts_min > wanted_pts || pts_max <= wanted_pts) {
726             pos = pts_min > wanted_pts ? pos_min : pos_max;
727             goto found;
728         }
729         /* linear interpolation */
730         pos1 = (double)(pos_max - pos_min) * (double)(wanted_pts - pts_min) /
731             (double)(pts_max - pts_min);
732         pos = (((int64_t)pos1) / FFM_PACKET_SIZE) * FFM_PACKET_SIZE;
733         if (pos <= pos_min)
734             pos = pos_min;
735         else if (pos >= pos_max)
736             pos = pos_max;
737         pts = get_dts(s, pos);
738         /* check if we are lucky */
739         if (pts == wanted_pts) {
740             goto found;
741         } else if (pts > wanted_pts) {
742             pos_max = pos - FFM_PACKET_SIZE;
743         } else {
744             pos_min = pos + FFM_PACKET_SIZE;
745         }
746     }
747     pos = (flags & AVSEEK_FLAG_BACKWARD) ? pos_min : pos_max;
748
749  found:
750     if (ffm_seek1(s, pos) < 0)
751         return -1;
752
753     /* reset read state */
754     ffm->read_state = READ_HEADER;
755     ffm->packet_ptr = ffm->packet;
756     ffm->packet_end = ffm->packet;
757     ffm->first_packet = 1;
758
759     return 0;
760 }
761
762 static int ffm_probe(AVProbeData *p)
763 {
764     if (
765         p->buf[0] == 'F' && p->buf[1] == 'F' && p->buf[2] == 'M' &&
766         (p->buf[3] == '1' || p->buf[3] == '2'))
767         return AVPROBE_SCORE_MAX + 1;
768     return 0;
769 }
770
771 static const AVOption options[] = {
772     {"server_attached", NULL, offsetof(FFMContext, server_attached), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_EXPORT },
773     {"ffm_write_index", NULL, offsetof(FFMContext, write_index), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, 1, AV_OPT_FLAG_EXPORT },
774     {"ffm_file_size", NULL, offsetof(FFMContext, file_size), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, 1, AV_OPT_FLAG_EXPORT },
775     { NULL },
776 };
777
778 static const AVClass ffm_class = {
779     .class_name = "ffm demuxer",
780     .item_name  = av_default_item_name,
781     .option     = options,
782     .version    = LIBAVUTIL_VERSION_INT,
783 };
784 AVInputFormat ff_ffm_demuxer = {
785     .name           = "ffm",
786     .long_name      = NULL_IF_CONFIG_SMALL("FFM (FFserver live feed)"),
787     .priv_data_size = sizeof(FFMContext),
788     .read_probe     = ffm_probe,
789     .read_header    = ffm_read_header,
790     .read_packet    = ffm_read_packet,
791     .read_close     = ffm_close,
792     .read_seek      = ffm_seek,
793     .priv_class     = &ffm_class,
794 };