1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 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 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
|
#ifdef _WIN32
#define VC_EXTRALEAN
#define STRICT
#include <windows.h>
#include <mmsystem.h>
#endif
#define NEED_STRHDL // for STRHTL struct in audiostr.h
#include "globalincs/pstypes.h"
#include "sound/openal.h"
#include "sound/audiostr.h"
#include "sound/ds.h"
#include "sound/acm.h"
#include "cfile/cfile.h"
#include "sound/sound.h"
#include "sound/ogg/ogg.h"
#include "io/timer.h"
#define THREADED
#include "osapi/osapi.h"
#define MAX_STREAM_BUFFERS 4
// status
#define ASF_FREE 0
#define ASF_USED 1
// constants
#define BIGBUF_SIZE 176400
ubyte *Wavedata_load_buffer = NULL; // buffer used for cueing audiostreams
ubyte *Wavedata_service_buffer = NULL; // buffer used for servicing audiostreams
CRITICAL_SECTION Global_service_lock;
typedef bool (*TIMERCALLBACK)(ptr_u);
#define COMPRESSED_BUFFER_SIZE 176400
ubyte *Compressed_buffer = NULL; // Used to load in compressed data during a cueing interval
ubyte *Compressed_service_buffer = NULL; // Used to read in compressed data during a service interval
#define AS_HIGHEST_MAX 999999999 // max uncompressed filesize supported is 999 meg
int Audiostream_inited = 0;
static int dbg_print_ogg_error(const char *filename, int rc)
{
int fatal = 0;
char err_msg[100];
memset( &err_msg, 0, sizeof(err_msg) );
Assert( filename != NULL );
switch (rc) {
case OV_FALSE:
strncpy(err_msg, "A false status was returned", 99);
// should this be fatal?
break;
case OV_EOF:
strncpy(err_msg, "End-of-file reached", 99);
fatal = 1;
break;
case OV_HOLE:
strncpy(err_msg, "Data interruption (hole)", 99);
// special handling
break;
case OV_EREAD:
strncpy(err_msg, "Media read error", 99);
fatal = 1;
break;
case OV_EFAULT:
strncpy(err_msg, "Internal logic fault", 99);
fatal = 1;
break;
case OV_EIMPL:
strncpy(err_msg, "Attempted to use a feature that's not supported", 99);
fatal = 1;
break;
case OV_EINVAL:
strncpy(err_msg, "Invalid argument value", 99);
// doesn't appear to be fatal
break;
case OV_ENOTVORBIS:
strncpy(err_msg, "File contains non-Vorbis data, or is not a Vorbis file", 99);
fatal = 1;
break;
case OV_EBADHEADER:
strncpy(err_msg, "Invalid bitstream header", 99);
fatal = 1;
break;
case OV_EVERSION:
strncpy(err_msg, "Vorbis version mismatch", 99);
fatal = 1;
break;
case OV_ENOTAUDIO:
strncpy(err_msg, "Submitted data is not audio", 99);
fatal = 1;
break;
case OV_EBADPACKET:
strncpy(err_msg, "An invalid packet was submitted", 99);
// is this fatal?
break;
case OV_EBADLINK:
strncpy(err_msg, "Invalid stream section supplied, or corrupt link", 99);
fatal = 1; // is this really fatal or does the lib compensate?
break;
case OV_ENOSEEK:
strncpy(err_msg, "Bitstream is not seekable", 99);
fatal = 1;
break;
default:
strncpy(err_msg, "Unknown error occurred", 99);
fatal = 1; // assume fatal
break;
}
// only dump fatal errors, everything else should be handled silently by default
if (fatal)
mprintf(("OGG ERROR: \"%s\" in %s\n", err_msg, filename));
// else
// nprintf(("OGGISH", "OGG ERROR: \"%s\" in %s\n", err_msg, filename));
return fatal;
}
static int audiostr_read_uint(HMMIO rw, uint *i)
{
int rc = mmioRead( rw, (char *)i, sizeof(uint) );
if (rc != sizeof(uint))
return 0;
*i = INTEL_INT(*i); //-V570
return 1;
}
static int audiostr_read_word(HMMIO rw, WORD *i)
{
int rc = mmioRead( rw, (char *)i, sizeof(WORD) );
if (rc != sizeof(WORD))
return 0;
*i = INTEL_SHORT(*i); //-V570
return 1;
}
static int audiostr_read_dword(HMMIO rw, DWORD *i)
{
int rc = mmioRead( rw, (char *)i, sizeof(DWORD) );
if (rc != sizeof(DWORD))
return 0;
*i = INTEL_INT(*i); //-V570
return 1;
}
class Timer
{
public:
void constructor(void);
void destructor(void);
bool Create (uint nPeriod, uint nRes, ptr_u dwUser, TIMERCALLBACK pfnCallback);
protected:
#ifndef SCP_UNIX
static void CALLBACK TimeProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2);
#else
static uint TimeProc(uint interval, void *param);
#endif
TIMERCALLBACK m_pfnCallback;
ptr_u m_dwUser;
uint m_nPeriod;
uint m_nRes;
#ifndef SCP_UNIX
uint m_nIDTimer;
#else
SDL_TimerID m_nIDTimer;
#endif
};
class WaveFile
{
public:
void Init(void);
void Close(void);
bool Open (char *pszFilename, bool keep_ext = true);
bool Cue (void);
int Read (ubyte *pbDest, uint cbSize, int service=1);
uint GetNumBytesRemaining (void) { return (m_nDataSize - m_nBytesPlayed); }
uint GetUncompressedAvgDataRate (void) { return (m_nUncompressedAvgDataRate); }
uint GetDataSize (void) { return (m_nDataSize); }
uint GetNumBytesPlayed (void) { return (m_nBytesPlayed); }
ALenum GetALFormat() { return (m_al_format); }
WAVEFORMATEX m_wfmt; // format of wave file used by Direct Sound
WAVEFORMATEX *m_pwfmt_original; // foramt of wave file from actual wave source
uint m_total_uncompressed_bytes_read;
uint m_max_uncompressed_bytes_to_read;
uint m_bits_per_sample_uncompressed;
protected:
uint m_data_offset; // number of bytes to actual wave data
int m_data_bytes_left;
uint m_wave_format; // format of wave source (ie WAVE_FORMAT_PCM, WAVE_FORMAT_ADPCM)
uint m_nBlockAlign; // wave data block alignment spec
uint m_nUncompressedAvgDataRate; // average wave data rate
uint m_nDataSize; // size of data chunk
uint m_nBytesPlayed; // offset into data chunk
bool m_abort_next_read;
ALenum m_al_format;
STRHDL m_snd_info;
void *m_hStream;
int m_hStream_open;
WAVEFORMATEX m_wfxDest;
char m_wFilename[MAX_FILENAME_LEN];
};
class AudioStream
{
public:
AudioStream (void);
~AudioStream (void);
bool Create (char *pszFilename);
bool Destroy (void);
void Play (float volume, int looping);
bool Is_Playing(){ return m_fPlaying; }
bool Is_Paused(){ return m_bIsPaused; }
bool Is_Past_Limit() { return m_bPastLimit; }
void Stop (int paused = 0);
void Stop_and_Rewind (void);
void Fade_and_Destroy (void);
void Fade_and_Stop(void);
void Set_Volume(float vol);
float Get_Volume();
void Init_Data();
void Set_Sample_Cutoff(uint sample_cutoff);
void Set_Default_Volume(float vol) { m_lDefaultVolume = vol; }
float Get_Default_Volume() { return m_lDefaultVolume; }
uint Get_Samples_Committed(void);
int Is_looping() { return m_bLooping; }
int status;
int type;
ushort m_bits_per_sample_uncompressed;
protected:
void Cue (void);
bool WriteWaveData (uint cbSize, uint *num_bytes_written, int service = 1);
uint GetMaxWriteSize (void);
bool ServiceBuffer (void);
static bool TimerCallback (ptr_u dwUser);
bool PlaybackDone(void);
ALuint m_source_id; // name of openAL source
ALuint m_buffer_ids[MAX_STREAM_BUFFERS]; // names of buffers
Timer m_timer; // ptr to Timer object
WaveFile *m_pwavefile; // ptr to WaveFile object
bool m_fCued; // semaphore (stream cued)
bool m_fPlaying; // semaphore (stream playing)
uint m_cbBufOffset; // last write position
uint m_cbBufSize; // size of sound buffer in bytes
uint m_nBufService; // service interval in msec
uint m_nTimeStarted; // time (in system time) playback started
bool m_bLooping; // whether or not to loop playback
bool m_bFade; // fade out music
bool m_bDestroy_when_faded;
float m_lVolume; // volume of stream ( 0 -> 1 )
float m_lCutoffVolume;
bool m_bIsPaused; // stream is stopped, but not rewinded
bool m_bReadingDone; // no more bytes to be read from disk, still have remaining buffer to play
uint m_fade_timer_id; // timestamp so we know when to start fade
uint m_finished_id; // timestamp so we know when we've played #bytes required
bool m_bPastLimit; // flag to show we've played past the number of bytes requred
float m_lDefaultVolume;
CRITICAL_SECTION write_lock;
};
// Timer class implementation
//
////////////////////////////////////////////////////////////
// constructor
void Timer::constructor(void)
{
m_nIDTimer = NULL;
}
// Destructor
void Timer::destructor(void)
{
if (m_nIDTimer) {
#ifndef SCP_UNIX
timeKillEvent (m_nIDTimer);
#else
SDL_RemoveTimer(m_nIDTimer);
#endif
m_nIDTimer = NULL;
}
}
// Create
bool Timer::Create (uint nPeriod, uint nRes, ptr_u dwUser, TIMERCALLBACK pfnCallback)
{
bool bRtn = true; // assume success
Assert(pfnCallback);
Assert(nPeriod > 10);
Assert(nPeriod >= nRes);
m_nPeriod = nPeriod;
m_nRes = nRes;
m_dwUser = dwUser;
m_pfnCallback = pfnCallback;
#ifndef SCP_UNIX
if ((m_nIDTimer = timeSetEvent ((UINT)m_nPeriod, (UINT)m_nRes, TimeProc, (DWORD)this, TIME_PERIODIC)) == NULL) {
#else
if ((m_nIDTimer = SDL_AddTimer(m_nPeriod, TimeProc, (void*)this)) == NULL) {
#endif
bRtn = false;
}
return (bRtn);
}
// Timer proc for multimedia timer callback set with timeSetTime().
//
// Calls procedure specified when Timer object was created. The
// dwUser parameter contains "this" pointer for associated Timer object.
//
#ifndef SCP_UNIX
void CALLBACK Timer::TimeProc(UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
#else
uint Timer::TimeProc(uint interval, void *dwUser)
#endif
{
// dwUser contains ptr to Timer object
Timer * ptimer = (Timer *) dwUser;
// Call user-specified callback and pass back user specified data
(ptimer->m_pfnCallback) (ptimer->m_dwUser);
#ifdef SCP_UNIX
if (ptimer->m_nPeriod) {
return interval;
} else {
SDL_RemoveTimer(ptimer->m_nIDTimer);
ptimer->m_nIDTimer = NULL;
return 0;
}
#endif
}
// WaveFile class implementation
//
////////////////////////////////////////////////////////////
// Constructor
void WaveFile::Init(void)
{
// Init data members
m_data_offset = 0;
m_snd_info.cfp = NULL;
m_snd_info.true_offset = 0;
m_snd_info.size = 0;
m_pwfmt_original = NULL;
m_nBlockAlign= 0;
m_nUncompressedAvgDataRate = 0;
m_nDataSize = 0;
m_nBytesPlayed = 0;
m_total_uncompressed_bytes_read = 0;
m_max_uncompressed_bytes_to_read = AS_HIGHEST_MAX;
m_al_format = AL_FORMAT_MONO8;
memset(&m_wFilename, 0, MAX_FILENAME_LEN);
m_hStream_open = 0;
m_abort_next_read = false;
}
// Destructor
void WaveFile::Close(void)
{
// Free memory
if (m_pwfmt_original) {
vm_free(m_pwfmt_original);
m_pwfmt_original = NULL;
}
if ( m_hStream_open ) {
ACM_stream_close((void*)m_hStream);
m_hStream_open = 0;
}
// Close file
if (m_snd_info.cfp) {
if (m_wave_format == OGG_FORMAT_VORBIS)
ov_clear(&m_snd_info.vorbis_file);
mmioClose( m_snd_info.cfp, 0 );
m_snd_info.cfp = NULL;
m_snd_info.true_offset = 0;
m_snd_info.size = 0;
}
}
// -- from parselo.cpp --
extern char *stristr(const char *str, const char *substr);
// Open
bool WaveFile::Open(char *pszFilename, bool keep_ext)
{
int rc = -1;
WORD cbExtra = 0;
bool fRtn = true; // assume success
PCMWAVEFORMAT pcmwf;
int FileSize, FileOffset;
char fullpath[MAX_PATH];
char filename[MAX_FILENAME_LEN];
const int NUM_EXT = 2;
const char *audio_ext[NUM_EXT] = { ".ogg", ".wav" };
m_total_uncompressed_bytes_read = 0;
m_max_uncompressed_bytes_to_read = AS_HIGHEST_MAX;
// NOTE: we assume that the extension has already been stripped off if it was supposed to be!!
strcpy_s( filename, pszFilename );
// if we are supposed to load the file as passed...
if (keep_ext) {
for (int i = 0; i < NUM_EXT; i++) {
if ( stristr(pszFilename, audio_ext[i]) ) {
rc = i;
break;
}
}
// not a supported extension format ... somebody screwed up their tbls :)
if (rc < 0)
goto OPEN_ERROR;
cf_find_file_location(pszFilename, CF_TYPE_ANY, sizeof(fullpath) - 1, fullpath, &FileSize, &FileOffset);
}
// ... otherwise we just find the best match
else {
rc = cf_find_file_location_ext(filename, NUM_EXT, audio_ext, CF_TYPE_ANY, sizeof(fullpath) - 1, fullpath, &FileSize, &FileOffset);
}
if (rc < 0) {
goto OPEN_ERROR;
} else {
// set proper filename for later use (assumes that it doesn't already have an extension)
strcat_s( filename, audio_ext[rc] );
}
m_snd_info.cfp = mmioOpen( fullpath, NULL, MMIO_ALLOCBUF | MMIO_READ );
if (m_snd_info.cfp == NULL)
goto OPEN_ERROR;
m_snd_info.true_offset = FileOffset;
m_snd_info.size = FileSize;
// if in a VP then position the stream at the start of the file
if (FileOffset > 0)
mmioSeek( m_snd_info.cfp, FileOffset, SEEK_SET );
// if Ogg Vorbis...
if (rc == 0) {
if ( ov_open_callbacks(&m_snd_info, &m_snd_info.vorbis_file, NULL, 0, mmio_callbacks) == 0 ) {
// got an Ogg Vorbis, so lets read the info in
ov_info(&m_snd_info.vorbis_file, -1);
// we only support one logical bitstream
if ( ov_streams(&m_snd_info.vorbis_file) != 1 ) {
mprintf(("AUDIOSTR => OGG reading error: We don't handle bitstream changes!\n"));
goto OPEN_ERROR;
}
m_wave_format = OGG_FORMAT_VORBIS;
m_wfmt.wFormatTag = WAVE_FORMAT_PCM;
m_wfmt.nChannels = (WORD) m_snd_info.vorbis_file.vi->channels;
m_wfmt.nSamplesPerSec = m_snd_info.vorbis_file.vi->rate;
switch (Ds_sound_quality) {
case DS_SQ_HIGH:
m_wfmt.wBitsPerSample = Ds_float_supported ? 32 : 16;
break;
case DS_SQ_MEDIUM:
m_wfmt.wBitsPerSample = 16;
break;
default:
m_wfmt.wBitsPerSample = 8;
break;
}
m_wfmt.cbSize = 0;
m_wfmt.nBlockAlign = (ushort)(( m_wfmt.nChannels * m_wfmt.wBitsPerSample ) / 8);
m_wfmt.nAvgBytesPerSec = m_wfmt.nSamplesPerSec * m_wfmt.nBlockAlign;
m_nBlockAlign = m_wfmt.nBlockAlign;
m_nUncompressedAvgDataRate = m_wfmt.nAvgBytesPerSec;
// location of start of file in VP
m_data_offset = 0;
m_nDataSize = m_data_bytes_left = ((int)ov_pcm_total(&m_snd_info.vorbis_file, -1) * m_wfmt.nBlockAlign);
} else {
mprintf(("AUDIOSTR => OGG reading error: Not a valid Vorbis file!\n"));
}
}
// if Wave...
else if (rc == 1) {
bool done = false;
// Skip the "RIFF" tag and file size (8 bytes)
// Skip the "WAVE" tag (4 bytes)
mmioSeek( m_snd_info.cfp, 12+FileOffset, SEEK_SET );
// Now read RIFF tags until the end of file
uint tag, size, next_chunk;
while ( !done ) {
if ( !audiostr_read_uint(m_snd_info.cfp, &tag) )
break;
if ( !audiostr_read_uint(m_snd_info.cfp, &size) )
break;
next_chunk = mmioSeek(m_snd_info.cfp, 0, SEEK_CUR );
next_chunk += size;
switch (tag)
{
case 0x20746d66: // The 'fmt ' tag
{
audiostr_read_word(m_snd_info.cfp, &pcmwf.wf.wFormatTag);
audiostr_read_word(m_snd_info.cfp, &pcmwf.wf.nChannels);
audiostr_read_dword(m_snd_info.cfp, &pcmwf.wf.nSamplesPerSec);
audiostr_read_dword(m_snd_info.cfp, &pcmwf.wf.nAvgBytesPerSec);
audiostr_read_word(m_snd_info.cfp, &pcmwf.wf.nBlockAlign);
audiostr_read_word(m_snd_info.cfp, &pcmwf.wBitsPerSample);
if (pcmwf.wf.wFormatTag == WAVE_FORMAT_ADPCM)
audiostr_read_word(m_snd_info.cfp, &cbExtra);
// Allocate memory for WAVEFORMATEX structure + extra bytes
if ( (m_pwfmt_original = (WAVEFORMATEX *) vm_malloc(sizeof(WAVEFORMATEX)+cbExtra)) != NULL ) {
Assert(m_pwfmt_original != NULL);
// Copy bytes from temporary format structure
memcpy (m_pwfmt_original, &pcmwf, sizeof(pcmwf));
m_pwfmt_original->cbSize = cbExtra;
// Read those extra bytes, append to WAVEFORMATEX structure
if (cbExtra != 0)
mmioRead( m_snd_info.cfp, ((char *)(m_pwfmt_original) + sizeof(WAVEFORMATEX)), cbExtra );
} else {
Int3(); // malloc failed
goto OPEN_ERROR;
}
break;
}
case 0x61746164: // the 'data' tag
{
m_nDataSize = size; // This is size of data chunk. Compressed if ADPCM.
m_data_bytes_left = size;
m_data_offset = mmioSeek( m_snd_info.cfp, 0, SEEK_CUR );
done = true;
break;
}
default: // unknown, skip it
break;
} // end switch
mmioSeek( m_snd_info.cfp, next_chunk, SEEK_SET );
}
// make sure that we did good
if ( !done || (m_pwfmt_original == NULL) )
goto OPEN_ERROR;
// At this stage, examine source format, and set up WAVEFORATEX structure for DirectSound.
// Since DirectSound only supports PCM, force this structure to be PCM compliant. We will
// need to convert data on the fly later if our souce is not PCM
switch (m_pwfmt_original->wFormatTag) {
case WAVE_FORMAT_PCM:
m_wave_format = WAVE_FORMAT_PCM;
m_wfmt.wBitsPerSample = m_pwfmt_original->wBitsPerSample;
break;
case WAVE_FORMAT_ADPCM:
m_wave_format = WAVE_FORMAT_ADPCM;
m_wfmt.wBitsPerSample = (Ds_sound_quality) ? 16: 8;
m_bits_per_sample_uncompressed = m_wfmt.wBitsPerSample;
break;
case WAVE_FORMAT_IEEE_FLOAT: {
m_wave_format = WAVE_FORMAT_IEEE_FLOAT;
switch (Ds_sound_quality) {
case DS_SQ_HIGH:
m_wfmt.wBitsPerSample = (Ds_float_supported) ? 32 : 16;
break;
case DS_SQ_MEDIUM:
m_wfmt.wBitsPerSample = 16;
break;
default:
m_wfmt.wBitsPerSample = 8;
break;
}
break;
}
default:
nprintf(("SOUND", "SOUND => Not supporting %d format for playing wave files\n", m_pwfmt_original->wFormatTag));
goto OPEN_ERROR;
break;
} // end switch
// Set up the WAVEFORMATEX structure to have the right PCM characteristics
m_wfmt.wFormatTag = WAVE_FORMAT_PCM;
m_wfmt.nChannels = m_pwfmt_original->nChannels;
m_wfmt.nSamplesPerSec = m_pwfmt_original->nSamplesPerSec;
m_wfmt.cbSize = 0;
m_wfmt.nBlockAlign = (ushort)(( m_wfmt.nChannels * m_wfmt.wBitsPerSample ) / 8);
m_wfmt.nAvgBytesPerSec = m_wfmt.nBlockAlign * m_wfmt.nSamplesPerSec;
// Init some member data from format chunk
m_nBlockAlign = m_pwfmt_original->nBlockAlign;
m_nUncompressedAvgDataRate = m_wfmt.nAvgBytesPerSec;
Assert( (m_wfmt.nChannels == 1) || (m_wfmt.nChannels == 2) );
}
// something unkown???
else {
Int3();
}
m_al_format = openal_get_format(m_wfmt.wBitsPerSample, m_wfmt.nChannels);
if (m_al_format != AL_INVALID_VALUE) {
// Cue for streaming
Cue();
goto OPEN_DONE;
}
OPEN_ERROR:
// Handle all errors here
nprintf(("SOUND","SOUND ==> Could not open wave file %s for streaming\n", filename));
fRtn = false;
if (m_snd_info.cfp != NULL) {
// Close file
mmioClose( m_snd_info.cfp, 0 );
m_snd_info.cfp = NULL;
m_snd_info.true_offset = 0;
m_snd_info.size = 0;
}
if (m_pwfmt_original) {
vm_free(m_pwfmt_original);
m_pwfmt_original = NULL;
}
OPEN_DONE:
strncpy(m_wFilename, filename, MAX_FILENAME_LEN-1);
if (fRtn)
nprintf(("SOUND", "AUDIOSTR => Successfully opened: %s\n", filename));
return (fRtn);
}
// Cue
//
// Set the file pointer to the start of wave data
//
bool WaveFile::Cue (void)
{
bool fRtn = true; // assume success
int rval;
m_total_uncompressed_bytes_read = 0;
m_max_uncompressed_bytes_to_read = AS_HIGHEST_MAX;
if (m_wave_format == OGG_FORMAT_VORBIS) {
rval = (int)ov_raw_seek(&m_snd_info.vorbis_file, m_data_offset);
} else {
rval = mmioSeek( m_snd_info.cfp, m_data_offset, SEEK_SET );
}
if ( rval == -1 ) {
fRtn = false;
}
m_data_bytes_left = m_nDataSize;
m_abort_next_read = false;
return fRtn;
}
// Read
//
// Returns number of bytes actually read.
//
// Returns -1 if there is nothing more to be read. This function can return 0, since
// sometimes the amount of bytes requested is too small for the ACM decompression to
// locate a suitable block
int WaveFile::Read(ubyte *pbDest, uint cbSize, int service)
{
void *dest_buf=NULL, *uncompressed_wave_data;
int rc, uncompressed_bytes_written, section, last_section = -1, byte_order = 0;
uint src_bytes_used, convert_len, num_bytes_desired=0, num_bytes_read;
// nprintf(("Alan","Reqeusted: %d\n", cbSize));
#if BYTE_ORDER == BIG_ENDIAN
byte_order = 1;
#endif
if ( service ) {
uncompressed_wave_data = Wavedata_service_buffer;
} else {
uncompressed_wave_data = Wavedata_load_buffer;
}
switch ( m_wave_format ) {
case WAVE_FORMAT_PCM:
num_bytes_desired = cbSize;
dest_buf = pbDest;
break;
case WAVE_FORMAT_ADPCM: {
if ( !m_hStream_open ) {
if ( !ACM_stream_open(m_pwfmt_original, &m_wfxDest, (void**)&m_hStream, m_bits_per_sample_uncompressed) ) {
m_hStream_open = 1;
} else {
Int3();
}
}
num_bytes_desired = cbSize;
if ( service ) {
dest_buf = Compressed_service_buffer;
} else {
dest_buf = Compressed_buffer;
}
if ( num_bytes_desired <= 0 ) {
num_bytes_desired = 0;
// nprintf(("Alan","No bytes required for ADPCM time interval\n"));
} else {
num_bytes_desired = ACM_query_source_size((void*)m_hStream, cbSize);
// nprintf(("Alan","Num bytes desired: %d\n", num_bytes_desired));
}
break;
}
case OGG_FORMAT_VORBIS:
num_bytes_desired = cbSize;
dest_buf = pbDest;
break;
case WAVE_FORMAT_IEEE_FLOAT: {
num_bytes_desired = cbSize;
if (m_wfmt.wBitsPerSample == 32) {
dest_buf = pbDest;
} else {
if (service) {
dest_buf = Compressed_service_buffer;
} else {
dest_buf = Compressed_buffer;
}
}
break;
}
default:
nprintf(("SOUND", "SOUND => Not supporting %d format for playing wave files\n", m_wave_format));
Int3();
break;
} // end switch
num_bytes_read = 0;
convert_len = 0;
src_bytes_used = 0;
// read data from disk
if ( m_data_bytes_left <= 0 ) {
num_bytes_read = 0;
uncompressed_bytes_written = 0;
return -1;
}
if ( (m_data_bytes_left > 0) && (num_bytes_desired > 0) ) {
int actual_read = 0;
if ( num_bytes_desired <= (uint)m_data_bytes_left ) {
num_bytes_read = num_bytes_desired;
}
else {
num_bytes_read = m_data_bytes_left;
}
// OGG reading is special
if ( m_wave_format == OGG_FORMAT_VORBIS ) {
int sign = (m_wfmt.wBitsPerSample == 8) ? 0 : 1;
int sample_size = sizeof(float) * m_wfmt.nChannels;
while ( !m_abort_next_read && ((uint)actual_read < num_bytes_read)) {
float **pcm = NULL;
if (m_wfmt.wBitsPerSample == 32) {
rc = ov_read_float(&m_snd_info.vorbis_file, &pcm, (num_bytes_read - actual_read) / sample_size, §ion);
} else {
rc = ov_read(&m_snd_info.vorbis_file, (char *)dest_buf + actual_read, num_bytes_read - actual_read, byte_order, m_wfmt.wBitsPerSample / 8, sign, §ion);
}
// fail if the bitstream changes, shouldn't get this far if that's the case though
if ((last_section != -1) && (last_section != section)) {
mprintf(("AUDIOSTR => OGG reading error: We don't handle bitstream changes!\n"));
goto READ_ERROR;
}
if ( rc > 0 ) {
if (m_wfmt.wBitsPerSample == 32) {
float *out_p = (float*)((ubyte*)dest_buf + actual_read);
for (int i = 0; i < rc; i++) {
for (int j = 0; j < m_wfmt.nChannels; j++) {
*out_p++ = pcm[j][i];
}
}
actual_read += (rc * m_wfmt.nBlockAlign);
} else {
actual_read += rc;
}
last_section = section;
} else if ( rc == 0 ) {
break;
} else if ( rc < 0 ) {
if ( dbg_print_ogg_error(m_wFilename, rc) ) {
// must be a fatal error
goto READ_ERROR;
} else {
// not fatal, just continue on
break;
}
}
}
}
// IEEE FLOAT is special too, downsampling can give short buffers
else if (m_wave_format == WAVE_FORMAT_IEEE_FLOAT) {
while ( !m_abort_next_read && ((uint)actual_read < num_bytes_read) ) {
rc = mmioRead(m_snd_info.cfp, (char *)dest_buf, num_bytes_read);
if (rc <= 0) {
break;
}
#if BYTE_ORDER == BIG_ENDIAN
// need to byte-swap before any later conversions
float *swap_tmp;
for (int i = 0; i < rc; i += sizeof(float)) {
swap_tmp = (float *)((ubyte*)dest_buf + i);
*swap_tmp = INTEL_FLOAT(swap_tmp);
}
#endif
if (m_wfmt.wBitsPerSample == 32) {
actual_read = rc;
} else if (m_wfmt.wBitsPerSample == 16) {
float *in_p = (float*)dest_buf;
short *out_p = (short*)((ubyte*)uncompressed_wave_data + actual_read);
int end = rc / sizeof(float);
for (int i = 0; i < end; i++) {
int i_val = (int)(in_p[i] * 32767.0f + 0.5f);
CLAMP(i_val, -32768, 32767);
*out_p++ = (short)i_val;
}
actual_read += (rc >> 1);
} else {
Assert( m_wfmt.wBitsPerSample == 8 );
float *in_p = (float*)dest_buf;
ubyte *out_p = (ubyte*)((ubyte*)uncompressed_wave_data + actual_read);
int end = num_bytes_read / sizeof(float);
for (int i = 0; i < end; i++) {
int i_val = (int)(in_p[i] * 127.0f + 0.5f) + 128;
CLAMP(i_val, 0, 255);
*out_p++ = (ubyte)i_val;
}
actual_read += (rc >> 2);
}
}
}
// standard WAVE reading
else {
actual_read = mmioRead( m_snd_info.cfp, (char *)dest_buf, num_bytes_read );
}
if ( (actual_read <= 0) || (m_abort_next_read) ) {
num_bytes_read = 0;
uncompressed_bytes_written = 0;
return -1;
}
if ( num_bytes_desired >= (uint)m_data_bytes_left ) {
m_abort_next_read = 1;
}
num_bytes_read = actual_read;
}
// convert data if necessary, to PCM
if ( m_wave_format == WAVE_FORMAT_ADPCM ) {
if ( num_bytes_read > 0 ) {
rc = ACM_convert((void*)m_hStream, (ubyte*)dest_buf, num_bytes_read, (ubyte*)uncompressed_wave_data, BIGBUF_SIZE, &convert_len, &src_bytes_used);
if ( rc == -1 ) {
goto READ_ERROR;
} else if ( convert_len == 0 ) {
if (num_bytes_read < m_nBlockAlign) {
mprintf(("AUDIOSTR => Warning: Short read detected in ACM decode of '%s'!!\n", m_wFilename));
} else {
Int3();
}
}
}
Assert(src_bytes_used <= num_bytes_read);
if ( src_bytes_used < num_bytes_read ) {
// seek back file pointer to reposition before unused source data
mmioSeek( m_snd_info.cfp, src_bytes_used - num_bytes_read, SEEK_CUR );
}
// Adjust number of bytes left
m_data_bytes_left -= src_bytes_used;
m_nBytesPlayed += src_bytes_used;
uncompressed_bytes_written = convert_len;
// Successful read, keep running total of number of data bytes read
goto READ_DONE;
}
else {
// Successful read, keep running total of number of data bytes read
// Adjust number of bytes left
m_data_bytes_left -= num_bytes_read;
m_nBytesPlayed += num_bytes_read;
uncompressed_bytes_written = num_bytes_read;
#if BYTE_ORDER == BIG_ENDIAN
if ( m_wave_format == WAVE_FORMAT_PCM ) {
// swap 16-bit sound data
if (m_wfmt.wBitsPerSample == 16) {
ushort *swap_tmp;
for (uint i=0; i<uncompressed_bytes_written; i=i+2) {
swap_tmp = (ushort*)((ubyte*)dest_buf + i);
*swap_tmp = INTEL_SHORT(*swap_tmp);
}
}
}
#endif
goto READ_DONE;
}
READ_ERROR:
num_bytes_read = 0;
uncompressed_bytes_written = 0;
READ_DONE:
m_total_uncompressed_bytes_read += uncompressed_bytes_written;
// nprintf(("Alan","Read: %d\n", uncompressed_bytes_written));
return (uncompressed_bytes_written);
}
//
// AudioStream class implementation
//
////////////////////////////////////////////////////////////
// The following constants are the defaults for our streaming buffer operation.
const ushort DefBufferServiceInterval = 250; // default buffer service interval in msec
// Constructor
AudioStream::AudioStream (void)
{
INITIALIZE_CRITICAL_SECTION( write_lock );
}
// Destructor
AudioStream::~AudioStream (void)
{
DELETE_CRITICAL_SECTION( write_lock );
}
void AudioStream::Init_Data ()
{
m_bLooping = 0;
m_bFade = false;
m_fade_timer_id = 0;
m_finished_id = 0;
m_bPastLimit = false;
m_bDestroy_when_faded = false;
m_lVolume = 1.0f;
m_lCutoffVolume = 0.0f;
m_bIsPaused = false;
m_bReadingDone = false;
m_pwavefile = NULL;
m_fPlaying = m_fCued = false;
m_cbBufOffset = 0;
m_cbBufSize = 0;
m_nBufService = DefBufferServiceInterval;
m_nTimeStarted = 0;
memset(m_buffer_ids, 0, sizeof(m_buffer_ids));
m_source_id = 0;
}
// Create
bool AudioStream::Create (char *pszFilename)
{
bool fRtn = true; // assume success
Assert(pszFilename);
Init_Data();
if (pszFilename) {
// make 100% sure we got a good filename
if ( !strlen(pszFilename) )
return false;
// Create a new WaveFile object
m_pwavefile = (WaveFile *)vm_malloc(sizeof(WaveFile));
Assert(m_pwavefile);
if (m_pwavefile) {
// Call constructor
m_pwavefile->Init();
// Open given file
m_pwavefile->m_bits_per_sample_uncompressed = m_bits_per_sample_uncompressed;
if ( m_pwavefile->Open(pszFilename, (type == ASF_EVENTMUSIC)) ) {
m_cbBufSize = m_pwavefile->m_wfmt.nAvgBytesPerSec >> 2;
// make sure that we are a multiple of the frame size
m_cbBufSize -= (m_cbBufSize % m_pwavefile->m_wfmt.nBlockAlign);
m_cbBufSize += (m_cbBufSize % 12) << 1;
// if the requested buffer size is too big then cap it
m_cbBufSize = (m_cbBufSize > BIGBUF_SIZE) ? BIGBUF_SIZE : m_cbBufSize;
// nprintf(("SOUND", "SOUND => Stream buffer created using %d bytes\n", m_cbBufSize));
OpenAL_ErrorCheck( alGenSources(1, &m_source_id), { fRtn = false; goto ErrorExit; } );
OpenAL_ErrorCheck( alGenBuffers(MAX_STREAM_BUFFERS, m_buffer_ids), { fRtn = false; goto ErrorExit; } );
OpenAL_ErrorPrint( alSourcef(m_source_id, AL_ROLLOFF_FACTOR, 1.0f) );
OpenAL_ErrorPrint( alSourcei(m_source_id, AL_SOURCE_RELATIVE, AL_TRUE) );
OpenAL_ErrorPrint( alSource3f(m_source_id, AL_POSITION, 0.0f, 0.0f, 0.0f) );
OpenAL_ErrorPrint( alSource3f(m_source_id, AL_VELOCITY, 0.0f, 0.0f, 0.0f) );
OpenAL_ErrorPrint( alSourcef(m_source_id, AL_GAIN, 1.0f) );
OpenAL_ErrorPrint( alSourcef(m_source_id, AL_PITCH, 1.0f) );
// maybe set EFX
if ( (type == ASF_SOUNDFX) && ds_eax_is_inited() ) {
extern ALuint AL_EFX_aux_id;
OpenAL_ErrorPrint( alSource3i(m_source_id, AL_AUXILIARY_SEND_FILTER, AL_EFX_aux_id, 0, AL_FILTER_NULL) );
}
// Cue for playback
Cue();
Snd_sram += (m_cbBufSize * MAX_STREAM_BUFFERS);
}
else {
// Error opening file
nprintf(("SOUND", "SOUND => Failed to open wave file: %s\n\r", pszFilename));
fRtn = false;
}
}
else {
// Error, unable to create WaveFile object
nprintf(("Sound", "SOUND => Failed to create WaveFile object %s\n\r", pszFilename));
fRtn = false;
}
}
else {
// Error, passed invalid parms
fRtn = false;
}
ErrorExit:
if ( (fRtn == false) && (m_pwavefile) ) {
mprintf(("AUDIOSTR => ErrorExit for ::Create() on wave file: %s\n", pszFilename));
if (m_source_id)
OpenAL_ErrorPrint( alDeleteSources(1, &m_source_id) );
m_pwavefile->Close();
vm_free(m_pwavefile);
m_pwavefile = NULL;
}
return (fRtn);
}
// Destroy
bool AudioStream::Destroy (void)
{
bool fRtn = true;
ALint buffers_processed = 0;
ENTER_CRITICAL_SECTION(write_lock);
// Stop playback
Stop ();
OpenAL_ErrorPrint( alGetSourcei(m_source_id, AL_BUFFERS_PROCESSED, &buffers_processed) );
while (buffers_processed) {
ALuint buffer_id = 0;
OpenAL_ErrorPrint( alSourceUnqueueBuffers(m_source_id, 1, &buffer_id) );
buffers_processed--;
}
// Release sound sources and buffers
OpenAL_ErrorPrint( alDeleteSources(1, &m_source_id) );
OpenAL_ErrorPrint( alDeleteBuffers(MAX_STREAM_BUFFERS, m_buffer_ids) );
Snd_sram -= (m_cbBufSize * MAX_STREAM_BUFFERS);
// Delete WaveFile object
if (m_pwavefile) {
m_pwavefile->Close();
vm_free(m_pwavefile);
m_pwavefile = NULL;
}
status = ASF_FREE;
LEAVE_CRITICAL_SECTION(write_lock);
return fRtn;
}
// WriteWaveData
//
// Writes wave data to sound buffer. This is a helper method used by Create and
// ServiceBuffer; it's not exposed to users of the AudioStream class.
bool AudioStream::WriteWaveData (uint size, uint *num_bytes_written, int service)
{
bool fRtn = true;
ubyte *uncompressed_wave_data;
*num_bytes_written = 0;
if ( size == 0 || m_bReadingDone ) {
return fRtn;
}
if ( (m_buffer_ids[0] == 0) || !m_pwavefile ) {
return fRtn;
}
if ( service ) {
ENTER_CRITICAL_SECTION(Global_service_lock);
}
if ( service ) {
uncompressed_wave_data = Wavedata_service_buffer;
} else {
uncompressed_wave_data = Wavedata_load_buffer;
}
int num_bytes_read = 0;
if ( !service ) {
for (int ib = 0; ib < MAX_STREAM_BUFFERS; ib++) {
num_bytes_read = m_pwavefile->Read(uncompressed_wave_data, m_cbBufSize, service);
if (num_bytes_read < 0) {
m_bReadingDone = 1;
} else if (num_bytes_read > 0) {
OpenAL_ErrorCheck( alBufferData(m_buffer_ids[ib], m_pwavefile->GetALFormat(), uncompressed_wave_data, num_bytes_read, m_pwavefile->m_wfmt.nSamplesPerSec), { fRtn = false; goto ErrorExit; } );
OpenAL_ErrorCheck( alSourceQueueBuffers(m_source_id, 1, &m_buffer_ids[ib]), { fRtn = false; goto ErrorExit; } );
*num_bytes_written += num_bytes_read;
}
}
} else {
ALint buffers_processed = 0;
OpenAL_ErrorPrint( alGetSourcei(m_source_id, AL_BUFFERS_PROCESSED, &buffers_processed) );
while (buffers_processed) {
ALuint buffer_id = 0;
OpenAL_ErrorPrint( alSourceUnqueueBuffers(m_source_id, 1, &buffer_id) );
num_bytes_read = m_pwavefile->Read(uncompressed_wave_data, m_cbBufSize, service);
if (num_bytes_read < 0) {
m_bReadingDone = 1;
} else if (num_bytes_read > 0) {
OpenAL_ErrorPrint( alBufferData(buffer_id, m_pwavefile->GetALFormat(), uncompressed_wave_data, num_bytes_read, m_pwavefile->m_wfmt.nSamplesPerSec) );
OpenAL_ErrorPrint( alSourceQueueBuffers(m_source_id, 1, &buffer_id) );
*num_bytes_written += num_bytes_read;
}
buffers_processed--;
}
}
ErrorExit:
if ( service ) {
LEAVE_CRITICAL_SECTION(Global_service_lock);
}
return (fRtn);
}
// GetMaxWriteSize
//
// Helper function to calculate max size of sound buffer write operation, i.e. how much
// free space there is in buffer.
uint AudioStream::GetMaxWriteSize (void)
{
uint dwMaxSize = m_cbBufSize;
ALint n, q;
OpenAL_ErrorCheck( alGetSourcei(m_source_id, AL_BUFFERS_PROCESSED, &n), return 0 );
OpenAL_ErrorCheck( alGetSourcei(m_source_id, AL_BUFFERS_QUEUED, &q), return 0 );
if (!n && (q >= MAX_STREAM_BUFFERS)) //all buffers queued
dwMaxSize = 0;
// nprintf(("Alan","Max write size: %d\n", dwMaxSize));
return (dwMaxSize);
}
#define VOLUME_ATTENUATION_BEFORE_CUTOFF 0.03f
#define VOLUME_ATTENUATION 0.65f
bool AudioStream::ServiceBuffer (void)
{
float vol;
bool fRtn = true;
if ( status != ASF_USED )
return false;
ENTER_CRITICAL_SECTION( write_lock );
// status may have changed, so lets check once again
if ( status != ASF_USED ){
LEAVE_CRITICAL_SECTION( write_lock );
return false;
}
if ( m_bFade == true ) {
if ( m_lCutoffVolume == 0.0f ) {
vol = Get_Volume();
// nprintf(("Alan","Volume is: %d\n",vol));
m_lCutoffVolume = vol * VOLUME_ATTENUATION_BEFORE_CUTOFF;
}
vol = Get_Volume() * VOLUME_ATTENUATION;
// nprintf(("Alan","Volume is now: %d\n",vol));
Set_Volume(vol);
// nprintf(("Sound","SOUND => Volume for stream sound is %d\n",vol));
// nprintf(("Alan","Cuttoff Volume is: %d\n",m_lCutoffVolume));
if ( vol < m_lCutoffVolume ) {
m_bFade = false;
m_lCutoffVolume = 0.0f;
if ( m_bDestroy_when_faded == true ) {
LEAVE_CRITICAL_SECTION( write_lock );
Destroy();
// Reset reentrancy semaphore
return false;
} else {
Stop_and_Rewind();
// Reset reentrancy semaphore
LEAVE_CRITICAL_SECTION( write_lock );
return true;
}
}
}
// All of sound not played yet, send more data to buffer
uint dwFreeSpace = GetMaxWriteSize ();
// Determine free space in sound buffer
if (dwFreeSpace) {
// Some wave data remains, but not enough to fill free space
// Send wave data to buffer, fill remainder of free space with silence
uint num_bytes_written;
if (WriteWaveData (dwFreeSpace, &num_bytes_written) == true) {
// nprintf(("Alan","Num bytes written: %d\n", num_bytes_written));
if ( m_pwavefile->m_total_uncompressed_bytes_read >= m_pwavefile->m_max_uncompressed_bytes_to_read ) {
m_fade_timer_id = timer_get_milliseconds() + 1700; // start fading 1.7 seconds from now
m_finished_id = timer_get_milliseconds() + 2000; // 2 seconds left to play out buffer
m_pwavefile->m_max_uncompressed_bytes_to_read = AS_HIGHEST_MAX;
}
if ( (m_fade_timer_id>0) && ((uint)timer_get_milliseconds() > m_fade_timer_id) ) {
m_fade_timer_id = 0;
Fade_and_Stop();
}
if ( (m_finished_id>0) && ((uint)timer_get_milliseconds() > m_finished_id) ) {
m_finished_id = 0;
m_bPastLimit = true;
}
if ( PlaybackDone() ) {
if ( m_bDestroy_when_faded == true ) {
LEAVE_CRITICAL_SECTION( write_lock );
Destroy();
// Reset reentrancy semaphore
return false;
}
// All of sound has played, stop playback or loop again
if ( m_bLooping && !m_bFade) {
Play(m_lVolume, m_bLooping);
} else {
Stop_and_Rewind();
}
}
}
else {
// Error writing wave data
fRtn = false;
Int3();
}
}
LEAVE_CRITICAL_SECTION( write_lock );
return (fRtn);
}
// Cue
void AudioStream::Cue (void)
{
uint num_bytes_written;
if (!m_fCued) {
m_bFade = false;
m_fade_timer_id = 0;
m_finished_id = 0;
m_bPastLimit = false;
m_lVolume = 1.0f;
m_lCutoffVolume = 0.0f;
m_bDestroy_when_faded = false;
// Reset buffer ptr
m_cbBufOffset = 0;
// Reset file ptr, etc
m_pwavefile->Cue ();
// Unqueue all buffers
ALint buffers_processed = 0;
OpenAL_ErrorPrint( alGetSourcei(m_source_id, AL_BUFFERS_PROCESSED, &buffers_processed) );
while (buffers_processed) {
ALuint buffer_id = 0;
OpenAL_ErrorPrint( alSourceUnqueueBuffers(m_source_id, 1, &buffer_id) );
buffers_processed--;
}
// Fill buffer with wave data
WriteWaveData (m_cbBufSize, &num_bytes_written, 0);
m_fCued = true;
}
}
// Play
void AudioStream::Play (float volume, int looping)
{
if (m_buffer_ids[0] != 0) {
// If playing, stop
if (m_fPlaying) {
if ( m_bIsPaused == false)
Stop_and_Rewind();
}
// Cue for playback if necessary
if ( !m_fCued )
Cue ();
if ( looping )
m_bLooping = 1;
else
m_bLooping = 0;
OpenAL_ErrorPrint( alSourcePlay(m_source_id) );
m_nTimeStarted = timer_get_milliseconds();
Set_Volume(volume);
// Kick off timer to service buffer
m_timer.constructor();
m_timer.Create (m_nBufService, m_nBufService, ptr_u (this), TimerCallback);
// Playback begun, no longer cued
m_fPlaying = true;
m_bIsPaused = false;
}
}
// Timer callback for Timer object created by ::Play method.
bool AudioStream::TimerCallback (ptr_u dwUser)
{
// dwUser contains ptr to AudioStream object
AudioStream * pas = (AudioStream *) dwUser;
return (pas->ServiceBuffer ());
}
void AudioStream::Set_Sample_Cutoff(unsigned int sample_cutoff)
{
if ( m_pwavefile == NULL )
return;
m_pwavefile->m_max_uncompressed_bytes_to_read = ((sample_cutoff * m_pwavefile->m_wfmt.wBitsPerSample) / 8);
}
uint AudioStream::Get_Samples_Committed(void)
{
if ( m_pwavefile == NULL )
return 0;
return ((m_pwavefile->m_total_uncompressed_bytes_read * 8) / m_pwavefile->m_wfmt.wBitsPerSample);
}
/** Have stream fade out and be destroyed when inaudabile.
If stream is already done or never started just destroy it now.
*/
void AudioStream::Fade_and_Destroy (void)
{
if (!m_fPlaying || PlaybackDone())
{
Destroy();
}
else
{
m_bFade = true;
m_bDestroy_when_faded = true;
}
}
// Fade_and_Destroy
void AudioStream::Fade_and_Stop (void)
{
m_bFade = true;
m_bDestroy_when_faded = false;
}
// Stop
void AudioStream::Stop(int paused)
{
if (m_fPlaying) {
if (paused) {
OpenAL_ErrorPrint( alSourcePause(m_source_id) );
} else {
OpenAL_ErrorPrint( alSourceStop(m_source_id) );
}
m_fPlaying = false;
m_bIsPaused = (paused != 0);
// Delete Timer object
m_timer.destructor();
}
}
// Stop_and_Rewind
void AudioStream::Stop_and_Rewind (void)
{
if (m_fPlaying) {
// Stop playback
OpenAL_ErrorPrint( alSourceStop(m_source_id) );
// Delete Timer object
m_timer.destructor();
m_fPlaying = false;
m_bIsPaused = false;
}
// Unqueue all buffers
ALint buffers_processed = 0;
OpenAL_ErrorPrint( alGetSourcei(m_source_id, AL_BUFFERS_PROCESSED, &buffers_processed) );
while (buffers_processed) {
ALuint buffer_id = 0;
OpenAL_ErrorPrint( alSourceUnqueueBuffers(m_source_id, 1, &buffer_id) );
buffers_processed--;
}
m_fCued = false; // this will cause wave file to start from beginning
m_bReadingDone = false;
}
// Set_Volume
void AudioStream::Set_Volume(float vol)
{
CAP(vol, 0.0f, 1.0f);
OpenAL_ErrorPrint( alSourcef(m_source_id, AL_GAIN, vol) );
m_lVolume = vol;
}
// Set_Volume
float AudioStream::Get_Volume()
{
return m_lVolume;
}
bool AudioStream::PlaybackDone()
{
ALint state = 0;
OpenAL_ErrorPrint( alGetSourcei(m_source_id, AL_SOURCE_STATE, &state) );
if (m_bReadingDone && (state != AL_PLAYING))
return true;
else
return false;
}
AudioStream Audio_streams[MAX_AUDIO_STREAMS];
void audiostream_init()
{
int i;
if ( Audiostream_inited == 1 )
return;
// Allocate memory for the buffer which holds the uncompressed wave data that is streamed from the
// disk during a load/cue
if ( Wavedata_load_buffer == NULL ) {
Wavedata_load_buffer = (ubyte*)vm_malloc(BIGBUF_SIZE);
Assert(Wavedata_load_buffer != NULL);
}
// Allocate memory for the buffer which holds the uncompressed wave data that is streamed from the
// disk during a service interval
if ( Wavedata_service_buffer == NULL ) {
Wavedata_service_buffer = (ubyte*)vm_malloc(BIGBUF_SIZE);
Assert(Wavedata_service_buffer != NULL);
}
// Allocate memory for the buffer which holds the compressed wave data that is read from the hard disk
if ( Compressed_buffer == NULL ) {
Compressed_buffer = (ubyte*)vm_malloc(COMPRESSED_BUFFER_SIZE);
Assert(Compressed_buffer != NULL);
}
if ( Compressed_service_buffer == NULL ) {
Compressed_service_buffer = (ubyte*)vm_malloc(COMPRESSED_BUFFER_SIZE);
Assert(Compressed_service_buffer != NULL);
}
for ( i = 0; i < MAX_AUDIO_STREAMS; i++ ) {
Audio_streams[i].Init_Data();
Audio_streams[i].status = ASF_FREE;
Audio_streams[i].type = ASF_NONE;
}
#ifdef SCP_UNIX
SDL_InitSubSystem(SDL_INIT_TIMER);
#endif
INITIALIZE_CRITICAL_SECTION( Global_service_lock );
Audiostream_inited = 1;
}
// Close down the audiostream system. Must call audiostream_init() before any audiostream functions can
// be used.
void audiostream_close()
{
if ( Audiostream_inited == 0 )
return;
int i;
for ( i = 0; i < MAX_AUDIO_STREAMS; i++ ) {
if ( Audio_streams[i].status == ASF_USED ) {
Audio_streams[i].status = ASF_FREE;
Audio_streams[i].Destroy();
}
}
// free global buffers
if ( Wavedata_load_buffer ) {
vm_free(Wavedata_load_buffer);
Wavedata_load_buffer = NULL;
}
if ( Wavedata_service_buffer ) {
vm_free(Wavedata_service_buffer);
Wavedata_service_buffer = NULL;
}
if ( Compressed_buffer ) {
vm_free(Compressed_buffer);
Compressed_buffer = NULL;
}
if ( Compressed_service_buffer ) {
vm_free(Compressed_service_buffer);
Compressed_service_buffer = NULL;
}
DELETE_CRITICAL_SECTION( Global_service_lock );
Audiostream_inited = 0;
}
// Open a digital sound file for streaming
//
// input: filename => disk filename of sound file
// type => what type of audio stream do we want to open:
// ASF_SOUNDFX
// ASF_EVENTMUSIC
// ASF_MENUMUSIC
// ASF_VOICE
//
// returns: success => handle to identify streaming sound
// failure => -1
int audiostream_open( char *filename, int type )
{
int i, rc;
char fname[MAX_FILENAME_LEN];
if ( !Audiostream_inited || !snd_is_inited() )
return -1;
for (i = 0; i < MAX_AUDIO_STREAMS; i++) {
if (Audio_streams[i].status == ASF_FREE) {
Audio_streams[i].status = ASF_USED;
Audio_streams[i].type = type;
break;
}
}
if (i == MAX_AUDIO_STREAMS) {
nprintf(("Sound", "SOUND => No more audio streams available!\n"));
return -1;
}
// copy filename, since we might modify it
strcpy_s(fname, filename);
// we always uncompress to 16 bits
Audio_streams[i].m_bits_per_sample_uncompressed = 16;
switch (type)
{
case ASF_VOICE:
case ASF_SOUNDFX:
case ASF_MENUMUSIC:
{
// go ahead and strip off file extension
char *p = strrchr(fname, '.');
if ( p && (strlen(p) > 2) )
(*p) = 0;
break;
}
case ASF_EVENTMUSIC:
break;
default:
Int3();
return -1;
}
rc = Audio_streams[i].Create(fname);
if ( rc == 0 ) {
Audio_streams[i].status = ASF_FREE;
return -1;
} else {
return i;
}
}
void audiostream_close_file(int i, int fade)
{
if (!Audiostream_inited)
return;
if ( i == -1 )
return;
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
if ( Audio_streams[i].status == ASF_USED ) {
if ( fade )
Audio_streams[i].Fade_and_Destroy();
else
Audio_streams[i].Destroy();
}
}
void audiostream_close_all(int fade)
{
int i;
for ( i = 0; i < MAX_AUDIO_STREAMS; i++ ) {
if ( Audio_streams[i].status == ASF_FREE )
continue;
audiostream_close_file(i, fade);
}
}
void audiostream_play(int i, float volume, int looping)
{
if (!Audiostream_inited)
return;
if ( i == -1 )
return;
Assert(looping >= 0);
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
if (volume == -1.0f) {
volume = Audio_streams[i].Get_Default_Volume();
}
Assert(volume >= 0.0f && volume <= 1.0f );
CAP(volume, 0.0f, 1.0f);
Assert( Audio_streams[i].status == ASF_USED );
Audio_streams[i].Set_Default_Volume(volume);
Audio_streams[i].Play(volume, looping);
}
// use as buffer service function
int audiostream_is_playing(int i)
{
if ( i == -1 )
return 0;
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
if ( Audio_streams[i].status != ASF_USED )
return 0;
return (int)Audio_streams[i].Is_Playing();
}
void audiostream_stop(int i, int rewind, int paused)
{
if (!Audiostream_inited)
return;
if ( i == -1 )
return;
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
Assert( Audio_streams[i].status == ASF_USED );
if ( rewind )
Audio_streams[i].Stop_and_Rewind();
else
Audio_streams[i].Stop(paused);
}
void audiostream_set_volume_all(float volume, int type)
{
int i;
for ( i = 0; i < MAX_AUDIO_STREAMS; i++ ) {
if ( Audio_streams[i].status == ASF_FREE )
continue;
if ( (Audio_streams[i].type == type) || ((Audio_streams[i].type == ASF_MENUMUSIC) && (type == ASF_EVENTMUSIC)) ) {
Audio_streams[i].Set_Volume(volume);
}
}
}
void audiostream_set_volume(int i, float volume)
{
if ( i == -1 )
return;
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
Assert( volume >= 0.0f && volume <= 1.0f);
if ( Audio_streams[i].status == ASF_FREE )
return;
Audio_streams[i].Set_Volume(volume);
}
int audiostream_is_paused(int i)
{
if ( i == -1 )
return 0;
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
if ( Audio_streams[i].status == ASF_FREE )
return -1;
return (int) Audio_streams[i].Is_Paused();
}
void audiostream_set_sample_cutoff(int i, uint cutoff)
{
if ( i == -1 )
return;
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
Assert( cutoff > 0 );
if ( Audio_streams[i].status == ASF_FREE )
return;
Audio_streams[i].Set_Sample_Cutoff(cutoff);
}
uint audiostream_get_samples_committed(int i)
{
if ( i == -1 )
return 0;
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
if ( Audio_streams[i].status == ASF_FREE )
return 0;
return Audio_streams[i].Get_Samples_Committed();
}
int audiostream_done_reading(int i)
{
if ( i == -1 )
return 0;
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
if ( Audio_streams[i].status == ASF_FREE )
return 0;
return Audio_streams[i].Is_Past_Limit();
}
int audiostream_is_inited()
{
return Audiostream_inited;
}
void audiostream_pause(int i)
{
if ( i == -1 )
return;
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
if ( Audio_streams[i].status == ASF_FREE )
return;
if ( audiostream_is_playing(i) == (int)true )
audiostream_stop(i, 0, 1);
}
void audiostream_pause_all()
{
int i;
for ( i = 0; i < MAX_AUDIO_STREAMS; i++ ) {
if ( Audio_streams[i].status == ASF_FREE )
continue;
audiostream_pause(i);
}
}
void audiostream_unpause(int i)
{
if ( i == -1 )
return;
Assert( i >= 0 && i < MAX_AUDIO_STREAMS );
if ( Audio_streams[i].status == ASF_FREE )
return;
if ( audiostream_is_paused(i) == (int)true ) {
audiostream_play(i, Audio_streams[i].Get_Volume(), Audio_streams[i].Is_looping());
}
}
void audiostream_unpause_all()
{
int i;
for ( i = 0; i < MAX_AUDIO_STREAMS; i++ ) {
if ( Audio_streams[i].status == ASF_FREE )
continue;
audiostream_unpause(i);
}
}
|