/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Parser for MPEG streams * * Copyright (c) 2007 Michael Sevakis * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #include "plugin.h" #include "mpegplayer.h" struct stream_parser str_parser SHAREDBSS_ATTR; static void parser_init_state(void) { str_parser.last_seek_time = 0; str_parser.format = STREAM_FMT_UNKNOWN; str_parser.start_pts = INVALID_TIMESTAMP; str_parser.end_pts = INVALID_TIMESTAMP; str_parser.flags = 0; str_parser.dims.w = 0; str_parser.dims.h = 0; } /* Place the stream in a state to begin parsing - sync will be performed * first */ void str_initialize(struct stream *str, off_t pos) { /* Initial positions start here */ str->hdr.win_left = str->hdr.win_right = pos; /* No packet */ str->curr_packet = NULL; /* Pick up parsing from this point in the buffer */ str->curr_packet_end = disk_buf_offset2ptr(pos); /* No flags */ str->pkt_flags = 0; /* Sync first */ str->state = SSTATE_SYNC; } /* Place the stream in an end of data state */ void str_end_of_stream(struct stream *str) { /* Offsets that prevent this stream from being included in the * min left/max right window so that no buffering is triggered on * its behalf. Set right to the min first so a thread reading the * overall window gets doesn't see this as valid no matter what the * file length. */ str->hdr.win_right = OFF_T_MIN; str->hdr.win_left = OFF_T_MAX; /* No packets */ str->curr_packet = str->curr_packet_end = NULL; /* No flags */ str->pkt_flags = 0; /* Fin */ str->state = SSTATE_END; } /* Return a timestamp at address p+offset if the marker bits are in tact */ static inline uint32_t read_pts(uint8_t *p, off_t offset) { return TS_CHECK_MARKERS(p, offset) ? TS_FROM_HEADER(p, offset) : INVALID_TIMESTAMP; } static inline bool validate_timestamp(uint32_t ts) { return ts >= str_parser.start_pts && ts <= str_parser.end_pts; } /* Find a start code before or after a given position */ uint8_t * mpeg_parser_scan_start_code(struct stream_scan *sk, uint32_t code) { stream_scan_normalize(sk); if (sk->dir < 0) { /* Reverse scan - start with at least the min needed */ stream_scan_offset(sk, 4); } code &= 0xff; /* Only the low byte matters */ while (sk->len >= 0 && sk->margin >= 4) { uint8_t *p; off_t pos = disk_buf_lseek(sk->pos, SEEK_SET); ssize_t len = disk_buf_getbuffer_l2(&sk->l2, 4, &p); if (pos < 0 || len < 4) break; if (CMP_3_CONST(p, PACKET_START_CODE_PREFIX) && p[3] == code) { return p; } stream_scan_offset(sk, 1); } return NULL; } /* Find a PES packet header for any stream - return stream to which it * belongs */ unsigned mpeg_parser_scan_pes(struct stream_scan *sk) { stream_scan_normalize(sk); if (sk->dir < 0) { /* Reverse scan - start with at least the min needed */ stream_scan_offset(sk, 4); } while (sk->len >= 0 && sk->margin >= 4) { uint8_t *p; off_t pos = disk_buf_lseek(sk->pos, SEEK_SET); ssize_t len = disk_buf_getbuffer_l2(&sk->l2, 4, &p); if (pos < 0 || len < 4) break; if (CMP_3_CONST(p, PACKET_START_CODE_PREFIX)) { unsigned id = p[3]; if (id >= 0xb9) return id; /* PES header */ /* else some video stream element */ } stream_scan_offset(sk, 1); } return -1; } /* Return the first SCR found from the scan direction */ uint32_t mpeg_parser_scan_scr(struct stream_scan *sk) { uint8_t *p = mpeg_parser_scan_start_code(sk, MPEG_STREAM_PACK_HEADER); if (p != NULL && sk->margin >= 9) /* 9 bytes total required */ { sk->data = 9; if ((p[4] & 0xc0) == 0x40) /* mpeg-2 */ { /* Lookhead p+8 */ if (MPEG2_CHECK_PACK_SCR_MARKERS(p, 4)) return MPEG2_PACK_HEADER_SCR(p, 4); } else if ((p[4] & 0xf0) == 0x20) /* mpeg-1 */ { /* Lookahead p+8 */ if (TS_CHECK_MARKERS(p, 4)) return TS_FROM_HEADER(p, 4); } /* Weird pack header */ sk->data = 5; } return INVALID_TIMESTAMP; } uint32_t mpeg_parser_scan_pts(struct stream_scan *sk, unsigned id) { stream_scan_normalize(sk); if (sk->dir < 0) { /* Reverse scan - start with at least the min needed */ stream_scan_offset(sk, 4); } while (sk->len >= 0 && sk->margin >= 4) { uint8_t *p; off_t pos = disk_buf_lseek(sk->pos, SEEK_SET); ssize_t len = disk_buf_getbuffer_l2(&sk->l2, 30, &p); if (pos < 0 || len < 4) break; if (CMP_3_CONST(p, PACKET_START_CODE_PREFIX) && p[3] == id) { uint8_t *h = p; if (sk->margin < 7) { /* Insufficient data */ } else if ((h[6] & 0xc0) == 0x80) /* mpeg2 */ { if (sk->margin >= 14 && (h[7] & 0x80) != 0x00) { sk->data = 14; return read_pts(h, 9); } } else /* mpeg1 */ { ssize_t l = 6; ssize_t margin = sk->margin; /* Skip stuffing_byte */ while (margin > 7 && h[l] == 0xff && ++l <= 22) --margin; if (margin >= 7) { if ((h[l] & 0xc0) == 0x40) { /* Skip STD_buffer_scale and STD_buffer_size */ margin -= 2; l += 2; } if (margin >= 5) { /* Header points to the mpeg1 pes header */ h += l; if ((h[0] & 0xe0) == 0x20) { /* PTS or PTS_DTS indicated */ sk->data = (h + 5) - p; return read_pts(h, 0); } } } } /* No PTS present - keep searching for a matching PES header with * one */ } stream_scan_offset(sk, 1); } return INVALID_TIMESTAMP; } static bool init_video_info(void) { DEBUGF("Getting movie size\n"); /* The decoder handles this in order to initialize its knowledge of the * movie parameters making seeking easier */ str_send_msg(&video_str, STREAM_RESET, 0); if (str_send_msg(&video_str, VIDEO_GET_SIZE, (intptr_t)&str_parser.dims) != 0) { return true; } DEBUGF(" failed\n"); return false; } static bool init_times(struct stream *str) { struct stream tmp_str; const ssize_t filesize = disk_buf_filesize(); const ssize_t max_probe = MIN(512*1024, filesize); bool found_stream; /* Simply find the first earliest timestamp - this will be the one * used when streaming anyway */ DEBUGF("Finding start_pts: 0x%02x\n", str->id); found_stream = false; str->start_pts = INVALID_TIMESTAMP; str->end_pts = INVALID_TIMESTAMP; tmp_str.id = str->id; tmp_str.hdr.pos = 0; tmp_str.hdr.limit = max_probe; /* Probe for many for the start because some stamps could be anomalous. * Video also can also have things out of order. Just see what it's got. */ while (1) { switch (parser_get_next_data(&tmp_str, STREAM_PM_RANDOM_ACCESS)) { case STREAM_DATA_END: break; case STREAM_OK: found_stream = true; if (tmp_str.pkt_flags & PKT_HAS_TS) { if (tmp_str.pts < str->start_pts) str->start_pts = tmp_str.pts; } continue; } break; } if (!found_stream) { DEBUGF(" stream not found:0x%02x\n", str->id); return false; } DEBUGF(" start:%u\n", (unsigned)str->start_pts); /* Use the decoder thread to perform a synchronized search - no * decoding should take place but just a simple run through timestamps * and durations as the decoder would see them. This should give the * precise time at the end of the last frame for the stream. */ DEBUGF("Finding end_pts: 0x%02x\n", str->id); str_parser.parms.sd.time = MAX_TIMESTAMP; str_parser.parms.sd.sk.pos = filesize - max_probe; str_parser.parms.sd.sk.len = max_probe; str_parser.parms.sd.sk.dir = SSCAN_FORWARD; str_send_msg(str, STREAM_RESET, 0); if (str_send_msg(str, STREAM_FIND_END_TIME, (intptr_t)&str_parser.parms.sd) == STREAM_PERFECT_MATCH) { str->end_pts = str_parser.parms.sd.time; DEBUGF(" end:%u\n", (unsigned)str->end_pts); } return true; } static bool check_times(const struct stream *str) { return str->start_pts < str->end_pts && str->end_pts != INVALID_TIMESTAMP; } /* Return the best-fit file offset of a timestamp in the PES where * timstamp <= time < next timestamp. Will try to return something reasonably * valid if best-fit could not be made. */ static off_t mpeg_parser_seek_PTS(uint32_t time, unsigned id) { ssize_t pos_left = 0; ssize_t pos_right = disk_buf.filesize; ssize_t pos, pos_new; uint32_t time_left = str_parser.start_pts; uint32_t time_right = str_parser.end_pts; uint32_t pts = 0; uint32_t prevpts = 0; enum state_enum state = STATE0; struct stream_scan sk; stream_scan_init(&sk); /* Initial estimate taken from average bitrate - later interpolations are * taken similarly based on the remaining file interval */ pos_new = muldiv_uint32(time - time_left, pos_right - pos_left, time_right - time_left) + pos_left; /* return this estimated position if nothing better comes up */ pos = pos_new; DEBUGF("Seeking stream 0x%02x\n", id); DEBUGF("$$ tl:%u t:%u ct:?? tr:%u\n pl:%ld pn:%ld pr:%ld\n", (unsigned)time_left, (unsigned)time, (unsigned)time_right, (long)pos_left, (long)pos_new, (long)pos_right); sk.dir = SSCAN_REVERSE; while (state < STATE9) { uint32_t currpts; sk.pos = pos_new; sk.len = (sk.dir < 0) ? pos_new - pos_left : pos_right - pos_new; currpts = mpeg_parser_scan_pts(&sk, id); if (currpts != INVALID_TIMESTAMP) { ssize_t pos_adj; /* Adjustment to over or under-estimate */ /* Found a valid timestamp - see were it lies in relation to * target */ if (currpts < time) { /* Time at current position is before seek time - move * forward */ if (currpts > pts) { /* This is less than the desired time but greater than * the currently seeked one; move the position up */ pts = currpts; pos = sk.pos; } /* No next timestamp can be sooner */ pos_left = sk.pos + sk.data; time_left = currpts; if (pos_right <= pos_left) break; /* If the window disappeared - we're done */ pos_new = muldiv_uint32(time - time_left, pos_right - pos_left, time_right - time_left); /* Point is ahead of us - fudge estimate a bit high */ pos_adj = pos_new / 10; if (pos_adj > 512*1024) pos_adj = 512*1024; pos_new += pos_left + pos_adj; if (pos_new >= pos_right) { /* Estimate could push too far */ pos_new = pos_right; } state = STATE2; /* Last scan was early */ sk.dir = SSCAN_REVERSE; DEBUGF(">> tl:%u t:%u ct:%u tr:%u\n pl:%ld pn:%ld pr:%ld\n", (unsigned)time_left, (unsigned)time, (unsigned)currpts, (unsigned)time_right, (long)pos_left, (long)pos_new, (long)pos_right); } else if (currpts > time) { /* Time at current position is past seek time - move backward */ pos_right = sk.pos; time_right = currpts; if (pos_right <= pos_left) break; /* If the window disappeared - we're done */ pos_new = muldiv_uint32(time - time_left, pos_right - pos_left, time_right - time_left); /* Overshot the seek point - fudge estimate a bit low */ pos_adj = pos_new / 10; if (pos_adj > 512*1024) pos_adj = 512*1024; pos_new += pos_left - pos_adj; state = STATE3; /* Last scan was late */ sk.dir = SSCAN_REVERSE; DEBUGF("<< tl:%u t:%u ct:%u tr:%u\n pl:%ld pn:%ld pr:%ld\n", (unsigned)time_left, (unsigned)time, (unsigned)currpts, (unsigned)time_right, (long)pos_left, (long)pos_new, (long)pos_right); } else { /* Exact match - it happens */ DEBUGF("|| tl:%u t:%u ct:%u tr:%u\n pl:%ld pn:%ld pr:%ld\n", (unsigned)time_left, (unsigned)time, (unsigned)currpts, (unsigned)time_right, (long)pos_left, (long)pos_new, (long)pos_right); pts = currpts; pos = sk.pos; state = STATE9; } } else { /* Nothing found */ switch (state) { case STATE1: /* We already tried the bruteforce scan and failed again - no * more stamps could possibly exist in the interval */ DEBUGF("!! no timestamp 2x\n"); break; case STATE0: /* Hardly likely except at very beginning - just do L->R scan * to find something */ DEBUGF("!! no timestamp on first probe: %ld\n", sk.pos); case STATE2: case STATE3: /* Could just be missing timestamps because the interval is * narrowing down. A large block of data from another stream * may also be in the midst of our chosen points which could * cluster at either extreme end. If anything is there, this * will find it. */ pos_new = pos_left; sk.dir = SSCAN_FORWARD; DEBUGF("?? tl:%u t:%u ct:%u tr:%u\n pl:%ld pn:%ld pr:%ld\n", (unsigned)time_left, (unsigned)time, (unsigned)currpts, (unsigned)time_right, (long)pos_left, (long)pos_new, (long)pos_right); state = STATE1; break; default: DEBUGF("?? Invalid state: %d\n", state); } } /* Same timestamp twice = quit */ if (currpts == prevpts) { DEBUGF("!! currpts == prevpts (stop)\n"); state = STATE9; } prevpts = currpts; } #if defined(DEBUG) || defined(SIMULATOR) /* The next pts after the seeked-to position should be greater - * most of the time - frames out of presentation order may muck it * up a slight bit */ sk.pos = pos + 1; sk.len = disk_buf.filesize; sk.dir = SSCAN_FORWARD; uint32_t nextpts = mpeg_parser_scan_pts(&sk, id); DEBUGF("Seek pos:%ld pts:%u t:%u next pts:%u \n", (long)pos, (unsigned)pts, (unsigned)time, (unsigned)nextpts); if (pts <= time && time < nextpts) { /* Smile - it worked */ DEBUGF(" :) pts<=time time) { /* Hmm */ DEBUGF(" :\\ pts>time\n"); } if (pts >= nextpts) { /* Weird - probably because of encoded order & tends to be right * anyway if other criteria are met */ DEBUGF(" :p pts>=next pts\n"); } if (time >= nextpts) { /* Ugh */ DEBUGF(" :( time>=nextpts\n"); } } #endif return pos; } static void prepare_audio(uint32_t time) { off_t pos; if (!str_send_msg(&audio_str, STREAM_NEEDS_SYNC, time)) { DEBUGF("Audio was ready\n"); return; } pos = mpeg_parser_seek_PTS(time, audio_str.id); str_send_msg(&audio_str, STREAM_RESET, 0); str_parser.parms.sd.time = time; str_parser.parms.sd.sk.pos = pos; str_parser.parms.sd.sk.len = 1024*1024; str_parser.parms.sd.sk.dir = SSCAN_FORWARD; str_send_msg(&audio_str, STREAM_SYNC, (intptr_t)&str_parser.parms.sd); } /* This function demuxes the streams and gives the next stream data * pointer. * * STREAM_PM_STREAMING is for operation during playback. If the nescessary * data and worst-case lookahead margin is not available, the stream is * registered for notification when the data becomes available. If parsing * extends beyond the end of the file or the end of stream marker is reached, * STREAM_DATA_END is returned and the stream state changed to SSTATE_EOS. * * STREAM_PM_RANDOM_ACCESS is for operation when not playing such as seeking. * If the file cache misses for the current position + lookahead, it will be * loaded from disk. When the specified limit is reached, STREAM_DATA_END is * returned. * * The results from one mode may be used as input to the other. Random access * requires cooperation amongst threads to avoid evicting another stream's * data. */ static int parse_demux(struct stream *str, enum stream_parse_mode type) { #define INC_BUF(offset) \ ({ off_t _o = (offset); \ str->hdr.win_right += _o; \ if ((p += _o) >= disk_buf.end) \ p -= disk_buf.size; }) static const int mpeg1_skip_table[16] = { 0, 0, 4, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint8_t *p = str->curr_packet_end; str->pkt_flags = 0; while (1) { uint8_t *header; unsigned id; ssize_t length, bytes; switch (type) { case STREAM_PM_STREAMING: /* Has the end been reached already? */ switch (str->state) { case SSTATE_PARSE: /* Expected case first if no jumptable */ /* Are we at the end of file? */ if (str->hdr.win_left < disk_buf.filesize) break; str_end_of_stream(str); return STREAM_DATA_END; case SSTATE_SYNC: /* Is sync at the end of file? */ if (str->hdr.win_right < disk_buf.filesize) break; str_end_of_stream(str); /* Fall-through */ case SSTATE_END: return STREAM_DATA_END; } if (!disk_buf_is_data_ready(&str->hdr, MIN_BUFAHEAD)) { /* This data range is not buffered yet - register stream to * be notified when it becomes available. Stream is obliged * to enter a TSTATE_DATA state if it must wait. */ int res = str_next_data_not_ready(str); if (res != STREAM_OK) return res; } break; /* STREAM_PM_STREAMING: */ case STREAM_PM_RANDOM_ACCESS: str->hdr.pos = disk_buf_lseek(str->hdr.pos, SEEK_SET); if (str->hdr.pos < 0 || str->hdr.pos >= str->hdr.limit || disk_buf_getbuffer(MIN_BUFAHEAD, &p, NULL, NULL) <= 0) { str_end_of_stream(str); return STREAM_DATA_END; } str->state = SSTATE_SYNC; str->hdr.win_left = str->hdr.pos; str->curr_packet = NULL; str->curr_packet_end = p; break; /* STREAM_PM_RANDOM_ACCESS: */ } if (str->state == SSTATE_SYNC) { /* Scanning for start code */ if (!CMP_3_CONST(p, PACKET_START_CODE_PREFIX)) { INC_BUF(1); continue; } } /* Found a start code - enter parse state */ str->state = SSTATE_PARSE; /* Pack header, skip it */ if (CMP_4_CONST(p, PACK_START_CODE)) { /* Max lookahead: 14 */ if ((p[4] & 0xc0) == 0x40) /* mpeg-2 */ { /* Max delta: 14 + 7 = 21 */ /* Skip pack header and any stuffing bytes*/ bytes = 14 + (p[13] & 7); } else if ((p[4] & 0xf0) == 0x20) /* mpeg-1 */ { bytes = 12; } else /* unknown - skip it */ { DEBUGF("weird pack header!\n"); bytes = 5; } INC_BUF(bytes); } /* System header, parse and skip it - 6 bytes + size */ if (CMP_4_CONST(p, SYSTEM_HEADER_START_CODE)) { /* Skip start code */ /* Max Delta = 65535 + 6 = 65541 */ bytes = 6 + ((p[4] << 8) | p[5]); INC_BUF(bytes); } /* Packet header, parse it */ if (!CMP_3_CONST(p, PACKET_START_CODE_PREFIX)) { /* Problem? Meh...probably not but just a corrupted section. * Try to resync the parser which will probably succeed. */ DEBUGF("packet start code prefix not found: 0x%02x\n" " wl:%lu wr:%lu\n" " p:%p cp:%p cpe:%p\n" " dbs:%p dbe:%p dbt:%p\n", str->id, str->hdr.win_left, str->hdr.win_right, p, str->curr_packet, str->curr_packet_end, disk_buf.start, disk_buf.end, disk_buf.tail); str->state = SSTATE_SYNC; INC_BUF(1); /* Next byte - this one's no good */ continue; } /* We retrieve basic infos */ /* Maximum packet length: 6 + 65535 = 65541 */ id = p[3]; length = ((p[4] << 8) | p[5]) + 6; if (id != str->id) { switch (id) { case MPEG_STREAM_PROGRAM_END: /* end of stream */ str_end_of_stream(str); DEBUGF("MPEG program end: 0x%02x\n", str->id); return STREAM_DATA_END; case MPEG_STREAM_PACK_HEADER: case MPEG_STREAM_SYSTEM_HEADER: /* These shouldn't be here - no increment or resync * since we'll pick it up above. */ continue; default: /* It's not the packet we're looking for, skip it */ INC_BUF(length); continue; } } /* Ok, it's our packet */ header = p; if ((header[6] & 0xc0) == 0x80) /* mpeg2 */ { /* Max Lookahead: 18 */ /* Min length: 9 */ /* Max length: 9 + 255 = 264 */ length = 9 + header[8]; /* header points to the mpeg2 pes header */ if ((header[7] & 0x80) != 0) { /* header has a pts */ uint32_t pts = read_pts(header, 9); if (pts != INVALID_TIMESTAMP) { str->pts = pts; #if 0 /* DTS isn't used for anything since things just get decoded ASAP but keep the code around */ if (STREAM_IS_VIDEO(id)) { /* Video stream - header may have a dts as well */ str->dts = pts; if (header[7] & 0x40) != 0x00) { pts = read_pts(header, 14); if (pts != INVALID_TIMESTAMP) str->dts = pts; } } #endif str->pkt_flags |= PKT_HAS_TS; } } } else /* mpeg1 */ { /* Max lookahead: 24 + 2 + 9 = 35 */ /* Max len_skip: 24 + 2 = 26 */ /* Min length: 7 */ /* Max length: 24 + 2 + 9 = 35 */ off_t len_skip; uint8_t * ptsbuf; length = 7; while (header[length - 1] == 0xff) { if (++length > 23) { DEBUGF("Too much stuffing" ); break; } } if ((header[length - 1] & 0xc0) == 0x40) length += 2; len_skip = length; length += mpeg1_skip_table[header[length - 1] >> 4]; /* Header points to the mpeg1 pes header */ ptsbuf = header + len_skip; if ((ptsbuf[-1] & 0xe0) == 0x20 && TS_CHECK_MARKERS(ptsbuf, -1)) { /* header has a pts */ uint32_t pts = read_pts(ptsbuf, -1); if (pts != INVALID_TIMESTAMP) { str->pts = pts; #if 0 /* DTS isn't used for anything since things just get decoded ASAP but keep the code around */ if (STREAM_IS_VIDEO(id)) { /* Video stream - header may have a dts as well */ str->dts = pts; if (ptsbuf[-1] & 0xf0) == 0x30) { pts = read_pts(ptsbuf, 4); if (pts != INVALID_TIMESTAMP) str->dts = pts; } } #endif str->pkt_flags |= PKT_HAS_TS; } } } p += length; /* Max bytes: 6 + 65535 - 7 = 65534 */ bytes = 6 + (header[4] << 8) + header[5] - length; str->curr_packet = p; str->curr_packet_end = p + bytes; str->hdr.win_left = str->hdr.win_right + length; str->hdr.win_right = str->hdr.win_left + bytes; if (str->hdr.win_right > disk_buf.filesize) { /* No packet that exceeds end of file can be valid */ str_end_of_stream(str); return STREAM_DATA_END; } return STREAM_OK; } /* end while */ #undef INC_BUF } /* This simply reads data from the file one page at a time and returns a * pointer to it in the buffer. */ static int parse_elementary(struct stream *str, enum stream_parse_mode type) { uint8_t *p; ssize_t len = 0; str->pkt_flags = 0; switch (type) { case STREAM_PM_STREAMING: /* Has the end been reached already? */ if (str->state == SSTATE_END) return STREAM_DATA_END; /* Are we at the end of file? */ if (str->hdr.win_left >= disk_buf.filesize) { str_end_of_stream(str); return STREAM_DATA_END; } if (!disk_buf_is_data_ready(&str->hdr, MIN_BUFAHEAD)) { /* This data range is not buffered yet - register stream to * be notified when it becomes available. Stream is obliged * to enter a TSTATE_DATA state if it must wait. */ int res = str_next_data_not_ready(str); if (res != STREAM_OK) return res; } len = DISK_BUF_PAGE_SIZE; if ((size_t)(str->hdr.win_right + len) > (size_t)disk_buf.filesize) len = disk_buf.filesize - str->hdr.win_right; if (len <= 0) { str_end_of_stream(str); return STREAM_DATA_END; } p = str->curr_packet_end; if (p >= disk_buf.end) p -= disk_buf.size; break; /* STREAM_PM_STREAMING: */ case STREAM_PM_RANDOM_ACCESS: str->hdr.pos = disk_buf_lseek(str->hdr.pos, SEEK_SET); len = disk_buf_getbuffer(DISK_BUF_PAGE_SIZE, &p, NULL, NULL); if (len <= 0 || str->hdr.pos < 0 || str->hdr.pos >= str->hdr.limit) { str_end_of_stream(str); return STREAM_DATA_END; } break; /* STREAM_PM_RANDOM_ACCESS: */ } str->state = SSTATE_PARSE; str->curr_packet = p; str->curr_packet_end = p + len; str->hdr.win_left = str->hdr.win_right; str->hdr.win_right = str->hdr.win_left + len; return STREAM_OK; } bool parser_prepare_image(uint32_t time) { struct stream_scan sk; int tries; int result; stream_scan_init(&sk); if (!str_send_msg(&video_str, STREAM_NEEDS_SYNC, time)) { DEBUGF("Image was ready\n"); return true; /* Should already have the image */ } #ifdef HAVE_ADJUSTABLE_CPU_FREQ rb->cpu_boost(true); /* No interference with trigger_cpu_boost */ #endif str_send_msg(&video_str, STREAM_RESET, 0); sk.pos = parser_can_seek() ? mpeg_parser_seek_PTS(time, video_str.id) : 0; sk.len = sk.pos; sk.dir = SSCAN_REVERSE; tries = 1; try_again: if (mpeg_parser_scan_start_code(&sk, MPEG_START_GOP)) { DEBUGF("GOP found at: %ld\n", sk.pos); unsigned id = mpeg_parser_scan_pes(&sk); if (id != video_str.id && sk.pos > 0) { /* Not part of our stream */ DEBUGF(" wrong stream: 0x%02x\n", id); goto try_again; } /* This will hit the PES header since it's known to be there */ uint32_t pts = mpeg_parser_scan_pts(&sk, id); if (pts == INVALID_TIMESTAMP || pts > time) { DEBUGF(" wrong timestamp: %u\n", (unsigned)pts); goto try_again; } } str_parser.parms.sd.time = time; str_parser.parms.sd.sk.pos = MAX(sk.pos, 0); str_parser.parms.sd.sk.len = 1024*1024; str_parser.parms.sd.sk.dir = SSCAN_FORWARD; DEBUGF("thumb pos:%ld len:%ld\n", str_parser.parms.sd.sk.pos, (long)str_parser.parms.sd.sk.len); result = str_send_msg(&video_str, STREAM_SYNC, (intptr_t)&str_parser.parms.sd); if (result != STREAM_PERFECT_MATCH) { /* Two tries should be all that is nescessary to find the exact frame * if the first GOP actually started later than the timestamp - the * GOP just prior must then start on or earlier. */ if (++tries <= 2) goto try_again; } #ifdef HAVE_ADJUSTABLE_CPU_FREQ rb->cpu_boost(false); #endif return result > STREAM_OK; } /* Seek parser to the specified time and return absolute time. * No actual hard stuff is performed here. That's done when streaming is * about to begin or something from the current position is requested */ uint32_t parser_seek_time(uint32_t time) { if (!parser_can_seek()) time = 0; else if (time > str_parser.duration) time = str_parser.duration; str_parser.last_seek_time = time + str_parser.start_pts; return str_parser.last_seek_time; } void parser_prepare_streaming(void) { struct stream_window sw; DEBUGF("parser_prepare_streaming\n"); /* Prepare initial video frame */ parser_prepare_image(str_parser.last_seek_time); /* Sync audio stream */ if (audio_str.start_pts != INVALID_TIMESTAMP) prepare_audio(str_parser.last_seek_time); /* Prequeue some data and set buffer window */ if (!stream_get_window(&sw)) sw.left = sw.right = disk_buf.filesize; DEBUGF(" swl:%ld swr:%ld\n", sw.left, sw.right); if (sw.right > disk_buf.filesize - 4*MIN_BUFAHEAD) sw.right = disk_buf.filesize - 4*MIN_BUFAHEAD; disk_buf_prepare_streaming(sw.left, sw.right - sw.left + 4*MIN_BUFAHEAD); } int parser_init_stream(void) { if (disk_buf.in_file < 0) return STREAM_ERROR; /* TODO: Actually find which streams are available */ audio_str.id = MPEG_STREAM_AUDIO_FIRST; video_str.id = MPEG_STREAM_VIDEO_FIRST; /* Try to pull a video PES - if not found, try video init anyway which * should succeed if it really is a video-only stream */ video_str.hdr.pos = 0; video_str.hdr.limit = 256*1024; if (parse_demux(&video_str, STREAM_PM_RANDOM_ACCESS) == STREAM_OK) { /* Found a video packet - assume program stream */ str_parser.format = STREAM_FMT_MPEG_PS; str_parser.next_data = parse_demux; } else { /* No PES element found - assume video elementary stream */ str_parser.format = STREAM_FMT_MPV; str_parser.next_data = parse_elementary; } if (!init_video_info()) { /* Cannot determine video size, etc. */ parser_init_state(); return STREAM_UNSUPPORTED; } if (str_parser.format == STREAM_FMT_MPEG_PS) { /* Initalize start_pts and end_pts with the length (in 45kHz units) of * the movie. INVALID_TIMESTAMP if the time could not be determined */ if (!init_times(&video_str) || !check_times(&video_str)) { /* Must have video at least */ parser_init_state(); return STREAM_UNSUPPORTED; } str_parser.flags |= STREAMF_CAN_SEEK; if (init_times(&audio_str)) { /* Audio will be part of playback pool */ stream_add_stream(&audio_str); if (check_times(&audio_str)) { /* Overall duration is maximum span */ str_parser.start_pts = MIN(audio_str.start_pts, video_str.start_pts); str_parser.end_pts = MAX(audio_str.end_pts, video_str.end_pts); } else { /* Bad times on audio - use video times */ str_parser.start_pts = video_str.start_pts; str_parser.end_pts = video_str.end_pts; /* Questionable: could use bitrate seek and match video to that */ audio_str.start_pts = video_str.start_pts; audio_str.end_pts = video_str.end_pts; } } else { /* No audio stream - use video only */ str_parser.start_pts = video_str.start_pts; str_parser.end_pts = video_str.end_pts; } str_parser.last_seek_time = str_parser.start_pts; } else { /* There's no way to handle times on this without a full file * scan */ audio_str.start_pts = INVALID_TIMESTAMP; audio_str.end_pts = INVALID_TIMESTAMP; video_str.start_pts = 0; video_str.end_pts = INVALID_TIMESTAMP; str_parser.start_pts = 0; str_parser.end_pts = INVALID_TIMESTAMP; } /* Add video to playback pool */ stream_add_stream(&video_str); /* Cache duration - it's used very often */ str_parser.duration = str_parser.end_pts - str_parser.start_pts; DEBUGF("Movie info:\n" " size:%dx%d\n" " start:%u\n" " end:%u\n" " duration:%u\n", str_parser.dims.w, str_parser.dims.h, (unsigned)str_parser.start_pts, (unsigned)str_parser.end_pts, (unsigned)str_parser.duration); return STREAM_OK; } void parser_close_stream(void) { stream_remove_streams(); parser_init_state(); } bool parser_init(void) { parser_init_state(); return true; } 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
/*
** FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR decoding
** Copyright (C) 2003-2004 M. Bakker, Ahead Software AG, http://www.nero.com
**  
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
** 
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
** 
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software 
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
** Any non-GPL usage of this software or parts of this software is strictly
** forbidden.
**
** Commercial non-GPL licensing of this software is possible.
** For more info contact Ahead Software through Mpeg4AAClicense@nero.com.
**
** $Id$
**/

