File: musicPlayer.cpp

package info (click to toggle)
between 6%2Bdfsg1-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 3,524 kB
  • sloc: cpp: 28,110; php: 718; ansic: 638; objc: 245; sh: 236; makefile: 102; perl: 67
file content (754 lines) | stat: -rw-r--r-- 21,603 bytes parent folder | download | duplicates (3)
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

#include "common.h"
#include "Timbre.h"
#include "Envelope.h"

#include "minorGems/util/SimpleVector.h"



#include <SDL/SDL.h>
#include <SDL/SDL_audio.h>

#include <math.h>
#include <stdlib.h>


// smoothly fade in particular tracks based on track fade level
// low value plays only first track... high value plays all tracks
extern double musicTrackFadeLevel;


int sampleRate = 22050;
//int sampleRate = 11025;




Image *musicImage = NULL;
int w, h;

// total number of samples played so far
int streamSamples = 0;

// offset into grid at start
// for testing
int gridStartOffset = 0;



// overal loudness of music
double musicLoudness = 1.0;






// one grid step in seconds
double gridStepDuration = 0.25;
int gridStepDurationInSamples = (int)( gridStepDuration * sampleRate );

double entireGridDuraton;


// c
double keyFrequency = 261.63;


int numTimbres = 9;

Timbre *musicTimbres[ 9 ];

int numEnvelopes = 9;

Envelope *musicEnvelopes[ 9 ];



class Note {
    public:
        // index into musicTimbres array
        int mTimbreNumber;
        
        // index into musicEnvelopes array
        int mEnvelopeNumber;
                
        int mScaleNoteNumber;
        
        // additional loudness adjustment
        // places note in stereo space
        double mLoudnessLeft;
        double mLoudnessRight;
        

        // start time, in seconds from start of note grid
        double mStartTime;

        // duration in seconds
        double mDuration;

        // used when note is currently playing to track progress in note
        // negative if we should wait before starting to play the note
        int mCurrentSampleNumber;

        // duration in samples
        int mNumSamples;
        
                
    };


// isomorphic to our music image, except only has an entry for each note
// start (all others, including grid spots that contain note continuations,
//  are NULL)
// indexed as noteGrid[y][x]
Note ***noteGrid;


SimpleVector<Note*> currentlyPlayingNotes;



// need to synch these with audio thread

void setMusicLoudness( double inLoudness ) {
    SDL_LockAudio();
    
    musicLoudness = inLoudness;
    
    SDL_UnlockAudio();
    }



void restartMusic() {
    SDL_LockAudio();

    // return to beginning (and forget samples we've played so far)
    streamSamples = 0;
    
    // drop all currently-playing notes
    currentlyPlayingNotes.deleteAll();
        
    SDL_UnlockAudio();
    }




