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