aboutsummaryrefslogtreecommitdiffstats
path: root/Game/Code/Classes/UAudioPlayback_Portaudio.pas
blob: 2743fa863db75aa3ec75d8a34ec49271ffa481e4 (plain) (blame)
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
unit UAudioPlayback_Portaudio;

interface

{$IFDEF FPC}
  {$MODE Delphi}
{$ENDIF}

{$I switches.inc}


uses
  Classes,
  SysUtils,
  UMusic;

implementation

uses
  {$IFNDEF Win32}
  libc,
  {$ENDIF}
  sdl,
  portaudio,
  ULog,
  UIni,
  UMain;

type
  TPortaudioPlaybackStream = class(TAudioPlaybackStream)
    private
      Status:   TStreamStatus;
      Loop:     boolean;

      _volume: integer;

      procedure Reset();
    public
      DecodeStream: TAudioDecodeStream;

      constructor Create();
      destructor Destroy(); override;

      function SetDecodeStream(decodeStream: TAudioDecodeStream): boolean;

      procedure Play();                     override;
      procedure Pause();                    override;
      procedure Stop();                     override;
      procedure Close();                    override;
      function GetLoop(): boolean;          override;
      procedure SetLoop(Enabled: boolean);  override;
      function GetLength(): real;           override;
      function GetStatus(): TStreamStatus;  override;

      function IsLoaded(): boolean;

      function GetVolume(): integer;        override;
      procedure SetVolume(volume: integer); override;

      // functions delegated to the decode stream
      function GetPosition: real;
      procedure SetPosition(Time: real);
      function ReadData(Buffer: PChar; BufSize: integer): integer;
  end;

type
  TAudioMixerStream = class
    private
      activeStreams: TList;
      mixerBuffer: PChar;
      internalLock: PSDL_Mutex;

      _volume: integer;

      procedure Lock(); inline;
      procedure Unlock(); inline;

      function GetVolume(): integer;
      procedure SetVolume(volume: integer);
    public
      constructor Create();
      destructor Destroy(); override;
      procedure AddStream(stream: TAudioPlaybackStream);
      procedure RemoveStream(stream: TAudioPlaybackStream);
      function ReadData(Buffer: PChar; BufSize: integer): integer;

      property Volume: integer READ GetVolume WRITE SetVolume;
  end;

type
  TAudioPlayback_Portaudio = class( TInterfacedObject, IAudioPlayback )
    private
      MusicStream:        TPortaudioPlaybackStream;

      MixerStream: TAudioMixerStream;
      paStream:    PPaStream;

      FrameSize: integer;

      function InitializePortaudio(): boolean;
      function StartPortaudioStream(): boolean;

      function InitializeSDLAudio(): boolean;
      function StartSDLAudioStream(): boolean;
      procedure StopSDLAudioStream();
    public
      function  GetName: String;

      function InitializePlayback(): boolean;
      destructor Destroy; override;

      function Load(const Filename: String): TPortaudioPlaybackStream;

      procedure SetVolume(Volume: integer);
      procedure SetMusicVolume(Volume: integer);
      procedure SetLoop(Enabled: boolean);
      function Open(Filename: string): boolean; // true if succeed
      procedure Rewind;
      procedure SetPosition(Time: real);
      procedure Play;
      procedure Pause;

      procedure Stop;
      procedure Close;
      function Finished: boolean;
      function Length: real;
      function GetPosition: real;

      // Equalizer
      procedure GetFFTData(var data: TFFTData);

      // Interface for Visualizer
      function GetPCMData(var data: TPCMData): Cardinal;

      // Sounds
      function OpenSound(const Filename: String): TAudioPlaybackStream;
      procedure PlaySound(stream: TAudioPlaybackStream);
      procedure StopSound(stream: TAudioPlaybackStream);
  end;