/*
   Reads the AAC bitstream as defined in 14496-3 (MPEG-4 Audio)
*/

#include "common.h"
#include "structs.h"

#include <stdlib.h>
#include <string.h>

#include "decoder.h"
#include "syntax.h"
#include "specrec.h"
#include "huffman.h"
#include "bits.h"
#include "pulse.h"
#include "analysis.h"
#include "drc.h"
#ifdef ERROR_RESILIENCE
#include "rvlc.h"
#endif
#ifdef SBR_DEC
#include "sbr_syntax.h"
#endif


/* static function declarations */
static void decode_sce_lfe(NeAACDecHandle hDecoder, NeAACDecFrameInfo *hInfo, bitfile *ld,
                           uint8_t id_syn_ele);
static void decode_cpe(NeAACDecHandle hDecoder, NeAACDecFrameInfo *hInfo, bitfile *ld,
                       uint8_t id_syn_ele);
static uint8_t single_lfe_channel_element(NeAACDecHandle hDecoder, bitfile *ld,
                                          uint8_t channel, uint8_t *tag);
static uint8_t channel_pair_element(NeAACDecHandle hDecoder, bitfile *ld,
                                    uint8_t channel, uint8_t *tag);
#ifdef COUPLING_DEC
static uint8_t coupling_channel_element(NeAACDecHandle hDecoder, bitfile *ld);
#endif
static uint16_t data_stream_element(NeAACDecHandle hDecoder, bitfile *ld);
static uint8_t program_config_element(program_config *pce, bitfile *ld);
static uint8_t fill_element(NeAACDecHandle hDecoder, bitfile *ld, drc_info *drc
#ifdef SBR_DEC
                            ,uint8_t sbr_ele
#endif
                            );
