[FFmpeg-devel] [PATCH] TAK demuxer and decoder

Paul B Mahol onemda at gmail.com
Sat Sep 29 18:27:20 CEST 2012


Signed-off-by: Paul B Mahol <onemda at gmail.com>
---
 configure                |   1 +
 doc/general.texi         |   2 +
 libavcodec/Makefile      |   2 +
 libavcodec/allcodecs.c   |   2 +
 libavcodec/avcodec.h     |   1 +
 libavcodec/codec_desc.c  |   7 +
 libavcodec/tak.c         | 164 +++++++++
 libavcodec/tak.h         | 127 +++++++
 libavcodec/tak_parser.c  |  88 +++++
 libavcodec/takdec.c      | 937 +++++++++++++++++++++++++++++++++++++++++++++++
 libavformat/Makefile     |   1 +
 libavformat/allformats.c |   1 +
 libavformat/takdec.c     | 141 +++++++
 13 files changed, 1474 insertions(+)
 create mode 100644 libavcodec/tak.c
 create mode 100644 libavcodec/tak.h
 create mode 100644 libavcodec/tak_parser.c
 create mode 100644 libavcodec/takdec.c
 create mode 100644 libavformat/takdec.c

diff --git a/configure b/configure
index b7a8b77..ac4a83c 100755
--- a/configure
+++ b/configure
@@ -1819,6 +1819,7 @@ sap_muxer_select="rtp_muxer rtp_protocol"
 sdp_demuxer_select="rtpdec"
 smoothstreaming_muxer_select="ismv_muxer"
 spdif_muxer_select="aac_parser"
+tak_demuxer_select="tak_parser"
 tg2_muxer_select="mov_muxer"
 tgp_muxer_select="mov_muxer"
 w64_demuxer_deps="wav_demuxer"
diff --git a/doc/general.texi b/doc/general.texi
index b5f4c99..f00911c 100644
--- a/doc/general.texi
+++ b/doc/general.texi
@@ -304,6 +304,7 @@ library:
 @item raw video                 @tab X @tab X
 @item raw id RoQ                @tab X @tab
 @item raw Shorten               @tab   @tab X
+ at item raw TAK                   @tab   @tab X
 @item raw TrueHD                @tab X @tab X
 @item raw VC-1                  @tab   @tab X
 @item raw PCM A-law             @tab X @tab X
@@ -861,6 +862,7 @@ following image formats are supported:
     @tab experimental codec
 @item Speex                  @tab  E  @tab  E
     @tab supported through external library libspeex
