libavcodec/libopusdec.c
a6cf296b
 /*
  * Opus decoder using libopus
  * Copyright (c) 2012 Nicolas George
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include <opus.h>
 #include <opus_multistream.h>
44617d6e
 
48cd3d23
 #include "libavutil/internal.h"
44617d6e
 #include "libavutil/intreadwrite.h"
279d2599
 #include "libavutil/ffmath.h"
204c7caf
 #include "libavutil/opt.h"
0f40c909
 
a6cf296b
 #include "avcodec.h"
 #include "internal.h"
 #include "vorbis.h"
44617d6e
 #include "mathops.h"
6cb8c854
 #include "libopus.h"
a6cf296b
 
 struct libopus_context {
204c7caf
     AVClass *class;
a6cf296b
     OpusMSDecoder *dec;
     int pre_skip;
 #ifndef OPUS_SET_GAIN
     union { int i; double d; } gain;
 #endif
204c7caf
 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
     int apply_phase_inv;
 #endif
a6cf296b
 };
 
 #define OPUS_HEAD_SIZE 19
 
44617d6e
 static av_cold int libopus_decode_init(AVCodecContext *avc)
a6cf296b
 {
     struct libopus_context *opus = avc->priv_data;
     int ret, channel_map = 0, gain_db = 0, nb_streams, nb_coupled;
d16860a2
     uint8_t mapping_arr[8] = { 0, 1 }, *mapping;
a6cf296b
 
8c8f543b
     avc->channels = avc->extradata_size >= 10 ? avc->extradata[9] : (avc->channels == 1) ? 1 : 2;
     if (avc->channels <= 0) {
         av_log(avc, AV_LOG_WARNING,
                "Invalid number of channels %d, defaulting to stereo\n", avc->channels);
         avc->channels = 2;
     }
 
44617d6e
     avc->sample_rate    = 48000;
     avc->sample_fmt     = avc->request_sample_fmt == AV_SAMPLE_FMT_FLT ?
                           AV_SAMPLE_FMT_FLT : AV_SAMPLE_FMT_S16;
a6cf296b
 
     if (avc->extradata_size >= OPUS_HEAD_SIZE) {
         opus->pre_skip = AV_RL16(avc->extradata + 10);
44617d6e
         gain_db     = sign_extend(AV_RL16(avc->extradata + 16), 16);
         channel_map = AV_RL8 (avc->extradata + 18);
a6cf296b
     }
     if (avc->extradata_size >= OPUS_HEAD_SIZE + 2 + avc->channels) {
         nb_streams = avc->extradata[OPUS_HEAD_SIZE + 0];
         nb_coupled = avc->extradata[OPUS_HEAD_SIZE + 1];
         if (nb_streams + nb_coupled != avc->channels)
             av_log(avc, AV_LOG_WARNING, "Inconsistent channel mapping.\n");
         mapping = avc->extradata + OPUS_HEAD_SIZE + 2;
     } else {
         if (avc->channels > 2 || channel_map) {
             av_log(avc, AV_LOG_ERROR,
                    "No channel mapping for %d channels.\n", avc->channels);
             return AVERROR(EINVAL);
         }
         nb_streams = 1;
         nb_coupled = avc->channels > 1;
d16860a2
         mapping    = mapping_arr;
     }
 
c8c995bc
     if (channel_map == 1) {
         avc->channel_layout = avc->channels > 8 ? 0 :
                               ff_vorbis_channel_layouts[avc->channels - 1];
         if (avc->channels > 2 && avc->channels <= 8) {
             const uint8_t *vorbis_offset = ff_vorbis_channel_layout_offsets[avc->channels - 1];
             int ch;
d16860a2
 
c8c995bc
             /* Remap channels from Vorbis order to ffmpeg order */
             for (ch = 0; ch < avc->channels; ch++)
                 mapping_arr[ch] = mapping[vorbis_offset[ch]];
             mapping = mapping_arr;
         }
     } else if (channel_map == 2) {
         int ambisonic_order = ff_sqrt(avc->channels) - 1;
         if (avc->channels != (ambisonic_order + 1) * (ambisonic_order + 1) &&
             avc->channels != (ambisonic_order + 1) * (ambisonic_order + 1) + 2) {
             av_log(avc, AV_LOG_ERROR,
                    "Channel mapping 2 is only specified for channel counts"
                    " which can be written as (n + 1)^2 or (n + 2)^2 + 2"
                    " for nonnegative integer n\n");
             return AVERROR_INVALIDDATA;
         }
         if (avc->channels > 227) {
             av_log(avc, AV_LOG_ERROR, "Too many channels\n");
             return AVERROR_INVALIDDATA;
         }
         avc->channel_layout = 0;
     } else {
         avc->channel_layout = 0;
a6cf296b
     }
 
44617d6e
     opus->dec = opus_multistream_decoder_create(avc->sample_rate, avc->channels,
                                                 nb_streams, nb_coupled,
                                                 mapping, &ret);
a6cf296b
     if (!opus->dec) {
         av_log(avc, AV_LOG_ERROR, "Unable to create decoder: %s\n",
                opus_strerror(ret));
6cb8c854
         return ff_opus_error_to_averror(ret);
a6cf296b
     }
 
 #ifdef OPUS_SET_GAIN
     ret = opus_multistream_decoder_ctl(opus->dec, OPUS_SET_GAIN(gain_db));
     if (ret != OPUS_OK)
         av_log(avc, AV_LOG_WARNING, "Failed to set gain: %s\n",
                opus_strerror(ret));
 #else
     {
48cd3d23
         double gain_lin = ff_exp10(gain_db / (20.0 * 256));
a6cf296b
         if (avc->sample_fmt == AV_SAMPLE_FMT_FLT)
             opus->gain.d = gain_lin;
         else
             opus->gain.i = FFMIN(gain_lin * 65536, INT_MAX);
     }
 #endif
 