function AudioCallback(input: Pointer; output: Pointer; frameCount: Longword;
      timeInfo: PPaStreamCallbackTimeInfo; statusFlags: TPaStreamCallbackFlags;
      userData: Pointer): Integer; cdecl; forward;

var
  singleton_AudioPlaybackPortaudio : IAudioPlayback;


{ TAudioMixerStream }

constructor TAudioMixerStream.Create();
begin
  activeStreams := TList.Create;
  internalLock := SDL_CreateMutex();
  _volume := 100;
end;

destructor TAudioMixerStream.Destroy();
begin
  if assigned(mixerBuffer) then
    Freemem(mixerBuffer);
  activeStreams.Free;
  SDL_DestroyMutex(internalLock);
end;

procedure TAudioMixerStream.Lock();
begin
  SDL_mutexP(internalLock);
end;

procedure TAudioMixerStream.Unlock();
begin
  SDL_mutexV(internalLock);
end;

function TAudioMixerStream.GetVolume(): integer;
begin
  Lock();
  result := _volume;
  Unlock();
end;

procedure TAudioMixerStream.SetVolume(volume: integer);
begin
  Lock();
  _volume := volume;
  Unlock();
end;

procedure TAudioMixerStream.AddStream(stream: TAudioPlaybackStream);
begin
  if not assigned(stream) then
    Exit;

  Lock();
  // check if stream is already in list to avoid duplicates
  if (activeStreams.IndexOf(Pointer(stream)) = -1) then
    activeStreams.Add(Pointer(stream));
  Unlock();
end;

procedure TAudioMixerStream.RemoveStream(stream: TAudioPlaybackStream);
begin
  Lock();
  activeStreams.Remove(Pointer(stream));
  Unlock();
end;

function TAudioMixerStream.ReadData(Buffer: PChar; BufSize: integer): integer;
var
  i: integer;
  size: integer;
  stream: TPortaudioPlaybackStream;
  appVolume: single;
begin
  result := BufSize;

  // zero target-buffer (silence)
  FillChar(Buffer^, BufSize, 0);

  // resize mixer-buffer if necessary
  ReallocMem(mixerBuffer, BufSize);
  if not assigned(mixerBuffer) then
    Exit;

  Lock();

  //writeln('Mix: ' + inttostr(activeStreams.Count));

  // use _volume instead of Volume to prevent recursive locking 
  appVolume := _volume / 100 * SDL_MIX_MAXVOLUME;

  for i := 0 to activeStreams.Count-1 do
  begin
    stream := TPortaudioPlaybackStream(activeStreams[i]);
    if (stream.GetStatus() = ssPlaying) then
    begin
      // fetch data from current stream
      size := stream.ReadData(mixerBuffer, BufSize);
      if (size > 0) then
      begin
        SDL_MixAudio(PUInt8(Buffer), PUInt8(mixerBuffer), size,
          Trunc(appVolume * stream.Volume / 100));
      end;
    end;
  end;

  Unlock();
end;


{ TPortaudioPlaybackStream }

constructor TPortaudioPlaybackStream.Create();
begin
  inherited Create();
  Reset();
end;

destructor TPortaudioPlaybackStream.Destroy();
begin
  Close();
  inherited Destroy();
end;

procedure TPortaudioPlaybackStream.Reset();
begin
  Status := ssStopped;
  Loop := false;
  DecodeStream := nil;
  _volume := 0;
end;

function TPortaudioPlaybackStream.SetDecodeStream(decodeStream: TAudioDecodeStream): boolean;
begin
  result := false;

  Reset();

  if not assigned(decodeStream) then
    Exit;
  Self.DecodeStream := decodeStream;

  _volume := 100;

  result := true;
end;

procedure TPortaudioPlaybackStream.Close();
begin
  Reset();
end;

procedure TPortaudioPlaybackStream.Play();
begin
  if (status <> ssPaused) then
  begin
    // rewind
    if assigned(DecodeStream) then
      DecodeStream.Position := 0;
  end;
  status := ssPlaying;
  //MixerStream.AddStream(Self);