static uint8_t individual_channel_stream(NeAACDecHandle hDecoder, element *ele,
                                         bitfile *ld, ic_stream *ics, uint8_t scal_flag,
                                         int16_t *spec_data);
static uint8_t ics_info(NeAACDecHandle hDecoder, ic_stream *ics, bitfile *ld,
                        uint8_t common_window);
static uint8_t section_data(NeAACDecHandle hDecoder, ic_stream *ics, bitfile *ld);
static uint8_t scale_factor_data(NeAACDecHandle hDecoder, ic_stream *ics, bitfile *ld);
#ifdef SSR_DEC
static void gain_control_data(bitfile *ld, ic_stream *ics);
#endif
static uint8_t spectral_data(NeAACDecHandle hDecoder, ic_stream *ics, bitfile *ld,
                             int16_t *spectral_data);
static uint16_t extension_payload(bitfile *ld, drc_info *drc, uint16_t count);
static uint8_t pulse_data(ic_stream *ics, pulse_info *pul, bitfile *ld);
static void tns_data(ic_stream *ics, tns_info *tns, bitfile *ld);
#ifdef LTP_DEC
static uint8_t ltp_data(NeAACDecHandle hDecoder, ic_stream *ics, ltp_info *ltp, bitfile *ld);
#endif
static uint8_t adts_fixed_header(adts_header *adts, bitfile *ld);
static void adts_variable_header(adts_header *adts, bitfile *ld);
static void adts_error_check(adts_header *adts, bitfile *ld);
static uint8_t dynamic_range_info(bitfile *ld, drc_info *drc);
static uint8_t excluded_channels(bitfile *ld, drc_info *drc);
#ifdef SCALABLE_DEC
static int8_t aac_scalable_main_header(NeAACDecHandle hDecoder, ic_stream *ics1, ic_stream *ics2,
                                       bitfile *ld, uint8_t this_layer_stereo);
