wavdec.c
Go to the documentation of this file.
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 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/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  int64_t data_end;
41  int w64;
43 
44 
45 #if CONFIG_WAV_DEMUXER
46 
47 static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
48 {
49  *tag = avio_rl32(pb);
50  return avio_rl32(pb);
51 }
52 
53 /* RIFF chunks are always on a even offset. */
54 static int64_t wav_seek_tag(AVIOContext *s, int64_t offset, int whence)
55 {
56  return avio_seek(s, offset + (offset & 1), whence);
57 }
58 
59 /* return the size of the found tag */
60 static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
61 {
62  unsigned int tag;
63  int64_t size;
64 
65  for (;;) {
66  if (pb->eof_reached)
67  return -1;
68  size = next_tag(pb, &tag);
69  if (tag == tag1)
70  break;
71  wav_seek_tag(pb, size, SEEK_CUR);
72  }
73  return size;
74 }
75 
76 static int wav_probe(AVProbeData *p)
77 {
78  /* check file header */
79  if (p->buf_size <= 32)
80  return 0;
81  if (!memcmp(p->buf + 8, "WAVE", 4)) {
82  if (!memcmp(p->buf, "RIFF", 4))
83  /*
84  Since ACT demuxer has standard WAV header at top of it's own,
85  returning score is decreased to avoid probe conflict
86  between ACT and WAV.
87  */
88  return AVPROBE_SCORE_MAX - 1;
89  else if (!memcmp(p->buf, "RF64", 4) &&
90  !memcmp(p->buf + 12, "ds64", 4))
91  return AVPROBE_SCORE_MAX;
92  }
93  return 0;
94 }
95 
96 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
97 {
98  AVIOContext *pb = s->pb;
99  int ret;
100 
101  /* parse fmt header */
102  *st = avformat_new_stream(s, NULL);
103  if (!*st)
104  return AVERROR(ENOMEM);
105 
106  ret = ff_get_wav_header(pb, (*st)->codec, size);
107  if (ret < 0)
108  return ret;
109  (*st)->need_parsing = AVSTREAM_PARSE_FULL;
110 
111  avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
112 
113  return 0;
114 }
115 
116 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
117  int length)
118 {
119  char temp[257];
120  int ret;
121 
122  av_assert0(length <= sizeof(temp));
123  if ((ret = avio_read(s->pb, temp, length)) < 0)
124  return ret;
125 
126  temp[length] = 0;
127 
128  if (strlen(temp))
129  return av_dict_set(&s->metadata, key, temp, 0);
130 
131  return 0;
132 }
133 
134 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
135 {
136  char temp[131], *coding_history;
137  int ret, x;
138  uint64_t time_reference;
139  int64_t umid_parts[8], umid_mask = 0;
140 
141  if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
142  (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
143  (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
144  (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
145  (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
146  return ret;
147 
148  time_reference = avio_rl64(s->pb);
149  snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
150  if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
151  return ret;
152 
153  /* check if version is >= 1, in which case an UMID may be present */
154  if (avio_rl16(s->pb) >= 1) {
155  for (x = 0; x < 8; x++)
156  umid_mask |= umid_parts[x] = avio_rb64(s->pb);
157 
158  if (umid_mask) {
159  /* the string formatting below is per SMPTE 330M-2004 Annex C */
160  if (umid_parts[4] == 0 && umid_parts[5] == 0 && umid_parts[6] == 0 && umid_parts[7] == 0) {
161  /* basic UMID */
162  snprintf(temp, sizeof(temp), "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
163  umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3]);
164  } else {
165  /* extended UMID */
166  snprintf(temp, sizeof(temp), "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
167  "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
168  umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3],
169  umid_parts[4], umid_parts[5], umid_parts[6], umid_parts[7]);
170  }
171 
172  if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
173  return ret;
174  }
175 
176  avio_skip(s->pb, 190);
177  } else
178  avio_skip(s->pb, 254);
179 
180  if (size > 602) {
181  /* CodingHistory present */
182  size -= 602;
183 
184  if (!(coding_history = av_malloc(size+1)))
185  return AVERROR(ENOMEM);
186 
187  if ((ret = avio_read(s->pb, coding_history, size)) < 0)
188  return ret;
189 
190  coding_history[size] = 0;
191  if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
193  return ret;
194  }
195 
196  return 0;
197 }
198 
199 static const AVMetadataConv wav_metadata_conv[] = {
200  {"description", "comment" },
201  {"originator", "encoded_by" },
202  {"origination_date", "date" },
203  {"origination_time", "creation_time"},
204  {0},
205 };
206 
207 /* wav input */
208 static int wav_read_header(AVFormatContext *s)
209 {
210  int64_t size, av_uninit(data_size);
211  int64_t sample_count=0;
212  int rf64;
213  uint32_t tag;
214  AVIOContext *pb = s->pb;
215  AVStream *st = NULL;
216  WAVDemuxContext *wav = s->priv_data;
217  int ret, got_fmt = 0;
218  int64_t next_tag_ofs, data_ofs = -1;
219 
220  /* check RIFF header */
221  tag = avio_rl32(pb);
222 
223  rf64 = tag == MKTAG('R', 'F', '6', '4');
224  if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
225  return -1;
226  avio_rl32(pb); /* file size */
227  tag = avio_rl32(pb);
228  if (tag != MKTAG('W', 'A', 'V', 'E'))
229  return -1;
230 
231  if (rf64) {
232  if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
233  return -1;
234  size = avio_rl32(pb);
235  if (size < 16)
236  return -1;
237  avio_rl64(pb); /* RIFF size */
238  data_size = avio_rl64(pb);
239  sample_count = avio_rl64(pb);
240  if (data_size < 0 || sample_count < 0) {
241  av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
242  "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
243  data_size, sample_count);
244  return AVERROR_INVALIDDATA;
245  }
246  avio_skip(pb, size - 16); /* skip rest of ds64 chunk */
247  }
248 
249  for (;;) {
250  size = next_tag(pb, &tag);
251  next_tag_ofs = avio_tell(pb) + size;
252 
253  if (pb->eof_reached)
254  break;
255 
256  switch (tag) {
257  case MKTAG('f', 'm', 't', ' '):
258  /* only parse the first 'fmt ' tag found */
259  if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st) < 0)) {
260  return ret;
261  } else if (got_fmt)
262  av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
263 
264  got_fmt = 1;
265  break;
266  case MKTAG('d', 'a', 't', 'a'):
267  if (!got_fmt) {
268  av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'data' tag\n");
269  return AVERROR_INVALIDDATA;
270  }
271 
272  if (rf64) {
273  next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
274  } else {
275  data_size = size;
276  next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
277  }
278 
279  data_ofs = avio_tell(pb);
280 
281  /* don't look for footer metadata if we can't seek or if we don't
282  * know where the data tag ends
283  */
284  if (!pb->seekable || (!rf64 && !size))
285  goto break_loop;
286  break;
287  case MKTAG('f','a','c','t'):
288  if (!sample_count)
289  sample_count = avio_rl32(pb);
290  break;
291  case MKTAG('b','e','x','t'):
292  if ((ret = wav_parse_bext_tag(s, size)) < 0)
293  return ret;
294  break;
295  case MKTAG('L', 'I', 'S', 'T'):
296  if (size < 4) {
297  av_log(s, AV_LOG_ERROR, "too short LIST");
298  return AVERROR_INVALIDDATA;
299  }
300  switch (avio_rl32(pb)) {
301  case MKTAG('I', 'N', 'F', 'O'):
302  if ((ret = ff_read_riff_info(s, size - 4)) < 0)
303  return ret;
304  }
305  break;
306  }
307 
308  /* seek to next tag unless we know that we'll run into EOF */
309  if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
310  wav_seek_tag(pb, next_tag_ofs, SEEK_SET) < 0) {
311  break;
312  }
313  }
314 break_loop:
315  if (data_ofs < 0) {
316  av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
317  return AVERROR_INVALIDDATA;
318  }
319 
320  avio_seek(pb, data_ofs, SEEK_SET);
321 
322  if (!sample_count && st->codec->channels && av_get_bits_per_sample(st->codec->codec_id))
323  sample_count = (data_size<<3) / (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
324  if (sample_count)
325  st->duration = sample_count;
326 
327  ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
329 
330  return 0;
331 }
332 
336 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
337 {
338  uint8_t guid[16];
339  int64_t size;
340 
341  while (!pb->eof_reached) {
342  avio_read(pb, guid, 16);
343  size = avio_rl64(pb);
344  if (size <= 24)
345  return -1;
346  if (!memcmp(guid, guid1, 16))
347  return size;
348  avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
349  }
350  return -1;
351 }
352 
353 static const uint8_t guid_data[16] = { 'd', 'a', 't', 'a',
354  0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
355 
356 #define MAX_SIZE 4096
357 
358 static int wav_read_packet(AVFormatContext *s,
359  AVPacket *pkt)
360 {
361  int ret, size;
362  int64_t left;
363  AVStream *st;
364  WAVDemuxContext *wav = s->priv_data;
365 
366  st = s->streams[0];
367 
368  left = wav->data_end - avio_tell(s->pb);
369  if (left <= 0){
370  if (CONFIG_W64_DEMUXER && wav->w64)
371  left = find_guid(s->pb, guid_data) - 24;
372  else
373  left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
374  if (left < 0)
375  return AVERROR_EOF;
376  wav->data_end= avio_tell(s->pb) + left;
377  }
378 
379  size = MAX_SIZE;
380  if (st->codec->block_align > 1) {
381  if (size < st->codec->block_align)
382  size = st->codec->block_align;
383  size = (size / st->codec->block_align) * st->codec->block_align;
384  }
385  size = FFMIN(size, left);
386  ret = av_get_packet(s->pb, pkt, size);
387  if (ret < 0)
388  return ret;
389  pkt->stream_index = 0;
390 
391  return ret;
392 }
393 
394 static int wav_read_seek(AVFormatContext *s,
395  int stream_index, int64_t timestamp, int flags)
396 {
397  AVStream *st;
398 
399  st = s->streams[0];
400  switch (st->codec->codec_id) {
401  case AV_CODEC_ID_MP2:
402  case AV_CODEC_ID_MP3:
403  case AV_CODEC_ID_AC3:
404  case AV_CODEC_ID_DTS:
405  /* use generic seeking with dynamically generated indexes */
406  return -1;
407  default:
408  break;
409  }
410  return ff_pcm_read_seek(s, stream_index, timestamp, flags);
411 }
412 
413 AVInputFormat ff_wav_demuxer = {
414  .name = "wav",
415  .long_name = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
416  .priv_data_size = sizeof(WAVDemuxContext),
417  .read_probe = wav_probe,
418  .read_header = wav_read_header,
419  .read_packet = wav_read_packet,
420  .read_seek = wav_read_seek,
421  .flags = AVFMT_GENERIC_INDEX,
422  .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
423 };
424 #endif /* CONFIG_WAV_DEMUXER */
425 
426 
427 #if CONFIG_W64_DEMUXER
428 static const uint8_t guid_riff[16] = { 'r', 'i', 'f', 'f',
429  0x2E, 0x91, 0xCF, 0x11, 0xA5, 0xD6, 0x28, 0xDB, 0x04, 0xC1, 0x00, 0x00 };
430 
431 static const uint8_t guid_wave[16] = { 'w', 'a', 'v', 'e',
432  0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
433 
434 static const uint8_t guid_fmt [16] = { 'f', 'm', 't', ' ',
435  0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
436 
437 static int w64_probe(AVProbeData *p)
438 {
439  if (p->buf_size <= 40)
440  return 0;
441  if (!memcmp(p->buf, guid_riff, 16) &&
442  !memcmp(p->buf + 24, guid_wave, 16))
443  return AVPROBE_SCORE_MAX;
444  else
445  return 0;
446 }
447 
448 static int w64_read_header(AVFormatContext *s)
449 {
450  int64_t size;
451  AVIOContext *pb = s->pb;
452  WAVDemuxContext *wav = s->priv_data;
453  AVStream *st;
454  uint8_t guid[16];
455  int ret;
456 
457  avio_read(pb, guid, 16);
458  if (memcmp(guid, guid_riff, 16))
459  return -1;
460 
461  if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8) /* riff + wave + fmt + sizes */
462  return -1;
463 
464  avio_read(pb, guid, 16);
465  if (memcmp(guid, guid_wave, 16)) {
466  av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
467  return -1;
468  }
469 
470  size = find_guid(pb, guid_fmt);
471  if (size < 0) {
472  av_log(s, AV_LOG_ERROR, "could not find fmt guid\n");
473  return -1;
474  }
475 
476  st = avformat_new_stream(s, NULL);
477  if (!st)
478  return AVERROR(ENOMEM);
479 
480  /* subtract chunk header size - normal wav file doesn't count it */
481  ret = ff_get_wav_header(pb, st->codec, size - 24);
482  if (ret < 0)
483  return ret;
484  avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
485 
487 
488  avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
489 
490  size = find_guid(pb, guid_data);
491  if (size < 0) {
492  av_log(s, AV_LOG_ERROR, "could not find data guid\n");
493  return -1;
494  }
495  wav->data_end = avio_tell(pb) + size - 24;
496  wav->w64 = 1;
497 
498  return 0;
499 }
500 
501 AVInputFormat ff_w64_demuxer = {
502  .name = "w64",
503  .long_name = NULL_IF_CONFIG_SMALL("Sony Wave64"),
504  .priv_data_size = sizeof(WAVDemuxContext),
505  .read_probe = w64_probe,
506  .read_header = w64_read_header,
507  .read_packet = wav_read_packet,
508  .read_seek = wav_read_seek,
509  .flags = AVFMT_GENERIC_INDEX,
510  .codec_tag = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
511 };
512 #endif /* CONFIG_W64_DEMUXER */
int ff_read_riff_info(AVFormatContext *s, int64_t size)
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:61
Bytestream IO Context.
Definition: avio.h:68
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:241
Buffered I/O operations.
int size
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:3283
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:153
struct WAVDemuxContext WAVDemuxContext
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:186
#define CONFIG_W64_DEMUXER
Definition: config.h:823
#define MAX_SIZE
Definition: vf_unsharp.c:48
int block_align
number of bytes per packet if constant and known or 0 Used by some WAV based audio codecs...
Definition: avcodec.h:2141
Format I/O context.
Definition: avformat.h:828
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
internal metadata API header see avformat.h or the public API!
Public dictionary API.
uint8_t
AVOptions.
enum AVStreamParseType need_parsing
Definition: avformat.h:775
AVStream ** streams
Definition: avformat.h:876
static int flags
Definition: log.c:42
uint32_t tag
Definition: movenc.c:802
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition: utils.c:218
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:642
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:219
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:446
int av_get_bits_per_sample(enum AVCodecID codec_id)
Return codec bits per sample.
Definition: utils.c:1813
AVDictionary * metadata
Definition: avformat.h:972
unsigned int avio_rl32(AVIOContext *s)
Definition: aviobuf.c:546
int ff_get_wav_header(AVIOContext *pb, AVCodecContext *codec, int size)
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:88
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: avcodec.h:348
simple assert() macros that are a bit more flexible than ISO C assert().
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:146
AVStream * avformat_new_stream(AVFormatContext *s, AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2736
const AVCodecTag ff_codec_wav_tags[]
Definition: riff.c:297
return
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:641
int buf_size
Size of buf except extra allocated bytes.
Definition: avformat.h:341
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:340
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:117
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:54
static av_always_inline int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: avio.h:210
internal header for RIFF based (de)muxers do NOT include this in end user applications ...
int ff_pcm_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
Definition: pcm.c:26
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:536
Stream structure.
Definition: avformat.h:622
NULL
Definition: eval.c:52
enum AVCodecID codec_id
Definition: avcodec.h:1350
int sample_rate
samples per second
Definition: avcodec.h:2104
AVIOContext * pb
I/O context.
Definition: avformat.h:861
static int read_packet(AVFormatContext *ctx, AVPacket *pkt)
Definition: libcdio.c:114
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:63
This structure contains the data a format has to probe a file.
Definition: avformat.h:338
const AVMetadataConv ff_riff_info_conv[]
Definition: riff.c:349
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:684
void ff_metadata_conv_ctx(AVFormatContext *ctx, const AVMetadataConv *d_conv, const AVMetadataConv *s_conv)
Definition: metadata.c:59
full parsing and repack
Definition: avformat.h:576
unsigned int avio_rl16(AVIOContext *s)
Definition: aviobuf.c:530
Main libavformat public API header.
int64_t data_end
Definition: wavdec.c:40
int eof_reached
true if eof reached
Definition: avio.h:96
int channels
number of audio channels
Definition: avcodec.h:2105
void * priv_data
Format private data.
Definition: avformat.h:848
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:455
int stream_index
Definition: avcodec.h:917
This structure stores compressed data.
Definition: avcodec.h:898
uint64_t avio_rl64(AVIOContext *s)
Definition: aviobuf.c:554
if(!(ptr_align%ac->ptr_align)&&samples_align >=aligned_len)