/* zenutils - Utilities for working with creative firmwares. * Copyright 2007 (c) Rasmus Ry * * 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 */ #include #include #include #include #include #include #include namespace { enum command_t { cmd_none = 0, cmd_sign, cmd_verify, cmd_encrypt, cmd_decrypt }; enum mode_t { mode_none = 0, mode_cenc, mode_fresc, mode_tl }; struct player_info_t { const char* name; const char* null_key; /* HMAC-SHA1 key */ const char* fresc_key; /* BlowFish key */ const char* tl_key; /* BlowFish key */ bool big_endian; }; }; /* namespace */ static const char VERSION[] = "0.2"; static const char null_key_v1[] = "CTL:N0MAD|PDE0.SIGN."; static const char null_key_v2[] = "CTL:N0MAD|PDE0.DPMP."; static const char null_key_v3[] = "CTL:N0MAD|PDE0.DPFP."; static const char null_key_v4[] = "CTL:Z3N07|PDE0.DPMP."; static const char fresc_key_v1[] = "Copyright (C) CTL. -" " zN0MAD iz v~p0wderful!"; static const char fresc_key_v2[] = ""; /* Unknown atm */ static const char tl_zvm_key[] = "1sN0TM3D az u~may th1nk*" "Creative Zen Vision:M"; static const char tl_zvm60_key[] = "1sN0TM3D az u~may th1nk*" "Creative Zen Vision:M (D" "VP-HD0004)"; static const char tl_zen_key[] = "1sN0TM3D az u~may th1nk*" "Creative ZEN"; static const char tl_zenxf_key[] = "1sN0TM3D az u~may th1nk*" "Creative ZEN X-Fi"; static const char tl_zenmo_key[] = "1sN0TM3D az u~may th1nk*" "Creative ZEN Mozaic"; static const char tl_zv_key[] = "1sN0TM3D az u~may th1nk*" "Creative Zen Vision"; static const char tl_zvw_key[] = "1sN0TM3D az u~may th1nk*" "Creative ZEN Vision W"; static const char tl_zm_key[] = "1sN0TM3D az u~may th1nk*" "Creative Zen Micro"; static const char tl_zmp_key[] = "1sN0TM3D az u~may th1nk*" "Creative Zen MicroPhoto"; static const char tl_zs_key[] = "1sN0TM3D az u~may th1nk*" "Creative Zen Sleek"; static const char tl_zsp_key[] = "1sN0TM3D az u~may th1nk*" "Creative Zen Sleek Photo"; static const char tl_zt_key[] = "1sN0TM3D az u~may th1nk*" "Creative Zen Touch"; static const char tl_zx_key[] = "1sN0TM3D az u~may th1nk*" "NOMAD Jukebox Zen Xtra"; static const char tl_zenv_key[] = "1sN0TM3D az u~may th1nk*" "Creative ZEN V"; static const char tl_zenvp_key[] = "1sN0TM3D az u~may th1nk*" "Creative ZEN V Plus"; static const char tl_zenvv_key[] = "1sN0TM3D az u~may th1nk*" "Creative ZEN V (Video)"; player_info_t players[] = { {"Zen Vision:M", null_key_v2, fresc_key_v1, tl_zvm_key, false}, {"Zen Vision:M 60GB", null_key_v2, fresc_key_v1, tl_zvm60_key, false}, {"ZEN", null_key_v4, fresc_key_v2, tl_zen_key, false}, {"ZEN X-Fi", null_key_v4, fresc_key_v2, tl_zenxf_key, false}, {"ZEN Mozaic", null_key_v4, fresc_key_v2, tl_zenmo_key, false}, {"Zen Vision", null_key_v2, fresc_key_v1, tl_zv_key, false}, {"Zen Vision W", null_key_v2, fresc_key_v1, tl_zvw_key, false}, {"Zen Micro", null_key_v1, fresc_key_v1, tl_zm_key, true}, {"Zen MicroPhoto", null_key_v1, fresc_key_v1, tl_zmp_key, true}, {"Zen Sleek", null_key_v1, fresc_key_v1, tl_zs_key, true}, {"Zen SleekPhoto", null_key_v1, fresc_key_v1, tl_zsp_key, true}, {"Zen Touch", null_key_v1, fresc_key_v1, tl_zt_key, true}, {"Zen Xtra", null_key_v1, fresc_key_v1, tl_zx_key, true}, {"Zen V", null_key_v3, fresc_key_v1, tl_zenv_key, false}, {"Zen V Plus", null_key_v3, fresc_key_v1, tl_zenvp_key, false}, {"Zen V Video", null_key_v3, fresc_key_v1, tl_zenvv_key, false}, {NULL, NULL, NULL, NULL, false} }; player_info_t* find_player_info(std::string player) { for (int i = 0; players[i].name != NULL; i++) { if (!strcasecmp(players[i].name, player.c_str())) { return &players[i]; } } return NULL; } void print_version() { std::cout << "zen_crypt - A utility for encrypting, decrypting or signing" " Creative firmwares." << std::endl << "Version " << VERSION << std::endl << "Copyright (c) 2007 Rasmus Ry" << std::endl; } void print_help() { print_version(); std::cout << std::endl << "Usage: zen_crypt [command] [options]" << std::endl << std::endl << " Commands:" << std::endl << " -h,--help" << std::endl << " prints this message." << std::endl << " -s,--sign" << std::endl << " signs a given input file." << std::endl << " -v,--verify" << std::endl << " verifies a signed input file." << std::endl << " -e,--encrypt" << std::endl << " encrypts a given input file." << std::endl << " -d,--decrypt" << std::endl << " decrypts a given input file." << std::endl << std::endl << " Options:" << std::endl << " -V,--verbose" << std::endl << " prints verbose messages." << std::endl << " -b,--big-endian" << std::endl << " specifies that the input is big-endian, default is" " little-endian." << std::endl << " -i,--input [file]" << std::endl << " specifies the input file." << std::endl << " -o,--output [file]" << std::endl << " specifies the output file." << std::endl << " -m,--mode [CENC|FRESC|TL]" << std::endl << " specifies which algorithm to use." << std::endl << " -k,--key [player|key]" << std::endl << " specifies which key to use." << std::endl << std::endl ; std::cout << " Players:" << std::endl; for (int i = 0; players[i].name != NULL; i++) { std::cout << " " << players[i].name; if (!i) std::cout << " (default)"; std::cout << std::endl; } } size_t find_null_signature(shared::bytes& data) { size_t index = data.size(); if (index < (20 + 8 + 7)) return 0; index -= 20 + 8; for (int i = 0; i < 7; i++) { if (*(dword*)&data[index-i] == 'NULL' || *(dword*)&data[index-i] == 'LLUN') { return index-i; } } return 0; } bool sign(shared::bytes& data, player_info_t* pi, const std::string& file, bool verbose) { if (verbose) std::cout << "[*] Checking for the presence of an existing" " NULL signature..." << std::endl; size_t index = find_null_signature(data); if (index) { if (verbose) std::cout << "[*] Found NULL signature at: 0x" << std::hex << index << std::endl; if (verbose) std::cout << "[*] Computing digest..." << std::endl; shared::bytes digest(20); if (!zen::hmac_sha1_calc((const byte*)pi->null_key, strlen(pi->null_key)+1, &data[0], index, &digest[0], NULL)) { std::cerr << "Failed to compute digest." << std::endl; return false; } if (verbose) std::cout << "[*] Writing file data..." << std::endl; if (!shared::write_file(file, data, true)) { std::cerr << "Failed to write file data." << std::endl; return false; } if (verbose) std::cout << "[*] Writing digest data..." << std::endl; if (!shared::write_file(file, digest, false, index+8)) { std::cerr << "Failed to write digest data." << std::endl; return false; } } else { if (verbose) std::cout << "[*] Computing digest..." << std::endl; shared::bytes signature(20+8); if (!zen::hmac_sha1_calc((const byte*)pi->null_key, strlen(pi->null_key)+1, &data[0], data.size(), &signature[8], NULL)) { std::cerr << "Failed to compute digest." << std::endl; return false; } zen::firmware_header_t header = {'NULL', 20}; if (pi->big_endian) { header.tag = shared::swap(header.tag); header.size = shared::swap(header.size); } memcpy(&signature[0], &header, sizeof(zen::firmware_header_t)); if (verbose) std::cout << "[*] Writing file data..." << std::endl; if (!shared::write_file(file, data, true)) { std::cerr << "Failed to write file data." << std::endl; return false; } if (verbose) std::cout << "[*] Writing signature data..." << std::endl; if (!shared::write_file(file, signature, false, data.size())) { std::cerr << "Failed to write signature data." << std::endl; return false; } if (verbose) std::cout << "[*] Ensuring that the file length is" " 32-bit aligned..." << std::endl; int length = data.size() + signature.size(); int align = length % 4; if (align) { shared::bytes padding(4 - align, 0); if (!shared::write_file(file, padding, false, length)) { std::cerr << "Failed to write padding data." << std::endl; return false; } } } return true; } bool verify(shared::bytes& data, player_info_t* pi, bool verbose) { if (verbose) std::cout << "[*] Checking for the presence of an existing" " NULL signature..." << std::endl; size_t index = find_null_signature(data); if (!index) { std::cerr << "No NULL signature present in the input file." << std::endl; return false; } if (verbose) std::cout << "[*] Found NULL signature at: 0x" << std::hex << index << std::endl; if (verbose) std::cout << "[*] Computing digest..." << std::endl; byte digest[20]; if (!zen::hmac_sha1_calc((const byte*)pi->null_key, strlen(pi->null_key)+1, &data[0], index, digest, NULL)) { std::cerr << "Failed to compute digest." << std::endl; return false; } if (verbose) std::cout << "[*] Verifying NULL signature digest..." << std::endl; if (memcmp(&digest[0], &data[index+8], 20)) { std::cerr << "The NULL signature contains an incorrect digest." << std::endl; return false; } return true; } bool encrypt(shared::bytes& data, int mode, player_info_t* pi, const std::string& file, bool verbose) { if (mode == mode_cenc) { if (verbose) std::cout << "[*] Encoding input file..." << std::endl; shared::bytes outbuf(data.size() * 2); int len = zen::cenc_encode(&data[0], data.size(), &outbuf[0], outbuf.size()); if (!len) { std::cerr << "Failed to encode the input file." << std::endl; return false; } if (verbose) std::cout << "[*] Writing decoded length to file..." << std::endl; shared::bytes length(sizeof(dword)); *(dword*)&length[0] = pi->big_endian ? shared::swap(data.size()) : data.size(); if (!shared::write_file(file, length, true)) { std::cerr << "Failed to write the file data." << std::endl; return false; } if (verbose) std::cout << "[*] Writing file data..." << std::endl; if (!shared::write_file(file, outbuf, sizeof(dword), len)) { std::cerr << "Failed to write the file data." << std::endl; return false; } } else if (mode == mode_fresc) { if (verbose) std::cout << "[*] Encrypting input file..." << std::endl; dword iv[2] = {shared::swap(data.size()), 0}; if (!zen::bf_cbc_encrypt((const byte*)pi->fresc_key, strlen(pi->fresc_key)+1, &data[0], data.size(), (const byte*)iv)) { std::cerr << "Failed to encrypt the input file." << std::endl; return false; } if (verbose) std::cout << "[*] Writing file data..." << std::endl; if (!shared::write_file(file, data, true)) { std::cerr << "Failed to save the output file." << std::endl; return false; } } else if (mode == mode_tl) { if (verbose) std::cout << "[*] Encoding input file..." << std::endl; shared::bytes outbuf(data.size() * 2); *(dword*)&outbuf[0] = pi->big_endian ? shared::swap(data.size()) : data.size(); int len = zen::cenc_encode(&data[0], data.size(), &outbuf[sizeof(dword)], outbuf.size()-sizeof(dword)); if (!len) { std::cerr << "Failed to encode the input file." << std::endl; return false; } len += sizeof(dword); int align = len % 8; align = align ? (8 - align) : 0; len += align; if (verbose) std::cout << "[*] Encrypting encoded data..." << std::endl; dword iv[2] = {0, shared::swap(len)}; if (!zen::bf_cbc_encrypt((const byte*)pi->tl_key, strlen(pi->tl_key)+1, &outbuf[0], len, (const byte*)iv)) { std::cerr << "Failed to encrypt the input file." << std::endl; return false; } if (verbose) std::cout << "[*] Writing file data..." << std::endl; if (!shared::write_file(file, outbuf, true, 0, len)) { std::cerr << "Failed to save the output file." << std::endl; return false; } } else { std::cerr << "Invalid mode specified." << std::endl; return false; } return true; } bool decrypt(shared::bytes& data, int mode, player_info_t* pi, const std::string& file, bool verbose) { if (mode == mode_cenc) { dword length = *(dword*)&data[0]; length = pi->big_endian ? shared::swap(length) : length; if (verbose) std::cout << "[*] Decoding input file..." << std::endl; shared::bytes outbuf(length); if (!zen::cenc_decode(&data[sizeof(dword)], data.size()-sizeof(dword), &outbuf[0], length)) { std::cerr << "Failed to decode the input file." << std::endl; return false; } if (verbose) std::cout << "[*] Writing file data..." << std::endl; if (!shared::write_file(file, outbuf, true)) { std::cerr << "Failed to write the file data." << std::endl; return false; } } else if (mode == mode_fresc) { if (verbose) std::cout << "[*] Decrypting input file..." << std::endl; dword iv[2] = {shared::swap(data.size()), 0}; if (!zen::bf_cbc_decrypt((const byte*)pi->fresc_key, strlen(pi->fresc_key)+1, &data[0], data.size(), (const byte*)iv)) { std::cerr << "Failed to decrypt the input file." << std::endl; return false; } if (*(dword*)&data[0] != 'EDOC' && *(dword*)&data[0] != 'CODE') { std::cerr << "Failed to decode the input file." << std::endl; return false; } if (verbose) std::cout << "[*] Writing file data..." << std::endl; if (!shared::write_file(file, data, true)) { std::cerr << "Failed to save the output file." << std::endl; return false; } } else if (mode == mode_tl) { if (verbose) std::cout << "[*] Decrypting input file..." << std::endl; dword iv[2] = {0, shared::swap(data.size())}; if (!zen::bf_cbc_decrypt((const byte*)pi->tl_key, strlen(pi->tl_key)+1, &data[0], data.size(), (const byte*)iv)) { std::cerr << "Failed to decrypt the input file." << std::endl; return false; } dword length = *(dword*)&data[0]; length = pi->big_endian ? shared::swap(length) : length; if (length > (data.size() * 3)) { std::cerr << "Decrypted length is unexpectedly large: " << std::hex << length << " Check the endian and key settings." << std::endl; return false; } if (verbose) std::cout << "[*] Decoding decrypted data..." << std::endl; shared::bytes outbuf(length); if (!zen::cenc_decode(&data[sizeof(dword)], data.size()-sizeof(dword), &outbuf[0], length)) { std::cerr << "Failed to decode the input file." << std::endl; return false; } if (verbose) std::cout << "[*] Writing file data..." << std::endl; if (!shared::write_file(file, outbuf, true)) { std::cerr << "Failed to save the output file." << std::endl; return false; } } else { std::cerr << "Invalid mode specified." << std::endl; return false; } return true; } int process_arguments(int argc, char*argv[]) { /* -------------------------------------------------------------------- Parse input variables. -------------------------------------------------------------------- */ GetPot cl(argc, argv); if (cl.size() == 1 || cl.search(2, "-h", "--help")) { print_help(); return 1; } int command = cmd_none; if (cl.search(2, "-s", "--sign")) command = cmd_sign; else if (cl.search(2, "-v", "--verify")) command = cmd_verify; else if (cl.search(2, "-e", "--encrypt")) command = cmd_encrypt; else if (cl.search(2, "-d", "--decrypt")) command = cmd_decrypt; if (command == cmd_none) { std::cerr << "No command specified." << std::endl; return 2; } int mode = mode_none; if (command == cmd_encrypt || command == cmd_decrypt) { if (!cl.search(2, "-m", "--mode")) { std::cerr << "The specified command requires that" " a mode is specified." << std::endl; return 3; } std::string name = cl.next(""); if (!name.empty()) { if (!strcasecmp(name.c_str(), "CENC")) mode = mode_cenc; else if (!strcasecmp(name.c_str(), "FRESC")) mode = mode_fresc; else if (!strcasecmp(name.c_str(), "TL")) mode = mode_tl; } if (mode == mode_none) { std::cerr << "Invalid mode specified." << std::endl; return 4; } } bool verbose = false; if (cl.search(2, "-V", "--verbose")) verbose = true; bool big_endian = false; if (cl.search(2, "-b", "--big-endian")) big_endian = true; std::string infile; if (cl.search(2, "-i", "--input")) infile = cl.next(""); if (infile.empty()) { std::cerr << "An input file must be specified." << std::endl; return 5; } std::string outfile = infile; if (cl.search(2, "-o", "--output")) outfile = cl.next(outfile.c_str()); player_info_t* pi = &players[0]; std::string key; if (cl.search(2, "-k", "--key")) key = cl.next(""); if (!key.empty()) { player_info_t* pitmp = find_player_info(key); if (pitmp != NULL) pi = pitmp; else { static player_info_t player = { NULL, key.c_str(), key.c_str(), key.c_str(), false }; pi = &player; } } if (big_endian) pi->big_endian = big_endian; /* -------------------------------------------------------------------- Read the input file. -------------------------------------------------------------------- */ if (verbose) std::cout << "[*] Reading input file..." << std::endl; shared::bytes buffer; if (!shared::read_file(infile, buffer)) { std::cerr << "Failed to read the input file." << std::endl; return 6; } /* -------------------------------------------------------------------- Process the input file. -------------------------------------------------------------------- */ switch (command) { case cmd_sign: if (verbose) std::cout << "[*] Signing input file..." << std::endl; if (!sign(buffer, pi, outfile, verbose)) return 7; std::cout << "Successfully signed the input file." << std::endl; break; case cmd_verify: if (verbose) std::cout << "[*] Verifying signature on input file..." << std::endl; if (!verify(buffer, pi, verbose)) return 8; std::cout << "Successfully verified the input file signature." << std::endl; break; case cmd_encrypt: if (verbose) std::cout << "[*] Encrypting input file..." << std::endl; if (!encrypt(buffer, mode, pi, outfile, verbose)) return 9; std::cout << "Successfully encrypted the input file." << std::endl; break; case cmd_decrypt: if (verbose) std::cout << "[*] Decrypting input file..." << std::endl; if (!decrypt(buffer, mode, pi, outfile, verbose)) return 10; std::cout << "Successfully decrypted the input file." << std::endl; break; }; return 0; } int main(int argc, char* argv[]) { try { return process_arguments(argc, argv); } catch (const std::exception& xcpt) { std::cerr << "Exception caught: " << xcpt.what() << std::endl; return -1; } catch (...) { std::cerr << "Unknown exception caught." << std::endl; return -2; } return -3; } 12 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 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
/*
  Copyright (c) 2005, The Musepack Development Team
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

  * Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above
  copyright notice, this list of conditions and the following
  disclaimer in the documentation and/or other materials provided
  with the distribution.

  * Neither the name of the The Musepack Development Team nor the
  names of its contributors may be used to endorse or promote
  products derived from this software without specific prior
  written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/// \file mpc_decoder.c
/// Core decoding routines and logic.

#include "musepack.h"
#include "internal.h"
#include "requant.h"
#include "huffman.h"

//SV7 tables
extern const HuffmanTyp*   mpc_table_HuffQ [2] [8];
extern const HuffmanTyp    mpc_table_HuffHdr  [10];
extern const HuffmanTyp    mpc_table_HuffSCFI [ 4];
extern const HuffmanTyp    mpc_table_HuffDSCF [16];


#ifdef MPC_SUPPORT_SV456
//SV4/5/6 tables
extern const HuffmanTyp*   mpc_table_SampleHuff [18];
extern const HuffmanTyp    mpc_table_SCFI_Bundle   [ 8];
extern const HuffmanTyp    mpc_table_DSCF_Entropie [13];
extern const HuffmanTyp    mpc_table_Region_A [16];
extern const HuffmanTyp    mpc_table_Region_B [ 8];
extern const HuffmanTyp    mpc_table_Region_C [ 4];

#endif

#ifndef MPC_LITTLE_ENDIAN
#define SWAP(X) mpc_swap32(X)
#else
#define SWAP(X) X
#endif

#ifdef SCF_HACK
#define SCF_DIFF(SCF, D) (SCF == -128 ? -128 : SCF + D)
#else 
#define SCF_DIFF(SCF, D) SCF + D
#endif

#define LOOKUP(x, e, q)   mpc_decoder_make_huffman_lookup ( (q), sizeof(q), (x), (e) )
#define Decode_DSCF()   HUFFMAN_DECODE_FASTEST ( d, mpc_table_HuffDSCF, LUTDSCF, 6 )
#define HUFFMAN_DECODE_FASTEST(d,a,b,c)  mpc_decoder_huffman_decode_fastest ( (d), (a), (b), 32-(c) )
#define HUFFMAN_DECODE_FASTERER(d,a,b,c)  mpc_decoder_huffman_decode_fasterer ( (d), (a), (b), 32-(c) )

mpc_uint8_t     LUT1_0  [1<< 6] IBSS_ATTR_MPC_LARGE_IRAM;
mpc_uint8_t     LUT1_1  [1<< 9] IBSS_ATTR_MPC_LARGE_IRAM; //  576 Bytes
mpc_uint8_t     LUT2_0  [1<< 7] IBSS_ATTR_MPC_LARGE_IRAM;
mpc_uint8_t     LUT2_1  [1<<10] IBSS_ATTR_MPC_LARGE_IRAM; // 1152 Bytes
mpc_uint8_t     LUT3_0  [1<< 4] IBSS_ATTR_MPC_LARGE_IRAM;
mpc_uint8_t     LUT3_1  [1<< 5] IBSS_ATTR_MPC_LARGE_IRAM; //   48 Bytes
mpc_uint8_t     LUT4_0  [1<< 4] IBSS_ATTR_MPC_LARGE_IRAM;
mpc_uint8_t     LUT4_1  [1<< 5] IBSS_ATTR_MPC_LARGE_IRAM; //   48 Bytes
mpc_uint8_t     LUT5_0  [1<< 6] IBSS_ATTR_MPC_LARGE_IRAM;
mpc_uint8_t     LUT5_1  [1<< 8] IBSS_ATTR_MPC_LARGE_IRAM; //  320 Bytes
mpc_uint8_t     LUT6_0  [1<< 7] IBSS_ATTR_MPC_LARGE_IRAM;
mpc_uint8_t     LUT6_1  [1<< 7] IBSS_ATTR_MPC_LARGE_IRAM; //  256 Bytes
mpc_uint8_t     LUT7_0  [1<< 8] IBSS_ATTR_MPC_LARGE_IRAM;
mpc_uint8_t     LUT7_1  [1<< 8] IBSS_ATTR_MPC_LARGE_IRAM; //  512 Bytes
mpc_uint8_t     LUTDSCF [1<< 6] IBSS_ATTR_MPC_LARGE_IRAM; //   64 Bytes = 2976 Bytes

//------------------------------------------------------------------------------
// types
//------------------------------------------------------------------------------
enum
    {
        MEMSIZE = MPC_DECODER_MEMSIZE,      // overall buffer size
        MEMSIZE2 = (MEMSIZE/2),             // size of one buffer
        MEMMASK = (MEMSIZE-1)
    };

//------------------------------------------------------------------------------
// forward declarations
//------------------------------------------------------------------------------
void mpc_decoder_read_bitstream_sv6(mpc_decoder *d);
void mpc_decoder_read_bitstream_sv7(mpc_decoder *d, mpc_bool_t fastSeeking);
void mpc_decoder_update_buffer(mpc_decoder *d);
mpc_bool_t mpc_decoder_seek_sample(mpc_decoder *d, mpc_int64_t destsample);
void mpc_decoder_requantisierung(mpc_decoder *d, const mpc_int32_t Last_Band);
void mpc_decoder_seek_to(mpc_decoder *d, mpc_uint32_t bitPos);
void mpc_decoder_seek_forward(mpc_decoder *d, mpc_uint32_t bits);
mpc_uint32_t mpc_decoder_jump_frame(mpc_decoder *d);
void mpc_decoder_fill_buffer(mpc_decoder *d);
void mpc_decoder_reset_state(mpc_decoder *d);
static mpc_uint32_t get_initial_fpos(mpc_decoder *d, mpc_uint32_t StreamVersion);
static inline mpc_int32_t mpc_decoder_huffman_decode_fastest(mpc_decoder *d, const HuffmanTyp* Table, const mpc_uint8_t* tab, mpc_uint16_t unused_bits);
static void mpc_move_next(mpc_decoder *d);

mpc_uint32_t  Speicher[MPC_DECODER_MEMSIZE];
MPC_SAMPLE_FORMAT Y_L[36][32] IBSS_ATTR_MPC_LARGE_IRAM;
MPC_SAMPLE_FORMAT Y_R[36][32] IBSS_ATTR_MPC_LARGE_IRAM;

//------------------------------------------------------------------------------
// utility functions
//------------------------------------------------------------------------------
static mpc_int32_t f_read(mpc_decoder *d, void *ptr, size_t size) 
{ 
    return d->r->read(d->r->data, ptr, size); 
};

static mpc_bool_t f_seek(mpc_decoder *d, mpc_int32_t offset) 
{ 
    return d->r->seek(d->r->data, offset); 
};

static mpc_int32_t f_read_dword(mpc_decoder *d, mpc_uint32_t * ptr, mpc_uint32_t count) 
{
    count = f_read(d, ptr, count << 2) >> 2;
    return count;
}

//------------------------------------------------------------------------------
// huffman & bitstream functions
//------------------------------------------------------------------------------
static const mpc_uint32_t mask [33] ICONST_ATTR = {
    0x00000000, 0x00000001, 0x00000003, 0x00000007,
    0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F,
    0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF,
    0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF,
    0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF,
    0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF,
    0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF,
    0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF,
    0xFFFFFFFF
};

/* F U N C T I O N S */