#endif


/* Table 4.4.1 */
int8_t GASpecificConfig(bitfile *ld, mp4AudioSpecificConfig *mp4ASC,
                        program_config *pce_out)
{
    program_config pce;

    /* 1024 or 960 */
    mp4ASC->frameLengthFlag = faad_get1bit(ld
        DEBUGVAR(1,138,"GASpecificConfig(): FrameLengthFlag"));
#ifndef ALLOW_SMALL_FRAMELENGTH
    if (mp4ASC->frameLengthFlag == 1)
        return -3;
#endif

    mp4ASC->dependsOnCoreCoder = faad_get1bit(ld
        DEBUGVAR(1,139,"GASpecificConfig(): DependsOnCoreCoder"));
    if (mp4ASC->dependsOnCoreCoder == 1)
    {
        mp4ASC->coreCoderDelay = (uint16_t)faad_getbits(ld, 14
            DEBUGVAR(1,140,"GASpecificConfig(): CoreCoderDelay"));
    }

    mp4ASC->extensionFlag = faad_get1bit(ld DEBUGVAR(1,141,"GASpecificConfig(): ExtensionFlag"));
    if (mp4ASC->channelsConfiguration == 0)
    {
        if (program_config_element(&pce, ld))
            return -3;
        //mp4ASC->channelsConfiguration = pce.channels;

        if (pce_out != NULL)
            memcpy(pce_out, &pce, sizeof(program_config));

        /*
        if (pce.num_valid_cc_elements)
            return -3;
        */
    }

#ifdef ERROR_RESILIENCE
    if (mp4ASC->extensionFlag == 1)
    {
        /* Error resilience not supported yet */
        if (mp4ASC->objectTypeIndex >= ER_OBJECT_START)
        {
            mp4ASC->aacSectionDataResilienceFlag = faad_get1bit(ld
                DEBUGVAR(1,144,"GASpecificConfig(): aacSectionDataResilienceFlag"));
            mp4ASC->aacScalefactorDataResilienceFlag = faad_get1bit(ld
                DEBUGVAR(1,145,"GASpecificConfig(): aacScalefactorDataResilienceFlag"));
            mp4ASC->aacSpectralDataResilienceFlag = faad_get1bit(ld
                DEBUGVAR(1,146,"GASpecificConfig(): aacSpectralDataResilienceFlag"));

            /* 1 bit: extensionFlag3 */
        }
    }
#endif

    return 0;
}

/* Table 4.4.2 */
/* An MPEG-4 Audio decoder is only required to follow the Program
   Configuration Element in GASpecificConfig(). The decoder shall ignore
   any Program Configuration Elements that may occur in raw data blocks.
   PCEs transmitted in raw data blocks cannot be used to convey decoder
   configuration information.
*/
static uint8_t program_config_element(program_config *pce, bitfile *ld)
{
    uint8_t i;

    memset(pce, 0, sizeof(program_config));

    pce->channels = 0;

    pce->element_instance_tag = (uint8_t)faad_getbits(ld, 4
        DEBUGVAR(1,10,"program_config_element(): element_instance_tag"));

    pce->object_type = (uint8_t)faad_getbits(ld, 2
        DEBUGVAR(1,11,"program_config_element(): object_type"));
    pce->sf_index = (uint8_t)faad_getbits(ld, 4
        DEBUGVAR(1,12,"program_config_element(): sf_index"));
    pce->num_front_channel_elements = (uint8_t)faad_getbits(ld, 4
        DEBUGVAR(1,13,"program_config_element(): num_front_channel_elements"));
    pce->num_side_channel_elements = (uint8_t)faad_getbits(ld, 4
        DEBUGVAR(1,14,"program_config_element(): num_side_channel_elements"));
    pce->num_back_channel_elements = (uint8_t)faad_getbits(ld, 4
        DEBUGVAR(1,15,"program_config_element(): num_back_channel_elements"));
    pce->num_lfe_channel_elements = (uint8_t)faad_getbits(ld, 2
        DEBUGVAR(1,16,"program_config_element(): num_lfe_channel_elements"));
    pce->num_assoc_data_elements = (uint8_t)faad_getbits(ld, 3
        DEBUGVAR(1,17,"program_config_element(): num_assoc_data_elements"));
    pce->num_valid_cc_elements = (uint8_t)faad_getbits(ld, 4
        DEBUGVAR(1,18,"program_config_element(): num_valid_cc_elements"));

    pce->mono_mixdown_present = faad_get1bit(ld
        DEBUGVAR(1,19,"program_config_element(): mono_mixdown_present"));
    if (pce->mono_mixdown_present == 1)
    {
        pce->mono_mixdown_element_number = (uint8_t)faad_getbits(ld, 4
            DEBUGVAR(1,20,"program_config_element(): mono_mixdown_element_number"));
    }

    pce->stereo_mixdown_present = faad_get1bit(ld
        DEBUGVAR(1,21,"program_config_element(): stereo_mixdown_present"));
    if (pce->stereo_mixdown_present == 1)
    {
        pce->stereo_mixdown_element_number = (uint8_t)faad_getbits(ld, 4
            DEBUGVAR(1,22,"program_config_element(): stereo_mixdown_element_number"));
    }

    pce->matrix_mixdown_idx_present = faad_get1bit(ld
        DEBUGVAR(1,23,"program_config_element(): matrix_mixdown_idx_present"));
    if (pce->matrix_mixdown_idx_present == 1)
    {
        pce->matrix_mixdown_idx = (uint8_t)faad_getbits(ld, 2
            DEBUGVAR(1,24,"program_config_element(): matrix_mixdown_idx"));
        pce->pseudo_surround_enable = faad_get1bit(ld
            DEBUGVAR(1,25,"program_config_element(): pseudo_surround_enable"));
    }

    for (i = 0; i < pce->num_front_channel_elements; i++)
    {
        pce->front_element_is_cpe[i] = faad_get1bit(ld
            DEBUGVAR(1,26,"program_config_element(): front_element_is_cpe"));
        pce->front_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
            DEBUGVAR(1,27,"program_config_element(): front_element_tag_select"));

        if (pce->front_element_is_cpe[i] & 1)
        {
            pce->cpe_channel[pce->front_element_tag_select[i]] = pce->channels;
            pce->num_front_channels += 2;
            pce->channels += 2;
        } else {
            pce->sce_channel[pce->front_element_tag_select[i]] = pce->channels;
            pce->num_front_channels++;
            pce->channels++;
        }
    }

    for (i = 0; i < pce->num_side_channel_elements; i++)
    {
        pce->side_element_is_cpe[i] = faad_get1bit(ld
            DEBUGVAR(1,28,"program_config_element(): side_element_is_cpe"));
        pce->side_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
            DEBUGVAR(1,29,"program_config_element(): side_element_tag_select"));

        if (pce->side_element_is_cpe[i] & 1)
        {
            pce->cpe_channel[pce->side_element_tag_select[i]] = pce->channels;
            pce->num_side_channels += 2;
            pce->channels += 2;
        } else {
            pce->sce_channel[pce->side_element_tag_select[i]] = pce->channels;
            pce->num_side_channels++;
            pce->channels++;
        }
    }

    for (i = 0; i < pce->num_back_channel_elements; i++)
    {
        pce->back_element_is_cpe[i] = faad_get1bit(ld
            DEBUGVAR(1,30,"program_config_element(): back_element_is_cpe"));
        pce->back_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
            DEBUGVAR(1,31,"program_config_element(): back_element_tag_select"));

        if (pce->back_element_is_cpe[i] & 1)
        {
            pce->cpe_channel[pce->back_element_tag_select[i]] = pce->channels;
            pce->channels += 2;
            pce->num_back_channels += 2;
        } else {
            pce->sce_channel[pce->back_element_tag_select[i]] = pce->channels;
            pce->num_back_channels++;
            pce->channels++;
        }
    }

    for (i = 0; i < pce->num_lfe_channel_elements; i++)
    {
        pce->lfe_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
            DEBUGVAR(1,32,"program_config_element(): lfe_element_tag_select"));

        pce->sce_channel[pce->lfe_element_tag_select[i]] = pce->channels;
        pce->num_lfe_channels++;
        pce->channels++;
    }

    for (i = 0; i < pce->num_assoc_data_elements; i++)
        pce->assoc_data_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
        DEBUGVAR(1,33,"program_config_element(): assoc_data_element_tag_select"));

    for (i = 0; i < pce->num_valid_cc_elements; i++)
    {
        pce->cc_element_is_ind_sw[i] = faad_get1bit(ld
            DEBUGVAR(1,34,"program_config_element(): cc_element_is_ind_sw"));
        pce->valid_cc_element_tag_select[i] = (uint8_t)faad_getbits(ld, 4
            DEBUGVAR(1,35,"program_config_element(): valid_cc_element_tag_select"));
    }

    faad_byte_align(ld);

    pce->comment_field_bytes = (uint8_t)faad_getbits(ld, 8
        DEBUGVAR(1,36,"program_config_element(): comment_field_bytes"));

    for (i = 0; i < pce->comment_field_bytes; i++)
    {
        pce->comment_field_data[i] = (uint8_t)faad_getbits(ld, 8
            DEBUGVAR(1,37,"program_config_element(): comment_field_data"));
    }
    pce->comment_field_data[i] = 0;

    if (pce->channels > MAX_CHANNELS)
        return 22;

    return 0;
}

