]> git.sesse.net Git - ffmpeg/blob - libavformat/mpeg.c
copy_block: Change type of array stride parameters to ptrdiff_t
[ffmpeg] / libavformat / mpeg.c
1 /*
2  * MPEG-1/2 demuxer
3  * Copyright (c) 2000, 2001, 2002 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 "avformat.h"
23 #include "internal.h"
24 #include "mpeg.h"
25
26 /*********************************************/
27 /* demux code */
28
29 #define MAX_SYNC_SIZE 100000
30
31 static int check_pes(uint8_t *p, uint8_t *end)
32 {
33     int pes1;
34     int pes2 = (p[3] & 0xC0) == 0x80 &&
35                (p[4] & 0xC0) != 0x40 &&
36                ((p[4] & 0xC0) == 0x00 ||
37                 (p[4] & 0xC0) >> 2 == (p[6] & 0xF0));
38
39     for (p += 3; p < end && *p == 0xFF; p++) ;
40     if ((*p & 0xC0) == 0x40)
41         p += 2;
42
43     if ((*p & 0xF0) == 0x20)
44         pes1 = p[0] & p[2] & p[4] & 1;
45     else if ((*p & 0xF0) == 0x30)
46         pes1 = p[0] & p[2] & p[4] & p[5] & p[7] & p[9] & 1;
47     else
48         pes1 = *p == 0x0F;
49
50     return pes1 || pes2;
51 }
52
53 static int check_pack_header(const uint8_t *buf)
54 {
55     return (buf[1] & 0xC0) == 0x40 || (buf[1] & 0xF0) == 0x20;
56 }
57
58 static int mpegps_probe(AVProbeData *p)
59 {
60     uint32_t code = -1;
61     int i;
62     int sys = 0, pspack = 0, priv1 = 0, vid = 0;
63     int audio = 0, invalid = 0, score = 0;
64
65     for (i = 0; i < p->buf_size; i++) {
66         code = (code << 8) + p->buf[i];
67         if ((code & 0xffffff00) == 0x100) {
68             int len  = p->buf[i + 1] << 8 | p->buf[i + 2];
69             int pes  = check_pes(p->buf + i, p->buf + p->buf_size);
70             int pack = check_pack_header(p->buf + i);
71
72             if (code == SYSTEM_HEADER_START_CODE)
73                 sys++;
74             else if (code == PACK_START_CODE && pack)
75                 pspack++;
76             else if ((code & 0xf0) == VIDEO_ID && pes)
77                 vid++;
78             // skip pes payload to avoid start code emulation for private
79             // and audio streams
80             else if ((code & 0xe0) == AUDIO_ID && pes) {
81                 audio++;
82                 i += len;
83             } else if (code == PRIVATE_STREAM_1 && pes) {
84                 priv1++;
85                 i += len;
86             } else if ((code & 0xf0) == VIDEO_ID && !pes)
87                 invalid++;
88             else if ((code & 0xe0) == AUDIO_ID && !pes)
89                 invalid++;
90             else if (code == PRIVATE_STREAM_1 && !pes)
91                 invalid++;
92         }
93     }
94
95     if (vid + audio > invalid)   /* invalid VDR files nd short PES streams */
96         score = AVPROBE_SCORE_EXTENSION / 2;
97
98     if (sys > invalid && sys * 9 <= pspack * 10)
99         return pspack > 2 ? AVPROBE_SCORE_EXTENSION + 2
100                           : AVPROBE_SCORE_EXTENSION / 2; // 1 more than .mpg
101     if (pspack > invalid && (priv1 + vid + audio) * 10 >= pspack * 9)
102         return pspack > 2 ? AVPROBE_SCORE_EXTENSION + 2
103                           : AVPROBE_SCORE_EXTENSION / 2; // 1 more than .mpg
104     if ((!!vid ^ !!audio) && (audio > 4 || vid > 1) && !sys &&
105         !pspack && p->buf_size > 2048 && vid + audio > invalid) /* PES stream */
106         return (audio > 12 || vid > 3) ? AVPROBE_SCORE_EXTENSION + 2
107                                        : AVPROBE_SCORE_EXTENSION / 2;
108
109     // 02-Penguin.flac has sys:0 priv1:0 pspack:0 vid:0 audio:1
110     // mp3_misidentified_2.mp3 has sys:0 priv1:0 pspack:0 vid:0 audio:6
111     return score;
112 }
113
114 typedef struct MpegDemuxContext {
115     int32_t header_state;
116     unsigned char psm_es_type[256];
117     int sofdec;
118 } MpegDemuxContext;
119
120 static int mpegps_read_header(AVFormatContext *s)
121 {
122     MpegDemuxContext *m = s->priv_data;
123     const char *sofdec  = "Sofdec";
124     int v, i = 0;
125
126     m->header_state = 0xff;
127     s->ctx_flags   |= AVFMTCTX_NOHEADER;
128
129     m->sofdec = -1;
130     do {
131         v = avio_r8(s->pb);
132         m->header_state = m->header_state << 8 | v;
133         m->sofdec++;
134     } while (v == sofdec[i] && i++ < 6);
135
136     m->sofdec = (m->sofdec == 6) ? 1 : 0;
137
138     /* no need to do more */
139     return 0;
140 }
141
142 static int64_t get_pts(AVIOContext *pb, int c)
143 {
144     uint8_t buf[5];
145
146     buf[0] = c < 0 ? avio_r8(pb) : c;
147     avio_read(pb, buf + 1, 4);
148
149     return ff_parse_pes_pts(buf);
150 }
151
152 static int find_next_start_code(AVIOContext *pb, int *size_ptr,
153                                 int32_t *header_state)
154 {
155     unsigned int state, v;
156     int val, n;
157
158     state = *header_state;
159     n     = *size_ptr;
160     while (n > 0) {
161         if (pb->eof_reached)
162             break;
163         v = avio_r8(pb);
164         n--;
165         if (state == 0x000001) {
166             state = ((state << 8) | v) & 0xffffff;
167             val   = state;
168             goto found;
169         }
170         state = ((state << 8) | v) & 0xffffff;
171     }
172     val = -1;
173
174 found:
175     *header_state = state;
176     *size_ptr     = n;
177     return val;
178 }
179
180 /**
181  * Extract stream types from a program stream map
182  * According to ISO/IEC 13818-1 ('MPEG-2 Systems') table 2-35
183  *
184  * @return number of bytes occupied by PSM in the bitstream
185  */
186 static long mpegps_psm_parse(MpegDemuxContext *m, AVIOContext *pb)
187 {
188     int psm_length, ps_info_length, es_map_length;
189
190     psm_length = avio_rb16(pb);
191     avio_r8(pb);
192     avio_r8(pb);
193     ps_info_length = avio_rb16(pb);
194
195     /* skip program_stream_info */
196     avio_skip(pb, ps_info_length);
197     es_map_length = avio_rb16(pb);
198
199     /* at least one es available? */
200     while (es_map_length >= 4) {
201         unsigned char type      = avio_r8(pb);
202         unsigned char es_id     = avio_r8(pb);
203         uint16_t es_info_length = avio_rb16(pb);
204
205         /* remember mapping from stream id to stream type */
206         m->psm_es_type[es_id] = type;
207         /* skip program_stream_info */
208         avio_skip(pb, es_info_length);
209         es_map_length -= 4 + es_info_length;
210     }
211     avio_rb32(pb); /* crc32 */
212     return 2 + psm_length;
213 }
214
215 /* read the next PES header. Return its position in ppos
216  * (if not NULL), and its start code, pts and dts.
217  */
218 static int mpegps_read_pes_header(AVFormatContext *s,
219                                   int64_t *ppos, int *pstart_code,
220                                   int64_t *ppts, int64_t *pdts)
221 {
222     MpegDemuxContext *m = s->priv_data;
223     int len, size, startcode, c, flags, header_len;
224     int pes_ext, ext2_len, id_ext, skip;
225     int64_t pts, dts;
226     int64_t last_sync = avio_tell(s->pb);
227
228 error_redo:
229     avio_seek(s->pb, last_sync, SEEK_SET);
230 redo:
231     /* next start code (should be immediately after) */
232     m->header_state = 0xff;
233     size      = MAX_SYNC_SIZE;
234     startcode = find_next_start_code(s->pb, &size, &m->header_state);
235     last_sync = avio_tell(s->pb);
236     if (startcode < 0) {
237         if (s->pb->eof_reached)
238             return AVERROR_EOF;
239         // FIXME we should remember header_state
240         return AVERROR(EAGAIN);
241     }
242
243     if (startcode == PACK_START_CODE)
244         goto redo;
245     if (startcode == SYSTEM_HEADER_START_CODE)
246         goto redo;
247     if (startcode == PADDING_STREAM) {
248         avio_skip(s->pb, avio_rb16(s->pb));
249         goto redo;
250     }
251     if (startcode == PRIVATE_STREAM_2) {
252         len = avio_rb16(s->pb);
253         if (!m->sofdec) {
254             while (len-- >= 6) {
255                 if (avio_r8(s->pb) == 'S') {
256                     uint8_t buf[5];
257                     avio_read(s->pb, buf, sizeof(buf));
258                     m->sofdec = !memcmp(buf, "ofdec", 5);
259                     len -= sizeof(buf);
260                     break;
261                 }
262             }
263             m->sofdec -= !m->sofdec;
264         }
265         avio_skip(s->pb, len);
266         goto redo;
267     }
268     if (startcode == PROGRAM_STREAM_MAP) {
269         mpegps_psm_parse(m, s->pb);
270         goto redo;
271     }
272
273     /* find matching stream */
274     if (!((startcode >= 0x1c0 && startcode <= 0x1df) ||
275           (startcode >= 0x1e0 && startcode <= 0x1ef) ||
276           (startcode == 0x1bd) || (startcode == 0x1fd)))
277         goto redo;
278     if (ppos) {
279         *ppos = avio_tell(s->pb) - 4;
280     }
281     len = avio_rb16(s->pb);
282     pts =
283     dts = AV_NOPTS_VALUE;
284     /* stuffing */
285     for (;;) {
286         if (len < 1)
287             goto error_redo;
288         c = avio_r8(s->pb);
289         len--;
290         /* XXX: for MPEG-1, should test only bit 7 */
291         if (c != 0xff)
292             break;
293     }
294     if ((c & 0xc0) == 0x40) {
295         /* buffer scale & size */
296         avio_r8(s->pb);
297         c    = avio_r8(s->pb);
298         len -= 2;
299     }
300     if ((c & 0xe0) == 0x20) {
301         dts  =
302         pts  = get_pts(s->pb, c);
303         len -= 4;
304         if (c & 0x10) {
305             dts  = get_pts(s->pb, -1);
306             len -= 5;
307         }
308     } else if ((c & 0xc0) == 0x80) {
309         /* mpeg 2 PES */
310         flags      = avio_r8(s->pb);
311         header_len = avio_r8(s->pb);
312         len       -= 2;
313         if (header_len > len)
314             goto error_redo;
315         len -= header_len;
316         if (flags & 0x80) {
317             dts         = pts = get_pts(s->pb, -1);
318             header_len -= 5;
319             if (flags & 0x40) {
320                 dts         = get_pts(s->pb, -1);
321                 header_len -= 5;
322             }
323         }
324         if (flags & 0x3f && header_len == 0) {
325             flags &= 0xC0;
326             av_log(s, AV_LOG_WARNING, "Further flags set but no bytes left\n");
327         }
328         if (flags & 0x01) { /* PES extension */
329             pes_ext = avio_r8(s->pb);
330             header_len--;
331             /* Skip PES private data, program packet sequence counter
332              * and P-STD buffer */
333             skip  = (pes_ext >> 4) & 0xb;
334             skip += skip & 0x9;
335             if (pes_ext & 0x40 || skip > header_len) {
336                 av_log(s, AV_LOG_WARNING, "pes_ext %X is invalid\n", pes_ext);
337                 pes_ext = skip = 0;
338             }
339             avio_skip(s->pb, skip);
340             header_len -= skip;
341
342             if (pes_ext & 0x01) { /* PES extension 2 */
343                 ext2_len = avio_r8(s->pb);
344                 header_len--;
345                 if ((ext2_len & 0x7f) > 0) {
346                     id_ext = avio_r8(s->pb);
347                     if ((id_ext & 0x80) == 0)
348                         startcode = ((startcode & 0xff) << 8) | id_ext;
349                     header_len--;
350                 }
351             }
352         }
353         if (header_len < 0)
354             goto error_redo;
355         avio_skip(s->pb, header_len);
356     } else if (c != 0xf)
357         goto redo;
358
359     if (startcode == PRIVATE_STREAM_1 && !m->psm_es_type[startcode & 0xff]) {
360         startcode = avio_r8(s->pb);
361         len--;
362         if (startcode >= 0x80 && startcode <= 0xcf) {
363             /* audio: skip header */
364             avio_r8(s->pb);
365             avio_r8(s->pb);
366             avio_r8(s->pb);
367             len -= 3;
368             if (startcode >= 0xb0 && startcode <= 0xbf) {
369                 /* MLP/TrueHD audio has a 4-byte header */
370                 avio_r8(s->pb);
371                 len--;
372             }
373         }
374     }
375     if (len < 0)
376         goto error_redo;
377     if (dts != AV_NOPTS_VALUE && ppos) {
378         int i;
379         for (i = 0; i < s->nb_streams; i++) {
380             if (startcode == s->streams[i]->id &&
381                 s->pb->seekable /* index useless on streams anyway */) {
382                 ff_reduce_index(s, i);
383                 av_add_index_entry(s->streams[i], *ppos, dts, 0, 0,
384                                    AVINDEX_KEYFRAME /* FIXME keyframe? */);
385             }
386         }
387     }
388
389     *pstart_code = startcode;
390     *ppts        = pts;
391     *pdts        = dts;
392     return len;
393 }
394
395 static int mpegps_read_packet(AVFormatContext *s,
396                               AVPacket *pkt)
397 {
398     MpegDemuxContext *m = s->priv_data;
399     AVStream *st;
400     int len, startcode, i, es_type, ret;
401     enum AVCodecID codec_id = AV_CODEC_ID_NONE;
402     enum AVMediaType type;
403     int64_t pts, dts, dummy_pos; // dummy_pos is needed for the index building to work
404     uint8_t av_uninit(dvdaudio_substream_type);
405
406 redo:
407     len = mpegps_read_pes_header(s, &dummy_pos, &startcode, &pts, &dts);
408     if (len < 0)
409         return len;
410
411     if (startcode == 0x1bd) {
412         dvdaudio_substream_type = avio_r8(s->pb);
413         avio_skip(s->pb, 3);
414         len -= 4;
415     }
416
417     /* now find stream */
418     for (i = 0; i < s->nb_streams; i++) {
419         st = s->streams[i];
420         if (st->id == startcode)
421             goto found;
422     }
423
424     es_type = m->psm_es_type[startcode & 0xff];
425     if (es_type > 0 && es_type != STREAM_TYPE_PRIVATE_DATA) {
426         if (es_type == STREAM_TYPE_VIDEO_MPEG1) {
427             codec_id = AV_CODEC_ID_MPEG2VIDEO;
428             type     = AVMEDIA_TYPE_VIDEO;
429         } else if (es_type == STREAM_TYPE_VIDEO_MPEG2) {
430             codec_id = AV_CODEC_ID_MPEG2VIDEO;
431             type     = AVMEDIA_TYPE_VIDEO;
432         } else if (es_type == STREAM_TYPE_AUDIO_MPEG1 ||
433                    es_type == STREAM_TYPE_AUDIO_MPEG2) {
434             codec_id = AV_CODEC_ID_MP3;
435             type     = AVMEDIA_TYPE_AUDIO;
436         } else if (es_type == STREAM_TYPE_AUDIO_AAC) {
437             codec_id = AV_CODEC_ID_AAC;
438             type     = AVMEDIA_TYPE_AUDIO;
439         } else if (es_type == STREAM_TYPE_VIDEO_MPEG4) {
440             codec_id = AV_CODEC_ID_MPEG4;
441             type     = AVMEDIA_TYPE_VIDEO;
442         } else if (es_type == STREAM_TYPE_VIDEO_H264) {
443             codec_id = AV_CODEC_ID_H264;
444             type     = AVMEDIA_TYPE_VIDEO;
445         } else if (es_type == STREAM_TYPE_AUDIO_AC3) {
446             codec_id = AV_CODEC_ID_AC3;
447             type     = AVMEDIA_TYPE_AUDIO;
448         } else {
449             goto skip;
450         }
451     } else if (startcode >= 0x1e0 && startcode <= 0x1ef) {
452         static const unsigned char avs_seqh[4] = { 0, 0, 1, 0xb0 };
453         unsigned char buf[8];
454
455         avio_read(s->pb, buf, 8);
456         avio_seek(s->pb, -8, SEEK_CUR);
457         if (!memcmp(buf, avs_seqh, 4) && (buf[6] != 0 || buf[7] != 1))
458             codec_id = AV_CODEC_ID_CAVS;
459         else
460             codec_id = AV_CODEC_ID_PROBE;
461         type = AVMEDIA_TYPE_VIDEO;
462     } else if (startcode >= 0x1c0 && startcode <= 0x1df) {
463         type     = AVMEDIA_TYPE_AUDIO;
464         codec_id = m->sofdec > 0 ? AV_CODEC_ID_ADPCM_ADX : AV_CODEC_ID_MP2;
465     } else if (startcode >= 0x80 && startcode <= 0x87) {
466         type     = AVMEDIA_TYPE_AUDIO;
467         codec_id = AV_CODEC_ID_AC3;
468     } else if ((startcode >= 0x88 && startcode <= 0x8f) ||
469                (startcode >= 0x98 && startcode <= 0x9f)) {
470         /* 0x90 - 0x97 is reserved for SDDS in DVD specs */
471         type     = AVMEDIA_TYPE_AUDIO;
472         codec_id = AV_CODEC_ID_DTS;
473     } else if (startcode >= 0xa0 && startcode <= 0xaf) {
474         type     = AVMEDIA_TYPE_AUDIO;
475         codec_id = AV_CODEC_ID_PCM_DVD;
476     } else if (startcode >= 0xb0 && startcode <= 0xbf) {
477         type     = AVMEDIA_TYPE_AUDIO;
478         codec_id = AV_CODEC_ID_TRUEHD;
479     } else if (startcode >= 0xc0 && startcode <= 0xcf) {
480         /* Used for both AC-3 and E-AC-3 in EVOB files */
481         type     = AVMEDIA_TYPE_AUDIO;
482         codec_id = AV_CODEC_ID_AC3;
483     } else if (startcode >= 0x20 && startcode <= 0x3f) {
484         type     = AVMEDIA_TYPE_SUBTITLE;
485         codec_id = AV_CODEC_ID_DVD_SUBTITLE;
486     } else if (startcode >= 0xfd55 && startcode <= 0xfd5f) {
487         type     = AVMEDIA_TYPE_VIDEO;
488         codec_id = AV_CODEC_ID_VC1;
489     } else if (startcode == 0x1bd) {
490         // check dvd audio substream type
491         type = AVMEDIA_TYPE_AUDIO;
492         switch (dvdaudio_substream_type & 0xe0) {
493         case 0xa0:
494             codec_id = AV_CODEC_ID_PCM_DVD;
495             break;
496         case 0x80:
497             if ((dvdaudio_substream_type & 0xf8) == 0x88)
498                 codec_id = AV_CODEC_ID_DTS;
499             else
500                 codec_id = AV_CODEC_ID_AC3;
501             break;
502         default:
503             av_log(s, AV_LOG_ERROR, "Unknown 0x1bd sub-stream\n");
504             goto skip;
505         }
506     } else {
507 skip:
508         /* skip packet */
509         avio_skip(s->pb, len);
510         goto redo;
511     }
512     /* no stream found: add a new stream */
513     st = avformat_new_stream(s, NULL);
514     if (!st)
515         goto skip;
516     st->id                = startcode;
517     st->codecpar->codec_type = type;
518     st->codecpar->codec_id   = codec_id;
519     st->need_parsing      = AVSTREAM_PARSE_FULL;
520
521 found:
522     if (st->discard >= AVDISCARD_ALL)
523         goto skip;
524     ret = av_get_packet(s->pb, pkt, len);
525
526     pkt->pts          = pts;
527     pkt->dts          = dts;
528     pkt->pos          = dummy_pos;
529     pkt->stream_index = st->index;
530     av_log(s, AV_LOG_TRACE, "%d: pts=%0.3f dts=%0.3f size=%d\n",
531             pkt->stream_index, pkt->pts / 90000.0, pkt->dts / 90000.0,
532             pkt->size);
533
534     return (ret < 0) ? ret : 0;
535 }
536
537 static int64_t mpegps_read_dts(AVFormatContext *s, int stream_index,
538                                int64_t *ppos, int64_t pos_limit)
539 {
540     int len, startcode;
541     int64_t pos, pts, dts;
542
543     pos = *ppos;
544     if (avio_seek(s->pb, pos, SEEK_SET) < 0)
545         return AV_NOPTS_VALUE;
546
547     for (;;) {
548         len = mpegps_read_pes_header(s, &pos, &startcode, &pts, &dts);
549         if (len < 0) {
550             av_log(s, AV_LOG_TRACE, "none (ret=%d)\n", len);
551             return AV_NOPTS_VALUE;
552         }
553         if (startcode == s->streams[stream_index]->id &&
554             dts != AV_NOPTS_VALUE) {
555             break;
556         }
557         avio_skip(s->pb, len);
558     }
559     av_log(s, AV_LOG_TRACE, "pos=0x%"PRIx64" dts=0x%"PRIx64" %0.3f\n",
560             pos, dts, dts / 90000.0);
561     *ppos = pos;
562     return dts;
563 }
564
565 AVInputFormat ff_mpegps_demuxer = {
566     .name           = "mpeg",
567     .long_name      = NULL_IF_CONFIG_SMALL("MPEG-PS (MPEG-2 Program Stream)"),
568     .priv_data_size = sizeof(MpegDemuxContext),
569     .read_probe     = mpegps_probe,
570     .read_header    = mpegps_read_header,
571     .read_packet    = mpegps_read_packet,
572     .read_timestamp = mpegps_read_dts,
573     .flags          = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT,
574 };