]> git.sesse.net Git - ffmpeg/blob - libavcodec/ralf.c
utvideodec: Support UQRA and UQRG
[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 "libavutil/attributes.h"
30 #include "libavutil/channel_layout.h"
31
32 #include "avcodec.h"
33 #include "bitstream.h"
34 #include "golomb.h"
35 #include "internal.h"
36 #include "unary.h"
37 #include "vlc.h"
38 #include "ralfdata.h"
39
40 #define FILTER_NONE 0
41 #define FILTER_RAW  642
42
43 typedef struct VLCSet {
44     VLC filter_params;
45     VLC bias;
46     VLC coding_mode;
47     VLC filter_coeffs[10][11];
48     VLC short_codes[15];
49     VLC long_codes[125];
50 } VLCSet;
51
52 #define RALF_MAX_PKT_SIZE 8192
53
54 typedef struct RALFContext {
55     int version;
56     int max_frame_size;
57     VLCSet sets[3];
58     int32_t channel_data[2][4096];
59
60     int     filter_params;   ///< combined filter parameters for the current channel data
61     int     filter_length;   ///< length of the filter for the current channel data
62     int     filter_bits;     ///< filter precision for the current channel data
63     int32_t filter[64];
64
65     int     bias[2];         ///< a constant value added to channel data after filtering
66
67     int num_blocks;          ///< number of blocks inside the frame
68     int sample_offset;
69     int block_size[1 << 12]; ///< size of the blocks
70     int block_pts[1 << 12];  ///< block start time (in milliseconds)
71
72     uint8_t pkt[16384];
73     int     has_pkt;
74 } RALFContext;
75
76 #define MAX_ELEMS 644 // no RALF table uses more than that
77
78 static av_cold int init_ralf_vlc(VLC *vlc, const uint8_t *data, int elems)
79 {
80     uint8_t  lens[MAX_ELEMS];
81     uint16_t codes[MAX_ELEMS];
82     int counts[17], prefixes[18];
83     int i, cur_len;
84     int max_bits = 0;
85     int nb = 0;
86
87     for (i = 0; i <= 16; i++)
88         counts[i] = 0;
89     for (i = 0; i < elems; i++) {
90         cur_len  = (nb ? *data & 0xF : *data >> 4) + 1;
91         counts[cur_len]++;
92         max_bits = FFMAX(max_bits, cur_len);
93         lens[i]  = cur_len;
94         data    += nb;
95         nb      ^= 1;
96     }
97     prefixes[1] = 0;
98     for (i = 1; i <= 16; i++)
99         prefixes[i + 1] = (prefixes[i] + counts[i]) << 1;
100
101     for (i = 0; i < elems; i++)
102         codes[i] = prefixes[lens[i]]++;
103
104     return ff_init_vlc_sparse(vlc, FFMIN(max_bits, 9), elems,
105                               lens, 1, 1, codes, 2, 2, NULL, 0, 0, 0);
106 }
107
108 static av_cold int decode_close(AVCodecContext *avctx)
109 {
110     RALFContext *ctx = avctx->priv_data;
111     int i, j, k;
112
113     for (i = 0; i < 3; i++) {
114         ff_free_vlc(&ctx->sets[i].filter_params);
115         ff_free_vlc(&ctx->sets[i].bias);
116         ff_free_vlc(&ctx->sets[i].coding_mode);
117         for (j = 0; j < 10; j++)
118             for (k = 0; k < 11; k++)
119                 ff_free_vlc(&ctx->sets[i].filter_coeffs[j][k]);
120         for (j = 0; j < 15; j++)
121             ff_free_vlc(&ctx->sets[i].short_codes[j]);
122         for (j = 0; j < 125; j++)
123             ff_free_vlc(&ctx->sets[i].long_codes[j]);
124     }
125
126     return 0;
127 }
128
129 static av_cold int decode_init(AVCodecContext *avctx)
130 {
131     RALFContext *ctx = avctx->priv_data;
132     int i, j, k;
133     int ret;
134
135     if (avctx->extradata_size < 24 || memcmp(avctx->extradata, "LSD:", 4)) {
136         av_log(avctx, AV_LOG_ERROR, "Extradata is not groovy, dude\n");
137         return AVERROR_INVALIDDATA;
138     }
139
140     ctx->version = AV_RB16(avctx->extradata + 4);
141     if (ctx->version != 0x103) {
142         avpriv_request_sample(avctx, "Unknown version %X", ctx->version);
143         return AVERROR_PATCHWELCOME;
144     }
145
146     avctx->channels    = AV_RB16(avctx->extradata + 8);
147     avctx->sample_rate = AV_RB32(avctx->extradata + 12);
148     if (avctx->channels < 1 || avctx->channels > 2
149         || avctx->sample_rate < 8000 || avctx->sample_rate > 96000) {
150         av_log(avctx, AV_LOG_ERROR, "Invalid coding parameters %d Hz %d ch\n",
151                avctx->sample_rate, avctx->channels);
152         return AVERROR_INVALIDDATA;
153     }
154     avctx->sample_fmt     = AV_SAMPLE_FMT_S16P;
155     avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO
156                                                    : AV_CH_LAYOUT_MONO;
157
158     ctx->max_frame_size = AV_RB32(avctx->extradata + 16);
159     if (ctx->max_frame_size > (1 << 20) || !ctx->max_frame_size) {
160         av_log(avctx, AV_LOG_ERROR, "invalid frame size %d\n",
161                ctx->max_frame_size);
162     }
163     ctx->max_frame_size = FFMAX(ctx->max_frame_size, avctx->sample_rate);
164
165     for (i = 0; i < 3; i++) {
166         ret = init_ralf_vlc(&ctx->sets[i].filter_params, filter_param_def[i],
167                             FILTERPARAM_ELEMENTS);
168         if (ret < 0) {
169             decode_close(avctx);
170             return ret;
171         }
172         ret = init_ralf_vlc(&ctx->sets[i].bias, bias_def[i], BIAS_ELEMENTS);
173         if (ret < 0) {
174             decode_close(avctx);
175             return ret;
176         }
177         ret = init_ralf_vlc(&ctx->sets[i].coding_mode, coding_mode_def[i],
178                             CODING_MODE_ELEMENTS);
179         if (ret < 0) {
180             decode_close(avctx);
181             return ret;
182         }
183         for (j = 0; j < 10; j++) {
184             for (k = 0; k < 11; k++) {
185                 ret = init_ralf_vlc(&ctx->sets[i].filter_coeffs[j][k],
186                                     filter_coeffs_def[i][j][k],
187                                     FILTER_COEFFS_ELEMENTS);
188                 if (ret < 0) {
189                     decode_close(avctx);
190                     return ret;
191                 }
192             }
193         }
194         for (j = 0; j < 15; j++) {
195             ret = init_ralf_vlc(&ctx->sets[i].short_codes[j],
196                                 short_codes_def[i][j], SHORT_CODES_ELEMENTS);
197             if (ret < 0) {
198                 decode_close(avctx);
199                 return ret;
200             }
201         }
202         for (j = 0; j < 125; j++) {
203             ret = init_ralf_vlc(&ctx->sets[i].long_codes[j],
204                                 long_codes_def[i][j], LONG_CODES_ELEMENTS);
205             if (ret < 0) {
206                 decode_close(avctx);
207                 return ret;
208             }
209         }
210     }
211
212     return 0;
213 }
214
215 static inline int extend_code(BitstreamContext *bc, int val, int range, int bits)
216 {
217     if (val == 0) {
218         val = -range - get_ue_golomb(bc);
219     } else if (val == range * 2) {
220         val =  range + get_ue_golomb(bc);
221     } else {
222         val -= range;
223     }
224     if (bits)
225         val = (val << bits) | bitstream_read(bc, bits);
226     return val;
227 }
228
229 static int decode_channel(RALFContext *ctx, BitstreamContext *bc, int ch,
230                           int length, int mode, int bits)
231 {
232     int i, t;
233     int code_params;
234     VLCSet *set = ctx->sets + mode;
235     VLC *code_vlc; int range, range2, add_bits;
236     int *dst = ctx->channel_data[ch];
237
238     ctx->filter_params = bitstream_read_vlc(bc, set->filter_params.table, 9, 2);
239     ctx->filter_bits   = (ctx->filter_params - 2) >> 6;
240     ctx->filter_length = ctx->filter_params - (ctx->filter_bits << 6) - 1;
241
242     if (ctx->filter_params == FILTER_RAW) {
243         for (i = 0; i < length; i++)
244             dst[i] = bitstream_read(bc, bits);
245         ctx->bias[ch] = 0;
246         return 0;
247     }
248
249     ctx->bias[ch] = bitstream_read_vlc(bc, set->bias.table, 9, 2);
250     ctx->bias[ch] = extend_code(bc, ctx->bias[ch], 127, 4);
251
252     if (ctx->filter_params == FILTER_NONE) {
253         memset(dst, 0, sizeof(*dst) * length);
254         return 0;
255     }
256
257     if (ctx->filter_params > 1) {
258         int cmode = 0, coeff = 0;
259         VLC *vlc = set->filter_coeffs[ctx->filter_bits] + 5;
260
261         add_bits = ctx->filter_bits;
262
263         for (i = 0; i < ctx->filter_length; i++) {
264             t = bitstream_read_vlc(bc, vlc[cmode].table, vlc[cmode].bits, 2);
265             t = extend_code(bc, t, 21, add_bits);
266             if (!cmode)
267                 coeff -= 12 << add_bits;
268             coeff = t - coeff;
269             ctx->filter[i] = coeff;
270
271             cmode = coeff >> add_bits;
272             if (cmode < 0) {
273                 cmode = -1 - av_log2(-cmode);
274                 if (cmode < -5)
275                     cmode = -5;
276             } else if (cmode > 0) {
277                 cmode =  1 + av_log2(cmode);
278                 if (cmode > 5)
279                     cmode = 5;
280             }
281         }
282     }
283
284     code_params = bitstream_read_vlc(bc, set->coding_mode.table, set->coding_mode.bits, 2);
285     if (code_params >= 15) {
286         add_bits = av_clip((code_params / 5 - 3) / 2, 0, 10);
287         if (add_bits > 9 && (code_params % 5) != 2)
288             add_bits--;
289         range    = 10;
290         range2   = 21;
291         code_vlc = set->long_codes + code_params - 15;
292     } else {
293         add_bits = 0;
294         range    = 6;
295         range2   = 13;
296         code_vlc = set->short_codes + code_params;
297     }
298
299     for (i = 0; i < length; i += 2) {
300         int code1, code2;
301
302         t = bitstream_read_vlc(bc, code_vlc->table, code_vlc->bits, 2);
303         code1 = t / range2;
304         code2 = t % range2;
305         dst[i]     = extend_code(bc, code1, range, 0) << add_bits;
306         dst[i + 1] = extend_code(bc, code2, range, 0) << add_bits;
307         if (add_bits) {
308             dst[i]     |= bitstream_read(bc, add_bits);
309             dst[i + 1] |= bitstream_read(bc, add_bits);
310         }
311     }
312
313     return 0;
314 }
315
316 static void apply_lpc(RALFContext *ctx, int ch, int length, int bits)
317 {
318     int i, j, acc;
319     int *audio = ctx->channel_data[ch];
320     int bias = 1 << (ctx->filter_bits - 1);
321     int max_clip = (1 << bits) - 1, min_clip = -max_clip - 1;
322
323     for (i = 1; i < length; i++) {
324         int flen = FFMIN(ctx->filter_length, i);
325
326         acc = 0;
327         for (j = 0; j < flen; j++)
328             acc += ctx->filter[j] * audio[i - j - 1];
329         if (acc < 0) {
330             acc = (acc + bias - 1) >> ctx->filter_bits;
331             acc = FFMAX(acc, min_clip);
332         } else {
333             acc = (acc + bias) >> ctx->filter_bits;
334             acc = FFMIN(acc, max_clip);
335         }
336         audio[i] += acc;
337     }
338 }
339
340 static int decode_block(AVCodecContext *avctx, BitstreamContext *bc,
341                         int16_t *dst0, int16_t *dst1)
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(bc, 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 = bitstream_read(bc, 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, bc, 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 (bitstream_bits_left(bc) < 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             dst0[i] = ch0[i] + ctx->bias[0];
386         break;
387     case 1:
388         for (i = 0; i < len; i++) {
389             dst0[i] = ch0[i] + ctx->bias[0];
390             dst1[i] = 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             dst0[i] = ch0[i];
397             dst1[i] = 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             dst0[i] = t + t2;
405             dst1[i] = 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             dst0[i] = (t2 + t) / 2;
413             dst1[i] = (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     AVFrame *frame   = data;
428     int16_t *samples0;
429     int16_t *samples1;
430     int ret;
431     BitstreamContext bc;
432     int table_size, table_bytes, i;
433     const uint8_t *src, *block_pointer;
434     int src_size;
435     int bytes_left;
436
437     if (ctx->has_pkt) {
438         ctx->has_pkt = 0;
439         table_bytes = (AV_RB16(avpkt->data) + 7) >> 3;
440         if (table_bytes + 3 > avpkt->size || avpkt->size > RALF_MAX_PKT_SIZE) {
441             av_log(avctx, AV_LOG_ERROR, "Wrong packet's breath smells of wrong data!\n");
442             return AVERROR_INVALIDDATA;
443         }
444         if (memcmp(ctx->pkt, avpkt->data, 2 + table_bytes)) {
445             av_log(avctx, AV_LOG_ERROR, "Wrong packet tails are wrong!\n");
446             return AVERROR_INVALIDDATA;
447         }
448
449         src      = ctx->pkt;
450         src_size = RALF_MAX_PKT_SIZE + avpkt->size;
451         memcpy(ctx->pkt + RALF_MAX_PKT_SIZE, avpkt->data + 2 + table_bytes,
452                avpkt->size - 2 - table_bytes);
453     } else {
454         if (avpkt->size == RALF_MAX_PKT_SIZE) {
455             memcpy(ctx->pkt, avpkt->data, avpkt->size);
456             ctx->has_pkt   = 1;
457             *got_frame_ptr = 0;
458
459             return avpkt->size;
460         }
461         src      = avpkt->data;
462         src_size = avpkt->size;
463     }
464
465     frame->nb_samples = ctx->max_frame_size;
466     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
467         av_log(avctx, AV_LOG_ERROR, "Me fail get_buffer()? That's unpossible!\n");
468         return ret;
469     }
470     samples0 = (int16_t *)frame->data[0];
471     samples1 = (int16_t *)frame->data[1];
472
473     if (src_size < 5) {
474         av_log(avctx, AV_LOG_ERROR, "too short packets are too short!\n");
475         return AVERROR_INVALIDDATA;
476     }
477     table_size  = AV_RB16(src);
478     table_bytes = (table_size + 7) >> 3;
479     if (src_size < table_bytes + 3) {
480         av_log(avctx, AV_LOG_ERROR, "short packets are short!\n");
481         return AVERROR_INVALIDDATA;
482     }
483     bitstream_init(&bc, src + 2, table_size);
484     ctx->num_blocks = 0;
485     while (bitstream_bits_left(&bc) > 0) {
486         ctx->block_size[ctx->num_blocks] = bitstream_read(&bc, 15);
487         if (bitstream_read_bit(&bc)) {
488             ctx->block_pts[ctx->num_blocks] = bitstream_read(&bc, 9);
489         } else {
490             ctx->block_pts[ctx->num_blocks] = 0;
491         }
492         ctx->num_blocks++;
493     }
494
495     block_pointer = src      + table_bytes + 2;
496     bytes_left    = src_size - table_bytes - 2;
497     ctx->sample_offset = 0;
498     for (i = 0; i < ctx->num_blocks; i++) {
499         if (bytes_left < ctx->block_size[i]) {
500             av_log(avctx, AV_LOG_ERROR, "I'm pedaling backwards\n");
501             break;
502         }
503         bitstream_init8(&bc, block_pointer, ctx->block_size[i]);
504         if (decode_block(avctx, &bc, samples0 + ctx->sample_offset,
505                                      samples1 + ctx->sample_offset) < 0) {
506             av_log(avctx, AV_LOG_ERROR, "Sir, I got carsick in your office. Not decoding the rest of packet.\n");
507             break;
508         }
509         block_pointer += ctx->block_size[i];
510         bytes_left    -= ctx->block_size[i];
511     }
512
513     frame->nb_samples = ctx->sample_offset;
514     *got_frame_ptr    = ctx->sample_offset > 0;
515
516     return avpkt->size;
517 }
518
519 static void decode_flush(AVCodecContext *avctx)
520 {
521     RALFContext *ctx = avctx->priv_data;
522
523     ctx->has_pkt = 0;
524 }
525
526
527 AVCodec ff_ralf_decoder = {
528     .name           = "ralf",
529     .long_name      = NULL_IF_CONFIG_SMALL("RealAudio Lossless"),
530     .type           = AVMEDIA_TYPE_AUDIO,
531     .id             = AV_CODEC_ID_RALF,
532     .priv_data_size = sizeof(RALFContext),
533     .init           = decode_init,
534     .close          = decode_close,
535     .decode         = decode_frame,
536     .flush          = decode_flush,
537     .capabilities   = AV_CODEC_CAP_DR1,
538     .sample_fmts    = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P,
539                                                       AV_SAMPLE_FMT_NONE },
540 };