// resets bitstream decoding
static void
mpc_decoder_reset_bitstream_decode(mpc_decoder *d) 
{
    d->dword = 0;
    d->next = 0;
    d->pos = 0;
    d->Zaehler = 0;
    d->WordsRead = 0;
}

// reports the number of read bits
static mpc_uint32_t
mpc_decoder_bits_read(mpc_decoder *d) 
{
    return 32 * d->WordsRead + d->pos;
}

static void mpc_move_next(mpc_decoder *d) {
    d->Zaehler = (d->Zaehler + 1) & MEMMASK;
    d->dword = d->next;
    d->next = SWAP(d->Speicher[(d->Zaehler + 1) & MEMMASK]);
    d->pos -= 32;
    ++(d->WordsRead);
}

// read desired number of bits out of the bitstream
static inline mpc_uint32_t
mpc_decoder_bitstream_read(mpc_decoder *d, const mpc_uint32_t bits) 
{
    mpc_uint32_t out = d->dword;

    d->pos += bits;

    if (d->pos < 32) {
        out >>= (32 - d->pos);
    }
    else {
        mpc_move_next(d);
        if (d->pos) {
            out <<= d->pos;
            out |= d->dword >> (32 - d->pos);
        }
    }

    return out & mask[bits];
}

static void 
mpc_decoder_make_huffman_lookup(
    mpc_uint8_t* lookup, size_t length, const HuffmanTyp* Table, size_t elements )
{
    size_t    i;
    size_t    idx  = elements;
    mpc_uint32_t  dval = (mpc_uint32_t)0x80000000L / length * 2;
    mpc_uint32_t  val  = dval - 1;

    for ( i = 0; i < length; i++, val += dval ) {
        while ( idx > 0  &&  val >= Table[idx-1].Code )
            idx--;
        *lookup++ = (mpc_uint8_t)idx;
    }

    return;
}

