]> git.sesse.net Git - ffmpeg/blob - libavformat/wavdec.c
avformat: Forward errors where possible
[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 <stdint.h>
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/dict.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/log.h"
32 #include "libavutil/mathematics.h"
33 #include "libavutil/opt.h"
34 #include "avformat.h"
35 #include "avio.h"
36 #include "avio_internal.h"
37 #include "id3v2.h"
38 #include "internal.h"
39 #include "metadata.h"
40 #include "pcm.h"
41 #include "riff.h"
42 #include "w64.h"
43 #include "spdif.h"
44
45 typedef struct WAVDemuxContext {
46     const AVClass *class;
47     int64_t data_end;
48     int w64;
49     int64_t smv_data_ofs;
50     int smv_block_size;
51     int smv_frames_per_jpeg;
52     int smv_block;
53     int smv_last_stream;
54     int smv_eof;
55     int audio_eof;
56     int ignore_length;
57     int spdif;
58     int smv_cur_pt;
59     int smv_given_first;
60     int unaligned; // e.g. if an odd number of bytes ID3 tag was prepended
61     int rifx; // RIFX: integer byte order for parameters is big endian
62 } WAVDemuxContext;
63
64 static void set_spdif(AVFormatContext *s, WAVDemuxContext *wav)
65 {
66     if (CONFIG_SPDIF_DEMUXER && s->streams[0]->codecpar->codec_tag == 1) {
67         enum AVCodecID codec;
68         int len = 1<<16;
69         int ret = ffio_ensure_seekback(s->pb, len);
70
71         if (ret >= 0) {
72             uint8_t *buf = av_malloc(len);
73             if (!buf) {
74                 ret = AVERROR(ENOMEM);
75             } else {
76                 int64_t pos = avio_tell(s->pb);
77                 len = ret = avio_read(s->pb, buf, len);
78                 if (len >= 0) {
79                     ret = ff_spdif_probe(buf, len, &codec);
80                     if (ret > AVPROBE_SCORE_EXTENSION) {
81                         s->streams[0]->codecpar->codec_id = codec;
82                         wav->spdif = 1;
83                     }
84                 }
85                 avio_seek(s->pb, pos, SEEK_SET);
86                 av_free(buf);
87             }
88         }
89
90         if (ret < 0)
91             av_log(s, AV_LOG_WARNING, "Cannot check for SPDIF\n");
92     }
93 }
94
95 #if CONFIG_WAV_DEMUXER
96
97 static int64_t next_tag(AVIOContext *pb, uint32_t *tag, int big_endian)
98 {
99     *tag = avio_rl32(pb);
100     if (!big_endian) {
101         return avio_rl32(pb);
102     } else {
103         return avio_rb32(pb);
104     }
105 }
106
107 /* RIFF chunks are always at even offsets relative to where they start. */
108 static int64_t wav_seek_tag(WAVDemuxContext * wav, AVIOContext *s, int64_t offset, int whence)
109 {
110     offset += offset < INT64_MAX && offset + wav->unaligned & 1;
111
112     return avio_seek(s, offset, whence);
113 }
114
115 /* return the size of the found tag */
116 static int64_t find_tag(WAVDemuxContext * wav, AVIOContext *pb, uint32_t tag1)
117 {
118     unsigned int tag;
119     int64_t size;
120
121     for (;;) {
122         if (avio_feof(pb))
123             return AVERROR_EOF;
124         size = next_tag(pb, &tag, wav->rifx);
125         if (tag == tag1)
126             break;
127         wav_seek_tag(wav, pb, size, SEEK_CUR);
128     }
129     return size;
130 }
131
132 static int wav_probe(const AVProbeData *p)
133 {
134     /* check file header */
135     if (p->buf_size <= 32)
136         return 0;
137     if (!memcmp(p->buf + 8, "WAVE", 4)) {
138         if (!memcmp(p->buf, "RIFF", 4) || !memcmp(p->buf, "RIFX", 4))
139             /* Since the ACT demuxer has a standard WAV header at the top of
140              * its own, the returned score is decreased to avoid a probe
141              * conflict between ACT and WAV. */
142             return AVPROBE_SCORE_MAX - 1;
143         else if (!memcmp(p->buf,      "RF64", 4) &&
144                  !memcmp(p->buf + 12, "ds64", 4))
145             return AVPROBE_SCORE_MAX;
146     }
147     return 0;
148 }
149
150 static void handle_stream_probing(AVStream *st)
151 {
152     if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) {
153         st->request_probe = AVPROBE_SCORE_EXTENSION;
154         st->probe_packets = FFMIN(st->probe_packets, 32);
155     }
156 }
157
158 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
159 {
160     AVIOContext *pb = s->pb;
161     WAVDemuxContext *wav = s->priv_data;
162     int ret;
163
164     /* parse fmt header */
165     *st = avformat_new_stream(s, NULL);
166     if (!*st)
167         return AVERROR(ENOMEM);
168
169     ret = ff_get_wav_header(s, pb, (*st)->codecpar, size, wav->rifx);
170     if (ret < 0)
171         return ret;
172     handle_stream_probing(*st);
173
174     (*st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
175
176     avpriv_set_pts_info(*st, 64, 1, (*st)->codecpar->sample_rate);
177
178     return 0;
179 }
180
181 static int wav_parse_xma2_tag(AVFormatContext *s, int64_t size, AVStream **st)
182 {
183     AVIOContext *pb = s->pb;
184     int version, num_streams, i, channels = 0, ret;
185
186     if (size < 36)
187         return AVERROR_INVALIDDATA;
188
189     *st = avformat_new_stream(s, NULL);
190     if (!*st)
191         return AVERROR(ENOMEM);
192
193     (*st)->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
194     (*st)->codecpar->codec_id   = AV_CODEC_ID_XMA2;
195     (*st)->need_parsing         = AVSTREAM_PARSE_FULL_RAW;
196
197     version = avio_r8(pb);
198     if (version != 3 && version != 4)
199         return AVERROR_INVALIDDATA;
200     num_streams = avio_r8(pb);
201     if (size != (32 + ((version==3)?0:8) + 4*num_streams))
202         return AVERROR_INVALIDDATA;
203     avio_skip(pb, 10);
204     (*st)->codecpar->sample_rate = avio_rb32(pb);
205     if (version == 4)
206         avio_skip(pb, 8);
207     avio_skip(pb, 4);
208     (*st)->duration = avio_rb32(pb);
209     avio_skip(pb, 8);
210
211     for (i = 0; i < num_streams; i++) {
212         channels += avio_r8(pb);
213         avio_skip(pb, 3);
214     }
215     (*st)->codecpar->channels = channels;
216
217     if ((*st)->codecpar->channels <= 0 || (*st)->codecpar->sample_rate <= 0)
218         return AVERROR_INVALIDDATA;
219
220     avpriv_set_pts_info(*st, 64, 1, (*st)->codecpar->sample_rate);
221
222     avio_seek(pb, -size, SEEK_CUR);
223     av_freep(&(*st)->codecpar->extradata);
224     if ((ret = ff_get_extradata(s, (*st)->codecpar, pb, size)) < 0)
225         return ret;
226
227     return 0;
228 }
229
230 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
231                                         int length)
232 {
233     char temp[257];
234     int ret;
235
236     av_assert0(length < sizeof(temp));
237     if ((ret = avio_read(s->pb, temp, length)) != length)
238         return ret < 0 ? ret : AVERROR_INVALIDDATA;
239
240     temp[length] = 0;
241
242     if (strlen(temp))
243         return av_dict_set(&s->metadata, key, temp, 0);
244
245     return 0;
246 }
247
248 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
249 {
250     char temp[131], *coding_history;
251     int ret, x;
252     uint64_t time_reference;
253     int64_t umid_parts[8], umid_mask = 0;
254
255     if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
256         (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
257         (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
258         (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
259         (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
260         return ret;
261
262     time_reference = avio_rl64(s->pb);
263     snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
264     if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
265         return ret;
266
267     /* check if version is >= 1, in which case an UMID may be present */
268     if (avio_rl16(s->pb) >= 1) {
269         for (x = 0; x < 8; x++)
270             umid_mask |= umid_parts[x] = avio_rb64(s->pb);
271
272         if (umid_mask) {
273             /* the string formatting below is per SMPTE 330M-2004 Annex C */
274             if (umid_parts[4] == 0 && umid_parts[5] == 0 &&
275                 umid_parts[6] == 0 && umid_parts[7] == 0) {
276                 /* basic UMID */
277                 snprintf(temp, sizeof(temp),
278                          "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
279                          umid_parts[0], umid_parts[1],
280                          umid_parts[2], umid_parts[3]);
281             } else {
282                 /* extended UMID */
283                 snprintf(temp, sizeof(temp),
284                          "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
285                          "%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
286                          umid_parts[0], umid_parts[1],
287                          umid_parts[2], umid_parts[3],
288                          umid_parts[4], umid_parts[5],
289                          umid_parts[6], umid_parts[7]);
290             }
291
292             if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
293                 return ret;
294         }
295
296         avio_skip(s->pb, 190);
297     } else
298         avio_skip(s->pb, 254);
299
300     if (size > 602) {
301         /* CodingHistory present */
302         size -= 602;
303
304         if (!(coding_history = av_malloc(size + 1)))
305             return AVERROR(ENOMEM);
306
307         if ((ret = avio_read(s->pb, coding_history, size)) != size) {
308             av_free(coding_history);
309             return ret < 0 ? ret : AVERROR_INVALIDDATA;
310         }
311
312         coding_history[size] = 0;
313         if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
314                                AV_DICT_DONT_STRDUP_VAL)) < 0)
315             return ret;
316     }
317
318     return 0;
319 }
320
321 static const AVMetadataConv wav_metadata_conv[] = {
322     { "description",      "comment"       },
323     { "originator",       "encoded_by"    },
324     { "origination_date", "date"          },
325     { "origination_time", "creation_time" },
326     { 0 },
327 };
328
329 /* wav input */
330 static int wav_read_header(AVFormatContext *s)
331 {
332     int64_t size, av_uninit(data_size);
333     int64_t sample_count = 0;
334     int rf64 = 0;
335     uint32_t tag;
336     AVIOContext *pb      = s->pb;
337     AVStream *st         = NULL;
338     WAVDemuxContext *wav = s->priv_data;
339     int ret, got_fmt = 0, got_xma2 = 0;
340     int64_t next_tag_ofs, data_ofs = -1;
341
342     wav->unaligned = avio_tell(s->pb) & 1;
343
344     wav->smv_data_ofs = -1;
345
346     /* read chunk ID */
347     tag = avio_rl32(pb);
348     switch (tag) {
349     case MKTAG('R', 'I', 'F', 'F'):
350         break;
351     case MKTAG('R', 'I', 'F', 'X'):
352         wav->rifx = 1;
353         break;
354     case MKTAG('R', 'F', '6', '4'):
355         rf64 = 1;
356         break;
357     default:
358         av_log(s, AV_LOG_ERROR, "invalid start code %s in RIFF header\n",
359                av_fourcc2str(tag));
360         return AVERROR_INVALIDDATA;
361     }
362
363     /* read chunk size */
364     avio_rl32(pb);
365
366     /* read format */
367     if (avio_rl32(pb) != MKTAG('W', 'A', 'V', 'E')) {
368         av_log(s, AV_LOG_ERROR, "invalid format in RIFF header\n");
369         return AVERROR_INVALIDDATA;
370     }
371
372     if (rf64) {
373         if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
374             return AVERROR_INVALIDDATA;
375         size = avio_rl32(pb);
376         if (size < 24)
377             return AVERROR_INVALIDDATA;
378         avio_rl64(pb); /* RIFF size */
379
380         data_size    = avio_rl64(pb);
381         sample_count = avio_rl64(pb);
382
383         if (data_size < 0 || sample_count < 0) {
384             av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
385                    "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
386                    data_size, sample_count);
387             return AVERROR_INVALIDDATA;
388         }
389         avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
390
391     }
392
393     for (;;) {
394         AVStream *vst;
395         size         = next_tag(pb, &tag, wav->rifx);
396         next_tag_ofs = avio_tell(pb) + size;
397
398         if (avio_feof(pb))
399             break;
400
401         switch (tag) {
402         case MKTAG('f', 'm', 't', ' '):
403             /* only parse the first 'fmt ' tag found */
404             if (!got_xma2 && !got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
405                 return ret;
406             } else if (got_fmt)
407                 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
408
409             got_fmt = 1;
410             break;
411         case MKTAG('X', 'M', 'A', '2'):
412             /* only parse the first 'XMA2' tag found */
413             if (!got_fmt && !got_xma2 && (ret = wav_parse_xma2_tag(s, size, &st)) < 0) {
414                 return ret;
415             } else if (got_xma2)
416                 av_log(s, AV_LOG_WARNING, "found more than one 'XMA2' tag\n");
417
418             got_xma2 = 1;
419             break;
420         case MKTAG('d', 'a', 't', 'a'):
421             if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) && !got_fmt && !got_xma2) {
422                 av_log(s, AV_LOG_ERROR,
423                        "found no 'fmt ' tag before the 'data' tag\n");
424                 return AVERROR_INVALIDDATA;
425             }
426
427             if (rf64) {
428                 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
429             } else if (size != 0xFFFFFFFF) {
430                 data_size    = size;
431                 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
432             } else {
433                 av_log(s, AV_LOG_WARNING, "Ignoring maximum wav data size, "
434                        "file may be invalid\n");
435                 data_size    = 0;
436                 next_tag_ofs = wav->data_end = INT64_MAX;
437             }
438
439             data_ofs = avio_tell(pb);
440
441             /* don't look for footer metadata if we can't seek or if we don't
442              * know where the data tag ends
443              */
444             if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || (!rf64 && !size))
445                 goto break_loop;
446             break;
447         case MKTAG('f', 'a', 'c', 't'):
448             if (!sample_count)
449                 sample_count = (!wav->rifx ? avio_rl32(pb) : avio_rb32(pb));
450             break;
451         case MKTAG('b', 'e', 'x', 't'):
452             if ((ret = wav_parse_bext_tag(s, size)) < 0)
453                 return ret;
454             break;
455         case MKTAG('S','M','V','0'):
456             if (!got_fmt) {
457                 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");
458                 return AVERROR_INVALIDDATA;
459             }
460             // SMV file, a wav file with video appended.
461             if (size != MKTAG('0','2','0','0')) {
462                 av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
463                 goto break_loop;
464             }
465             av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
466             wav->smv_given_first = 0;
467             vst = avformat_new_stream(s, NULL);
468             if (!vst)
469                 return AVERROR(ENOMEM);
470             avio_r8(pb);
471             vst->id = 1;
472             vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
473             vst->codecpar->codec_id = AV_CODEC_ID_SMVJPEG;
474             vst->codecpar->width  = avio_rl24(pb);
475             vst->codecpar->height = avio_rl24(pb);
476             if ((ret = ff_alloc_extradata(vst->codecpar, 4)) < 0) {
477                 av_log(s, AV_LOG_ERROR, "Could not allocate extradata.\n");
478                 return ret;
479             }
480             size = avio_rl24(pb);
481             wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
482             avio_rl24(pb);
483             wav->smv_block_size = avio_rl24(pb);
484             avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
485             vst->duration = avio_rl24(pb);
486             avio_rl24(pb);
487             avio_rl24(pb);
488             wav->smv_frames_per_jpeg = avio_rl24(pb);
489             if (wav->smv_frames_per_jpeg > 65536) {
490                 av_log(s, AV_LOG_ERROR, "too many frames per jpeg\n");
491                 return AVERROR_INVALIDDATA;
492             }
493             AV_WL32(vst->codecpar->extradata, wav->smv_frames_per_jpeg);
494             wav->smv_cur_pt = 0;
495             goto break_loop;
496         case MKTAG('L', 'I', 'S', 'T'):
497             if (size < 4) {
498                 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
499                 return AVERROR_INVALIDDATA;
500             }
501             switch (avio_rl32(pb)) {
502             case MKTAG('I', 'N', 'F', 'O'):
503                 ff_read_riff_info(s, size - 4);
504             }
505             break;
506         case MKTAG('I', 'D', '3', ' '):
507         case MKTAG('i', 'd', '3', ' '): {
508             ID3v2ExtraMeta *id3v2_extra_meta = NULL;
509             ff_id3v2_read_dict(pb, &s->internal->id3v2_meta, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);
510             if (id3v2_extra_meta) {
511                 ff_id3v2_parse_apic(s, &id3v2_extra_meta);
512                 ff_id3v2_parse_chapters(s, &id3v2_extra_meta);
513                 ff_id3v2_parse_priv(s, &id3v2_extra_meta);
514             }
515             ff_id3v2_free_extra_meta(&id3v2_extra_meta);
516             }
517             break;
518         }
519
520         /* seek to next tag unless we know that we'll run into EOF */
521         if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
522             wav_seek_tag(wav, pb, next_tag_ofs, SEEK_SET) < 0) {
523             break;
524         }
525     }
526
527 break_loop:
528     if (!got_fmt && !got_xma2) {
529         av_log(s, AV_LOG_ERROR, "no 'fmt ' or 'XMA2' tag found\n");
530         return AVERROR_INVALIDDATA;
531     }
532
533     if (data_ofs < 0) {
534         av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");
535         return AVERROR_INVALIDDATA;
536     }
537
538     avio_seek(pb, data_ofs, SEEK_SET);
539
540     if (data_size > (INT64_MAX>>3)) {
541         av_log(s, AV_LOG_WARNING, "Data size %"PRId64" is too large\n", data_size);
542         data_size = 0;
543     }
544
545     if (   st->codecpar->bit_rate > 0 && data_size > 0
546         && st->codecpar->sample_rate > 0
547         && sample_count > 0 && st->codecpar->channels > 1
548         && sample_count % st->codecpar->channels == 0) {
549         if (fabs(8.0 * data_size * st->codecpar->channels * st->codecpar->sample_rate /
550             sample_count /st->codecpar->bit_rate - 1.0) < 0.3)
551             sample_count /= st->codecpar->channels;
552     }
553
554     if (   data_size > 0 && sample_count && st->codecpar->channels
555         && (data_size << 3) / sample_count / st->codecpar->channels > st->codecpar->bits_per_coded_sample  + 1) {
556         av_log(s, AV_LOG_WARNING, "ignoring wrong sample_count %"PRId64"\n", sample_count);
557         sample_count = 0;
558     }
559
560     /* G.729 hack (for Ticket4577)
561      * FIXME: Come up with cleaner, more general solution */
562     if (st->codecpar->codec_id == AV_CODEC_ID_G729 && sample_count && (data_size << 3) > sample_count) {
563         av_log(s, AV_LOG_WARNING, "ignoring wrong sample_count %"PRId64"\n", sample_count);
564         sample_count = 0;
565     }
566
567     if (!sample_count || av_get_exact_bits_per_sample(st->codecpar->codec_id) > 0)
568         if (   st->codecpar->channels
569             && data_size
570             && av_get_bits_per_sample(st->codecpar->codec_id)
571             && wav->data_end <= avio_size(pb))
572             sample_count = (data_size << 3)
573                                   /
574                 (st->codecpar->channels * (uint64_t)av_get_bits_per_sample(st->codecpar->codec_id));
575
576     if (sample_count)
577         st->duration = sample_count;
578
579     if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S32LE &&
580         st->codecpar->block_align == st->codecpar->channels * 4 &&
581         st->codecpar->bits_per_coded_sample == 32 &&
582         st->codecpar->extradata_size == 2 &&
583         AV_RL16(st->codecpar->extradata) == 1) {
584         st->codecpar->codec_id = AV_CODEC_ID_PCM_F16LE;
585         st->codecpar->bits_per_coded_sample = 16;
586     } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE &&
587                st->codecpar->block_align == st->codecpar->channels * 4 &&
588                st->codecpar->bits_per_coded_sample == 24) {
589         st->codecpar->codec_id = AV_CODEC_ID_PCM_F24LE;
590     } else if (st->codecpar->codec_id == AV_CODEC_ID_XMA1 ||
591                st->codecpar->codec_id == AV_CODEC_ID_XMA2) {
592         st->codecpar->block_align = 2048;
593     } else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS && st->codecpar->channels > 2) {
594         st->codecpar->block_align *= st->codecpar->channels;
595     }
596
597     ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
598     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
599
600     set_spdif(s, wav);
601
602     return 0;
603 }
604
605 /**
606  * Find chunk with w64 GUID by skipping over other chunks.
607  * @return the size of the found chunk
608  */
609 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
610 {
611     uint8_t guid[16];
612     int64_t size;
613
614     while (!avio_feof(pb)) {
615         avio_read(pb, guid, 16);
616         size = avio_rl64(pb);
617         if (size <= 24)
618             return AVERROR_INVALIDDATA;
619         if (!memcmp(guid, guid1, 16))
620             return size;
621         avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
622     }
623     return AVERROR_EOF;
624 }
625
626 #define MAX_SIZE 4096
627
628 static int wav_read_packet(AVFormatContext *s, AVPacket *pkt)
629 {
630     int ret, size;
631     int64_t left;
632     AVStream *st;
633     WAVDemuxContext *wav = s->priv_data;
634
635     if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1)
636         return ff_spdif_read_packet(s, pkt);
637
638     if (wav->smv_data_ofs > 0) {
639         int64_t audio_dts, video_dts;
640 smv_retry:
641         audio_dts = (int32_t)s->streams[0]->cur_dts;
642         video_dts = (int32_t)s->streams[1]->cur_dts;
643
644         if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
645             /*We always return a video frame first to get the pixel format first*/
646             wav->smv_last_stream = wav->smv_given_first ?
647                 av_compare_ts(video_dts, s->streams[1]->time_base,
648                               audio_dts, s->streams[0]->time_base) > 0 : 0;
649             wav->smv_given_first = 1;
650         }
651         wav->smv_last_stream = !wav->smv_last_stream;
652         wav->smv_last_stream |= wav->audio_eof;
653         wav->smv_last_stream &= !wav->smv_eof;
654         if (wav->smv_last_stream) {
655             uint64_t old_pos = avio_tell(s->pb);
656             uint64_t new_pos = wav->smv_data_ofs +
657                 wav->smv_block * wav->smv_block_size;
658             if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
659                 ret = AVERROR_EOF;
660                 goto smv_out;
661             }
662             size = avio_rl24(s->pb);
663             ret  = av_get_packet(s->pb, pkt, size);
664             if (ret < 0)
665                 goto smv_out;
666             pkt->pos -= 3;
667             pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg + wav->smv_cur_pt;
668             wav->smv_cur_pt++;
669             if (wav->smv_frames_per_jpeg > 0)
670                 wav->smv_cur_pt %= wav->smv_frames_per_jpeg;
671             if (!wav->smv_cur_pt)
672                 wav->smv_block++;
673
674             pkt->stream_index = 1;
675 smv_out:
676             avio_seek(s->pb, old_pos, SEEK_SET);
677             if (ret == AVERROR_EOF) {
678                 wav->smv_eof = 1;
679                 goto smv_retry;
680             }
681             return ret;
682         }
683     }
684
685     st = s->streams[0];
686
687     left = wav->data_end - avio_tell(s->pb);
688     if (wav->ignore_length)
689         left = INT_MAX;
690     if (left <= 0) {
691         if (CONFIG_W64_DEMUXER && wav->w64)
692             left = find_guid(s->pb, ff_w64_guid_data) - 24;
693         else
694             left = find_tag(wav, s->pb, MKTAG('d', 'a', 't', 'a'));
695         if (left < 0) {
696             wav->audio_eof = 1;
697             if (wav->smv_data_ofs > 0 && !wav->smv_eof)
698                 goto smv_retry;
699             return AVERROR_EOF;
700         }
701         wav->data_end = avio_tell(s->pb) + left;
702     }
703
704     size = MAX_SIZE;
705     if (st->codecpar->block_align > 1) {
706         if (size < st->codecpar->block_align)
707             size = st->codecpar->block_align;
708         size = (size / st->codecpar->block_align) * st->codecpar->block_align;
709     }
710     size = FFMIN(size, left);
711     ret  = av_get_packet(s->pb, pkt, size);
712     if (ret < 0)
713         return ret;
714     pkt->stream_index = 0;
715
716     return ret;
717 }
718
719 static int wav_read_seek(AVFormatContext *s,
720                          int stream_index, int64_t timestamp, int flags)
721 {
722     WAVDemuxContext *wav = s->priv_data;
723     AVStream *st;
724     wav->smv_eof = 0;
725     wav->audio_eof = 0;
726     if (wav->smv_data_ofs > 0) {
727         int64_t smv_timestamp = timestamp;
728         if (stream_index == 0)
729             smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
730         else
731             timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
732         if (wav->smv_frames_per_jpeg > 0) {
733             wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
734             wav->smv_cur_pt = smv_timestamp % wav->smv_frames_per_jpeg;
735         }
736     }
737
738     st = s->streams[0];
739     switch (st->codecpar->codec_id) {
740     case AV_CODEC_ID_MP2:
741     case AV_CODEC_ID_MP3:
742     case AV_CODEC_ID_AC3:
743     case AV_CODEC_ID_DTS:
744     case AV_CODEC_ID_XMA2:
745         /* use generic seeking with dynamically generated indexes */
746         return -1;
747     default:
748         break;
749     }
750     return ff_pcm_read_seek(s, stream_index, timestamp, flags);
751 }
752
753 #define OFFSET(x) offsetof(WAVDemuxContext, x)
754 #define DEC AV_OPT_FLAG_DECODING_PARAM
755 static const AVOption demux_options[] = {
756     { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, DEC },
757     { NULL },
758 };
759
760 static const AVClass wav_demuxer_class = {
761     .class_name = "WAV demuxer",
762     .item_name  = av_default_item_name,
763     .option     = demux_options,
764     .version    = LIBAVUTIL_VERSION_INT,
765 };
766 AVInputFormat ff_wav_demuxer = {
767     .name           = "wav",
768     .long_name      = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
769     .priv_data_size = sizeof(WAVDemuxContext),
770     .read_probe     = wav_probe,
771     .read_header    = wav_read_header,
772     .read_packet    = wav_read_packet,
773     .read_seek      = wav_read_seek,
774     .flags          = AVFMT_GENERIC_INDEX,
775     .codec_tag      = (const AVCodecTag * const []) { ff_codec_wav_tags,  0 },
776     .priv_class     = &wav_demuxer_class,
777 };
778 #endif /* CONFIG_WAV_DEMUXER */
779
780 #if CONFIG_W64_DEMUXER
781 static int w64_probe(const AVProbeData *p)
782 {
783     if (p->buf_size <= 40)
784         return 0;
785     if (!memcmp(p->buf,      ff_w64_guid_riff, 16) &&
786         !memcmp(p->buf + 24, ff_w64_guid_wave, 16))
787         return AVPROBE_SCORE_MAX;
788     else
789         return 0;
790 }
791
792 static int w64_read_header(AVFormatContext *s)
793 {
794     int64_t size, data_ofs = 0;
795     AVIOContext *pb      = s->pb;
796     WAVDemuxContext *wav = s->priv_data;
797     AVStream *st;
798     uint8_t guid[16];
799     int ret;
800
801     avio_read(pb, guid, 16);
802     if (memcmp(guid, ff_w64_guid_riff, 16))
803         return AVERROR_INVALIDDATA;
804
805     /* riff + wave + fmt + sizes */
806     if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8)
807         return AVERROR_INVALIDDATA;
808
809     avio_read(pb, guid, 16);
810     if (memcmp(guid, ff_w64_guid_wave, 16)) {
811         av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
812         return AVERROR_INVALIDDATA;
813     }
814
815     wav->w64 = 1;
816
817     st = avformat_new_stream(s, NULL);
818     if (!st)
819         return AVERROR(ENOMEM);
820
821     while (!avio_feof(pb)) {
822         if (avio_read(pb, guid, 16) != 16)
823             break;
824         size = avio_rl64(pb);
825         if (size <= 24 || INT64_MAX - size < avio_tell(pb))
826             return AVERROR_INVALIDDATA;
827
828         if (!memcmp(guid, ff_w64_guid_fmt, 16)) {
829             /* subtract chunk header size - normal wav file doesn't count it */
830             ret = ff_get_wav_header(s, pb, st->codecpar, size - 24, 0);
831             if (ret < 0)
832                 return ret;
833             avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
834
835             avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
836         } else if (!memcmp(guid, ff_w64_guid_fact, 16)) {
837             int64_t samples;
838
839             samples = avio_rl64(pb);
840             if (samples > 0)
841                 st->duration = samples;
842             avio_skip(pb, FFALIGN(size, INT64_C(8)) - 32);
843         } else if (!memcmp(guid, ff_w64_guid_data, 16)) {
844             wav->data_end = avio_tell(pb) + size - 24;
845
846             data_ofs = avio_tell(pb);
847             if (!(pb->seekable & AVIO_SEEKABLE_NORMAL))
848                 break;
849
850             avio_skip(pb, size - 24);
851         } else if (!memcmp(guid, ff_w64_guid_summarylist, 16)) {
852             int64_t start, end, cur;
853             uint32_t count, chunk_size, i;
854
855             start = avio_tell(pb);
856             end = start + FFALIGN(size, INT64_C(8)) - 24;
857             count = avio_rl32(pb);
858
859             for (i = 0; i < count; i++) {
860                 char chunk_key[5], *value;
861
862                 if (avio_feof(pb) || (cur = avio_tell(pb)) < 0 || cur > end - 8 /* = tag + size */)
863                     break;
864
865                 chunk_key[4] = 0;
866                 avio_read(pb, chunk_key, 4);
867                 chunk_size = avio_rl32(pb);
868                 if (chunk_size == UINT32_MAX)
869                     return AVERROR_INVALIDDATA;
870
871                 value = av_mallocz(chunk_size + 1);
872                 if (!value)
873                     return AVERROR(ENOMEM);
874
875                 ret = avio_get_str16le(pb, chunk_size, value, chunk_size);
876                 avio_skip(pb, chunk_size - ret);
877
878                 av_dict_set(&s->metadata, chunk_key, value, AV_DICT_DONT_STRDUP_VAL);
879             }
880
881             avio_skip(pb, end - avio_tell(pb));
882         } else {
883             av_log(s, AV_LOG_DEBUG, "unknown guid: "FF_PRI_GUID"\n", FF_ARG_GUID(guid));
884             avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
885         }
886     }
887
888     if (!data_ofs)
889         return AVERROR_EOF;
890
891     ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
892     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
893
894     handle_stream_probing(st);
895     st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
896
897     avio_seek(pb, data_ofs, SEEK_SET);
898
899     set_spdif(s, wav);
900
901     return 0;
902 }
903
904 AVInputFormat ff_w64_demuxer = {
905     .name           = "w64",
906     .long_name      = NULL_IF_CONFIG_SMALL("Sony Wave64"),
907     .priv_data_size = sizeof(WAVDemuxContext),
908     .read_probe     = w64_probe,
909     .read_header    = w64_read_header,
910     .read_packet    = wav_read_packet,
911     .read_seek      = wav_read_seek,
912     .flags          = AVFMT_GENERIC_INDEX,
913     .codec_tag      = (const AVCodecTag * const []) { ff_codec_wav_tags, 0 },
914 };
915 #endif /* CONFIG_W64_DEMUXER */