aboutsummaryrefslogblamecommitdiffstats
path: root/cmake/src/media/UAudioPlayback_SoftMixer.pas
blob: c87e461d055717c6848099ca3c0d2676e9e6f855 (plain) (tree)
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

































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                          
{* UltraStar Deluxe - Karaoke Game
 *
 * UltraStar Deluxe is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING. If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 * $URL$
 * $Id$
 *}

unit UAudioPlayback_SoftMixer;

interface

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

{$I switches.inc}

uses
  Classes,
  sdl,
  SysUtils,
  URingBuffer,
  UMusic,
  UAudioPlaybackBase;

type
  TAudioPlayback_SoftMixer = class;

  TGenericPlaybackStream = class(TAudioPlaybackStream)
    private
      Engine: TAudioPlayback_SoftMixer;

      SampleBuffer:      PByteArray;
      SampleBufferSize:  integer;
      SampleBufferCount: integer; // number of available bytes in SampleBuffer
      SampleBufferPos:   integer;

      SourceBuffer:      PByteArray;
      SourceBufferSize:  integer;
      SourceBufferCount: integer; // number of available bytes in SourceBuffer

      Converter: TAudioConverter;
      Status:   TStreamStatus;
      InternalLock: PSDL_Mutex;
      SoundEffects: TList;
      fVolume: single;

      FadeInStartTime, FadeInTime: cardinal;
      FadeInStartVolume, FadeInTargetVolume: single;

      NeedsRewind: boolean;

      procedure Reset();

      procedure ApplySoundEffects(Buffer: PByteArray; BufferSize: integer);
      function InitFormatConversion(): boolean;
      procedure FlushBuffers();

      procedure LockSampleBuffer(); {$IFDEF HasInline}inline;{$ENDIF}
      procedure UnlockSampleBuffer(); {$IFDEF HasInline}inline;{$ENDIF}
    protected
      function GetLatency(): double;        override;
      function GetStatus(): TStreamStatus;  override;
      function GetVolume(): single;         override;
      procedure SetVolume(Volume: single);  override;
      function GetLength(): real;           override;
      function GetLoop(): boolean;          override;
      procedure SetLoop(Enabled: boolean);  override;
      function GetPosition: real;           override;
      procedure SetPosition(Time: real);    override;
    public
      constructor Create(Engine: TAudioPlayback_SoftMixer);
      destructor Destroy(); override;

      function Open(SourceStream: TAudioSourceStream): boolean; override;
      procedure Close();                    override;

      procedure Play();                     override;
      procedure Pause();                    override;
      procedure Stop();                     override;
      procedure FadeIn(Time: real; TargetVolume: single); override;

      function GetAudioFormatInfo(): TAudioFormatInfo; override;

      function ReadData(Buffer: PByteArray; BufferSize: integer): integer;

      function GetPCMData(var Data: TPCMData): Cardinal; override;
      procedure GetFFTData(var Data: TFFTData);          override;

      procedure AddSoundEffect(Effect: TSoundEffect);    override;
      procedure RemoveSoundEffect(Effect: TSoundEffect); override;
  end;

  TAudioMixerStream = class
    private
      Engine: TAudioPlayback_SoftMixer;

      ActiveStreams: TList;
      MixerBuffer: PByteArray;
      InternalLock: PSDL_Mutex;

      AppVolume: single;

      procedure Lock(); {$IFDEF HasInline}inline;{$ENDIF}
      procedure Unlock(); {$IFDEF HasInline}inline;{$ENDIF}

      function GetVolume(): single;
      procedure SetVolume(Volume: single);
    public
      constructor Create(Engine: TAudioPlayback_SoftMixer);
      destructor Destroy(); override;
      procedure AddStream(Stream: TAudioPlaybackStream);
      procedure RemoveStream(Stream: TAudioPlaybackStream);
      function ReadData(Buffer: PByteArray; BufferSize: integer): integer;

      property Volume: single read GetVolume write SetVolume;
  end;

  TAudioPlayback_SoftMixer = class(TAudioPlaybackBase)
    private
      MixerStream: TAudioMixerStream;
    protected
      FormatInfo: TAudioFormatInfo;

      function InitializeAudioPlaybackEngine(): boolean; virtual; abstract;
      function StartAudioPlaybackEngine(): boolean;      virtual; abstract;
      procedure StopAudioPlaybackEngine();               virtual; abstract;
      function FinalizeAudioPlaybackEngine(): boolean;   virtual; abstract;
      procedure AudioCallback(Buffer: PByteArray; Size: integer); {$IFDEF HasInline}inline;{$ENDIF}

      function CreatePlaybackStream(): TAudioPlaybackStream; override;
    public
      function GetName: String; override; abstract;
      function InitializePlayback(): boolean; override;
      function FinalizePlayback: boolean; override;

      procedure SetAppVolume(Volume: single); override;

      function CreateVoiceStream(ChannelMap: integer; FormatInfo: TAudioFormatInfo): TAudioVoiceStream; override;

      function GetMixer(): TAudioMixerStream; {$IFDEF HasInline}inline;{$ENDIF}
      function GetAudioFormatInfo(): TAudioFormatInfo;

      procedure MixBuffers(DstBuffer, SrcBuffer: PByteArray; Size: Cardinal; Volume: Single); virtual;
  end;