#ifdef MPC_SUPPORT_SV456
// decode SCFI-bundle (sv4,5,6)
static void
mpc_decoder_scfi_bundle_read(
    mpc_decoder *d,
    const HuffmanTyp* Table, mpc_int8_t* SCFI, mpc_bool_t* DSCF) 
{
    // load preview and decode
    mpc_uint32_t code  = d->dword << d->pos;

    if (d->pos > 26) {
        code |= d->next >> (32 - d->pos);
    }
    while (code < Table->Code) {
        Table++;
    }

    // set the new position within bitstream without performing a dummy-read
    if ((d->pos += Table->Length) >= 32) {
        mpc_move_next(d);
    }

    *SCFI = Table->Value >> 1;
    *DSCF = Table->Value &  1;
}

// basic huffman decoding routine
// works with maximum lengths up to 14
static mpc_int32_t
mpc_decoder_huffman_decode(mpc_decoder *d, const HuffmanTyp *Table) 
{
    // load preview and decode
    mpc_uint32_t code = d->dword << d->pos;
    
    if (d->pos > 18) {
        code |= d->next >> (32 - d->pos);
    }
    while (code < Table->Code) {
        Table++;
    }

    // set the new position within bitstream without performing a dummy-read
    if ((d->pos += Table->Length) >= 32) {
        mpc_move_next(d);
    }

    return Table->Value;
}
#endif