end;

procedure TPortaudioPlaybackStream.Pause();
begin
  status := ssPaused;
end;

procedure TPortaudioPlaybackStream.Stop();
begin
  status := ssStopped;
end;

function TPortaudioPlaybackStream.IsLoaded(): boolean;
begin
  result := assigned(DecodeStream);
end;

function TPortaudioPlaybackStream.GetLoop(): boolean;
begin
  result := Loop;
end;

procedure TPortaudioPlaybackStream.SetLoop(Enabled: boolean);
begin
  Loop := Enabled;
end;

function TPortaudioPlaybackStream.GetLength(): real;
begin
  if assigned(DecodeStream) then
    result := DecodeStream.Length
  else
    result := -1;
end;

function TPortaudioPlaybackStream.GetStatus(): TStreamStatus;
begin
  result := status;
end;

function TPortaudioPlaybackStream.ReadData(Buffer: PChar; BufSize: integer): integer;
begin
  if not assigned(DecodeStream) then
  begin
    result := -1;
    Exit;
  end;
  result := DecodeStream.ReadData(Buffer, BufSize);
  // end-of-file reached -> stop playback
  if (DecodeStream.EOF) then
  begin
    status := ssStopped;
  end;
end;

function TPortaudioPlaybackStream.GetPosition: real;
begin
  if assigned(DecodeStream) then
    result := DecodeStream.Position
  else
    result := -1;
end;

procedure TPortaudioPlaybackStream.SetPosition(Time: real);
begin
  if assigned(DecodeStream) then
    DecodeStream.Position := Time;
end;

function TPortaudioPlaybackStream.GetVolume(): integer;
begin
  result := _volume;
end;

procedure TPortaudioPlaybackStream.SetVolume(volume: integer);
begin
  // clamp volume
  if (volume > 100) then
    _volume := 100
  else if (volume < 0) then
    _volume := 0
  else
    _volume := volume;
end;


{ TAudioPlayback_Portaudio }

function AudioCallback(input: Pointer; output: Pointer; frameCount: Longword;
    timeInfo: PPaStreamCallbackTimeInfo; statusFlags: TPaStreamCallbackFlags;
    userData: Pointer): Integer; cdecl;
var
  playback: TAudioPlayback_Portaudio;
begin
  playback := TAudioPlayback_Portaudio(userData);
  with playback do
  begin
    MixerStream.ReadData(output, frameCount * FrameSize);
  end;
  result := paContinue;
end;

procedure SDLAudioCallback(userdata: Pointer; stream: PChar; len: integer); cdecl;
var
  playback: TAudioPlayback_Portaudio;
begin
  playback := TAudioPlayback_Portaudio(userdata);
  with playback do
  begin
    //MixerStream.ReadData(stream, len);
  end;
end;

function TAudioPlayback_Portaudio.GetName: String;
begin
  result := 'Portaudio_Playback';
end;

function TAudioPlayback_Portaudio.InitializePortaudio(): boolean;
var
  paApi           : TPaHostApiIndex;
  paApiInfo       : PPaHostApiInfo;
  paOutParams     : TPaStreamParameters;
  paOutDevice     : TPaDeviceIndex;
  paOutDeviceInfo : PPaDeviceInfo;
  err             : TPaError;