type
  TGenericVoiceStream = class(TAudioVoiceStream)
    private
      VoiceBuffer: TRingBuffer;
      BufferLock: PSDL_Mutex;
      PlaybackStream: TGenericPlaybackStream;
      Engine: TAudioPlayback_SoftMixer;
    public
      constructor Create(Engine: TAudioPlayback_SoftMixer);

      function Open(ChannelMap: integer; FormatInfo: TAudioFormatInfo): boolean; override;
      procedure Close(); override;
      procedure WriteData(Buffer: PByteArray; BufferSize: integer); override;
      function ReadData(Buffer: PByteArray; BufferSize: integer): integer; override;
      function IsEOF(): boolean; override;
      function IsError(): boolean; override;
  end;

const
  SOURCE_BUFFER_FRAMES = 4096;

const
  MAX_VOICE_DELAY = 0.500; // 20ms

implementation

uses
  Math,
  ULog,
  UIni,
  UFFT,
  UAudioConverter,
  UMain;

{ TAudioMixerStream }

constructor TAudioMixerStream.Create(Engine: TAudioPlayback_SoftMixer);
begin
  inherited Create();

  Self.Engine := Engine;

  ActiveStreams := TList.Create;
  InternalLock := SDL_CreateMutex();
  AppVolume := 1.0;
end;

destructor TAudioMixerStream.Destroy();
begin
  if assigned(MixerBuffer) then
    Freemem(MixerBuffer);
  ActiveStreams.Free;
  SDL_DestroyMutex(InternalLock);
  inherited;
end;

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

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

function TAudioMixerStream.GetVolume(): single;
begin
  Lock();
  Result := AppVolume;
  Unlock();
end;

procedure TAudioMixerStream.SetVolume(Volume: single);
begin
  Lock();
  AppVolume := 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;

(*
 * Sets the entry of stream in the ActiveStreams-List to nil
 * but does not remove it from the list (Count is not changed!).
 * Otherwise iterations over the elements might fail due to a
 * changed Count-property.
 * Call ActiveStreams.Pack() to remove the nil-pointers
 * or check for nil-pointers when accessing ActiveStreams.
 *)
procedure TAudioMixerStream.RemoveStream(Stream: TAudioPlaybackStream);
var
  Index: integer;
begin
  Lock();
  Index := activeStreams.IndexOf(Pointer(Stream));
  if (Index <> -1) then
  begin
    // remove entry but do not decrease count-property
    ActiveStreams[Index] := nil;
  end;
  Unlock();
end;

function TAudioMixerStream.ReadData(Buffer: PByteArray; BufferSize: integer): integer;
var
  i: integer;
  Size: integer;
  Stream: TGenericPlaybackStream;
  NeedsPacking: boolean;