// faster huffman through previewing less bits
// works with maximum lengths up to 10
static mpc_int32_t
mpc_decoder_huffman_decode_fast(mpc_decoder *d, const HuffmanTyp* Table)
{
    // load preview and decode
    mpc_uint32_t code  = d->dword << d->pos;
    
    if (d->pos > 22) {
        code |= d->next >> (32 - d->pos);
    }
    while (code < Table->Code) {
        Table++;
    }

    // set the new position within bitstream without performing a dummy-read
    if ((d->pos += Table->Length) >= 32) {
        mpc_move_next(d);
    }

    return Table->Value;
}

// even faster huffman through previewing even less bits
// works with maximum lengths up to 5
static mpc_int32_t
mpc_decoder_huffman_decode_faster(mpc_decoder *d, const HuffmanTyp* Table)
{
    // load preview and decode
    mpc_uint32_t code  = d->dword << d->pos;
    
    if (d->pos > 27) {
        code |= d->next >> (32 - d->pos);
    }
    while (code < Table->Code) {
        Table++;
    }

    // set the new position within bitstream without performing a dummy-read
    if ((d->pos += Table->Length) >= 32) {
        mpc_move_next(d);
    }

    return Table->Value;
}

/* partial lookup table decode */
static mpc_int32_t
mpc_decoder_huffman_decode_fasterer(mpc_decoder *d, const HuffmanTyp* Table, const mpc_uint8_t* tab, mpc_uint16_t unused_bits)
{
    // load preview and decode
    mpc_uint32_t code  = d->dword << d->pos;
    
    if (d->pos > 18) { // preview 14 bits
        code |= d->next >> (32 - d->pos);
    }

    Table += tab [(size_t)(code >> unused_bits) ];

    while (code < Table->Code) {
        Table++;
    }

    // set the new position within bitstream without performing a dummy-read
    if ((d->pos += Table->Length) >= 32) {
        mpc_move_next(d);
    }

    return Table->Value;
}

