1 /***************************************************************************
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
10 * Copyright (C) 2005 Dave Chapman
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
21 #include "libwma/asf.h"
22 #include "libwma/wmadec.h"
28 /* The output buffer containing the decoded samples (channels 0 and 1)
29 BLOCK_MAX_SIZE is 2048 (samples) and MAX_CHANNELS is 2.
32 static uint32_t decoded
[BLOCK_MAX_SIZE
* MAX_CHANNELS
];
34 /* NOTE: WMADecodeContext is 120152 bytes (on x86) */
35 static WMADecodeContext wmadec
;
38 ASF_ERROR_INTERNAL
= -1, /* incorrect input to API calls */
39 ASF_ERROR_OUTOFMEM
= -2, /* some malloc inside program failed */
40 ASF_ERROR_EOF
= -3, /* unexpected end of file */
41 ASF_ERROR_IO
= -4, /* error reading or writing to file */
42 ASF_ERROR_INVALID_LENGTH
= -5, /* length value conflict in input data */
43 ASF_ERROR_INVALID_VALUE
= -6, /* other value conflict in input data */
44 ASF_ERROR_INVALID_OBJECT
= -7, /* ASF object missing or in wrong place */
45 ASF_ERROR_OBJECT_SIZE
= -8, /* invalid ASF object size (too small) */
46 ASF_ERROR_SEEKABLE
= -9, /* file not seekable */
47 ASF_ERROR_SEEK
= -10 /* file is seekable but seeking failed */
50 /* Read an unaligned 32-bit little endian long from buffer. */
51 static unsigned long get_long_le(void* buf
)
53 unsigned char* p
= (unsigned char*) buf
;
55 return p
[0] | (p
[1] << 8) | (p
[2] << 16) | (p
[3] << 24);
58 /* Read an unaligned 16-bit little endian short from buffer. */
59 static unsigned short get_short_le(void* buf
)
61 unsigned char* p
= (unsigned char*) buf
;
63 return p
[0] | (p
[1] << 8);
66 #define GETLEN2b(bits) (((bits) == 0x03) ? 4 : bits)
68 #define GETVALUE2b(bits, data) \
69 (((bits) != 0x03) ? ((bits) != 0x02) ? ((bits) != 0x01) ? \
70 0 : *(data) : get_short_le(data) : get_long_le(data))
72 static int asf_read_packet(uint8_t** audiobuf
, int* audiobufsize
, int* packetlength
, asf_waveformatex_t
* wfx
)
74 uint8_t tmp8
, packet_flags
, packet_property
;
76 int ec_length
, opaque_data
, ec_length_type
;
81 uint32_t padding_length
;
84 uint16_t payload_count
;
85 int payload_length_type
;
86 uint32_t payload_hdrlen
;
89 uint32_t replicated_length
;
90 uint32_t media_object_number
;
91 uint32_t media_object_offset
;
92 uint32_t bytesread
= 0;
96 DEBUGF("Reading new packet at %d bytes ", (int)ci
->curpos
);
98 if (ci
->read_filebuf(&tmp8
, 1) == 0) {
103 //DEBUGF("tmp8=0x%02x\n",tmp8);
104 /* TODO: We need a better way to detect endofstream */
106 DEBUGF("Read failed: packet did not sync\n");
112 ec_length
= tmp8
& 0x0f;
113 opaque_data
= (tmp8
>> 4) & 0x01;
114 ec_length_type
= (tmp8
>> 5) & 0x03;
116 if (ec_length_type
!= 0x00 || opaque_data
!= 0 || ec_length
!= 0x02) {
117 DEBUGF("incorrect error correction flags\n");
118 return ASF_ERROR_INVALID_VALUE
;
122 ci
->advance_buffer(ec_length
);
123 bytesread
+= ec_length
;
128 if (ci
->read_filebuf(&packet_flags
, 1) == 0) { return ASF_ERROR_EOF
; }
129 if (ci
->read_filebuf(&packet_property
, 1) == 0) { return ASF_ERROR_EOF
; }
132 datalen
= GETLEN2b((packet_flags
>> 1) & 0x03) +
133 GETLEN2b((packet_flags
>> 3) & 0x03) +
134 GETLEN2b((packet_flags
>> 5) & 0x03) + 6;
137 if (datalen
> sizeof(data
)) {
138 DEBUGF("Unexpectedly long datalen in data - %d\n",datalen
);
139 return ASF_ERROR_OUTOFMEM
;
143 if (ci
->read_filebuf(data
, datalen
) == 0) {
144 return ASF_ERROR_EOF
;
147 bytesread
+= datalen
;
150 length
= GETVALUE2b((packet_flags
>> 5) & 0x03, datap
);
151 datap
+= GETLEN2b((packet_flags
>> 5) & 0x03);
152 /* sequence value is not used */
153 GETVALUE2b((packet_flags
>> 1) & 0x03, datap
);
154 datap
+= GETLEN2b((packet_flags
>> 1) & 0x03);
155 padding_length
= GETVALUE2b((packet_flags
>> 3) & 0x03, datap
);
156 datap
+= GETLEN2b((packet_flags
>> 3) & 0x03);
157 send_time
= get_long_le(datap
);
159 duration
= get_short_le(datap
);
161 DEBUGF("and duration %d ms\n", duration
);
163 /* this is really idiotic, packet length can (and often will) be
164 * undefined and we just have to use the header packet size as the size
166 if (!((packet_flags
>> 5) & 0x03)) {
167 length
= wfx
->packet_size
;
170 /* this is also really idiotic, if packet length is smaller than packet
171 * size, we need to manually add the additional bytes into padding length
173 if (length
< wfx
->packet_size
) {
174 padding_length
+= wfx
->packet_size
- length
;
175 length
= wfx
->packet_size
;
178 if (length
> wfx
->packet_size
) {
179 DEBUGF("packet with too big length value\n");
180 return ASF_ERROR_INVALID_LENGTH
;
183 /* check if we have multiple payloads */
184 if (packet_flags
& 0x01) {
185 if (ci
->read_filebuf(&tmp8
, 1) == 0) {
186 return ASF_ERROR_EOF
;
188 payload_count
= tmp8
& 0x3f;
189 payload_length_type
= (tmp8
>> 6) & 0x03;
193 payload_length_type
= 0x02; /* not used */
196 if (length
< bytesread
) {
197 DEBUGF("header exceeded packet size, invalid file - length=%d, bytesread=%d\n",(int)length
,(int)bytesread
);
198 /* FIXME: should this be checked earlier? */
199 return ASF_ERROR_INVALID_LENGTH
;
203 /* We now parse the individual payloads, and move all payloads
204 belonging to our audio stream to a contiguous block, starting at
205 the location of the first payload.
210 *packetlength
= length
- bytesread
;
212 buf
= ci
->request_buffer(&bufsize
, length
);
215 if (bufsize
!= length
) {
216 /* This should only happen with packets larger than 32KB (the
217 guard buffer size). All the streams I've seen have
218 relatively small packets less than about 8KB), but I don't
219 know what is expected.
221 DEBUGF("Could not read packet (requested %d bytes, received %d), curpos=%d, aborting\n",
222 (int)length
,(int)bufsize
,(int)ci
->curpos
);
226 for (i
=0; i
<payload_count
; i
++) {
227 stream_id
= datap
[0]&0x7f;
231 payload_hdrlen
= GETLEN2b(packet_property
& 0x03) +
232 GETLEN2b((packet_property
>> 2) & 0x03) +
233 GETLEN2b((packet_property
>> 4) & 0x03);
235 //DEBUGF("payload_hdrlen = %d\n",payload_hdrlen);
238 if (payload_hdrlen
> size
) {
239 return ASF_ERROR_INVALID_LENGTH
;
242 if (payload_hdrlen
> sizeof(data
)) {
243 DEBUGF("Unexpectedly long datalen in data - %d\n",datalen
);
244 return ASF_ERROR_OUTOFMEM
;
247 bytesread
+= payload_hdrlen
;
248 media_object_number
= GETVALUE2b((packet_property
>> 4) & 0x03, datap
);
249 datap
+= GETLEN2b((packet_property
>> 4) & 0x03);
250 media_object_offset
= GETVALUE2b((packet_property
>> 2) & 0x03, datap
);
251 datap
+= GETLEN2b((packet_property
>> 2) & 0x03);
252 replicated_length
= GETVALUE2b(packet_property
& 0x03, datap
);
253 datap
+= GETLEN2b(packet_property
& 0x03);
255 /* TODO: Validate replicated_length */
256 /* TODO: Is the content of this important for us? */
257 datap
+= replicated_length
;
258 bytesread
+= replicated_length
;
260 multiple
= packet_flags
& 0x01;
266 x
= GETLEN2b(payload_length_type
);
269 /* in multiple payloads datalen should be a word */
270 return ASF_ERROR_INVALID_VALUE
;
274 if (skip
+ tmp
> datalen
) {
275 /* not enough data */
276 return ASF_ERROR_INVALID_LENGTH
;
279 payload_datalen
= GETVALUE2b(payload_length_type
, datap
);
283 payload_datalen
= length
- bytesread
- padding_length
;
286 if (stream_id
== wfx
->audiostream
)
288 if (*audiobuf
== NULL
) {
289 /* The first payload can stay where it is */
291 *audiobufsize
= payload_datalen
;
293 /* The second and subsequent payloads in this packet
294 that belong to the audio stream need to be moved to be
295 contiguous with the first payload.
297 memmove(*audiobuf
+ *audiobufsize
, datap
, payload_datalen
);
298 *audiobufsize
+= payload_datalen
;
301 datap
+= payload_datalen
;
302 bytesread
+= payload_datalen
;
305 if (*audiobuf
!= NULL
)
312 static int get_timestamp(int *duration
)
314 uint8_t tmp8
, packet_flags
, packet_property
;
316 int ec_length
, opaque_data
, ec_length_type
;
321 uint32_t padding_length
;
324 //uint16_t payload_count;
325 uint32_t bytesread
= 0;
327 if (ci
->read_filebuf(&tmp8
, 1) == 0) {
328 DEBUGF("ASF ERROR (EOF?)\n");
329 return ASF_ERROR_EOF
;
333 /* TODO: We need a better way to detect endofstream */
335 DEBUGF("Get timestamp: Detected end of stream\n");
336 return ASF_ERROR_EOF
;
341 ec_length
= tmp8
& 0x0f;
342 opaque_data
= (tmp8
>> 4) & 0x01;
343 ec_length_type
= (tmp8
>> 5) & 0x03;
345 if (ec_length_type
!= 0x00 || opaque_data
!= 0 || ec_length
!= 0x02) {
346 DEBUGF("incorrect error correction flags\n");
347 return ASF_ERROR_INVALID_VALUE
;
351 ci
->advance_buffer(ec_length
);
352 bytesread
+= ec_length
;
357 if (ci
->read_filebuf(&packet_flags
, 1) == 0) {
358 DEBUGF("Detected end of stream 2\n");
359 return ASF_ERROR_EOF
;
362 if (ci
->read_filebuf(&packet_property
, 1) == 0) {
363 DEBUGF("Detected end of stream3\n");
364 return ASF_ERROR_EOF
;
368 datalen
= GETLEN2b((packet_flags
>> 1) & 0x03) +
369 GETLEN2b((packet_flags
>> 3) & 0x03) +
370 GETLEN2b((packet_flags
>> 5) & 0x03) + 6;
372 if (ci
->read_filebuf(data
, datalen
) == 0) {
373 DEBUGF("Detected end of stream4\n");
374 return ASF_ERROR_EOF
;
377 bytesread
+= datalen
;
380 length
= GETVALUE2b((packet_flags
>> 5) & 0x03, datap
);
381 datap
+= GETLEN2b((packet_flags
>> 5) & 0x03);
383 /* sequence value is not used */
384 GETVALUE2b((packet_flags
>> 1) & 0x03, datap
);
385 datap
+= GETLEN2b((packet_flags
>> 1) & 0x03);
386 padding_length
= GETVALUE2b((packet_flags
>> 3) & 0x03, datap
);
387 datap
+= GETLEN2b((packet_flags
>> 3) & 0x03);
388 send_time
= get_long_le(datap
);
390 *duration
= get_short_le(datap
);
392 /*the get_timestamp function advances us 12-13 bytes past the packet start,
393 need to undo this here so that we stay synced with the packet*/
394 ci
->seek_buffer(ci
->curpos
-bytesread
);
399 /*entry point for seeks*/
400 static int seek(int ms
, asf_waveformatex_t
* wfx
)
402 int time
, duration
, delta
, temp
, count
=0;
404 /*estimate packet number from bitrate*/
405 int initial_packet
= ci
->curpos
/wfx
->packet_size
;
406 int packet_num
= (((int64_t)ms
)*(wfx
->bitrate
>>3))/wfx
->packet_size
/1000;
407 int last_packet
= ci
->id3
->filesize
/ wfx
->packet_size
;
409 if (packet_num
> last_packet
) {
410 packet_num
= last_packet
;
413 /*calculate byte address of the start of that packet*/
414 int packet_offset
= packet_num
*wfx
->packet_size
;
416 /*seek to estimated packet*/
417 ci
->seek_buffer(ci
->id3
->first_frame_offset
+packet_offset
);
421 /*for very large files it can be difficult and unimportant to find the exact packet*/
424 /*check the time stamp of our packet*/
425 time
= get_timestamp(&duration
);
426 DEBUGF("seeked to %d ms with duration %d\n", time
, duration
);
429 /*unknown error, try to recover*/
430 DEBUGF("UKNOWN SEEK ERROR\n");
431 ci
->seek_buffer(ci
->id3
->first_frame_offset
+initial_packet
*wfx
->packet_size
);
432 /*seek failed so return time stamp of the initial packet*/
433 return get_timestamp(&duration
);
436 if ((time
+duration
>=ms
&& time
<=ms
) || count
> 10) {
437 DEBUGF("Found our packet! Now at %d packet\n", packet_num
);
442 /*estimate new packet number from bitrate and our current position*/
444 packet_num
= ((temp
/1000)*(wfx
->bitrate
>>3) - (wfx
->packet_size
>>1))/wfx
->packet_size
; //round down!
445 packet_offset
= packet_num
*wfx
->packet_size
;
446 ci
->seek_buffer(ci
->id3
->first_frame_offset
+packet_offset
);
453 /* this is the codec entry point */
454 enum codec_status
codec_main(void)
456 uint32_t elapsedtime
;
458 asf_waveformatex_t wfx
;
459 uint32_t currentframe
;
460 size_t resume_offset
;
468 /* Generic codec initialisation */
469 ci
->configure(CODEC_SET_FILEBUF_WATERMARK
, 1024*512);
471 ci
->configure(DSP_SET_SAMPLE_DEPTH
, 30);
475 /* Wait for the metadata to be read */
476 while (!*ci
->taginfo_ready
&& !ci
->stop_codec
)
481 /* Remember the resume position - when the codec is opened, the
482 playback engine will reset it. */
483 resume_offset
= ci
->id3
->offset
;
486 LOGF("WMA: Error initialising codec\n");
487 retval
= CODEC_ERROR
;
491 /* Copy the format metadata we've stored in the id3 TOC field. This
492 saves us from parsing it again here. */
493 memcpy(&wfx
, ci
->id3
->toc
, sizeof(wfx
));
495 if (wma_decode_init(&wmadec
,&wfx
) < 0) {
496 LOGF("WMA: Unsupported or corrupt file\n");
497 retval
= CODEC_ERROR
;
501 /* Now advance the file position to the first frame */
502 ci
->seek_buffer(ci
->id3
->first_frame_offset
);
504 ci
->configure(DSP_SWITCH_FREQUENCY
, wfx
.rate
);
505 ci
->configure(DSP_SET_STEREO_MODE
, wfx
.channels
== 1 ?
506 STEREO_MONO
: STEREO_INTERLEAVED
);
507 codec_set_replaygain(ci
->id3
);
509 /* The main decoding loop */
514 DEBUGF("**************** IN WMA.C ******************\n");
515 wma_decode_init(&wmadec
,&wfx
);
521 if (ci
->stop_codec
|| ci
->new_track
) {
525 /* Deal with any pending seek requests */
528 if (ci
->seek_time
== 1) {
530 goto next_track
; /* Pretend you never saw this... */
533 elapsedtime
= seek(ci
->seek_time
, &wfx
);
534 if (elapsedtime
< 1){
538 DEBUGF("Seek returned %d\n", (int)elapsedtime
);
539 ci
->set_elapsed(elapsedtime
);
541 /*flush the wma decoder state*/
542 wmadec
.last_superframe_len
= 0;
543 wmadec
.last_bitoffset
= 0;
548 res
= asf_read_packet(&audiobuf
, &audiobufsize
, &packetlength
, &wfx
);
551 /* We'll try to recover from a parse error a certain number of
552 * times. If we succeed, the error counter will be reset.
556 DEBUGF("read_packet error %d, errcount %d\n",wmares
, errcount
);
560 ci
->advance_buffer(packetlength
);
563 } else if (res
> 0) {
564 wma_decode_superframe_init(&wmadec
, audiobuf
, audiobufsize
);
566 for (i
=0; i
< wmadec
.nb_frames
; i
++)
568 wmares
= wma_decode_superframe_frame(&wmadec
,
570 audiobuf
, audiobufsize
);
575 /* Do the above, but for errors in decode. */
577 DEBUGF("WMA decode error %d, errcount %d\n",wmares
, errcount
);
581 ci
->advance_buffer(packetlength
);
584 } else if (wmares
> 0) {
585 ci
->pcmbuf_insert(decoded
, NULL
, wmares
);
586 elapsedtime
+= (wmares
*10)/(wfx
.rate
/100);
587 ci
->set_elapsed(elapsedtime
);
593 ci
->advance_buffer(packetlength
);
598 LOGF("WMA: Decoded %ld samples\n",elapsedtime
*wfx
.rate
/1000);
600 if (ci
->request_next_track())