static void decode_sce_lfe(NeAACDecHandle hDecoder,
                           NeAACDecFrameInfo *hInfo, bitfile *ld,
                           uint8_t id_syn_ele)
{
    uint8_t channels = hDecoder->fr_channels;
    uint8_t tag = 0;

    if (channels+1 > MAX_CHANNELS)
    {
        hInfo->error = 12;
        return;
    }
    if (hDecoder->fr_ch_ele+1 > MAX_SYNTAX_ELEMENTS)
    {
        hInfo->error = 13;
        return;
    }

    /* for SCE hDecoder->element_output_channels[] is not set here because this
       can become 2 when some form of Parametric Stereo coding is used
    */

    /* save the syntax element id */
    hDecoder->element_id[hDecoder->fr_ch_ele] = id_syn_ele;

    /* decode the element */
    hInfo->error = single_lfe_channel_element(hDecoder, ld, channels, &tag);

    /* map output channels position to internal data channels */
    if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 2)
    {
        /* this might be faulty when pce_set is true */
        hDecoder->internal_channel[channels] = channels;
        hDecoder->internal_channel[channels+1] = channels+1;
    } else {
        if (hDecoder->pce_set)
            hDecoder->internal_channel[hDecoder->pce.sce_channel[tag]] = channels;
        else
            hDecoder->internal_channel[channels] = channels;
    }

    hDecoder->fr_channels += hDecoder->element_output_channels[hDecoder->fr_ch_ele];
    hDecoder->fr_ch_ele++;
}

static void decode_cpe(NeAACDecHandle hDecoder, NeAACDecFrameInfo *hInfo, bitfile *ld,
                       uint8_t id_syn_ele)
{
    uint8_t channels = hDecoder->fr_channels;
    uint8_t tag = 0;

    if (channels+2 > MAX_CHANNELS)
    {
        hInfo->error = 12;
        return;
    }
    if (hDecoder->fr_ch_ele+1 > MAX_SYNTAX_ELEMENTS)
    {
        hInfo->error = 13;
        return;
    }

    /* for CPE the number of output channels is always 2 */
    if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 0)
    {
        /* element_output_channels not set yet */
        hDecoder->element_output_channels[hDecoder->fr_ch_ele] = 2;
    } else if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] != 2) {
        /* element inconsistency */
        hInfo->error = 21;
        return;
    }

    /* save the syntax element id */
    hDecoder->element_id[hDecoder->fr_ch_ele] = id_syn_ele;

    /* decode the element */
    hInfo->error = channel_pair_element(hDecoder, ld, channels, &tag);

    /* map output channel position to internal data channels */
    if (hDecoder->pce_set)
    {
        hDecoder->internal_channel[hDecoder->pce.cpe_channel[tag]] = channels;
        hDecoder->internal_channel[hDecoder->pce.cpe_channel[tag]+1] = channels+1;
    } else {
        hDecoder->internal_channel[channels] = channels;
        hDecoder->internal_channel[channels+1] = channels+1;
    }

    hDecoder->fr_channels += 2;
    hDecoder->fr_ch_ele++;
}

void raw_data_block(NeAACDecHandle hDecoder, NeAACDecFrameInfo *hInfo,
                    bitfile *ld, program_config *pce, drc_info *drc)
{
    uint8_t id_syn_ele;

    hDecoder->fr_channels = 0;
    hDecoder->fr_ch_ele = 0;
    hDecoder->first_syn_ele = 25;
    hDecoder->has_lfe = 0;

#ifdef ERROR_RESILIENCE
    if (hDecoder->object_type < ER_OBJECT_START)
    {
#endif
        /* Table 4.4.3: raw_data_block() */
        while ((id_syn_ele = (uint8_t)faad_getbits(ld, LEN_SE_ID
            DEBUGVAR(1,4,"NeAACDecDecode(): id_syn_ele"))) != ID_END)
        {
            switch (id_syn_ele) {
            case ID_SCE:
                if (hDecoder->first_syn_ele == 25) hDecoder->first_syn_ele = id_syn_ele;
                decode_sce_lfe(hDecoder, hInfo, ld, id_syn_ele);
                if (hInfo->error > 0)
                    return;
                break;
            case ID_CPE:
                if (hDecoder->first_syn_ele == 25) hDecoder->first_syn_ele = id_syn_ele;
                decode_cpe(hDecoder, hInfo, ld, id_syn_ele);
                if (hInfo->error > 0)
                    return;
                break;
            case ID_LFE:
                hDecoder->has_lfe++;
                decode_sce_lfe(hDecoder, hInfo, ld, id_syn_ele);
                if (hInfo->error > 0)
                    return;
                break;
            case ID_CCE: /* not implemented yet, but skip the bits */
#ifdef COUPLING_DEC
                hInfo->error = coupling_channel_element(hDecoder, ld);
#else
                hInfo->error = 6;
#endif
                if (hInfo->error > 0)
                    return;
                break;
            case ID_DSE:
                data_stream_element(hDecoder, ld);
                break;
            case ID_PCE:
                /* 14496-4: 5.6.4.1.2.1.3: */
                /* program_configuration_element()'s in access units shall be ignored */
                program_config_element(pce, ld);
                //if ((hInfo->error = program_config_element(pce, ld)) > 0)
                //    return;
                //hDecoder->pce_set = 1;
                break;
            case ID_FIL:
                /* one sbr_info describes a channel_element not a channel! */
                /* if we encounter SBR data here: error */
                /* SBR data will be read directly in the SCE/LFE/CPE element */
                if ((hInfo->error = fill_element(hDecoder, ld, drc
#ifdef SBR_DEC
                    , INVALID_SBR_ELEMENT
#endif
                    )) > 0)
                    return;
                break;
            }
        }
#ifdef ERROR_RESILIENCE
    } else {
        /* Table 262: er_raw_data_block() */
        switch (hDecoder->channelConfiguration)
        {
        case 1:
            decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
            if (hInfo->error > 0)
                return;
            break;
        case 2:
            decode_cpe(hDecoder, hInfo, ld, ID_CPE);
            if (hInfo->error > 0)
                return;
            break;
        case 3:
            decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
            decode_cpe(hDecoder, hInfo, ld, ID_CPE);
            if (hInfo->error > 0)
                return;
            break;
        case 4:
            decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
            decode_cpe(hDecoder, hInfo, ld, ID_CPE);
            decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
            if (hInfo->error > 0)
                return;
            break;
        case 5:
            decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
            decode_cpe(hDecoder, hInfo, ld, ID_CPE);
            decode_cpe(hDecoder, hInfo, ld, ID_CPE);
            if (hInfo->error > 0)
                return;
            break;
        case 6:
            decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
            decode_cpe(hDecoder, hInfo, ld, ID_CPE);
            decode_cpe(hDecoder, hInfo, ld, ID_CPE);
            decode_sce_lfe(hDecoder, hInfo, ld, ID_LFE);
            if (hInfo->error > 0)
                return;
            break;
        case 7: /* 8 channels */
            decode_sce_lfe(hDecoder, hInfo, ld, ID_SCE);
            decode_cpe(hDecoder, hInfo, ld, ID_CPE);
            decode_cpe(hDecoder, hInfo, ld, ID_CPE);
            decode_cpe(hDecoder, hInfo, ld, ID_CPE);
            decode_sce_lfe(hDecoder, hInfo, ld, ID_LFE);
            if (hInfo->error > 0)
                return;
            break;
        default:
            hInfo->error = 7;
            return;
        }
#if 0
        cnt = bits_to_decode() / 8;
        while (cnt >= 1)
        {
            cnt -= extension_payload(cnt);
        }
#endif
    }
#endif

    /* new in corrigendum 14496-3:2002 */
#ifdef DRM
    if (hDecoder->object_type != DRM_ER_LC)
#endif
    {
        faad_byte_align(ld);
    }

    return;
}

/* Table 4.4.4 and */
/* Table 4.4.9 */
ALIGN int16_t spec_data[1024] = {0};
element sce;
static uint8_t single_lfe_channel_element(NeAACDecHandle hDecoder, bitfile *ld,
                                          uint8_t channel, uint8_t *tag)
{
    uint8_t retval = 0;
    ic_stream *ics = &(sce.ics1);

    memset(spec_data,0,sizeof(spec_data));
    memset(&sce,0,sizeof(sce));
    sce.element_instance_tag = (uint8_t)faad_getbits(ld, LEN_TAG
        DEBUGVAR(1,38,"single_lfe_channel_element(): element_instance_tag"));

    *tag = sce.element_instance_tag;
    sce.channel = channel;
    sce.paired_channel = -1;

    retval = individual_channel_stream(hDecoder, &sce, ld, ics, 0, spec_data);
    if (retval > 0)
        return retval;

#ifdef SBR_DEC
    /* check if next bitstream element is a fill element */
    /* if so, read it now so SBR decoding can be done in case of a file with SBR */
    if (faad_showbits(ld, LEN_SE_ID) == ID_FIL)
    {
        faad_flushbits(ld, LEN_SE_ID);

        /* one sbr_info describes a channel_element not a channel! */
        if ((retval = fill_element(hDecoder, ld, hDecoder->drc, hDecoder->fr_ch_ele)) > 0)
        {
            return retval;
        }
    }
#endif

    /* noiseless coding is done, spectral reconstruction is done now */
    retval = reconstruct_single_channel(hDecoder, ics, &sce, spec_data);
    if (retval > 0)
        return retval;

    return 0;
}

/* Table 4.4.5 */
ALIGN int16_t spec_data1[1024] IBSS_ATTR;
ALIGN int16_t spec_data2[1024] IBSS_ATTR;
element cpe;
static uint8_t channel_pair_element(NeAACDecHandle hDecoder, bitfile *ld,
                                    uint8_t channels, uint8_t *tag)
{
    ic_stream *ics1 = &(cpe.ics1);
    ic_stream *ics2 = &(cpe.ics2);
    uint8_t result;

    memset(spec_data1,0,sizeof(spec_data1));
    memset(spec_data2,0,sizeof(spec_data2));
    memset(&cpe,0,sizeof(cpe));
    cpe.channel        = channels;
    cpe.paired_channel = channels+1;

    cpe.element_instance_tag = (uint8_t)faad_getbits(ld, LEN_TAG
        DEBUGVAR(1,39,"channel_pair_element(): element_instance_tag"));
    *tag = cpe.element_instance_tag;

    if ((cpe.common_window = faad_get1bit(ld
        DEBUGVAR(1,40,"channel_pair_element(): common_window"))) & 1)
    {
        /* both channels have common ics information */
        if ((result = ics_info(hDecoder, ics1, ld, cpe.common_window)) > 0)
            return result;

        ics1->ms_mask_present = (uint8_t)faad_getbits(ld, 2
            DEBUGVAR(1,41,"channel_pair_element(): ms_mask_present"));
        if (ics1->ms_mask_present == 1)
        {
            uint8_t g, sfb;
            for (g = 0; g < ics1->num_window_groups; g++)
            {
                for (sfb = 0; sfb < ics1->max_sfb; sfb++)
                {
                    ics1->ms_used[g][sfb] = faad_get1bit(ld
                        DEBUGVAR(1,42,"channel_pair_element(): faad_get1bit"));
                }
            }
        }

#ifdef ERROR_RESILIENCE
        if ((hDecoder->object_type >= ER_OBJECT_START) && (ics1->predictor_data_present))
        {
            if ((
#ifdef LTP_DEC
                ics1->ltp.data_present =
#endif
                faad_get1bit(ld DEBUGVAR(1,50,"channel_pair_element(): ltp.data_present"))) & 1)
            {
#ifdef LTP_DEC
                if ((result = ltp_data(hDecoder, ics1, &(ics1->ltp), ld)) > 0)
                {
                    return result;
                }
#else
                return 26;
#endif
            }
        }
#endif

        memcpy(ics2, ics1, sizeof(ic_stream));
    } else {
        ics1->ms_mask_present = 0;
    }

    if ((result = individual_channel_stream(hDecoder, &cpe, ld, ics1,
        0, spec_data1)) > 0)
    {
        return result;
    }

#ifdef ERROR_RESILIENCE
    if (cpe.common_window && (hDecoder->object_type >= ER_OBJECT_START) &&
        (ics1->predictor_data_present))
    {
        if ((
#ifdef LTP_DEC
            ics1->ltp2.data_present =
#endif
            faad_get1bit(ld DEBUGVAR(1,50,"channel_pair_element(): ltp.data_present"))) & 1)
        {
#ifdef LTP_DEC
            if ((result = ltp_data(hDecoder, ics1, &(ics1->ltp2), ld)) > 0)
            {
                return result;
            }
#else
            return 26;
#endif
        }
    }
#endif

    if ((result = individual_channel_stream(hDecoder, &cpe, ld, ics2,
        0, spec_data2)) > 0)
    {
        return result;
    }

#ifdef SBR_DEC
    /* check if next bitstream element is a fill element */
    /* if so, read it now so SBR decoding can be done in case of a file with SBR */
    if (faad_showbits(ld, LEN_SE_ID) == ID_FIL)
    {
        faad_flushbits(ld, LEN_SE_ID);

        /* one sbr_info describes a channel_element not a channel! */
        if ((result = fill_element(hDecoder, ld, hDecoder->drc, hDecoder->fr_ch_ele)) > 0)
        {
            return result;
        }
    }
#endif

    /* noiseless coding is done, spectral reconstruction is done now */
    if ((result = reconstruct_channel_pair(hDecoder, ics1, ics2, &cpe,
        spec_data1, spec_data2)) > 0)
    {
        return result;
    }

    return 0;
}