/* full decode using lookup table */
static inline mpc_int32_t
mpc_decoder_huffman_decode_fastest(mpc_decoder *d, const HuffmanTyp* Table, const mpc_uint8_t* tab, mpc_uint16_t unused_bits)
{
    // load preview and decode
    mpc_uint32_t code  = d->dword << d->pos;

    if (d->pos > unused_bits) {
        code |= d->next >> (32 - d->pos);
    }

    Table+=tab [(size_t)(code >> unused_bits) ];

    // set the new position within bitstream without performing a dummy-read
    if ((d->pos += Table->Length) >= 32) {
        mpc_move_next(d);
    }

    return Table->Value;
}

static void
mpc_decoder_reset_v(mpc_decoder *d) 
{
    memset(d->V_L, 0, sizeof d->V_L);
    memset(d->V_R, 0, sizeof d->V_R);
}

static void
mpc_decoder_reset_synthesis(mpc_decoder *d) 
{
    mpc_decoder_reset_v(d);
}

static void
mpc_decoder_reset_y(mpc_decoder *d) 
{
    memset(d->Y_L, 0, sizeof Y_L);
    memset(d->Y_R, 0, sizeof Y_R);
}

static void
mpc_decoder_reset_globals(mpc_decoder *d) 
{
    mpc_decoder_reset_bitstream_decode(d);

    d->DecodedFrames    = 0;
    d->SeekTableIndex   = 0;
    d->MaxDecodedFrames = 0;
    d->StreamVersion    = 0;
    d->MS_used          = 0;

    memset(d->Y_L          , 0, sizeof Y_L           );
    memset(d->Y_R          , 0, sizeof Y_R           );
    memset(d->SCF_Index_L  , 0, sizeof d->SCF_Index_L);
    memset(d->SCF_Index_R  , 0, sizeof d->SCF_Index_R);
    memset(d->Res_L        , 0, sizeof d->Res_L      );
    memset(d->Res_R        , 0, sizeof d->Res_R      );
    memset(d->SCFI_L       , 0, sizeof d->SCFI_L     );
    memset(d->SCFI_R       , 0, sizeof d->SCFI_R     );
#ifdef MPC_SUPPORT_SV456
    memset(d->DSCF_Flag_L  , 0, sizeof d->DSCF_Flag_L);
    memset(d->DSCF_Flag_R  , 0, sizeof d->DSCF_Flag_R);
#endif
    memset(d->Q            , 0, sizeof d->Q          );
    memset(d->MS_Flag      , 0, sizeof d->MS_Flag    );
}

