2 * Audio Toolbox system codecs
4 * copyright (c) 2016 Rodger Combs
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 #include <AudioToolbox/AudioToolbox.h>
27 #include "ac3_parser.h"
28 #include "bytestream.h"
30 #include "mpegaudiodecheader.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/log.h"
36 #define kAudioFormatEnhancedAC3 'ec-3'
39 typedef struct ATDecodeContext {
42 AudioConverterRef converter;
43 AudioStreamPacketDescription pkt_desc;
46 AVBitStreamFilterContext *bsf;
54 static UInt32 ffat_get_format_id(enum AVCodecID codec, int profile)
58 return kAudioFormatMPEG4AAC;
60 return kAudioFormatAC3;
61 case AV_CODEC_ID_ADPCM_IMA_QT:
62 return kAudioFormatAppleIMA4;
63 case AV_CODEC_ID_ALAC:
64 return kAudioFormatAppleLossless;
65 case AV_CODEC_ID_AMR_NB:
66 return kAudioFormatAMR;
67 case AV_CODEC_ID_EAC3:
68 return kAudioFormatEnhancedAC3;
69 case AV_CODEC_ID_GSM_MS:
70 return kAudioFormatMicrosoftGSM;
71 case AV_CODEC_ID_ILBC:
72 return kAudioFormatiLBC;
74 return kAudioFormatMPEGLayer1;
76 return kAudioFormatMPEGLayer2;
78 return kAudioFormatMPEGLayer3;
79 case AV_CODEC_ID_PCM_ALAW:
80 return kAudioFormatALaw;
81 case AV_CODEC_ID_PCM_MULAW:
82 return kAudioFormatULaw;
83 case AV_CODEC_ID_QDMC:
84 return kAudioFormatQDesign;
85 case AV_CODEC_ID_QDM2:
86 return kAudioFormatQDesign2;
88 av_assert0(!"Invalid codec ID!");
93 static int ffat_get_channel_id(AudioChannelLabel label)
97 else if (label <= kAudioChannelLabel_LFEScreen)
99 else if (label <= kAudioChannelLabel_RightSurround)
101 else if (label <= kAudioChannelLabel_CenterSurround)
103 else if (label <= kAudioChannelLabel_RightSurroundDirect)
105 else if (label <= kAudioChannelLabel_TopBackRight)
107 else if (label < kAudioChannelLabel_RearSurroundLeft)
109 else if (label <= kAudioChannelLabel_RearSurroundRight)
111 else if (label <= kAudioChannelLabel_RightWide)
113 else if (label == kAudioChannelLabel_LFE2)
114 return ff_ctzll(AV_CH_LOW_FREQUENCY_2);
115 else if (label == kAudioChannelLabel_Mono)
116 return ff_ctzll(AV_CH_FRONT_CENTER);
121 static int ffat_compare_channel_descriptions(const void* a, const void* b)
123 const AudioChannelDescription* da = a;
124 const AudioChannelDescription* db = b;
125 return ffat_get_channel_id(da->mChannelLabel) - ffat_get_channel_id(db->mChannelLabel);
128 static AudioChannelLayout *ffat_convert_layout(AudioChannelLayout *layout, UInt32* size)
130 AudioChannelLayoutTag tag = layout->mChannelLayoutTag;
131 AudioChannelLayout *new_layout;
132 if (tag == kAudioChannelLayoutTag_UseChannelDescriptions)
134 else if (tag == kAudioChannelLayoutTag_UseChannelBitmap)
135 AudioFormatGetPropertyInfo(kAudioFormatProperty_ChannelLayoutForBitmap,
136 sizeof(UInt32), &layout->mChannelBitmap, size);
138 AudioFormatGetPropertyInfo(kAudioFormatProperty_ChannelLayoutForTag,
139 sizeof(AudioChannelLayoutTag), &tag, size);
140 new_layout = av_malloc(*size);
145 if (tag == kAudioChannelLayoutTag_UseChannelBitmap)
146 AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
147 sizeof(UInt32), &layout->mChannelBitmap, size, new_layout);
149 AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
150 sizeof(AudioChannelLayoutTag), &tag, size, new_layout);
151 new_layout->mChannelLayoutTag = kAudioChannelLayoutTag_UseChannelDescriptions;
156 static int ffat_update_ctx(AVCodecContext *avctx)
158 ATDecodeContext *at = avctx->priv_data;
159 AudioStreamBasicDescription format;
160 UInt32 size = sizeof(format);
161 if (!AudioConverterGetProperty(at->converter,
162 kAudioConverterCurrentInputStreamDescription,
164 if (format.mSampleRate)
165 avctx->sample_rate = format.mSampleRate;
166 avctx->channels = format.mChannelsPerFrame;
167 avctx->channel_layout = av_get_default_channel_layout(avctx->channels);
168 avctx->frame_size = format.mFramesPerPacket;
171 if (!AudioConverterGetProperty(at->converter,
172 kAudioConverterCurrentOutputStreamDescription,
174 format.mSampleRate = avctx->sample_rate;
175 format.mChannelsPerFrame = avctx->channels;
176 AudioConverterSetProperty(at->converter,
177 kAudioConverterCurrentOutputStreamDescription,
181 if (!AudioConverterGetPropertyInfo(at->converter, kAudioConverterOutputChannelLayout,
182 &size, NULL) && size) {
183 AudioChannelLayout *layout = av_malloc(size);
184 uint64_t layout_mask = 0;
187 return AVERROR(ENOMEM);
188 AudioConverterGetProperty(at->converter, kAudioConverterOutputChannelLayout,
190 if (!(layout = ffat_convert_layout(layout, &size)))
191 return AVERROR(ENOMEM);
192 for (i = 0; i < layout->mNumberChannelDescriptions; i++) {
193 int id = ffat_get_channel_id(layout->mChannelDescriptions[i].mChannelLabel);
196 if (layout_mask & (1 << id))
198 layout_mask |= 1 << id;
199 layout->mChannelDescriptions[i].mChannelFlags = i; // Abusing flags as index
201 avctx->channel_layout = layout_mask;
202 qsort(layout->mChannelDescriptions, layout->mNumberChannelDescriptions,
203 sizeof(AudioChannelDescription), &ffat_compare_channel_descriptions);
204 for (i = 0; i < layout->mNumberChannelDescriptions; i++)
205 at->channel_map[i] = layout->mChannelDescriptions[i].mChannelFlags;
210 if (!avctx->frame_size)
211 avctx->frame_size = 2048;
216 static void put_descr(PutByteContext *pb, int tag, unsigned int size)
219 bytestream2_put_byte(pb, tag);
221 bytestream2_put_byte(pb, (size >> (7 * i)) | 0x80);
222 bytestream2_put_byte(pb, size & 0x7F);
225 static uint8_t* ffat_get_magic_cookie(AVCodecContext *avctx, UInt32 *cookie_size)
227 if (avctx->codec_id == AV_CODEC_ID_AAC) {
230 *cookie_size = 5 + 3 + 5+13 + 5+avctx->extradata_size;
231 if (!(extradata = av_malloc(*cookie_size)))
234 bytestream2_init_writer(&pb, extradata, *cookie_size);
237 put_descr(&pb, 0x03, 3 + 5+13 + 5+avctx->extradata_size);
238 bytestream2_put_be16(&pb, 0);
239 bytestream2_put_byte(&pb, 0x00); // flags (= no flags)
241 // DecoderConfig descriptor
242 put_descr(&pb, 0x04, 13 + 5+avctx->extradata_size);
244 // Object type indication
245 bytestream2_put_byte(&pb, 0x40);
247 bytestream2_put_byte(&pb, 0x15); // flags (= Audiostream)
249 bytestream2_put_be24(&pb, 0); // Buffersize DB
251 bytestream2_put_be32(&pb, 0); // maxbitrate
252 bytestream2_put_be32(&pb, 0); // avgbitrate
254 // DecoderSpecific info descriptor
255 put_descr(&pb, 0x05, avctx->extradata_size);
256 bytestream2_put_buffer(&pb, avctx->extradata, avctx->extradata_size);
259 *cookie_size = avctx->extradata_size;
260 return avctx->extradata;
264 static av_cold int ffat_usable_extradata(AVCodecContext *avctx)
266 return avctx->extradata_size &&
267 (avctx->codec_id == AV_CODEC_ID_ALAC ||
268 avctx->codec_id == AV_CODEC_ID_AAC);
271 static int ffat_set_extradata(AVCodecContext *avctx)
273 ATDecodeContext *at = avctx->priv_data;
274 if (ffat_usable_extradata(avctx)) {
277 uint8_t *cookie = ffat_get_magic_cookie(avctx, &cookie_size);
279 return AVERROR(ENOMEM);
281 status = AudioConverterSetProperty(at->converter,
282 kAudioConverterDecompressionMagicCookie,
283 cookie_size, cookie);
285 av_log(avctx, AV_LOG_WARNING, "AudioToolbox cookie error: %i\n", (int)status);
287 if (cookie != avctx->extradata)
293 static av_cold int ffat_create_decoder(AVCodecContext *avctx, AVPacket *pkt)
295 ATDecodeContext *at = avctx->priv_data;
299 enum AVSampleFormat sample_fmt = (avctx->bits_per_raw_sample == 32) ?
300 AV_SAMPLE_FMT_S32 : AV_SAMPLE_FMT_S16;
302 AudioStreamBasicDescription in_format = {
303 .mFormatID = ffat_get_format_id(avctx->codec_id, avctx->profile),
304 .mBytesPerPacket = avctx->block_align,
306 AudioStreamBasicDescription out_format = {
307 .mFormatID = kAudioFormatLinearPCM,
308 .mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked,
309 .mFramesPerPacket = 1,
310 .mBitsPerChannel = av_get_bytes_per_sample(sample_fmt) * 8,
313 avctx->sample_fmt = sample_fmt;
315 if (ffat_usable_extradata(avctx)) {
316 UInt32 format_size = sizeof(in_format);
318 uint8_t *cookie = ffat_get_magic_cookie(avctx, &cookie_size);
320 return AVERROR(ENOMEM);
321 status = AudioFormatGetProperty(kAudioFormatProperty_FormatInfo,
322 cookie_size, cookie, &format_size, &in_format);
323 if (cookie != avctx->extradata)
326 av_log(avctx, AV_LOG_ERROR, "AudioToolbox header-parse error: %i\n", (int)status);
327 return AVERROR_UNKNOWN;
329 #if CONFIG_MP1_AT_DECODER || CONFIG_MP2_AT_DECODER || CONFIG_MP3_AT_DECODER
330 } else if (pkt && pkt->size >= 4 &&
331 (avctx->codec_id == AV_CODEC_ID_MP1 ||
332 avctx->codec_id == AV_CODEC_ID_MP2 ||
333 avctx->codec_id == AV_CODEC_ID_MP3)) {
334 enum AVCodecID codec_id;
336 if (ff_mpa_decode_header(AV_RB32(pkt->data), &avctx->sample_rate,
337 &in_format.mChannelsPerFrame, &avctx->frame_size,
338 &bit_rate, &codec_id) < 0)
339 return AVERROR_INVALIDDATA;
340 avctx->bit_rate = bit_rate;
341 in_format.mSampleRate = avctx->sample_rate;
343 #if CONFIG_AC3_AT_DECODER || CONFIG_EAC3_AT_DECODER
344 } else if (pkt && pkt->size >= 7 &&
345 (avctx->codec_id == AV_CODEC_ID_AC3 ||
346 avctx->codec_id == AV_CODEC_ID_EAC3)) {
347 AC3HeaderInfo hdr, *phdr = &hdr;
349 init_get_bits(&gbc, pkt->data, pkt->size);
350 if (avpriv_ac3_parse_header(&gbc, &phdr) < 0)
351 return AVERROR_INVALIDDATA;
352 in_format.mSampleRate = hdr.sample_rate;
353 in_format.mChannelsPerFrame = hdr.channels;
354 avctx->frame_size = hdr.num_blocks * 256;
355 avctx->bit_rate = hdr.bit_rate;
358 in_format.mSampleRate = avctx->sample_rate ? avctx->sample_rate : 44100;
359 in_format.mChannelsPerFrame = avctx->channels ? avctx->channels : 1;
362 avctx->sample_rate = out_format.mSampleRate = in_format.mSampleRate;
363 avctx->channels = out_format.mChannelsPerFrame = in_format.mChannelsPerFrame;
365 if (avctx->codec_id == AV_CODEC_ID_ADPCM_IMA_QT)
366 in_format.mFramesPerPacket = 64;
368 status = AudioConverterNew(&in_format, &out_format, &at->converter);
371 av_log(avctx, AV_LOG_ERROR, "AudioToolbox init error: %i\n", (int)status);
372 return AVERROR_UNKNOWN;
375 if ((status = ffat_set_extradata(avctx)) < 0)
378 for (i = 0; i < (sizeof(at->channel_map) / sizeof(at->channel_map[0])); i++)
379 at->channel_map[i] = i;
381 ffat_update_ctx(avctx);
383 if(!(at->decoded_data = av_malloc(av_get_bytes_per_sample(avctx->sample_fmt)
384 * avctx->frame_size * avctx->channels)))
385 return AVERROR(ENOMEM);
387 at->last_pts = AV_NOPTS_VALUE;
392 static av_cold int ffat_init_decoder(AVCodecContext *avctx)
394 if ((avctx->channels && avctx->sample_rate) || ffat_usable_extradata(avctx))
395 return ffat_create_decoder(avctx, NULL);
400 static OSStatus ffat_decode_callback(AudioConverterRef converter, UInt32 *nb_packets,
401 AudioBufferList *data,
402 AudioStreamPacketDescription **packets,
405 AVCodecContext *avctx = inctx;
406 ATDecodeContext *at = avctx->priv_data;
411 *packets = &at->pkt_desc;
412 at->pkt_desc.mDataByteSize = 0;
417 av_packet_move_ref(&at->in_pkt, &at->new_in_pkt);
418 at->new_in_pkt.data = 0;
419 at->new_in_pkt.size = 0;
421 if (!at->in_pkt.data) {
426 data->mNumberBuffers = 1;
427 data->mBuffers[0].mNumberChannels = 0;
428 data->mBuffers[0].mDataByteSize = at->in_pkt.size;
429 data->mBuffers[0].mData = at->in_pkt.data;
433 *packets = &at->pkt_desc;
434 at->pkt_desc.mDataByteSize = at->in_pkt.size;
440 #define COPY_SAMPLES(type) \
441 type *in_ptr = (type*)at->decoded_data; \
442 type *end_ptr = in_ptr + frame->nb_samples * avctx->channels; \
443 type *out_ptr = (type*)frame->data[0]; \
444 for (; in_ptr < end_ptr; in_ptr += avctx->channels, out_ptr += avctx->channels) { \
446 for (c = 0; c < avctx->channels; c++) \
447 out_ptr[c] = in_ptr[at->channel_map[c]]; \
450 static void ffat_copy_samples(AVCodecContext *avctx, AVFrame *frame)
452 ATDecodeContext *at = avctx->priv_data;
453 if (avctx->sample_fmt == AV_SAMPLE_FMT_S32) {
454 COPY_SAMPLES(int32_t);
456 COPY_SAMPLES(int16_t);
460 static int ffat_decode(AVCodecContext *avctx, void *data,
461 int *got_frame_ptr, AVPacket *avpkt)
463 ATDecodeContext *at = avctx->priv_data;
464 AVFrame *frame = data;
465 int pkt_size = avpkt->size;
466 AVPacket filtered_packet;
468 AudioBufferList out_buffers;
470 if (avctx->codec_id == AV_CODEC_ID_AAC && avpkt->size > 2 &&
471 (AV_RB16(avpkt->data) & 0xfff0) == 0xfff0) {
472 uint8_t *p_filtered = NULL;
475 if(!(at->bsf = av_bitstream_filter_init("aac_adtstoasc")))
476 return AVERROR(ENOMEM);
479 ret = av_bitstream_filter_filter(at->bsf, avctx, NULL, &p_filtered, &n_filtered,
480 avpkt->data, avpkt->size, 0);
481 if (ret >= 0 && p_filtered != avpkt->data) {
482 filtered_packet = *avpkt;
483 avpkt = &filtered_packet;
484 avpkt->data = p_filtered;
485 avpkt->size = n_filtered;
489 if (!at->converter) {
490 if ((ret = ffat_create_decoder(avctx, avpkt)) < 0)
494 out_buffers = (AudioBufferList){
498 .mNumberChannels = avctx->channels,
499 .mDataByteSize = av_get_bytes_per_sample(avctx->sample_fmt) * avctx->frame_size
505 av_packet_unref(&at->new_in_pkt);
508 if ((ret = av_packet_ref(&at->new_in_pkt, avpkt)) < 0)
510 at->new_in_pkt.data = avpkt->data;
515 frame->sample_rate = avctx->sample_rate;
517 frame->nb_samples = avctx->frame_size;
519 out_buffers.mBuffers[0].mData = at->decoded_data;
521 ret = AudioConverterFillComplexBuffer(at->converter, ffat_decode_callback, avctx,
522 &frame->nb_samples, &out_buffers, NULL);
523 if ((!ret || ret == 1) && frame->nb_samples) {
524 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
526 ffat_copy_samples(avctx, frame);
528 if (at->last_pts != AV_NOPTS_VALUE) {
529 frame->pkt_pts = at->last_pts;
530 at->last_pts = avpkt->pts;
532 } else if (ret && ret != 1) {
533 av_log(avctx, AV_LOG_WARNING, "Decode error: %i\n", ret);
535 at->last_pts = avpkt->pts;
541 static av_cold void ffat_decode_flush(AVCodecContext *avctx)
543 ATDecodeContext *at = avctx->priv_data;
544 AudioConverterReset(at->converter);
545 av_packet_unref(&at->new_in_pkt);
546 av_packet_unref(&at->in_pkt);
549 static av_cold int ffat_close_decoder(AVCodecContext *avctx)
551 ATDecodeContext *at = avctx->priv_data;
552 AudioConverterDispose(at->converter);
553 av_packet_unref(&at->new_in_pkt);
554 av_packet_unref(&at->in_pkt);
555 av_free(at->decoded_data);
559 #define FFAT_DEC_CLASS(NAME) \
560 static const AVClass ffat_##NAME##_dec_class = { \
561 .class_name = "at_" #NAME "_dec", \
562 .version = LIBAVUTIL_VERSION_INT, \
565 #define FFAT_DEC(NAME, ID) \
566 FFAT_DEC_CLASS(NAME) \
567 AVCodec ff_##NAME##_at_decoder = { \
568 .name = #NAME "_at", \
569 .long_name = NULL_IF_CONFIG_SMALL(#NAME " (AudioToolbox)"), \
570 .type = AVMEDIA_TYPE_AUDIO, \
572 .priv_data_size = sizeof(ATDecodeContext), \
573 .init = ffat_init_decoder, \
574 .close = ffat_close_decoder, \
575 .decode = ffat_decode, \
576 .flush = ffat_decode_flush, \
577 .priv_class = &ffat_##NAME##_dec_class, \
578 .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY, \
579 .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE, \
582 FFAT_DEC(aac, AV_CODEC_ID_AAC)
583 FFAT_DEC(ac3, AV_CODEC_ID_AC3)
584 FFAT_DEC(adpcm_ima_qt, AV_CODEC_ID_ADPCM_IMA_QT)
585 FFAT_DEC(alac, AV_CODEC_ID_ALAC)
586 FFAT_DEC(amr_nb, AV_CODEC_ID_AMR_NB)
587 FFAT_DEC(eac3, AV_CODEC_ID_EAC3)
588 FFAT_DEC(gsm_ms, AV_CODEC_ID_GSM_MS)
589 FFAT_DEC(ilbc, AV_CODEC_ID_ILBC)
590 FFAT_DEC(mp1, AV_CODEC_ID_MP1)
591 FFAT_DEC(mp2, AV_CODEC_ID_MP2)
592 FFAT_DEC(mp3, AV_CODEC_ID_MP3)
593 FFAT_DEC(pcm_alaw, AV_CODEC_ID_PCM_ALAW)
594 FFAT_DEC(pcm_mulaw, AV_CODEC_ID_PCM_MULAW)
595 FFAT_DEC(qdmc, AV_CODEC_ID_QDMC)
596 FFAT_DEC(qdm2, AV_CODEC_ID_QDM2)