/
audiooutputbase.cpp
1762 lines (1512 loc) · 51.9 KB
/
audiooutputbase.cpp
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
// Std C headers
#include <cmath>
#include <limits>
// POSIX headers
#include <unistd.h>
#include <sys/time.h>
// Qt headers
#include <QMutexLocker>
// MythTV headers
#include "compat.h"
#include "audiooutputbase.h"
#include "audiooutputdigitalencoder.h"
#include "audiooutpututil.h"
#include "audiooutputdownmix.h"
#include "SoundTouch.h"
#include "freesurround.h"
#include "spdifencoder.h"
#include "mythlogging.h"
#define LOC QString("AO: ")
#define WPOS audiobuffer + org_waud
#define RPOS audiobuffer + raud
#define ABUF audiobuffer
#define STST soundtouch::SAMPLETYPE
#define AOALIGN(x) (((long)&x + 15) & ~0xf);
// 1,2,5 and 7 channels are currently valid for upmixing if required
#define UPMIX_CHANNEL_MASK ((1<<1)|(1<<2)|(1<<5)|1<<7)
#define IS_VALID_UPMIX_CHANNEL(ch) ((1 << (ch)) & UPMIX_CHANNEL_MASK)
const char *AudioOutputBase::quality_string(int q)
{
switch(q)
{
case QUALITY_DISABLED: return "disabled";
case QUALITY_LOW: return "low";
case QUALITY_MEDIUM: return "medium";
case QUALITY_HIGH: return "high";
default: return "unknown";
}
}
AudioOutputBase::AudioOutputBase(const AudioSettings &settings) :
MThread("AudioOutputBase"),
// protected
channels(-1), codec(CODEC_ID_NONE),
bytes_per_frame(0), output_bytes_per_frame(0),
format(FORMAT_NONE), output_format(FORMAT_NONE),
samplerate(-1), effdsp(0),
fragment_size(0), soundcard_buffer_size(0),
main_device(settings.GetMainDevice()),
passthru_device(settings.GetPassthruDevice()),
m_discretedigital(false), passthru(false),
enc(false), reenc(false),
stretchfactor(1.0f),
eff_stretchfactor(100000),
source(settings.source), killaudio(false),
pauseaudio(false), actually_paused(false),
was_paused(false), unpause_when_ready(false),
set_initial_vol(settings.set_initial_vol),
buffer_output_data_for_use(false),
configured_channels(0),
max_channels(0),
src_quality(QUALITY_MEDIUM),
// private
output_settingsraw(NULL), output_settings(NULL),
output_settingsdigitalraw(NULL), output_settingsdigital(NULL),
need_resampler(false), src_ctx(NULL),
pSoundStretch(NULL),
encoder(NULL), upmixer(NULL),
source_channels(-1), source_samplerate(0),
source_bytes_per_frame(0), upmix_default(false),
needs_upmix(false), needs_downmix(false),
surround_mode(QUALITY_LOW), old_stretchfactor(1.0f),
volume(80), volumeControl(QString()),
processing(false),
frames_buffered(0),
audio_thread_exists(false),
audiotime(0),
raud(0), waud(0),
audbuf_timecode(0),
killAudioLock(QMutex::NonRecursive),
current_seconds(-1), source_bitrate(-1),
memory_corruption_test0(0xdeadbeef),
memory_corruption_test1(0xdeadbeef),
src_out(NULL), kAudioSRCOutputSize(0),
memory_corruption_test2(0xdeadbeef),
memory_corruption_test3(0xdeadbeef),
m_configure_succeeded(true),m_length_last_data(0),
m_spdifenc(NULL)
{
src_in = (float *)AOALIGN(src_in_buf);
memset(&src_data, 0, sizeof(SRC_DATA));
memset(src_in_buf, 0, sizeof(src_in_buf));
memset(audiobuffer, 0, sizeof(audiobuffer));
// Handle override of SRC quality settings
if (gCoreContext->GetNumSetting("SRCQualityOverride", false))
{
src_quality = gCoreContext->GetNumSetting("SRCQuality", QUALITY_MEDIUM);
// Extra test to keep backward compatibility with earlier SRC setting
if (src_quality > QUALITY_HIGH)
src_quality = QUALITY_HIGH;
VBAUDIO(QString("SRC quality = %1").arg(quality_string(src_quality)));
}
}
/**
* Destructor
*
* You must kill the output thread via KillAudio() prior to destruction
*/
AudioOutputBase::~AudioOutputBase()
{
if (!killaudio)
VBERROR("Programmer Error: "
"~AudioOutputBase called, but KillAudio has not been called!");
// We got this from a subclass, delete it
delete output_settings;
delete output_settingsraw;
if (output_settings != output_settingsdigital)
{
delete output_settingsdigital;
delete output_settingsdigitalraw;
}
if (kAudioSRCOutputSize > 0)
delete[] src_out;
assert(memory_corruption_test0 == 0xdeadbeef);
assert(memory_corruption_test1 == 0xdeadbeef);
assert(memory_corruption_test2 == 0xdeadbeef);
assert(memory_corruption_test3 == 0xdeadbeef);
}
void AudioOutputBase::InitSettings(const AudioSettings &settings)
{
if (settings.custom)
{
// got a custom audio report already, use it
// this was likely provided by the AudioTest utility
output_settings = new AudioOutputSettings;
*output_settings = *settings.custom;
output_settingsdigital = output_settings;
max_channels = output_settings->BestSupportedChannels();
configured_channels = max_channels;
return;
}
// Ask the subclass what we can send to the device
output_settings = GetOutputSettingsUsers(false);
output_settingsdigital = GetOutputSettingsUsers(true);
max_channels = output_settings->BestSupportedChannels();
configured_channels = max_channels;
upmix_default = max_channels > 2 ?
gCoreContext->GetNumSetting("AudioDefaultUpmix", false) :
false;
if (settings.upmixer == 1) // music, upmixer off
upmix_default = false;
else if (settings.upmixer == 2) // music, upmixer on
upmix_default = true;
}
/**
* Returns capabilities supported by the audio device
* amended to take into account the digital audio
* options (AC3, DTS, E-AC3 and TrueHD)
*/
AudioOutputSettings* AudioOutputBase::GetOutputSettingsCleaned(bool digital)
{
// If we've already checked the port, use the cache
// version instead
if (!m_discretedigital || !digital)
{
digital = false;
if (output_settingsraw)
return output_settingsraw;
}
else if (output_settingsdigitalraw)
return output_settingsdigitalraw;
AudioOutputSettings* aosettings = GetOutputSettings(digital);
if (aosettings)
aosettings->GetCleaned();
else
aosettings = new AudioOutputSettings(true);
if (digital)
return (output_settingsdigitalraw = aosettings);
else
return (output_settingsraw = aosettings);
}
/**
* Returns capabilities supported by the audio device
* amended to take into account the digital audio
* options (AC3, DTS, E-AC3 and TrueHD) as well as the user settings
*/
AudioOutputSettings* AudioOutputBase::GetOutputSettingsUsers(bool digital)
{
if (!m_discretedigital || !digital)
{
digital = false;
if (output_settings)
return output_settings;
}
else if (output_settingsdigital)
return output_settingsdigital;
AudioOutputSettings* aosettings = new AudioOutputSettings;
*aosettings = *GetOutputSettingsCleaned(digital);
aosettings->GetUsers();
if (digital)
return (output_settingsdigital = aosettings);
else
return (output_settings = aosettings);
}
/**
* Test if we can output digital audio and if sample rate is supported
*/
bool AudioOutputBase::CanPassthrough(int samplerate, int channels,
int codec, int profile) const
{
DigitalFeature arg = FEATURE_NONE;
bool ret = !(internal_vol && SWVolume());
switch(codec)
{
case CODEC_ID_AC3:
arg = FEATURE_AC3;
break;
case CODEC_ID_DTS:
switch(profile)
{
case FF_PROFILE_DTS:
case FF_PROFILE_DTS_ES:
case FF_PROFILE_DTS_96_24:
arg = FEATURE_DTS;
break;
case FF_PROFILE_DTS_HD_HRA:
case FF_PROFILE_DTS_HD_MA:
arg = FEATURE_DTSHD;
break;
default:
break;
}
break;
case CODEC_ID_EAC3:
arg = FEATURE_EAC3;
break;
case CODEC_ID_TRUEHD:
arg = FEATURE_TRUEHD;
break;
}
// we can't passthrough any other codecs than those defined above
ret &= output_settingsdigital->canFeature(arg);
ret &= output_settingsdigital->IsSupportedFormat(FORMAT_S16);
ret &= output_settingsdigital->IsSupportedRate(samplerate);
// if we must resample to 48kHz ; we can't passthrough
ret &= !((samplerate != 48000) &&
gCoreContext->GetNumSetting("Audio48kOverride", false));
// Don't know any cards that support spdif clocked at < 44100
// Some US cable transmissions have 2ch 32k AC-3 streams
ret &= samplerate >= 44100;
if (!ret)
return false;
// Will passthrough if surround audio was defined. Amplifier will
// do the downmix if required
ret &= max_channels >= 6 && channels > 2;
// Stereo content will always be decoded so it can later be upmixed
// unless audio is configured for stereo. We can passthrough otherwise
ret |= max_channels == 2;
return ret;
}
/**
* Set the bitrate of the source material, reported in periodic OutputEvents
*/
void AudioOutputBase::SetSourceBitrate(int rate)
{
if (rate > 0)
source_bitrate = rate;
}
/**
* Set the timestretch factor
*
* You must hold the audio_buflock to call this safely
*/
void AudioOutputBase::SetStretchFactorLocked(float lstretchfactor)
{
if (stretchfactor == lstretchfactor && pSoundStretch)
return;
stretchfactor = lstretchfactor;
eff_stretchfactor = (int)(100000.0f * lstretchfactor + 0.5);
if (pSoundStretch)
{
VBGENERAL(QString("Changing time stretch to %1").arg(stretchfactor));
pSoundStretch->setTempo(stretchfactor);
}
else if (stretchfactor != 1.0f)
{
VBGENERAL(QString("Using time stretch %1").arg(stretchfactor));
pSoundStretch = new soundtouch::SoundTouch();
pSoundStretch->setSampleRate(samplerate);
pSoundStretch->setChannels(needs_upmix || needs_downmix ?
configured_channels : source_channels);
pSoundStretch->setTempo(stretchfactor);
pSoundStretch->setSetting(SETTING_SEQUENCE_MS, 35);
/* If we weren't already processing we need to turn on float conversion
adjust sample and frame sizes accordingly and dump the contents of
the audiobuffer */
if (!processing)
{
processing = true;
bytes_per_frame = source_channels *
AudioOutputSettings::SampleSize(FORMAT_FLT);
waud = raud = 0;
reset_active.Ref();
}
}
}
/**
* Set the timestretch factor
*/
void AudioOutputBase::SetStretchFactor(float lstretchfactor)
{
QMutexLocker lock(&audio_buflock);
SetStretchFactorLocked(lstretchfactor);
}
/**
* Get the timetretch factor
*/
float AudioOutputBase::GetStretchFactor(void) const
{
return stretchfactor;
}
/**
* Source is currently being upmixed
*/
bool AudioOutputBase::IsUpmixing(void)
{
return needs_upmix && upmixer;
}
/**
* Toggle between stereo and upmixed 5.1 if the source material is stereo
*/
bool AudioOutputBase::ToggleUpmix(void)
{
// Can only upmix from mono/stereo to 6 ch
if (max_channels == 2 || source_channels > 2 || passthru)
return false;
upmix_default = !upmix_default;
const AudioSettings settings(format, source_channels, codec,
source_samplerate, passthru);
Reconfigure(settings);
return configured_channels == max_channels;
}
/**
* Upmixing of the current source is available if requested
*/
bool AudioOutputBase::CanUpmix(void)
{
return needs_upmix && IS_VALID_UPMIX_CHANNEL(source_channels) &&
configured_channels > 2;
}
/*
* Setup samplerate and number of channels for passthrough
* Create SPDIF encoder and true if successful
*/
bool AudioOutputBase::SetupPassthrough(int codec, int codec_profile,
int &samplerate_tmp, int &channels_tmp)
{
if (codec == CODEC_ID_DTS &&
!output_settingsdigital->canFeature(FEATURE_DTSHD))
{
// We do not support DTS-HD bitstream so force extraction of the
// DTS core track instead
codec_profile = FF_PROFILE_DTS;
}
QString log = AudioOutputSettings::GetPassthroughParams(
codec, codec_profile,
samplerate_tmp, channels_tmp,
output_settingsdigital->GetMaxHDRate() == 768000);
VBAUDIO("Setting " + log + " passthrough");
if (m_spdifenc)
{
delete m_spdifenc;
}
m_spdifenc = new SPDIFEncoder("spdif", codec);
if (m_spdifenc->Succeeded() && codec == CODEC_ID_DTS)
{
switch(codec_profile)
{
case FF_PROFILE_DTS:
case FF_PROFILE_DTS_ES:
case FF_PROFILE_DTS_96_24:
m_spdifenc->SetMaxHDRate(0);
break;
case FF_PROFILE_DTS_HD_HRA:
case FF_PROFILE_DTS_HD_MA:
m_spdifenc->SetMaxHDRate(samplerate_tmp * channels_tmp / 2);
break;
}
}
if (!m_spdifenc->Succeeded())
{
delete m_spdifenc;
m_spdifenc = NULL;
return false;
}
return true;
}
AudioOutputSettings *AudioOutputBase::OutputSettings(bool digital)
{
if (digital)
return output_settingsdigital;
return output_settings;
}
/**
* (Re)Configure AudioOutputBase
*
* Must be called from concrete subclasses
*/
void AudioOutputBase::Reconfigure(const AudioSettings &orig_settings)
{
AudioSettings settings = orig_settings;
int lsource_channels = settings.channels;
int lconfigured_channels = configured_channels;
bool lneeds_upmix = false;
bool lneeds_downmix = false;
bool lreenc = false;
bool lenc = false;
if (!settings.use_passthru)
{
// Do we upmix stereo or mono?
lconfigured_channels =
(upmix_default && lsource_channels <= 2) ? 6 : lsource_channels;
bool cando_channels =
output_settings->IsSupportedChannels(lconfigured_channels);
// check if the number of channels could be transmitted via AC3 encoding
lenc = output_settingsdigital->canFeature(FEATURE_AC3) &&
(!output_settings->canFeature(FEATURE_LPCM) &&
lconfigured_channels > 2 && lconfigured_channels <= 6);
if (!lenc && !cando_channels)
{
// if hardware doesn't support source audio configuration
// we will upmix/downmix to what we can
// (can safely assume hardware supports stereo)
switch (lconfigured_channels)
{
case 7:
lconfigured_channels = 8;
break;
case 8:
case 5:
lconfigured_channels = 6;
break;
case 6:
case 4:
case 3:
case 2: //Will never happen
lconfigured_channels = 2;
break;
case 1:
lconfigured_channels = upmix_default ? 6 : 2;
break;
default:
lconfigured_channels = 2;
break;
}
}
// Make sure we never attempt to output more than what we can
// the upmixer can only upmix to 6 channels when source < 6
if (lsource_channels <= 6)
lconfigured_channels = min(lconfigured_channels, 6);
lconfigured_channels = min(lconfigured_channels, max_channels);
/* Encode to AC-3 if we're allowed to passthru but aren't currently
and we have more than 2 channels but multichannel PCM is not
supported or if the device just doesn't support the number of
channels */
lenc = output_settingsdigital->canFeature(FEATURE_AC3) &&
((!output_settings->canFeature(FEATURE_LPCM) &&
lconfigured_channels > 2) ||
!output_settings->IsSupportedChannels(lconfigured_channels));
/* Might we reencode a bitstream that's been decoded for timestretch?
If the device doesn't support the number of channels - see below */
if (output_settingsdigital->canFeature(FEATURE_AC3) &&
(settings.codec == CODEC_ID_AC3 || settings.codec == CODEC_ID_DTS))
{
lreenc = true;
}
// Enough channels? Upmix if not, but only from mono/stereo/5.0 to 5.1
if (IS_VALID_UPMIX_CHANNEL(settings.channels) &&
settings.channels < lconfigured_channels)
{
VBAUDIO(QString("Needs upmix from %1 -> %2 channels")
.arg(settings.channels).arg(lconfigured_channels));
settings.channels = lconfigured_channels;
lneeds_upmix = true;
}
else if (settings.channels > lconfigured_channels)
{
VBAUDIO(QString("Needs downmix from %1 -> %2 channels")
.arg(settings.channels).arg(lconfigured_channels));
settings.channels = lconfigured_channels;
lneeds_downmix = true;
}
}
ClearError();
bool general_deps = true;
/* Set samplerate_tmp and channels_tmp to appropriate values
if passing through */
int samplerate_tmp, channels_tmp;
if (settings.use_passthru)
{
samplerate_tmp = settings.samplerate;
SetupPassthrough(settings.codec, settings.codec_profile,
samplerate_tmp, channels_tmp);
general_deps = samplerate == samplerate_tmp && channels == channels_tmp;
}
// Check if anything has changed
general_deps &=
settings.format == format &&
settings.samplerate == source_samplerate &&
settings.use_passthru == passthru &&
lconfigured_channels == configured_channels &&
lneeds_upmix == needs_upmix && lreenc == reenc &&
lsource_channels == source_channels &&
lneeds_downmix == needs_downmix;
if (general_deps && m_configure_succeeded)
{
VBAUDIO("Reconfigure(): No change -> exiting");
return;
}
KillAudio();
QMutexLocker lock(&audio_buflock);
QMutexLocker lockav(&avsync_lock);
waud = raud = 0;
reset_active.Clear();
actually_paused = processing = false;
channels = settings.channels;
source_channels = lsource_channels;
reenc = lreenc;
codec = settings.codec;
passthru = settings.use_passthru;
configured_channels = lconfigured_channels;
needs_upmix = lneeds_upmix;
needs_downmix = lneeds_downmix;
format = output_format = settings.format;
source_samplerate = samplerate = settings.samplerate;
enc = lenc;
killaudio = pauseaudio = false;
was_paused = true;
// Don't try to do anything if audio hasn't been
// initialized yet (e.g. rubbish was provided)
if (source_channels <= 0 || format <= 0 || samplerate <= 0)
{
SilentError(QString("Aborting Audio Reconfigure. ") +
QString("Invalid audio parameters ch %1 fmt %2 @ %3Hz")
.arg(source_channels).arg(format).arg(samplerate));
return;
}
VBAUDIO(QString("Original codec was %1, %2, %3 kHz, %4 channels")
.arg(ff_codec_id_string((CodecID)codec))
.arg(output_settings->FormatToString(format))
.arg(samplerate/1000)
.arg(source_channels));
VBAUDIO(QString("enc(%1), passthru(%2), features (%3) "
"configured_channels(%4), %5 channels supported(%6) "
"max_channels(%7)")
.arg(enc)
.arg(passthru)
.arg(output_settingsdigital->FeaturesToString())
.arg(configured_channels)
.arg(channels)
.arg(output_settings->IsSupportedChannels(channels))
.arg(max_channels));
int dest_rate = 0;
// Force resampling if we are encoding to AC3 and sr > 48k
// or if 48k override was checked in settings
if ((samplerate != 48000 &&
gCoreContext->GetNumSetting("Audio48kOverride", false)) ||
(enc && (samplerate > 48000 || (need_resampler && dest_rate > 48000))))
{
VBAUDIO("Forcing resample to 48 kHz");
if (src_quality < 0)
src_quality = QUALITY_MEDIUM;
need_resampler = true;
dest_rate = 48000;
}
else if (
(need_resampler = !OutputSettings(enc)->IsSupportedRate(samplerate)))
{
dest_rate = OutputSettings(enc)->NearestSupportedRate(samplerate);
}
if (need_resampler && src_quality > QUALITY_DISABLED)
{
int error;
samplerate = dest_rate;
VBGENERAL(QString("Resampling from %1 kHz to %2 kHz with quality %3")
.arg(settings.samplerate/1000).arg(samplerate/1000)
.arg(quality_string(src_quality)));
int chans = needs_downmix ? configured_channels : source_channels;
src_ctx = src_new(2-src_quality, chans, &error);
if (error)
{
Error(QString("Error creating resampler: %1")
.arg(src_strerror(error)));
src_ctx = NULL;
return;
}
src_data.src_ratio = (double)samplerate / settings.samplerate;
src_data.data_in = src_in;
int newsize = (int)(kAudioSRCInputSize * src_data.src_ratio + 15)
& ~0xf;
if (kAudioSRCOutputSize < newsize)
{
kAudioSRCOutputSize = newsize;
VBAUDIO(QString("Resampler allocating %1").arg(newsize));
if (src_out)
delete[] src_out;
src_out = new float[kAudioSRCOutputSize];
}
src_data.data_out = src_out;
src_data.output_frames = kAudioSRCOutputSize / chans;
src_data.end_of_input = 0;
}
if (enc)
{
if (reenc)
VBAUDIO("Reencoding decoded AC-3/DTS to AC-3");
VBAUDIO(QString("Creating AC-3 Encoder with sr = %1, ch = %2")
.arg(samplerate).arg(configured_channels));
encoder = new AudioOutputDigitalEncoder();
if (!encoder->Init(CODEC_ID_AC3, 448000, samplerate,
configured_channels))
{
Error("AC-3 encoder initialization failed");
delete encoder;
encoder = NULL;
enc = false;
// upmixing will fail if we needed the encoder
needs_upmix = false;
}
}
if (passthru)
{
//AC3, DTS, DTS-HD MA and TrueHD all use 16 bits samples
channels = channels_tmp;
samplerate = samplerate_tmp;
format = output_format = FORMAT_S16;
source_bytes_per_frame = channels *
output_settings->SampleSize(format);
}
else
{
source_bytes_per_frame = source_channels *
output_settings->SampleSize(format);
}
// Turn on float conversion?
if (need_resampler || needs_upmix || needs_downmix ||
stretchfactor != 1.0f || (internal_vol && SWVolume()) ||
(enc && output_format != FORMAT_S16) ||
!OutputSettings(enc)->IsSupportedFormat(output_format))
{
VBAUDIO("Audio processing enabled");
processing = true;
if (enc)
output_format = FORMAT_S16; // Output s16le for AC-3 encoder
else
output_format = output_settings->BestSupportedFormat();
}
bytes_per_frame = processing ?
sizeof(float) : output_settings->SampleSize(format);
bytes_per_frame *= channels;
if (enc)
channels = 2; // But only post-encoder
output_bytes_per_frame = channels *
output_settings->SampleSize(output_format);
VBGENERAL(
QString("Opening audio device '%1' ch %2(%3) sr %4 sf %5 reenc %6")
.arg(main_device).arg(channels).arg(source_channels).arg(samplerate)
.arg(output_settings->FormatToString(output_format)).arg(reenc));
audbuf_timecode = audiotime = frames_buffered = 0;
current_seconds = source_bitrate = -1;
effdsp = samplerate * 100;
// Actually do the device specific open call
if (!OpenDevice())
{
if (GetError().isEmpty())
Error("Aborting reconfigure");
else
VBGENERAL("Aborting reconfigure");
m_configure_succeeded = false;
return;
}
VBAUDIO(QString("Audio fragment size: %1").arg(fragment_size));
// Only used for software volume
if (set_initial_vol && internal_vol && SWVolume())
{
VBAUDIO("Software volume enabled");
volumeControl = gCoreContext->GetSetting("MixerControl", "PCM");
volumeControl += "MixerVolume";
volume = gCoreContext->GetNumSetting(volumeControl, 80);
}
VolumeBase::SetChannels(configured_channels);
VolumeBase::SyncVolume();
VolumeBase::UpdateVolume();
if (needs_upmix && IS_VALID_UPMIX_CHANNEL(source_channels) &&
configured_channels > 2)
{
surround_mode = gCoreContext->GetNumSetting("AudioUpmixType", QUALITY_HIGH);
if ((upmixer = new FreeSurround(samplerate, source == AUDIOOUTPUT_VIDEO,
(FreeSurround::SurroundMode)surround_mode)))
VBAUDIO(QString("Create %1 quality upmixer done")
.arg(quality_string(surround_mode)));
else
{
VBERROR("Failed to create upmixer");
needs_upmix = false;
}
}
VBAUDIO(QString("Audio Stretch Factor: %1").arg(stretchfactor));
SetStretchFactorLocked(old_stretchfactor);
// Setup visualisations, zero the visualisations buffers
prepareVisuals();
if (unpause_when_ready)
pauseaudio = actually_paused = true;
m_configure_succeeded = true;
StartOutputThread();
VBAUDIO("Ending Reconfigure()");
}
bool AudioOutputBase::StartOutputThread(void)
{
if (audio_thread_exists)
return true;
start();
audio_thread_exists = true;
return true;
}
void AudioOutputBase::StopOutputThread(void)
{
if (audio_thread_exists)
{
wait();
audio_thread_exists = false;
}
}
/**
* Kill the output thread and cleanup
*/
void AudioOutputBase::KillAudio()
{
killAudioLock.lock();
VBAUDIO("Killing AudioOutputDSP");
killaudio = true;
StopOutputThread();
QMutexLocker lock(&audio_buflock);
if (pSoundStretch)
{
delete pSoundStretch;
pSoundStretch = NULL;
old_stretchfactor = stretchfactor;
stretchfactor = 1.0f;
}
if (encoder)
{
delete encoder;
encoder = NULL;
}
if (upmixer)
{
delete upmixer;
upmixer = NULL;
}
if (src_ctx)
{
src_delete(src_ctx);
src_ctx = NULL;
}
needs_upmix = need_resampler = enc = false;
CloseDevice();
killAudioLock.unlock();
}
void AudioOutputBase::Pause(bool paused)
{
if (unpause_when_ready)
return;
VBAUDIO(QString("Pause %0").arg(paused));
if (pauseaudio != paused)
was_paused = pauseaudio;
pauseaudio = paused;
actually_paused = false;
}
void AudioOutputBase::PauseUntilBuffered()
{
Reset();
Pause(true);
unpause_when_ready = true;
}
/**
* Reset the audiobuffer, timecode and mythmusic visualisation
*/
void AudioOutputBase::Reset()
{
QMutexLocker lock(&audio_buflock);
QMutexLocker lockav(&avsync_lock);
audbuf_timecode = audiotime = frames_buffered = 0;
waud = raud; // empty ring buffer
reset_active.Ref();
current_seconds = -1;
was_paused = !pauseaudio;
// Setup visualisations, zero the visualisations buffers
prepareVisuals();
}
/**
* Set the timecode of the samples most recently added to the audiobuffer
*
* Used by mythmusic for seeking since it doesn't provide timecodes to
* AddData()
*/
void AudioOutputBase::SetTimecode(int64_t timecode)
{
audbuf_timecode = audiotime = timecode;
frames_buffered = (timecode * source_samplerate) / 1000;
}
/**
* Set the effective DSP rate
*
* Equal to 100 * samples per second
* NuppelVideo sets this every sync frame to achieve av sync
*/
void AudioOutputBase::SetEffDsp(int dsprate)
{
VBAUDIO(QString("SetEffDsp: %1").arg(dsprate));
effdsp = dsprate;
}
/**
* Get the number of bytes in the audiobuffer
*/
inline int AudioOutputBase::audiolen()
{
if (waud >= raud)
return waud - raud;
else
return kAudioRingBufferSize - (raud - waud);
}
/**
* Get the free space in the audiobuffer in bytes
*/
int AudioOutputBase::audiofree()
{
return kAudioRingBufferSize - audiolen() - 1;
/* There is one wasted byte in the buffer. The case where waud = raud is
interpreted as an empty buffer, so the fullest the buffer can ever
be is kAudioRingBufferSize - 1. */
}
/**
* Get the scaled number of bytes in the audiobuffer, i.e. the number of
* samples * the output bytes per sample
*
* This value can differ from that returned by audiolen if samples are
* being converted to floats and the output sample format is not 32 bits
*/
int AudioOutputBase::audioready()
{
if (passthru || enc || bytes_per_frame == output_bytes_per_frame)
return audiolen();
else
return audiolen() * output_bytes_per_frame / bytes_per_frame;
}
/**
* Calculate the timecode of the samples that are about to become audible
*/
int64_t AudioOutputBase::GetAudiotime(void)
{
if (audbuf_timecode == 0 || !m_configure_succeeded)
return 0;
int obpf = output_bytes_per_frame;
int64_t oldaudiotime;
/* We want to calculate 'audiotime', which is the timestamp of the audio
Which is leaving the sound card at this instant.
We use these variables:
'effdsp' is frames/sec