1/*
2 * RoQ audio encoder
3 *
4 * Copyright (c) 2005 Eric Lasota
5 *    Based on RoQ specs (c)2001 Tim Ferguson
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#include "avcodec.h"
25#include "bytestream.h"
26#include "codec_internal.h"
27#include "encode.h"
28#include "mathops.h"
29
30#define ROQ_FRAME_SIZE           735
31#define ROQ_HEADER_SIZE   8
32
33#define MAX_DPCM (127*127)
34
35
36typedef struct ROQDPCMContext {
37    short lastSample[2];
38    int input_frames;
39    int buffered_samples;
40    int16_t *frame_buffer;
41    int64_t first_pts;
42} ROQDPCMContext;
43
44
45static av_cold int roq_dpcm_encode_close(AVCodecContext *avctx)
46{
47    ROQDPCMContext *context = avctx->priv_data;
48
49    av_freep(&context->frame_buffer);
50
51    return 0;
52}
53
54static av_cold int roq_dpcm_encode_init(AVCodecContext *avctx)
55{
56    ROQDPCMContext *context = avctx->priv_data;
57    int channels = avctx->ch_layout.nb_channels;
58
59    if (channels > 2) {
60        av_log(avctx, AV_LOG_ERROR, "Audio must be mono or stereo\n");
61        return AVERROR(EINVAL);
62    }
63    if (avctx->sample_rate != 22050) {
64        av_log(avctx, AV_LOG_ERROR, "Audio must be 22050 Hz\n");
65        return AVERROR(EINVAL);
66    }
67
68    avctx->frame_size = ROQ_FRAME_SIZE;
69    avctx->bit_rate   = (ROQ_HEADER_SIZE + ROQ_FRAME_SIZE * channels) *
70                        (22050 / ROQ_FRAME_SIZE) * 8;
71
72    context->frame_buffer = av_malloc(8 * ROQ_FRAME_SIZE * channels *
73                                      sizeof(*context->frame_buffer));
74    if (!context->frame_buffer)
75        return AVERROR(ENOMEM);
76
77    context->lastSample[0] = context->lastSample[1] = 0;
78
79    return 0;
80}
81
82static unsigned char dpcm_predict(short *previous, short current)
83{
84    int diff;
85    int negative;
86    int result;
87    int predicted;
88
89    diff = current - *previous;
90
91    negative = diff<0;
92    diff = FFABS(diff);
93
94    if (diff >= MAX_DPCM)
95        result = 127;
96    else {
97        result = ff_sqrt(diff);
98        result += diff > result*result+result;
99    }
100
101    /* See if this overflows */
102 retry:
103    diff = result*result;
104    if (negative)
105        diff = -diff;
106    predicted = *previous + diff;
107
108    /* If it overflows, back off a step */
109    if (predicted > 32767 || predicted < -32768) {
110        result--;
111        goto retry;
112    }
113
114    /* Add the sign bit */
115    result |= negative << 7;   //if (negative) result |= 128;
116
117    *previous = predicted;
118
119    return result;
120}
121
122static int roq_dpcm_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
123                                 const AVFrame *frame, int *got_packet_ptr)
124{
125    int i, stereo, data_size, ret;
126    const int16_t *in = frame ? (const int16_t *)frame->data[0] : NULL;
127    int channels = avctx->ch_layout.nb_channels;
128    uint8_t *out;
129    ROQDPCMContext *context = avctx->priv_data;
130
131    stereo = (channels == 2);
132
133    if (!in && context->input_frames >= 8)
134        return 0;
135
136    if (in && context->input_frames < 8) {
137        memcpy(&context->frame_buffer[context->buffered_samples * channels],
138               in, avctx->frame_size * channels * sizeof(*in));
139        context->buffered_samples += avctx->frame_size;
140        if (context->input_frames == 0)
141            context->first_pts = frame->pts;
142        if (context->input_frames < 7) {
143            context->input_frames++;
144            return 0;
145        }
146    }
147    if (context->input_frames < 8)
148        in = context->frame_buffer;
149
150    if (stereo) {
151        context->lastSample[0] &= 0xFF00;
152        context->lastSample[1] &= 0xFF00;
153    }
154
155    if (context->input_frames == 7)
156        data_size = channels * context->buffered_samples;
157    else
158        data_size = channels * avctx->frame_size;
159
160    ret = ff_get_encode_buffer(avctx, avpkt, ROQ_HEADER_SIZE + data_size, 0);
161    if (ret < 0)
162        return ret;
163    out = avpkt->data;
164
165    bytestream_put_byte(&out, stereo ? 0x21 : 0x20);
166    bytestream_put_byte(&out, 0x10);
167    bytestream_put_le32(&out, data_size);
168
169    if (stereo) {
170        bytestream_put_byte(&out, (context->lastSample[1])>>8);
171        bytestream_put_byte(&out, (context->lastSample[0])>>8);
172    } else
173        bytestream_put_le16(&out, context->lastSample[0]);
174
175    /* Write the actual samples */
176    for (i = 0; i < data_size; i++)
177        *out++ = dpcm_predict(&context->lastSample[i & 1], *in++);
178
179    avpkt->pts      = context->input_frames <= 7 ? context->first_pts : frame->pts;
180    avpkt->duration = data_size / channels;
181
182    context->input_frames++;
183    if (!in)
184        context->input_frames = FFMAX(context->input_frames, 8);
185
186    *got_packet_ptr = 1;
187    return 0;
188}
189
190const FFCodec ff_roq_dpcm_encoder = {
191    .p.name         = "roq_dpcm",
192    .p.long_name    = NULL_IF_CONFIG_SMALL("id RoQ DPCM"),
193    .p.type         = AVMEDIA_TYPE_AUDIO,
194    .p.id           = AV_CODEC_ID_ROQ_DPCM,
195    .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY,
196    .priv_data_size = sizeof(ROQDPCMContext),
197    .init           = roq_dpcm_encode_init,
198    FF_CODEC_ENCODE_CB(roq_dpcm_encode_frame),
199    .close          = roq_dpcm_encode_close,
200    .p.sample_fmts  = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
201                                                     AV_SAMPLE_FMT_NONE },
202    .caps_internal  = FF_CODEC_CAP_INIT_THREADSAFE,
203};
204