/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * mpegplayer audio thread implementation * * 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" #include "codecs/libmad/bit.h" #include "codecs/libmad/mad.h" /** Audio stream and thread **/ struct pts_queue_slot; struct audio_thread_data { struct queue_event ev; /* Our event queue to receive commands */ int state; /* Thread state */ int status; /* Media status (STREAM_PLAYING, etc.) */ int mad_errors; /* A count of the errors in each frame */ unsigned samplerate; /* Current stream sample rate */ int nchannels; /* Number of audio channels */ struct dsp_config *dsp; /* The DSP we're using */ }; /* The audio thread is stolen from the core codec thread */ static struct event_queue audio_str_queue SHAREDBSS_ATTR; static struct queue_sender_list audio_str_queue_send SHAREDBSS_ATTR; struct stream audio_str IBSS_ATTR; /* libmad related definitions */ static struct mad_stream stream IBSS_ATTR; static struct mad_frame frame IBSS_ATTR; static struct mad_synth synth IBSS_ATTR; /*sbsample buffer for mad_frame*/ mad_fixed_t sbsample[2][36][32]; /* 2567 bytes */ static unsigned char mad_main_data[MAD_BUFFER_MDLEN]; /* There isn't enough room for this in IRAM on PortalPlayer, but there is for Coldfire. */ /* 4608 bytes */ #if defined(CPU_COLDFIRE) || defined(CPU_S5L870X) static mad_fixed_t mad_frame_overlap[2][32][18] IBSS_ATTR; #else static mad_fixed_t mad_frame_overlap[2][32][18]; #endif /** A queue for saving needed information about MPEG audio packets **/ #define AUDIODESC_QUEUE_LEN (1 << 5) /* 32 should be way more than sufficient - if not, the case is handled */ #define AUDIODESC_QUEUE_MASK (AUDIODESC_QUEUE_LEN-1) struct audio_frame_desc { uint32_t time; /* Time stamp for packet in audio ticks */ ssize_t size; /* Number of unprocessed bytes left in packet */ }; /* This starts out wr == rd but will never be emptied to zero during streaming again in order to support initializing the first packet's timestamp without a special case */ struct { /* Compressed audio data */ uint8_t *start; /* Start of encoded audio buffer */ uint8_t *ptr; /* Pointer to next encoded audio data */ ssize_t used; /* Number of bytes in MPEG audio buffer */ /* Compressed audio data descriptors */ unsigned read, write; struct audio_frame_desc *curr; /* Current slot */ struct audio_frame_desc descs[AUDIODESC_QUEUE_LEN]; } audio_queue; static inline int audiodesc_queue_count(void) { return audio_queue.write - audio_queue.read; } static inline bool audiodesc_queue_full(void) { return audio_queue.used >= MPA_MAX_FRAME_SIZE + MAD_BUFFER_GUARD || audiodesc_queue_count() >= AUDIODESC_QUEUE_LEN; } /* Increments the queue tail postion - should be used to preincrement */ static inline void audiodesc_queue_add_tail(void) { if (audiodesc_queue_full()) { DEBUGF("audiodesc_queue_add_tail: audiodesc queue full!\n"); return; } audio_queue.write++; } /* Increments the queue tail position - leaves one slot as current */ static inline bool audiodesc_queue_remove_head(void) { if (audio_queue.write == audio_queue.read) return false; audio_queue.read++; return true; } /* Returns the "tail" at the index just behind the write index */ static inline struct audio_frame_desc * audiodesc_queue_tail(void) { return &audio_queue.descs[(audio_queue.write - 1) & AUDIODESC_QUEUE_MASK]; } /* Returns a pointer to the current head */ static inline struct audio_frame_desc * audiodesc_queue_head(void) { return &audio_queue.descs[audio_queue.read & AUDIODESC_QUEUE_MASK]; } /* Resets the pts queue - call when starting and seeking */ static void audio_queue_reset(void) { audio_queue.ptr = audio_queue.start; audio_queue.used = 0; audio_queue.read = 0; audio_queue.write = 0; rb->memset(audio_queue.descs, 0, sizeof (audio_queue.descs)); audio_queue.curr = audiodesc_queue_head(); } static void audio_queue_advance_pos(ssize_t len) { audio_queue.ptr += len; audio_queue.used -= len; audio_queue.curr->size -= len; } static int audio_buffer(struct stream *str, enum stream_parse_mode type) { int ret = STREAM_OK; /* Carry any overshoot to the next size since we're technically -size bytes into it already. If size is negative an audio frame was split across packets. Old has to be saved before moving the head. */ if (audio_queue.curr->size <= 0 && audiodesc_queue_remove_head()) { struct audio_frame_desc *old = audio_queue.curr; audio_queue.curr = audiodesc_queue_head(); audio_queue.curr->size += old->size; old->size = 0; } /* Add packets to compressed audio buffer until it's full or the * timestamp queue is full - whichever happens first */ while (!audiodesc_queue_full()) { ret = parser_get_next_data(str, type); struct audio_frame_desc *curr; ssize_t len; if (ret != STREAM_OK) break; /* Get data from next audio packet */ len = str->curr_packet_end - str->curr_packet; if (str->pkt_flags & PKT_HAS_TS) { audiodesc_queue_add_tail(); curr = audiodesc_queue_tail(); curr->time = TS_TO_TICKS(str->pts); /* pts->size should have been zeroed when slot was freed */ } else { /* Add to the one just behind the tail - this may be * the head or the previouly added tail - whether or * not we'll ever reach this is quite in question * since audio always seems to have every packet * timestamped */ curr = audiodesc_queue_tail(); } curr->size += len; /* Slide any remainder over to beginning */ if (audio_queue.ptr > audio_queue.start && audio_queue.used > 0) { rb->memmove(audio_queue.start, audio_queue.ptr, audio_queue.used); } /* Splice this packet onto any remainder */ rb->memcpy(audio_queue.start + audio_queue.used, str->curr_packet, len); audio_queue.used += len; audio_queue.ptr = audio_queue.start; rb->yield(); } return ret; } /* Initialise libmad */ static void init_mad(void) { /* init the sbsample buffer */ frame.sbsample_prev = &sbsample; frame.sbsample = &sbsample; /* We do this so libmad doesn't try to call codec_calloc(). This needs to * be called before mad_stream_init(), mad_frame_inti() and * mad_synth_init(). */ frame.overlap = &mad_frame_overlap; stream.main_data = &mad_main_data; /* Call mad initialization. Those will zero the arrays frame.overlap, * frame.sbsample and frame.sbsample_prev. Therefore there is no need to * zero them here. */ mad_stream_init(&stream); mad_frame_init(&frame); mad_synth_init(&synth); } /* Sync audio stream to a particular frame - see main decoder loop for * detailed remarks */ static int audio_sync(struct audio_thread_data *td, struct str_sync_data *sd) { int retval = STREAM_MATCH; uint32_t sdtime = TS_TO_TICKS(clip_time(&audio_str, sd->time)); uint32_t time; uint32_t duration = 0; struct stream *str; struct stream tmp_str; struct mad_header header; struct mad_stream stream; if (td->ev.id == STREAM_SYNC) { /* Actually syncing for playback - use real stream */ time = 0; str = &audio_str; } else { /* Probing - use temp stream */ time = INVALID_TIMESTAMP; str = &tmp_str; str->id = audio_str.id; } str->hdr.pos = sd->sk.pos; str->hdr.limit = sd->sk.pos + sd->sk.len; mad_stream_init(&stream); mad_header_init(&header); while (1) { if (audio_buffer(str, STREAM_PM_RANDOM_ACCESS) == STREAM_DATA_END) { DEBUGF("audio_sync:STR_DATA_END\n aqu:%ld swl:%ld swr:%ld\n", (long)audio_queue.used, str->hdr.win_left, str->hdr.win_right); if (audio_queue.used <= MAD_BUFFER_GUARD) goto sync_data_end; } stream.error = 0; mad_stream_buffer(&stream, audio_queue.ptr, audio_queue.used); if (stream.sync && mad_stream_sync(&stream) < 0) { DEBUGF(" audio: mad_stream_sync failed\n"); audio_queue_advance_pos(MAX(audio_queue.curr->size - 1, 1)); continue; } stream.sync = 0; if (mad_header_decode(&header, &stream) < 0) { DEBUGF(" audio: mad_header_decode failed:%s\n", mad_stream_errorstr(&stream)); audio_queue_advance_pos(1); continue; } duration = 32*MAD_NSBSAMPLES(&header); time = audio_queue.curr->time; DEBUGF(" audio: ft:%u t:%u fe:%u nsamp:%u sampr:%u\n", (unsigned)TICKS_TO_TS(time), (unsigned)sd->time, (unsigned)TICKS_TO_TS(time + duration), (unsigned)duration, header.samplerate); audio_queue_advance_pos(stream.this_frame - audio_queue.ptr); if (time <= sdtime && sdtime < time + duration) { DEBUGF(" audio: ft<=t sdtime) { DEBUGF(" audio: ft>t\n"); break; } audio_queue_advance_pos(stream.next_frame - audio_queue.ptr); audio_queue.curr->time += duration; rb->yield(); } sync_data_end: if (td->ev.id == STREAM_FIND_END_TIME) { if (time != INVALID_TIMESTAMP) { time = TICKS_TO_TS(time); duration = TICKS_TO_TS(duration); sd->time = time + duration; retval = STREAM_PERFECT_MATCH; } else { retval = STREAM_NOT_FOUND; } } DEBUGF(" audio header: 0x%02X%02X%02X%02X\n", (unsigned)audio_queue.ptr[0], (unsigned)audio_queue.ptr[1], (unsigned)audio_queue.ptr[2], (unsigned)audio_queue.ptr[3]); return retval; (void)td; } static void audio_thread_msg(struct audio_thread_data *td) { while (1) { intptr_t reply = 0; switch (td->ev.id) { case STREAM_PLAY: td->status = STREAM_PLAYING; switch (td->state) { case TSTATE_INIT: td->state = TSTATE_DECODE; case TSTATE_DECODE: case TSTATE_RENDER_WAIT: case TSTATE_RENDER_WAIT_END: break; case TSTATE_EOS: /* At end of stream - no playback possible so fire the * completion event */ stream_generate_event(&audio_str, STREAM_EV_COMPLETE, 0); break; } break; case STREAM_PAUSE: td->status = STREAM_PAUSED; reply = td->state != TSTATE_EOS; break; case STREAM_STOP: if (td->state == TSTATE_DATA) stream_clear_notify(&audio_str, DISK_BUF_DATA_NOTIFY); td->status = STREAM_STOPPED; td->state = TSTATE_EOS; reply = true; break; case STREAM_RESET: if (td->state == TSTATE_DATA) stream_clear_notify(&audio_str, DISK_BUF_DATA_NOTIFY); td->status = STREAM_STOPPED; td->state = TSTATE_INIT; td->samplerate = 0; td->nchannels = 0; init_mad(); td->mad_errors = 0; audio_queue_reset(); reply = true; break; case STREAM_NEEDS_SYNC: reply = true; /* Audio always needs to */ break; case STREAM_SYNC: case STREAM_FIND_END_TIME: if (td->state != TSTATE_INIT) break; reply = audio_sync(td, (struct str_sync_data *)td->ev.data); break; case DISK_BUF_DATA_NOTIFY: /* Our bun is done */ if (td->state != TSTATE_DATA) break; td->state = TSTATE_DECODE; str_data_notify_received(&audio_str); break; case STREAM_QUIT: /* Time to go - make thread exit */ td->state = TSTATE_EOS; return; } str_reply_msg(&audio_str, reply); if (td->status == STREAM_PLAYING) { switch (td->state) { case TSTATE_DECODE: case TSTATE_RENDER_WAIT: case TSTATE_RENDER_WAIT_END: /* These return when in playing state */ return; } } str_get_msg(&audio_str, &td->ev); } } static void audio_thread(void) { struct audio_thread_data td; #ifdef HAVE_PRIORITY_SCHEDULING /* Up the priority since the core DSP over-yields internally */ int old_priority = rb->thread_set_priority(THREAD_ID_CURRENT, PRIORITY_PLAYBACK-4); #endif rb->memset(&td, 0, sizeof (td)); td.status = STREAM_STOPPED; td.state = TSTATE_EOS; /* We need this here to init the EMAC for Coldfire targets */ init_mad(); td.dsp = (struct dsp_config *)rb->dsp_configure(NULL, DSP_MYDSP, CODEC_IDX_AUDIO); #ifdef HAVE_PITCHSCREEN rb->sound_set_pitch(PITCH_SPEED_100); #endif rb->dsp_configure(td.dsp, DSP_RESET, 0); rb->dsp_configure(td.dsp, DSP_SET_SAMPLE_DEPTH, MAD_F_FRACBITS); goto message_wait; /* This is the decoding loop. */ while (1) { td.state = TSTATE_DECODE; /* Check for any pending messages and process them */ if (str_have_msg(&audio_str)) { message_wait: /* Wait for a message to be queued */ str_get_msg(&audio_str, &td.ev); message_process: /* Process a message already dequeued */ audio_thread_msg(&td); switch (td.state) { /* These states are the only ones that should return */ case TSTATE_DECODE: goto audio_decode; case TSTATE_RENDER_WAIT: goto render_wait; case TSTATE_RENDER_WAIT_END: goto render_wait_end; /* Anything else is interpreted as an exit */ default: { #ifdef HAVE_PRIORITY_SCHEDULING rb->thread_set_priority(THREAD_ID_CURRENT, old_priority); #endif return; } } } audio_decode: /** Buffering **/ switch (audio_buffer(&audio_str, STREAM_PM_STREAMING)) { case STREAM_DATA_NOT_READY: { td.state = TSTATE_DATA; goto message_wait; } /* STREAM_DATA_NOT_READY: */ case STREAM_DATA_END: { if (audio_queue.used > MAD_BUFFER_GUARD) break; /* Used up remainder of compressed audio buffer. * Force any residue to play if audio ended before * reaching the threshold */ td.state = TSTATE_RENDER_WAIT_END; audio_queue_reset(); render_wait_end: pcm_output_drain(); while (pcm_output_used() > (ssize_t)PCMOUT_LOW_WM) { str_get_msg_w_tmo(&audio_str, &td.ev, 1); if (td.ev.id != SYS_TIMEOUT) goto message_process; } td.state = TSTATE_EOS; if (td.status == STREAM_PLAYING) stream_generate_event(&audio_str, STREAM_EV_COMPLETE, 0); rb->yield(); goto message_wait; } /* STREAM_DATA_END: */ } /** Decoding **/ mad_stream_buffer(&stream, audio_queue.ptr, audio_queue.used); int mad_stat = mad_frame_decode(&frame, &stream); ssize_t len = stream.next_frame - audio_queue.ptr; if (mad_stat != 0) { DEBUGF("audio: Stream error: %s\n", mad_stream_errorstr(&stream)); /* If something's goofed - try to perform resync by moving * at least one byte at a time */ audio_queue_advance_pos(MAX(len, 1)); if (stream.error == MAD_ERROR_BUFLEN) { /* This makes the codec support partially corrupted files */ if (++td.mad_errors <= MPA_MAX_FRAME_SIZE) { stream.error = 0; rb->yield(); continue; } DEBUGF("audio: Too many errors\n"); } else if (MAD_RECOVERABLE(stream.error)) { /* libmad says it can recover - just keep on decoding */ rb->yield(); continue; } else { /* Some other unrecoverable error */ DEBUGF("audio: Unrecoverable error\n"); } /* This is too hard - bail out */ td.state = TSTATE_EOS; if (td.status == STREAM_PLAYING) stream_generate_event(&audio_str, STREAM_EV_COMPLETE, 0); td.status = STREAM_ERROR; goto message_wait; } /* Adjust sizes by the frame size */ audio_queue_advance_pos(len); td.mad_errors = 0; /* Clear errors */ /* Generate the pcm samples */ mad_synth_frame(&synth, &frame); /** Output **/ if (frame.header.samplerate != td.samplerate) { td.samplerate = frame.header.samplerate; rb->dsp_configure(td.dsp, DSP_SWITCH_FREQUENCY, td.samplerate); } if (MAD_NCHANNELS(&frame.header) != td.nchannels) { td.nchannels = MAD_NCHANNELS(&frame.header); rb->dsp_configure(td.dsp, DSP_SET_STEREO_MODE, td.nchannels == 1 ? STEREO_MONO : STEREO_NONINTERLEAVED); } td.state = TSTATE_RENDER_WAIT; /* Add a frame of audio to the pcm buffer. Maximum is 1152 samples. */ render_wait: if (synth.pcm.length > 0) { struct pcm_frame_header *dst_hdr = pcm_output_get_buffer(); const char *src[2] = { (char *)synth.pcm.samples[0], (char *)synth.pcm.samples[1] }; int out_count = (synth.pcm.length * CLOCK_RATE + (td.samplerate - 1)) / td.samplerate; ssize_t size = sizeof(*dst_hdr) + out_count*4; /* Wait for required amount of free buffer space */ while (pcm_output_free() < size) { /* Wait one frame */ int timeout = out_count*HZ / td.samplerate; str_get_msg_w_tmo(&audio_str, &td.ev, MAX(timeout, 1)); if (td.ev.id != SYS_TIMEOUT) goto message_process; } out_count = rb->dsp_process(td.dsp, dst_hdr->data, src, synth.pcm.length); if (out_count <= 0) break; dst_hdr->size = sizeof(*dst_hdr) + out_count*4; dst_hdr->time = audio_queue.curr->time; /* As long as we're on this timestamp, the time is just incremented by the number of samples */ audio_queue.curr->time += out_count; /* Make this data available to DMA */ pcm_output_add_data(); } rb->yield(); } /* end decoding loop */ } /* Initializes the audio thread resources and starts the thread */ bool audio_thread_init(void) { /* Initialise the encoded audio buffer and its descriptors */ audio_queue.start = mpeg_malloc(AUDIOBUF_ALLOC_SIZE, MPEG_ALLOC_AUDIOBUF); if (audio_queue.start == NULL) return false; /* Start the audio thread */ audio_str.hdr.q = &audio_str_queue; rb->queue_init(audio_str.hdr.q, false); /* We steal the codec thread for audio */ rb->codec_thread_do_callback(audio_thread, &audio_str.thread); rb->queue_enable_queue_send(audio_str.hdr.q, &audio_str_queue_send, audio_str.thread); /* Wait for thread to initialize */ str_send_msg(&audio_str, STREAM_NULL, 0); return true; } /* Stops the audio thread */ void audio_thread_exit(void) { if (audio_str.thread != 0) { str_post_msg(&audio_str, STREAM_QUIT, 0); rb->codec_thread_do_callback(NULL, NULL); audio_str.thread = 0; } } 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 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
/*
 * header.c
 * Copyright (C) 2000-2003 Michel Lespinasse <walken@zoy.org>
 * Copyright (C) 2003      Regis Duchesne <hpreg@zoy.org>
 * Copyright (C) 1999-2000 Aaron Holtzman <aholtzma@ess.engr.uvic.ca>
 *
 * This file is part of mpeg2dec, a free MPEG-2 video stream decoder.
 * See http://libmpeg2.sourceforge.net/ for updates.
 *
 * mpeg2dec 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.
 *
 * mpeg2dec 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
 *
 * $Id$
 * libmpeg2 sync history:
 * 2008-07-01 - CVS revision 1.101
 */

#include "plugin.h"

#include "mpeg2dec_config.h"

#include "mpeg2.h"
#include "attributes.h"
#include "mpeg2_internal.h"

#define SEQ_EXT 2
#define SEQ_DISPLAY_EXT 4
#define QUANT_MATRIX_EXT 8
#define COPYRIGHT_EXT 0x10
#define PIC_DISPLAY_EXT 0x80
#define PIC_CODING_EXT 0x100

/* default intra quant matrix, in zig-zag order */
static const uint8_t default_intra_quantizer_matrix[64] =
{
    8,
    16, 16,
    19, 16, 19,
    22, 22, 22, 22,
    22, 22, 26, 24, 26,
    27, 27, 27, 26, 26, 26,
    26, 27, 27, 27, 29, 29, 29,
    34, 34, 34, 29, 29, 29, 27, 27,
    29, 29, 32, 32, 34, 34, 37,
    38, 37, 35, 35, 34, 35,
    38, 38, 40, 40, 40,
    48, 48, 46, 46,
    56, 56, 58,
    69, 69,
    83
};

const uint8_t default_mpeg2_scan_norm[64] =
{
    /* Zig-Zag scan pattern */
     0,  1,  8, 16,  9,  2,  3, 10,
    17, 24, 32, 25, 18, 11,  4,  5,
    12, 19, 26, 33, 40, 48, 41, 34,
    27, 20, 13,  6,  7, 14, 21, 28,
    35, 42, 49, 56, 57, 50, 43, 36,
    29, 22, 15, 23, 30, 37, 44, 51,
    58, 59, 52, 45, 38, 31, 39, 46,
    53, 60, 61, 54, 47, 55, 62, 63
};

const uint8_t default_mpeg2_scan_alt[64] =
{
    /* Alternate scan pattern */
     0, 8,  16, 24,  1,  9,  2, 10,
    17, 25, 32, 40, 48, 56, 57, 49,
    41, 33, 26, 18,  3, 11,  4, 12,
    19, 27, 34, 42, 50, 58, 35, 43,
    51, 59, 20, 28,  5, 13,  6, 14,
    21, 29, 36, 44, 52, 60, 37, 45,
    53, 61, 22, 30,  7, 15, 23, 31,
    38, 46, 54, 62, 39, 47, 55, 63
};

uint8_t mpeg2_scan_norm[64] IDATA_ATTR;
uint8_t mpeg2_scan_alt[64] IDATA_ATTR;

void mpeg2_header_state_init (mpeg2dec_t * mpeg2dec)
{
    if (mpeg2dec->sequence.width != (unsigned)-1)
    {
        mpeg2dec->sequence.width = (unsigned)-1;
        mpeg2_mem_reset(); /* Clean the memory slate */
#if 0
        if (!mpeg2dec->custom_fbuf)
        {
            int i;
            for (i = mpeg2dec->alloc_index_user;
                 i < mpeg2dec->alloc_index; i++)
            {
                mpeg2_free(mpeg2dec->fbuf_alloc[i].fbuf.buf[0]);
#if MPEG2_COLOR
                mpeg2_free(mpeg2dec->fbuf_alloc[i].fbuf.buf[1]);
                mpeg2_free(mpeg2dec->fbuf_alloc[i].fbuf.buf[2]);
#endif
            }
        }

        if (mpeg2dec->convert_start)
        {
            int i;
            for (i = 0; i < 3; i++)
            {
                mpeg2_free(mpeg2dec->yuv_buf[i][0]);
#if MPEG2_COLOR
                mpeg2_free(mpeg2dec->yuv_buf[i][1]);
                mpeg2_free(mpeg2dec->yuv_buf[i][2]);
#endif
            }
        }

        if (mpeg2dec->decoder.convert_id)
        {
            mpeg2_free(mpeg2dec->decoder.convert_id);
        }
#endif
    }

    mpeg2dec->decoder.coding_type = I_TYPE;
    mpeg2dec->decoder.convert = NULL;
    mpeg2dec->decoder.convert_id = NULL;

    mpeg2dec->picture = mpeg2dec->pictures;

    mpeg2dec->fbuf[0] = &mpeg2dec->fbuf_alloc[0].fbuf;
    mpeg2dec->fbuf[1] = &mpeg2dec->fbuf_alloc[1].fbuf;
    mpeg2dec->fbuf[2] = &mpeg2dec->fbuf_alloc[2].fbuf;

    mpeg2dec->first = 1;
    mpeg2dec->alloc_index = 0;
    mpeg2dec->alloc_index_user = 0;
    mpeg2dec->first_decode_slice = 1;
    mpeg2dec->nb_decode_slices = 0xb0 - 1;
    mpeg2dec->convert = NULL;
    mpeg2dec->convert_start = NULL;
    mpeg2dec->custom_fbuf = 0;
    mpeg2dec->yuv_index = 0;
}

void mpeg2_reset_info (mpeg2_info_t * info)
{
    info->current_picture =
    info->current_picture_2nd = NULL;

    info->display_picture =
    info->display_picture_2nd = NULL;

    info->current_fbuf =
    info->display_fbuf =
    info->discard_fbuf = NULL;
}

static void info_user_data (mpeg2dec_t * mpeg2dec)
{
    if (mpeg2dec->user_data_len)
    {
        mpeg2dec->info.user_data = mpeg2dec->chunk_buffer;
        mpeg2dec->info.user_data_len = mpeg2dec->user_data_len - 3;
    }
}

int mpeg2_header_sequence (mpeg2dec_t * mpeg2dec)
{
    static const unsigned int frame_period[16] =
    {
        0, 1126125, 1125000, 1080000, 900900, 900000, 540000, 450450, 450000,
        /* unofficial: xing 15 fps */
        1800000,
        /* unofficial: libmpeg3 "Unofficial economy rates" 5/10/12/15 fps */
        5400000, 2700000, 2250000, 1800000, 0, 0
    };

    uint8_t * buffer = mpeg2dec->chunk_start;
    mpeg2_sequence_t * sequence = &mpeg2dec->new_sequence;
    int i;

    if ((buffer[6] & 0x20) != 0x20)        /* missing marker_bit */
        return 1;

    i = (buffer[0] << 16) | (buffer[1] << 8) | buffer[2];

    if (!(sequence->display_width = sequence->picture_width = i >> 12))
        return 1;

    if (!(sequence->display_height = sequence->picture_height = i & 0xfff))
        return 1;

    sequence->width = (sequence->picture_width + 15) & ~15;
    sequence->height = (sequence->picture_height + 15) & ~15;
    sequence->chroma_width = sequence->width >> 1;
    sequence->chroma_height = sequence->height >> 1;

    sequence->flags = SEQ_FLAG_PROGRESSIVE_SEQUENCE |
                      SEQ_VIDEO_FORMAT_UNSPECIFIED;

    sequence->pixel_width = buffer[3] >> 4;        /* aspect ratio */
    sequence->frame_period = frame_period[buffer[3] & 15];

    sequence->byte_rate = (buffer[4]<<10) | (buffer[5]<<2) | (buffer[6]>>6);

    sequence->vbv_buffer_size = ((buffer[6]<<16) | (buffer[7]<<8)) & 0x1ff800;

    if (buffer[7] & 4)
        sequence->flags |= SEQ_FLAG_CONSTRAINED_PARAMETERS;

    mpeg2dec->copy_matrix = 3;

    if (buffer[7] & 2)
    {
        for (i = 0; i < 64; i++)
        {
            mpeg2dec->new_quantizer_matrix[0][mpeg2_scan_norm[i]] =
                (buffer[i+7] << 7) | (buffer[i+8] >> 1);
        }

        buffer += 64;
    }
    else
    {
        for (i = 0; i < 64; i++)
        {
            mpeg2dec->new_quantizer_matrix[0][mpeg2_scan_norm[i]] =
                default_intra_quantizer_matrix[i];
        }
    }

    if (buffer[7] & 1)
    {
        for (i = 0; i < 64; i++)
        {
            mpeg2dec->new_quantizer_matrix[1][mpeg2_scan_norm[i]] =
                buffer[i+8];
        }
    }
    else
    {
        rb->memset (mpeg2dec->new_quantizer_matrix[1], 16, 64);
    }

    sequence->profile_level_id = 0x80;
    sequence->colour_primaries = 0;
    sequence->transfer_characteristics = 0;
    sequence->matrix_coefficients = 0;

    mpeg2dec->ext_state = SEQ_EXT;
    mpeg2dec->state = STATE_SEQUENCE;

    mpeg2dec->display_offset_x =
    mpeg2dec->display_offset_y = 0;

    return 0;
}

static int sequence_ext (mpeg2dec_t * mpeg2dec)
{
    uint8_t * buffer = mpeg2dec->chunk_start;
    mpeg2_sequence_t * sequence = &mpeg2dec->new_sequence;
    uint32_t flags;

    if (!(buffer[3] & 1))
        return 1;

    sequence->profile_level_id = (buffer[0] << 4) | (buffer[1] >> 4);

    sequence->picture_width += ((buffer[1] << 13) | (buffer[2] << 5)) & 0x3000;
    sequence->display_width = sequence->picture_width;

    sequence->picture_height += (buffer[2] << 7) & 0x3000;
    sequence->display_height = sequence->picture_height;

    sequence->width = (sequence->picture_width + 15) & ~15;
    sequence->height = (sequence->picture_height + 15) & ~15;

    flags = sequence->flags | SEQ_FLAG_MPEG2;

    if (!(buffer[1] & 8))
    {
        flags &= ~SEQ_FLAG_PROGRESSIVE_SEQUENCE;
        sequence->height = (sequence->height + 31) & ~31;
    }

    if (buffer[5] & 0x80)
        flags |= SEQ_FLAG_LOW_DELAY;

    sequence->flags = flags;
    sequence->chroma_width = sequence->width;
    sequence->chroma_height = sequence->height;

    switch (buffer[1] & 6)
    {
    case 0:        /* invalid */
        return 1;
    case 2:        /* 4:2:0 */
        sequence->chroma_height >>= 1;
    case 4:        /* 4:2:2 */
        sequence->chroma_width >>= 1;
    }

    sequence->byte_rate += ((buffer[2]<<25) | (buffer[3]<<17)) & 0x3ffc0000;

    sequence->vbv_buffer_size |= buffer[4] << 21;

    sequence->frame_period =
        sequence->frame_period * ((buffer[5]&31)+1) / (((buffer[5]>>2)&3)+1);

    mpeg2dec->ext_state = SEQ_DISPLAY_EXT;

    return 0;
}

static int sequence_display_ext (mpeg2dec_t * mpeg2dec)
{
    uint8_t * buffer = mpeg2dec->chunk_start;
    mpeg2_sequence_t * sequence = &mpeg2dec->new_sequence;
    int x;

    sequence->flags = (sequence->flags & ~SEQ_MASK_VIDEO_FORMAT) |
             ((buffer[0] << 4) & SEQ_MASK_VIDEO_FORMAT);

    if (buffer[0] & 1)
    {
        sequence->flags |= SEQ_FLAG_COLOUR_DESCRIPTION;
        sequence->colour_primaries = buffer[1];
        sequence->transfer_characteristics = buffer[2];
        sequence->matrix_coefficients = buffer[3];
        buffer += 3;
    }

    if (!(buffer[2] & 2))        /* missing marker_bit */
        return 1;

    x = (buffer[1] << 6) | (buffer[2] >> 2);
    if (x)
        sequence->display_width = x;

    x = ((buffer[2] & 1) << 13) | (buffer[3] << 5) | (buffer[4] >> 3);
    if (x)
        sequence->display_height = x;

    return 0;
}

static inline void simplify (unsigned int * u, unsigned int * v) 
{ 
    unsigned int a, b, tmp; 
 
    a = *u;
    b = *v; 

    /* find greatest common divisor */ 
    while (a)
    {
        tmp = a;
        a = b % tmp;
        b = tmp; 
    } 

    *u /= b;
    *v /= b; 
} 

static inline void finalize_sequence (mpeg2_sequence_t * sequence)
{
    int width;
    int height;

    sequence->byte_rate *= 50;

    if (sequence->flags & SEQ_FLAG_MPEG2)
    {
        switch (sequence->pixel_width)
        {
        case 1:                /* square pixels */
            sequence->pixel_width =
            sequence->pixel_height = 1;
            return;
        case 2:                /* 4:3 aspect ratio */
            width = 4;
            height = 3;
            break;
        case 3:                /* 16:9 aspect ratio */
            width = 16;
            height = 9;
            break;
        case 4:                /* 2.21:1 aspect ratio */
            width = 221;
            height = 100;
            break;
        default:        /* illegal */
            sequence->pixel_width =
            sequence->pixel_height = 0;
            return;
        }

        width *= sequence->display_height;
        height *= sequence->display_width;
    }
    else
    {
        if (sequence->byte_rate == 50 * 0x3ffff)
            sequence->byte_rate = 0;        /* mpeg-1 VBR */

        switch (sequence->pixel_width)
        {
        case 0:
        case 15:        /* illegal */
            sequence->pixel_width =
            sequence->pixel_height = 0;
            return;
        case 1:        /* square pixels */
            sequence->pixel_width =
            sequence->pixel_height = 1;
            return;
        case 3:        /* 720x576 16:9 */
            sequence->pixel_width = 64;
            sequence->pixel_height = 45;
            return;
        case 6:        /* 720x480 16:9 */
            sequence->pixel_width = 32;
            sequence->pixel_height = 27;
            return;
        case 8:        /* BT.601 625 lines 4:3 */
            sequence->pixel_width = 59;
            sequence->pixel_height = 54;
            return;
        case 12:       /* BT.601 525 lines 4:3 */
            sequence->pixel_width = 10;
            sequence->pixel_height = 11;
            return;
        default:
            height = 88 * sequence->pixel_width + 1171;
            width = 2000;
        }
    }

    sequence->pixel_width = width;
    sequence->pixel_height = height;

    simplify(&sequence->pixel_width, &sequence->pixel_height);
}

int mpeg2_guess_aspect (const mpeg2_sequence_t * sequence, 
                        unsigned int * pixel_width, 
                        unsigned int * pixel_height) 
{ 
    static const struct
    { 
        unsigned int width, height; 
    } video_modes[] =
    {
        {720, 576}, /* 625 lines, 13.5 MHz (D1, DV, DVB, DVD) */ 
        {704, 576}, /* 625 lines, 13.5 MHz (1/1 D1, DVB, DVD, 4CIF) */ 
        {544, 576}, /* 625 lines, 10.125 MHz (DVB, laserdisc) */ 
        {528, 576}, /* 625 lines, 10.125 MHz (3/4 D1, DVB, laserdisc) */ 
        {480, 576}, /* 625 lines, 9 MHz (2/3 D1, DVB, SVCD) */ 
        {352, 576}, /* 625 lines, 6.75 MHz (D2, 1/2 D1, CVD, DVB, DVD) */ 
        {352, 288}, /* 625 lines, 6.75 MHz, 1 field (D4, VCD, DVB, DVD, CIF) */ 
        {176, 144}, /* 625 lines, 3.375 MHz, half field (QCIF) */ 
        {720, 486}, /* 525 lines, 13.5 MHz (D1) */ 
        {704, 486}, /* 525 lines, 13.5 MHz */ 
        {720, 480}, /* 525 lines, 13.5 MHz (DV, DSS, DVD) */ 
        {704, 480}, /* 525 lines, 13.5 MHz (1/1 D1, ATSC, DVD) */ 
        {544, 480}, /* 525 lines. 10.125 MHz (DSS, laserdisc) */ 
        {528, 480}, /* 525 lines. 10.125 MHz (3/4 D1, laserdisc) */ 
        {480, 480}, /* 525 lines, 9 MHz (2/3 D1, SVCD) */ 
        {352, 480}, /* 525 lines, 6.75 MHz (D2, 1/2 D1, CVD, DVD) */ 
        {352, 240}  /* 525 lines. 6.75 MHz, 1 field (D4, VCD, DSS, DVD) */ 
    }; 
    unsigned int width, height, pix_width, pix_height, i, DAR_16_9; 
 
    *pixel_width = sequence->pixel_width; 
    *pixel_height = sequence->pixel_height; 
    width = sequence->picture_width; 
    height = sequence->picture_height; 

    for (i = 0; i < sizeof (video_modes) / sizeof (video_modes[0]); i++) 
    {
        if (width == video_modes[i].width && height == video_modes[i].height) 
            break; 
    }

    if (i == ARRAYLEN(video_modes) || 
        (sequence->pixel_width == 1 && sequence->pixel_height == 1) ||
        width != sequence->display_width || height != sequence->display_height)
    {
        return 0; 
    }
 
    for (pix_height = 1; height * pix_height < 480; pix_height <<= 1);
    height *= pix_height; 

    for (pix_width = 1; width * pix_width <= 352; pix_width <<= 1); 
    width *= pix_width; 
 
    if (!(sequence->flags & SEQ_FLAG_MPEG2))
    {
        static unsigned int mpeg1_check[2][2] = {{11, 54}, {27, 45}}; 
        DAR_16_9 = (sequence->pixel_height == 27 || 
                    sequence->pixel_height == 45); 
        if (width < 704 || 
            sequence->pixel_height != mpeg1_check[DAR_16_9][height == 576]) 
            return 0; 
    }
    else
    { 
        DAR_16_9 = (3 * sequence->picture_width * sequence->pixel_width > 
                    4 * sequence->picture_height * sequence->pixel_height); 
        switch (width)
        { 
        case 528:
        case 544:
            pix_width *= 4;
            pix_height *= 3;
            break;
        case 480:
            pix_width *= 3;
            pix_height *= 2;
            break;
        } 
    }

    if (DAR_16_9)
    { 
        pix_width *= 4;
        pix_height *= 3; 
    } 

    if (height == 576)
    { 
        pix_width *= 59;
        pix_height *= 54; 
    }
    else
    { 
        pix_width *= 10;
        pix_height *= 11; 
    }

    *pixel_width = pix_width; 
    *pixel_height = pix_height;

    simplify (pixel_width, pixel_height); 

    return (height == 576) ? 1 : 2; 
} 

static void copy_matrix (mpeg2dec_t * mpeg2dec, int index)
{
    if (rb->memcmp (mpeg2dec->quantizer_matrix[index],
                mpeg2dec->new_quantizer_matrix[index], 64))
    {
        rb->memcpy (mpeg2dec->quantizer_matrix[index],