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