begin
  result := false;

  Pa_Initialize();

  // FIXME: determine automatically
  {$IFDEF WIN32}
  paApi := Pa_HostApiTypeIdToHostApiIndex(paDirectSound);
  {$ELSE}
  paApi := Pa_HostApiTypeIdToHostApiIndex(paALSA);
  {$ENDIF}
  if (paApi < 0) then
  begin
    Log.LogStatus('Pa_HostApiTypeIdToHostApiIndex: '+Pa_GetErrorText(paApi), 'UAudioPlayback_Portaudio');
    exit;
  end;

  paApiInfo := Pa_GetHostApiInfo(paApi);
  paOutDevice     := paApiInfo^.defaultOutputDevice;
  paOutDeviceInfo := Pa_GetDeviceInfo(paOutDevice);

  with paOutParams do begin
    device := paOutDevice;
    channelCount := 2;
    sampleFormat := paInt16;
    suggestedLatency := paOutDeviceInfo^.defaultHighOutputLatency;
    hostApiSpecificStreamInfo := nil;
  end;

  // set the size of one audio frame (2channel 16bit uint sample)
  FrameSize := 2 * sizeof(Smallint);

  err := Pa_OpenStream(paStream, nil, @paOutParams, 44100,
          paFramesPerBufferUnspecified,
          paNoFlag, @AudioCallback, Self);
  if(err <> paNoError) then begin
    Log.LogStatus('Pa_OpenStream: '+Pa_GetErrorText(err), 'UAudioPlayback_Portaudio');
    exit;
  end;

  Log.LogStatus('Opened audio device', 'UAudioPlayback_Portaudio');

  result := true;
end;

function TAudioPlayback_Portaudio.StartPortaudioStream(): boolean;
var
  err: TPaError;
begin
  result := false;

  err := Pa_StartStream(paStream);
  if(err <> paNoError) then
  begin
    Log.LogStatus('Pa_StartStream: '+Pa_GetErrorText(err), 'UAudioPlayback_Portaudio');
    exit;
  end;

  result := true;
end;

function TAudioPlayback_Portaudio.InitializeSDLAudio(): boolean;
var
  desiredAudioSpec, obtainedAudioSpec: TSDL_AudioSpec;
  err: integer;
begin
  result := false;

  SDL_InitSubSystem(SDL_INIT_AUDIO);

  FillChar(desiredAudioSpec, sizeof(desiredAudioSpec), 0);
  with desiredAudioSpec do
  begin
    freq := 44100;
    format := AUDIO_S16SYS;
    channels := 2;
    samples := 1024; // latency: 23 ms
    callback := @SDLAudioCallback;
    userdata := Self;
  end;

  // set the size of one audio frame (2channel 16bit uint sample)
  FrameSize := 2 * sizeof(Smallint);

  if(SDL_OpenAudio(@desiredAudioSpec, @obtainedAudioSpec) = -1) then
  begin
    Log.LogStatus('SDL_OpenAudio: ' + SDL_GetError(), 'UAudioPlayback_SDL');
    exit;
  end;

  Log.LogStatus('Opened audio device', 'UAudioPlayback_SDL');

  result := true;
end;

function TAudioPlayback_Portaudio.StartSDLAudioStream(): boolean;
begin
  SDL_PauseAudio(0);
  result := true;
end;

procedure TAudioPlayback_Portaudio.StopSDLAudioStream();
begin
  SDL_CloseAudio();
end;

function TAudioPlayback_Portaudio.InitializePlayback: boolean;
begin
  result := false;

  //Log.LogStatus('InitializePlayback', 'UAudioPlayback_Portaudio');

  //if(not InitializePortaudio()) then
  if(not InitializeSDLAudio()) then
    Exit;

  MixerStream := TAudioMixerStream.Create;

  //if(not StartPortaudioStream()) then;
  if(not StartSDLAudioStream()) then
    Exit;

  result := true;
end;

destructor TAudioPlayback_Portaudio.Destroy;
begin
  StopSDLAudioStream();

  MixerStream.Free();
  MusicStream.Free();

  inherited Destroy();
end;

function TAudioPlayback_Portaudio.Load(const Filename: String): TPortaudioPlaybackStream;
var
  decodeStream: TAudioDecodeStream;
  playbackStream: TPortaudioPlaybackStream;