begin
  Result := BufferSize;

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

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

  Lock();

  NeedsPacking := false;

  // mix streams to one stream
  for i := 0 to ActiveStreams.Count-1 do
  begin
    if (ActiveStreams[i] = nil) then
    begin
      NeedsPacking := true;
      continue;
    end;

    Stream := TGenericPlaybackStream(ActiveStreams[i]);
    // fetch data from current stream
    Size := Stream.ReadData(MixerBuffer, BufferSize);
    if (Size > 0) then
    begin
      // mix stream-data with mixer-buffer
      // Note: use Self.appVolume instead of Self.Volume to prevent recursive locking
      Engine.MixBuffers(Buffer, MixerBuffer, Size, AppVolume * Stream.Volume);
    end;
  end;

  // remove nil-pointers from list
  if (NeedsPacking) then
  begin
    ActiveStreams.Pack();
  end;

  Unlock();
end;


{ TGenericPlaybackStream }

constructor TGenericPlaybackStream.Create(Engine: TAudioPlayback_SoftMixer);
begin
  inherited Create();
  Self.Engine := Engine;
  InternalLock := SDL_CreateMutex();
  SoundEffects := TList.Create;
  Status := ssStopped;
  Reset();
end;

destructor TGenericPlaybackStream.Destroy();
begin
  Close();
  SDL_DestroyMutex(InternalLock);
  FreeAndNil(SoundEffects);
  inherited;
end;

procedure TGenericPlaybackStream.Reset();
begin
  SourceStream := nil;

  FreeAndNil(Converter);

  FreeMem(SampleBuffer);
  SampleBuffer := nil;
  SampleBufferPos := 0;
  SampleBufferSize := 0;
  SampleBufferCount := 0;

  FreeMem(SourceBuffer);
  SourceBuffer := nil;
  SourceBufferSize := 0;
  SourceBufferCount := 0;

  NeedsRewind := false;

  fVolume := 0;
  SoundEffects.Clear;
  FadeInTime := 0;
end;

function TGenericPlaybackStream.Open(SourceStream: TAudioSourceStream): boolean;
begin
  Result := false;

  Close();

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

  if (not InitFormatConversion()) then
  begin
    // reset decode-stream so it will not be freed on destruction
    Self.SourceStream := nil;
    Exit;
  end;

  SourceBufferSize := SOURCE_BUFFER_FRAMES * SourceStream.GetAudioFormatInfo().FrameSize;
  GetMem(SourceBuffer, SourceBufferSize);
  fVolume := 1.0;

  Result := true;
end;

procedure TGenericPlaybackStream.Close();
begin
  // stop audio-callback on this stream
  Stop();

  // Note: PerformOnClose must be called before SourceStream is invalidated
  PerformOnClose();
  // and free data
  Reset();
end;

procedure TGenericPlaybackStream.LockSampleBuffer();
begin
  SDL_mutexP(InternalLock);
end;

procedure TGenericPlaybackStream.UnlockSampleBuffer();
begin
  SDL_mutexV(InternalLock);
end;

function TGenericPlaybackStream.InitFormatConversion(): boolean;
var
  SrcFormatInfo: TAudioFormatInfo;
  DstFormatInfo: TAudioFormatInfo;
begin
  Result := false;

  SrcFormatInfo := SourceStream.GetAudioFormatInfo();
  DstFormatInfo := GetAudioFormatInfo();

  // TODO: selection should not be done here, use a factory (TAudioConverterFactory) instead 
  {$IF Defined(UseFFmpegResample)}
  Converter := TAudioConverter_FFmpeg.Create();
  {$ELSEIF Defined(UseSRCResample)}
  Converter := TAudioConverter_SRC.Create();
  {$ELSE}
  Converter := TAudioConverter_SDL.Create();
  {$IFEND}

  Result := Converter.Init(SrcFormatInfo, DstFormatInfo);
end;

procedure TGenericPlaybackStream.Play();
var
  Mixer: TAudioMixerStream;
begin
  // only paused streams are not flushed
  if (Status = ssPaused) then
    NeedsRewind := false;

  // rewind if necessary. Cases that require no rewind are:
  // - stream was created and never played
  // - stream was paused and is resumed now
  // - stream was stopped and set to a new position already
  if (NeedsRewind) then
    SetPosition(0);

  // update status
  Status := ssPlaying;

  NeedsRewind := true;

  // add this stream to the mixer
  Mixer := Engine.GetMixer();
  if (Mixer <> nil) then
    Mixer.AddStream(Self);
