player.c 39.9 KB
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

/*************************************************************

  player.c : Nintendo 64 Music Tools Programmers Library
  (c) Copyright 1997/1998, Software Creations (Holdings) Ltd.

  Version 3.14

  Music player source file.

**************************************************************/

/* include current configuration settings */
#include "libmus_config.h"

/* include system headers */
#include <ultra64.h>
#ifndef SUPPORT_NAUDIO
  #include <libaudio.h>
#else
  #include <n_libaudio_sc.h>
  #include <n_libaudio_sn_sc.h>
#endif

/* include other header files */
#include "libmus.h"
#include "lib_memory.h"
#include "aud_sched.h"
#include "aud_thread.h"

/* include current header files */
#include "player.h"
#include "player_fifo.h"
#ifdef SUPPORT_FXCHANGE
  #include "player_fx.h"
#endif


/* define note data */
#define REST		   96	/* c8 = rest				*/
#define BASEOFFSET	48	/* c4 = sample base note default	*/

/* convert unsigned char values to floats */
#define U8_TO_FLOAT(c) ((c)&128) ? -(256-(c)) : (c)


/* internal function prototypes */
static ALMicroTime __MusIntMain			(void *node);
static void __MusIntProcessContinuousVolume	(channel_t *cp);
static void __MusIntProcessContinuousPitchBend	(channel_t *cp);
static void __MusIntGetNewNote			(channel_t *cp, int x);
static void __MusIntFlushPending		(channel_t *cp, int x);
static void __MusIntSetVolumeAndPan		(channel_t *cp, int x);
static void __MusIntSetPitch			(channel_t *cp, int x, float offset);
static void __MusIntInitEnvelope		(channel_t *cp);
static void __MusIntProcessEnvelope		(channel_t *cp);
static void __MusIntInitSweep			(channel_t *cp);
static void __MusIntProcessSweep		(channel_t *cp);
static float __MusIntProcessVibrato		(channel_t *cp);
static float __MusIntProcessWobble		(channel_t *cp);

/* Internal utility functions... */
static void __MusIntInitialiseChannel		(channel_t *cp);
static void __MusIntRemapPtrBank		(char *pptr, char *wptr);
static void __MusIntHandleSetFlag		(unsigned long handle, unsigned long clear, unsigned long set);

static float __MusIntPowerOf2			(float x);
static int  __MusIntRandom			(int range);
static int __MusIntFindChannel                  (song_t *addr, int song_chan);
static unsigned long __MusIntStartEffect(channel_t *cp, fx_header_t *header, int number, int volume, int pan, int priority);
static unsigned long __MusIntFindChannelAndStart(fx_header_t *header, int number, int volume, int pan, int priority);

static void __MusIntRemapPtrs			(void *addr, void *offset, int count);
static musHandle	__MusIntStartSong	(void *addr);



/* internal workspace */
static ALPlayer        plr_player;                /* synthesizer player        */
static int             max_channels;              /* number of channels        */
static ALVoice         *mus_voices;               /* audio library voices      */
static channel_t       *mus_channels;             /* music player channels     */
static channel_t       *mus_channels2;            /* music player channels (past songs) */
static int             mus_vsyncs_per_second;     /* video refresh rate        */
static ALMicroTime     mus_next_frame_time;	  /* time until next frame     */
static unsigned short  mus_master_volume_effects; /* sound effect master value */
static unsigned short  mus_master_volume_songs;   /* song master volume        */
static unsigned long   mus_current_handle;        /* current handle number     */
static long            mus_random_seed;           /* random number seed value  */
static ptr_bank_t      *mus_init_bank;		  /* sample bank to initialise */
static ptr_bank_t      *mus_default_bank;	  /* sample bank default       */
static musBool       mus_songfxchange_flag;	  /* can songs set the FX type */
static int	       mus_last_fxtype;		  /* last FX type set          */

static fx_header_t      *libmus_fxheader_current;  /* address of current FX bank */
static fx_header_t      *libmus_fxheader_single;  /* address of current FX bank */

static LIBMUScb_marker	marker_callback;			/* marker callback function */

/* global workspace */
unsigned long __muscontrol_flag;                /* music player control flag */
#ifdef SUPPORT_PROFILER
unsigned long _mus_cpu_last = 0;                /* driver CPU usage for last frame */
unsigned long _mus_cpu_worst = 0;               /* driver CPU usage for worst case */
#endif


/* C files included directly (to avoid lots of global variables in the library)*/
/* these files are separated just for readability                              */
#include "player_commands.c"
#include "player_api.c"
#include "player_fifo.c"

/* C files for SC effect extensions */
#ifdef SUPPORT_EFFECTS
  #include "player_effects.c"
#endif


/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [EXTERNAL FUNCTION]
  __MusExtPlayerDelete(player)

  [Parameters]
  player	address of player structure

  [Explanation]
  Called by synthesis driver to remove the music player. This should never be
  called!

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

