-
Notifications
You must be signed in to change notification settings - Fork 459
/
Copy pathAudioExtrasSource.cs
610 lines (537 loc) · 24 KB
/
AudioExtrasSource.cs
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
//-----------------------------------------------------------------------------
// Filename: AudioExtrasSource.cs
//
// Description: Implements an audio source that can generate samples from a
// variety of non-live sources. For examples signal generators or reading
// samples from files.
//
// Author(s):
// Aaron Clauson (aaron@sipsorcery.com)
//
// History:
// 19 Mar 2020 Aaron Clauson Created, Dublin, Ireland.
// 21 Apr 2020 Aaron Clauson Added alaw and mulaw decode classes.
// 31 May 2020 Aaron Clauson Refactored codecs and signal generator to
// separate class files.
// 19 Aug 2020 Aaron Clauson Renamed from RtpAudioSession to
// AudioExtrasSource.
//
// License:
// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SIPSorceryMedia.Abstractions;
namespace SIPSorcery.Media
{
public enum AudioSourcesEnum
{
/// <summary>
/// Plays music samples from a file. The file will be played in a loop until
/// another source option is set.
/// </summary>
Music = 0,
/// <summary>
/// Send an audio stream of silence. Note this option does result
/// in audio RTP packet getting sent.
/// </summary>
Silence = 1,
/// <summary>
/// White noise static.
/// </summary>
WhiteNoise = 2,
/// <summary>
/// A continuous sine wave.
/// </summary>
SineWave = 3,
/// <summary>
/// Pink noise static.
/// </summary>
PinkNoise = 4,
/// <summary>
/// Don't generate any audio samples.
/// </summary>
None = 5,
}
public class AudioSourceOptions
{
/// <summary>
/// The type of audio source to use.
/// </summary>
public AudioSourcesEnum AudioSource;
/// <summary>
/// The sampling rate used to generate the input or if the source is
/// being generated the sample rate to generate it at.
/// </summary>
public AudioSamplingRatesEnum MusicInputSamplingRate = AudioSamplingRatesEnum.Rate8KHz;
/// <summary>
/// If the audio source is set to music this must be the path to a raw PCM 8K sampled file.
/// If set to null or the file doesn't exist the default embedded resource music file will
/// be used.
/// </summary>
public string MusicFile;
}
/// <summary>
/// An audio source implementation that provides a diverse range of audio source options.
/// The available options encompass signal generation, playback from file and more.
/// </summary>
public class AudioExtrasSource : IAudioSource
{
public const int AUDIO_SAMPLE_PERIOD_MILLISECONDS_DEFAULT = 20;
public const int AUDIO_SAMPLE_PERIOD_MILLISECONDS_MIN = 20;
public const int AUDIO_SAMPLE_PERIOD_MILLISECONDS_MAX = 500;
private const string MUSIC_RESOURCE_PATH = "SIPSorcery.media.Macroform_-_Simplicity.raw";
private static float LINEAR_MAXIMUM = 32767f;
private static ILogger Log = SIPSorcery.Sys.Log.Logger;
private MediaFormatManager<AudioFormat> _audioFormatManager;
private BinaryReader _musicStreamReader;
private SignalGenerator _signalGenerator;
private Timer _sendSampleTimer;
private AudioSourceOptions _audioOpts;
private bool _isStarted;
private bool _isPaused;
private bool _isClosed;
private IAudioEncoder _audioEncoder;
// Fields for interrupting the main audio source with a different stream. For example playing
// an announcement over music etc.
private Timer _streamSourceTimer;
private BinaryReader _streamSourceReader;
private bool _streamSendInProgress; // When a send for stream is in progress it takes precedence over the existing audio source.
private AudioSamplingRatesEnum _streamSourceRate = AudioSamplingRatesEnum.Rate8KHz;
/// <summary>
/// Fires when the current send audio from stream operation completes. Send from
/// stream operations are intended to be short snippets of audio that get sent
/// as interruptions to the primary audio stream.
/// </summary>
public event Action OnSendFromAudioStreamComplete;
public event EncodedSampleDelegate OnAudioSourceEncodedSample;
/// <summary>
/// This audio source DOES NOT generate raw samples. Subscribe to the encoded samples event
/// to get samples ready for passing to the RTP transport layer.
/// </summary>
[Obsolete("This audio source only produces encoded samples. Do not subscribe to this event.")]
public event RawAudioSampleDelegate OnAudioSourceRawSample { add { } remove { } }
#pragma warning disable CS0067
public event SourceErrorDelegate OnAudioSourceError;
public event SourceErrorDelegate OnAudioSinkError;
#pragma warning restore CS0067
public AudioExtrasSource()
{
_audioEncoder = new AudioEncoder();
_audioFormatManager = new MediaFormatManager<AudioFormat>(_audioEncoder.SupportedFormats);
_audioOpts = new AudioSourceOptions { AudioSource = AudioSourcesEnum.None };
}
public int _audioSamplePeriodMilliseconds = AUDIO_SAMPLE_PERIOD_MILLISECONDS_DEFAULT;
public int AudioSamplePeriodMilliseconds
{
get => _audioSamplePeriodMilliseconds;
set
{
if (value < AUDIO_SAMPLE_PERIOD_MILLISECONDS_MIN || value > AUDIO_SAMPLE_PERIOD_MILLISECONDS_MAX)
{
throw new ApplicationException("Invalid value for the audio sample period. Must be between " +
$"{AUDIO_SAMPLE_PERIOD_MILLISECONDS_MIN} and {AUDIO_SAMPLE_PERIOD_MILLISECONDS_MAX}ms.");
}
else
{
_audioSamplePeriodMilliseconds = value;
}
}
}
/// <summary>
/// Instantiates an audio source that can generate output samples from a variety of different
/// non-live sources.
/// </summary>
/// <param name="audioOptions">Optional. The options that determine the type of audio to stream to the remote party.
/// Example type of audio sources are music, silence, white noise etc.</param>
public AudioExtrasSource(
IAudioEncoder audioEncoder,
AudioSourceOptions audioOptions = null)
{
_audioEncoder = audioEncoder;
_audioFormatManager = new MediaFormatManager<AudioFormat>(_audioEncoder.SupportedFormats);
_audioOpts = audioOptions ?? new AudioSourceOptions { AudioSource = AudioSourcesEnum.None };
}
public void ExternalAudioSourceRawSample(AudioSamplingRatesEnum samplingRate, uint durationMilliseconds, short[] sample) =>
throw new NotImplementedException();
public bool HasEncodedAudioSubscribers() => OnAudioSourceEncodedSample != null;
public bool IsAudioSourcePaused() => _isPaused;
public void RestrictFormats(Func<AudioFormat, bool> filter) => _audioFormatManager.RestrictFormats(filter);
public List<AudioFormat> GetAudioSourceFormats() => _audioFormatManager.GetSourceFormats();
public void SetAudioSourceFormat(AudioFormat audioFormat) => _audioFormatManager.SetSelectedFormat(audioFormat);
public Task CloseAudio()
{
if (!_isClosed)
{
_isClosed = true;
_sendSampleTimer?.Dispose();
_musicStreamReader?.Close();
StopSendFromAudioStream();
}
return Task.CompletedTask;
}
/// <summary>
/// Initialises the audio source as required.
/// </summary>
public Task StartAudio()
{
if (_audioFormatManager.SelectedFormat.IsEmpty())
{
throw new ApplicationException("The sending format for the Audio Extras Source has not been set. Cannot start source.");
}
else
{
if (!_isStarted)
{
_isStarted = true;
SetSource(_audioOpts);
}
return Task.CompletedTask;
}
}
public Task PauseAudio()
{
_isPaused = true;
return Task.CompletedTask;
}
public Task ResumeAudio()
{
_isPaused = false;
return Task.CompletedTask;
}
/// <summary>
/// Attempts to send audio samples from a stream, typically a file, input.
/// </summary>
/// <param name="audioStream">The stream containing the 16 bit PCM sampled at either 8 or 16Khz
/// to send to the remote party.</param>
/// <param name="streamSampleRate">The sample rate of the supplied PCM samples. Supported rates are
/// 8 or 16 KHz.</param>
/// <returns>A task that completes once the stream has been fully sent.</returns>
public Task SendAudioFromStream(Stream audioStream, AudioSamplingRatesEnum streamSampleRate)
{
if (!_isClosed && audioStream != null && audioStream.Length > 0)
{
// Stop any existing send from stream operation.
StopSendFromAudioStream();
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
Action handler = null;
handler = () =>
{
tcs.TrySetResult(true);
OnSendFromAudioStreamComplete -= handler;
};
OnSendFromAudioStreamComplete += handler;
InitialiseSendAudioFromStreamTimer(audioStream, streamSampleRate);
_streamSourceTimer.Change(_audioSamplePeriodMilliseconds, _audioSamplePeriodMilliseconds);
return tcs.Task;
}
else
{
return Task.CompletedTask;
}
}
/// <summary>
/// Cancels an in-progress send audio from stream operation.
/// </summary>
public void CancelSendAudioFromStream()
{
StopSendFromAudioStream();
}
/// <summary>
/// Convenience method for audio sources when only default options are required,
/// e.g. the default music file rather than a custom one.
/// </summary>
/// <param name="audioSource">The audio source to set. The call will fail
/// if the source requires additional options, e.g. stream from file.</param>
public void SetSource(AudioSourcesEnum audioSource)
{
SetSource(new AudioSourceOptions { AudioSource = audioSource });
}
/// <summary>
/// Sets the source for the session. Overrides any existing source.
/// </summary>
/// <param name="sourceOptions">The new audio source.</param>
public void SetSource(AudioSourceOptions sourceOptions)
{
if (!_isStarted)
{
// Audio source is being adjusted prior to starting.
_audioOpts = sourceOptions;
}
else
{
// If required start the audio source.
if (sourceOptions != null)
{
_sendSampleTimer?.Dispose();
_musicStreamReader?.Close();
StopSendFromAudioStream();
_audioOpts = sourceOptions;
if (_audioOpts.AudioSource == AudioSourcesEnum.None)
{
// Do nothing, all other sources have already been stopped.
}
else if (_audioOpts.AudioSource == AudioSourcesEnum.Silence)
{
_sendSampleTimer = new Timer(SendSilenceSample, null, 0, _audioSamplePeriodMilliseconds);
}
else if (_audioOpts.AudioSource == AudioSourcesEnum.PinkNoise ||
_audioOpts.AudioSource == AudioSourcesEnum.WhiteNoise ||
_audioOpts.AudioSource == AudioSourcesEnum.SineWave)
{
_signalGenerator = new SignalGenerator(_audioFormatManager.SelectedFormat.ClockRate, 1);
switch (_audioOpts.AudioSource)
{
case AudioSourcesEnum.PinkNoise:
_signalGenerator.Type = SignalGeneratorType.Pink;
break;
case AudioSourcesEnum.SineWave:
_signalGenerator.Type = SignalGeneratorType.Sin;
break;
case AudioSourcesEnum.WhiteNoise:
default:
_signalGenerator.Type = SignalGeneratorType.White;
break;
}
_sendSampleTimer = new Timer(SendSignalGeneratorSample, null, 0, _audioSamplePeriodMilliseconds);
}
else if (_audioOpts.AudioSource == AudioSourcesEnum.Music)
{
if (string.IsNullOrWhiteSpace(_audioOpts.MusicFile) || !File.Exists(_audioOpts.MusicFile))
{
if (!string.IsNullOrWhiteSpace(_audioOpts.MusicFile))
{
Log.LogWarning("Music file not set or not found, using default music resource.");
}
var assem = typeof(VideoTestPatternSource).GetTypeInfo().Assembly;
var audioStream = assem.GetManifestResourceStream(MUSIC_RESOURCE_PATH);
_musicStreamReader = new BinaryReader(audioStream);
}
else
{
_musicStreamReader = new BinaryReader(new FileStream(_audioOpts.MusicFile, FileMode.Open, FileAccess.Read));
}
_sendSampleTimer = new Timer(SendMusicSample, null, 0, _audioSamplePeriodMilliseconds);
}
}
}
}
/// <summary>
/// Sends a stream containing 16 bit PCM audio to the remote party. Calling this method
/// will pause the existing audio source until the stream has been sent.
/// </summary>
/// <param name="audioStream">The stream containing the 16 bit PCM, sampled at either 8 or 16 Khz,
/// to send to the remote party.</param>
/// <param name="streamSampleRate">The sample rate of the supplied PCM samples. Supported rates are
/// 8 or 16 KHz.</param>
private void InitialiseSendAudioFromStreamTimer(Stream audioStream, AudioSamplingRatesEnum streamSampleRate)
{
if (!_isClosed && audioStream != null && audioStream.Length > 0)
{
Log.LogDebug("Sending audio stream length {AudioStreamLength}.", audioStream.Length);
_streamSendInProgress = true;
_streamSourceRate = streamSampleRate;
_streamSourceReader = new BinaryReader(audioStream);
_streamSourceTimer = new Timer(SendStreamSample, null, Timeout.Infinite, Timeout.Infinite);
}
}
/// <summary>
/// Sends audio samples read from a file.
/// </summary>
private void SendMusicSample(object state)
{
try
{
if (!_isClosed && !_streamSendInProgress && _musicStreamReader != null)
{
lock (_musicStreamReader)
{
var pcm = GetPcmSampleFromReader(_musicStreamReader, _audioOpts.MusicInputSamplingRate, out int samplesRead);
if (samplesRead > 0)
{
EncodeAndSend(pcm, (int)_audioOpts.MusicInputSamplingRate);
}
if (samplesRead == 0)
{
_musicStreamReader.BaseStream.Position = 0;
}
}
}
}
catch (Exception e)
{
Log.LogWarning(e, "Stream Closed.");
}
}
/// <summary>
/// Sends the sounds of silence.
/// </summary>
private void SendSilenceSample(object state)
{
try
{
if (!_isClosed && !_streamSendInProgress && _sendSampleTimer != null)
{
lock (_sendSampleTimer)
{
short[] silencePcm = new short[_audioFormatManager.SelectedFormat.ClockRate / 1000 * _audioSamplePeriodMilliseconds];
EncodeAndSend(silencePcm, _audioFormatManager.SelectedFormat.ClockRate);
}
}
}
catch (Exception e)
{
Log.LogError(e, "Exception sending silence sample");
}
}
/// <summary>
/// Sends a sample from a signal generator generated waveform.
/// </summary>
private void SendSignalGeneratorSample(object state)
{
try
{
if (!_isClosed && !_streamSendInProgress && _sendSampleTimer != null)
{
lock (_sendSampleTimer)
{
// Get the signal generator to generate the samples and then convert from signed linear to PCM.
float[] linear = new float[_audioFormatManager.SelectedFormat.ClockRate / 1000 * _audioSamplePeriodMilliseconds];
_signalGenerator.Read(linear, 0, linear.Length);
short[] pcm = linear.Select(x => (short)(x * LINEAR_MAXIMUM)).ToArray();
EncodeAndSend(pcm, _audioFormatManager.SelectedFormat.ClockRate);
}
}
}
catch (Exception e)
{
Log.LogError(e, "Exception sending signal generator sample");
}
}
/// <summary>
/// Sends audio samples read from a file containing 16 bit PCM samples.
/// </summary>
private void SendStreamSample(object state)
{
if (!_isClosed && _streamSourceReader != null)
{
try
{
lock (_streamSourceReader)
{
if (_streamSourceReader?.BaseStream?.CanRead == true)
{
var pcm = GetPcmSampleFromReader(_streamSourceReader, _streamSourceRate, out int samplesRead);
if (samplesRead > 0)
{
EncodeAndSend(pcm, (int)_streamSourceRate);
if (_streamSourceReader.BaseStream.Position >= _streamSourceReader.BaseStream.Length)
{
Log.LogDebug("Send audio from stream completed.");
StopSendFromAudioStream();
}
}
else
{
Log.LogWarning("Failed to read from audio stream source.");
StopSendFromAudioStream();
}
}
else
{
Log.LogWarning("Failed to read from audio stream source, stream null or closed.");
StopSendFromAudioStream();
}
}
}
catch (Exception e)
{
Log.LogWarning(e, "Caught unhandled exception");
StopSendFromAudioStream();
}
if (!_streamSendInProgress)
{
try
{
// An error has occurred or a request has been made to stop the stream.
if (_streamSourceReader != null)
{
_streamSourceReader.Close();
}
}
catch (Exception e)
{
Log.LogWarning(e, "Error occurred whilst trying to close the stream source reader.");
}
}
}
}
private short[] GetPcmSampleFromReader(BinaryReader binaryReader, AudioSamplingRatesEnum inputSampleRate, out int samplesRead)
{
samplesRead = 0;
if (binaryReader?.BaseStream?.CanRead == true)
{
int sampleRate = (int)inputSampleRate;
int sampleSize = sampleRate / 1000 * _audioSamplePeriodMilliseconds;
short[] pcm = new short[sampleSize];
for (int i = 0; i < sampleSize && binaryReader.BaseStream.Position < binaryReader.BaseStream.Length; i++)
{
pcm[samplesRead++] = binaryReader.ReadInt16();
}
return pcm;
}
return null;
}
private void EncodeAndSend(short[] pcm, int pcmSampleRate)
{
if (pcm.Length > 0)
{
if (pcmSampleRate != _audioFormatManager.SelectedFormat.ClockRate)
{
pcm = PcmResampler.Resample(pcm, pcmSampleRate, _audioFormatManager.SelectedFormat.ClockRate);
}
byte[] encodedSample = _audioEncoder.EncodeAudio(pcm, _audioFormatManager.SelectedFormat);
uint rtpUnits = (uint)(_audioFormatManager.SelectedFormat.RtpClockRate / 1000 * _audioSamplePeriodMilliseconds);
OnAudioSourceEncodedSample?.Invoke(rtpUnits, encodedSample);
}
}
/// <summary>
/// Stops a send from audio stream job.
/// </summary>
private void StopSendFromAudioStream()
{
if (_streamSendInProgress)
{
lock (_streamSourceTimer)
{
_streamSourceTimer?.Dispose();
_streamSendInProgress = false;
OnSendFromAudioStreamComplete?.Invoke();
}
}
}
public void Close()
{
if (_streamSourceReader != null)
{
lock (_streamSourceReader)
{
_streamSourceReader.Close();
}
}
if (_musicStreamReader != null)
{
lock (_musicStreamReader)
{
_musicStreamReader.Close();
}
}
}
}
}