]> git.sesse.net Git - ffmpeg/blob - libavformat/wav.c
lavf: block special characters in dump metadata
[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
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 {
40     const AVClass *class;
41     int64_t data;
42     int64_t data_end;
43     int64_t minpts;
44     int64_t maxpts;
45     int last_duration;
46     int w64;
47     int write_bext;
48     int64_t smv_data_ofs;
49     int smv_block_size;
50     int smv_frames_per_jpeg;
51     int smv_block;
52     int smv_last_stream;
53     int smv_eof;
54     int audio_eof;
55     int ignore_length;
56 } WAVContext;
57
58 #if CONFIG_WAV_MUXER
59 static inline void bwf_write_bext_string(AVFormatContext *s, const char *key, int maxlen)
60 {
61     AVDictionaryEntry *tag;
62     int len = 0;
63
64     if (tag = av_dict_get(s->metadata, key, NULL, 0)) {
65         len = strlen(tag->value);
66         len = FFMIN(len, maxlen);
67         avio_write(s->pb, tag->value, len);
68     }
69
70     ffio_fill(s->pb, 0, maxlen - len);
71 }
72
73 static void bwf_write_bext_chunk(AVFormatContext *s)
74 {
75     AVDictionaryEntry *tmp_tag;
76     uint64_t time_reference = 0;
77     int64_t bext = ff_start_tag(s->pb, "bext");
78
79     bwf_write_bext_string(s, "description", 256);
80     bwf_write_bext_string(s, "originator", 32);
81     bwf_write_bext_string(s, "originator_reference", 32);
82     bwf_write_bext_string(s, "origination_date", 10);
83     bwf_write_bext_string(s, "origination_time", 8);
84
85     if (tmp_tag = av_dict_get(s->metadata, "time_reference", NULL, 0))
86         time_reference = strtoll(tmp_tag->value, NULL, 10);
87     avio_wl64(s->pb, time_reference);
88     avio_wl16(s->pb, 1);  // set version to 1
89
90     if (tmp_tag = av_dict_get(s->metadata, "umid", NULL, 0)) {
91         unsigned char umidpart_str[17] = {0};
92         int i;
93         uint64_t umidpart;
94         int len = strlen(tmp_tag->value+2);
95
96         for (i = 0; i < len/16; i++) {
97             memcpy(umidpart_str, tmp_tag->value + 2 + (i*16), 16);
98             umidpart = strtoll(umidpart_str, NULL, 16);
99             avio_wb64(s->pb, umidpart);
100         }
101         ffio_fill(s->pb, 0, 64 - i*8);
102     } else
103         ffio_fill(s->pb, 0, 64); // zero UMID
104
105     ffio_fill(s->pb, 0, 190); // Reserved
106
107     if (tmp_tag = av_dict_get(s->metadata, "coding_history", NULL, 0))
108         avio_put_str(s->pb, tmp_tag->value);
109
110     ff_end_tag(s->pb, bext);
111 }
112
113 static int wav_write_header(AVFormatContext *s)
114 {
115     WAVContext *wav = s->priv_data;
116     AVIOContext *pb = s->pb;
117     int64_t fmt, fact;
118
119     ffio_wfourcc(pb, "RIFF");
120     avio_wl32(pb, 0); /* file length */
121     ffio_wfourcc(pb, "WAVE");
122
123     /* format header */
124     fmt = ff_start_tag(pb, "fmt ");
125     if (ff_put_wav_header(pb, s->streams[0]->codec) < 0) {
126         av_log(s, AV_LOG_ERROR, "%s codec not supported in WAVE format\n",
127                s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");
128         return -1;
129     }
130     ff_end_tag(pb, fmt);
131
132     if (s->streams[0]->codec->codec_tag != 0x01 /* hence for all other than PCM */
133         && s->pb->seekable) {
134         fact = ff_start_tag(pb, "fact");
135         avio_wl32(pb, 0);
136         ff_end_tag(pb, fact);
137     }
138
139     if (wav->write_bext)
140         bwf_write_bext_chunk(s);
141
142     avpriv_set_pts_info(s->streams[0], 64, 1, s->streams[0]->codec->sample_rate);
143     wav->maxpts = wav->last_duration = 0;
144     wav->minpts = INT64_MAX;
145
146     /* data header */
147     wav->data = ff_start_tag(pb, "data");
148
149     avio_flush(pb);
150
151     return 0;
152 }
153
154 static int wav_write_packet(AVFormatContext *s, AVPacket *pkt)
155 {
156     AVIOContext *pb  = s->pb;
157     WAVContext    *wav = s->priv_data;
158     avio_write(pb, pkt->data, pkt->size);
159     if(pkt->pts != AV_NOPTS_VALUE) {
160         wav->minpts        = FFMIN(wav->minpts, pkt->pts);
161         wav->maxpts        = FFMAX(wav->maxpts, pkt->pts);
162         wav->last_duration = pkt->duration;
163     } else
164         av_log(s, AV_LOG_ERROR, "wav_write_packet: NOPTS\n");
165     return 0;
166 }
167
168 static int wav_write_trailer(AVFormatContext *s)
169 {
170     AVIOContext *pb  = s->pb;
171     WAVContext    *wav = s->priv_data;
172     int64_t file_size;
173
174     avio_flush(pb);
175
176     if (s->pb->seekable) {
177         ff_end_tag(pb, wav->data);
178
179         /* update file size */
180         file_size = avio_tell(pb);
181         avio_seek(pb, 4, SEEK_SET);
182         avio_wl32(pb, (uint32_t)(file_size - 8));
183         avio_seek(pb, file_size, SEEK_SET);
184
185         avio_flush(pb);
186
187         if(s->streams[0]->codec->codec_tag != 0x01) {
188             /* Update num_samps in fact chunk */
189             int number_of_samples;
190             number_of_samples = av_rescale(wav->maxpts - wav->minpts + wav->last_duration,
191                                            s->streams[0]->codec->sample_rate * (int64_t)s->streams[0]->time_base.num,
192                                            s->streams[0]->time_base.den);
193             avio_seek(pb, wav->data-12, SEEK_SET);
194             avio_wl32(pb, number_of_samples);
195             avio_seek(pb, file_size, SEEK_SET);
196             avio_flush(pb);
197         }
198     }
199     return 0;
200 }
201
202 #define OFFSET(x) offsetof(WAVContext, x)
203 #define ENC AV_OPT_FLAG_ENCODING_PARAM
204 static const AVOption options[] = {
205     { "write_bext", "Write BEXT chunk.", OFFSET(write_bext), AV_OPT_TYPE_INT, { 0 }, 0, 1, ENC },
206     { NULL },
207 };
208
209 static const AVClass wav_muxer_class = {
210     .class_name = "WAV muxer",
211     .item_name  = av_default_item_name,
212     .option     = options,
213     .version    = LIBAVUTIL_VERSION_INT,
214 };
215
216 AVOutputFormat ff_wav_muxer = {
217     .name              = "wav",
218     .long_name         = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
219     .mime_type         = "audio/x-wav",
220     .extensions        = "wav",
221     .priv_data_size    = sizeof(WAVContext),
222     .audio_codec       = AV_CODEC_ID_PCM_S16LE,
223     .video_codec       = AV_CODEC_ID_NONE,
224     .write_header      = wav_write_header,
225     .write_packet      = wav_write_packet,
226     .write_trailer     = wav_write_trailer,
227     .flags             = AVFMT_TS_NONSTRICT,
228     .codec_tag         = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
229     .priv_class        = &wav_muxer_class,
230 };
231 #endif /* CONFIG_WAV_MUXER */
232
233
234 #if CONFIG_WAV_DEMUXER
235
236 static int64_t next_tag(AVIOContext *pb, uint32_t *tag)
237 {
238     *tag = avio_rl32(pb);
239     return avio_rl32(pb);
240 }
241
242 /* return the size of the found tag */
243 static int64_t find_tag(AVIOContext *pb, uint32_t tag1)
244 {
245     unsigned int tag;
246     int64_t size;
247
248     for (;;) {
249         if (url_feof(pb))
250             return -1;
251         size = next_tag(pb, &tag);
252         if (tag == tag1)
253             break;
254         avio_skip(pb, size);
255     }
256     return size;
257 }
258
259 static int wav_probe(AVProbeData *p)
260 {
261     /* check file header */
262     if (p->buf_size <= 32)
263         return 0;
264     if (!memcmp(p->buf + 8, "WAVE", 4)) {
265         if (!memcmp(p->buf, "RIFF", 4))
266             /*
267               Since ACT demuxer has standard WAV header at top of it's own,
268               returning score is decreased to avoid probe conflict
269               between ACT and WAV.
270             */
271             return AVPROBE_SCORE_MAX - 1;
272         else if (!memcmp(p->buf,      "RF64", 4) &&
273                  !memcmp(p->buf + 12, "ds64", 4))
274             return AVPROBE_SCORE_MAX;
275     }
276     return 0;
277 }
278
279 static int wav_parse_fmt_tag(AVFormatContext *s, int64_t size, AVStream **st)
280 {
281     AVIOContext *pb = s->pb;
282     int ret;
283
284     /* parse fmt header */
285     *st = avformat_new_stream(s, NULL);
286     if (!*st)
287         return AVERROR(ENOMEM);
288
289     ret = ff_get_wav_header(pb, (*st)->codec, size);
290     if (ret < 0)
291         return ret;
292     (*st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
293
294     avpriv_set_pts_info(*st, 64, 1, (*st)->codec->sample_rate);
295
296     return 0;
297 }
298
299 static inline int wav_parse_bext_string(AVFormatContext *s, const char *key,
300                                         int length)
301 {
302     char temp[257];
303     int ret;
304
305     av_assert0(length <= sizeof(temp));
306     if ((ret = avio_read(s->pb, temp, length)) < 0)
307         return ret;
308
309     temp[length] = 0;
310
311     if (strlen(temp))
312         return av_dict_set(&s->metadata, key, temp, 0);
313
314     return 0;
315 }
316
317 static int wav_parse_bext_tag(AVFormatContext *s, int64_t size)
318 {
319     char temp[131], *coding_history;
320     int ret, x;
321     uint64_t time_reference;
322     int64_t umid_parts[8], umid_mask = 0;
323
324     if ((ret = wav_parse_bext_string(s, "description", 256)) < 0 ||
325         (ret = wav_parse_bext_string(s, "originator", 32)) < 0 ||
326         (ret = wav_parse_bext_string(s, "originator_reference", 32)) < 0 ||
327         (ret = wav_parse_bext_string(s, "origination_date", 10)) < 0 ||
328         (ret = wav_parse_bext_string(s, "origination_time", 8)) < 0)
329         return ret;
330
331     time_reference = avio_rl64(s->pb);
332     snprintf(temp, sizeof(temp), "%"PRIu64, time_reference);
333     if ((ret = av_dict_set(&s->metadata, "time_reference", temp, 0)) < 0)
334         return ret;
335
336     /* check if version is >= 1, in which case an UMID may be present */
337     if (avio_rl16(s->pb) >= 1) {
338         for (x = 0; x < 8; x++)
339             umid_mask |= umid_parts[x] = avio_rb64(s->pb);
340
341         if (umid_mask) {
342             /* the string formatting below is per SMPTE 330M-2004 Annex C */
343             if (umid_parts[4] == 0 && umid_parts[5] == 0 && umid_parts[6] == 0 && umid_parts[7] == 0) {
344                 /* basic UMID */
345                 snprintf(temp, sizeof(temp), "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
346                          umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3]);
347             } else {
348                 /* extended UMID */
349                 snprintf(temp, sizeof(temp), "0x%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64
350                                                "%016"PRIX64"%016"PRIX64"%016"PRIX64"%016"PRIX64,
351                          umid_parts[0], umid_parts[1], umid_parts[2], umid_parts[3],
352                          umid_parts[4], umid_parts[5], umid_parts[6], umid_parts[7]);
353             }
354
355             if ((ret = av_dict_set(&s->metadata, "umid", temp, 0)) < 0)
356                 return ret;
357         }
358
359         avio_skip(s->pb, 190);
360     } else
361         avio_skip(s->pb, 254);
362
363     if (size > 602) {
364         /* CodingHistory present */
365         size -= 602;
366
367         if (!(coding_history = av_malloc(size+1)))
368             return AVERROR(ENOMEM);
369
370         if ((ret = avio_read(s->pb, coding_history, size)) < 0)
371             return ret;
372
373         coding_history[size] = 0;
374         if ((ret = av_dict_set(&s->metadata, "coding_history", coding_history,
375                                AV_DICT_DONT_STRDUP_VAL)) < 0)
376             return ret;
377     }
378
379     return 0;
380 }
381
382 static const AVMetadataConv wav_metadata_conv[] = {
383     {"description",      "comment"      },
384     {"originator",       "encoded_by"   },
385     {"origination_date", "date"         },
386     {"origination_time", "creation_time"},
387     {0},
388 };
389
390 /* wav input */
391 static int wav_read_header(AVFormatContext *s)
392 {
393     int64_t size, av_uninit(data_size);
394     int64_t sample_count=0;
395     int rf64;
396     uint32_t tag, list_type;
397     AVIOContext *pb = s->pb;
398     AVStream *st = NULL;
399     WAVContext *wav = s->priv_data;
400     int ret, got_fmt = 0;
401     int64_t next_tag_ofs, data_ofs = -1;
402
403     wav->smv_data_ofs = -1;
404
405     /* check RIFF header */
406     tag = avio_rl32(pb);
407
408     rf64 = tag == MKTAG('R', 'F', '6', '4');
409     if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))
410         return -1;
411     avio_rl32(pb); /* file size */
412     tag = avio_rl32(pb);
413     if (tag != MKTAG('W', 'A', 'V', 'E'))
414         return -1;
415
416     if (rf64) {
417         if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))
418             return -1;
419         size = avio_rl32(pb);
420         if (size < 24)
421             return -1;
422         avio_rl64(pb); /* RIFF size */
423         data_size = avio_rl64(pb);
424         sample_count = avio_rl64(pb);
425         if (data_size < 0 || sample_count < 0) {
426             av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "
427                    "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",
428                    data_size, sample_count);
429             return AVERROR_INVALIDDATA;
430         }
431         avio_skip(pb, size - 24); /* skip rest of ds64 chunk */
432
433     }
434
435     for (;;) {
436         AVStream *vst;
437         size = next_tag(pb, &tag);
438         next_tag_ofs = avio_tell(pb) + size;
439
440         if (url_feof(pb))
441             break;
442
443         switch (tag) {
444         case MKTAG('f', 'm', 't', ' '):
445             /* only parse the first 'fmt ' tag found */
446             if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st)) < 0) {
447                 return ret;
448             } else if (got_fmt)
449                 av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");
450
451             got_fmt = 1;
452             break;
453         case MKTAG('d', 'a', 't', 'a'):
454             if (!got_fmt) {
455                 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'data' tag\n");
456                 return AVERROR_INVALIDDATA;
457             }
458
459             if (rf64) {
460                 next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;
461             } else {
462                 data_size = size;
463                 next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;
464             }
465
466             data_ofs = avio_tell(pb);
467
468             /* don't look for footer metadata if we can't seek or if we don't
469              * know where the data tag ends
470              */
471             if (!pb->seekable || (!rf64 && !size))
472                 goto break_loop;
473             break;
474         case MKTAG('f','a','c','t'):
475             if (!sample_count)
476                 sample_count = avio_rl32(pb);
477             break;
478         case MKTAG('b','e','x','t'):
479             if ((ret = wav_parse_bext_tag(s, size)) < 0)
480                 return ret;
481             break;
482         case MKTAG('S','M','V','0'):
483             if (!got_fmt) {
484                 av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'SMV0' tag\n");
485                 return AVERROR_INVALIDDATA;
486             }
487             // SMV file, a wav file with video appended.
488             if (size != MKTAG('0','2','0','0')) {
489                 av_log(s, AV_LOG_ERROR, "Unknown SMV version found\n");
490                 goto break_loop;
491             }
492             av_log(s, AV_LOG_DEBUG, "Found SMV data\n");
493             vst = avformat_new_stream(s, NULL);
494             if (!vst)
495                 return AVERROR(ENOMEM);
496             avio_r8(pb);
497             vst->id = 1;
498             vst->codec->codec_type = AVMEDIA_TYPE_VIDEO;
499             vst->codec->codec_id = AV_CODEC_ID_MJPEG;
500             vst->codec->width  = avio_rl24(pb);
501             vst->codec->height = avio_rl24(pb);
502             size = avio_rl24(pb);
503             wav->smv_data_ofs = avio_tell(pb) + (size - 5) * 3;
504             avio_rl24(pb);
505             wav->smv_block_size = avio_rl24(pb);
506             avpriv_set_pts_info(vst, 32, 1, avio_rl24(pb));
507             vst->duration = avio_rl24(pb);
508             avio_rl24(pb);
509             avio_rl24(pb);
510             wav->smv_frames_per_jpeg = avio_rl24(pb);
511             goto break_loop;
512         case MKTAG('L', 'I', 'S', 'T'):
513             list_type = avio_rl32(pb);
514             if (size < 4) {
515                 av_log(s, AV_LOG_ERROR, "too short LIST tag\n");
516                 return AVERROR_INVALIDDATA;
517             }
518             switch (list_type) {
519             case MKTAG('I', 'N', 'F', 'O'):
520                 if ((ret = ff_read_riff_info(s, size - 4)) < 0)
521                     return ret;
522             }
523             break;
524         }
525
526         /* seek to next tag unless we know that we'll run into EOF */
527         if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||
528             avio_seek(pb, next_tag_ofs, SEEK_SET) < 0) {
529             break;
530         }
531     }
532 break_loop:
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 (!sample_count && st->codec->channels && av_get_bits_per_sample(st->codec->codec_id))
541         sample_count = (data_size<<3) / (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));
542     if (sample_count)
543         st->duration = sample_count;
544
545     ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);
546     ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
547
548     return 0;
549 }
550
551 /** Find chunk with w64 GUID by skipping over other chunks
552  * @return the size of the found chunk
553  */
554 static int64_t find_guid(AVIOContext *pb, const uint8_t guid1[16])
555 {
556     uint8_t guid[16];
557     int64_t size;
558
559     while (!url_feof(pb)) {
560         avio_read(pb, guid, 16);
561         size = avio_rl64(pb);
562         if (size <= 24)
563             return -1;
564         if (!memcmp(guid, guid1, 16))
565             return size;
566         avio_skip(pb, FFALIGN(size, INT64_C(8)) - 24);
567     }
568     return -1;
569 }
570
571 static const uint8_t guid_data[16] = { 'd', 'a', 't', 'a',
572     0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
573
574 #define MAX_SIZE 4096
575
576 static int wav_read_packet(AVFormatContext *s,
577                            AVPacket *pkt)
578 {
579     int ret, size;
580     int64_t left;
581     AVStream *st;
582     WAVContext *wav = s->priv_data;
583
584     if (wav->smv_data_ofs > 0) {
585         int64_t audio_dts, video_dts;
586 smv_retry:
587         audio_dts = s->streams[0]->cur_dts;
588         video_dts = s->streams[1]->cur_dts;
589         if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {
590             audio_dts = av_rescale_q(audio_dts, s->streams[0]->time_base, AV_TIME_BASE_Q);
591             video_dts = av_rescale_q(video_dts, s->streams[1]->time_base, AV_TIME_BASE_Q);
592             wav->smv_last_stream = video_dts >= audio_dts;
593         }
594         wav->smv_last_stream = !wav->smv_last_stream;
595         wav->smv_last_stream |= wav->audio_eof;
596         wav->smv_last_stream &= !wav->smv_eof;
597         if (wav->smv_last_stream) {
598             uint64_t old_pos = avio_tell(s->pb);
599             uint64_t new_pos = wav->smv_data_ofs +
600                 wav->smv_block * wav->smv_block_size;
601             if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {
602                 ret = AVERROR_EOF;
603                 goto smv_out;
604             }
605             size = avio_rl24(s->pb);
606             ret  = av_get_packet(s->pb, pkt, size);
607             if (ret < 0)
608                 goto smv_out;
609             pkt->pos -= 3;
610             pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg;
611             wav->smv_block++;
612             pkt->stream_index = 1;
613 smv_out:
614             avio_seek(s->pb, old_pos, SEEK_SET);
615             if (ret == AVERROR_EOF) {
616                 wav->smv_eof = 1;
617                 goto smv_retry;
618             }
619             return ret;
620         }
621     }
622
623     st = s->streams[0];
624
625     left = wav->data_end - avio_tell(s->pb);
626     if (wav->ignore_length)
627         left= INT_MAX;
628     if (left <= 0){
629         if (CONFIG_W64_DEMUXER && wav->w64)
630             left = find_guid(s->pb, guid_data) - 24;
631         else
632             left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));
633         if (left < 0) {
634             wav->audio_eof = 1;
635             if (wav->smv_data_ofs > 0 && !wav->smv_eof)
636                 goto smv_retry;
637             return AVERROR_EOF;
638         }
639         wav->data_end= avio_tell(s->pb) + left;
640     }
641
642     size = MAX_SIZE;
643     if (st->codec->block_align > 1) {
644         if (size < st->codec->block_align)
645             size = st->codec->block_align;
646         size = (size / st->codec->block_align) * st->codec->block_align;
647     }
648     size = FFMIN(size, left);
649     ret  = av_get_packet(s->pb, pkt, size);
650     if (ret < 0)
651         return ret;
652     pkt->stream_index = 0;
653
654     return ret;
655 }
656
657 static int wav_read_seek(AVFormatContext *s,
658                          int stream_index, int64_t timestamp, int flags)
659 {
660     WAVContext *wav = s->priv_data;
661     AVStream *st;
662     wav->smv_eof = 0;
663     wav->audio_eof = 0;
664     if (wav->smv_data_ofs > 0) {
665         int64_t smv_timestamp = timestamp;
666         if (stream_index == 0)
667             smv_timestamp = av_rescale_q(timestamp, s->streams[0]->time_base, s->streams[1]->time_base);
668         else
669             timestamp = av_rescale_q(smv_timestamp, s->streams[1]->time_base, s->streams[0]->time_base);
670         wav->smv_block = smv_timestamp / wav->smv_frames_per_jpeg;
671     }
672
673     st = s->streams[0];
674     switch (st->codec->codec_id) {
675     case AV_CODEC_ID_MP2:
676     case AV_CODEC_ID_MP3:
677     case AV_CODEC_ID_AC3:
678     case AV_CODEC_ID_DTS:
679         /* use generic seeking with dynamically generated indexes */
680         return -1;
681     default:
682         break;
683     }
684     return ff_pcm_read_seek(s, stream_index, timestamp, flags);
685 }
686
687 #define OFFSET(x) offsetof(WAVContext, x)
688 #define DEC AV_OPT_FLAG_DECODING_PARAM
689 static const AVOption demux_options[] = {
690     { "ignore_length", "Ignore length", OFFSET(ignore_length), AV_OPT_TYPE_INT, { 0 }, 0, 1, DEC },
691     { NULL },
692 };
693
694 static const AVClass wav_demuxer_class = {
695     .class_name = "WAV demuxer",
696     .item_name  = av_default_item_name,
697     .option     = demux_options,
698     .version    = LIBAVUTIL_VERSION_INT,
699 };
700 AVInputFormat ff_wav_demuxer = {
701     .name           = "wav",
702     .long_name      = NULL_IF_CONFIG_SMALL("WAV / WAVE (Waveform Audio)"),
703     .priv_data_size = sizeof(WAVContext),
704     .read_probe     = wav_probe,
705     .read_header    = wav_read_header,
706     .read_packet    = wav_read_packet,
707     .read_seek      = wav_read_seek,
708     .flags          = AVFMT_GENERIC_INDEX,
709     .codec_tag      = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
710     .priv_class     = &wav_demuxer_class,
711 };
712 #endif /* CONFIG_WAV_DEMUXER */
713
714
715 #if CONFIG_W64_DEMUXER
716 static const uint8_t guid_riff[16] = { 'r', 'i', 'f', 'f',
717     0x2E, 0x91, 0xCF, 0x11, 0xA5, 0xD6, 0x28, 0xDB, 0x04, 0xC1, 0x00, 0x00 };
718
719 static const uint8_t guid_wave[16] = { 'w', 'a', 'v', 'e',
720     0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
721
722 static const uint8_t guid_fmt [16] = { 'f', 'm', 't', ' ',
723     0xF3, 0xAC, 0xD3, 0x11, 0x8C, 0xD1, 0x00, 0xC0, 0x4F, 0x8E, 0xDB, 0x8A };
724
725 static int w64_probe(AVProbeData *p)
726 {
727     if (p->buf_size <= 40)
728         return 0;
729     if (!memcmp(p->buf,      guid_riff, 16) &&
730         !memcmp(p->buf + 24, guid_wave, 16))
731         return AVPROBE_SCORE_MAX;
732     else
733         return 0;
734 }
735
736 static int w64_read_header(AVFormatContext *s)
737 {
738     int64_t size;
739     AVIOContext *pb  = s->pb;
740     WAVContext    *wav = s->priv_data;
741     AVStream *st;
742     uint8_t guid[16];
743     int ret;
744
745     avio_read(pb, guid, 16);
746     if (memcmp(guid, guid_riff, 16))
747         return -1;
748
749     if (avio_rl64(pb) < 16 + 8 + 16 + 8 + 16 + 8) /* riff + wave + fmt + sizes */
750         return -1;
751
752     avio_read(pb, guid, 16);
753     if (memcmp(guid, guid_wave, 16)) {
754         av_log(s, AV_LOG_ERROR, "could not find wave guid\n");
755         return -1;
756     }
757
758     size = find_guid(pb, guid_fmt);
759     if (size < 0) {
760         av_log(s, AV_LOG_ERROR, "could not find fmt guid\n");
761         return -1;
762     }
763
764     st = avformat_new_stream(s, NULL);
765     if (!st)
766         return AVERROR(ENOMEM);
767
768     /* subtract chunk header size - normal wav file doesn't count it */
769     ret = ff_get_wav_header(pb, st->codec, size - 24);
770     if (ret < 0)
771         return ret;
772     avio_skip(pb, FFALIGN(size, INT64_C(8)) - size);
773
774     st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
775
776     avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
777
778     size = find_guid(pb, guid_data);
779     if (size < 0) {
780         av_log(s, AV_LOG_ERROR, "could not find data guid\n");
781         return -1;
782     }
783     wav->data_end = avio_tell(pb) + size - 24;
784     wav->w64      = 1;
785
786     return 0;
787 }
788
789 AVInputFormat ff_w64_demuxer = {
790     .name           = "w64",
791     .long_name      = NULL_IF_CONFIG_SMALL("Sony Wave64"),
792     .priv_data_size = sizeof(WAVContext),
793     .read_probe     = w64_probe,
794     .read_header    = w64_read_header,
795     .read_packet    = wav_read_packet,
796     .read_seek      = wav_read_seek,
797     .flags          = AVFMT_GENERIC_INDEX,
798     .codec_tag      = (const AVCodecTag* const []){ ff_codec_wav_tags, 0 },
799 };
800 #endif /* CONFIG_W64_DEMUXER */