end;

procedure TGenericPlaybackStream.FadeIn(Time: real; TargetVolume: single);
begin
  FadeInTime := Trunc(Time * 1000);
  FadeInStartTime := SDL_GetTicks();
  FadeInStartVolume := fVolume;
  FadeInTargetVolume := TargetVolume;
  Play();
end;

procedure TGenericPlaybackStream.Pause();
var
  Mixer: TAudioMixerStream;
begin
  if (Status <> ssPlaying) then
    Exit;

  Status := ssPaused;

  Mixer := Engine.GetMixer();
  if (Mixer <> nil) then
    Mixer.RemoveStream(Self);
end;

procedure TGenericPlaybackStream.Stop();
var
  Mixer: TAudioMixerStream;
begin
  if (Status = ssStopped) then
    Exit;

  Status := ssStopped;

  Mixer := Engine.GetMixer();
  if (Mixer <> nil) then
    Mixer.RemoveStream(Self);
end;

function TGenericPlaybackStream.GetLoop(): boolean;
begin
  if assigned(SourceStream) then
    Result := SourceStream.Loop
  else
    Result := false;
end;

procedure TGenericPlaybackStream.SetLoop(Enabled: boolean);
begin
  if assigned(SourceStream) then
    SourceStream.Loop := Enabled;
end;

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

function TGenericPlaybackStream.GetLatency(): double;
begin
  Result := Engine.GetLatency();
end;

function TGenericPlaybackStream.GetStatus(): TStreamStatus;
begin
  Result := Status;
end;

function TGenericPlaybackStream.GetAudioFormatInfo(): TAudioFormatInfo;
begin
  Result := Engine.GetAudioFormatInfo();
end;

procedure TGenericPlaybackStream.FlushBuffers();
begin
  SampleBufferCount := 0;
  SampleBufferPos := 0;
  SourceBufferCount := 0;
end;

procedure TGenericPlaybackStream.ApplySoundEffects(Buffer: PByteArray; BufferSize: integer);
var
  i: integer;
begin
  for i := 0 to SoundEffects.Count-1 do
  begin
    if (SoundEffects[i] <> nil) then
    begin
      TSoundEffect(SoundEffects[i]).Callback(Buffer, BufferSize);
    end;
  end;
end;

function TGenericPlaybackStream.ReadData(Buffer: PByteArray; BufferSize: integer): integer;
var
  ConversionInputCount: integer;
  ConversionOutputSize: integer;   // max. number of converted data (= buffer size)
  ConversionOutputCount: integer;  // actual number of converted data
  SourceSize: integer;
  NeededSampleBufferSize: integer;
  BytesNeeded: integer;
  SourceFormatInfo, OutputFormatInfo: TAudioFormatInfo;
  SourceFrameSize, OutputFrameSize: integer;
  SkipOutputCount: integer;  // number of output-data bytes to skip
  SkipSourceCount: integer;  // number of source-data bytes to skip
  FillCount: integer;  // number of bytes to fill with padding data
  CopyCount: integer;
  PadFrame: PByteArray;