/* Table 4.4.6 */
static uint8_t ics_info(NeAACDecHandle hDecoder, ic_stream *ics, bitfile *ld,
                        uint8_t common_window)
{
    uint8_t retval = 0;

    /* ics->ics_reserved_bit = */ faad_get1bit(ld
        DEBUGVAR(1,43,"ics_info(): ics_reserved_bit"));
    ics->window_sequence = (uint8_t)faad_getbits(ld, 2
        DEBUGVAR(1,44,"ics_info(): window_sequence"));
    ics->window_shape = faad_get1bit(ld
        DEBUGVAR(1,45,"ics_info(): window_shape"));

    if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
    {
        ics->max_sfb = (uint8_t)faad_getbits(ld, 4
            DEBUGVAR(1,46,"ics_info(): max_sfb (short)"));
        ics->scale_factor_grouping = (uint8_t)faad_getbits(ld, 7
            DEBUGVAR(1,47,"ics_info(): scale_factor_grouping"));
    } else {
        ics->max_sfb = (uint8_t)faad_getbits(ld, 6
            DEBUGVAR(1,48,"ics_info(): max_sfb (long)"));
    }

    /* get the grouping information */
    if ((retval = window_grouping_info(hDecoder, ics)) > 0)
        return retval;

    /* should be an error */
    /* check the range of max_sfb */
    if (ics->max_sfb > ics->num_swb)
        return 16;

    if (ics->window_sequence != EIGHT_SHORT_SEQUENCE)
    {
        if ((ics->predictor_data_present = faad_get1bit(ld
            DEBUGVAR(1,49,"ics_info(): predictor_data_present"))) & 1)
        {
            if (hDecoder->object_type == MAIN) /* MPEG2 style AAC predictor */
            {
                uint8_t sfb;

                uint8_t limit = min(ics->max_sfb, max_pred_sfb(hDecoder->sf_index));
#ifdef MAIN_DEC
                ics->pred.limit = limit;
#endif

                if ((
#ifdef MAIN_DEC
                    ics->pred.predictor_reset =
#endif
                    faad_get1bit(ld DEBUGVAR(1,53,"ics_info(): pred.predictor_reset"))) & 1)
                {
#ifdef MAIN_DEC
                    ics->pred.predictor_reset_group_number =
                        (uint8_t)
#endif
                        faad_getbits(ld, 5 DEBUGVAR(1,54,"ics_info(): pred.predictor_reset_group_number"));
                }

                for (sfb = 0; sfb < limit; sfb++)
                {
#ifdef MAIN_DEC
                    ics->pred.prediction_used[sfb] =
#endif
                        faad_get1bit(ld DEBUGVAR(1,55,"ics_info(): pred.prediction_used"));
                }
            }
#ifdef LTP_DEC
            else { /* Long Term Prediction */
                if (hDecoder->object_type < ER_OBJECT_START)
                {
                    if ((ics->ltp.data_present = faad_get1bit(ld
                        DEBUGVAR(1,50,"ics_info(): ltp.data_present"))) & 1)
                    {
                        if ((retval = ltp_data(hDecoder, ics, &(ics->ltp), ld)) > 0)
                        {
                            return retval;
                        }
                    }
                    if (common_window)
                    {
                        if ((ics->ltp2.data_present = faad_get1bit(ld
                            DEBUGVAR(1,51,"ics_info(): ltp2.data_present"))) & 1)
                        {
                            if ((retval = ltp_data(hDecoder, ics, &(ics->ltp2), ld)) > 0)
                            {
                                return retval;
                            }
                        }
                    }
                }
#ifdef ERROR_RESILIENCE
                if (!common_window && (hDecoder->object_type >= ER_OBJECT_START))
                {
                    if ((ics->ltp.data_present = faad_get1bit(ld
                        DEBUGVAR(1,50,"ics_info(): ltp.data_present"))) & 1)
                    {
                        ltp_data(hDecoder, ics, &(ics->ltp), ld);
                    }
                }
#endif
            }
#else
            (void) common_window;
#endif
        }
    }

    return retval;
}

/* Table 4.4.7 */
static uint8_t pulse_data(ic_stream *ics, pulse_info *pul, bitfile *ld)
{
    uint8_t i;

    pul->number_pulse = (uint8_t)faad_getbits(ld, 2
        DEBUGVAR(1,56,"pulse_data(): number_pulse"));
    pul->pulse_start_sfb = (uint8_t)faad_getbits(ld, 6
        DEBUGVAR(1,57,"pulse_data(): pulse_start_sfb"));

    /* check the range of pulse_start_sfb */
    if (pul->pulse_start_sfb > ics->num_swb)
        return 16;

    for (i = 0; i < pul->number_pulse+1; i++)
    {
        pul->pulse_offset[i] = (uint8_t)faad_getbits(ld, 5
            DEBUGVAR(1,58,"pulse_data(): pulse_offset"));
#if 0
        printf("%d\n", pul->pulse_offset[i]);
#endif
        pul->pulse_amp[i] = (uint8_t)faad_getbits(ld, 4
            DEBUGVAR(1,59,"pulse_data(): pulse_amp"));
#if 0
        printf("%d\n", pul->pulse_amp[i]);
#endif
    }

    return 0;
}

#ifdef COUPLING_DEC
/* Table 4.4.8: Currently just for skipping the bits... */
static uint8_t coupling_channel_element(NeAACDecHandle hDecoder, bitfile *ld)
{
    uint8_t c, result = 0;
    uint8_t ind_sw_cce_flag = 0;
    uint8_t num_gain_element_lists = 0;
    uint8_t num_coupled_elements = 0;

    element el_empty = {0};
    ic_stream ics_empty = {0};
    static int16_t sh_data[1024];

    c = faad_getbits(ld, LEN_TAG
        DEBUGVAR(1,900,"coupling_channel_element(): element_instance_tag"));

    ind_sw_cce_flag = faad_get1bit(ld
        DEBUGVAR(1,901,"coupling_channel_element(): ind_sw_cce_flag"));
    num_coupled_elements = faad_getbits(ld, 3
        DEBUGVAR(1,902,"coupling_channel_element(): num_coupled_elements"));

    for (c = 0; c < num_coupled_elements + 1; c++)
    {
        uint8_t cc_target_is_cpe, cc_target_tag_select;

        num_gain_element_lists++;

        cc_target_is_cpe = faad_get1bit(ld
            DEBUGVAR(1,903,"coupling_channel_element(): cc_target_is_cpe"));
        cc_target_tag_select = faad_getbits(ld, 4
            DEBUGVAR(1,904,"coupling_channel_element(): cc_target_tag_select"));

        if (cc_target_is_cpe)
        {
            uint8_t cc_l = faad_get1bit(ld
                DEBUGVAR(1,905,"coupling_channel_element(): cc_l"));
            uint8_t cc_r = faad_get1bit(ld
                DEBUGVAR(1,906,"coupling_channel_element(): cc_r"));

            if (cc_l && cc_r)
                num_gain_element_lists++;
        }
    }

    faad_get1bit(ld
        DEBUGVAR(1,907,"coupling_channel_element(): cc_domain"));
    faad_get1bit(ld
        DEBUGVAR(1,908,"coupling_channel_element(): gain_element_sign"));
    faad_getbits(ld, 2
        DEBUGVAR(1,909,"coupling_channel_element(): gain_element_scale"));

    if ((result = individual_channel_stream(hDecoder, &el_empty, ld, &ics_empty,
        0, sh_data)) > 0)
    {
        return result;
    }

    for (c = 1; c < num_gain_element_lists; c++)
    {
        uint8_t cge;

        if (ind_sw_cce_flag)
        {
            cge = 1;
        } else {
            cge = faad_get1bit(ld
                DEBUGVAR(1,910,"coupling_channel_element(): common_gain_element_present"));
        }

        if (cge)
        {
            huffman_scale_factor(ld);
        } else {
            uint8_t g, sfb;

            for (g = 0; g < ics_empty.num_window_groups; g++)
            {
                for (sfb = 0; sfb < ics_empty.max_sfb; sfb++)
                {
                    if (ics_empty.sfb_cb[g][sfb] != ZERO_HCB)
                        huffman_scale_factor(ld);
                }
            }
        }
    }

    return 0;
}
#endif

/* Table 4.4.10 */
static uint16_t data_stream_element(NeAACDecHandle hDecoder, bitfile *ld)
{
    uint8_t byte_aligned;
    uint16_t i, count;

    (void)hDecoder;

    /* element_instance_tag = */ faad_getbits(ld, LEN_TAG
        DEBUGVAR(1,60,"data_stream_element(): element_instance_tag"));
    byte_aligned = faad_get1bit(ld
        DEBUGVAR(1,61,"data_stream_element(): byte_aligned"));
    count = (uint16_t)faad_getbits(ld, 8
        DEBUGVAR(1,62,"data_stream_element(): count"));
    if (count == 255)
    {
        count += (uint16_t)faad_getbits(ld, 8
            DEBUGVAR(1,63,"data_stream_element(): extra count"));
    }
    if (byte_aligned)
        faad_byte_align(ld);

    for (i = 0; i < count; i++)
    {
        faad_getbits(ld, LEN_BYTE
            DEBUGVAR(1,64,"data_stream_element(): data_stream_byte"));
    }

    return count;
}