// called by SDL to get more samples
void audioCallback( void *inUserData, Uint8 *inStream, int inLengthToFill ) {
    
    // 2 bytes for each channel of stereo sample
    int numSamples = inLengthToFill / 4;
    

    Sint16 *samplesL = new Sint16[ numSamples ];
    Sint16 *samplesR = new Sint16[ numSamples ];
    
    // first, zero-out the buffer to prepare it for our sum of note samples
    // each sample is 2 bytes
    memset( samplesL, 0, 2 * numSamples );
    memset( samplesR, 0, 2 * numSamples );
    

    int i;


    // hop through all grid steps that *start* in this stream buffer
    // add notes that start during this stream buffer

    // how far into stream buffer before we hit our first grid step? 
    int startOfFirstGridStep = streamSamples % gridStepDurationInSamples;
    
    if( startOfFirstGridStep != 0 ) {
        startOfFirstGridStep = 
            gridStepDurationInSamples - startOfFirstGridStep;
        }
    

    // hop from start of grid step to start of next grid step
    // ignore samples in between, since notes don't start there,
    // and all we're doing right now is finding notes that start
    for( i=startOfFirstGridStep; 
         i<numSamples; 
         i += gridStepDurationInSamples ) {
        
        // start of new grid position

        // check for new notes that are starting
        
        // map into our music image:
        int x = ( streamSamples + i ) / gridStepDurationInSamples;
            
        // wrap in image
        x = x % w;

        for( int y=0; y<h; y++ ) {
            
            Note *note = noteGrid[y][x];
                
            if( note != NULL ) {
                // new note
                currentlyPlayingNotes.push_back( note );
                // start it
                
                // set a delay for its start based on our position
                // in this callback buffer
                note->mCurrentSampleNumber = -i;
                }
            }
        }
    
    streamSamples += numSamples;
    

    // loop over all current notes and add their samples to buffer
        
    for( int n=0; n<currentlyPlayingNotes.size(); n++ ) {
            
        Note *note = *( currentlyPlayingNotes.getElement( n ) );
             
        int waveTableNumber = note->mScaleNoteNumber;
        Timbre *timbre = musicTimbres[ note->mTimbreNumber ];
        int tableLength = timbre->mWaveTableLengths[ waveTableNumber ];
            
        Sint16 *waveTable = timbre->mWaveTable[ waveTableNumber ];
        
        Envelope *env = musicEnvelopes[ note->mEnvelopeNumber ];
        double *envLevels = 
            env->getEnvelope( 
                // index envelope by number of grid steps in note
                note->mNumSamples / gridStepDurationInSamples );
        
        
        double noteLoudnessL = note->mLoudnessLeft;
        double noteLoudnessR = note->mLoudnessRight;
        
        // do this outside inner loop
        noteLoudnessL *= musicLoudness;
        noteLoudnessR *= musicLoudness;
        
        // factor in externally-set track fade level

        // level from 0..(numTimbres)
        double trackFadeInLevel = musicTrackFadeLevel * (numTimbres);

        // level for this track based on trackFadeInLevel
        double thisTrackLevel;
        
        if( trackFadeInLevel >= note->mTimbreNumber + 1 ) {
            // full volume
            thisTrackLevel = 1.0;
            }
        else if( trackFadeInLevel > note->mTimbreNumber ) {
            // linear fade in for this track
            thisTrackLevel = trackFadeInLevel - (int)trackFadeInLevel;
            }
        else {
            // track silent
            thisTrackLevel = 0;
            }
        
        noteLoudnessL *= thisTrackLevel;
        noteLoudnessR *= thisTrackLevel;
        


        int noteStartInBuffer = 0;
        int noteEndInBuffer = numSamples;
        
        if( note->mCurrentSampleNumber < 0 ) {
            // delay before note starts in this sample buffer
            noteStartInBuffer = - note->mCurrentSampleNumber;
            
            // we've taken account of the delay
            note->mCurrentSampleNumber = 0;
            }

        char endNote = false;
        
        int numSamplesLeftInNote = 
            note->mNumSamples - note->mCurrentSampleNumber;
        
        if( noteStartInBuffer + numSamplesLeftInNote < noteEndInBuffer ) {
            // note ends before end of buffer
            noteEndInBuffer = noteStartInBuffer + numSamplesLeftInNote;
            endNote = true;
            }
        

        int waveTablePos = note->mCurrentSampleNumber % tableLength;
        
        int currentSampleNumber = note->mCurrentSampleNumber;
        
        for( i=noteStartInBuffer; i != noteEndInBuffer; i++ ) {
            double envelope = envLevels[ currentSampleNumber ];
            
            double monoSample = envelope * 
                waveTable[ waveTablePos ];
            

            samplesL[i] += (Sint16)( noteLoudnessL * monoSample );
            samplesR[i] += (Sint16)( noteLoudnessR * monoSample );
            
            currentSampleNumber ++;
            
            waveTablePos ++;
            
            // avoid using mod operator (%) in inner loop
            // found with profiler
            if( waveTablePos == tableLength ) {
                // back to start of table
                waveTablePos = 0;
                }
            
            }
        
        note->mCurrentSampleNumber += ( noteEndInBuffer - noteStartInBuffer );
        
        if( endNote ) {
            // note ended in this buffer
            currentlyPlayingNotes.deleteElement( n );
            n--;
            }
        
        }


    // now copy samples into Uint8 buffer
    int streamPosition = 0;
    for( i=0; i != numSamples; i++ ) {
        Sint16 intSampleL = samplesL[i];
        Sint16 intSampleR = samplesR[i];
        
        inStream[ streamPosition ] = (Uint8)( intSampleL & 0xFF );
        inStream[ streamPosition + 1 ] = (Uint8)( ( intSampleL >> 8 ) & 0xFF );
        
        inStream[ streamPosition + 2 ] = (Uint8)( intSampleR & 0xFF );
        inStream[ streamPosition + 3 ] = (Uint8)( ( intSampleR >> 8 ) & 0xFF );
        
        streamPosition += 4;
        }

    delete [] samplesL;
    delete [] samplesR;
    
    }