begin
  Result := -1;

  // sanity check for the source-stream
  if (not assigned(SourceStream)) then
    Exit;
  
  SkipOutputCount := 0;
  SkipSourceCount := 0;
  FillCount := 0;

  SourceFormatInfo := SourceStream.GetAudioFormatInfo();
  SourceFrameSize := SourceFormatInfo.FrameSize;
  OutputFormatInfo := GetAudioFormatInfo();
  OutputFrameSize := OutputFormatInfo.FrameSize;

  // synchronize (adjust buffer size)
  BytesNeeded := Synchronize(BufferSize, OutputFormatInfo);
  if (BytesNeeded > BufferSize) then
  begin
    SkipOutputCount := BytesNeeded - BufferSize;
    BytesNeeded := BufferSize;
  end
  else if (BytesNeeded < BufferSize) then
  begin
    FillCount := BufferSize - BytesNeeded;
  end;

  // lock access to sample-buffer
  LockSampleBuffer();
  try

    // skip sample-buffer data
    SampleBufferPos := SampleBufferPos + SkipOutputCount;
    // size of available bytes in SampleBuffer after skipping
    SampleBufferCount := SampleBufferCount - SampleBufferPos;
    // update byte skip-count
    SkipOutputCount := -SampleBufferCount;

    // now that we skipped all buffered data from the last pass, we have to skip
    // data directly after fetching it from the source-stream.
    if (SkipOutputCount > 0) then
    begin
      SampleBufferCount := 0;
      // convert skip-count to source-format units and resize to a multiple of
      // the source frame-size.
      SkipSourceCount := Round((SkipOutputCount * OutputFormatInfo.GetRatio(SourceFormatInfo)) /
                               SourceFrameSize) * SourceFrameSize;
      SkipOutputCount := 0;
    end;

    // copy data to front of buffer
    if ((SampleBufferCount > 0) and (SampleBufferPos > 0)) then
      Move(SampleBuffer[SampleBufferPos], SampleBuffer[0], SampleBufferCount);
    SampleBufferPos := 0;

    // resize buffer to a reasonable size
    if (BufferSize > SampleBufferCount) then
    begin
      // Note: use BufferSize instead of BytesNeeded to minimize the need for resizing
      SampleBufferSize := BufferSize;
      ReallocMem(SampleBuffer, SampleBufferSize);
      if (not assigned(SampleBuffer)) then
        Exit;
    end;

    // fill sample-buffer (fetch and convert one block of source data per loop)
    while (SampleBufferCount < BytesNeeded) do
    begin
      // move remaining source data from the previous pass to front of buffer
      if (SourceBufferCount > 0) then
      begin
        Move(SourceBuffer[SourceBufferSize-SourceBufferCount],
             SourceBuffer[0],
             SourceBufferCount);
      end;

      SourceSize := SourceStream.ReadData(
          @SourceBuffer[SourceBufferCount], SourceBufferSize-SourceBufferCount);
      // break on error (-1) or if no data is available (0), e.g. while seeking
      if (SourceSize <= 0) then
      begin
        // if we do not have data -> exit
        if (SourceBufferCount = 0) then
        begin
          FlushBuffers();
          Exit;
        end;
        // if we have some data, stop retrieving data from the source stream
        // and use the data we have so far
        Break;
      end;

      SourceBufferCount := SourceBufferCount + SourceSize;

      // end-of-file reached -> stop playback
      if (SourceStream.EOF) then
      begin
        if (Loop) then
          SourceStream.Position := 0
        else
          Stop();
      end;

      if (SkipSourceCount > 0) then
      begin
        // skip data and update source buffer count
        SourceBufferCount := SourceBufferCount - SkipSourceCount;
        SkipSourceCount := -SourceBufferCount;
        // continue with next pass if we skipped all data
        if (SourceBufferCount <= 0) then
        begin
          SourceBufferCount := 0;
          Continue;
        end;
      end;

      // calc buffer size (might be bigger than actual resampled byte count)
      ConversionOutputSize := Converter.GetOutputBufferSize(SourceBufferCount);
      NeededSampleBufferSize := SampleBufferCount + ConversionOutputSize;

      // resize buffer if necessary
      if (SampleBufferSize < NeededSampleBufferSize) then
      begin
        SampleBufferSize := NeededSampleBufferSize;
        ReallocMem(SampleBuffer, SampleBufferSize);
        if (not assigned(SampleBuffer)) then
        begin
          FlushBuffers();
          Exit;
        end;
      end;

      // resample source data (Note: ConversionInputCount might be adjusted by Convert())
      ConversionInputCount := SourceBufferCount;
      ConversionOutputCount := Converter.Convert(
          SourceBuffer, @SampleBuffer[SampleBufferCount], ConversionInputCount);
      if (ConversionOutputCount = -1) then
      begin
        FlushBuffers();
        Exit;
      end;

      // adjust sample- and source-buffer count by the number of converted bytes
      SampleBufferCount := SampleBufferCount + ConversionOutputCount;
      SourceBufferCount := SourceBufferCount - ConversionInputCount;
    end;

    // apply effects
    ApplySoundEffects(SampleBuffer, SampleBufferCount);

    // copy data to result buffer
    CopyCount := Min(BytesNeeded, SampleBufferCount);
    Move(SampleBuffer[0], Buffer[BufferSize - BytesNeeded], CopyCount);
    Dec(BytesNeeded, CopyCount);
    SampleBufferPos := CopyCount;

  // release buffer lock
  finally
    UnlockSampleBuffer();
  end;

  // pad the buffer with the last frame if we are to fast
  if (FillCount > 0) then
  begin
    if (CopyCount >= OutputFrameSize) then
      PadFrame := @Buffer[CopyCount-OutputFrameSize]
    else
      PadFrame := nil;
    FillBufferWithFrame(@Buffer[CopyCount], FillCount,
                        PadFrame, OutputFrameSize);
  end;

  // BytesNeeded now contains the number of remaining bytes we were not able to fetch
  Result := BufferSize - BytesNeeded;