/* Table 4.4.11 */
static uint8_t fill_element(NeAACDecHandle hDecoder, bitfile *ld, drc_info *drc
#ifdef SBR_DEC
                            ,uint8_t sbr_ele
#endif
                            )
{
    uint16_t count;
#ifdef SBR_DEC
    uint8_t bs_extension_type;
#endif

    count = (uint16_t)faad_getbits(ld, 4
        DEBUGVAR(1,65,"fill_element(): count"));
    if (count == 15)
    {
        count += (uint16_t)faad_getbits(ld, 8
            DEBUGVAR(1,66,"fill_element(): extra count")) - 1;
    }

    if (count > 0)
    {
#ifdef SBR_DEC
        bs_extension_type = (uint8_t)faad_showbits(ld, 4);

        if ((bs_extension_type == EXT_SBR_DATA) ||
            (bs_extension_type == EXT_SBR_DATA_CRC))
        {
            if (sbr_ele == INVALID_SBR_ELEMENT)
                return 24;

            if (!hDecoder->sbr[sbr_ele])
            {
                hDecoder->sbr[sbr_ele] = sbrDecodeInit(hDecoder->frameLength,
                    hDecoder->element_id[sbr_ele], 2*get_sample_rate(hDecoder->sf_index),
                    hDecoder->downSampledSBR
#ifdef DRM
                    , 0
#endif
                    );
            }

            hDecoder->sbr_present_flag = 1;

            /* parse the SBR data */
            hDecoder->sbr[sbr_ele]->ret = sbr_extension_data(ld, hDecoder->sbr[sbr_ele], count);

#if 0
            if (hDecoder->sbr[sbr_ele]->ret > 0)
            {
                printf("%s\n", NeAACDecGetErrorMessage(hDecoder->sbr[sbr_ele]->ret));
            }
#endif

#if (defined(PS_DEC) || defined(DRM_PS))
            if (hDecoder->sbr[sbr_ele]->ps_used)
            {
                hDecoder->ps_used[sbr_ele] = 1;

                /* set element independent flag to 1 as well */
                hDecoder->ps_used_global = 1;
            }
#endif
        } else {
#endif
            while (count > 0)
            {
                count -= extension_payload(ld, drc, count);
            }
#ifdef SBR_DEC
        }
#endif
    }

    return 0;
}

/* Table 4.4.12 */
#ifdef SSR_DEC
static void gain_control_data(bitfile *ld, ic_stream *ics)
{
    uint8_t bd, wd, ad;
    ssr_info *ssr = &(ics->ssr);

    ssr->max_band = (uint8_t)faad_getbits(ld, 2
        DEBUGVAR(1,1000,"gain_control_data(): max_band"));

    if (ics->window_sequence == ONLY_LONG_SEQUENCE)
    {
        for (bd = 1; bd <= ssr->max_band; bd++)
        {
            for (wd = 0; wd < 1; wd++)
            {
                ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
                    DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));

                for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
                {
                    ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
                        DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
                    ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 5
                        DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
                }
            }
        }
    } else if (ics->window_sequence == LONG_START_SEQUENCE) {
        for (bd = 1; bd <= ssr->max_band; bd++)
        {
            for (wd = 0; wd < 2; wd++)
            {
                ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
                    DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));

                for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
                {
                    ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
                        DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
                    if (wd == 0)
                    {
                        ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
                            DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
                    } else {
                        ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 2
                            DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
                    }
                }
            }
        }
    } else if (ics->window_sequence == EIGHT_SHORT_SEQUENCE) {
        for (bd = 1; bd <= ssr->max_band; bd++)
        {
            for (wd = 0; wd < 8; wd++)
            {
                ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
                    DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));

                for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
                {
                    ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
                        DEBUGVAR(1,1002,"gain_control_data(): alevcode"));
                    ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 2
                        DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
                }
            }
        }
    } else if (ics->window_sequence == LONG_STOP_SEQUENCE) {
        for (bd = 1; bd <= ssr->max_band; bd++)
        {
            for (wd = 0; wd < 2; wd++)
            {
                ssr->adjust_num[bd][wd] = (uint8_t)faad_getbits(ld, 3
                    DEBUGVAR(1,1001,"gain_control_data(): adjust_num"));

                for (ad = 0; ad < ssr->adjust_num[bd][wd]; ad++)
                {
                    ssr->alevcode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
                        DEBUGVAR(1,1002,"gain_control_data(): alevcode"));

                    if (wd == 0)
                    {
                        ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 4
                            DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
                    } else {
                        ssr->aloccode[bd][wd][ad] = (uint8_t)faad_getbits(ld, 5
                            DEBUGVAR(1,1003,"gain_control_data(): aloccode"));
                    }
                }
            }
        }
    }
}
#endif

#ifdef SCALABLE_DEC
ALIGN int16_t spec_data1[1024];
ALIGN int16_t spec_data2[1024];
/* Table 4.4.13 ASME */
void aac_scalable_main_element(NeAACDecHandle hDecoder, NeAACDecFrameInfo *hInfo,
                               bitfile *ld, program_config *pce, drc_info *drc)
{
    uint8_t retval = 0;
    uint8_t channels = hDecoder->fr_channels = 0;
    uint8_t ch;
    uint8_t this_layer_stereo = (hDecoder->channelConfiguration > 1) ? 1 : 0;
    element cpe = {0};
    ic_stream *ics1 = &(cpe.ics1);
    ic_stream *ics2 = &(cpe.ics2);
    int16_t *spec_data;

    memset(spec_data1,0,sizeof(spec_data1));
    memset(spec_data2,0,sizeof(spec_data2));
    hDecoder->fr_ch_ele = 0;

    hInfo->error = aac_scalable_main_header(hDecoder, ics1, ics2, ld, this_layer_stereo);
    if (hInfo->error > 0)
        return;

    cpe.common_window = 1;
    if (this_layer_stereo)
    {
        hDecoder->element_id[0] = ID_CPE;
        if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 0)
            hDecoder->element_output_channels[hDecoder->fr_ch_ele] = 2;
    } else {
        hDecoder->element_id[0] = ID_SCE;
    }

    for (ch = 0; ch < (this_layer_stereo ? 2 : 1); ch++)
    {
        ic_stream *ics;
        if (ch == 0)
        {
            ics = ics1;
            spec_data = spec_data1;
        } else {
            ics = ics2;
            spec_data = spec_data2;
        }

        hInfo->error = individual_channel_stream(hDecoder, &cpe, ld, ics, 1, spec_data);
        if (hInfo->error > 0)
            return;
    }

#ifdef DRM
#ifdef SBR_DEC
    /* In case of DRM we need to read the SBR info before channel reconstruction */
    if ((hDecoder->sbr_present_flag == 1) && (hDecoder->object_type == DRM_ER_LC))
    {
        bitfile ld_sbr = {0};
        uint32_t i;
        uint16_t count = 0;
        uint8_t *revbuffer;
        uint8_t *prevbufstart;
        uint8_t *pbufend;

        /* all forward bitreading should be finished at this point */
        uint32_t bitsconsumed = faad_get_processed_bits(ld);
        uint32_t buffer_size = faad_origbitbuffer_size(ld);
        uint8_t *buffer = (uint8_t*)faad_origbitbuffer(ld);

        if (bitsconsumed + 8 > buffer_size*8)
        {
            hInfo->error = 14;
            return;
        }

        if (!hDecoder->sbr[0])
        {
            hDecoder->sbr[0] = sbrDecodeInit(hDecoder->frameLength, hDecoder->element_id[0],
                2*get_sample_rate(hDecoder->sf_index), 0 /* ds SBR */, 1);
        }

        /* Reverse bit reading of SBR data in DRM audio frame */
        revbuffer = (uint8_t*)faad_malloc(buffer_size*sizeof(uint8_t));
        prevbufstart = revbuffer;
        pbufend = &buffer[buffer_size - 1];
        for (i = 0; i < buffer_size; i++)
            *prevbufstart++ = tabFlipbits[*pbufend--];

        /* Set SBR data */
        /* consider 8 bits from AAC-CRC */
        count = (uint16_t)bit2byte(buffer_size*8 - bitsconsumed);
        faad_initbits(&ld_sbr, revbuffer, count);

        hDecoder->sbr[0]->sample_rate = get_sample_rate(hDecoder->sf_index);
        hDecoder->sbr[0]->sample_rate *= 2;

        faad_getbits(&ld_sbr, 8); /* Skip 8-bit CRC */

        hDecoder->sbr[0]->ret = sbr_extension_data(&ld_sbr, hDecoder->sbr[0], count);
#if (defined(PS_DEC) || defined(DRM_PS))
        if (hDecoder->sbr[0]->ps_used)
        {
            hDecoder->ps_used[0] = 1;
            hDecoder->ps_used_global = 1;
        }
#endif

        /* check CRC */
        /* no need to check it if there was already an error */
        if (hDecoder->sbr[0]->ret == 0)
            hDecoder->sbr[0]->ret = (uint8_t)faad_check_CRC(&ld_sbr, (uint16_t)faad_get_processed_bits(&ld_sbr) - 8);

        /* SBR data was corrupted, disable it until the next header */
        if (hDecoder->sbr[0]->ret != 0)
        {
            hDecoder->sbr[0]->header_count = 0;  
        }

        faad_endbits(&ld_sbr);

        if (revbuffer)
            faad_free(revbuffer);
    }
#endif
#endif

    if (this_layer_stereo)
    {
        hInfo->error = reconstruct_channel_pair(hDecoder, ics1, ics2, &cpe, spec_data1, spec_data2);
        if (hInfo->error > 0)
            return;
    } else {
        hInfo->error = reconstruct_single_channel(hDecoder, ics1, &cpe, spec_data1);
        if (hInfo->error > 0)
            return;
    }

    /* map output channels position to internal data channels */
    if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 2)
    {
        /* this might be faulty when pce_set is true */
        hDecoder->internal_channel[channels] = channels;
        hDecoder->internal_channel[channels+1] = channels+1;
    } else {
        hDecoder->internal_channel[channels] = channels;
    }

    hDecoder->fr_channels += hDecoder->element_output_channels[hDecoder->fr_ch_ele];
    hDecoder->fr_ch_ele++;

    return;
}