begin
  Result := nil;

  decodeStream := AudioDecoder.Open(Filename);
  if not assigned(decodeStream) then
  begin
    Log.LogStatus('LoadSoundFromFile: Sound not found "' + Filename + '"', 'UAudioPlayback_Portaudio');
    Exit;
  end;

  playbackStream := TPortaudioPlaybackStream.Create();
  if (not playbackStream.SetDecodeStream(decodeStream)) then
    Exit;

  // FIXME: remove this line
  MixerStream.AddStream(playbackStream);

  result := playbackStream;
end;

procedure TAudioPlayback_Portaudio.SetVolume(Volume: integer);
begin
  // sets volume only for this application
  MixerStream.Volume := Volume;
end;

procedure TAudioPlayback_Portaudio.SetMusicVolume(Volume: Integer);
begin
  if assigned(MusicStream) then
    MusicStream.Volume := Volume;
end;

procedure TAudioPlayback_Portaudio.SetLoop(Enabled: boolean);
begin
  if assigned(MusicStream) then
    MusicStream.SetLoop(Enabled);
end;

function TAudioPlayback_Portaudio.Open(Filename: string): boolean;
var
  decodeStream: TAudioDecodeStream;
begin
  Result := false;

  // free old MusicStream
  MusicStream.Free();

  MusicStream := Load(Filename);
  if not assigned(MusicStream) then
    Exit;

  //Set Max Volume
  SetMusicVolume(100);

  Result := true;
end;

procedure TAudioPlayback_Portaudio.Rewind;
begin
  SetPosition(0);
end;

procedure TAudioPlayback_Portaudio.SetPosition(Time: real);
begin
  if assigned(MusicStream) then
    MusicStream.SetPosition(Time);
end;

function TAudioPlayback_Portaudio.GetPosition: real;
begin
  if assigned(MusicStream) then
    Result := MusicStream.GetPosition()
  else
    Result := -1;
end;

function TAudioPlayback_Portaudio.Length: real;
begin
  if assigned(MusicStream) then
    Result := MusicStream.GetLength()
  else
    Result := -1;
end;

procedure TAudioPlayback_Portaudio.Play;
begin
  if assigned(MusicStream) then
    MusicStream.Play();
end;

procedure TAudioPlayback_Portaudio.Pause;
begin
  if assigned(MusicStream) then
    MusicStream.Pause();
end;

procedure TAudioPlayback_Portaudio.Stop;
begin
  if assigned(MusicStream) then
    MusicStream.Stop();
end;

procedure TAudioPlayback_Portaudio.Close;
begin
  if assigned(MusicStream) then
  begin
    MixerStream.RemoveStream(MusicStream);
    MusicStream.Close();
  end;
end;

function TAudioPlayback_Portaudio.Finished: boolean;
begin
  if assigned(MusicStream) then
    Result := (MusicStream.GetStatus() = ssStopped)
  else
    Result := true;
end;

//Equalizer
procedure TAudioPlayback_Portaudio.GetFFTData(var data: TFFTData);
begin
  //Get Channel Data Mono and 256 Values
//  BASS_ChannelGetData(Bass, @Result, BASS_DATA_FFT512);
end;

// Interface for Visualizer
function TAudioPlayback_Portaudio.GetPCMData(var data: TPCMData): Cardinal;
begin
  result := 0;
end;

function TAudioPlayback_Portaudio.OpenSound(const Filename: String): TAudioPlaybackStream;
begin
  result := Load(Filename);
end;

procedure TAudioPlayback_Portaudio.PlaySound(stream: TAudioPlaybackStream);
begin
  if assigned(stream) then
    stream.Play();
end;

procedure TAudioPlayback_Portaudio.StopSound(stream: TAudioPlaybackStream);
begin
  if assigned(stream) then
    stream.Stop();
end;


initialization
  singleton_AudioPlaybackPortaudio := TAudioPlayback_Portaudio.create();
  AudioManager.add( singleton_AudioPlaybackPortaudio );

finalization
  AudioManager.Remove( singleton_AudioPlaybackPortaudio );


end.