end;

function TGenericPlaybackStream.GetPCMData(var Data: TPCMData): Cardinal;
var
  ByteCount: integer;
begin
  Result := 0;

  // just SInt16 stereo support for now
  if ((Engine.GetAudioFormatInfo().Format <> asfS16) or
      (Engine.GetAudioFormatInfo().Channels <> 2)) then
  begin
    Exit;
  end;

  // zero memory
  FillChar(Data, SizeOf(Data), 0);

  // TODO: At the moment just the first samples of the SampleBuffer
  // are returned, even if there is newer data in the upper samples.

  LockSampleBuffer();
  ByteCount := Min(SizeOf(Data), SampleBufferCount);
  if (ByteCount > 0) then
  begin
    Move(SampleBuffer[0], Data, ByteCount);
  end;
  UnlockSampleBuffer();
  
  Result := ByteCount div SizeOf(TPCMStereoSample);
end;

procedure TGenericPlaybackStream.GetFFTData(var Data: TFFTData);
var
  i: integer;
  Frames: integer;
  DataIn: PSingleArray;
  AudioFormat: TAudioFormatInfo;
begin
  // only works with SInt16 and Float values at the moment
  AudioFormat := GetAudioFormatInfo();

  DataIn := AllocMem(FFTSize * SizeOf(Single));
  if (DataIn = nil) then
    Exit;

  LockSampleBuffer();
  // TODO: We just use the first Frames frames, the others are ignored.
  Frames := Min(FFTSize, SampleBufferCount div AudioFormat.FrameSize);
  // use only first channel and convert data to float-values
  case AudioFormat.Format of
    asfS16:
    begin
      for i := 0 to Frames-1 do
        DataIn[i] := PSmallInt(@SampleBuffer[i*AudioFormat.FrameSize])^ / -Low(SmallInt);
    end;
    asfFloat:
    begin
      for i := 0 to Frames-1 do
        DataIn[i] := PSingle(@SampleBuffer[i*AudioFormat.FrameSize])^;
    end;
  end;
  UnlockSampleBuffer();

  WindowFunc(fwfHanning, FFTSize, DataIn);
  PowerSpectrum(FFTSize, DataIn, @Data);
  FreeMem(DataIn);

  // resize data to a 0..1 range
  for i := 0 to High(TFFTData) do
  begin
    Data[i] := Sqrt(Data[i]) / 100;
  end;
end;

procedure TGenericPlaybackStream.AddSoundEffect(Effect: TSoundEffect);
begin
  if (not assigned(Effect)) then
    Exit;

  LockSampleBuffer();
  // check if effect is already in list to avoid duplicates
  if (SoundEffects.IndexOf(Pointer(Effect)) = -1) then
    SoundEffects.Add(Pointer(Effect));
  UnlockSampleBuffer();
end;

procedure TGenericPlaybackStream.RemoveSoundEffect(Effect: TSoundEffect);
begin
  LockSampleBuffer();
  SoundEffects.Remove(Effect);
  UnlockSampleBuffer();
end;

function TGenericPlaybackStream.GetPosition: real;
var
  BufferedTime: double;
begin
  if assigned(SourceStream) then
  begin
    LockSampleBuffer();

    // calc the time of source data that is buffered (in the SampleBuffer and SourceBuffer)
    // but not yet outputed
    BufferedTime := (SampleBufferCount - SampleBufferPos) / Engine.FormatInfo.BytesPerSec +
                    SourceBufferCount / SourceStream.GetAudioFormatInfo().BytesPerSec;
    // and subtract it from the source position
    Result := SourceStream.Position - BufferedTime;

    UnlockSampleBuffer();
  end
  else
  begin
    Result := -1;
  end;