204c7caf
 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
     ret = opus_multistream_decoder_ctl(opus->dec,
                                        OPUS_SET_PHASE_INVERSION_DISABLED(!opus->apply_phase_inv));
     if (ret != OPUS_OK)
         av_log(avc, AV_LOG_WARNING,
                "Unable to set phase inversion: %s\n",
                opus_strerror(ret));
 #endif
 
b2597042
     /* Decoder delay (in samples) at 48kHz */
     avc->delay = avc->internal->skip_samples = opus->pre_skip;
19b2cb26
 
a6cf296b
     return 0;
 }
 
44617d6e
 static av_cold int libopus_decode_close(AVCodecContext *avc)
a6cf296b
 {
     struct libopus_context *opus = avc->priv_data;
 
e43e97f0
     if (opus->dec) {
         opus_multistream_decoder_destroy(opus->dec);
         opus->dec = NULL;
     }
a6cf296b
     return 0;
 }
 
44617d6e
 #define MAX_FRAME_SIZE (960 * 6)
a6cf296b
 
19b2cb26
 static int libopus_decode(AVCodecContext *avc, void *data,
44617d6e
                           int *got_frame_ptr, AVPacket *pkt)
a6cf296b
 {
     struct libopus_context *opus = avc->priv_data;
19b2cb26
     AVFrame *frame               = data;
a6cf296b
     int ret, nb_samples;
 
19b2cb26
     frame->nb_samples = MAX_FRAME_SIZE;
1ec94b0f
     if ((ret = ff_get_buffer(avc, frame, 0)) < 0)
a6cf296b
         return ret;
 
44617d6e
     if (avc->sample_fmt == AV_SAMPLE_FMT_S16)
         nb_samples = opus_multistream_decode(opus->dec, pkt->data, pkt->size,
19b2cb26
                                              (opus_int16 *)frame->data[0],
                                              frame->nb_samples, 0);
44617d6e
     else
         nb_samples = opus_multistream_decode_float(opus->dec, pkt->data, pkt->size,
19b2cb26
                                                    (float *)frame->data[0],
                                                    frame->nb_samples, 0);
44617d6e
 
a6cf296b
     if (nb_samples < 0) {
         av_log(avc, AV_LOG_ERROR, "Decoding error: %s\n",
                opus_strerror(nb_samples));
6cb8c854
         return ff_opus_error_to_averror(nb_samples);
a6cf296b
     }
 
 #ifndef OPUS_SET_GAIN
     {
         int i = avc->channels * nb_samples;
         if (avc->sample_fmt == AV_SAMPLE_FMT_FLT) {
afe30fe0
             float *pcm = (float *)frame->data[0];
a6cf296b
             for (; i > 0; i--, pcm++)
                 *pcm = av_clipf(*pcm * opus->gain.d, -1, 1);
         } else {
afe30fe0
             int16_t *pcm = (int16_t *)frame->data[0];
a6cf296b
             for (; i > 0; i--, pcm++)
                 *pcm = av_clip_int16(((int64_t)opus->gain.i * *pcm) >> 16);
         }
     }
 #endif
 
19b2cb26
     frame->nb_samples = nb_samples;
     *got_frame_ptr    = 1;
 
a6cf296b
     return pkt->size;
 }
 
44617d6e
 static void libopus_flush(AVCodecContext *avc)
a6cf296b
 {
     struct libopus_context *opus = avc->priv_data;
 
     opus_multistream_decoder_ctl(opus->dec, OPUS_RESET_STATE);
     /* The stream can have been extracted by a tool that is not Opus-aware.
        Therefore, any packet can become the first of the stream. */
     avc->internal->skip_samples = opus->pre_skip;
 }
 
204c7caf
 
 #define OFFSET(x) offsetof(struct libopus_context, x)
 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
 static const AVOption libopusdec_options[] = {
 #ifdef OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST
     { "apply_phase_inv", "Apply intensity stereo phase inversion", OFFSET(apply_phase_inv), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
 #endif
     { NULL },
 };
 
 static const AVClass libopusdec_class = {
     .class_name = "libopusdec",
     .item_name  = av_default_item_name,
     .option     = libopusdec_options,
     .version    = LIBAVUTIL_VERSION_INT,
 };
 
 
a6cf296b
 AVCodec ff_libopus_decoder = {
     .name           = "libopus",
b2bed932
     .long_name      = NULL_IF_CONFIG_SMALL("libopus Opus"),
a6cf296b
     .type           = AVMEDIA_TYPE_AUDIO,
7a72695c
     .id             = AV_CODEC_ID_OPUS,
a6cf296b
     .priv_data_size = sizeof(struct libopus_context),
44617d6e
     .init           = libopus_decode_init,
     .close          = libopus_decode_close,
     .decode         = libopus_decode,
     .flush          = libopus_flush,
def97856
     .capabilities   = AV_CODEC_CAP_DR1,
e43e97f0
     .caps_internal  = FF_CODEC_CAP_INIT_CLEANUP,
44617d6e
     .sample_fmts    = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLT,
                                                      AV_SAMPLE_FMT_S16,
                                                      AV_SAMPLE_FMT_NONE },
204c7caf
     .priv_class     = &libopusdec_class,
b945fed6
     .wrapper_name   = "libopus",
a6cf296b
 };