+ at item TAK (Tom's lossless Audio Kompressor)  @tab     @tab  X
 @item True Audio (TTA)       @tab     @tab  X
 @item TrueHD                 @tab     @tab  X
     @tab Used in HD-DVD and Blu-Ray discs.
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index 34737f2..51a519a 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -410,6 +410,7 @@ OBJS-$(CONFIG_SVQ3_DECODER)            += svq3.o svq13.o h263.o h264.o        \
                                           h264_loopfilter.o h264_direct.o     \
                                           h264_sei.o h264_ps.o h264_refs.o    \
                                           h264_cavlc.o h264_cabac.o cabac.o
+OBJS-$(CONFIG_TAK_DECODER)             += takdec.o tak.o
 OBJS-$(CONFIG_TARGA_DECODER)           += targa.o
 OBJS-$(CONFIG_TARGA_ENCODER)           += targaenc.o rle.o
 OBJS-$(CONFIG_THEORA_DECODER)          += xiph.o
@@ -719,6 +720,7 @@ OBJS-$(CONFIG_MPEGVIDEO_PARSER)        += mpegvideo_parser.o    \
 OBJS-$(CONFIG_PNM_PARSER)              += pnm_parser.o pnm.o
 OBJS-$(CONFIG_RV30_PARSER)             += rv34_parser.o
 OBJS-$(CONFIG_RV40_PARSER)             += rv34_parser.o
+OBJS-$(CONFIG_TAK_PARSER)              += tak_parser.o tak.o
 OBJS-$(CONFIG_VC1_PARSER)              += vc1_parser.o vc1.o vc1data.o \
                                           msmpeg4.o msmpeg4data.o mpeg4video.o \
                                           h263.o
diff --git a/libavcodec/allcodecs.c b/libavcodec/allcodecs.c
index cba953f..1a4cc36 100644
--- a/libavcodec/allcodecs.c
+++ b/libavcodec/allcodecs.c
@@ -327,6 +327,7 @@ void avcodec_register_all(void)
     REGISTER_DECODER (SMACKAUD, smackaud);
     REGISTER_ENCDEC  (SONIC, sonic);
     REGISTER_ENCODER (SONIC_LS, sonic_ls);
+    REGISTER_DECODER (TAK, tak);
     REGISTER_DECODER (TRUEHD, truehd);
     REGISTER_DECODER (TRUESPEECH, truespeech);
     REGISTER_DECODER (TTA, tta);
@@ -485,6 +486,7 @@ void avcodec_register_all(void)
     REGISTER_PARSER  (PNM, pnm);
     REGISTER_PARSER  (RV30, rv30);
     REGISTER_PARSER  (RV40, rv40);
+    REGISTER_PARSER  (TAK, tak);
     REGISTER_PARSER  (VC1, vc1);
     REGISTER_PARSER  (VORBIS, vorbis);
     REGISTER_PARSER  (VP3, vp3);
diff --git a/libavcodec/avcodec.h b/libavcodec/avcodec.h
index 2c18b42..05efd8e 100644
--- a/libavcodec/avcodec.h
+++ b/libavcodec/avcodec.h
@@ -430,6 +430,7 @@ enum AVCodecID {
     AV_CODEC_ID_SONIC_LS    = MKBETAG('S','O','N','L'),
     AV_CODEC_ID_PAF_AUDIO   = MKBETAG('P','A','F','A'),
     AV_CODEC_ID_OPUS        = MKBETAG('O','P','U','S'),
+    AV_CODEC_ID_TAK         = MKBETAG('t','B','a','K'),
 
     /* subtitle codecs */
     AV_CODEC_ID_FIRST_SUBTITLE = 0x17000,          ///< A dummy ID pointing at the start of subtitle codecs.
diff --git a/libavcodec/codec_desc.c b/libavcodec/codec_desc.c
index 2f9e348..35cc9a6 100644
--- a/libavcodec/codec_desc.c
+++ b/libavcodec/codec_desc.c
@@ -2370,6 +2370,13 @@ static const AVCodecDescriptor codec_descriptors[] = {
         .long_name = NULL_IF_CONFIG_SMALL("iCEDraw text"),
         .props     = AV_CODEC_PROP_INTRA_ONLY,
     },
+    {
+        .id        = AV_CODEC_ID_TAK,
+        .type      = AVMEDIA_TYPE_AUDIO,
+        .name      = "tak",
+        .long_name = NULL_IF_CONFIG_SMALL("TAK (Tom's lossless Audio Kompressor)"),
+        .props     = AV_CODEC_PROP_LOSSLESS,
+    },
 
 };
 
diff --git a/libavcodec/tak.c b/libavcodec/tak.c
new file mode 100644
index 0000000..acd3841
--- /dev/null
+++ b/libavcodec/tak.c
@@ -0,0 +1,164 @@
+/*
+ * TAK common code
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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 "tak.h"
+
+static const int64_t tak_channel_layouts[] = {
+    0,
+    AV_CH_FRONT_LEFT,
+    AV_CH_FRONT_RIGHT,
+    AV_CH_FRONT_CENTER,
+    AV_CH_LOW_FREQUENCY,
+    AV_CH_BACK_LEFT,
+    AV_CH_BACK_RIGHT,
+    AV_CH_FRONT_LEFT_OF_CENTER,
+    AV_CH_FRONT_RIGHT_OF_CENTER,
+    AV_CH_BACK_CENTER,
+    AV_CH_SIDE_LEFT,
+    AV_CH_SIDE_RIGHT,
+    AV_CH_TOP_CENTER,
+    AV_CH_TOP_FRONT_LEFT,
+    AV_CH_TOP_FRONT_CENTER,
+    AV_CH_TOP_FRONT_RIGHT,
+    AV_CH_TOP_BACK_LEFT,
+    AV_CH_TOP_BACK_CENTER,
+    AV_CH_TOP_BACK_RIGHT,
+};
+
+static const uint16_t frame_duration_type_quants[] = {
+    3, 4, 6, 8, 4096, 8192, 16384, 512, 1024, 2048,
+};
+
+static int tak_get_nb_samples(AVCodecContext *avctx, int sample_rate,
+                              enum TAKFrameSizeType type)
+{
+    int nb_samples, max_nb_samples;
+
+    if (type <= TAK_FST_250ms) {
+        nb_samples     = sample_rate * frame_duration_type_quants[type] >>
+                                       TAK_FRAME_DURATION_QUANT_SHIFT;
+        max_nb_samples = 16384;
+    } else if (type < FF_ARRAY_ELEMS(frame_duration_type_quants)) {
+        nb_samples     = frame_duration_type_quants[type];
+        max_nb_samples = sample_rate * frame_duration_type_quants[TAK_FST_250ms] >>
+                                       TAK_FRAME_DURATION_QUANT_SHIFT;
+    } else {
+        av_log(avctx, AV_LOG_ERROR, "unsupported frame type %d\n", type);
+        return AVERROR_INVALIDDATA;
+    }
+
+    if (nb_samples <= 0 || nb_samples > max_nb_samples)
+        return AVERROR_INVALIDDATA;
+
+    return nb_samples;
+}
+
+int avpriv_tak_parse_streaminfo(void *log, GetBitContext *gb, TAKStreamInfo *s)
+{
+    uint64_t channel_mask = 0;
+    int frame_type, i;
+
+    s->codec = get_bits(gb, TAK_ENCODER_CODEC_BITS);
+    if (s->codec != 2 && s->codec != 4) {
+        av_log(log, AV_LOG_ERROR, "unsupported codec: %d\n", s->codec);
+        return AVERROR_PATCHWELCOME;
+    }
+
+    skip_bits(gb, TAK_ENCODER_PROFILE_BITS);
+
+    frame_type = get_bits(gb, TAK_SIZE_FRAME_DURATION_BITS);
+    s->samples = get_bits_long(gb, TAK_SIZE_SAMPLES_NUM_BITS);
+
+    if (get_bits(gb, TAK_FORMAT_DATA_TYPE_BITS)) {
+        av_log(log, AV_LOG_ERROR, "unsupported data type\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    s->sample_rate = get_bits(gb, TAK_FORMAT_SAMPLE_RATE_BITS) + TAK_SAMPLE_RATE_MIN;
+    s->bps         = get_bits(gb, TAK_FORMAT_BPS_BITS) + TAK_BPS_MIN;
+    s->channels    = get_bits(gb, TAK_FORMAT_CHANNEL_BITS) + TAK_CHANNELS_MIN;
+
+    if (get_bits1(gb)) {
+        skip_bits(gb, TAK_FORMAT_VALID_BITS);
+        if (get_bits1(gb)) {
+            for (i = 0; i < s->channels; i++) {
+                int value = get_bits(gb, TAK_FORMAT_CH_LAYOUT_BITS);
+
+                if (value < FF_ARRAY_ELEMS(tak_channel_layouts))
+                    channel_mask |= tak_channel_layouts[value];
+            }
+        }
+    }
+
+    s->ch_layout     = channel_mask;
+    s->frame_samples = tak_get_nb_samples(log, s->sample_rate, frame_type);
+    if (s->frame_samples < 0)
+        return AVERROR_INVALIDDATA;
+
+    return 0;
+}
+
+#define FRAME_IS_LAST       1
+#define FRAME_HAVE_INFO     2
+#define FRAME_HAVE_METADATA 4
+
+int ff_tak_decode_frame_header(AVCodecContext *avctx, GetBitContext *gb,
+                               TAKStreamInfo *ti)
+{
+    int flags, ret;
+
+    if (get_bits(gb, TAK_FRAME_HEADER_SYNC_ID_BITS) != TAK_FRAME_HEADER_SYNC_ID) {
+        av_log(avctx, AV_LOG_ERROR, "missing sync id\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    flags = get_bits(gb, 3);
+    skip_bits(gb, TAK_FRAME_HEADER_NO_BITS);
+
+    if (flags & FRAME_IS_LAST) {
+        ti->last_frame_samples = get_bits(gb, TAK_FRAME_HEADER_SAMPLE_COUNT_BITS) + 1;
+        skip_bits(gb, 2);
+    } else {
+        ti->last_frame_samples = 0;
+    }
+
+    if (flags & FRAME_HAVE_INFO) {
+        if ((ret = avpriv_tak_parse_streaminfo(avctx, gb, ti)) < 0)
+            return ret;
+
+        avctx->bits_per_coded_sample = ti->bps;
+        if (ti->ch_layout)
+            avctx->channel_layout = ti->ch_layout;
+        avctx->sample_rate = ti->sample_rate;
+        avctx->channels    = ti->channels;
+
+        if (get_bits(gb, 6))
+            skip_bits(gb, 25);
+        align_get_bits(gb);
+    }
+
+    if (flags & FRAME_HAVE_METADATA)
+        return AVERROR_INVALIDDATA;
+
+    skip_bits(gb, 24);
+
+    return 0;
+}
diff --git a/libavcodec/tak.h b/libavcodec/tak.h
new file mode 100644
index 0000000..3c834e6
--- /dev/null
+++ b/libavcodec/tak.h
@@ -0,0 +1,127 @@
+/*
+ * TAK decoder/demuxer common code
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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
+ */
+
+/**
+ * @file
+ * TAK (Tom's lossless Audio Kompressor) decoder/demuxer common functions
+ */
+
+#ifndef AVCODEC_TAK_H
+#define AVCODEC_TAK_H
+
+#define BITSTREAM_READER_LE
+#include "get_bits.h"
+#include "avcodec.h"
+
+#define TAK_FORMAT_DATA_TYPE_BITS    3
+#define TAK_FORMAT_SAMPLE_RATE_BITS  18
+#define TAK_FORMAT_BPS_BITS          5
+#define TAK_FORMAT_CHANNEL_BITS      4
+#define TAK_FORMAT_VALID_BITS        5
+#define TAK_FORMAT_CH_LAYOUT_BITS    6
+#define TAK_SIZE_FRAME_DURATION_BITS 4
+#define TAK_SIZE_SAMPLES_NUM_BITS    35
+#define TAK_LAST_FRAME_POS_BITS      40
+#define TAK_LAST_FRAME_SIZE_BITS     24
+#define TAK_ENCODER_CODEC_BITS       6
+#define TAK_ENCODER_PROFILE_BITS     4
+#define TAK_ENCODER_VERSION_BITS     24
+#define TAK_SAMPLE_RATE_MIN          6000
+#define TAK_CHANNELS_MIN             1
+#define TAK_BPS_MIN                  8
+#define TAK_FRAME_HEADER_BITS               40
+#define TAK_FRAME_HEADER_LAST_BITS          (TAK_FRAME_HEADER_BITS + 16)
+#define TAK_FRAME_HEADER_SYNC_ID            0xA0FF
+#define TAK_FRAME_HEADER_SYNC_ID_BITS       16
+#define TAK_FRAME_HEADER_SAMPLE_COUNT_BITS  14
+#define TAK_FRAME_HEADER_NO_BITS            21
+#define TAK_FRAME_DURATION_QUANT_SHIFT      5
+
+#define TAK_ENCODER_BITS         ( TAK_ENCODER_CODEC_BITS        + \
+                                   TAK_ENCODER_PROFILE_BITS)
+#define TAK_SIZE_BITS            ( TAK_SIZE_SAMPLES_NUM_BITS     + \
+                                   TAK_SIZE_FRAME_DURATION_BITS)
+#define TAK_FORMAT_BITS          ( TAK_FORMAT_DATA_TYPE_BITS     + \
+                                   TAK_FORMAT_SAMPLE_RATE_BITS   + \
+                                   TAK_FORMAT_BPS_BITS           + \
+                                   TAK_FORMAT_CHANNEL_BITS + 1)
+
+#define TAK_STREAMINFO_BITS      ( TAK_ENCODER_BITS              + \
+                                   TAK_SIZE_BITS                 + \
+                                   TAK_FORMAT_BITS)
+
+#define TAK_STREAMINFO_BYTES    (( TAK_STREAMINFO_BITS + 7 ) / 8)
+#define TAK_FRAME_HEADER_BYTES  (( TAK_FRAME_HEADER_BITS + 7 ) / 8)
+
+enum {
+    TAK_METADATA_END = 0,
+    TAK_METADATA_STREAMINFO,
+    TAK_METADATA_SEEKTABLE,
+    TAK_METADATA_SIMPLE_WAVE_DATA,
+    TAK_METADATA_ENCODER,
+    TAK_METADATA_PADDING,
+    TAK_METADATA_MD5,
+    TAK_METADATA_LAST_FRAME,
+};
+
+enum TAKFrameSizeType {
+    TAK_FST_94ms = 0,
+    TAK_FST_125ms,
+    TAK_FST_188ms,
+    TAK_FST_250ms,
+    TAK_FST_4096,
+    TAK_FST_8192,
+    TAK_FST_16384,
+    TAK_FST_512,
+    TAK_FST_1024,
+    TAK_FST_2048,
+};
+
+typedef struct TAKStreamInfo {
+    int      codec;
+    int      sample_rate;
+    int      channels;
+    int      bps;
+    int      frame_samples;
+    int      last_frame_samples;
+    uint64_t ch_layout;
+    int64_t  samples;
+} TAKStreamInfo;
+
+/**
+ * Parse the Streaminfo metadata block
+ * @param      log     context used for av_log()
+ * @param[in]  gb      pointer to GetBitContext
+ * @param[out] s       where parsed information is stored
+ * @return non-zero on error, 0 if ok
+ */
+int avpriv_tak_parse_streaminfo(void *log, GetBitContext *gb, TAKStreamInfo *s);
+
+/**
+ * Validate and decode a frame header.
+ * @param      avctx AVCodecContext to use as av_log() context
+ * @param[in]  gb    GetBitContext from which to read frame header
+ * @param[out] s     frame information
+ * @return non-zero on error, 0 if ok
+ */
+int ff_tak_decode_frame_header(AVCodecContext *avctx, GetBitContext *gb,
+                               TAKStreamInfo *s);
+#endif /* AVCODEC_TAK_H */
diff --git a/libavcodec/tak_parser.c b/libavcodec/tak_parser.c
new file mode 100644
index 0000000..6512df0
--- /dev/null
+++ b/libavcodec/tak_parser.c
@@ -0,0 +1,88 @@
+/*
+ * TAK parser
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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 "libavutil/bswap.h"
+#include "parser.h"
+#include "tak.h"
+
+typedef struct TAKParseContext {
+    ParseContext  pc;
+    TAKStreamInfo ti;
+    int           frame_number;
+} TAKParseContext;
+
+static int tak_parse(AVCodecParserContext *s, AVCodecContext *avctx,
+                     const uint8_t **poutbuf, int *poutbuf_size,
+                     const uint8_t *buf, int buf_size)
+{
+    TAKParseContext *t = s->priv_data;
+    int next = END_NOT_FOUND, i = 0;
+    uint64_t state = t->pc.state64;
+
+    *poutbuf_size = 0;
+    if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
+        *poutbuf      = buf;
+        *poutbuf_size = buf_size;
+        return buf_size;
+    }
+
+    if (!t->pc.frame_start_found) {
+        for (; i < buf_size; i++) {
+            state = (state << 8) | buf[i];
+            if ((state >> 48) == av_bswap16(TAK_FRAME_HEADER_SYNC_ID)) {
+                t->frame_number = av_bswap32(state >> 24) >> 11;
+                t->pc.frame_start_found = 1;
+                break;
+            }
+        }
+        t->pc.state64 = state;
+    }
+
+    if (t->pc.frame_start_found) {
+        for (; i < buf_size; i++) {
+            state = (state << 8) | buf[i];
+            if ((state >> 48) == av_bswap16(TAK_FRAME_HEADER_SYNC_ID)) {
+                int frame_number = av_bswap32(state >> 24) >> 11;
+
+                if (t->frame_number + 1 == frame_number) {
+                    next = i - 7;
+                    t->pc.frame_start_found = 0;
+                    break;
+                }
+            }
+        }
+        t->pc.state64 = state;
+    }
+
+    if (ff_combine_frame(&t->pc, next, &buf, &buf_size) < 0)
+        return buf_size;
+
+    *poutbuf      = buf;
+    *poutbuf_size = buf_size;
+    return next;
+}
+
+AVCodecParser ff_tak_parser = {
+    .codec_ids      = { AV_CODEC_ID_TAK },
+    .priv_data_size = sizeof(TAKParseContext),
+    .parser_parse   = tak_parse,
+    .parser_close   = ff_parse_close,
+};
diff --git a/libavcodec/takdec.c b/libavcodec/takdec.c
new file mode 100644
index 0000000..4d6707e
--- /dev/null
+++ b/libavcodec/takdec.c
@@ -0,0 +1,937 @@
+/*
+ * TAK decoder
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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
+ */
+
+/**
+ * @file
+ * TAK (Tom's lossless Audio Kompressor) decoder
+ * @author Paul B Mahol
+ */
+
+#include "tak.h"
+#include "avcodec.h"
+#include "libavutil/crc.h"
+#include "libavutil/intreadwrite.h"
+#include "unary.h"
+
+#define MAX_CHANNELS     (1 << TAK_FORMAT_CHANNEL_BITS)
+#define MAX_SUBFRAMES   8                      ///< max number of subframes per channel
+#define MAX_PREDICTORS  256
+
+typedef struct MCDParam {
+    int8_t     present;
+    int8_t     index;
+    int8_t     chan1;
+    int8_t     chan2;
+} MCDParam;
+
+typedef struct TAKDecContext {
+    AVFrame        frame;
+    AVCodecContext *avctx;                     ///< parent AVCodecContext
+
+    int            nb_samples;                 ///< number of samples in the current frame
+    int            nb_subframes;               ///< number of subframes in the current frame
+
+    TAKStreamInfo  ti;
+    GetBitContext  gb;                         ///< GetBitContext initialized to start at the current frame
+
+    int32_t        *decode_buffer;
+    int            decode_buffer_size;
+
+    int8_t         lpc[MAX_CHANNELS];
+    int8_t         sample_shift[MAX_CHANNELS]; ///< shift applied to every sample in the channel
+    int32_t        xred;
+    int            size;
+    int            ared;
+    int            nb_predictors;
+    int16_t        predictors[MAX_PREDICTORS];
+    int8_t         subframes[MAX_SUBFRAMES];   ///< indexes of relative subframe start in the frame
+    int            subframe_scale;             ///< number multiplied with above index to get actual subframe position
+
+    int            dmode;                      ///< channel decorrelation type in the current frame
+    int            dshift;
+    int            dfactor;
+    int            nb_dcoeffs;
+    int16_t        dcoeffs[16];
+
+    int            dval1;
+    int            dval2;
+
+    MCDParam       mcdparams[MAX_CHANNELS];
+
+    int            wlength;
+    int8_t         xvals[128];
+    int            uval;
+    int            rval;
+    int32_t        ncoeff[MAX_PREDICTORS];
+    int16_t        f[544];
+
+    AVCRC          crc24[257];
+} TAKDecContext;
+
+static int tak_check_crc(TAKDecContext *s, const uint8_t *buf, int buf_size)
+{
+    uint32_t crc, CRC;
+
+    if (buf_size < 4)
+        return AVERROR_INVALIDDATA;
+    buf_size -= 3;
+
+    CRC = av_bswap32(AV_RL24(buf + buf_size)) >> 8;
+    crc = av_crc(s->crc24, 0xCE04B7U, buf, buf_size);
+    if (CRC != crc) {
+        av_log(s->avctx, AV_LOG_ERROR, "CRC error\n");
+        return AVERROR_INVALIDDATA;
+    }
+
+    return 0;
+}
+
+static void tak_set_bps(AVCodecContext *avctx)
+{
+    switch (avctx->bits_per_coded_sample) {
+    case 8:
+        avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
+        break;
+    case 16:
+        avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
+        break;
+    case 24:
+        avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
+        break;
+    }
+}
+
+static int get_shift(int sample_rate)
+{
+    int shift;
+
+    if (sample_rate < 11025)
+        shift = 3;
+    else if (sample_rate < 22050)
+        shift = 2;
+    else if (sample_rate < 44100)
+        shift = 1;
+    else
+        shift = 0;
+
+    return shift;
+}
+
+static int get_scale(int sample_rate, int shift)
+{
+    return (((sample_rate + 511 >> 9) + 3) & 0xFFFFFFFC) << shift;
+}
+
+static av_cold int tak_decode_init(AVCodecContext *avctx)
+{
+    TAKDecContext *s = avctx->priv_data;
+
+    s->avctx = avctx;
+    avcodec_get_frame_defaults(&s->frame);
+    avctx->coded_frame = &s->frame;
+
+    av_crc_init(s->crc24, 0, 24, 0x864CFBU, sizeof(s->crc24));
+    tak_set_bps(avctx);
+    s->uval = get_scale(avctx->sample_rate, get_shift(avctx->sample_rate));
+    s->subframe_scale = get_scale(avctx->sample_rate, 1);
+
+    return 0;
+}
+
+static int get_code(GetBitContext *gb, int nbits)
+{
+    int ret;
+
+    if (nbits == 1) {
+        skip_bits1(gb);
+        ret = 0;
+    } else {
+        ret = get_sbits(gb, nbits);
+    }
+
+    return ret;
+}
+
+static void decode_lpc(int32_t *ptr, int lpc, int length)
+{
+    int i, a1, a2, a3, a4, a5;
+
+    if (length < 2)
+        return;
+
+    if (lpc == 1) {
+        a1 = *ptr++;
+        for (i = 0; i < (length - 1 >> 1); i++) {
+            *ptr   += a1;
+            ptr[1] += *ptr;
+            a1      = ptr[1];
+            ptr    += 2;
+        }
+        if ((length - 1) & 1)
+            *ptr += a1;
+    } else if (lpc == 2) {
+        a1     = ptr[1];
+        a2     = a1 + *ptr;
+        ptr[1] = a2;
+        if (length > 2) {
+            ptr += 2;
+            for (i = 0; i < (length - 2 >> 1); i++) {
+                a3     = *ptr + a1;
+                a4     = a3 + a2;
+                *ptr   = a4;
+                a1     = ptr[1] + a3;
+                a2     = a1 + a4;
+                ptr[1] = a2;
+                ptr   += 2;
+            }
+            if (length & 1)
+                *ptr  += a1 + a2;
+        }
+    } else if (lpc == 3) {
+        a1     = ptr[1];
+        a2     = a1 + *ptr;
+        ptr[1] = a2;
+        if (length > 2) {
+            a3   = ptr[2];
+            a4   = a3 + a1;
+            a5   = a4 + a2;
+            ptr += 3;
+            for (i = 0; i < length - 3; i++) {
+                a3  += *ptr;
+                a4  += a3;
+                a5  += a4;
+                *ptr = a5;
+                ptr++;
+            }
+        }
+    }
+}
+
+static const int8_t mc_dmodes[] = {
+    1, 3, 4, 6,
+};
+
+static const uint16_t predictor_sizes[] = {
+    4, 8, 12, 16, 24, 32, 48, 64, 80, 96, 128, 160, 192, 224, 256, 0,
+};
+
+static const uint32_t xcodes[50][5] = {
+    { 0x01, 0x0000001, 0x0000001, 0x0000003, 0x0000008 },
+    { 0x02, 0x0000003, 0x0000001, 0x0000007, 0x0000006 },
+    { 0x03, 0x0000005, 0x0000002, 0x000000E, 0x000000D },
+    { 0x03, 0x0000003, 0x0000003, 0x000000D, 0x0000018 },
+    { 0x04, 0x000000B, 0x0000004, 0x000001C, 0x0000019 },
+    { 0x04, 0x0000006, 0x0000006, 0x000001A, 0x0000030 },
+    { 0x05, 0x0000016, 0x0000008, 0x0000038, 0x0000032 },
+    { 0x05, 0x000000C, 0x000000C, 0x0000034, 0x0000060 },
+    { 0x06, 0x000002C, 0x0000010, 0x0000070, 0x0000064 },
+    { 0x06, 0x0000018, 0x0000018, 0x0000068, 0x00000C0 },
+    { 0x07, 0x0000058, 0x0000020, 0x00000E0, 0x00000C8 },
+    { 0x07, 0x0000030, 0x0000030, 0x00000D0, 0x0000180 },
+    { 0x08, 0x00000B0, 0x0000040, 0x00001C0, 0x0000190 },
+    { 0x08, 0x0000060, 0x0000060, 0x00001A0, 0x0000300 },
+    { 0x09, 0x0000160, 0x0000080, 0x0000380, 0x0000320 },
+    { 0x09, 0x00000C0, 0x00000C0, 0x0000340, 0x0000600 },
+    { 0x0A, 0x00002C0, 0x0000100, 0x0000700, 0x0000640 },
+    { 0x0A, 0x0000180, 0x0000180, 0x0000680, 0x0000C00 },
+    { 0x0B, 0x0000580, 0x0000200, 0x0000E00, 0x0000C80 },
+    { 0x0B, 0x0000300, 0x0000300, 0x0000D00, 0x0001800 },
+    { 0x0C, 0x0000B00, 0x0000400, 0x0001C00, 0x0001900 },
+    { 0x0C, 0x0000600, 0x0000600, 0x0001A00, 0x0003000 },
+    { 0x0D, 0x0001600, 0x0000800, 0x0003800, 0x0003200 },
+    { 0x0D, 0x0000C00, 0x0000C00, 0x0003400, 0x0006000 },
+    { 0x0E, 0x0002C00, 0x0001000, 0x0007000, 0x0006400 },
+    { 0x0E, 0x0001800, 0x0001800, 0x0006800, 0x000C000 },
+    { 0x0F, 0x0005800, 0x0002000, 0x000E000, 0x000C800 },
+    { 0x0F, 0x0003000, 0x0003000, 0x000D000, 0x0018000 },
+    { 0x10, 0x000B000, 0x0004000, 0x001C000, 0x0019000 },
+    { 0x10, 0x0006000, 0x0006000, 0x001A000, 0x0030000 },
+    { 0x11, 0x0016000, 0x0008000, 0x0038000, 0x0032000 },
+    { 0x11, 0x000C000, 0x000C000, 0x0034000, 0x0060000 },
+    { 0x12, 0x002C000, 0x0010000, 0x0070000, 0x0064000 },
+    { 0x12, 0x0018000, 0x0018000, 0x0068000, 0x00C0000 },
+    { 0x13, 0x0058000, 0x0020000, 0x00E0000, 0x00C8000 },
+    { 0x13, 0x0030000, 0x0030000, 0x00D0000, 0x0180000 },
+    { 0x14, 0x00B0000, 0x0040000, 0x01C0000, 0x0190000 },
+    { 0x14, 0x0060000, 0x0060000, 0x01A0000, 0x0300000 },
+    { 0x15, 0x0160000, 0x0080000, 0x0380000, 0x0320000 },
+    { 0x15, 0x00C0000, 0x00C0000, 0x0340000, 0x0600000 },
+    { 0x16, 0x02C0000, 0x0100000, 0x0700000, 0x0640000 },
+    { 0x16, 0x0180000, 0x0180000, 0x0680000, 0x0C00000 },
+    { 0x17, 0x0580000, 0x0200000, 0x0E00000, 0x0C80000 },
+    { 0x17, 0x0300000, 0x0300000, 0x0D00000, 0x1800000 },
+    { 0x18, 0x0B00000, 0x0400000, 0x1C00000, 0x1900000 },
+    { 0x18, 0x0600000, 0x0600000, 0x1A00000, 0x3000000 },
+    { 0x19, 0x1600000, 0x0800000, 0x3800000, 0x3200000 },
+    { 0x19, 0x0C00000, 0x0C00000, 0x3400000, 0x6000000 },
+    { 0x1A, 0x2C00000, 0x1000000, 0x7000000, 0x6400000 },
+    { 0x1A, 0x1800000, 0x1800000, 0x6800000, 0xC000000 },
+};
+
+static int decode_n(TAKDecContext *s, int8_t value, int32_t *ptr, int len)
+{
+    GetBitContext  *gb = &s->gb;
+
+    if (!value) {
+        memset(ptr, 0, len * 4);
+    } else {
+        int x, y, z, i = 0;
+
+        value--;
+        do {
+            while (1) {
+                x = get_bits_long(gb, xcodes[value][0]);
+                if (x >= xcodes[value][1])
+                    break;
+                ptr[i++] = (x >> 1) ^ -(x & 1);
+                if (i >= len)
+                    return 0;
+            }
+
+            y = get_bits1(gb);
+            x = (y << xcodes[value][0]) | x;
+            if (x >= xcodes[value][3]) {
+                int c = get_unary(gb, 1, 9);
+
+                if (c == 9) {
+                    int d;
+
+                    z = xcodes[value][4] + x;
+                    d = get_bits(gb, 3);
+                    if (d == 7) {
+                        d = get_bits(gb, 5) + 7;
+                        if (d > 29)
+                            return AVERROR_INVALIDDATA;
+                    }
+                    if (d)
+                        z += xcodes[value][2] * (get_bits_long(gb, d) + 1);
+                } else {
+                    z = xcodes[value][2] * c + x - xcodes[value][1];
+                }
+            } else {
+                z = x - (xcodes[value][1] & -y);
+            }
+            ptr[i++] = (z >> 1) ^ -(z & 1);
+        } while (i < len);
+    }
+
+    return 0;
+}
+
+static int xget(TAKDecContext *s, int d, int *v)
+{
+    int x;
+
+    x = d / s->uval;
+
+    s->rval = d - (x * s->uval);
+
+    if (s->rval < s->uval / 2) {
+        s->rval += s->uval;
+    } else {
+        x++;
+    }
+
+    if (x <= 1 || x > 128)
+        return AVERROR_INVALIDDATA;
+
+    *v = x;
+    return 0;
+}
+
+static int get_len(TAKDecContext *s, int b)
+{
+    if (b >= s->wlength - 1)
+        return s->rval;
+    else
+        return s->uval;
+}
+
+static int decode_m(TAKDecContext *s, int32_t *ptr, int length)
+{
+    GetBitContext  *gb = &s->gb;
+    int i, v, ret = 0;
+
+    if (length > s->nb_samples)
+        return AVERROR_INVALIDDATA;
+
+    if (get_bits1(gb)) {
+        if (xget(s, length, &s->wlength))
+            return AVERROR_INVALIDDATA;
+
+        s->xvals[0] = v = get_bits(gb, 6);
+        if (s->xvals[0] > FF_ARRAY_ELEMS(xcodes))
+            return AVERROR_INVALIDDATA;
+
+        for (i = 1; i < s->wlength; i++) {
+            int c = get_unary(gb, 1, 6);
+
+            if (c > 5) {
+                v = get_bits(gb, 6);
+            } else if (c > 2) {
+                int t = get_bits1(gb);
+
+                v += (-t ^ (c - 1)) + t;
+            } else {
+                v += (-(c & 1) ^ (((c & 1) + c) >> 1)) + (c & 1);
+            }
+
+            if (v > 50)
+                return AVERROR_INVALIDDATA;
+            s->xvals[i] = v;
+        }
+
+        i = 0;
+        while (i < s->wlength) {
+            int len = 0;
+
+            v = s->xvals[i];
+            do {
+                len += get_len(s, i);
+                i++;
+
+                if (i == s->wlength)
+                    break;
+            } while (v == s->xvals[i]);
+
+            if ((ret = decode_n(s, v, ptr, len)) < 0)
+                return ret;
+            ptr += len;
+        }
+    } else {
+        v = get_bits(gb, 6);
+        if (v > FF_ARRAY_ELEMS(xcodes))
+            return AVERROR_INVALIDDATA;
+        if ((ret = decode_n(s, v, ptr, length)) < 0)
+            return ret;
+    }
+
+    return ret;
+}
+
+static int get_b(GetBitContext *gb)
+{
+    if (get_bits1(gb))
+        return get_bits(gb, 4) + 1;
+    else
+        return 0;
+}
+
+static int decode_subframe(TAKDecContext *s, int32_t *ptr, int subframe_size, int prev_subframe_size)
+{
+    GetBitContext  *gb = &s->gb;
+    int tmp, x, y, i, j, ret = 0;
+
+    if (get_bits1(gb)) {
+        s->nb_predictors = predictor_sizes[get_bits(gb, 4)];
+
+        if (prev_subframe_size > 0 && get_bits1(gb)) {
+            if (s->nb_predictors > prev_subframe_size)
+                return AVERROR_INVALIDDATA;
+
+            ptr           -= s->nb_predictors;
+            subframe_size += s->nb_predictors;
+
+            if (s->nb_predictors > subframe_size)
+                return AVERROR_INVALIDDATA;
+        } else {
+            int lpc;
+
+            if (s->nb_predictors > subframe_size)
+                return AVERROR_INVALIDDATA;
+
+            lpc = get_bits(gb, 2);
+            if (lpc > 2)
+                return AVERROR_INVALIDDATA;
+
+            if ((ret = decode_m(s, ptr, s->nb_predictors)) < 0)
+                return ret;
+
+            decode_lpc(ptr, lpc, s->nb_predictors);
+        }
+
+        s->xred = get_b(gb);
+        s->size = get_bits1(gb) + 5;
+
+        if (get_bits1(gb)) {
+            s->ared = get_bits(gb, 3) + 1;
+            if (s->ared > 7)
+                return AVERROR_INVALIDDATA;
+        } else {
+            s->ared = 0;
+        }
+        s->predictors[0] = get_code(gb, 10);
+        s->predictors[1] = get_code(gb, 10);
+        s->predictors[2] = get_code(gb, s->size + 1) << (9 - s->size);
+        s->predictors[3] = get_code(gb, s->size + 1) << (9 - s->size);
+        if (s->nb_predictors > 4) {
+            tmp = s->size + 1 - get_bits1(gb);
+
+            for (i = 4; i < s->nb_predictors; i++) {
+                if (!(i & 3))
+                    x = tmp - get_bits(gb, 2);
+                s->predictors[i] = get_code(gb, x) << (9 - s->size);
+            }
+        }
+
+        s->ncoeff[0] = s->predictors[0] << 6;
+        for (i = 1; i < s->nb_predictors; i++) {
+            int32_t *p1 = s->ncoeff;
+            int32_t *p2 = &s->ncoeff[i - 1];
+
+            for (j = 0; j < (i + 1) / 2; j++) {
+                x     = *p1 + (s->predictors[i] * *p2 + 256 >> 9);
+                *p2  += s->predictors[i] * *p1 + 256 >> 9;
+                *p1++ = x;
+                p2--;
+            }
+
+            s->ncoeff[i] = s->predictors[i] << 6;
+        }
+
+        x = -1 << (32 - (s->ared + 5));
+        y =  1 << ((s->ared + 5) - 1);
+        for (i = 0, j = s->nb_predictors - 1; i < s->nb_predictors / 2; i++, j--) {
+            tmp = y + s->ncoeff[j];
+            s->ncoeff[j] = -(x & -(y + s->ncoeff[i] >> 31) |
+                            (y + s->ncoeff[i]) >> (s->ared + 5));
+            s->ncoeff[i] = -(x & -(tmp >> 31) | (tmp >> s->ared + 5));
+        }
+
+        if ((ret = decode_m(s, &ptr[s->nb_predictors], subframe_size - s->nb_predictors)) < 0)
+            return ret;
+
+        for (i = 0; i < s->nb_predictors; i++)
+            s->f[i] = *ptr++ >> s->xred;
+
+        y    = FF_ARRAY_ELEMS(s->f) - s->nb_predictors;
+        x    = subframe_size - s->nb_predictors;
+        while (x > 0) {
+            if (y >= x)
+                tmp = x;
+            else
+                tmp = y;
+
+            for (i = 0; i < tmp; i++) {
+                int v, w, m;
+
+                v = 1 << (10 - s->ared - 1);
+                if (s->nb_predictors & 4) {
+                    for (j = 0; j < s->nb_predictors; j += 4) {
+                        v += s->f[i + j + 3] * s->ncoeff[j + 3] +
+                             s->f[i + j + 2] * s->ncoeff[j + 2] +
+                             s->f[i + j + 1] * s->ncoeff[j + 1] +
+                             s->f[i + j    ] * s->ncoeff[j    ];
+                    }
+                } else {
+                    for (j = 0; j < s->nb_predictors; j += 8) {
+                        v += s->f[i + j + 7] * s->ncoeff[j + 7] +
+                             s->f[i + j + 6] * s->ncoeff[j + 6] +
+                             s->f[i + j + 5] * s->ncoeff[j + 5] +
+                             s->f[i + j + 4] * s->ncoeff[j + 4] +
+                             s->f[i + j + 3] * s->ncoeff[j + 3] +
+                             s->f[i + j + 2] * s->ncoeff[j + 2] +
+                             s->f[i + j + 1] * s->ncoeff[j + 1] +
+                             s->f[i + j    ] * s->ncoeff[j    ];
+                    }
+                }
+                m = (-1 << (32 - (10 - s->ared))) & -(v >> 31) | (v >> 10 - s->ared);
+                m = av_clip(m, -8192, 8191);
+                w = (m << s->xred) - *ptr;
+                *ptr++ = w;
+                s->f[s->nb_predictors + i] = w >> s->xred;
+            }
+
+            x -= tmp;
+            if (x > 0)
+                memcpy(s->f, &s->f[y], 2 * s->nb_predictors);
+        }
+    } else {
+        ret = decode_m(s, ptr, subframe_size);
+    }
+
+    return ret;
+}
+
+static int decode_channel(TAKDecContext *s, int chan)
+{
+    AVCodecContext *avctx = s->avctx;
+    GetBitContext  *gb = &s->gb;
+    int32_t *p    = s->decode_buffer + chan * s->nb_samples;
+    int i, ret, prev_subframe_size = 0, subframe_size;
+    int left = s->nb_samples - 1;
+
+    s->sample_shift[chan] = get_b(gb);
+    if (s->sample_shift[chan] >= avctx->bits_per_coded_sample)
+        return AVERROR_INVALIDDATA;
+
+    *p++ = get_code(gb, avctx->bits_per_coded_sample - s->sample_shift[chan]);
+    s->lpc[chan] = get_bits(gb, 2);
+    s->nb_subframes = get_bits(gb, 3) + 1;
+
+    s->subframes[0] = 0;
+    if (s->nb_subframes > 1) {
+        if (get_bits_left(gb) < (s->nb_subframes - 1) * 6)
+            return AVERROR_INVALIDDATA;
+        for (i = 1; i < s->nb_subframes; i++) {
+            s->subframes[i] = get_bits(gb, 6);
+            if (s->subframes[i] <= s->subframes[i - 1])
+                return AVERROR_INVALIDDATA;
+        }
+    }
+
+    for (i = 1; i < s->nb_subframes; i++) {
+        subframe_size = (s->subframes[i] - s->subframes[i - 1]) * s->subframe_scale;
+        left -= subframe_size;
+        if (left < 0)
+            return AVERROR_INVALIDDATA;
+        if ((ret = decode_subframe(s, p, subframe_size, prev_subframe_size)) < 0)
+            return ret;
+        p += subframe_size;
+        prev_subframe_size = subframe_size;
+    }
+
+    subframe_size = s->nb_samples - 1 - s->subframes[i - 1] * s->subframe_scale;
+    left -= subframe_size;
+    if (left < 0)
+        return AVERROR_INVALIDDATA;
+    if ((ret = decode_subframe(s, p, subframe_size, prev_subframe_size)) < 0)
+        return ret;
+
+    return 0;
+}
+
+static int decorrelate(TAKDecContext *s, int c1, int c2, int length)
+{
+    GetBitContext  *gb = &s->gb;
+    int32_t *p1 = &s->decode_buffer[c1 * s->nb_samples + 1];
+    int32_t *p2 = &s->decode_buffer[c2 * s->nb_samples + 1];
+    int a, b, i, j, x, tmp;
+
+    if (s->dmode > 3) {
+        s->dshift = get_b(gb);
+        if (s->dmode > 5) {
+            if (get_bits1(gb))
+                s->nb_dcoeffs = 16;
+            else
+                s->nb_dcoeffs = 8;
+
+            s->dval1 = get_bits1(gb);
+            s->dval2 = get_bits1(gb);
+
+            for (i = 0; i < s->nb_dcoeffs; i++) {
+                if (!(i & 3))
+                    x = 14 - get_bits(gb, 3);
+                s->dcoeffs[i] = get_code(gb, x);
+            }
+        } else {
+            s->dfactor = get_code(gb, 10);
+        }
+    }
+
+    switch (s->dmode) {
+    case 1:
+        for (i = 0; i < length; i++, p1++, p2++)
+            *p2 += *p1;
+        break;
+    case 2:
+        for (i = 0; i < length; i++, p1++, p2++)
+            *p1 = *p2 - *p1;
+        break;
+    case 3:
+        for (i = 0; i < length; i++, p1++, p2++) {
+            x   = (*p2 & 1) + 2 * *p1;
+            *p1 = (  x - *p2) & 0x80000000 | (  x - *p2 >> 1);
+            *p2 = (*p2 + x  ) & 0x80000000 | (*p2 + x   >> 1);
+        }
+        break;
+    case 4:
+        FFSWAP(int32_t *, p1, p2);
+    case 5:
+        if (s->dshift)
+            tmp = -1 << (32 - s->dshift);
+        else
+            tmp = 0;
+
+        for (i = 0; i < length; i++, p1++, p2++) {
+            x   = *p2 >> s->dshift;;
+            *p1 = ((-((s->dfactor * (tmp & -(*p2 >> 31) | x) + 128) >> 31) &
+                    0xFF000000 |
+                  ((   s->dfactor * (tmp & -(*p2 >> 31) | x) + 128) >> 8)) <<
+                   s->dshift) - *p1;
+        }
+        break;
+    case 6:
+        FFSWAP(int32_t *, p1, p2);
+    case 7:
+        if (length < 256)
+            return AVERROR_INVALIDDATA;
+
+        a = s->nb_dcoeffs / 2;
+        b = length - (s->nb_dcoeffs - 1);
+
+        if (s->dval1) {
+            for (i = 0; i < a; i++)
+                p1[i] += p2[i];
+        }
+
+        if (s->dval2) {
+            x = a + b;
+            for (i = 0; i < length - x; i++)
+                p1[x + i] += p2[x + i];
+        }
+
+        for (i = 0; i < s->nb_dcoeffs; i++)
+            s->f[i] = *p2++ >> s->dshift;
+
+        p1 += a;
+        x = FF_ARRAY_ELEMS(s->f) - s->nb_dcoeffs;
+        for (; b > 0; b -= tmp) {
+            if (b <= x)
+                tmp = b;
+            else
+                tmp = x;
+
+            for (i = 0; i < tmp; i++)
+                s->f[s->nb_dcoeffs + i] = *p2++ >> s->dshift;
+
+            for (i = 0; i < tmp; i++) {
+                int v, w, m;
+
+                v = 1 << 9;
+                for (j = 0; j < s->nb_dcoeffs; j += 8) {
+                    v += s->f[i + j + 7] * s->dcoeffs[j + 7] +
+                         s->f[i + j + 6] * s->dcoeffs[j + 6] +
+                         s->f[i + j + 5] * s->dcoeffs[j + 5] +
+                         s->f[i + j + 4] * s->dcoeffs[j + 4] +
+                         s->f[i + j + 3] * s->dcoeffs[j + 3] +
+                         s->f[i + j + 2] * s->dcoeffs[j + 2] +
+                         s->f[i + j + 1] * s->dcoeffs[j + 1] +
+                         s->f[i + j    ] * s->dcoeffs[j    ];
+                }
+
+                m = (-1 << 22) & -(v >> 31) | (v >> 10);
+                m = av_clip(m, -8192, 8191);
+                w = (m << s->dshift) - *p1;
+                *p1++ = w;
+            }
+
+            memcpy(s->f, &s->f[tmp], 2 * s->nb_dcoeffs);
+        }
+        break;
+    }
+
+    return 0;
+}
+
+static int tak_decode_frame(AVCodecContext *avctx, void *data,
+                            int *got_frame_ptr, AVPacket *pkt)
+{
+    TAKDecContext *s = avctx->priv_data;
+    GetBitContext  *gb = &s->gb;
+    int chan, i, ret;
+    int32_t *p;
+
+    if (pkt->size < TAK_FRAME_HEADER_BYTES)
+        return AVERROR_INVALIDDATA;
+
+    init_get_bits(gb, pkt->data, pkt->size * 8);
+
+    if ((ret = ff_tak_decode_frame_header(avctx, gb, &s->ti)) < 0)
+        return ret;
+
+    if (avctx->err_recognition & AV_EF_CRCCHECK) {
+        if (tak_check_crc(s, pkt->data, get_bits_count(gb) / 8) ||
+            tak_check_crc(s, pkt->data + get_bits_count(gb) / 8,
+                             pkt->size - get_bits_count(gb) / 8))
+            return AVERROR_INVALIDDATA;
+    }
+
+    s->nb_samples = s->ti.last_frame_samples ? s->ti.last_frame_samples : s->ti.frame_samples;
+    tak_set_bps(avctx);
+
+    s->frame.nb_samples = s->nb_samples;
+    if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0)
+        return ret;
+
+    if (avctx->bits_per_coded_sample <= 16) {
+        av_fast_malloc(&s->decode_buffer, &s->decode_buffer_size,
+                       sizeof(*s->decode_buffer) * s->nb_samples * avctx->channels +
+                       FF_INPUT_BUFFER_PADDING_SIZE);
+        if (!s->decode_buffer)
+            return AVERROR(ENOMEM);
+    } else {
+        s->decode_buffer = (int32_t *)s->frame.data[0];
+    }
+
+    p = s->decode_buffer;
+    if (s->nb_samples < 16) {
+        for (chan = 0; chan < avctx->channels; chan++)
+            for (i = 0; i < s->nb_samples; i++)
+                *p++ = get_code(gb, avctx->bits_per_coded_sample);
+    } else {
+        if (s->ti.codec == 2) {
+            for (chan = 0; chan < avctx->channels; chan++) {
+                if (ret = decode_channel(s, chan))
+                    return ret;
+            }
+
+            if (avctx->channels == 2) {
+                s->nb_subframes = get_bits(gb, 1) + 1;
+                if (s->nb_subframes > 1)
+                    s->subframes[1] = get_bits(gb, 6);
+
+                s->dmode = get_bits(gb, 3);
+                if (ret = decorrelate(s, 0, 1, s->nb_samples - 1))
+                    return ret;
+            }
+        } else if (s->ti.codec == 4) {
+            if (get_bits1(gb)) {
+                int ch_mask = 0;
+
+                chan = get_bits(gb, 4) + 1;
+                if (chan > avctx->channels)
+                    return AVERROR_INVALIDDATA;
+
+                for (i = 0; i < chan; i++) {
+                    int nbit = get_bits(gb, 4);
+
+                    if (nbit >= avctx->channels)
+                        return AVERROR_INVALIDDATA;
+                    if (ch_mask & 1 << nbit)
+                        return AVERROR_INVALIDDATA;
+
+                    s->mcdparams[i].present = get_bits1(gb);
+                    if (s->mcdparams[i].present) {
+                        s->mcdparams[i].index = get_bits(gb, 2);
+                        s->mcdparams[i].chan2 = get_bits(gb, 4);
+                        if (s->mcdparams[i].index == 1) {
+                            if ((nbit == s->mcdparams[i].chan2) ||
+                                (ch_mask & 1 << s->mcdparams[i].chan2))
+                                return AVERROR_INVALIDDATA;
+
+                            ch_mask |= 1 << s->mcdparams[i].chan2;
+                        } else if (!(ch_mask & 1 << s->mcdparams[i].chan2)) {
+                            return AVERROR_INVALIDDATA;
+                        }
+                    }
+                    s->mcdparams[i].chan1 = nbit;
+
+                    ch_mask |= 1 << nbit;
+                }
+            } else {
+                chan = avctx->channels;
+                for (i = 0; i < chan; i++) {
+                    s->mcdparams[i].present = 0;
+                    s->mcdparams[i].chan1   = i;
+                }
+            }
+
+            for (i = 0; i < chan; i++) {
+                if (s->mcdparams[i].present && s->mcdparams[i].index == 1) {
+                    if (ret = decode_channel(s, s->mcdparams[i].chan2))
+                        return ret;
+                }
+
+                if (ret = decode_channel(s, s->mcdparams[i].chan1))
+                    return ret;
+
+                if (s->mcdparams[i].present) {
+                    s->dmode = mc_dmodes[s->mcdparams[i].index];
+                    if (ret = decorrelate(s, s->mcdparams[i].chan2,
+                                             s->mcdparams[i].chan1,
+                                             s->nb_samples - 1))
+                        return ret;
+                }
+            }
+        }
+
+        for (chan = 0; chan < avctx->channels; chan++) {
+            p = &s->decode_buffer[chan * s->nb_samples];
+            decode_lpc(p, s->lpc[chan], s->nb_samples);
+
+            if (s->sample_shift[chan] > 0) {
+                for (i = 0; i < s->nb_samples; i++)
+                    *p++ <<= s->sample_shift[chan];
+            }
+        }
+    }
+
+    // convert to output buffer
+    p = s->decode_buffer;
+    switch (avctx->bits_per_coded_sample) {
+    case 8:
+        for (chan = 0; chan < avctx->channels; chan++) {
+            uint8_t *samples = (uint8_t *)s->frame.data[chan];
+            for (i = 0; i < s->nb_samples; i++, p++)
+                *samples++ = *p + 0x80;
+        }
+        break;
+    case 16:
+        for (chan = 0; chan < avctx->channels; chan++) {
+            int16_t *samples = (int16_t *)s->frame.data[chan];
+            for (i = 0; i < s->nb_samples; i++, p++)
+                *samples++ = *p;
+        }
+        break;
+    case 24:
+        for (chan = 0; chan < avctx->channels; chan++) {
+            int32_t *samples = (int32_t *)s->frame.data[chan];
+            for (i = 0; i < s->nb_samples; i++, p++)
+                *samples++ <<= 8;
+        }
+        s->decode_buffer = NULL;
+        break;
+    }
+
+    align_get_bits(gb);
+    skip_bits(gb, 24);
+    if (get_bits_left(gb) < 0)
+        av_log(avctx, AV_LOG_DEBUG, "overread\n");
+    else if (get_bits_left(gb) > 0)
+        av_log(avctx, AV_LOG_DEBUG, "underread\n");
+
+    *got_frame_ptr   = 1;
+    *(AVFrame *)data = s->frame;
+
+    return pkt->size;
+}
+
+static av_cold int tak_decode_close(AVCodecContext *avctx)
+{
+    TAKDecContext *s = avctx->priv_data;
+
+    av_freep(&s->decode_buffer);
+
+    return 0;
+}
+
+AVCodec ff_tak_decoder = {
+    .name           = "tak",
+    .type           = AVMEDIA_TYPE_AUDIO,
+    .id             = AV_CODEC_ID_TAK,
+    .priv_data_size = sizeof(TAKDecContext),
+    .init           = tak_decode_init,
+    .close          = tak_decode_close,
+    .decode         = tak_decode_frame,
+    .capabilities   = CODEC_CAP_DR1,
+    .long_name      = NULL_IF_CONFIG_SMALL("TAK (Tom's lossless Audio Kompressor)"),
+};
diff --git a/libavformat/Makefile b/libavformat/Makefile
index 92adfcd..3356bc3 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -332,6 +332,7 @@ OBJS-$(CONFIG_STR_DEMUXER)               += psxstr.o
 OBJS-$(CONFIG_SUBVIEWER_DEMUXER)         += subviewerdec.o
 OBJS-$(CONFIG_SWF_DEMUXER)               += swfdec.o swf.o
 OBJS-$(CONFIG_SWF_MUXER)                 += swfenc.o swf.o