end;

procedure TGenericPlaybackStream.SetPosition(Time: real);
begin
  if assigned(SourceStream) then
  begin
    LockSampleBuffer();

    SourceStream.Position := Time;
    if (Status = ssStopped) then
      NeedsRewind := false;
    // do not use outdated data
    FlushBuffers();

    AvgSyncDiff := -1;
    
    UnlockSampleBuffer();
  end;
end;

function TGenericPlaybackStream.GetVolume(): single;
var
  FadeAmount: Single;
begin
  LockSampleBuffer();
  // adjust volume if fading is enabled
  if (FadeInTime > 0) then
  begin
    FadeAmount := (SDL_GetTicks() - FadeInStartTime) / FadeInTime;
    // check if fade-target is reached
    if (FadeAmount >= 1) then
    begin
      // target reached -> stop fading
      FadeInTime := 0;
      fVolume := FadeInTargetVolume;
    end
    else
    begin
      // fading in progress
      fVolume := FadeAmount*FadeInTargetVolume + (1-FadeAmount)*FadeInStartVolume;
    end;
  end;
  // return current volume
  Result := fVolume;
  UnlockSampleBuffer();
end;

procedure TGenericPlaybackStream.SetVolume(Volume: single);
begin
  LockSampleBuffer();
  // stop fading
  FadeInTime := 0;
  // clamp volume
  if (Volume > 1.0) then
    fVolume := 1.0
  else if (Volume < 0) then
    fVolume := 0
  else
    fVolume := Volume;
  UnlockSampleBuffer();
end;


{ TGenericVoiceStream }

constructor TGenericVoiceStream.Create(Engine: TAudioPlayback_SoftMixer);
begin
  inherited Create();
  Self.Engine := Engine;
end;

function TGenericVoiceStream.Open(ChannelMap: integer; FormatInfo: TAudioFormatInfo): boolean;
var
  BufferSize: integer;
begin
  Result := false;

  Close();

  if (not inherited Open(ChannelMap, FormatInfo)) then
    Exit;

  // Note:
  // - use Self.FormatInfo instead of FormatInfo as the latter one might have a
  //   channel size of 2.
  // - the buffer-size must be a multiple of the FrameSize
  BufferSize := (Ceil(MAX_VOICE_DELAY * Self.FormatInfo.BytesPerSec) div Self.FormatInfo.FrameSize) *
                Self.FormatInfo.FrameSize;
  VoiceBuffer := TRingBuffer.Create(BufferSize);

  BufferLock := SDL_CreateMutex();


  // create a matching playback stream for the voice-stream
  PlaybackStream := TGenericPlaybackStream.Create(Engine);
  // link voice- and playback-stream
  if (not PlaybackStream.Open(Self)) then
  begin
    PlaybackStream.Free;
    Exit;
  end;

  // start voice passthrough
  PlaybackStream.Play();

  Result := true;
end;

procedure TGenericVoiceStream.Close();
begin
  // stop and free the playback stream
  FreeAndNil(PlaybackStream);

  // free data
  FreeAndNil(VoiceBuffer);
  if (BufferLock <> nil) then
    SDL_DestroyMutex(BufferLock);

  inherited Close();
end;

procedure TGenericVoiceStream.WriteData(Buffer: PByteArray; BufferSize: integer);
begin
  // lock access to buffer
  SDL_mutexP(BufferLock);
  try
    if (VoiceBuffer = nil) then
      Exit;
    VoiceBuffer.Write(Buffer, BufferSize);
  finally
    SDL_mutexV(BufferLock);
  end;
end;

function TGenericVoiceStream.ReadData(Buffer: PByteArray; BufferSize: integer): integer;
begin
  Result := -1;

  // lock access to buffer
  SDL_mutexP(BufferLock);
  try
    if (VoiceBuffer = nil) then
      Exit;
    Result := VoiceBuffer.Read(Buffer, BufferSize);
  finally
    SDL_mutexV(BufferLock);
  end;
