]> git.sesse.net Git - ffmpeg/blob - libavformat/wavdec.c
ffmdec: fix hypothetical overflows
[ffmpeg] / libavformat / wavdec.c
1 /*
2  * WAV demuxer
3  * Copyright (c) 2001, 2002 Fabrice Bellard
4  *
5  * Sony Wave64 demuxer
6  * RF64 demuxer
7  * Copyright (c) 2009 Daniel Verkamp
8  *
9  * This file is part of FFmpeg.
10  *
11  * FFmpeg is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * FFmpeg is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with FFmpeg; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24  */
25
26 #include "libavutil/avassert.h"
27 #include "libavutil/dict.h"
28 #include "libavutil/log.h"
29 #include "libavutil/mathematics.h"
30 #include "libavutil/opt.h"
31 #include "avformat.h"
32 #include "internal.h"
33 #include "avio_internal.h"
34 #include "pcm.h"
35 #include "riff.h"
36 #include "avio.h"
37 #include "metadata.h"
38
39 typedef struct WAVDemuxContext {
40     const AVClass *class;
41     int64_t data_end;
42     int w64;
43     int64_t smv_data_ofs;
44     int smv_block_size;
45     int smv_frames_per_jpeg;
46     int smv_block;
47     int smv_last_stream;
48     int smv_eof;
49     int audio_eof;
50     int ignore_length;
51 } WAVDemuxContext;
52
53
54 #if CONFIG_WAV_DEMUXER
55
56 static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
57 {
58     *tag = avio_rl32(pb);
59     return avio_rl32(pb);
60 }
61
62 /* return the size of the found tag */
63 static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
64 {
65     unsigned int tag;
66     int64_t size;
67
68     for (;;) {
69         if (url_feof(pb))
70             return -1;
71         size = next_tag(pb, &tag);
72         if (tag == tag1)
73             break;
74         avio_skip(pb, size);
75     }
76     return size;
77 }
78
79 static int wav_probe(AVProbeData *p)
80 {
81     /* check file header */
82     if (p->buf_size <= 32)
83         return 0;
84     if (!memcmp(p->buf + 8, "WAVE", 4)) {
85         if (!memcmp(p->buf, "RIFF", 4))
86             /*
87               Since ACT demuxer has standard WAV header at top of it's own,
88               returning score is decreased to avoid probe conflict
89               between ACT and WAV.
90             */
91             return AVPROBE_SCORE_MAX - 1;
92         else if (!memcmp(p->buf,      "RF64", 4) &&
93                  !memcmp(p->buf + 12, "ds64", 4))
94             return AVPROBE_SCORE_MAX;
95     }
96     return 0;
97 }
98
99 static void handle_stream_probing(AVStream *st)
100 {
101     if (st->codec->codec_id == AV_CODEC_ID_PCM_S16LE) {
102         st->request_probe = AVPROBE_SCORE_MAX/2;
103         st->probe_packets = FFMIN(st->probe_packets, 4);
104     }
105 }
106
107 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
108 {
109     AVIOContext *pb = s->pb;
110     int ret;
111
112     /* parse fmt header */
113     *st = avformat_new_stream(s, NULL);
114     if (!*st)
115         return AVERROR(ENOMEM);
116
117     ret = ff_get_wav_header(pb, (*st)->codec, size);
118     if (ret < 0)
119         return ret;
120     handle_stream_probing(*st);
121
122     (*st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
123
124     avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
125
126     return 0;
127 }
128
129 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
130                                         int length)
131 {
132     char temp[257];
133     int ret;
134
135     av_assert0(length <= sizeof(temp));
136     if ((ret = avio_read(s->pb, temp, length)) < 0)
137         return ret;
138
139     temp[length] = 0;
140
141     if (strlen(temp))
142         return av_dict_set(&s->metadata, key, temp, 0);
143
144     return 0;
145 }
146
147 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
148 {
149     char temp[131], *coding_history;
150     int ret, x;
151     uint64_t time_reference;
152     int64_t umid_parts[8], umid_mask = 0;
153
154     if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
155         (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
156         (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
157         (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
158         (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
159         return ret;
160
161     time_reference = avio_rl64(s->pb);
162     snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
163     if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
164         return ret;
165
166     /* check if version is >= 1, in which case an UMID may be present */
167     if (avio_rl16(s->pb) >= 1) {
168         for (x = 0; x < 8; x++)
169             umid_mask |= umid_parts[x] = avio_rb64(s->pb);
170
171         if (umid_mask) {
172             /* the string formatting below is per SMPTE 330M-2004 Annex C */
173             if (umid_parts[4] == 0 && umid_parts[5] == 0 && umid_parts[6] == 0 && umid_parts[7] == 0) {
174                 /* basic UMID */
175                 snprintf(temp, sizeof(temp), "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
176                          umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3]);
177             } else {
178                 /* extended UMID */
179                 snprintf(temp, sizeof(temp), "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
180                                                "%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
181                          umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3],
182                          umid_parts[4], umid_parts[5], umid_parts[6], umid_parts[7]);
183             }
184
185             if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
186                 return ret;
187         }
188
189         avio_skip(s->pb, 190);
190     } else
191         avio_skip(s->pb, 254);
192
193     if (size > 602) {
194         /* CodingHistory present */
195         size -= 602;
196
197         if (!(coding_history = av_malloc(size+1)))
198             return AVERROR(ENOMEM);
199
200         if ((ret = avio_read(s->pb, coding_history, size)) < 0)
201             return ret;
202
203         coding_history[size] = 0;
204         if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
205                                AV_DICT_DONT_STRDUP_VAL)) < 0)
206             return ret;
207     }
208
209     return 0;
210 }
211
212 static const AVMetadataConv wav_metadata_conv[] = {
213     {"description",      "comment"      },
214     {"originator",       "encoded_by"   },
215     {"origination_date", "date"         },
216     {"origination_time", "creation_time"},
217     {0},
218 };
219
220 /* wav input */
221 static int wav_read_header(AVFormatContext *s)
222 {
223     int64_t size, av_uninit(data_size);
224     int64_t sample_count=0;
225     int rf64;
226     uint32_t tag;
227     AVIOContext *pb = s->pb;
228     AVStream *st = NULL;
229     WAVDemuxContext *wav = s->priv_data;
230     int ret, got_fmt = 0;
231     int64_t next_tag_ofs, data_ofs = -1;
232
233     wav->smv_data_ofs = -1;
234
235     /* check RIFF header */
236     tag = avio_rl32(pb);
237
238     rf64 = tag == MKTAG('R', 'F', '6', '4');
239     if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
240         return -1;
241     avio_rl32(pb); /* file size */
242     tag = avio_rl32(pb);
243     if (tag != MKTAG('W', 'A', 'V', 'E'))
244         return -1;
245
246     if (rf64) {
247         if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
248             return -1;
249         size = avio_rl32(pb);
250         if (size < 24)
251             return -1;
252         avio_rl64(pb); /* RIFF size */
253         data_size = avio_rl64(pb);
254         sample_count = avio_rl64(pb);
255         if (data_size < 0 || sample_count < 0) {
256             av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
257                    "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
258                    data_size, sample_count);
259             return AVERROR_INVALIDDATA;
260         }
261         avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
262
263     }
264
265     for (;;) {
266         AVStream *vst;
267         size = next_tag(pb, &tag);
268         next_tag_ofs = avio_tell(pb) + size;
269
270         if (url_feof(pb))
271             break;
272
273         switch (tag) {
274         case MKTAG('f', 'm', 't', ' '):
275             /* only parse the first 'fmt ' tag found */
276             if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
277                 return ret;
278             } else if (got_fmt)
279                 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
280
281             got_fmt = 1;
282             break;
283         case MKTAG('d', 'a', 't', 'a'):
284             if (!got_fmt) {
285                 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'data' tag\n");
286                 return AVERROR_INVALIDDATA;
287             }
288
289             if (rf64) {
290                 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
291             } else {
292                 data_size = size;
293                 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
294             }
295
296             data_ofs = avio_tell(pb);
297
298             /* don't look for footer metadata if we can't seek or if we don't
299              * know where the data tag ends
300              */
301             if (!pb->seekable || (!rf64 && !size))
302                 goto break_loop;
303             break;
304         case MKTAG('f','a','c','t'):
305             if (!sample_count)
306                 sample_count = avio_rl32(pb);
307             break;
308         case MKTAG('b','e','x','t'):
309             if ((ret = wav_parse_bext_tag(s, size)) < 0)
310                 return ret;
311             break;
312         case MKTAG('S','M','V','0'):
313             if (!got_fmt) {
314                 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");
315                 return AVERROR_INVALIDDATA;
316             }
317             // SMV file, a wav file with video appended.
318             if (size != MKTAG('0','2','0','0')) {
319                 av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
320                 goto break_loop;
321             }
322             av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
323             vst = avformat_new_stream(s, NULL);
324             if (!vst)
325                 return AVERROR(ENOMEM);
326             avio_r8(pb);
327             vst->id = 1;
328             vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
329             vst->codec->codec_id = AV_CODEC_ID_MJPEG;
330             vst->codec->width  = avio_rl24(pb);
331             vst->codec->height = avio_rl24(pb);
332             size = avio_rl24(pb);
333             wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
334             avio_rl24(pb);
335             wav->smv_block_size = avio_rl24(pb);
336             avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
337             vst->duration = avio_rl24(pb);
338             avio_rl24(pb);
339             avio_rl24(pb);
340             wav->smv_frames_per_jpeg = avio_rl24(pb);
341             goto break_loop;
342         case MKTAG('L', 'I', 'S', 'T'):
343             if (size < 4) {
344                 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
345                 return AVERROR_INVALIDDATA;
346             }
347             switch (avio_rl32(pb)) {
348             case MKTAG('I', 'N', 'F', 'O'):
349                 if ((ret = ff_read_riff_info(s, size - 4)) < 0)
350                     return ret;
351             }
352             break;
353         }
354
355         /* seek to next tag unless we know that we'll run into EOF */
356         if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
357             avio_seek(pb, next_tag_ofs, SEEK_SET) < 0) {
358             break;
359         }
360     }
361 break_loop:
362     if (data_ofs < 0) {
363         av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
364         return AVERROR_INVALIDDATA;
365     }
366
367     avio_seek(pb, data_ofs, SEEK_SET);
368
369     if (!sample_count && st->codec->channels && av_get_bits_per_sample(st->codec->codec_id))
370         sample_count = (data_size<<3) / (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
371     if (sample_count)
372         st->duration = sample_count;
373
374     ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
375     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
376
377     return 0;
378 }
379
380 /** Find chunk with w64 GUID by skipping over other chunks
381  * @return the size of the found chunk
382  */
383 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
384 {
385     uint8_t guid[16];
386     int64_t size;
387
388     while (!url_feof(pb)) {
389         avio_read(pb, guid, 16);
390         size = avio_rl64(pb);
391         if (size <= 24)
392             return -1;
393         if (!memcmp(guid, guid1, 16))
394             return size;
395         avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
396     }
397     return -1;
398 }
399
400 static const uint8_t guid_data[16] = { 'd', 'a', 't', 'a',
401     0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
402
403 #define MAX_SIZE 4096
404
405 static int wav_read_packet(AVFormatContext *s,
406                            AVPacket *pkt)
407 {
408     int ret, size;
409     int64_t left;
410     AVStream *st;
411     WAVDemuxContext *wav = s->priv_data;
412
413     if (wav->smv_data_ofs > 0) {
414         int64_t audio_dts, video_dts;
415 smv_retry:
416         audio_dts = s->streams[0]->cur_dts;
417         video_dts = s->streams[1]->cur_dts;
418         if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
419             audio_dts = av_rescale_q(audio_dts, s->streams[0]->time_base, AV_TIME_BASE_Q);
420             video_dts = av_rescale_q(video_dts, s->streams[1]->time_base, AV_TIME_BASE_Q);
421             wav->smv_last_stream = video_dts >= audio_dts;
422         }
423         wav->smv_last_stream = !wav->smv_last_stream;
424         wav->smv_last_stream |= wav->audio_eof;
425         wav->smv_last_stream &= !wav->smv_eof;
426         if (wav->smv_last_stream) {
427             uint64_t old_pos = avio_tell(s->pb);
428             uint64_t new_pos = wav->smv_data_ofs +
429                 wav->smv_block * wav->smv_block_size;
430             if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
431                 ret = AVERROR_EOF;
432                 goto smv_out;
433             }
434             size = avio_rl24(s->pb);
435             ret  = av_get_packet(s->pb, pkt, size);
436             if (ret < 0)
437                 goto smv_out;
438             pkt->pos -= 3;
439             pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg;
440             wav->smv_block++;
441             pkt->stream_index = 1;
442 smv_out:
443             avio_seek(s->pb, old_pos, SEEK_SET);
444             if (ret == AVERROR_EOF) {
445                 wav->smv_eof = 1;
446                 goto smv_retry;
447             }
448             return ret;
449         }
450     }
451
452     st = s->streams[0];
453
454     left = wav->data_end - avio_tell(s->pb);
455     if (wav->ignore_length)
456         left= INT_MAX;
457     if (left <= 0){
458         if (CONFIG_W64_DEMUXER && wav->w64)
459             left = find_guid(s->pb, guid_data) - 24;
460         else
461             left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
462         if (left < 0) {
463             wav->audio_eof = 1;
464             if (wav->smv_data_ofs > 0 && !wav->smv_eof)
465                 goto smv_retry;
466             return AVERROR_EOF;
467         }
468         wav->data_end= avio_tell(s->pb) + left;
469     }
470
471     size = MAX_SIZE;
472     if (st->codec->block_align > 1) {
473         if (size < st->codec->block_align)
474             size = st->codec->block_align;
475         size = (size / st->codec->block_align) * st->codec->block_align;
476     }
477     size = FFMIN(size, left);
478     ret  = av_get_packet(s->pb, pkt, size);
479     if (ret < 0)
480         return ret;
481     pkt->stream_index = 0;
482
483     return ret;
484 }
485
486 static int wav_read_seek(AVFormatContext *s,
487                          int stream_index, int64_t timestamp, int flags)
488 {
489     WAVDemuxContext *wav = s->priv_data;
490     AVStream *st;
491     wav->smv_eof = 0;
492     wav->audio_eof = 0;
493     if (wav->smv_data_ofs > 0) {
494         int64_t smv_timestamp = timestamp;
495         if (stream_index == 0)
496             smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
497         else
498             timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
499         wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
500     }
501
502     st = s->streams[0];
503     switch (st->codec->codec_id) {
504     case AV_CODEC_ID_MP2:
505     case AV_CODEC_ID_MP3:
506     case AV_CODEC_ID_AC3:
507     case AV_CODEC_ID_DTS:
508         /* use generic seeking with dynamically generated indexes */
509         return -1;
510     default:
511         break;
512     }
513     return ff_pcm_read_seek(s, stream_index, timestamp, flags);
514 }
515
516 #define OFFSET(x) offsetof(WAVDemuxContext, x)
517 #define DEC AV_OPT_FLAG_DECODING_PARAM
518 static const AVOption demux_options[] = {
519     { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, DEC },
520     { NULL },
521 };
522
523 static const AVClass wav_demuxer_class = {
524     .class_name = "WAV demuxer",
525     .item_name  = av_default_item_name,
526     .option     = demux_options,
527     .version    = LIBAVUTIL_VERSION_INT,
528 };
529 AVInputFormat ff_wav_demuxer = {
530     .name           = "wav",
531     .long_name      = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
532     .priv_data_size = sizeof(WAVDemuxContext),
533     .read_probe     = wav_probe,
534     .read_header    = wav_read_header,
535     .read_packet    = wav_read_packet,
536     .read_seek      = wav_read_seek,
537     .flags          = AVFMT_GENERIC_INDEX,
538     .codec_tag      = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
539     .priv_class     = &wav_demuxer_class,
540 };
541 #endif /* CONFIG_WAV_DEMUXER */
542
543
544 #if CONFIG_W64_DEMUXER
545 static const uint8_t guid_riff[16] = { 'r', 'i', 'f', 'f',
546     0x2E, 0x91, 0xCF, 0x11, 0xA5, 0xD6, 0x28, 0xDB, 0x04, 0xC1, 0x00, 0x00 };
547
548 static const uint8_t guid_wave[16] = { 'w', 'a', 'v', 'e',
549     0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
550
551 static const uint8_t guid_fmt [16] = { 'f', 'm', 't', ' ',
552     0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
553
554 static int w64_probe(AVProbeData *p)
555 {
556     if (p->buf_size <= 40)
557         return 0;
558     if (!memcmp(p->buf,      guid_riff, 16) &&
559         !memcmp(p->buf + 24, guid_wave, 16))
560         return AVPROBE_SCORE_MAX;
561     else
562         return 0;
563 }
564
565 static int w64_read_header(AVFormatContext *s)
566 {
567     int64_t size;
568     AVIOContext *pb  = s->pb;
569     WAVDemuxContext    *wav = s->priv_data;
570     AVStream *st;
571     uint8_t guid[16];
572     int ret;
573
574     avio_read(pb, guid, 16);
575     if (memcmp(guid, guid_riff, 16))
576         return -1;
577
578     if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8) /* riff + wave + fmt + sizes */
579         return -1;
580
581     avio_read(pb, guid, 16);
582     if (memcmp(guid, guid_wave, 16)) {
583         av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
584         return -1;
585     }
586
587     size = find_guid(pb, guid_fmt);
588     if (size < 0) {
589         av_log(s, AV_LOG_ERROR, "could not find fmt guid\n");
590         return -1;
591     }
592
593     st = avformat_new_stream(s, NULL);
594     if (!st)
595         return AVERROR(ENOMEM);
596
597     /* subtract chunk header size - normal wav file doesn't count it */
598     ret = ff_get_wav_header(pb, st->codec, size - 24);
599     if (ret < 0)
600         return ret;
601     avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
602
603     handle_stream_probing(st);
604     st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
605
606     avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
607
608     size = find_guid(pb, guid_data);
609     if (size < 0) {
610         av_log(s, AV_LOG_ERROR, "could not find data guid\n");
611         return -1;
612     }
613     wav->data_end = avio_tell(pb) + size - 24;
614     wav->w64      = 1;
615
616     return 0;
617 }
618
619 AVInputFormat ff_w64_demuxer = {
620     .name           = "w64",
621     .long_name      = NULL_IF_CONFIG_SMALL("Sony Wave64"),
622     .priv_data_size = sizeof(WAVDemuxContext),
623     .read_probe     = w64_probe,
624     .read_header    = w64_read_header,
625     .read_packet    = wav_read_packet,
626     .read_seek      = wav_read_seek,
627     .flags          = AVFMT_GENERIC_INDEX,
628     .codec_tag      = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
629 };
630 #endif /* CONFIG_W64_DEMUXER */