+OBJS-$(CONFIG_TAK_DEMUXER)               += takdec.o apetag.o img2.o rawdec.o
 OBJS-$(CONFIG_THP_DEMUXER)               += thp.o
 OBJS-$(CONFIG_TIERTEXSEQ_DEMUXER)        += tiertexseq.o
 OBJS-$(CONFIG_MKVTIMESTAMP_V2_MUXER)     += mkvtimestamp_v2.o
diff --git a/libavformat/allformats.c b/libavformat/allformats.c
index 36b6988..f1e8edc 100644
--- a/libavformat/allformats.c
+++ b/libavformat/allformats.c
@@ -233,6 +233,7 @@ void av_register_all(void)
     REGISTER_DEMUXER  (STR, str);
     REGISTER_DEMUXER  (SUBVIEWER, subviewer);
     REGISTER_MUXDEMUX (SWF, swf);
+    REGISTER_DEMUXER  (TAK, tak);
     REGISTER_MUXER    (TG2, tg2);
     REGISTER_MUXER    (TGP, tgp);
     REGISTER_DEMUXER  (THP, thp);
diff --git a/libavformat/takdec.c b/libavformat/takdec.c
new file mode 100644
index 0000000..2cecda0
--- /dev/null
+++ b/libavformat/takdec.c
@@ -0,0 +1,141 @@
+/*
+ * Raw TAK demuxer
+ * Copyright (c) 2012 Paul B Mahol
+ *
+ * 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 "libavcodec/tak.h"
+#include "avformat.h"
+#include "internal.h"
+#include "rawdec.h"
+#include "apetag.h"
+
+static int tak_probe(AVProbeData *p)
+{
+    if (!memcmp(p->buf, "tBaK", 4))
+        return AVPROBE_SCORE_MAX / 2;
+    return 0;
+}
+
+static int tak_read_header(AVFormatContext *s)
+{
+    AVIOContext *pb = s->pb;
+    GetBitContext gb;
+    AVStream *st;
+    uint8_t *buffer = NULL;
+    int ret;
+
+    st = avformat_new_stream(s, 0);
+    if (!st)
+        return AVERROR(ENOMEM);
+    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
+    st->codec->codec_id   = AV_CODEC_ID_TAK;
+    st->need_parsing      = AVSTREAM_PARSE_FULL_RAW;
+
+    if (avio_rl32(pb) != MKTAG('t', 'B', 'a', 'K')) {
+        avio_seek(pb, -4, SEEK_CUR);
+        return 0;
+    }
+
+    while (!url_feof(pb)) {
+        int metadata_type, metadata_size;
+
+        metadata_type = avio_r8(pb) & 0x7f;
+        metadata_size = avio_rl24(pb);
+
+        switch (metadata_type) {
+        case TAK_METADATA_STREAMINFO:
+        case TAK_METADATA_ENCODER:
+            buffer = av_malloc(metadata_size + FF_INPUT_BUFFER_PADDING_SIZE);
+            if (!buffer)
+                return AVERROR(ENOMEM);
+
+            if (avio_read(pb, buffer, metadata_size) != metadata_size) {
+                av_freep(&buffer);
+                return AVERROR(EIO);
+            }
+
+            init_get_bits(&gb, buffer, metadata_size * 8);
+            break;
+        case TAK_METADATA_MD5: {
+            uint8_t md5[16];
+            int i;
+
+            if (metadata_size != 19)
+                return AVERROR_INVALIDDATA;
+            avio_read(pb, md5, 16);
+            avio_skip(pb, 3);
+            av_log(s, AV_LOG_VERBOSE, "MD5=");
+            for (i = 0; i < 16; i++)
+                av_log(s, AV_LOG_VERBOSE, "%02x", md5[i]);
+            av_log(s, AV_LOG_VERBOSE, "\n");
+            break;
+            }
+        case TAK_METADATA_END:
+            if (pb->seekable) {
+                int64_t curpos = avio_tell(pb);
+
+                ff_ape_parse_tag(s);
+                avio_seek(pb, curpos, SEEK_SET);
+            }
+            return 0;
+            break;
+        default:
+            ret = avio_skip(s->pb, metadata_size);
+            if (ret < 0)
+                return ret;
+        }
+
+        if (metadata_type == TAK_METADATA_STREAMINFO) {
+            TAKStreamInfo ti;
+
+            if ((ret = avpriv_tak_parse_streaminfo(s, &gb, &ti)) < 0)
+                return ret;
+
+            if (ti.samples > 0)
+                st->duration = ti.samples;
+            st->codec->extradata             = buffer;
+            st->codec->extradata_size        = metadata_size;
+            st->codec->bits_per_coded_sample = ti.bps;
+            if (ti.ch_layout)
+                st->codec->channel_layout = ti.ch_layout;
+            st->codec->sample_rate = ti.sample_rate;
+            st->codec->channels    = ti.channels;
+            st->start_time = 0;
+            buffer = NULL;
+            avpriv_set_pts_info(st, 64, 1, st->codec->sample_rate);
+        } else if (metadata_type == TAK_METADATA_ENCODER) {
+            av_log(s, AV_LOG_VERBOSE, "encoder version: %0X\n",
+                   get_bits_long(&gb, TAK_ENCODER_VERSION_BITS));
+            av_freep(&buffer);
+        }
+    }
+
+    return AVERROR_EOF;
+}
+
+AVInputFormat ff_tak_demuxer = {
+    .name           = "tak",
+    .long_name      = NULL_IF_CONFIG_SMALL("raw TAK"),
+    .read_probe     = tak_probe,
+    .read_header    = tak_read_header,
+    .read_packet    = ff_raw_read_partial_packet,
+    .flags          = AVFMT_GENERIC_INDEX,
+    .extensions     = "tak",
+    .raw_codec_id   = AV_CODEC_ID_TAK,
+};
-- 
1.7.11.4



More information about the ffmpeg-devel mailing list