/* Table 4.4.15 */
static int8_t aac_scalable_main_header(NeAACDecHandle hDecoder, ic_stream *ics1, ic_stream *ics2,
                                       bitfile *ld, uint8_t this_layer_stereo)
{
    uint8_t retval = 0;
    uint8_t ch;
    ic_stream *ics;

    /* ics1->ics_reserved_bit = */ faad_get1bit(ld
        DEBUGVAR(1,300,"aac_scalable_main_header(): ics_reserved_bits"));
    ics1->window_sequence = (uint8_t)faad_getbits(ld, 2
        DEBUGVAR(1,301,"aac_scalable_main_header(): window_sequence"));
    ics1->window_shape = faad_get1bit(ld
        DEBUGVAR(1,302,"aac_scalable_main_header(): window_shape"));

    if (ics1->window_sequence == EIGHT_SHORT_SEQUENCE)
    {
        ics1->max_sfb = (uint8_t)faad_getbits(ld, 4
            DEBUGVAR(1,303,"aac_scalable_main_header(): max_sfb (short)"));
        ics1->scale_factor_grouping = (uint8_t)faad_getbits(ld, 7
            DEBUGVAR(1,304,"aac_scalable_main_header(): scale_factor_grouping"));
    } else {
        ics1->max_sfb = (uint8_t)faad_getbits(ld, 6
            DEBUGVAR(1,305,"aac_scalable_main_header(): max_sfb (long)"));
    }

    /* get the grouping information */
    if ((retval = window_grouping_info(hDecoder, ics1)) > 0)
        return retval;

    /* should be an error */
    /* check the range of max_sfb */
    if (ics1->max_sfb > ics1->num_swb)
        return 16;

    if (this_layer_stereo)
    {
        ics1->ms_mask_present = (uint8_t)faad_getbits(ld, 2
            DEBUGVAR(1,306,"aac_scalable_main_header(): ms_mask_present"));
        if (ics1->ms_mask_present == 1)
        {
            uint8_t g, sfb;
            for (g = 0; g < ics1->num_window_groups; g++)
            {
                for (sfb = 0; sfb < ics1->max_sfb; sfb++)
                {
                    ics1->ms_used[g][sfb] = faad_get1bit(ld
                        DEBUGVAR(1,307,"aac_scalable_main_header(): faad_get1bit"));
                }
            }
        }

        memcpy(ics2, ics1, sizeof(ic_stream));
    } else {
        ics1->ms_mask_present = 0;
    }

    if (0)
    {
        faad_get1bit(ld
            DEBUGVAR(1,308,"aac_scalable_main_header(): tns_channel_mono_layer"));
    }

    for (ch = 0; ch < (this_layer_stereo ? 2 : 1); ch++)
    {
        if (ch == 0)
            ics = ics1;
        else
            ics = ics2;

        if ( 1 /*!tvq_layer_pesent || (tns_aac_tvq_en[ch] == 1)*/)
        {
            if ((ics->tns_data_present = faad_get1bit(ld
                DEBUGVAR(1,309,"aac_scalable_main_header(): tns_data_present"))) & 1)
            {
#ifdef DRM
                /* different order of data units in DRM */
                if (hDecoder->object_type != DRM_ER_LC)
#endif
                {
                    tns_data(ics, &(ics->tns), ld);
                }
            }
        }
#if 0
        if (0 /*core_flag || tvq_layer_pesent*/)
        {
            if ((ch==0) || ((ch==1) && (core_stereo || tvq_stereo))
                diff_control_data();
            if (mono_stereo_flag)
                diff_control_data_lr();
        } else {
#endif
            if ((
#ifdef LTP_DEC
                ics->ltp.data_present =
#endif
                faad_get1bit(ld DEBUGVAR(1,310,"aac_scalable_main_header(): ltp.data_present"))) & 1)
            {
#ifdef LTP_DEC
                if ((retval = ltp_data(hDecoder, ics, &(ics->ltp), ld)) > 0)
                {
                    return retval;
                }
#else
                return 26;
#endif
            }
#if 0
        }
#endif
    }

    return 0;
}
#endif

/* Table 4.4.24 */
static uint8_t individual_channel_stream(NeAACDecHandle hDecoder, element *ele,
                                         bitfile *ld, ic_stream *ics, uint8_t scal_flag,
                                         int16_t *spec_data)
{
    uint8_t result;

    ics->global_gain = (uint8_t)faad_getbits(ld, 8
        DEBUGVAR(1,67,"individual_channel_stream(): global_gain"));

    if (!ele->common_window && !scal_flag)
    {
        if ((result = ics_info(hDecoder, ics, ld, ele->common_window)) > 0)
            return result;
    }

    if ((result = section_data(hDecoder, ics, ld)) > 0)
        return result;

    if ((result = scale_factor_data(hDecoder, ics, ld)) > 0)
        return result;

    if (!scal_flag)
    {
        /**
         **  NOTE: It could be that pulse data is available in scalable AAC too,
         **        as said in Amendment 1, this could be only the case for ER AAC,
         **        though. (have to check this out later)
         **/
        /* get pulse data */
        if ((ics->pulse_data_present = faad_get1bit(ld
            DEBUGVAR(1,68,"individual_channel_stream(): pulse_data_present"))) & 1)
        {
            if ((result = pulse_data(ics, &(ics->pul), ld)) > 0)
                return result;
        }

        /* get tns data */
        if ((ics->tns_data_present = faad_get1bit(ld
            DEBUGVAR(1,69,"individual_channel_stream(): tns_data_present"))) & 1)
        {
#ifdef ERROR_RESILIENCE
            if (hDecoder->object_type < ER_OBJECT_START)
#endif
                tns_data(ics, &(ics->tns), ld);
        }

        /* get gain control data */
        if ((ics->gain_control_data_present = faad_get1bit(ld
            DEBUGVAR(1,70,"individual_channel_stream(): gain_control_data_present"))) & 1)
        {
#ifdef SSR_DEC
            if (hDecoder->object_type != SSR)
                return 1;
            else
                gain_control_data(ld, ics);
#else
            return 1;
#endif
        }
    }

#ifdef ERROR_RESILIENCE
    if (hDecoder->aacSpectralDataResilienceFlag)
    {
        ics->length_of_reordered_spectral_data = (uint16_t)faad_getbits(ld, 14
            DEBUGVAR(1,147,"individual_channel_stream(): length_of_reordered_spectral_data"));

        if (hDecoder->channelConfiguration == 2)
        {
            if (ics->length_of_reordered_spectral_data > 6144)
                ics->length_of_reordered_spectral_data = 6144;
        } else {
            if (ics->length_of_reordered_spectral_data > 12288)
                ics->length_of_reordered_spectral_data = 12288;
        }

        ics->length_of_longest_codeword = (uint8_t)faad_getbits(ld, 6
            DEBUGVAR(1,148,"individual_channel_stream(): length_of_longest_codeword"));
        if (ics->length_of_longest_codeword >= 49)
            ics->length_of_longest_codeword = 49;
    }

    /* RVLC spectral data is put here */
    if (hDecoder->aacScalefactorDataResilienceFlag)
    {
        if ((result = rvlc_decode_scale_factors(ics, ld)) > 0)
            return result;
    }

    if (hDecoder->object_type >= ER_OBJECT_START) 
    {
        if (ics->tns_data_present)
            tns_data(ics, &(ics->tns), ld);
    }

#ifdef DRM
    /* CRC check */
    if (hDecoder->object_type == DRM_ER_LC)
        if ((result = (uint8_t)faad_check_CRC(ld, (uint16_t)faad_get_processed_bits(ld) - 8)) > 0)
            return result;
#endif

    if (hDecoder->aacSpectralDataResilienceFlag)
    {
        /* error resilient spectral data decoding */
        if ((result = reordered_spectral_data(hDecoder, ics, ld, spec_data)) > 0)
        {
            return result;
        }
    } else {
#endif
        /* decode the spectral data */
        if ((result = spectral_data(hDecoder, ics, ld, spec_data)) > 0)
        {
            return result;
        }
#ifdef ERROR_RESILIENCE
    }
#endif

    /* pulse coding reconstruction */
    if (ics->pulse_data_present)
    {
        if (ics->window_sequence != EIGHT_SHORT_SEQUENCE)
        {
            if ((result = pulse_decode(ics, spec_data, hDecoder->frameLength)) > 0)
                return result;
        } else {
            return 2; /* pulse coding not allowed for short blocks */
        }
    }

    return 0;
}

/* Table 4.4.25 */
static uint8_t section_data(NeAACDecHandle hDecoder, ic_stream *ics, bitfile *ld)
{
    uint8_t g;
    uint8_t sect_esc_val, sect_bits;

    if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
        sect_bits = 3;
    else
        sect_bits = 5;
    sect_esc_val = (1<<sect_bits) - 1;

#if 0
    printf("\ntotal sfb %d\n", ics->max_sfb);
    printf("   sect    top     cb\n");
#endif

    for (g = 0; g < ics->num_window_groups; g++)
    {
        uint8_t k = 0;
        uint8_t i = 0;

        while (k < ics->max_sfb)
        {
#ifdef ERROR_RESILIENCE
            uint8_t vcb11 = 0;
#endif
            uint8_t sfb;
            uint8_t sect_len_incr;
            uint16_t sect_len = 0;
            uint8_t sect_cb_bits = 4;

            /* if "faad_getbits" detects error and returns "0", "k" is never
               incremented and we cannot leave the while loop */
            if ((ld->error != 0) || (ld->no_more_reading))
                return 14;

#ifdef ERROR_RESILIENCE
            if (hDecoder->aacSectionDataResilienceFlag)
                sect_cb_bits = 5;
#else
            (void) hDecoder;
#endif

            ics->sect_cb[g][i] = (uint8_t)faad_getbits(ld, sect_cb_bits
                DEBUGVAR(1,71,"section_data(): sect_cb"));

#if 0
            printf("%d\n", ics->sect_cb[g][i]);
#endif

            if (ics->sect_cb[g][i] == NOISE_HCB)
                ics->noise_used = 1;

#ifdef ERROR_RESILIENCE
            if (hDecoder->aacSectionDataResilienceFlag)
            {
                if ((ics->sect_cb[g][i] == 11) ||
                    ((ics->sect_cb[g][i] >= 16) && (ics->sect_cb[g][i] <= 32)))
                {
                    vcb11 = 1;
                }
            }
            if (vcb11)
            {
                sect_len_incr = 1;
            } else {
#endif
                sect_len_incr = (uint8_t)faad_getbits(ld, sect_bits
                    DEBUGVAR(1,72,"section_data(): sect_len_incr"));
#ifdef ERROR_RESILIENCE
            }
#endif
            while ((sect_len_incr == sect_esc_val) /* &&
                (k+sect_len < ics->max_sfb)*/)
            {
                sect_len += sect_len_incr;
                sect_len_incr = (uint8_t)faad_getbits(ld, sect_bits
                    DEBUGVAR(1,72,"section_data(): sect_len_incr"));
            }

            sect_len += sect_len_incr;

            ics->sect_start[g][i] = k;
            ics->sect_end[g][i] = k + sect_len;

#if 0
            printf("%d\n", ics->sect_start[g][i]);
#endif
#if 0
            printf("%d\n", ics->sect_end[g][i]);
#endif

            if (k + sect_len >= 8*15)
                return 15;
            if (i >= 8*15)
                return 15;

            for (sfb = k; sfb < k + sect_len; sfb++)
            {
                ics->sfb_cb[g][sfb] = ics->sect_cb[g][i];
#if 0
                printf("%d\n", ics->sfb_cb[g][sfb]);
#endif
            }

#if 0
            printf(" %6d %6d %6d\n",
                i,
                ics->sect_end[g][i],
                ics->sect_cb[g][i]);
#endif

            k += sect_len;
            i++;
        }
        ics->num_sec[g] = i;
#if 0
        printf("%d\n", ics->num_sec[g]);
#endif
    }

#if 0
    printf("\n");
#endif

    return 0;
}

/*
 *  decode_scale_factors()
 *   decodes the scalefactors from the bitstream
 */
/*
 * All scalefactors (and also the stereo positions and pns energies) are
 * transmitted using Huffman coded DPCM relative to the previous active
 * scalefactor (respectively previous stereo position or previous pns energy,
 * see subclause 4.6.2 and 4.6.3). The first active scalefactor is
 * differentially coded relative to the global gain.
 */
static uint8_t decode_scale_factors(ic_stream *ics, bitfile *ld)
{
    uint8_t g, sfb;
    int16_t t;
    int8_t noise_pcm_flag = 1;

    int16_t scale_factor = ics->global_gain;
    int16_t is_position = 0;
    int16_t noise_energy = ics->global_gain - 90;

    for (g = 0; g < ics->num_window_groups; g++)
    {
        for (sfb = 0; sfb < ics->max_sfb; sfb++)
        {
            switch (ics->sfb_cb[g][sfb])
            {
            case ZERO_HCB: /* zero book */
                ics->scale_factors[g][sfb] = 0;
//#define SF_PRINT
#ifdef SF_PRINT
                printf("%d\n", ics->scale_factors[g][sfb]);
#endif
                break;
            case INTENSITY_HCB: /* intensity books */
            case INTENSITY_HCB2:

                /* decode intensity position */
                t = huffman_scale_factor(ld);
                is_position += (t - 60);
                ics->scale_factors[g][sfb] = is_position;
#ifdef SF_PRINT
                printf("%d\n", ics->scale_factors[g][sfb]);
#endif

                break;
            case NOISE_HCB: /* noise books */