mpc_uint32_t
mpc_decoder_decode_frame(mpc_decoder *d, mpc_uint32_t *in_buffer,
                         mpc_uint32_t in_len, MPC_SAMPLE_FORMAT *out_buffer)
{
  mpc_decoder_reset_bitstream_decode(d);
  if (in_len > sizeof(Speicher)) in_len = sizeof(Speicher);
  memcpy(d->Speicher, in_buffer, in_len);
  d->dword = SWAP(d->Speicher[0]);
  d->next = SWAP(d->Speicher[1]);
  switch (d->StreamVersion) {
#ifdef MPC_SUPPORT_SV456
    case 0x04:
    case 0x05:
    case 0x06:
        mpc_decoder_read_bitstream_sv6(d);
        break;
#endif
    case 0x07:
    case 0x17:
        mpc_decoder_read_bitstream_sv7(d, FALSE);
        break;
    default:
        return (mpc_uint32_t)(-1);
  }
  mpc_decoder_requantisierung(d, d->Max_Band);
  mpc_decoder_synthese_filter_float(d, out_buffer);
  return mpc_decoder_bits_read(d);
}

static mpc_uint32_t
mpc_decoder_decode_internal(mpc_decoder *d, MPC_SAMPLE_FORMAT *buffer) 
{
    mpc_uint32_t output_frame_length = MPC_FRAME_LENGTH;

    mpc_uint32_t  FrameBitCnt = 0;

    // output the last part of the last frame here, if needed
    if (d->last_block_samples > 0) {
        output_frame_length = d->last_block_samples;
        d->last_block_samples = 0; // it's going to be handled now, so reset it 
        if (!d->TrueGaplessPresent) {
            mpc_decoder_reset_y(d);
        } else {
            mpc_decoder_bitstream_read(d, 20);
            mpc_decoder_read_bitstream_sv7(d, FALSE);
            mpc_decoder_requantisierung(d, d->Max_Band);
        }
        mpc_decoder_synthese_filter_float(d, buffer);
        return output_frame_length;
    }
    
    if (d->DecodedFrames >= d->OverallFrames) {
        return (mpc_uint32_t)(-1);                           // end of file -> abort decoding
    }

    if (d->DecodedFrames == 0)
        d->SeekTable[0] = mpc_decoder_bits_read(d);

    // read jump-info for validity check of frame
    d->FwdJumpInfo  = mpc_decoder_bitstream_read(d, 20);

    d->ActDecodePos = (d->Zaehler << 5) + d->pos;

    // decode data and check for validity of frame
    FrameBitCnt = mpc_decoder_bits_read(d);
    switch (d->StreamVersion) {
#ifdef MPC_SUPPORT_SV456
    case 0x04:
    case 0x05:
    case 0x06:
        mpc_decoder_read_bitstream_sv6(d);
        break;
#endif
    case 0x07:
    case 0x17:
        mpc_decoder_read_bitstream_sv7(d, FALSE);
        break;
    default:
        return (mpc_uint32_t)(-1);
    }
    d->FrameWasValid = mpc_decoder_bits_read(d) - FrameBitCnt == d->FwdJumpInfo;

    d->DecodedFrames++;

    /* update seek table */
    if (d->SeekTable_Step == 1) {
        d->SeekTable [d->DecodedFrames] = d->FwdJumpInfo + 20;
    } else {
        if ((d->DecodedFrames-1) % d->SeekTable_Step == 0) {
            d->SeekTable[d->SeekTableIndex] = d->SeekTableCounter;
            d->SeekTableIndex += 1;
            d->SeekTableCounter = 0;
        }
        d->SeekTableCounter += d->FwdJumpInfo + 20;
    }

    // synthesize signal
    mpc_decoder_requantisierung(d, d->Max_Band);

    mpc_decoder_synthese_filter_float(d, buffer);

    // cut off first MPC_DECODER_SYNTH_DELAY zero-samples
    if (d->DecodedFrames == d->OverallFrames  && d->StreamVersion >= 6) {        
        // reconstruct exact filelength
        mpc_int32_t  mod_block   = mpc_decoder_bitstream_read(d,  11);
        mpc_int32_t  FilterDecay;

        if (mod_block == 0) {
            // Encoder bugfix
            mod_block = 1152;                    
        }
        FilterDecay = (mod_block + MPC_DECODER_SYNTH_DELAY) % MPC_FRAME_LENGTH;

        // additional FilterDecay samples are needed for decay of synthesis filter
        if (MPC_DECODER_SYNTH_DELAY + mod_block >= MPC_FRAME_LENGTH) {
            // this variable will be checked for at the top of the function
            d->last_block_samples = FilterDecay;
        }
        else { // there are only FilterDecay samples needed for this frame
            output_frame_length = FilterDecay;
        }
    }

    if (d->samples_to_skip) {
        if (output_frame_length < d->samples_to_skip) {
            d->samples_to_skip -= output_frame_length;
            output_frame_length = 0;
        }
        else {
            output_frame_length -= d->samples_to_skip;
            memmove(
                buffer, 
                buffer + d->samples_to_skip, 
                output_frame_length * sizeof (MPC_SAMPLE_FORMAT));
            memmove(
                buffer + MPC_FRAME_LENGTH, 
                buffer + MPC_FRAME_LENGTH + d->samples_to_skip, 
                output_frame_length * sizeof (MPC_SAMPLE_FORMAT));
            d->samples_to_skip = 0;
        }
    }

    return output_frame_length;
}

