]> git.sesse.net Git - ffmpeg/blob - libavcodec/ralf.c
x86: rename libavutil/x86_cpu.h to libavutil/x86/asm.h
[ffmpeg] / libavcodec / ralf.c
1 /*
2  * RealAudio Lossless decoder
3  *
4  * Copyright (c) 2012 Konstantin Shishkov
5  *
6  * This file is part of Libav.
7  *
8  * Libav 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.
12  *
13  * Libav 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.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with Libav; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * This is a decoder for Real Audio Lossless format.
26  * Dedicated to the mastermind behind it, Ralph Wiggum.
27  */
28
29 #include "avcodec.h"
30 #include "get_bits.h"
31 #include "golomb.h"
32 #include "unary.h"
33 #include "libavutil/audioconvert.h"
34 #include "ralfdata.h"
35
36 #define FILTER_NONE 0
37 #define FILTER_RAW  642
38
39 typedef struct VLCSet {
40     VLC filter_params;
41     VLC bias;
42     VLC coding_mode;
43     VLC filter_coeffs[10][11];
44     VLC short_codes[15];
45     VLC long_codes[125];
46 } VLCSet;
47
48 #define RALF_MAX_PKT_SIZE 8192
49
50 typedef struct RALFContext {
51     AVFrame frame;
52
53     int version;
54     int max_frame_size;
55     VLCSet sets[3];
56     int32_t channel_data[2][4096];
57
58     int     filter_params;   ///< combined filter parameters for the current channel data
59     int     filter_length;   ///< length of the filter for the current channel data
60     int     filter_bits;     ///< filter precision for the current channel data
61     int32_t filter[64];
62
63     int     bias[2];         ///< a constant value added to channel data after filtering
64
65     int num_blocks;          ///< number of blocks inside the frame
66     int sample_offset;
67     int block_size[1 << 12]; ///< size of the blocks
68     int block_pts[1 << 12];  ///< block start time (in milliseconds)
69
70     uint8_t pkt[16384];
71     int     has_pkt;
72 } RALFContext;
73
74 #define MAX_ELEMS 644 // no RALF table uses more than that
75
76 static int init_ralf_vlc(VLC *vlc, const uint8_t *data, int elems)
77 {
78     uint8_t  lens[MAX_ELEMS];
79     uint16_t codes[MAX_ELEMS];
80     int counts[17], prefixes[18];
81     int i, cur_len;
82     int max_bits = 0;
83     int nb = 0;
84
85     for (i = 0; i <= 16; i++)
86         counts[i] = 0;
87     for (i = 0; i < elems; i++) {
88         cur_len  = (nb ? *data & 0xF : *data >> 4) + 1;
89         counts[cur_len]++;
90         max_bits = FFMAX(max_bits, cur_len);
91         lens[i]  = cur_len;
92         data    += nb;
93         nb      ^= 1;
94     }
95     prefixes[1] = 0;
96     for (i = 1; i <= 16; i++)
97         prefixes[i + 1] = (prefixes[i] + counts[i]) << 1;
98
99     for (i = 0; i < elems; i++)
100         codes[i] = prefixes[lens[i]]++;
101
102     return ff_init_vlc_sparse(vlc, FFMIN(max_bits, 9), elems,
103                               lens, 1, 1, codes, 2, 2, NULL, 0, 0, 0);
104 }
105
106 static av_cold int decode_close(AVCodecContext *avctx)
107 {
108     RALFContext *ctx = avctx->priv_data;
109     int i, j, k;
110
111     for (i = 0; i < 3; i++) {
112         ff_free_vlc(&ctx->sets[i].filter_params);
113         ff_free_vlc(&ctx->sets[i].bias);
114         ff_free_vlc(&ctx->sets[i].coding_mode);
115         for (j = 0; j < 10; j++)
116             for (k = 0; k < 11; k++)
117                 ff_free_vlc(&ctx->sets[i].filter_coeffs[j][k]);
118         for (j = 0; j < 15; j++)
119             ff_free_vlc(&ctx->sets[i].short_codes[j]);
120         for (j = 0; j < 125; j++)
121             ff_free_vlc(&ctx->sets[i].long_codes[j]);
122     }
123
124     return 0;
125 }
126
127 static av_cold int decode_init(AVCodecContext *avctx)
128 {
129     RALFContext *ctx = avctx->priv_data;
130     int i, j, k;
131     int ret;
132
133     if (avctx->extradata_size < 24 || memcmp(avctx->extradata, "LSD:", 4)) {
134         av_log(avctx, AV_LOG_ERROR, "Extradata is not groovy, dude\n");
135         return AVERROR_INVALIDDATA;
136     }
137
138     ctx->version = AV_RB16(avctx->extradata + 4);
139     if (ctx->version != 0x103) {
140         av_log_ask_for_sample(avctx, "unknown version %X\n", ctx->version);
141         return AVERROR_PATCHWELCOME;
142     }
143
144     avctx->channels    = AV_RB16(avctx->extradata + 8);
145     avctx->sample_rate = AV_RB32(avctx->extradata + 12);
146     if (avctx->channels < 1 || avctx->channels > 2
147         || avctx->sample_rate < 8000 || avctx->sample_rate > 96000) {
148         av_log(avctx, AV_LOG_ERROR, "Invalid coding parameters %d Hz %d ch\n",
149                avctx->sample_rate, avctx->channels);
150         return AVERROR_INVALIDDATA;
151     }
152     avctx->sample_fmt     = AV_SAMPLE_FMT_S16;
153     avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO
154                                                    : AV_CH_LAYOUT_MONO;
155
156     avcodec_get_frame_defaults(&ctx->frame);
157     avctx->coded_frame = &ctx->frame;
158
159     ctx->max_frame_size = AV_RB32(avctx->extradata + 16);
160     if (ctx->max_frame_size > (1 << 20) || !ctx->max_frame_size) {
161         av_log(avctx, AV_LOG_ERROR, "invalid frame size %d\n",
162                ctx->max_frame_size);
163     }
164     ctx->max_frame_size = FFMAX(ctx->max_frame_size, avctx->sample_rate);
165
166     for (i = 0; i < 3; i++) {
167         ret = init_ralf_vlc(&ctx->sets[i].filter_params, filter_param_def[i],
168                             FILTERPARAM_ELEMENTS);
169         if (ret < 0) {
170             decode_close(avctx);
171             return ret;
172         }
173         ret = init_ralf_vlc(&ctx->sets[i].bias, bias_def[i], BIAS_ELEMENTS);
174         if (ret < 0) {
175             decode_close(avctx);
176             return ret;
177         }
178         ret = init_ralf_vlc(&ctx->sets[i].coding_mode, coding_mode_def[i],
179                             CODING_MODE_ELEMENTS);
180         if (ret < 0) {
181             decode_close(avctx);
182             return ret;
183         }
184         for (j = 0; j < 10; j++) {
185             for (k = 0; k < 11; k++) {
186                 ret = init_ralf_vlc(&ctx->sets[i].filter_coeffs[j][k],
187                                     filter_coeffs_def[i][j][k],
188                                     FILTER_COEFFS_ELEMENTS);
189                 if (ret < 0) {
190                     decode_close(avctx);
191                     return ret;
192                 }
193             }
194         }
195         for (j = 0; j < 15; j++) {
196             ret = init_ralf_vlc(&ctx->sets[i].short_codes[j],
197                                 short_codes_def[i][j], SHORT_CODES_ELEMENTS);
198             if (ret < 0) {
199                 decode_close(avctx);
200                 return ret;
201             }
202         }
203         for (j = 0; j < 125; j++) {
204             ret = init_ralf_vlc(&ctx->sets[i].long_codes[j],
205                                 long_codes_def[i][j], LONG_CODES_ELEMENTS);
206             if (ret < 0) {
207                 decode_close(avctx);
208                 return ret;
209             }
210         }
211     }
212
213     return 0;
214 }
215
216 static inline int extend_code(GetBitContext *gb, int val, int range, int bits)
217 {
218     if (val == 0) {
219         val = -range - get_ue_golomb(gb);
220     } else if (val == range * 2) {
221         val =  range + get_ue_golomb(gb);
222     } else {
223         val -= range;
224     }
225     if (bits)
226         val = (val << bits) | get_bits(gb, bits);
227     return val;
228 }
229
230 static int decode_channel(RALFContext *ctx, GetBitContext *gb, int ch,
231                           int length, int mode, int bits)
232 {
233     int i, t;
234     int code_params;
235     VLCSet *set = ctx->sets + mode;
236     VLC *code_vlc; int range, range2, add_bits;
237     int *dst = ctx->channel_data[ch];
238
239     ctx->filter_params = get_vlc2(gb, set->filter_params.table, 9, 2);
240     ctx->filter_bits   = (ctx->filter_params - 2) >> 6;
241     ctx->filter_length = ctx->filter_params - (ctx->filter_bits << 6) - 1;
242
243     if (ctx->filter_params == FILTER_RAW) {
244         for (i = 0; i < length; i++)
245             dst[i] = get_bits(gb, bits);
246         ctx->bias[ch] = 0;
247         return 0;
248     }
249
250     ctx->bias[ch] = get_vlc2(gb, set->bias.table, 9, 2);
251     ctx->bias[ch] = extend_code(gb, ctx->bias[ch], 127, 4);
252
253     if (ctx->filter_params == FILTER_NONE) {
254         memset(dst, 0, sizeof(*dst) * length);
255         return 0;
256     }
257
258     if (ctx->filter_params > 1) {
259         int cmode = 0, coeff = 0;
260         VLC *vlc = set->filter_coeffs[ctx->filter_bits] + 5;
261
262         add_bits = ctx->filter_bits;
263
264         for (i = 0; i < ctx->filter_length; i++) {
265             t = get_vlc2(gb, vlc[cmode].table, vlc[cmode].bits, 2);
266             t = extend_code(gb, t, 21, add_bits);
267             if (!cmode)
268                 coeff -= 12 << add_bits;
269             coeff = t - coeff;
270             ctx->filter[i] = coeff;
271
272             cmode = coeff >> add_bits;
273             if (cmode < 0) {
274                 cmode = -1 - av_log2(-cmode);
275                 if (cmode < -5)
276                     cmode = -5;
277             } else if (cmode > 0) {
278                 cmode =  1 + av_log2(cmode);
279                 if (cmode > 5)
280                     cmode = 5;
281             }
282         }
283     }
284
285     code_params = get_vlc2(gb, set->coding_mode.table, set->coding_mode.bits, 2);
286     if (code_params >= 15) {
287         add_bits = av_clip((code_params / 5 - 3) / 2, 0, 10);
288         if (add_bits > 9 && (code_params % 5) != 2)
289             add_bits--;
290         range    = 10;
291         range2   = 21;
292         code_vlc = set->long_codes + code_params - 15;
293     } else {
294         add_bits = 0;
295         range    = 6;
296         range2   = 13;
297         code_vlc = set->short_codes + code_params;
298     }
299
300     for (i = 0; i < length; i += 2) {
301         int code1, code2;
302
303         t = get_vlc2(gb, code_vlc->table, code_vlc->bits, 2);
304         code1 = t / range2;
305         code2 = t % range2;
306         dst[i]     = extend_code(gb, code1, range, 0) << add_bits;
307         dst[i + 1] = extend_code(gb, code2, range, 0) << add_bits;
308         if (add_bits) {
309             dst[i]     |= get_bits(gb, add_bits);
310             dst[i + 1] |= get_bits(gb, add_bits);
311         }
312     }
313
314     return 0;
315 }
316
317 static void apply_lpc(RALFContext *ctx, int ch, int length, int bits)
318 {
319     int i, j, acc;
320     int *audio = ctx->channel_data[ch];
321     int bias = 1 << (ctx->filter_bits - 1);
322     int max_clip = (1 << bits) - 1, min_clip = -max_clip - 1;
323
324     for (i = 1; i < length; i++) {
325         int flen = FFMIN(ctx->filter_length, i);
326
327         acc = 0;
328         for (j = 0; j < flen; j++)
329             acc += ctx->filter[j] * audio[i - j - 1];
330         if (acc < 0) {
331             acc = (acc + bias - 1) >> ctx->filter_bits;
332             acc = FFMAX(acc, min_clip);
333         } else {
334             acc = (acc + bias) >> ctx->filter_bits;
335             acc = FFMIN(acc, max_clip);
336         }
337         audio[i] += acc;
338     }
339 }
340
341 static int decode_block(AVCodecContext *avctx, GetBitContext *gb, int16_t *dst)
342 {
343     RALFContext *ctx = avctx->priv_data;
344     int len, ch, ret;
345     int dmode, mode[2], bits[2];
346     int *ch0, *ch1;
347     int i, t, t2;
348
349     len = 12 - get_unary(gb, 0, 6);
350
351     if (len <= 7) len ^= 1; // codes for length = 6 and 7 are swapped
352     len = 1 << len;
353
354     if (ctx->sample_offset + len > ctx->max_frame_size) {
355         av_log(avctx, AV_LOG_ERROR,
356                "Decoder's stomach is crying, it ate too many samples\n");
357         return AVERROR_INVALIDDATA;
358     }
359
360     if (avctx->channels > 1)
361         dmode = get_bits(gb, 2) + 1;
362     else
363         dmode = 0;
364
365     mode[0] = (dmode == 4) ? 1 : 0;
366     mode[1] = (dmode >= 2) ? 2 : 0;
367     bits[0] = 16;
368     bits[1] = (mode[1] == 2) ? 17 : 16;
369
370     for (ch = 0; ch < avctx->channels; ch++) {
371         if ((ret = decode_channel(ctx, gb, ch, len, mode[ch], bits[ch])) < 0)
372             return ret;
373         if (ctx->filter_params > 1 && ctx->filter_params != FILTER_RAW) {
374             ctx->filter_bits += 3;
375             apply_lpc(ctx, ch, len, bits[ch]);
376         }
377         if (get_bits_left(gb) < 0)
378             return AVERROR_INVALIDDATA;
379     }
380     ch0 = ctx->channel_data[0];
381     ch1 = ctx->channel_data[1];
382     switch (dmode) {
383     case 0:
384         for (i = 0; i < len; i++)
385             *dst++ = ch0[i] + ctx->bias[0];
386         break;
387     case 1:
388         for (i = 0; i < len; i++) {
389             *dst++ = ch0[i] + ctx->bias[0];
390             *dst++ = ch1[i] + ctx->bias[1];
391         }
392         break;
393     case 2:
394         for (i = 0; i < len; i++) {
395             ch0[i] += ctx->bias[0];
396             *dst++ = ch0[i];
397             *dst++ = ch0[i] - (ch1[i] + ctx->bias[1]);
398         }
399         break;
400     case 3:
401         for (i = 0; i < len; i++) {
402             t  = ch0[i] + ctx->bias[0];
403             t2 = ch1[i] + ctx->bias[1];
404             *dst++ = t + t2;
405             *dst++ = t;
406         }
407         break;
408     case 4:
409         for (i = 0; i < len; i++) {
410             t  =   ch1[i] + ctx->bias[1];
411             t2 = ((ch0[i] + ctx->bias[0]) << 1) | (t & 1);
412             *dst++ = (t2 + t) / 2;
413             *dst++ = (t2 - t) / 2;
414         }
415         break;
416     }
417
418     ctx->sample_offset += len;
419
420     return 0;
421 }
422
423 static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr,
424                         AVPacket *avpkt)
425 {
426     RALFContext *ctx = avctx->priv_data;
427     int16_t *samples;
428     int ret;
429     GetBitContext gb;
430     int table_size, table_bytes, i;
431     const uint8_t *src, *block_pointer;
432     int src_size;
433     int bytes_left;
434
435     if (ctx->has_pkt) {
436         ctx->has_pkt = 0;
437         table_bytes = (AV_RB16(avpkt->data) + 7) >> 3;
438         if (table_bytes + 3 > avpkt->size || avpkt->size > RALF_MAX_PKT_SIZE) {
439             av_log(avctx, AV_LOG_ERROR, "Wrong packet's breath smells of wrong data!\n");
440             return AVERROR_INVALIDDATA;
441         }
442         if (memcmp(ctx->pkt, avpkt->data, 2 + table_bytes)) {
443             av_log(avctx, AV_LOG_ERROR, "Wrong packet tails are wrong!\n");
444             return AVERROR_INVALIDDATA;
445         }
446
447         src      = ctx->pkt;
448         src_size = RALF_MAX_PKT_SIZE + avpkt->size;
449         memcpy(ctx->pkt + RALF_MAX_PKT_SIZE, avpkt->data + 2 + table_bytes,
450                avpkt->size - 2 - table_bytes);
451     } else {
452         if (avpkt->size == RALF_MAX_PKT_SIZE) {
453             memcpy(ctx->pkt, avpkt->data, avpkt->size);
454             ctx->has_pkt   = 1;
455             *got_frame_ptr = 0;
456
457             return avpkt->size;
458         }
459         src      = avpkt->data;
460         src_size = avpkt->size;
461     }
462
463     ctx->frame.nb_samples = ctx->max_frame_size;
464     if ((ret = avctx->get_buffer(avctx, &ctx->frame)) < 0) {
465         av_log(avctx, AV_LOG_ERROR, "Me fail get_buffer()? That's unpossible!\n");
466         return ret;
467     }
468     samples = (int16_t*)ctx->frame.data[0];
469
470     if (src_size < 5) {
471         av_log(avctx, AV_LOG_ERROR, "too short packets are too short!\n");
472         return AVERROR_INVALIDDATA;
473     }
474     table_size  = AV_RB16(src);
475     table_bytes = (table_size + 7) >> 3;
476     if (src_size < table_bytes + 3) {
477         av_log(avctx, AV_LOG_ERROR, "short packets are short!\n");
478         return AVERROR_INVALIDDATA;
479     }
480     init_get_bits(&gb, src + 2, table_size);
481     ctx->num_blocks = 0;
482     while (get_bits_left(&gb) > 0) {
483         ctx->block_size[ctx->num_blocks] = get_bits(&gb, 15);
484         if (get_bits1(&gb)) {
485             ctx->block_pts[ctx->num_blocks] = get_bits(&gb, 9);
486         } else {
487             ctx->block_pts[ctx->num_blocks] = 0;
488         }
489         ctx->num_blocks++;
490     }
491
492     block_pointer = src      + table_bytes + 2;
493     bytes_left    = src_size - table_bytes - 2;
494     ctx->sample_offset = 0;
495     for (i = 0; i < ctx->num_blocks; i++) {
496         if (bytes_left < ctx->block_size[i]) {
497             av_log(avctx, AV_LOG_ERROR, "I'm pedaling backwards\n");
498             break;
499         }
500         init_get_bits(&gb, block_pointer, ctx->block_size[i] * 8);
501         if (decode_block(avctx, &gb, samples + ctx->sample_offset
502                                                * avctx->channels) < 0) {
503             av_log(avctx, AV_LOG_ERROR, "Sir, I got carsick in your office. Not decoding the rest of packet.\n");
504             break;
505         }
506         block_pointer += ctx->block_size[i];
507         bytes_left    -= ctx->block_size[i];
508     }
509
510     ctx->frame.nb_samples = ctx->sample_offset;
511     *got_frame_ptr  = ctx->sample_offset > 0;
512     *(AVFrame*)data = ctx->frame;
513
514     return avpkt->size;
515 }
516
517 static void decode_flush(AVCodecContext *avctx)
518 {
519     RALFContext *ctx = avctx->priv_data;
520
521     ctx->has_pkt = 0;
522 }
523
524
525 AVCodec ff_ralf_decoder = {
526     .name           = "ralf",
527     .type           = AVMEDIA_TYPE_AUDIO,
528     .id             = AV_CODEC_ID_RALF,
529     .priv_data_size = sizeof(RALFContext),
530     .init           = decode_init,
531     .close          = decode_close,
532     .decode         = decode_frame,
533     .flush          = decode_flush,
534     .capabilities   = CODEC_CAP_DR1,
535     .long_name      = NULL_IF_CONFIG_SMALL("RealAudio Lossless"),
536 };