end;

function TGenericVoiceStream.IsEOF(): boolean;
begin
  SDL_mutexP(BufferLock);
  Result := (VoiceBuffer = nil);
  SDL_mutexV(BufferLock);
end;

function TGenericVoiceStream.IsError(): boolean;
begin
  Result := false;
end;


{ TAudioPlayback_SoftMixer }

function TAudioPlayback_SoftMixer.InitializePlayback: boolean;
begin
  Result := false;

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

  if(not InitializeAudioPlaybackEngine()) then
    Exit;

  MixerStream := TAudioMixerStream.Create(Self);

  if(not StartAudioPlaybackEngine()) then
    Exit;

  Result := true;
end;

function TAudioPlayback_SoftMixer.FinalizePlayback: boolean;
begin
  Close;
  StopAudioPlaybackEngine();

  FreeAndNil(MixerStream);
  FreeAndNil(FormatInfo);

  FinalizeAudioPlaybackEngine();
  inherited FinalizePlayback;
  Result := true;
end;

procedure TAudioPlayback_SoftMixer.AudioCallback(Buffer: PByteArray; Size: integer);
begin
  MixerStream.ReadData(Buffer, Size);
end;

function TAudioPlayback_SoftMixer.GetMixer(): TAudioMixerStream;
begin
  Result := MixerStream;
end;

function TAudioPlayback_SoftMixer.GetAudioFormatInfo(): TAudioFormatInfo;
begin
  Result := FormatInfo;
end;

function TAudioPlayback_SoftMixer.CreatePlaybackStream(): TAudioPlaybackStream;
begin
  Result := TGenericPlaybackStream.Create(Self);
end;

function TAudioPlayback_SoftMixer.CreateVoiceStream(ChannelMap: integer; FormatInfo: TAudioFormatInfo): TAudioVoiceStream;
var
  VoiceStream: TGenericVoiceStream;
begin
  Result := nil;

  // create a voice stream
  VoiceStream := TGenericVoiceStream.Create(Self);
  if (not VoiceStream.Open(ChannelMap, FormatInfo)) then
  begin
    VoiceStream.Free;
    Exit;
  end;

  Result := VoiceStream;
end;

procedure TAudioPlayback_SoftMixer.SetAppVolume(Volume: single);
begin
  // sets volume only for this application
  MixerStream.Volume := Volume;
end;

procedure TAudioPlayback_SoftMixer.MixBuffers(DstBuffer, SrcBuffer: PByteArray; Size: Cardinal; Volume: Single);
var
  SampleIndex: Cardinal;
  SampleInt: Integer;
  SampleFlt: Single;
begin
  SampleIndex := 0;
  case FormatInfo.Format of
    asfS16:
    begin
      while (SampleIndex < Size) do
      begin
        // apply volume and sum with previous mixer value
        SampleInt := PSmallInt(@DstBuffer[SampleIndex])^ +
                     Round(PSmallInt(@SrcBuffer[SampleIndex])^ * Volume);
        // clip result
        if (SampleInt > High(SmallInt)) then
          SampleInt := High(SmallInt)
        else if (SampleInt < Low(SmallInt)) then
          SampleInt := Low(SmallInt);
        // assign result
        PSmallInt(@DstBuffer[SampleIndex])^ := SampleInt;
        // increase index by one sample
        Inc(SampleIndex, SizeOf(SmallInt));
      end;
    end;
    asfFloat:
    begin
      while (SampleIndex < Size) do
      begin
        // apply volume and sum with previous mixer value
        SampleFlt := PSingle(@DstBuffer[SampleIndex])^ +
                     PSingle(@SrcBuffer[SampleIndex])^ * Volume;
        // clip result
        if (SampleFlt > 1.0) then
          SampleFlt := 1.0
        else if (SampleFlt < -1.0) then
          SampleFlt := -1.0;
        // assign result
        PSingle(@DstBuffer[SampleIndex])^ := SampleFlt;
        // increase index by one sample
        Inc(SampleIndex, SizeOf(Single));
      end;
    end;
    else
    begin
      Log.LogError('Incompatible format', 'TAudioMixerStream.MixAudio');
    end;
  end;
end;

end.