mpc_uint32_t mpc_decoder_decode(
    mpc_decoder *d,
    MPC_SAMPLE_FORMAT *buffer, 
    mpc_uint32_t *vbr_update_acc, 
    mpc_uint32_t *vbr_update_bits)
{
    for(;;)
    {
        mpc_uint32_t RING = d->Zaehler;
        mpc_int32_t vbr_ring = (RING << 5) + d->pos;

        mpc_uint32_t valid_samples = mpc_decoder_decode_internal(d, buffer);

        if (valid_samples == (mpc_uint32_t)(-1) ) {
            return 0;
        }

        /**************** ERROR CONCEALMENT *****************/
        if (d->FrameWasValid == 0 ) {
            // error occurred in bitstream
            return (mpc_uint32_t)(-1);
        } 
        else {
            if (vbr_update_acc && vbr_update_bits) {
                (*vbr_update_acc) ++;
                vbr_ring = (d->Zaehler << 5) + d->pos - vbr_ring;
                if (vbr_ring < 0) {
                    vbr_ring += 524288;
                }
                (*vbr_update_bits) += vbr_ring;
            }

        }
        mpc_decoder_update_buffer(d);

        if (valid_samples > 0) {
            return valid_samples;
        }
    }
}

void
mpc_decoder_requantisierung(mpc_decoder *d, const mpc_int32_t Last_Band) 
{
    mpc_int32_t     Band;
    mpc_int32_t     n;
    MPC_SAMPLE_FORMAT facL;
    MPC_SAMPLE_FORMAT facR;
    MPC_SAMPLE_FORMAT templ;
    MPC_SAMPLE_FORMAT tempr;
    MPC_SAMPLE_FORMAT* YL;
    MPC_SAMPLE_FORMAT* YR;
    mpc_int16_t*    L;
    mpc_int16_t*    R;

#ifdef MPC_FIXED_POINT
#if MPC_FIXED_POINT_FRACTPART == 14
#define MPC_MULTIPLY_SCF(CcVal, SCF_idx) \
    MPC_MULTIPLY_EX(CcVal, d->SCF[SCF_idx], d->SCF_shift[SCF_idx])
#else

#error FIXME, Cc table is in 18.14 format

#endif
#else
#define MPC_MULTIPLY_SCF(CcVal, SCF_idx) \
    MPC_MULTIPLY(CcVal, d->SCF[SCF_idx])
#endif
    // requantization and scaling of subband-samples
    for ( Band = 0; Band <= Last_Band; Band++ ) {   // setting pointers
        YL = d->Y_L[0] + Band;
        YR = d->Y_R[0] + Band;
        L  = d->Q[Band].L;
        R  = d->Q[Band].R;
        /************************** MS-coded **************************/
        if ( d->MS_Flag [Band] ) {
            if ( d->Res_L [Band] ) {
                if ( d->Res_R [Band] ) {    // M!=0, S!=0
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][0]);
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][0]);
                    for ( n = 0; n < 12; n++, YL += 32, YR += 32 ) {
                        *YL   = (templ = MPC_MULTIPLY_FLOAT_INT(facL,*L++))+(tempr = MPC_MULTIPLY_FLOAT_INT(facR,*R++));
                        *YR   = templ - tempr;
                    }
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][1]);
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][1]);
                    for ( ; n < 24; n++, YL += 32, YR += 32 ) {
                        *YL   = (templ = MPC_MULTIPLY_FLOAT_INT(facL,*L++))+(tempr = MPC_MULTIPLY_FLOAT_INT(facR,*R++));
                        *YR   = templ - tempr;
                    }
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][2]);
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][2]);
                    for ( ; n < 36; n++, YL += 32, YR += 32 ) {
                        *YL   = (templ = MPC_MULTIPLY_FLOAT_INT(facL,*L++))+(tempr = MPC_MULTIPLY_FLOAT_INT(facR,*R++));
                        *YR   = templ - tempr;
                    }
                } else {    // M!=0, S==0
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][0]);
                    for ( n = 0; n < 12; n++, YL += 32, YR += 32 ) {
                        *YR = *YL = MPC_MULTIPLY_FLOAT_INT(facL,*L++);
                    }
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][1]);
                    for ( ; n < 24; n++, YL += 32, YR += 32 ) {
                        *YR = *YL = MPC_MULTIPLY_FLOAT_INT(facL,*L++);
                    }
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][2]);
                    for ( ; n < 36; n++, YL += 32, YR += 32 ) {
                        *YR = *YL = MPC_MULTIPLY_FLOAT_INT(facL,*L++);
                    }
                }
            } else {
                if (d->Res_R[Band])    // M==0, S!=0
                {
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][0]);
                    for ( n = 0; n < 12; n++, YL += 32, YR += 32 ) {
                        *YR = - (*YL = MPC_MULTIPLY_FLOAT_INT(facR,*(R++)));
                    }
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][1]);
                    for ( ; n < 24; n++, YL += 32, YR += 32 ) {
                        *YR = - (*YL = MPC_MULTIPLY_FLOAT_INT(facR,*(R++)));
                    }
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][2]);
                    for ( ; n < 36; n++, YL += 32, YR += 32 ) {
                        *YR = - (*YL = MPC_MULTIPLY_FLOAT_INT(facR,*(R++)));
                    }
                } else {    // M==0, S==0
                    for ( n = 0; n < 36; n++, YL += 32, YR += 32 ) {
                        *YR = *YL = 0;
                    }
                }
            }
        }
        /************************** LR-coded **************************/
        else {
            if ( d->Res_L [Band] ) {
                if ( d->Res_R [Band] ) {    // L!=0, R!=0
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][0]);
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][0]);
                    for (n = 0; n < 12; n++, YL += 32, YR += 32 ) {
                        *YL = MPC_MULTIPLY_FLOAT_INT(facL,*L++);
                        *YR = MPC_MULTIPLY_FLOAT_INT(facR,*R++);
                    }
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][1]);
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][1]);
                    for (; n < 24; n++, YL += 32, YR += 32 ) {
                        *YL = MPC_MULTIPLY_FLOAT_INT(facL,*L++);
                        *YR = MPC_MULTIPLY_FLOAT_INT(facR,*R++);
                    }
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][2]);
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][2]);
                    for (; n < 36; n++, YL += 32, YR += 32 ) {
                        *YL = MPC_MULTIPLY_FLOAT_INT(facL,*L++);
                        *YR = MPC_MULTIPLY_FLOAT_INT(facR,*R++);
                    }
                } else {     // L!=0, R==0
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][0]);
                    for ( n = 0; n < 12; n++, YL += 32, YR += 32 ) {
                        *YL = MPC_MULTIPLY_FLOAT_INT(facL,*L++);
                        *YR = 0;
                    }
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][1]);
                    for ( ; n < 24; n++, YL += 32, YR += 32 ) {
                        *YL = MPC_MULTIPLY_FLOAT_INT(facL,*L++);
                        *YR = 0;
                    }
                    facL = MPC_MULTIPLY_SCF( Cc[d->Res_L[Band]] , (unsigned char)d->SCF_Index_L[Band][2]);
                    for ( ; n < 36; n++, YL += 32, YR += 32 ) {
                        *YL = MPC_MULTIPLY_FLOAT_INT(facL,*L++);
                        *YR = 0;
                    }
                }
            }
            else {
                if ( d->Res_R [Band] ) {    // L==0, R!=0
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][0]);
                    for ( n = 0; n < 12; n++, YL += 32, YR += 32 ) {
                        *YL = 0;
                        *YR = MPC_MULTIPLY_FLOAT_INT(facR,*R++);
                    }
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][1]);
                    for ( ; n < 24; n++, YL += 32, YR += 32 ) {
                        *YL = 0;
                        *YR = MPC_MULTIPLY_FLOAT_INT(facR,*R++);
                    }
                    facR = MPC_MULTIPLY_SCF( Cc[d->Res_R[Band]] , (unsigned char)d->SCF_Index_R[Band][2]);
                    for ( ; n < 36; n++, YL += 32, YR += 32 ) {
                        *YL = 0;
                        *YR = MPC_MULTIPLY_FLOAT_INT(facR,*R++);
                    }
                } else {    // L==0, R==0
                    for ( n = 0; n < 36; n++, YL += 32, YR += 32 ) {
                        *YR = *YL = 0;
                    }
                }
            }
        }
    }
}

#ifdef MPC_SUPPORT_SV456
static const unsigned char Q_res[32][16] ICONST_ATTR = {
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17},
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17},
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17},
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17},
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17},
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17},
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17},
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17},