// limit on n, based on Nyquist, when summing sine components
//int nLimit = (int)( sampleRate * M_PI );
// actually, this is way too many:  it takes forever to compute
// use a lower limit instead
// This produces fine results (almost perfect square wave)
int nLimit = 40;



// square wave with period of 2pi
double squareWave( double inT ) {
    double sum = 0;
    
    for( int n=1; n<nLimit; n+=2 ) {
        sum += 1.0/n * sin( n * inT );
        }
    return sum;
    }



// sawtoot wave with period of 2pi
double sawWave( double inT ) {
    double sum = 0;
    
    for( int n=1; n<nLimit; n++ ) {
        sum += 1.0/n * sin( n * inT );
        }
    return sum;
    }


// white noise, ignores inT
double whiteNoise( double inT ) {
    return 2.0 * ( rand() / (double)RAND_MAX ) - 1.0;
    }


// white noise where each sample is averaged with last sample
// effectively a low-pass filter
double lastNoiseSample = 0;

double smoothedWhiteNoise( double inT ) {
    // give double-weight to last sample to make it even smoother
    lastNoiseSample = ( 2 * lastNoiseSample + whiteNoise( inT ) ) / 3;
    
    return lastNoiseSample;
    }



// square where each sample is averaged with last sample
// effectively a low-pass filter
double lastSquareSample = 0;

double smoothedSquareWave( double inT ) {
    // give double-weight to last sample to make it even smoother
    lastSquareSample = ( 4 * lastSquareSample + squareWave( inT ) ) / 5;
    
    return lastSquareSample;
    }


double harmonicSine( double inT ) {
    return
        0.5 * sin( inT ) 
        +
        0.25 * sin( 2 * inT )
        +
        0.125 * sin( 4 * inT );
    }


double harmonicSaw( double inT ) {
    return
        0.5 * sawWave( inT ) 
        +
        0.25 * sawWave( 2 * inT )
        +
        0.125 * sawWave( 4 * inT );
    }



