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