FS#10047 : Clipv2
[kugel-rb.git] / apps / codecs / wma.c
blob8f8b91bd4aa410512601e5d694ecdde93493e5fc
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2007 Dave Chapman
12 * ASF parsing code based on libasf by Juho Vähä-Herttua
13 * http://code.google.com/p/libasf/ libasf itself was based on the ASF
14 * parser in VLC - http://www.videolan.org/
16 * This program is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU General Public License
18 * as published by the Free Software Foundation; either version 2
19 * of the License, or (at your option) any later version.
21 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
22 * KIND, either express or implied.
24 ****************************************************************************/
26 #include "codeclib.h"
27 #include "libwma/asf.h"
28 #include "libwma/wmadec.h"
30 CODEC_HEADER
32 int packet_count=0;
34 /* The output buffer containing the decoded samples (channels 0 and 1)
35 BLOCK_MAX_SIZE is 2048 (samples) and MAX_CHANNELS is 2.
38 static uint32_t decoded[BLOCK_MAX_SIZE * MAX_CHANNELS] IBSS_ATTR;
40 /* NOTE: WMADecodeContext is 120152 bytes (on x86) */
41 static WMADecodeContext wmadec;
43 enum asf_error_e {
44 ASF_ERROR_INTERNAL = -1, /* incorrect input to API calls */
45 ASF_ERROR_OUTOFMEM = -2, /* some malloc inside program failed */
46 ASF_ERROR_EOF = -3, /* unexpected end of file */
47 ASF_ERROR_IO = -4, /* error reading or writing to file */
48 ASF_ERROR_INVALID_LENGTH = -5, /* length value conflict in input data */
49 ASF_ERROR_INVALID_VALUE = -6, /* other value conflict in input data */
50 ASF_ERROR_INVALID_OBJECT = -7, /* ASF object missing or in wrong place */
51 ASF_ERROR_OBJECT_SIZE = -8, /* invalid ASF object size (too small) */
52 ASF_ERROR_SEEKABLE = -9, /* file not seekable */
53 ASF_ERROR_SEEK = -10 /* file is seekable but seeking failed */
56 /* Read an unaligned 32-bit little endian long from buffer. */
57 static unsigned long get_long_le(void* buf)
59 unsigned char* p = (unsigned char*) buf;
61 return p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
64 /* Read an unaligned 16-bit little endian short from buffer. */
65 static unsigned short get_short_le(void* buf)
67 unsigned char* p = (unsigned char*) buf;
69 return p[0] | (p[1] << 8);
72 #define GETLEN2b(bits) (((bits) == 0x03) ? 4 : bits)
74 #define GETVALUE2b(bits, data) \
75 (((bits) != 0x03) ? ((bits) != 0x02) ? ((bits) != 0x01) ? \
76 0 : *(data) : get_short_le(data) : get_long_le(data))
78 static int asf_read_packet(uint8_t** audiobuf, int* audiobufsize, int* packetlength, asf_waveformatex_t* wfx)
80 uint8_t tmp8, packet_flags, packet_property;
81 int stream_id;
82 int ec_length, opaque_data, ec_length_type;
83 int datalen;
84 uint8_t data[18];
85 uint8_t* datap;
86 uint32_t length;
87 uint32_t padding_length;
88 uint32_t send_time;
89 uint16_t duration;
90 uint16_t payload_count;
91 int payload_length_type;
92 uint32_t payload_hdrlen;
93 int payload_datalen;
94 int multiple;
95 uint32_t replicated_length;
96 uint32_t media_object_number;
97 uint32_t media_object_offset;
98 uint32_t bytesread = 0;
99 uint8_t* buf;
100 size_t bufsize;
101 int i;
102 /*DEBUGF("Reading new packet at %d bytes ", (int)ci->curpos);*/
104 if (ci->read_filebuf(&tmp8, 1) == 0) {
105 return ASF_ERROR_EOF;
107 bytesread++;
109 /* TODO: We need a better way to detect endofstream */
110 if (tmp8 != 0x82) {
111 DEBUGF("Read failed: packet did not sync\n");
112 return -1;
116 if (tmp8 & 0x80) {
117 ec_length = tmp8 & 0x0f;
118 opaque_data = (tmp8 >> 4) & 0x01;
119 ec_length_type = (tmp8 >> 5) & 0x03;
121 if (ec_length_type != 0x00 || opaque_data != 0 || ec_length != 0x02) {
122 DEBUGF("incorrect error correction flags\n");
123 return ASF_ERROR_INVALID_VALUE;
126 /* Skip ec_data */
127 ci->advance_buffer(ec_length);
128 bytesread += ec_length;
129 } else {
130 ec_length = 0;
133 if (ci->read_filebuf(&packet_flags, 1) == 0) { return ASF_ERROR_EOF; }
134 if (ci->read_filebuf(&packet_property, 1) == 0) { return ASF_ERROR_EOF; }
135 bytesread += 2;
137 datalen = GETLEN2b((packet_flags >> 1) & 0x03) +
138 GETLEN2b((packet_flags >> 3) & 0x03) +
139 GETLEN2b((packet_flags >> 5) & 0x03) + 6;
141 #if 0
142 if (datalen > sizeof(data)) {
143 DEBUGF("Unexpectedly long datalen in data - %d\n",datalen);
144 return ASF_ERROR_OUTOFMEM;
146 #endif
148 if (ci->read_filebuf(data, datalen) == 0) {
149 return ASF_ERROR_EOF;
152 bytesread += datalen;
154 datap = data;
155 length = GETVALUE2b((packet_flags >> 5) & 0x03, datap);
156 datap += GETLEN2b((packet_flags >> 5) & 0x03);
157 /* sequence value is not used */
158 GETVALUE2b((packet_flags >> 1) & 0x03, datap);
159 datap += GETLEN2b((packet_flags >> 1) & 0x03);
160 padding_length = GETVALUE2b((packet_flags >> 3) & 0x03, datap);
161 datap += GETLEN2b((packet_flags >> 3) & 0x03);
162 send_time = get_long_le(datap);
163 datap += 4;
164 duration = get_short_le(datap);
165 datap += 2;
166 /*DEBUGF("and duration %d ms\n", duration);*/
168 /* this is really idiotic, packet length can (and often will) be
169 * undefined and we just have to use the header packet size as the size
170 * value */
171 if (!((packet_flags >> 5) & 0x03)) {
172 length = wfx->packet_size;
175 /* this is also really idiotic, if packet length is smaller than packet
176 * size, we need to manually add the additional bytes into padding length
178 if (length < wfx->packet_size) {
179 padding_length += wfx->packet_size - length;
180 length = wfx->packet_size;
183 if (length > wfx->packet_size) {
184 DEBUGF("packet with too big length value\n");
185 return ASF_ERROR_INVALID_LENGTH;
188 /* check if we have multiple payloads */
189 if (packet_flags & 0x01) {
190 if (ci->read_filebuf(&tmp8, 1) == 0) {
191 return ASF_ERROR_EOF;
193 payload_count = tmp8 & 0x3f;
194 payload_length_type = (tmp8 >> 6) & 0x03;
195 bytesread++;
196 } else {
197 payload_count = 1;
198 payload_length_type = 0x02; /* not used */
201 if (length < bytesread) {
202 DEBUGF("header exceeded packet size, invalid file - length=%d, bytesread=%d\n",(int)length,(int)bytesread);
203 /* FIXME: should this be checked earlier? */
204 return ASF_ERROR_INVALID_LENGTH;
208 /* We now parse the individual payloads, and move all payloads
209 belonging to our audio stream to a contiguous block, starting at
210 the location of the first payload.
213 *audiobuf = NULL;
214 *audiobufsize = 0;
215 *packetlength = length - bytesread;
217 buf = ci->request_buffer(&bufsize, length);
218 datap = buf;
220 if (bufsize != length) {
221 /* This should only happen with packets larger than 32KB (the
222 guard buffer size). All the streams I've seen have
223 relatively small packets less than about 8KB), but I don't
224 know what is expected.
226 DEBUGF("Could not read packet (requested %d bytes, received %d), curpos=%d, aborting\n",
227 (int)length,(int)bufsize,(int)ci->curpos);
228 return -1;
231 for (i=0; i<payload_count; i++) {
232 stream_id = datap[0]&0x7f;
233 datap++;
234 bytesread++;
236 payload_hdrlen = GETLEN2b(packet_property & 0x03) +
237 GETLEN2b((packet_property >> 2) & 0x03) +
238 GETLEN2b((packet_property >> 4) & 0x03);
240 //DEBUGF("payload_hdrlen = %d\n",payload_hdrlen);
241 #if 0
242 /* TODO */
243 if (payload_hdrlen > size) {
244 return ASF_ERROR_INVALID_LENGTH;
246 #endif
247 if (payload_hdrlen > sizeof(data)) {
248 DEBUGF("Unexpectedly long datalen in data - %d\n",datalen);
249 return ASF_ERROR_OUTOFMEM;
252 bytesread += payload_hdrlen;
253 media_object_number = GETVALUE2b((packet_property >> 4) & 0x03, datap);
254 datap += GETLEN2b((packet_property >> 4) & 0x03);
255 media_object_offset = GETVALUE2b((packet_property >> 2) & 0x03, datap);
256 datap += GETLEN2b((packet_property >> 2) & 0x03);
257 replicated_length = GETVALUE2b(packet_property & 0x03, datap);
258 datap += GETLEN2b(packet_property & 0x03);
260 /* TODO: Validate replicated_length */
261 /* TODO: Is the content of this important for us? */
262 datap += replicated_length;
263 bytesread += replicated_length;
265 multiple = packet_flags & 0x01;
268 if (multiple) {
269 int x;
271 x = GETLEN2b(payload_length_type);
273 if (x != 2) {
274 /* in multiple payloads datalen should be a word */
275 return ASF_ERROR_INVALID_VALUE;
278 #if 0
279 if (skip + tmp > datalen) {
280 /* not enough data */
281 return ASF_ERROR_INVALID_LENGTH;
283 #endif
284 payload_datalen = GETVALUE2b(payload_length_type, datap);
285 datap += x;
286 bytesread += x;
287 } else {
288 payload_datalen = length - bytesread - padding_length;
291 if (replicated_length==1)
292 datap++;
294 if (stream_id == wfx->audiostream)
296 if (*audiobuf == NULL) {
297 /* The first payload can stay where it is */
298 *audiobuf = datap;
299 *audiobufsize = payload_datalen;
300 } else {
301 /* The second and subsequent payloads in this packet
302 that belong to the audio stream need to be moved to be
303 contiguous with the first payload.
305 memmove(*audiobuf + *audiobufsize, datap, payload_datalen);
306 *audiobufsize += payload_datalen;
309 datap += payload_datalen;
310 bytesread += payload_datalen;
313 if (*audiobuf != NULL)
314 return 1;
315 else
316 return 0;
320 static int get_timestamp(int *duration)
322 uint8_t tmp8, packet_flags, packet_property;
323 int ec_length, opaque_data, ec_length_type;
324 int datalen;
325 uint8_t data[18];
326 uint8_t* datap;
327 uint32_t length;
328 uint32_t padding_length;
329 uint32_t send_time;
331 uint32_t bytesread = 0;
332 packet_count++;
333 if (ci->read_filebuf(&tmp8, 1) == 0) {
334 DEBUGF("ASF ERROR (EOF?)\n");
335 return ASF_ERROR_EOF;
337 bytesread++;
339 /* TODO: We need a better way to detect endofstream */
340 if (tmp8 != 0x82) {
341 DEBUGF("Get timestamp: Detected end of stream\n");
342 return ASF_ERROR_EOF;
346 if (tmp8 & 0x80) {
347 ec_length = tmp8 & 0x0f;
348 opaque_data = (tmp8 >> 4) & 0x01;
349 ec_length_type = (tmp8 >> 5) & 0x03;
351 if (ec_length_type != 0x00 || opaque_data != 0 || ec_length != 0x02) {
352 DEBUGF("incorrect error correction flags\n");
353 return ASF_ERROR_INVALID_VALUE;
356 /* Skip ec_data */
357 ci->advance_buffer(ec_length);
358 bytesread += ec_length;
359 } else {
360 ec_length = 0;
363 if (ci->read_filebuf(&packet_flags, 1) == 0) {
364 DEBUGF("Detected end of stream 2\n");
365 return ASF_ERROR_EOF;
368 if (ci->read_filebuf(&packet_property, 1) == 0) {
369 DEBUGF("Detected end of stream3\n");
370 return ASF_ERROR_EOF;
372 bytesread += 2;
374 datalen = GETLEN2b((packet_flags >> 1) & 0x03) +
375 GETLEN2b((packet_flags >> 3) & 0x03) +
376 GETLEN2b((packet_flags >> 5) & 0x03) + 6;
378 if (ci->read_filebuf(data, datalen) == 0) {
379 DEBUGF("Detected end of stream4\n");
380 return ASF_ERROR_EOF;
383 bytesread += datalen;
385 datap = data;
386 length = GETVALUE2b((packet_flags >> 5) & 0x03, datap);
387 datap += GETLEN2b((packet_flags >> 5) & 0x03);
389 /* sequence value is not used */
390 GETVALUE2b((packet_flags >> 1) & 0x03, datap);
391 datap += GETLEN2b((packet_flags >> 1) & 0x03);
392 padding_length = GETVALUE2b((packet_flags >> 3) & 0x03, datap);
393 datap += GETLEN2b((packet_flags >> 3) & 0x03);
394 send_time = get_long_le(datap);
395 datap += 4;
396 *duration = get_short_le(datap);
398 /*the get_timestamp function advances us 12-13 bytes past the packet start,
399 need to undo this here so that we stay synced with the packet*/
400 ci->seek_buffer(ci->curpos-bytesread);
402 return send_time;
405 /*entry point for seeks*/
406 static int seek(int ms, asf_waveformatex_t* wfx)
408 int time, duration, delta, temp, count=0;
410 /*estimate packet number from bitrate*/
411 int initial_packet = ci->curpos/wfx->packet_size;
412 int packet_num = (((int64_t)ms)*(wfx->bitrate>>3))/wfx->packet_size/1000;
413 int last_packet = ci->id3->filesize / wfx->packet_size;
415 if (packet_num > last_packet) {
416 packet_num = last_packet;
419 /*calculate byte address of the start of that packet*/
420 int packet_offset = packet_num*wfx->packet_size;
422 /*seek to estimated packet*/
423 ci->seek_buffer(ci->id3->first_frame_offset+packet_offset);
424 temp = ms;
425 while (1)
427 /*for very large files it can be difficult and unimportant to find the exact packet*/
428 count++;
430 /*check the time stamp of our packet*/
431 time = get_timestamp(&duration);
432 DEBUGF("seeked to %d ms with duration %d\n", time, duration);
434 if (time < 0) {
435 /*unknown error, try to recover*/
436 DEBUGF("UKNOWN SEEK ERROR\n");
437 ci->seek_buffer(ci->id3->first_frame_offset+initial_packet*wfx->packet_size);
438 /*seek failed so return time stamp of the initial packet*/
439 return get_timestamp(&duration);
442 if ((time+duration>=ms && time<=ms) || count > 10) {
443 DEBUGF("Found our packet! Now at %d packet\n", packet_num);
444 return time;
445 } else {
446 /*seek again*/
447 delta = ms-time;
448 /*estimate new packet number from bitrate and our current position*/
449 temp += delta;
450 packet_num = ((temp/1000)*(wfx->bitrate>>3) - (wfx->packet_size>>1))/wfx->packet_size; //round down!
451 packet_offset = packet_num*wfx->packet_size;
452 ci->seek_buffer(ci->id3->first_frame_offset+packet_offset);
459 /* this is the codec entry point */
460 enum codec_status codec_main(void)
462 uint32_t elapsedtime;
463 int retval;
464 asf_waveformatex_t wfx;
465 size_t resume_offset;
466 int i;
467 int wmares, res;
468 uint8_t* audiobuf;
469 int audiobufsize;
470 int packetlength = 0;
471 int errcount = 0;
473 /* Generic codec initialisation */
474 ci->configure(DSP_SET_SAMPLE_DEPTH, 29);
476 next_track:
478 /* Wait for the metadata to be read */
479 while (!*ci->taginfo_ready && !ci->stop_codec)
480 ci->sleep(1);
482 retval = CODEC_OK;
484 /* Remember the resume position - when the codec is opened, the
485 playback engine will reset it. */
486 resume_offset = ci->id3->offset;
487 restart_track:
488 if (codec_init()) {
489 LOGF("WMA: Error initialising codec\n");
490 retval = CODEC_ERROR;
491 goto exit;
494 /* Copy the format metadata we've stored in the id3 TOC field. This
495 saves us from parsing it again here. */
496 memcpy(&wfx, ci->id3->toc, sizeof(wfx));
498 if (wma_decode_init(&wmadec,&wfx) < 0) {
499 LOGF("WMA: Unsupported or corrupt file\n");
500 retval = CODEC_ERROR;
501 goto exit;
504 DEBUGF("**************** IN WMA.C ******************\n");
506 if (resume_offset > ci->id3->first_frame_offset)
508 /* Get start of current packet */
509 int packet_offset = (resume_offset - ci->id3->first_frame_offset)
510 % wfx.packet_size;
511 ci->seek_buffer(resume_offset - packet_offset);
512 elapsedtime = get_timestamp(&i);
513 ci->set_elapsed(elapsedtime);
515 else
517 /* Now advance the file position to the first frame */
518 ci->seek_buffer(ci->id3->first_frame_offset);
519 elapsedtime = 0;
522 resume_offset = 0;
523 ci->configure(DSP_SWITCH_FREQUENCY, wfx.rate);
524 ci->configure(DSP_SET_STEREO_MODE, wfx.channels == 1 ?
525 STEREO_MONO : STEREO_INTERLEAVED);
526 codec_set_replaygain(ci->id3);
528 /* The main decoding loop */
530 res = 1;
531 while (res >= 0)
533 ci->yield();
534 if (ci->stop_codec || ci->new_track) {
535 goto done;
538 /* Deal with any pending seek requests */
539 if (ci->seek_time){
541 if (ci->seek_time == 1) {
542 ci->seek_complete();
543 goto restart_track; /* Pretend you never saw this... */
546 elapsedtime = seek(ci->seek_time, &wfx);
547 if (elapsedtime < 1){
548 ci->seek_complete();
549 goto next_track;
551 /*DEBUGF("Seek returned %d\n", (int)elapsedtime);*/
552 ci->set_elapsed(elapsedtime);
554 /*flush the wma decoder state*/
555 wmadec.last_superframe_len = 0;
556 wmadec.last_bitoffset = 0;
557 ci->seek_complete();
559 errcount = 0;
560 new_packet:
561 res = asf_read_packet(&audiobuf, &audiobufsize, &packetlength, &wfx);
563 if (res < 0) {
564 /* We'll try to recover from a parse error a certain number of
565 * times. If we succeed, the error counter will be reset.
568 errcount++;
569 DEBUGF("read_packet error %d, errcount %d\n",wmares, errcount);
570 if (errcount > 5) {
571 goto done;
572 } else {
573 ci->advance_buffer(packetlength);
574 goto new_packet;
576 } else if (res > 0) {
577 wma_decode_superframe_init(&wmadec, audiobuf, audiobufsize);
579 for (i=0; i < wmadec.nb_frames; i++)
581 wmares = wma_decode_superframe_frame(&wmadec,
582 decoded,
583 audiobuf, audiobufsize);
585 ci->yield ();
587 if (wmares < 0) {
588 /* Do the above, but for errors in decode. */
589 errcount++;
590 DEBUGF("WMA decode error %d, errcount %d\n",wmares, errcount);
591 if (errcount > 5) {
592 goto done;
593 } else {
594 ci->advance_buffer(packetlength);
595 goto new_packet;
597 } else if (wmares > 0) {
598 ci->pcmbuf_insert(decoded, NULL, wmares);
599 elapsedtime += (wmares*10)/(wfx.rate/100);
600 ci->set_elapsed(elapsedtime);
602 ci->yield();
606 ci->advance_buffer(packetlength);
608 retval = CODEC_OK;
610 done:
611 /*LOGF("WMA: Decoded %ld samples\n",elapsedtime*wfx.rate/1000);*/
613 if (ci->request_next_track())
614 goto next_track;
615 exit:
616 return retval;