void loadMusicImage( const char *inTGAFileName ) {
        
    musicImage = readTGA( DATADIR"music", inTGAFileName );

    w = musicImage->getWidth();
    h = musicImage->getHeight();

    // notes are in red and green channel
    double *redChannel = musicImage->getChannel( 0 );
    double *greenChannel = musicImage->getChannel( 1 );

    
    entireGridDuraton = gridStepDuration * w;
    

    // jump ahead in stream, if needed
    streamSamples += gridStartOffset * gridStepDurationInSamples;
    
    
    // blank line of pixels between timbres
    int heightPerTimbre = (h+1) / numTimbres - 1;


    // find the maximum number of simultaneous notes in the song
    // take loudness into account
    double  maxNoteLoudnessInAColumn = 0;
    
    int x, y;
    for( x=0; x<w; x++ ) {
        double noteLoudnessInColumnL = 0;
        double noteLoudnessInColumnR = 0;
        
        for( y=0; y<h; y++ ) {
            
            int imageIndex = y * w + x;
            
            // the note number in our scale
            // scale starts over for each timbre, with blank line
            // in between timbres
            int noteNumber = (h - y - 1) % (heightPerTimbre + 1);

            if( // not blank line between timbres
                noteNumber < heightPerTimbre &&  
                // tone present in image
                ( redChannel[ imageIndex ] > 0 || 
                  greenChannel[ imageIndex ] > 0 ) ) {
                
                noteLoudnessInColumnL += greenChannel[ imageIndex ];
                noteLoudnessInColumnR += redChannel[ imageIndex ];
                
                }
            }
        // pick loudest channel for this column and compare it to
        // loudest column/channel seen so far
        if( maxNoteLoudnessInAColumn < noteLoudnessInColumnL ) {
            maxNoteLoudnessInAColumn = noteLoudnessInColumnL;
            }
        if( maxNoteLoudnessInAColumn < noteLoudnessInColumnR ) {
            maxNoteLoudnessInAColumn = noteLoudnessInColumnR;
            }
        
        }
    
   
    // divide loudness amoung timbres to avoid clipping
    double loudnessPerTimbre = 1.0 / maxNoteLoudnessInAColumn;
    
    // further adjust loudness per channel here as we construct
    // each timbre.
    // This is easier than tweaking loundness of a given part by hand
    // using a painting program

    
    musicTimbres[0] = new Timbre( sampleRate, 0.4 * loudnessPerTimbre,
                                  keyFrequency / 2,
                                  heightPerTimbre, sin );   
 
    musicTimbres[1] = new Timbre( sampleRate, 0.3 * loudnessPerTimbre,
                                  keyFrequency,
                                  heightPerTimbre, harmonicSine );

    musicTimbres[2] = new Timbre( sampleRate, 0.2 * loudnessPerTimbre,
                                  keyFrequency * 2,
                                  heightPerTimbre, sin );

    musicTimbres[3] = new Timbre( sampleRate, 0.6 * loudnessPerTimbre,
                                  keyFrequency,
                                  heightPerTimbre, sin );

    musicTimbres[4] = new Timbre( sampleRate, loudnessPerTimbre,
                                  keyFrequency,
                                  heightPerTimbre, sin );

    musicTimbres[5] = new Timbre( sampleRate, 0.7 * loudnessPerTimbre,
                                  keyFrequency / 4,
                                  heightPerTimbre, harmonicSaw );


    musicTimbres[6] = new Timbre( sampleRate, 0.4 * loudnessPerTimbre,
                                  keyFrequency,
                                  heightPerTimbre, harmonicSaw );

    musicTimbres[7] = new Timbre( sampleRate, 0.6 * loudnessPerTimbre,
                                  keyFrequency,
                                  heightPerTimbre, sin );

    musicTimbres[8] = new Timbre( sampleRate, 0.4 *   loudnessPerTimbre,
                                  keyFrequency,
                                  heightPerTimbre, sawWave );
    
    // next, compute the longest note in the song
    int maxNoteLength = 0;
    
    for( y=0; y<h; y++ ) {
        int currentNoteLength = 0;
        
        for( x=0; x<w; x++ ) {
            int imageIndex = y * w + x;
            
            // the note number in our scale
            // scale starts over for each timbre, with blank line
            // in between timbres
            int noteNumber = (h - y - 1) % (heightPerTimbre + 1);

            if( // not blank line between timbres
                noteNumber < heightPerTimbre &&  
                // tone present in image
                ( redChannel[ imageIndex ] > 0 ||
                  greenChannel[ imageIndex ] > 0 ) ) {
                
                currentNoteLength ++;
                }
            else {
                currentNoteLength = 0;
                }
            if( currentNoteLength > maxNoteLength ) {
                maxNoteLength = currentNoteLength;
                }
            }
        }
    
    printf( "Max note length in song = %d\n", maxNoteLength );
    

    
    musicEnvelopes[0] = new Envelope( 0.02, 0.98, 0, 0,
                                      maxNoteLength,
                                      gridStepDurationInSamples );
    musicEnvelopes[1] = new Envelope( 0.1, 0.9, 0.0, 0.0,
                                      maxNoteLength,
                                      gridStepDurationInSamples );

    musicEnvelopes[2] = new Envelope( 0.5, 0.5, 0.0, 0.0,
                                      maxNoteLength,
                                      gridStepDurationInSamples );

    musicEnvelopes[3] = new Envelope( 0.02, 0.98, 0.0, 0.0,
                                      maxNoteLength,
                                      gridStepDurationInSamples );

    musicEnvelopes[4] = new Envelope( 0.9, 0.0, 1.0, 0.1,
                                      maxNoteLength,
                                      gridStepDurationInSamples );

    musicEnvelopes[5] = new Envelope( 0.25, 0.5, 1.0, 0.25,
                                      maxNoteLength,
                                      gridStepDurationInSamples );

    musicEnvelopes[6] = new Envelope( 0.25, 0.7, 1.0, 0.05,
                                      maxNoteLength,
                                      gridStepDurationInSamples );

    musicEnvelopes[7] = new Envelope( 0.02, 0.98, 0.0, 0.0,
                                      maxNoteLength,
                                      gridStepDurationInSamples );

    musicEnvelopes[8] = new Envelope( 0.1, 0.9, 0.0, 0.0,
                                      maxNoteLength,
                                      gridStepDurationInSamples );
    


    
    noteGrid = new Note**[ h ];
    
    for( int y=0; y<h; y++ ) {
        noteGrid[y] = new Note*[ w ];
        
        // each row is one pitch for a given instrument
        // thus, two consecutive pixels should be the same note
        // handle this by tracking whether a note is playing or not
        char notePlaying = false;
        Note *noteStart = NULL;
        for( int x=0; x<w; x++ ) {
            int imageIndex = y * w + x;
            
            // default to NULL
            noteGrid[y][x] = NULL;

            // the note number in our scale
            // scale starts over for each timbre, with blank line
            // in between timbres
            int noteNumber = (h - y - 1) % (heightPerTimbre + 1);

            

            if( // not blank line between timbres
                noteNumber < heightPerTimbre &&  
                // tone present in image
                ( redChannel[ imageIndex ] > 0 || 
                  greenChannel[ imageIndex ] > 0 ) ) {
               

                if( notePlaying ) {
                    // part of note that's already playing
                    
                    // one more grid step
                    noteStart->mDuration += gridStepDuration;
                    noteStart->mNumSamples += gridStepDurationInSamples;
                    
                    }
                else {
                    // start a new note
                    noteGrid[y][x] = new Note();
                    
                    noteGrid[y][x]->mScaleNoteNumber = noteNumber;
                    
                    noteGrid[y][x]->mTimbreNumber = 
                        y / ( heightPerTimbre + 1 );
            
                    // same as timbre number
                    noteGrid[y][x]->mEnvelopeNumber = 
                        noteGrid[y][x]->mTimbreNumber;
                    
                    // left loudness from green brightness
                    noteGrid[y][x]->mLoudnessLeft = greenChannel[ imageIndex ];
                    
                    // right loudness from red brightness
                    noteGrid[y][x]->mLoudnessRight = redChannel[ imageIndex ];
                    
                    noteGrid[y][x]->mStartTime = gridStepDuration * x;
                    
                    // one grid step so far
                    noteGrid[y][x]->mDuration = gridStepDuration;
                    noteGrid[y][x]->mNumSamples = gridStepDurationInSamples;
                    
                    // track if it needs to be continued
                    notePlaying = true;
                    noteStart = noteGrid[y][x];
                    }
                }
            else {
                // no tone

                if( notePlaying ) {
                    // stop it
                    notePlaying = false;
                    noteStart = NULL;
                    }
                }
            }
        }
    
        
    }



