1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
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 ****************************************************************************/
27 #include "libwma/asf.h"
28 #include "libwma/wmadec.h"
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
;
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
;
82 int ec_length
, opaque_data
, ec_length_type
;
87 uint32_t padding_length
;
90 uint16_t payload_count
;
91 int payload_length_type
;
92 uint32_t payload_hdrlen
;
95 uint32_t replicated_length
;
96 uint32_t media_object_number
;
97 uint32_t media_object_offset
;
98 uint32_t bytesread
= 0;
102 /*DEBUGF("Reading new packet at %d bytes ", (int)ci->curpos);*/
104 if (ci
->read_filebuf(&tmp8
, 1) == 0) {
105 return ASF_ERROR_EOF
;
109 /* TODO: We need a better way to detect endofstream */
111 DEBUGF("Read failed: packet did not sync\n");
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
;
127 ci
->advance_buffer(ec_length
);
128 bytesread
+= ec_length
;
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
; }
137 datalen
= GETLEN2b((packet_flags
>> 1) & 0x03) +
138 GETLEN2b((packet_flags
>> 3) & 0x03) +
139 GETLEN2b((packet_flags
>> 5) & 0x03) + 6;
142 if (datalen
> sizeof(data
)) {
143 DEBUGF("Unexpectedly long datalen in data - %d\n",datalen
);
144 return ASF_ERROR_OUTOFMEM
;
148 if (ci
->read_filebuf(data
, datalen
) == 0) {
149 return ASF_ERROR_EOF
;
152 bytesread
+= datalen
;
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
);
164 duration
= get_short_le(datap
);
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
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;
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.
215 *packetlength
= length
- bytesread
;
217 buf
= ci
->request_buffer(&bufsize
, length
);
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
);
231 for (i
=0; i
<payload_count
; i
++) {
232 stream_id
= datap
[0]&0x7f;
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);
243 if (payload_hdrlen
> size
) {
244 return ASF_ERROR_INVALID_LENGTH
;
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;
271 x
= GETLEN2b(payload_length_type
);
274 /* in multiple payloads datalen should be a word */
275 return ASF_ERROR_INVALID_VALUE
;
279 if (skip
+ tmp
> datalen
) {
280 /* not enough data */
281 return ASF_ERROR_INVALID_LENGTH
;
284 payload_datalen
= GETVALUE2b(payload_length_type
, datap
);
288 payload_datalen
= length
- bytesread
- padding_length
;
291 if (replicated_length
==1)
294 if (stream_id
== wfx
->audiostream
)
296 if (*audiobuf
== NULL
) {
297 /* The first payload can stay where it is */
299 *audiobufsize
= payload_datalen
;
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
)
320 static int get_timestamp(int *duration
)
322 uint8_t tmp8
, packet_flags
, packet_property
;
323 int ec_length
, opaque_data
, ec_length_type
;
328 uint32_t padding_length
;
331 uint32_t bytesread
= 0;
333 if (ci
->read_filebuf(&tmp8
, 1) == 0) {
334 DEBUGF("ASF ERROR (EOF?)\n");
335 return ASF_ERROR_EOF
;
339 /* TODO: We need a better way to detect endofstream */
341 DEBUGF("Get timestamp: Detected end of stream\n");
342 return ASF_ERROR_EOF
;
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
;
357 ci
->advance_buffer(ec_length
);
358 bytesread
+= ec_length
;
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
;
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
;
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
);
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
);
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
);
427 /*for very large files it can be difficult and unimportant to find the exact packet*/
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
);
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
);
448 /*estimate new packet number from bitrate and our current position*/
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
;
464 asf_waveformatex_t wfx
;
465 size_t resume_offset
;
470 int packetlength
= 0;
473 /* Generic codec initialisation */
474 ci
->configure(DSP_SET_SAMPLE_DEPTH
, 29);
478 /* Wait for the metadata to be read */
479 while (!*ci
->taginfo_ready
&& !ci
->stop_codec
)
484 /* Remember the resume position - when the codec is opened, the
485 playback engine will reset it. */
486 resume_offset
= ci
->id3
->offset
;
489 LOGF("WMA: Error initialising codec\n");
490 retval
= CODEC_ERROR
;
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
;
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
)
511 ci
->seek_buffer(resume_offset
- packet_offset
);
512 elapsedtime
= get_timestamp(&i
);
513 ci
->set_elapsed(elapsedtime
);
517 /* Now advance the file position to the first frame */
518 ci
->seek_buffer(ci
->id3
->first_frame_offset
);
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 */
534 if (ci
->stop_codec
|| ci
->new_track
) {
538 /* Deal with any pending seek requests */
541 if (ci
->seek_time
== 1) {
543 goto restart_track
; /* Pretend you never saw this... */
546 elapsedtime
= seek(ci
->seek_time
, &wfx
);
547 if (elapsedtime
< 1){
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;
561 res
= asf_read_packet(&audiobuf
, &audiobufsize
, &packetlength
, &wfx
);
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.
569 DEBUGF("read_packet error %d, errcount %d\n",wmares
, errcount
);
573 ci
->advance_buffer(packetlength
);
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
,
583 audiobuf
, audiobufsize
);
588 /* Do the above, but for errors in decode. */
590 DEBUGF("WMA decode error %d, errcount %d\n",wmares
, errcount
);
594 ci
->advance_buffer(packetlength
);
597 } else if (wmares
> 0) {
598 ci
->pcmbuf_insert(decoded
, NULL
, wmares
);
599 elapsedtime
+= (wmares
*10)/(wfx
.rate
/100);
600 ci
->set_elapsed(elapsedtime
);
606 ci
->advance_buffer(packetlength
);
611 /*LOGF("WMA: Decoded %ld samples\n",elapsedtime*wfx.rate/1000);*/
613 if (ci
->request_next_track())