Imported Upstream version 6.1
[platform/upstream/ffmpeg.git] / libavformat / au.c
1 /*
2  * AU muxer and demuxer
3  * Copyright (c) 2001 Fabrice Bellard
4  *
5  * first version by Francois Revol <revol@free.fr>
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 /*
25  * Reference documents:
26  * http://www.opengroup.org/public/pubs/external/auformat.html
27  * http://www.goice.co.jp/member/mo/formats/au.html
28  */
29
30 #include "config_components.h"
31
32 #include "libavutil/bprint.h"
33 #include "libavutil/intreadwrite.h"
34 #include "avformat.h"
35 #include "internal.h"
36 #include "avio_internal.h"
37 #include "mux.h"
38 #include "pcm.h"
39 #include "libavutil/avassert.h"
40
41 /* if we don't know the size in advance */
42 #define AU_UNKNOWN_SIZE ((uint32_t)(~0))
43
44 static const AVCodecTag codec_au_tags[] = {
45     { AV_CODEC_ID_PCM_MULAW,  1 },
46     { AV_CODEC_ID_PCM_S8,     2 },
47     { AV_CODEC_ID_PCM_S16BE,  3 },
48     { AV_CODEC_ID_PCM_S24BE,  4 },
49     { AV_CODEC_ID_PCM_S32BE,  5 },
50     { AV_CODEC_ID_PCM_F32BE,  6 },
51     { AV_CODEC_ID_PCM_F64BE,  7 },
52     { AV_CODEC_ID_ADPCM_G726LE, 23 },
53     { AV_CODEC_ID_ADPCM_G722,24 },
54     { AV_CODEC_ID_ADPCM_G726LE, 25 },
55     { AV_CODEC_ID_ADPCM_G726LE, 26 },
56     { AV_CODEC_ID_PCM_ALAW,  27 },
57     { AV_CODEC_ID_ADPCM_G726LE, MKBETAG('7','2','6','2') },
58     { AV_CODEC_ID_NONE,       0 },
59 };
60
61 static const AVCodecTag *const au_codec_tags[] = { codec_au_tags, NULL };
62
63 #if CONFIG_AU_DEMUXER
64
65 static int au_probe(const AVProbeData *p)
66 {
67     if (p->buf_size < 24 ||
68         AV_RL32(p->buf) != MKTAG('.', 's', 'n', 'd') ||
69         AV_RN32(p->buf+4)  == 0 ||
70         AV_RN32(p->buf+8)  == 0 ||
71         AV_RN32(p->buf+12) == 0 ||
72         AV_RN32(p->buf+16) == 0 ||
73         AV_RN32(p->buf+20) == 0)
74         return 0;
75     return AVPROBE_SCORE_MAX;
76 }
77
78 static int au_read_annotation(AVFormatContext *s, int size)
79 {
80     static const char keys[][7] = {
81         "title",
82         "artist",
83         "album",
84         "track",
85         "genre",
86     };
87     AVIOContext *pb = s->pb;
88     enum { PARSE_KEY, PARSE_VALUE, PARSE_FINISHED } state = PARSE_KEY;
89     char c;
90     AVBPrint bprint;
91     char * key = NULL;
92     char * value = NULL;
93     int ret, i;
94
95     av_bprint_init(&bprint, 64, AV_BPRINT_SIZE_UNLIMITED);
96
97     while (size-- > 0) {
98         if (avio_feof(pb)) {
99             av_bprint_finalize(&bprint, NULL);
100             av_freep(&key);
101             return AVERROR_EOF;
102         }
103         c = avio_r8(pb);
104         switch(state) {
105         case PARSE_KEY:
106             if (c == '\0') {
107                 state = PARSE_FINISHED;
108             } else if (c == '=') {
109                 ret = av_bprint_finalize(&bprint, &key);
110                 if (ret < 0)
111                     return ret;
112                 av_bprint_init(&bprint, 64, AV_BPRINT_SIZE_UNLIMITED);
113                 state = PARSE_VALUE;
114             } else {
115                 av_bprint_chars(&bprint, c, 1);
116             }
117             break;
118         case PARSE_VALUE:
119             if (c == '\0' || c == '\n') {
120                 if (av_bprint_finalize(&bprint, &value) != 0) {
121                     av_log(s, AV_LOG_ERROR, "Memory error while parsing AU metadata.\n");
122                 } else {
123                     av_bprint_init(&bprint, 64, AV_BPRINT_SIZE_UNLIMITED);
124                     for (i = 0; i < FF_ARRAY_ELEMS(keys); i++) {
125                         if (av_strcasecmp(keys[i], key) == 0) {
126                             av_dict_set(&(s->metadata), keys[i], value, AV_DICT_DONT_STRDUP_VAL);
127                             value = NULL;
128                             break;
129                         }
130                     }
131                 }
132                 av_freep(&key);
133                 av_freep(&value);
134                 state = (c == '\0') ? PARSE_FINISHED : PARSE_KEY;
135             } else {
136                 av_bprint_chars(&bprint, c, 1);
137             }
138             break;
139         case PARSE_FINISHED:
140             break;
141         default:
142             /* should never happen */
143             av_assert0(0);
144         }
145     }
146     av_bprint_finalize(&bprint, NULL);
147     av_freep(&key);
148     return 0;
149 }
150
151 #define BLOCK_SIZE 1024
152
153 static int au_read_header(AVFormatContext *s)
154 {
155     int size, data_size = 0;
156     unsigned int tag;
157     AVIOContext *pb = s->pb;
158     unsigned int id, channels, rate;
159     int bps, ba = 0;
160     enum AVCodecID codec;
161     AVStream *st;
162     int ret;
163
164     tag = avio_rl32(pb);
165     if (tag != MKTAG('.', 's', 'n', 'd'))
166         return AVERROR_INVALIDDATA;
167     size = avio_rb32(pb); /* header size */
168     data_size = avio_rb32(pb); /* data size in bytes */
169
170     if (data_size < 0 && data_size != AU_UNKNOWN_SIZE) {
171         av_log(s, AV_LOG_ERROR, "Invalid negative data size '%d' found\n", data_size);
172         return AVERROR_INVALIDDATA;
173     }
174
175     id       = avio_rb32(pb);
176     rate     = avio_rb32(pb);
177     channels = avio_rb32(pb);
178
179     if (size > 24) {
180         /* parse annotation field to get metadata */
181         ret = au_read_annotation(s, size - 24);
182         if (ret < 0)
183             return ret;
184     }
185
186     codec = ff_codec_get_id(codec_au_tags, id);
187
188     if (codec == AV_CODEC_ID_NONE) {
189         avpriv_request_sample(s, "unknown or unsupported codec tag: %u", id);
190         return AVERROR_PATCHWELCOME;
191     }
192
193     bps = av_get_bits_per_sample(codec);
194     if (codec == AV_CODEC_ID_ADPCM_G726LE) {
195         if (id == MKBETAG('7','2','6','2')) {
196             bps = 2;
197         } else {
198             const uint8_t bpcss[] = {4, 0, 3, 5};
199             av_assert0(id >= 23 && id < 23 + 4);
200             ba = bpcss[id - 23];
201             bps = bpcss[id - 23];
202         }
203     } else if (!bps) {
204         avpriv_request_sample(s, "Unknown bits per sample");
205         return AVERROR_PATCHWELCOME;
206     }
207
208     if (channels == 0 || channels >= INT_MAX / (BLOCK_SIZE * bps >> 3)) {
209         av_log(s, AV_LOG_ERROR, "Invalid number of channels %u\n", channels);
210         return AVERROR_INVALIDDATA;
211     }
212
213     if (rate == 0 || rate > INT_MAX) {
214         av_log(s, AV_LOG_ERROR, "Invalid sample rate: %u\n", rate);
215         return AVERROR_INVALIDDATA;
216     }
217
218     st = avformat_new_stream(s, NULL);
219     if (!st)
220         return AVERROR(ENOMEM);
221     st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;
222     st->codecpar->codec_tag   = id;
223     st->codecpar->codec_id    = codec;
224     st->codecpar->ch_layout.nb_channels = channels;
225     st->codecpar->sample_rate = rate;
226     st->codecpar->bits_per_coded_sample = bps;
227     st->codecpar->bit_rate    = channels * rate * bps;
228     st->codecpar->block_align = ba ? ba : FFMAX(bps * channels / 8, 1);
229     if (data_size != AU_UNKNOWN_SIZE)
230         st->duration = (((int64_t)data_size)<<3) / (channels * (int64_t)bps);
231
232     st->start_time = 0;
233     avpriv_set_pts_info(st, 64, 1, rate);
234
235     return 0;
236 }
237
238 const AVInputFormat ff_au_demuxer = {
239     .name        = "au",
240     .long_name   = NULL_IF_CONFIG_SMALL("Sun AU"),
241     .read_probe  = au_probe,
242     .read_header = au_read_header,
243     .read_packet = ff_pcm_read_packet,
244     .read_seek   = ff_pcm_read_seek,
245     .codec_tag   = au_codec_tags,
246 };
247
248 #endif /* CONFIG_AU_DEMUXER */
249
250 #if CONFIG_AU_MUXER
251
252 typedef struct AUContext {
253     uint32_t header_size;
254 } AUContext;
255
256 #include "rawenc.h"
257
258 static int au_get_annotations(AVFormatContext *s, AVBPrint *annotations)
259 {
260     static const char keys[][7] = {
261         "Title",
262         "Artist",
263         "Album",
264         "Track",
265         "Genre",
266     };
267     int cnt = 0;
268     AVDictionary *m = s->metadata;
269     AVDictionaryEntry *t = NULL;
270
271     for (int i = 0; i < FF_ARRAY_ELEMS(keys); i++) {
272         t = av_dict_get(m, keys[i], NULL, 0);
273         if (t != NULL) {
274             if (cnt++)
275                 av_bprint_chars(annotations, '\n', 1);
276             av_bprintf(annotations, "%s=%s", keys[i], t->value);
277         }
278     }
279     /* The specification requires the annotation field to be zero-terminated
280      * and its length to be a multiple of eight, so pad with 0's */
281     av_bprint_chars(annotations, '\0', 8);
282     return av_bprint_is_complete(annotations) ? 0 : AVERROR(ENOMEM);
283 }
284
285 static int au_write_header(AVFormatContext *s)
286 {
287     int ret;
288     AUContext *au = s->priv_data;
289     AVIOContext *pb = s->pb;
290     AVCodecParameters *par = s->streams[0]->codecpar;
291     AVBPrint annotations;
292
293     if (s->nb_streams != 1) {
294         av_log(s, AV_LOG_ERROR, "only one stream is supported\n");
295         return AVERROR(EINVAL);
296     }
297
298     par->codec_tag = ff_codec_get_tag(codec_au_tags, par->codec_id);
299     if (!par->codec_tag) {
300         av_log(s, AV_LOG_ERROR, "unsupported codec\n");
301         return AVERROR(EINVAL);
302     }
303
304     av_bprint_init(&annotations, 0, INT_MAX - 24);
305     ret = au_get_annotations(s, &annotations);
306     if (ret < 0)
307         goto fail;
308     au->header_size = 24 + annotations.len & ~7;
309
310     ffio_wfourcc(pb, ".snd");                   /* magic number */
311     avio_wb32(pb, au->header_size);             /* header size */
312     avio_wb32(pb, AU_UNKNOWN_SIZE);             /* data size */
313     avio_wb32(pb, par->codec_tag);              /* codec ID */
314     avio_wb32(pb, par->sample_rate);
315     avio_wb32(pb, par->ch_layout.nb_channels);
316     avio_write(pb, annotations.str, annotations.len & ~7);
317
318 fail:
319     av_bprint_finalize(&annotations, NULL);
320
321     return ret;
322 }
323
324 static int au_write_trailer(AVFormatContext *s)
325 {
326     AVIOContext *pb = s->pb;
327     AUContext *au = s->priv_data;
328     int64_t file_size = avio_tell(pb);
329
330     if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && file_size < INT32_MAX) {
331         /* update file size */
332         avio_seek(pb, 8, SEEK_SET);
333         avio_wb32(pb, (uint32_t)(file_size - au->header_size));
334         avio_seek(pb, file_size, SEEK_SET);
335     }
336
337     return 0;
338 }
339
340 const FFOutputFormat ff_au_muxer = {
341     .p.name         = "au",
342     .p.long_name    = NULL_IF_CONFIG_SMALL("Sun AU"),
343     .p.mime_type    = "audio/basic",
344     .p.extensions   = "au",
345     .p.codec_tag    = au_codec_tags,
346     .p.audio_codec  = AV_CODEC_ID_PCM_S16BE,
347     .p.video_codec  = AV_CODEC_ID_NONE,
348     .p.flags        = AVFMT_NOTIMESTAMPS,
349     .priv_data_size = sizeof(AUContext),
350     .write_header  = au_write_header,
351     .write_packet  = ff_raw_write_packet,
352     .write_trailer = au_write_trailer,
353 };
354
355 #endif /* CONFIG_AU_MUXER */