void startMusic( const char *inTGAFileName ) {
    
    loadMusicImage( inTGAFileName );
    
    SDL_AudioSpec audioFormat;

    /* Set 16-bit stereo audio at 22Khz */
    audioFormat.freq = sampleRate;
    audioFormat.format = AUDIO_S16;
    audioFormat.channels = 2;
    audioFormat.samples = 512;        /* A good value for games */
    audioFormat.callback = audioCallback;
    audioFormat.userdata = NULL;

    /* Open the audio device and start playing sound! */
    if( SDL_OpenAudio( &audioFormat, NULL ) < 0 ) {
        printf( "Unable to open audio: %s\n", SDL_GetError() );
        }

    // set pause to 0 to start audio
    SDL_PauseAudio(0);
    
    
    }



void stopMusic() {
    SDL_CloseAudio();

    if( musicImage != NULL ) {
        delete musicImage;
        musicImage = NULL;
        }

    for( int y=0; y<h; y++ ) {

        for( int x=0; x<w; x++ ) {
            
            if( noteGrid[y][x] != NULL ) {
                delete noteGrid[y][x];
                }
            }
        delete [] noteGrid[y];
        }
    
    delete [] noteGrid;

    
    int i;
    
    for( i=0; i<numTimbres; i++ ) {
        delete musicTimbres[i];
        }
    for( i=0; i<numEnvelopes; i++ ) {
        delete musicEnvelopes[i];
        }
    
    }