#if 0 /* never called */
void __MusExtPlayerDelete(ALPlayer *player)
{
  alSynRemovePlayer(&__libmus_alglobals.drvr, player);
  player->handler = NULL;
}
#endif

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [EXTERNAL FUNCTION]
  __MusIntMain(node)

  [Parameters]
  node		ignored

  [Explanation]
  Called by synthesis driver to generate hardware output, this is the music
  players main loop.

  [Return value]
  amount of time before next callback
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static ALMicroTime __MusIntMain(void *node)
{
  int	x;
  channel_t *cp;
#ifdef SUPPORT_PROFILER
  unsigned long start=osGetCount();
#endif

  /* process any fifo commands */
  __MusIntFifoProcess();

  for(x=-MAX_SONGS, cp=mus_channels; x<max_channels-MAX_SONGS; x++, cp++)
  {
    if(cp->pdata==NULL || (cp->channel_flag&CHFLAG_PAUSE))
      continue;

    if (cp->pending)
      __MusIntFlushPending(cp,x);

    cp->channel_frame+=cp->channel_tempo;
    /* process until note or stop for this frame is found */
    if(cp->length != 0x7fff)
    {
      while (((long)(cp->note_end_frame-cp->channel_frame))<0 && cp->pdata!=NULL)
         __MusIntGetNewNote(cp, x);
      /* cancel processing if channel stopped */
      if(!cp->pdata)
         continue;
    }
    /* process volume and pitchbend continous data streams */
    if(cp->pvolume && ((long)(cp->volume_frame-cp->channel_frame))<0)
      __MusIntProcessContinuousVolume(cp);
    if(cp->ppitchbend && ((long)(cp->pitchbend_frame-cp->channel_frame))<0)
      __MusIntProcessContinuousPitchBend(cp);

    /* process fade down and stop API command */
    if (cp->stopping != -1)
    {
      cp->stopping--;
      if (cp->stopping==-1)
      {
         cp->pdata = Fstop(cp, NULL);      
         if(cp->playing)
         {
            cp->playing = 0;
            alSynStopVoice(&__libmus_alglobals.drvr, mus_voices+x);
         }
      }
    }

    /* process current note to generate sound */
    if(cp->playing)
    {
      float total;
      
      if(cp->env_phase)
        __MusIntProcessEnvelope(cp);
      if(cp->sweep_speed && ((long)(cp->sweep_frame-cp->channel_frame))<0)
        __MusIntProcessSweep(cp);

      total = cp->freqoffset;
#ifdef SUPPORT_EFFECTS
      if (cp->vib_speed || cp->specialvib_speed)
#else
      if (cp->vib_speed)
#endif
	total += __MusIntProcessVibrato(cp);
      if (cp->wobble_on_speed)
	total += __MusIntProcessWobble(cp);
      if (!cp->pending)
      {
	__MusIntSetPitch(cp, x, total);
	__MusIntSetVolumeAndPan(cp, x);
      }
    }
    /* increment channel counters */
    cp->count= (cp->channel_frame-cp->note_start_frame)>>8;
  }

#ifdef SUPPORT_PROFILER
  _mus_cpu_last = osGetCount()-start;
  if (_mus_cpu_last>_mus_cpu_worst)
    _mus_cpu_worst = _mus_cpu_last;
#endif
  
  /* set to call back next video frame */
  return (mus_next_frame_time);
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntGetNewNote(cp,x)

  [Parameters]
  cp		address of music player channel
  x		channel number

  [Explanation]
  Get the next note from the sound data, processing any commands before a note is
  found.

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntGetNewNote(channel_t *cp,  int x)
{
  unsigned char *ptr;
  unsigned char command;

  ptr = cp->pdata;
  while(ptr && (command=*ptr)>127)
  {
#ifdef _AUDIODEBUG
    if(command >= Clast)
    {
      osSyncPrintf("PLAYER.C: Channel %d is corrupt (command=%02x)\n",x,command);
      cp->pdata = NULL;
      break;
    }    
#endif
    /* Execute the relevant code for the token.  */
    ptr = (jumptable[command&0x7f].func)(cp, ptr+1);
  }
  cp->pdata = ptr;

  /* new note */
  if(ptr)
  {
    int note;

    cp->last_note = cp->port_base;
    note = *(cp->pdata++);

    if(cp->velocity_on)
    {
        /* modified 98.12.15 TW */
        /* rests' velocities are not now stored, allowing previous notes to release or whatever */
        /* this was only a problem if the first note in the loop was a rest, */
        /* and the last note was a quiet note using low velocity */
        u8 vel = *cp->pdata++;
        if(vel >= 0x80)
        {
            vel &= 0x7F;
            cp->velocity_on = 0;
            cp->default_velocity = vel;
        }

        if(note != REST)
            cp->velocity = vel;
    }
    else
      cp->velocity = cp->default_velocity;

    if (cp->fixed_length)
    {
      if (!cp->ignore)
	cp->length = cp->fixed_length;
      else
      {
	cp->ignore = 0;
	command = *(cp->pdata++);
	if (command < 128)
	  cp->length = command;
	else
	  cp->length = ((int)(command&0x7f)<<8)+*(cp->pdata++);
      }
    }
    else
    {
      command = *(cp->pdata++);
      if(command < 128)
	cp->length = command;
      else
	cp->length = ((int)(command&0x7f)<<8)+*(cp->pdata++);
    }

    /* set length and timer */
    cp->note_start_frame = cp->note_end_frame;
    cp->note_end_frame += cp->length*256;
    cp->count = 0;
    /* initialise wobble */
    cp->wobble_count = cp->wobble_off_speed;
    cp->wobble_current = 0;


   /* check to see if wave is valid */
   if (cp->song_addr && !cp->pdrums)
   {
      if (cp->song_addr->wave_table[cp->wave]==0xffff)
         note = REST;
   }

    if (note!=REST)
    {
      int wave;
      ptr_bank_t *bank;

      /* get current sample bank */
      bank = cp->sample_bank;

      /* check for drums */
      if(cp->pdrums != NULL)
      {
         cp->wave = cp->pdrums[note].wave;
         cp->pan  = cp->pdrums[note].pan/2;
         (void) Fdefa(cp, &cp->song_addr->env_table[cp->pdrums[note].adsr*7]);
         note     = cp->pdrums[note].pitch;
      }


      /* initialise envelope */
      if(!cp->env_trigger_off)
	__MusIntInitEnvelope(cp);

      /* initialise sweep */
      if (cp->sweep_speed)
	__MusIntInitSweep(cp);

      /* get current wave number */
      wave = cp->wave;

      if (cp->song_addr)
         wave = cp->song_addr->wave_table[wave];
      else
         wave = cp->fx_addr->wave_table[wave];

#ifdef _AUDIODEBUG
      /* validate wave number with sample bank */
      if (wave>=bank->count)
      {
	osSyncPrintf("PLAYER.C: Wave number overflow!\n");
        wave = 0;
      }
#endif

      /* start relevant sample if required */
      if(!cp->trigger_off)
      {
	ALWaveTable *wave_addr;

	wave_addr = bank->wave_list[wave];
#ifdef SUPPORT_WAVEMONITORING
	wave_addr->flags++; /* flags isn't needed by ALWaveTable honest! */
#endif
	cp->pending = wave_addr;
	if (cp->playing && cp->old_volume)
	{
	  cp->old_volume = 0;
	  alSynSetVol(&__libmus_alglobals.drvr, mus_voices+x, 0, mus_next_frame_time);
	}
	else
	  __MusIntFlushPending(cp,x);
      }
      cp->base_note = (float)note+bank->detune[wave];
      command = cp->transpose*(1-cp->ignore_transpose);
      cp->base_note += (float)U8_TO_FLOAT(command);

      /* set reverb level if required */
      if (cp->reverb!=cp->old_reverb)
      {
	unsigned char work;

	work = cp->reverb_base;
	work += ((128-work)*cp->reverb)>>7;
	cp->old_reverb = cp->reverb;
	alSynSetFXMix(&__libmus_alglobals.drvr, mus_voices+x, work);
      }
    }
    else
    {
      /* rest allows previous notes release to finish */
      if (cp->env_phase<4)
      {
	cp->env_phase = 4; /* Start Release */
	cp->release_frame = cp->channel_frame;
	cp->env_count=1;
	cp->release_start_vol = cp->env_current;
      }
    }
  }
  else	/* must have hit a Cstop so stop its voice */
  {
    if(cp->playing)
    {
      cp->playing = 0;
      alSynSetVol(&__libmus_alglobals.drvr, mus_voices+x, 0, mus_next_frame_time);
      alSynStopVoice(&__libmus_alglobals.drvr, mus_voices+x);
    }
  }
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntFlushPending(cp,x)

  [Parameters]
  cp		address of music player channel
  x		channel number

  [Explanation]
  Start the sample waiting to play and, if necessary, stop the previous one.

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntFlushPending(channel_t *cp, int x)
{
  if (cp->playing)
    alSynStopVoice(&__libmus_alglobals.drvr, mus_voices+x);
  cp->playing = 1;
  /* start sample */
  alSynStartVoice(&__libmus_alglobals.drvr, mus_voices+x, cp->pending);
  cp->pending = NULL;
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntSetVolumeAndPan(cp,x)

  [Parameters]
  cp		address of music player channel
  x		channel number

  [Explanation]
  Output the volume level and pan position of the current channel to the hardware 
  (if necessary).

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntSetVolumeAndPan(channel_t *cp, int x)
{
  u32	volume;

  /* process volume */
  volume = ((u32)(cp->volume)*(u32)(cp->env_current)*(u32)(cp->velocity)*(u32)(cp->volscale))>>13;
  if (volume>32767)
    volume = 32767;


   if (!cp->fx_addr)
    volume *= mus_master_volume_songs;
  else
    volume *= mus_master_volume_effects;
  volume >>= 15;
  if (cp->stopping != -1)
    volume = (volume*cp->stopping)/cp->stopping_speed;

  if (volume!=cp->old_volume)
  {
    cp->old_volume = volume;
    alSynSetVol(&__libmus_alglobals.drvr, mus_voices+x, volume, mus_next_frame_time);

  }

  /* process pan */
  volume = ((cp->pan*cp->panscale)>>7)&0x7f;
  if (volume!=cp->old_pan)
  {
    cp->old_pan = volume;
    alSynSetPan(&__libmus_alglobals.drvr, mus_voices+x, volume);
  }
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntSetPitch(cp,x)

  [Parameters]
  cp		address of music player channel
  x		channel number

  [Explanation]
  Output the frequency of the current channel to the hardware (if necessary).

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntSetPitch(channel_t *cp, int x, float offset)
{
  float   frequency, temp;

  /* base frequency */
  frequency = cp->base_note;

  /* incorporate portamento */
  if(cp->port != 0)	
  {
    if(cp->count <= cp->port)
    {
      temp = (frequency - cp->last_note)/(float)(cp->port);
      temp *= (float)cp->count;
      frequency = cp->last_note + temp;
    }
    cp->port_base = frequency;
  }  

  /* incorporate offsets */
  frequency += offset+cp->pitchbend_precalc;

  /* only output it if it's changed! */
  if (frequency==cp->old_frequency)
    return;
  cp->old_frequency = frequency;  
  frequency = __MusIntPowerOf2(frequency*(1.0/12.0));
#ifdef _AUDIODEBUG
  if(frequency <= 0)
  {
    osSyncPrintf("PLAYER.C: frequency underflow.\n");
    frequency= 1.0;  
  }
#endif
  if(frequency > 2.0)
  {
#ifdef _AUDIODEBUG
    osSyncPrintf("PLAYER.C: frequency overflow (note silenced).\n");
#endif
    frequency = 2.0;
    cp->velocity = 0;    
  }  
  alSynSetPitch(&__libmus_alglobals.drvr, mus_voices+x, frequency);
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntInitEnvelope(cp)

  [Parameters]
  cp		address of music player channel

  [Explanation]
  Initialise the envelope settings.

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntInitEnvelope(channel_t *cp)
{   
  if(cp->length != 0x7fff)
  {
    if(cp->cutoff != 0) /* release time is from start of note */
      cp->release_frame = cp->note_start_frame + (cp->cutoff<<8);
    else		/* release time is from end of note */
      cp->release_frame = cp->note_end_frame - (cp->endit<<8);
  }
  else
  {
    cp->release_frame = cp->note_start_frame+0x7fffffff; /* release tomorrow please! */
  }    
  cp->env_current = cp->env_init_vol;
  cp->env_count = cp->env_speed;
  cp->env_phase = 1;
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntProcessEnvelope(cp)

  [Parameters]
  cp		address of music player channel

  [Explanation]
  If necessary process the envelope settings to calculate the current value.

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntProcessEnvelope(channel_t *cp)
{
  int env_phase_count;
 
  if(((long)(cp->release_frame-cp->channel_frame))<0 && cp->env_phase<4)
  {
    /* Start Release */
    cp->env_phase = 4;
    cp->env_count=1;
    cp->release_start_vol = cp->env_current;
  }

  /* 99.01.29 - Removed this decrement and check of env_count - TW */
  /* It looks like this should have been remived at the time env_speed_calc was introduced */
  /* assuming it works ok, env_count can be removed from the channel structure */
  /* cp->env_count--; */
  /* if(!cp->env_count) */
  {
    cp->env_count = cp->env_speed;

    switch(cp->env_phase)
    {
	case 1:
	  {
	    /* Attack */
            env_phase_count = (((cp->channel_frame - cp->note_start_frame)>>8)*cp->env_speed_calc)>>10;
	    if (env_phase_count<cp->env_attack_speed)
	    {
	      cp->env_current = (int)cp->env_init_vol+(int)((float)(cp->env_attack_calc*(float)env_phase_count));
	      return;
	    }
	    else
	    {
	      cp->env_phase++;
	      cp->env_current = cp->env_max_vol;
	      return;
	    }
	  }
	case 2:
	  {
	    /* Decay */
	    env_phase_count = ((((cp->channel_frame - cp->note_start_frame)>>8) - cp->env_attack_speed)*cp->env_speed_calc)>>10;
	    if (env_phase_count<cp->env_decay_speed)
	    {
	      cp->env_current = (int)cp->env_max_vol+(int)((float)(cp->env_decay_calc*(float)env_phase_count));
	      return;
	    }
	    else
	    {
	      cp->env_phase++;
	      cp->env_current = cp->env_sustain_vol;
	      return;
	    }
	  }
	case 3:
	  {
	    /* Sustain */
	    return;
	  }
	case 4:
	  {
	    /* Do Release */
            env_phase_count = (((cp->channel_frame - cp->release_frame)>>8)*cp->env_speed_calc)>>10;
	    if (env_phase_count < cp->env_release_speed)
	    {
	      cp->env_current = (int)cp->release_start_vol-(int)((float)(cp->env_release_calc*(float)env_phase_count*(float)cp->release_start_vol));
	      return;
	    }
	    else
	    {
	      cp->env_phase++;
	      cp->env_current = 0;
	      return;
	    }
	  }
    }	
  }
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntInitSweep(cp)

  [Parameters]
  cp		address of music player channel

  [Explanation]
  Initialise settings for sweep pan processing.

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntInitSweep(channel_t *cp)
{
  cp->sweep_frame = cp->note_start_frame;
  cp->sweep_timer = 0;
  cp->sweep_dir = cp->pan&0x40;
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntProcessSweep(cp)

  [Parameters]
  cp		address of music player channel

  [Explanation]
  Process the current sweep settings to move the pan position.

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

void __MusIntProcessSweep(channel_t *cp)
{
  unsigned long calc;

  do
  {
    cp->sweep_frame += 256;
    calc = cp->sweep_timer+cp->sweep_speed;
    if (calc<64)
    {
      cp->sweep_timer=calc;
      continue;
    }
    cp->sweep_timer=calc&63;
    calc>>=6;
    if (!cp->sweep_dir)
    {
      cp->pan += calc;
      if (cp->pan>0x7f)
      {
	cp->pan=0x7f;
	cp->sweep_dir = 1;
      }
    }
    else
    {
      cp->pan -= calc;
      if (cp->pan>=0x80 || cp->pan==0)
      {
	cp->pan=0;
	cp->sweep_dir = 0;
      }    
    }
  } while ((long)(cp->sweep_frame-cp->channel_frame)<0);
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntProcessWobble(cp)

  [Parameters]
  cp		address of music player channel

  [Explanation]
  Process the wobble settings to calculate the current value.

  [Return value]
  Current wobble offset
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static float __MusIntProcessWobble(channel_t *cp)
{
  cp->wobble_count--;
  if(!cp->wobble_count)
  {
    if(cp->wobble_current==0)
    {
      cp->wobble_current=cp->wobble_amount;
      cp->wobble_count=cp->wobble_on_speed;
    }
    else
    {
      cp->wobble_current=0;
      cp->wobble_count=cp->wobble_off_speed;
    }
  }
  return ((float)cp->wobble_current);
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntProcessVibrato(cp)

  [Parameters]
  cp		address of music player channel

  [Explanation]
  Process the vibrato settings to calculate the current value.

  [Return value]
  Current vibrato offset
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static float __MusIntProcessVibrato (channel_t *cp)
{
  int temp;
  float temp1;

#ifdef SUPPORT_EFFECTS
  if (cp->specialvib_speed)
  {
    if((temp = cp->count-cp->specialvib_delay) > 0)
	{
      temp1 = (sinf( (float) temp/cp->specialvib_speed*2*3.1415926)*cp->specialvib_amount);
      cp->vibrato = temp1;
    }    
	 else
	{
		return (0);
	}
  }
  else
  {
#endif

  temp = cp->count-cp->vib_delay ;
  if(temp > 0)
  {
    temp1 = sinf( (float) temp*cp->vib_precalc)*cp->vib_amount;
    cp->vibrato = temp1;
  }
  else
	{
		return (0);
	}
#ifdef SUPPORT_EFFECTS
  }
#endif
  return (cp->vibrato);
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntProcessContinuousVolume(cp)

  [Parameters]
  cp		address of music player channel

  [Explanation]
  Process the continuous RLE volume data to set the current value.

  ------------------------
  Current RLE data format:
  ------------------------
  If the top bit of the value is set then the value is to be repeated and the count
  byte follows. If the top bit of the count byte is set then it represents the top
  seven bits of the count and the following byte is the lower eight bits. The count
  is stored with two subtracted from it (0=2, 1=3 etc.etc.) because it is not worth
  compressing runs of less than two. The processing of this data can be show as
  follows:

       if count = 0
          byte = next byte from data stream
          if byte>128
             byte = byte & 127
             count = next byte from data stream
             if count>128
                count = count & 127
                count = count * 256
                count = count + next byte from the data stream
             endif
             count = count + 2
          endif
       else
          count = count - 1
       endif

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntProcessContinuousVolume(channel_t *cp)
{
  unsigned char work_vol;

  do
  {    
    cp->volume_frame += 256;
    cp->cont_vol_repeat_count--;
    if(cp->cont_vol_repeat_count == 0)   /* already repeating? */
    {
      work_vol = *(cp->pvolume++);
      if(work_vol > 127)		    /* does count follow? */
      {
	/* yes  volume is followed by run length data */
#ifdef SUPPORT_EFFECTS
	cp->last_volume = 
#endif
	cp->volume = work_vol &0x7f;
	work_vol = *(cp->pvolume++);
	if(work_vol > 127)
	{
	  cp->cont_vol_repeat_count = ((int)(work_vol&0x7f)*256);
	  cp->cont_vol_repeat_count += (int)*(cp->pvolume++)+2;
	}
	else
	  cp->cont_vol_repeat_count = (int)work_vol+2;
      }
      else
      {
#ifdef SUPPORT_EFFECTS
	cp->last_volume = 
#endif
	cp->volume = work_vol;
	cp->cont_vol_repeat_count=1;
      }
    }
  } while ((long)(cp->volume_frame-cp->channel_frame)<0);

#ifdef SUPPORT_EFFECTS
  __MusIntSpecialVol(cp);
#endif
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntProcessContinuousPitchBend(cp)

  [Parameters]
  cp		address of music player channel

  [Explanation]
  Process the continuous RLE pitchbend data to set the current value.

  ------------------------
  Current RLE data format:
  ------------------------
  If the top bit of the value is set then the value is to be repeated and the count
  byte follows. If the top bit of the count byte is set then it represents the top
  seven bits of the count and the following byte is the lower eight bits. The count
  is stored with two subtracted from it (0=2, 1=3 etc.etc.) because it is not worth
  compressing runs of less than two. The processing of this data can be show as
  follows:

       if count = 0
          byte = next byte from data stream
          if byte>128
             byte = byte & 127
             count = next byte from data stream
             if count>128
                count = count & 127
                count = count * 256
                count = count + next byte from the data stream
             endif
             count = count + 2
          endif
       else
          count = count - 1
       endif

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntProcessContinuousPitchBend(channel_t *cp)
{
  unsigned char work_pb;

  do 
  {    
    cp->pitchbend_frame += 256;
    cp->cont_pb_repeat_count--;
    if(cp->cont_pb_repeat_count == 0)   /* already repeating? */
    {
      work_pb = *(cp->ppitchbend++);
      if(work_pb > 127)		    /* does count follow? */
      {
	/* yes  pitchbend is followed by run length data */
	cp->pitchbend = ((float)(work_pb &0x7f))-64.0;
	cp->pitchbend_precalc = cp->pitchbend*cp->bendrange;
	work_pb = *(cp->ppitchbend++);
	if(work_pb > 127)
	{
	  cp->cont_pb_repeat_count = ((int)(work_pb&0x7f)*256);
	  cp->cont_pb_repeat_count += (int)*(cp->ppitchbend++)+2;
	}
	else
	  cp->cont_pb_repeat_count = (int)work_pb+2;
      }
      else
      {
	cp->pitchbend = ((float)work_pb)-64.0;
	cp->pitchbend_precalc = cp->pitchbend*cp->bendrange;
	cp->cont_pb_repeat_count=1;
      }
    }
  } while ((long)(cp->pitchbend_frame-cp->channel_frame)<0);

#ifdef SUPPORT_EFFECTS
  __MusIntSpecialPitchBend(cp);
#endif
}


/***********************************************************************************
************************************************************************************

               I N T E R N A L   U T I L I T Y   F U N C T I O N S

************************************************************************************
***********************************************************************************/


/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntPowerOf2(x)

  [Parameters]
  x		value

  [Explanation]
  Calculate the power of 2 which represents the specified value.

  [Return value]
  power of 2
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static float __MusIntPowerOf2(float x)
{
  float x2;
  
  if(x == 0)
    return 1;
  
  if(x > 0)
  {
    x2 = x*x;
    return (1+(x*.693147180559945)
	    +(x2*.240226506959101)
	    +(x2*x* 5.55041086648216E-02)
	    +(x2*x2* 9.61812910762848E-03)
	    +(x2*x2*x* 1.33335581464284E-03)
	    +(x2*x2*x2* 1.54035303933816E-04)
	    );
  }	
  else	
  {
    x = -x;
    x2 = x*x;
    return (1/(1+(x*.693147180559945)
	       +(x2*.240226506959101)
	       +(x2*x* 5.55041086648216E-02)
	       +(x2*x2* 9.61812910762848E-03)
	       +(x2*x2*x* 1.33335581464284E-03)
	       +(x2*x2*x2* 1.54035303933816E-04)
	       ));
  }
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntRemapPtrBank(pptr, wptr, remap)

  [Parameters]
  pptr		address of PTR file in RAM
  wptr		address of WBK file in ROM

  [Explanation]
  Change the offsets stored within the pointer bank file (PTR) to pointers.

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntRemapPtrBank(char *pptr, char *wptr)
{
  int i;
  ptr_bank_t *ptrfile_addr;
  unsigned char *chardetune, charwork;
  float *floatdetune, floatwork;
  unsigned long base;

  ptrfile_addr = (ptr_bank_t *)pptr;
  /* return if already remapped */
  if (ptrfile_addr->flags&PTRFLAG_REMAPPED)
    return;
  /* set remapped flag */
  ptrfile_addr->flags |= PTRFLAG_REMAPPED;

  /* remap first set of pointers */
  __MusIntRemapPtrs(&ptrfile_addr->basenote, pptr, 3);
  /* remap wave list pointers */
  __MusIntRemapPtrs(&ptrfile_addr->wave_list[0], pptr, ptrfile_addr->count);

  /* now calculate detune values and remap wave list */
  for (i=0; i<ptrfile_addr->count; i++)
  {
    floatdetune = &ptrfile_addr->detune[i];
    chardetune = (unsigned char *)floatdetune;
    charwork = *chardetune;

    floatwork = U8_TO_FLOAT(charwork);
    *floatdetune = floatwork/100.0;

    charwork = ptrfile_addr->basenote[i]-BASEOFFSET;
    floatwork = U8_TO_FLOAT(charwork);
    *floatdetune += floatwork;

    /* remap pointers inside ALWaveTable structures */
    if(!ptrfile_addr->wave_list[i]->flags)
    {
      base = (unsigned long)ptrfile_addr->wave_list[i]->base;
      if ((base&0xff000000)!=0xff000000) /* not n64dd sample */
      {
	base += (unsigned long)wptr;
	ptrfile_addr->wave_list[i]->base = (u8 *)base;	
      }
      ptrfile_addr->wave_list[i]->flags = 1;
      
      if(ptrfile_addr->wave_list[i]->waveInfo.adpcmWave.loop)			
	ptrfile_addr->wave_list[i]->waveInfo.adpcmWave.loop = (ALADPCMloop *)((u32)(ptrfile_addr->wave_list[i]->waveInfo.adpcmWave.loop)+(u32)(pptr));
      if(ptrfile_addr->wave_list[i]->type == AL_ADPCM_WAVE)			
	ptrfile_addr->wave_list[i]->waveInfo.adpcmWave.book = (ALADPCMBook *)((u32)(ptrfile_addr->wave_list[i]->waveInfo.adpcmWave.book)+(u32)(pptr));			
    }	
  }
  /* flush data cache so the new sample pointers are visible to the RSP */
  osWritebackDCacheAll();
}



/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntRandom(range)

  [Parameters]
  range		upper limit of random number limit (0 to range-1)

  [Explanation]
  Calculate a random(ish) number.

  [Return value]
  random number
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static int __MusIntRandom (int range)
{
  long temp;
  int x;
  float f;
  
  for (x=0;x<8;x++)
  {
    temp = mus_random_seed & 0x48000000;
    mus_random_seed = mus_random_seed<<1;
    if (temp==0x48000000 || temp == 0x08000000)
      mus_random_seed = mus_random_seed | 1;
  }
  f = (float)(mus_random_seed)/(1<<16);
  f /= (1<<16);
  return ((int)((float)(range)*f));
}	

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntInitialiseChannel(cp)

  [Parameters]
  cp		address of music player channel

  [Explanation]
  Initialise a music player channel to it's default state whilst preserving it's
  playing status.

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntInitialiseChannel(channel_t *cp)
{
  unsigned char old_playing, *work_ptr;
  int i;

  /* disable channel processing 1st!!! */
  cp->pdata = NULL;
  old_playing = cp->playing;

  /* zero out channel */
  work_ptr = (unsigned char *)cp;
  for (i=0; i<sizeof(channel_t); i++)
    *work_ptr++ = 0;

  /* set none zero values */
  cp->old_volume    	= 0xffff;
  cp->old_reverb    	= 0xff;
  cp->old_pan       	= 0xff;
  cp->old_frequency 	= 99.9;

  cp->channel_tempo = cp->channel_tempo_save = 96*256/mus_vsyncs_per_second;

  cp->length        	= 1;

  cp->default_velocity 	= 127;
  cp->volume		= 127;
  cp->bendrange		= 2*(1.0/64.0);
  cp->pan		= 64;

  cp->cont_vol_repeat_count = 1;
  cp->cont_pb_repeat_count = 1;

  cp->stopping  = -1;

  /* new volume and pan scales */
  cp->volscale = 0x80;
  cp->panscale = 0x80;
  cp->temscale = 0x80;
  
  /* setup a default envelope */
  cp->env_speed = 1;
  cp->env_attack_speed = 1;
  cp->env_attack_calc = 1.0F;
  cp->env_max_vol = 127;
  cp->env_decay_speed = 255;
  cp->env_decay_calc = 1.0/255.0;
  cp->env_sustain_vol = 127;
  cp->env_release_speed = 15;
  cp->env_release_calc = 1.0/15.0;

  /* set current sample bank */
  cp->sample_bank = mus_init_bank ? mus_init_bank : mus_default_bank;

  /* restore channel status flag */
  cp->playing = old_playing;
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntFindChannel(addr, song_chan)

  [Parameters]
  addr		address of song data
  song_chan	song channel number

  [Explanation]
  Find a music player channel for the specified song channel. 

  [Return value]
  channel found for music channel
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static int __MusIntFindChannel(song_t *addr, int song_chan)
{
	channel_t *cp;
	int i,current,current_channel;

	/* master tacks can use channels reserved for them */
	if (song_chan<0)
	{
		for (i=0, cp=mus_channels; i<MAX_SONGS; i++, cp++)
			if (!cp->pdata)
				return (i);
	}

	/* 1st scan for empty channel */
	for (i=MAX_SONGS, cp=mus_channels2; i<max_channels; i++, cp++)
		if (!cp->pdata)
			return (i);

	/* 2nd scan for sfx channel to override */
	for (i=MAX_SONGS, cp=mus_channels2, current=0x7fffffff, current_channel=MAX_SONGS-1; i<max_channels; i++, cp++)
	{
		if (cp->fx_addr)
		{
			if (cp->priority<=current)
			{
				current=cp->priority;
				current_channel=i;
			}
		}
	}
	if (current_channel>=MAX_SONGS)
		return (current_channel);

	/* 3rd scan for song channel (not this song) */
	for (i=MAX_SONGS, cp=mus_channels2; i<max_channels; i++)
		if (!cp->fx_addr && cp->song_addr!=addr)
			return (i);

	/* 4th scan for same tune, same channel */
	for (i=MAX_SONGS, cp=mus_channels2; i<max_channels; i++, cp++)
		if (cp->song_addr==addr && addr->data_list[song_chan]==cp->pbase)
			return (i);

	/* get any channel */
	return ((song_chan%(max_channels-MAX_SONGS))+MAX_SONGS);
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntRemapPtrs(addr, offset, count)

  [Parameters]
  addr		address of pointer list (zero pointer is kept as a NULL pointer)
  offset	offset to add to pointer
  count		number of pointers to remap

  [Explanation]
  Convert a list of offsets into pointers.

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntRemapPtrs(void *addr, void *offset, int count)
{
  unsigned long *dest, add;
  int i;

  dest = (unsigned long *)addr;
  add = (unsigned long)offset;
  for (i=0; i<count; i++)
    if (dest[i])
      dest[i]+=add;
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntStartEffect(cp, number, volume, pan, priority)

  [Parameters]
  cp		address of music player channel
  number	sound effect number to start
  volume	volume scale
  pan		pan scale
  priority	priority level

  [Explanation]
  Start the specified sound effect on the specified sound channel with the specified
  settings.

  [Return value]
  sound handle
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static unsigned long __MusIntStartEffect(channel_t *cp, fx_header_t *header, int number, int volume, int pan, int priority)
{
   __MusIntInitialiseChannel(cp);

   cp->fx_number	= number;
   cp->fx_addr = header;
   cp->volscale = volume;
   cp->panscale = pan;
   cp->handle = mus_current_handle++;
   cp->priority = priority;

   /* set sample bank pointer */
   if (header->ptr_addr)
      cp->sample_bank = header->ptr_addr;
  
   /* pdata must be set last to avoid processing clash */
   cp->pdata = cp->pbase = header->effects[number].fxdata;

   return (cp->handle);
}

static unsigned long __MusIntFindChannelAndStart(fx_header_t *header, int number, int volume, int pan, int priority)
{
   int i, current_priority;
   channel_t *cp, *current_cp;

	/* get default priority if required */
   if (priority==-1)
      priority = header->effects[number].priority;
   current_priority = priority+1;

   for(i=MAX_SONGS, cp=mus_channels2; i<max_channels; i++, cp++)
   {
      if (cp->pdata==NULL)
         return (__MusIntStartEffect(cp, header, number, volume, pan, priority));
      if (cp->fx_addr && cp->priority<current_priority)
      {
         current_priority = cp->priority;
         current_cp = cp;
      }
   }
   if (current_priority<priority)
      return (__MusIntStartEffect(current_cp, header, number, volume, pan, priority));
  return (0);
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntStartSong(addr)

  [Parameters]
  addr		address of song

  [Explanation]
  Start the specified song.

  [Return value]
  sound handle
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static musHandle __MusIntStartSong(void *addr)
{
	song_t *song_addr;
   int i, channels;
   channel_t *cp;
   unsigned long handle;

   song_addr = addr;
   channels = song_addr->num_channels;

   if (!song_addr->flags&SONGFLAG_INITIALISED)
   {
		song_addr->flags |= SONGFLAG_INITIALISED;
      /* convert header offsets to pointers */
      __MusIntRemapPtrs(SONGHDR_ADR(song_addr), addr, SONGHDR_COUNT);
      /* convert pointer tables */
      __MusIntRemapPtrs(song_addr->data_list, addr, channels);
      __MusIntRemapPtrs(song_addr->volume_list, addr, channels);
      __MusIntRemapPtrs(song_addr->pbend_list, addr, channels);
   }
	/* get next handle */
	handle = mus_current_handle++;

   /* start master track last - always gets started! */
	cp=mus_channels+__MusIntFindChannel(song_addr,-1);
   __MusIntInitialiseChannel(cp);
	cp->velocity_on = 1; 		/* enable velocity for songs */
	cp->channel_flag |= CHFLAG_PAUSE|CHFLAG_MASTERTRACK;
	cp->song_addr = song_addr;
	cp->pdata = cp->pbase = song_addr->master_track;
	cp->handle = handle;

	for(i=0; i<channels; i++)
	{
		if(song_addr->data_list[i]) /* should never happen but just in case! */
		{
			cp=mus_channels+__MusIntFindChannel(song_addr,i);
			__MusIntInitialiseChannel(cp);
			cp->velocity_on = 1; 		/* enable velocity for songs */
			cp->channel_flag |= CHFLAG_PAUSE;
			cp->song_addr = song_addr;
			cp->pvolume = cp->pvolumebase = song_addr->volume_list[i];
			cp->ppitchbend = cp->ppitchbendbase = song_addr->pbend_list[i];
			/* pdata must be set last to avoid processing clash */
			cp->pdata = cp->pbase = song_addr->data_list[i];
			cp->handle = handle;
		}
	}
	/* reset any single sample bank override */
	mus_init_bank = NULL;
	return (handle);
}

/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
  [INTERNAL FUNCTION]
  __MusIntHandleSetFlag(handle, clear, set)

  [Parameters]
  handle	sound handle
  clear		mask (ANDed with flags)
  set		mask (ORed with flags)

  [Explanation]
  Change the channel flags associated with a particular sound handle.

  [Return value]
  NONE
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/

static void __MusIntHandleSetFlag(unsigned long handle, unsigned long clear, unsigned long set)
{
  int i;
  channel_t *cp;

  for (i=0, cp=mus_channels; i<max_channels; i++, cp++)
  {
    if (cp->handle==handle)
    {
      cp->channel_flag &= clear;
      cp->channel_flag |= set;
    }
  }
}


/* end of file */