]> git.sesse.net Git - ffmpeg/blob - libavformat/wav.c
wav: make sure neither data_size nor sample_count is negative.
[ffmpeg] / libavformat / wav.c
1 /*
2  * WAV muxer and 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 Libav.
10  *
11  * Libav 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  * Libav 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 Libav; 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/log.h"
27 #include "libavutil/mathematics.h"
28 #include "libavutil/opt.h"
29 #include "avformat.h"
30 #include "avio_internal.h"
31 #include "pcm.h"
32 #include "riff.h"
33 #include "avio.h"
34 #include "avio_internal.h"
35
36 typedef struct {
37     const AVClass *class;
38     int64_t data;
39     int64_t data_end;
40     int64_t minpts;
41     int64_t maxpts;
42     int last_duration;
43     int w64;
44     int write_bext;
45 } WAVContext;
46
47 #if CONFIG_WAV_MUXER
48 static inline void bwf_write_bext_string(AVFormatContext *s, const char *key, int maxlen)
49 {
50     AVDictionaryEntry *tag;
51     int len = 0;
52
53     if (tag = av_dict_get(s->metadata, key, NULL, 0)) {
54         len = strlen(tag->value);
55         len = FFMIN(len, maxlen);
56         avio_write(s->pb, tag->value, len);
57     }
58
59     ffio_fill(s->pb, 0, maxlen - len);
60 }
61
62 static void bwf_write_bext_chunk(AVFormatContext *s)
63 {
64     AVDictionaryEntry *tmp_tag;
65     uint64_t time_reference = 0;
66     int64_t bext = ff_start_tag(s->pb, "bext");
67
68     bwf_write_bext_string(s, "description", 256);
69     bwf_write_bext_string(s, "originator", 32);
70     bwf_write_bext_string(s, "originator_reference", 32);
71     bwf_write_bext_string(s, "origination_date", 10);
72     bwf_write_bext_string(s, "origination_time", 8);
73
74     if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))
75         time_reference = strtoll(tmp_tag->value, NULL, 10);
76     avio_wl64(s->pb, time_reference);
77     avio_wl16(s->pb, 1);  // set version to 1
78
79     if (tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) {
80         unsigned char umidpart_str[17] = {0};
81         int i;
82         uint64_t umidpart;
83         int len = strlen(tmp_tag->value+2);
84
85         for (i = 0; i < len/16; i++) {
86             memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);
87             umidpart = strtoll(umidpart_str, NULL, 16);
88             avio_wb64(s->pb, umidpart);
89         }
90         ffio_fill(s->pb, 0, 64 - i*8);
91     } else
92         ffio_fill(s->pb, 0, 64); // zero UMID
93
94     ffio_fill(s->pb, 0, 190); // Reserved
95
96     if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))
97         avio_put_str(s->pb, tmp_tag->value);
98
99     ff_end_tag(s->pb, bext);
100 }
101
102 static int wav_write_header(AVFormatContext *s)
103 {
104     WAVContext *wav = s->priv_data;
105     AVIOContext *pb = s->pb;
106     int64_t fmt, fact;
107
108     ffio_wfourcc(pb, "RIFF");
109     avio_wl32(pb, 0); /* file length */
110     ffio_wfourcc(pb, "WAVE");
111
112     /* format header */
113     fmt = ff_start_tag(pb, "fmt ");
114     if (ff_put_wav_header(pb, s->streams[0]->codec) < 0) {
115         av_log(s, AV_LOG_ERROR, "%s codec not supported in WAVE format\n",
116                s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");
117         return -1;
118     }
119     ff_end_tag(pb, fmt);
120
121     if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
122         && s->pb->seekable) {
123         fact = ff_start_tag(pb, "fact");
124         avio_wl32(pb, 0);
125         ff_end_tag(pb, fact);
126     }
127
128     if (wav->write_bext)
129         bwf_write_bext_chunk(s);
130
131     av_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
132     wav->maxpts = wav->last_duration = 0;
133     wav->minpts = INT64_MAX;
134
135     /* data header */
136     wav->data = ff_start_tag(pb, "data");
137
138     avio_flush(pb);
139
140     return 0;
141 }
142
143 static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
144 {
145     AVIOContext *pb  = s->pb;
146     WAVContext    *wav = s->priv_data;
147     avio_write(pb, pkt->data, pkt->size);
148     if(pkt->pts != AV_NOPTS_VALUE) {
149         wav->minpts        = FFMIN(wav->minpts, pkt->pts);
150         wav->maxpts        = FFMAX(wav->maxpts, pkt->pts);
151         wav->last_duration = pkt->duration;
152     } else
153         av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
154     return 0;
155 }
156
157 static int wav_write_trailer(AVFormatContext *s)
158 {
159     AVIOContext *pb  = s->pb;
160     WAVContext    *wav = s->priv_data;
161     int64_t file_size;
162
163     avio_flush(pb);
164
165     if (s->pb->seekable) {
166         ff_end_tag(pb, wav->data);
167
168         /* update file size */
169         file_size = avio_tell(pb);
170         avio_seek(pb, 4, SEEK_SET);
171         avio_wl32(pb, (uint32_t)(file_size - 8));
172         avio_seek(pb, file_size, SEEK_SET);
173
174         avio_flush(pb);
175
176         if(s->streams[0]->codec->codec_tag != 0x01) {
177             /* Update num_samps in fact chunk */
178             int number_of_samples;
179             number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
180                                            s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,
181                                            s->streams[0]->time_base.den);
182             avio_seek(pb, wav->data-12, SEEK_SET);
183             avio_wl32(pb, number_of_samples);
184             avio_seek(pb, file_size, SEEK_SET);
185             avio_flush(pb);
186         }
187     }
188     return 0;
189 }
190
191 #define OFFSET(x) offsetof(WAVContext, x)
192 #define ENC AV_OPT_FLAG_ENCODING_PARAM
193 static const AVOption options[] = {
194     { "write_bext", "Write BEXT chunk.", OFFSET(write_bext), FF_OPT_TYPE_INT, { 0 }, 0, 1, ENC },
195     { NULL },
196 };
197
198 static const AVClass wav_muxer_class = {
199     .class_name = "WAV muxer",
200     .item_name  = av_default_item_name,
201     .option     = options,
202     .version    = LIBAVUTIL_VERSION_INT,
203 };
204
205 AVOutputFormat ff_wav_muxer = {
206     "wav",
207     NULL_IF_CONFIG_SMALL("WAV format"),
208     "audio/x-wav",
209     "wav",
210     sizeof(WAVContext),
211     CODEC_ID_PCM_S16LE,
212     CODEC_ID_NONE,
213     wav_write_header,
214     wav_write_packet,
215     wav_write_trailer,
216     .codec_tag= (const AVCodecTag* const []){ff_codec_wav_tags, 0},
217     .priv_class = &wav_muxer_class,
218 };
219 #endif /* CONFIG_WAV_MUXER */
220
221
222 #if CONFIG_WAV_DEMUXER
223
224 static int64_t next_tag(AVIOContext *pb, unsigned int *tag)
225 {
226     *tag = avio_rl32(pb);
227     return avio_rl32(pb);
228 }
229
230 /* return the size of the found tag */
231 static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
232 {
233     unsigned int tag;
234     int64_t size;
235
236     for (;;) {
237         if (pb->eof_reached)
238             return -1;
239         size = next_tag(pb, &tag);
240         if (tag == tag1)
241             break;
242         avio_skip(pb, size);
243     }
244     return size;
245 }
246
247 static int wav_probe(AVProbeData *p)
248 {
249     /* check file header */
250     if (p->buf_size <= 32)
251         return 0;
252     if (!memcmp(p->buf + 8, "WAVE", 4)) {
253         if (!memcmp(p->buf, "RIFF", 4))
254             /*
255               Since ACT demuxer has standard WAV header at top of it's own,
256               returning score is decreased to avoid probe conflict
257               between ACT and WAV.
258             */
259             return AVPROBE_SCORE_MAX - 1;
260         else if (!memcmp(p->buf,      "RF64", 4) &&
261                  !memcmp(p->buf + 12, "ds64", 4))
262             return AVPROBE_SCORE_MAX;
263     }
264     return 0;
265 }
266
267 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
268 {
269     AVIOContext *pb = s->pb;
270     int ret;
271
272     /* parse fmt header */
273     *st = av_new_stream(s, 0);
274     if (!*st)
275         return AVERROR(ENOMEM);
276
277     ret = ff_get_wav_header(pb, (*st)->codec, size);
278     if (ret < 0)
279         return ret;
280     (*st)->need_parsing = AVSTREAM_PARSE_FULL;
281
282     av_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
283
284     return 0;
285 }
286
287 /* wav input */
288 static int wav_read_header(AVFormatContext *s,
289                            AVFormatParameters *ap)
290 {
291     int64_t size, av_uninit(data_size);
292     int64_t sample_count=0;
293     int rf64;
294     unsigned int tag;
295     AVIOContext *pb = s->pb;
296     AVStream *st;
297     WAVContext *wav = s->priv_data;
298     int ret, got_fmt = 0;
299     int64_t next_tag_ofs;
300
301     /* check RIFF header */
302     tag = avio_rl32(pb);
303
304     rf64 = tag == MKTAG('R', 'F', '6', '4');
305     if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
306         return -1;
307     avio_rl32(pb); /* file size */
308     tag = avio_rl32(pb);
309     if (tag != MKTAG('W', 'A', 'V', 'E'))
310         return -1;
311
312     if (rf64) {
313         if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
314             return -1;
315         size = avio_rl32(pb);
316         if (size < 16)
317             return -1;
318         avio_rl64(pb); /* RIFF size */
319         data_size = avio_rl64(pb);
320         sample_count = avio_rl64(pb);
321         if (data_size < 0 || sample_count < 0) {
322             av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
323                    "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
324                    data_size, sample_count);
325             return AVERROR_INVALIDDATA;
326         }
327         avio_skip(pb, size - 16); /* skip rest of ds64 chunk */
328     }
329
330
331     for (;;) {
332         if (pb->eof_reached)
333             return -1;
334         size = next_tag(pb, &tag);
335         next_tag_ofs = avio_tell(pb) + size;
336
337         if (tag == MKTAG('f', 'm', 't', ' ')) {
338             /* only parse the first 'fmt ' tag found */
339             if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st) < 0)) {
340                 return ret;
341             } else if (got_fmt)
342                 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
343
344             got_fmt = 1;
345         } else if (tag == MKTAG('d', 'a', 't', 'a')) {
346             if (!got_fmt) {
347                 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'data' tag\n");
348                 return AVERROR_INVALIDDATA;
349             }
350
351             break;
352         }else if (tag == MKTAG('f','a','c','t') && !sample_count){
353             sample_count = avio_rl32(pb);
354         }
355         avio_seek(pb, next_tag_ofs, SEEK_SET);
356     }
357     if (rf64)
358         size = data_size;
359     if (size < 0)
360         return -1;
361     if (!size) {
362         wav->data_end = INT64_MAX;
363     } else
364         wav->data_end= avio_tell(pb) + size;
365
366     if (!sample_count && st->codec->channels && av_get_bits_per_sample(st->codec->codec_id))
367         sample_count = (size<<3) / (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
368     if (sample_count)
369         st->duration = sample_count;
370     return 0;
371 }
372
373 /** Find chunk with w64 GUID by skipping over other chunks
374  * @return the size of the found chunk
375  */
376 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
377 {
378     uint8_t guid[16];
379     int64_t size;
380
381     while (!pb->eof_reached) {
382         avio_read(pb, guid, 16);
383         size = avio_rl64(pb);
384         if (size <= 24)
385             return -1;
386         if (!memcmp(guid, guid1, 16))
387             return size;
388         avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
389     }
390     return -1;
391 }
392
393 static const uint8_t guid_data[16] = { 'd', 'a', 't', 'a',
394     0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
395
396 #define MAX_SIZE 4096
397
398 static int wav_read_packet(AVFormatContext *s,
399                            AVPacket *pkt)
400 {
401     int ret, size;
402     int64_t left;
403     AVStream *st;
404     WAVContext *wav = s->priv_data;
405
406     st = s->streams[0];
407
408     left = wav->data_end - avio_tell(s->pb);
409     if (left <= 0){
410         if (CONFIG_W64_DEMUXER && wav->w64)
411             left = find_guid(s->pb, guid_data) - 24;
412         else
413             left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
414         if (left < 0)
415             return AVERROR_EOF;
416         wav->data_end= avio_tell(s->pb) + left;
417     }
418
419     size = MAX_SIZE;
420     if (st->codec->block_align > 1) {
421         if (size < st->codec->block_align)
422             size = st->codec->block_align;
423         size = (size / st->codec->block_align) * st->codec->block_align;
424     }
425     size = FFMIN(size, left);
426     ret  = av_get_packet(s->pb, pkt, size);
427     if (ret < 0)
428         return ret;
429     pkt->stream_index = 0;
430
431     return ret;
432 }
433
434 static int wav_read_seek(AVFormatContext *s,
435                          int stream_index, int64_t timestamp, int flags)
436 {
437     AVStream *st;
438
439     st = s->streams[0];
440     switch (st->codec->codec_id) {
441     case CODEC_ID_MP2:
442     case CODEC_ID_MP3:
443     case CODEC_ID_AC3:
444     case CODEC_ID_DTS:
445         /* use generic seeking with dynamically generated indexes */
446         return -1;
447     default:
448         break;
449     }
450     return pcm_read_seek(s, stream_index, timestamp, flags);
451 }
452
453 AVInputFormat ff_wav_demuxer = {
454     "wav",
455     NULL_IF_CONFIG_SMALL("WAV format"),
456     sizeof(WAVContext),
457     wav_probe,
458     wav_read_header,
459     wav_read_packet,
460     NULL,
461     wav_read_seek,
462     .flags= AVFMT_GENERIC_INDEX,
463     .codec_tag= (const AVCodecTag* const []){ff_codec_wav_tags, 0},
464 };
465 #endif /* CONFIG_WAV_DEMUXER */
466
467
468 #if CONFIG_W64_DEMUXER
469 static const uint8_t guid_riff[16] = { 'r', 'i', 'f', 'f',
470     0x2E, 0x91, 0xCF, 0x11, 0xA5, 0xD6, 0x28, 0xDB, 0x04, 0xC1, 0x00, 0x00 };
471
472 static const uint8_t guid_wave[16] = { 'w', 'a', 'v', 'e',
473     0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
474
475 static const uint8_t guid_fmt [16] = { 'f', 'm', 't', ' ',
476     0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
477
478 static int w64_probe(AVProbeData *p)
479 {
480     if (p->buf_size <= 40)
481         return 0;
482     if (!memcmp(p->buf,      guid_riff, 16) &&
483         !memcmp(p->buf + 24, guid_wave, 16))
484         return AVPROBE_SCORE_MAX;
485     else
486         return 0;
487 }
488
489 static int w64_read_header(AVFormatContext *s, AVFormatParameters *ap)
490 {
491     int64_t size;
492     AVIOContext *pb  = s->pb;
493     WAVContext    *wav = s->priv_data;
494     AVStream *st;
495     uint8_t guid[16];
496     int ret;
497
498     avio_read(pb, guid, 16);
499     if (memcmp(guid, guid_riff, 16))
500         return -1;
501
502     if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8) /* riff + wave + fmt + sizes */
503         return -1;
504
505     avio_read(pb, guid, 16);
506     if (memcmp(guid, guid_wave, 16)) {
507         av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
508         return -1;
509     }
510
511     size = find_guid(pb, guid_fmt);
512     if (size < 0) {
513         av_log(s, AV_LOG_ERROR, "could not find fmt guid\n");
514         return -1;
515     }
516
517     st = av_new_stream(s, 0);
518     if (!st)
519         return AVERROR(ENOMEM);
520
521     /* subtract chunk header size - normal wav file doesn't count it */
522     ret = ff_get_wav_header(pb, st->codec, size - 24);
523     if (ret < 0)
524         return ret;
525     avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
526
527     st->need_parsing = AVSTREAM_PARSE_FULL;
528
529     av_set_pts_info(st, 64, 1, st->codec->sample_rate);
530
531     size = find_guid(pb, guid_data);
532     if (size < 0) {
533         av_log(s, AV_LOG_ERROR, "could not find data guid\n");
534         return -1;
535     }
536     wav->data_end = avio_tell(pb) + size - 24;
537     wav->w64      = 1;
538
539     return 0;
540 }
541
542 AVInputFormat ff_w64_demuxer = {
543     "w64",
544     NULL_IF_CONFIG_SMALL("Sony Wave64 format"),
545     sizeof(WAVContext),
546     w64_probe,
547     w64_read_header,
548     wav_read_packet,
549     NULL,
550     wav_read_seek,
551     .flags = AVFMT_GENERIC_INDEX,
552     .codec_tag = (const AVCodecTag* const []){ff_codec_wav_tags, 0},
553 };
554 #endif /* CONFIG_W64_DEMUXER */