/
cellAudio.cpp
2112 lines (1706 loc) · 54.6 KB
/
cellAudio.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
#include "stdafx.h"
#include "Emu/System.h"
#include "Emu/system_config.h"
#include "Emu/Cell/PPUModule.h"
#include "Emu/Cell/lv2/sys_process.h"
#include "Emu/Cell/lv2/sys_event.h"
#include "cellAudio.h"
#include <cmath>
LOG_CHANNEL(cellAudio);
extern void lv2_sleep(u64 timeout, ppu_thread* ppu = nullptr);
vm::gvar<char, AUDIO_PORT_OFFSET * AUDIO_PORT_COUNT> g_audio_buffer;
struct alignas(16) aligned_index_t
{
be_t<u64> index;
u8 pad[8];
};
vm::gvar<aligned_index_t, AUDIO_PORT_COUNT> g_audio_indices;
template <>
void fmt_class_string<CellAudioError>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](CellAudioError value)
{
switch (value)
{
STR_CASE(CELL_AUDIO_ERROR_ALREADY_INIT);
STR_CASE(CELL_AUDIO_ERROR_AUDIOSYSTEM);
STR_CASE(CELL_AUDIO_ERROR_NOT_INIT);
STR_CASE(CELL_AUDIO_ERROR_PARAM);
STR_CASE(CELL_AUDIO_ERROR_PORT_FULL);
STR_CASE(CELL_AUDIO_ERROR_PORT_ALREADY_RUN);
STR_CASE(CELL_AUDIO_ERROR_PORT_NOT_OPEN);
STR_CASE(CELL_AUDIO_ERROR_PORT_NOT_RUN);
STR_CASE(CELL_AUDIO_ERROR_TRANS_EVENT);
STR_CASE(CELL_AUDIO_ERROR_PORT_OPEN);
STR_CASE(CELL_AUDIO_ERROR_SHAREDMEMORY);
STR_CASE(CELL_AUDIO_ERROR_MUTEX);
STR_CASE(CELL_AUDIO_ERROR_EVENT_QUEUE);
STR_CASE(CELL_AUDIO_ERROR_AUDIOSYSTEM_NOT_FOUND);
STR_CASE(CELL_AUDIO_ERROR_TAG_NOT_FOUND);
}
return unknown;
});
}
cell_audio_config::cell_audio_config()
{
raw = audio::get_raw_config();
}
void cell_audio_config::reset(bool backend_changed)
{
if (!backend || backend_changed)
{
backend.reset();
backend = Emu.GetCallbacks().get_audio();
}
cellAudio.notice("cellAudio initializing. Backend: %s", backend->GetName());
const AudioFreq freq = AudioFreq::FREQ_48K;
const AudioSampleSize sample_size = raw.convert_to_s16 ? AudioSampleSize::S16 : AudioSampleSize::FLOAT;
const auto [req_ch_cnt, downmix] = AudioBackend::get_channel_count_and_downmixer(0); // CELL_AUDIO_OUT_PRIMARY
f64 cb_frame_len = 0.0;
u32 ch_cnt = 2;
if (backend->Open(raw.audio_device, freq, sample_size, req_ch_cnt))
{
cb_frame_len = backend->GetCallbackFrameLen();
ch_cnt = backend->get_channels();
}
else
{
cellAudio.error("Failed to open audio backend. Make sure that no other application is running that might block audio access (e.g. Netflix).");
}
audio_downmix = downmix;
backend_ch_cnt = AudioChannelCnt{ch_cnt};
audio_channels = static_cast<u32>(req_ch_cnt);
audio_sampling_rate = static_cast<u32>(freq);
audio_block_period = AUDIO_BUFFER_SAMPLES * 1'000'000 / audio_sampling_rate;
audio_sample_size = static_cast<u32>(sample_size);
audio_min_buffer_duration = cb_frame_len + u32{AUDIO_BUFFER_SAMPLES} * 2.0 / audio_sampling_rate; // Add 2 blocks to allow jitter compensation
audio_buffer_length = AUDIO_BUFFER_SAMPLES * audio_channels;
desired_buffer_duration = std::max(static_cast<s64>(audio_min_buffer_duration * 1000), raw.desired_buffer_duration) * 1000llu;
buffering_enabled = raw.buffering_enabled && raw.renderer != audio_renderer::null;
minimum_block_period = audio_block_period / 2;
maximum_block_period = (6 * audio_block_period) / 5;
desired_full_buffers = buffering_enabled ? static_cast<u32>(desired_buffer_duration / audio_block_period) + 3 : 2;
num_allocated_buffers = desired_full_buffers + EXTRA_AUDIO_BUFFERS;
fully_untouched_timeout = static_cast<u64>(audio_block_period) * 2;
partially_untouched_timeout = static_cast<u64>(audio_block_period) * 4;
const bool raw_time_stretching_enabled = buffering_enabled && raw.enable_time_stretching && (raw.time_stretching_threshold > 0);
time_stretching_enabled = raw_time_stretching_enabled;
time_stretching_threshold = raw.time_stretching_threshold / 100.0f;
// Warn if audio backend does not support all requested features
if (raw.buffering_enabled && !buffering_enabled)
{
cellAudio.error("Audio backend %s does not support buffering, this option will be ignored.", backend->GetName());
if (raw.enable_time_stretching)
{
cellAudio.error("Audio backend %s does not support time stretching, this option will be ignored.", backend->GetName());
}
}
}
audio_ringbuffer::audio_ringbuffer(cell_audio_config& _cfg)
: backend(_cfg.backend)
, cfg(_cfg)
, buf_sz(AUDIO_BUFFER_SAMPLES * _cfg.audio_channels)
{
// Initialize buffers
if (cfg.num_allocated_buffers > MAX_AUDIO_BUFFERS)
{
fmt::throw_exception("MAX_AUDIO_BUFFERS is too small");
}
for (u32 i = 0; i < cfg.num_allocated_buffers; i++)
{
buffer[i].reset(new float[buf_sz]{});
}
// Init audio dumper if enabled
if (cfg.raw.dump_to_file)
{
m_dump.Open(static_cast<AudioChannelCnt>(cfg.audio_channels), static_cast<AudioFreq>(cfg.audio_sampling_rate), AudioSampleSize::FLOAT);
}
// Configure resampler
resampler.set_params(static_cast<AudioChannelCnt>(cfg.audio_channels), static_cast<AudioFreq>(cfg.audio_sampling_rate));
resampler.set_tempo(RESAMPLER_MAX_FREQ_VAL);
const f64 buffer_dur_mult = [&]()
{
if (cfg.buffering_enabled)
{
return cfg.desired_buffer_duration / 1'000'000.0 + 0.02; // Add 20ms to buffer to keep buffering algorithm happy
}
return cfg.audio_min_buffer_duration;
}();
cb_ringbuf.set_buf_size(static_cast<u32>(static_cast<u32>(cfg.backend_ch_cnt) * cfg.audio_sampling_rate * cfg.audio_sample_size * buffer_dur_mult));
backend->SetWriteCallback(std::bind(&audio_ringbuffer::backend_write_callback, this, std::placeholders::_1, std::placeholders::_2));
backend->SetStateCallback(std::bind(&audio_ringbuffer::backend_state_callback, this, std::placeholders::_1));
}
audio_ringbuffer::~audio_ringbuffer()
{
if (get_backend_playing())
{
flush();
}
backend->Close();
}
f32 audio_ringbuffer::set_frequency_ratio(f32 new_ratio)
{
frequency_ratio = static_cast<f32>(resampler.set_tempo(new_ratio));
return frequency_ratio;
}
float* audio_ringbuffer::get_buffer(u32 num) const
{
AUDIT(num < cfg.num_allocated_buffers);
AUDIT(buffer[num]);
return buffer[num].get();
}
u32 audio_ringbuffer::backend_write_callback(u32 size, void *buf)
{
if (!backend_active.observe()) backend_active = true;
return static_cast<u32>(cb_ringbuf.pop(buf, size, true));
}
void audio_ringbuffer::backend_state_callback(AudioStateEvent event)
{
if (event == AudioStateEvent::DEFAULT_DEVICE_MAYBE_CHANGED)
{
backend_device_changed = true;
}
}
u64 audio_ringbuffer::get_timestamp()
{
return get_system_time();
}
float* audio_ringbuffer::get_current_buffer() const
{
return get_buffer(cur_pos);
}
u64 audio_ringbuffer::get_enqueued_samples() const
{
AUDIT(cfg.buffering_enabled);
const u64 ringbuf_samples = cb_ringbuf.get_used_size() / (cfg.audio_sample_size * static_cast<u32>(cfg.backend_ch_cnt));
if (cfg.time_stretching_enabled)
{
return ringbuf_samples + resampler.samples_available();
}
return ringbuf_samples;
}
u64 audio_ringbuffer::get_enqueued_playtime() const
{
AUDIT(cfg.buffering_enabled);
return get_enqueued_samples() * 1'000'000 / cfg.audio_sampling_rate;
}
void audio_ringbuffer::enqueue(bool enqueue_silence, bool force)
{
AUDIT(cur_pos < cfg.num_allocated_buffers);
// Prepare buffer
static float silence_buffer[u32{AUDIO_MAX_CHANNELS_COUNT} * u32{AUDIO_BUFFER_SAMPLES}]{};
float* buf = silence_buffer;
if (!enqueue_silence)
{
buf = buffer[cur_pos].get();
cur_pos = (cur_pos + 1) % cfg.num_allocated_buffers;
}
if (!backend_active.observe() && !force)
{
// backend is not ready yet
return;
}
// Enqueue audio
if (cfg.time_stretching_enabled)
{
resampler.put_samples(buf, AUDIO_BUFFER_SAMPLES);
}
else
{
// Since time stretching step is skipped, we can commit to buffer directly
commit_data(buf, AUDIO_BUFFER_SAMPLES);
}
}
void audio_ringbuffer::enqueue_silence(u32 buf_count, bool force)
{
for (u32 i = 0; i < buf_count; i++)
{
enqueue(true, force);
}
}
void audio_ringbuffer::process_resampled_data()
{
if (!cfg.time_stretching_enabled) return;
const auto [buffer, samples] = resampler.get_samples(static_cast<u32>(cb_ringbuf.get_free_size() / (cfg.audio_sample_size * static_cast<u32>(cfg.backend_ch_cnt))));
commit_data(buffer, samples);
}
void audio_ringbuffer::commit_data(f32* buf, u32 sample_cnt)
{
sample_cnt *= cfg.audio_channels;
// Dump audio if enabled
m_dump.WriteData(buf, sample_cnt * static_cast<u32>(AudioSampleSize::FLOAT));
if (cfg.backend_ch_cnt < AudioChannelCnt{cfg.audio_channels})
{
if (AudioChannelCnt{cfg.audio_channels} == AudioChannelCnt::SURROUND_7_1)
{
if (cfg.backend_ch_cnt == AudioChannelCnt::SURROUND_5_1)
{
AudioBackend::downmix<AudioChannelCnt::SURROUND_7_1, AudioChannelCnt::SURROUND_5_1>(sample_cnt, buf, buf);
}
else if (cfg.backend_ch_cnt == AudioChannelCnt::STEREO)
{
AudioBackend::downmix<AudioChannelCnt::SURROUND_7_1, AudioChannelCnt::STEREO>(sample_cnt, buf, buf);
}
else
{
fmt::throw_exception("Invalid downmix combination: %u -> %u", cfg.audio_channels, static_cast<u32>(cfg.backend_ch_cnt));
}
}
else if (AudioChannelCnt{cfg.audio_channels} == AudioChannelCnt::SURROUND_5_1)
{
if (cfg.backend_ch_cnt == AudioChannelCnt::STEREO)
{
AudioBackend::downmix<AudioChannelCnt::SURROUND_5_1, AudioChannelCnt::STEREO>(sample_cnt, buf, buf);
}
else
{
fmt::throw_exception("Invalid downmix combination: %u -> %u", cfg.audio_channels, static_cast<u32>(cfg.backend_ch_cnt));
}
}
else
{
fmt::throw_exception("Invalid downmix combination: %u -> %u", cfg.audio_channels, static_cast<u32>(cfg.backend_ch_cnt));
}
}
const u32 sample_cnt_out = sample_cnt / cfg.audio_channels * static_cast<u32>(cfg.backend_ch_cnt);
if (cfg.backend->get_convert_to_s16())
{
AudioBackend::convert_to_s16(sample_cnt_out, buf, buf);
}
cb_ringbuf.push(buf, sample_cnt_out * cfg.audio_sample_size);
}
void audio_ringbuffer::play()
{
if (playing)
{
return;
}
playing = true;
play_timestamp = get_timestamp();
backend->Play();
}
void audio_ringbuffer::flush()
{
backend->Pause();
cb_ringbuf.writer_flush();
resampler.flush();
backend_active = false;
playing = false;
if (frequency_ratio != RESAMPLER_MAX_FREQ_VAL)
{
frequency_ratio = set_frequency_ratio(RESAMPLER_MAX_FREQ_VAL);
}
}
u64 audio_ringbuffer::update(bool emu_is_paused)
{
// Check emulator pause state
if (emu_is_paused)
{
// Emulator paused
if (playing)
{
flush();
}
}
else
{
// Emulator unpaused
play();
}
// Prepare timestamp
const u64 timestamp = get_timestamp();
// Store and return timestamp
update_timestamp = timestamp;
return timestamp;
}
void audio_port::tag(s32 offset)
{
auto port_buf = get_vm_ptr(offset);
// This tag will be used to make sure that the game has finished writing the audio for the next audio period
// We use -0.0f in case games check if the buffer is empty. -0.0f == 0.0f evaluates to true, but std::signbit can be used to distinguish them
const f32 tag = -0.0f;
const u32 tag_first_pos = num_channels == 2 ? PORT_BUFFER_TAG_FIRST_2CH : PORT_BUFFER_TAG_FIRST_8CH;
const u32 tag_delta = num_channels == 2 ? PORT_BUFFER_TAG_DELTA_2CH : PORT_BUFFER_TAG_DELTA_8CH;
for (u32 tag_pos = tag_first_pos, tag_nr = 0; tag_nr < PORT_BUFFER_TAG_COUNT; tag_pos += tag_delta, tag_nr++)
{
port_buf[tag_pos] = tag;
last_tag_value[tag_nr] = -0.0f;
}
prev_touched_tag_nr = -1;
}
cell_audio_thread::cell_audio_thread(utils::serial& ar)
: cell_audio_thread()
{
ar(init);
if (!init)
{
return;
}
ar(key_count, event_period);
keys.resize(ar);
for (key_info& k : keys)
{
ar(k.start_period, k.flags, k.source);
k.port = lv2_event_queue::load_ptr(ar, k.port, "audio");
}
ar(ports);
}
void cell_audio_thread::save(utils::serial& ar)
{
ar(init);
if (!init)
{
return;
}
USING_SERIALIZATION_VERSION(cellAudio);
ar(key_count, event_period);
ar(keys.size());
for (const key_info& k : keys)
{
ar(k.start_period, k.flags, k.source);
lv2_event_queue::save_ptr(ar, k.port.get());
}
ar(ports);
}
std::tuple<u32, u32, u32, u32> cell_audio_thread::count_port_buffer_tags()
{
AUDIT(cfg.buffering_enabled);
u32 active = 0;
u32 in_progress = 0;
u32 untouched = 0;
u32 incomplete = 0;
for (audio_port& port : ports)
{
if (port.state != audio_port_state::started) continue;
active++;
auto port_buf = port.get_vm_ptr();
// Find the last tag that has been touched
const u32 tag_first_pos = port.num_channels == 2 ? PORT_BUFFER_TAG_FIRST_2CH : PORT_BUFFER_TAG_FIRST_8CH;
const u32 tag_delta = port.num_channels == 2 ? PORT_BUFFER_TAG_DELTA_2CH : PORT_BUFFER_TAG_DELTA_8CH;
u32 last_touched_tag_nr = port.prev_touched_tag_nr;
bool retouched = false;
for (u32 tag_pos = tag_first_pos, tag_nr = 0; tag_nr < PORT_BUFFER_TAG_COUNT; tag_pos += tag_delta, tag_nr++)
{
const f32 val = port_buf[tag_pos];
f32& last_val = port.last_tag_value[tag_nr];
if (val != last_val || (last_val == -0.0f && std::signbit(last_val) && !std::signbit(val)))
{
last_val = val;
retouched |= (tag_nr <= port.prev_touched_tag_nr) && port.prev_touched_tag_nr != umax;
last_touched_tag_nr = tag_nr;
}
}
// Decide whether the buffer is untouched, in progress, incomplete, or complete
if (last_touched_tag_nr == umax)
{
// no tag has been touched yet
untouched++;
}
else if (last_touched_tag_nr == PORT_BUFFER_TAG_COUNT - 1)
{
if (retouched)
{
// we retouched, so wait at least once more to make sure no more tags get touched
in_progress++;
}
// buffer has been completely filled
port.prev_touched_tag_nr = last_touched_tag_nr;
}
else if (last_touched_tag_nr == port.prev_touched_tag_nr)
{
if (retouched)
{
// we retouched, so wait at least once more to make sure no more tags get touched
in_progress++;
}
else
{
// hasn't been touched since the last call
incomplete++;
}
}
else
{
// the touched tag changed since the last call
in_progress++;
port.prev_touched_tag_nr = last_touched_tag_nr;
}
}
return std::make_tuple(active, in_progress, untouched, incomplete);
}
void cell_audio_thread::reset_ports(s32 offset)
{
// Memset buffer to 0 and tag
for (audio_port& port : ports)
{
if (port.state != audio_port_state::started) continue;
memset(port.get_vm_ptr(offset), 0, port.block_size() * sizeof(float));
if (cfg.buffering_enabled)
{
port.tag(offset);
}
}
}
void cell_audio_thread::advance(u64 timestamp)
{
ringbuffer->process_resampled_data();
std::unique_lock lock(mutex);
// update ports
reset_ports(0);
for (audio_port& port : ports)
{
if (port.state != audio_port_state::started) continue;
port.global_counter = m_counter;
port.active_counter++;
port.timestamp = timestamp;
port.cur_pos = port.position(1);
*port.index = port.cur_pos;
}
if (cfg.buffering_enabled)
{
// Calculate rolling average of enqueued playtime
m_average_playtime = cfg.period_average_alpha * ringbuffer->get_enqueued_playtime() + (1.0f - cfg.period_average_alpha) * m_average_playtime;
}
m_counter++;
m_last_period_end = timestamp;
m_dynamic_period = 0;
// send aftermix event (normal audio event)
std::array<std::shared_ptr<lv2_event_queue>, MAX_AUDIO_EVENT_QUEUES> queues;
u32 queue_count = 0;
event_period++;
for (const key_info& key_inf : keys)
{
if (key_inf.flags & CELL_AUDIO_EVENTFLAG_NOMIX)
{
continue;
}
if ((queues[queue_count] = key_inf.port))
{
u32 periods = 1;
if (key_inf.flags & CELL_AUDIO_EVENTFLAG_DECIMATE_2)
{
periods *= 2;
}
if (key_inf.flags & CELL_AUDIO_EVENTFLAG_DECIMATE_4)
{
// If both flags are set periods is set to x8
periods *= 4;
}
if ((event_period ^ key_inf.start_period) & (periods - 1))
{
// The time has not come for this key to receive event
queues[queue_count].reset();
continue;
}
event_sources[queue_count] = key_inf.source;
event_data3[queue_count] = (key_inf.flags & CELL_AUDIO_EVENTFLAG_BEFOREMIX) ? key_inf.source : 0;
queue_count++;
}
}
lock.unlock();
for (u32 i = 0; i < queue_count; i++)
{
lv2_obj::notify_all_t notify;
queues[i]->send(event_sources[i], CELL_AUDIO_EVENT_MIX, 0, event_data3[i]);
}
}
namespace audio
{
cell_audio_config::raw_config get_raw_config()
{
return
{
.audio_device = g_cfg.audio.audio_device,
.buffering_enabled = static_cast<bool>(g_cfg.audio.enable_buffering),
.desired_buffer_duration = g_cfg.audio.desired_buffer_duration,
.enable_time_stretching = static_cast<bool>(g_cfg.audio.enable_time_stretching),
.time_stretching_threshold = g_cfg.audio.time_stretching_threshold,
.convert_to_s16 = static_cast<bool>(g_cfg.audio.convert_to_s16),
.dump_to_file = static_cast<bool>(g_cfg.audio.dump_to_file),
.renderer = g_cfg.audio.renderer,
.provider = g_cfg.audio.provider
};
}
void configure_audio(bool force_reset)
{
if (g_cfg.audio.provider != audio_provider::cell_audio)
{
return;
}
if (auto& g_audio = g_fxo->get<cell_audio>(); g_fxo->is_init<cell_audio>())
{
// Only reboot the audio renderer if a relevant setting changed
const cell_audio_config::raw_config new_raw = get_raw_config();
if (const cell_audio_config::raw_config raw = g_audio.cfg.raw;
force_reset ||
raw.audio_device != new_raw.audio_device ||
raw.desired_buffer_duration != new_raw.desired_buffer_duration ||
raw.buffering_enabled != new_raw.buffering_enabled ||
raw.time_stretching_threshold != new_raw.time_stretching_threshold ||
raw.enable_time_stretching != new_raw.enable_time_stretching ||
raw.convert_to_s16 != new_raw.convert_to_s16 ||
raw.renderer != new_raw.renderer ||
raw.dump_to_file != new_raw.dump_to_file)
{
std::lock_guard lock{g_audio.emu_cfg_upd_m};
g_audio.cfg.new_raw = new_raw;
g_audio.m_update_configuration = raw.renderer != new_raw.renderer ? audio_backend_update::ALL : audio_backend_update::PARAM;
}
}
}
}
void cell_audio_thread::update_config(bool backend_changed)
{
std::lock_guard lock(mutex);
// Clear ringbuffer
ringbuffer.reset();
// Reload config
cfg.reset(backend_changed);
// Allocate ringbuffer
ringbuffer.reset(new audio_ringbuffer(cfg));
// Reset thread state
reset_counters();
}
void cell_audio_thread::reset_counters()
{
m_counter = 0;
m_start_time = ringbuffer->get_timestamp();
m_last_period_end = m_start_time;
m_dynamic_period = 0;
m_audio_should_restart = true;
}
cell_audio_thread::cell_audio_thread()
{
// Initialize loop variables (regardless of provider in order to initialize timestamps)
reset_counters();
if (cfg.raw.provider != audio_provider::cell_audio)
{
return;
}
// Init audio config
cfg.reset();
// Allocate ringbuffer
ringbuffer.reset(new audio_ringbuffer(cfg));
}
void cell_audio_thread::operator()()
{
if (cfg.raw.provider != audio_provider::cell_audio)
{
return;
}
thread_ctrl::scoped_priority high_prio(+1);
while (Emu.IsPaused())
{
thread_ctrl::wait_for(5000);
}
u32 untouched_expected = 0;
u32 loop_count = 0;
// Main cellAudio loop
while (thread_ctrl::state() != thread_state::aborting)
{
loop_count++;
const audio_backend_update update_req = m_update_configuration.observe();
if (update_req != audio_backend_update::NONE)
{
cellAudio.warning("Updating cell_audio_thread configuration");
{
std::lock_guard lock{emu_cfg_upd_m};
cfg.raw = cfg.new_raw;
m_update_configuration = audio_backend_update::NONE;
}
update_config(update_req == audio_backend_update::ALL);
}
const bool emu_paused = Emu.IsPaused();
const u64 timestamp = ringbuffer->update(emu_paused || m_backend_failed);
if (emu_paused)
{
m_audio_should_restart = true;
ringbuffer->flush();
thread_ctrl::wait_for(10000);
continue;
}
// TODO: (no idea how much of this is already implemented)
// The hardware heartbeat interval of libaudio is ~5.3ms.
// As soon as one interval starts, libaudio waits for ~2.6ms (half of the interval) before it mixes the audio.
// There are 2 different types of games:
// - Normal games:
// Once the audio was mixed, we send the CELL_AUDIO_EVENT_MIX event and the game can process audio.
// - Latency sensitive games:
// If CELL_AUDIO_EVENTFLAG_BEFOREMIX is specified, we immediately send the CELL_AUDIO_EVENT_MIX event and the game can process audio.
// We then have to wait for a maximum of ~2.6ms for cellAudioSendAck and then mix immediately.
const u64 time_since_last_period = timestamp - m_last_period_end;
// Handle audio restart
if (m_audio_should_restart)
{
// align to 5.(3)ms on global clock - some games seem to prefer this
const s64 audio_period_alignment_delta = (timestamp - m_start_time) % cfg.audio_block_period;
if (audio_period_alignment_delta > cfg.period_comparison_margin)
{
thread_ctrl::wait_for(audio_period_alignment_delta - cfg.period_comparison_margin);
}
if (cfg.buffering_enabled)
{
// Restart algorithm
cellAudio.trace("restarting audio");
ringbuffer->enqueue_silence(cfg.desired_full_buffers, true);
finish_port_volume_stepping();
m_average_playtime = static_cast<f32>(ringbuffer->get_enqueued_playtime());
untouched_expected = 0;
}
m_audio_should_restart = false;
continue;
}
bool operational = ringbuffer->get_operational_status();
if (!operational && loop_count % 128 == 0)
{
update_config(true);
operational = ringbuffer->get_operational_status();
}
if (ringbuffer->device_changed())
{
cellAudio.warning("Default device changed, attempting to switch...");
update_config(false);
if (operational != ringbuffer->get_operational_status())
{
continue;
}
}
if (!m_backend_failed && !operational)
{
cellAudio.error("Backend stopped unexpectedly (likely device change). Attempting to recover...");
m_backend_failed = true;
}
else if (m_backend_failed && operational)
{
cellAudio.success("Backend recovered");
m_backend_failed = false;
}
if (!cfg.buffering_enabled)
{
const u64 period_end = (m_counter * cfg.audio_block_period) + m_start_time;
const s64 time_left = period_end - timestamp;
if (time_left > cfg.period_comparison_margin)
{
thread_ctrl::wait_for(get_thread_wait_delay(time_left));
continue;
}
}
else
{
const u64 enqueued_samples = ringbuffer->get_enqueued_samples();
const f32 frequency_ratio = ringbuffer->get_frequency_ratio();
const u64 enqueued_playtime = ringbuffer->get_enqueued_playtime();
const u64 enqueued_buffers = enqueued_samples / AUDIO_BUFFER_SAMPLES;
const auto tag_info = count_port_buffer_tags();
const u32 active_ports = std::get<0>(tag_info);
const u32 in_progress = std::get<1>(tag_info);
const u32 untouched = std::get<2>(tag_info);
const u32 incomplete = std::get<3>(tag_info);
// Ratio between the rolling average of the audio period, and the desired audio period
const f32 average_playtime_ratio = m_average_playtime / cfg.audio_buffer_length;
// Use the above average ratio to decide how much buffer we should be aiming for
f32 desired_duration_adjusted = cfg.desired_buffer_duration + (cfg.audio_block_period / 2.0f);
if (average_playtime_ratio < 1.0f)
{
desired_duration_adjusted /= std::max(average_playtime_ratio, 0.25f);
}
if (cfg.time_stretching_enabled)
{
// 1.0 means exactly as desired
// <1.0 means not as full as desired
// >1.0 means more full than desired
const f32 desired_duration_rate = enqueued_playtime / desired_duration_adjusted;
// update frequency ratio if necessary
if (desired_duration_rate < cfg.time_stretching_threshold)
{
const f32 normalized_desired_duration_rate = desired_duration_rate / cfg.time_stretching_threshold;
// change frequency ratio in steps
const f32 req_time_stretching_step = (normalized_desired_duration_rate + frequency_ratio) / 2.0f;
if (std::abs(req_time_stretching_step - frequency_ratio) > cfg.time_stretching_step)
{
ringbuffer->set_frequency_ratio(req_time_stretching_step);
}
}
else if (frequency_ratio != RESAMPLER_MAX_FREQ_VAL)
{
ringbuffer->set_frequency_ratio(RESAMPLER_MAX_FREQ_VAL);
}
}
// 1.0 means exactly as desired
// <1.0 means not as full as desired
// >1.0 means more full than desired
const f32 desired_duration_rate = enqueued_playtime / desired_duration_adjusted;
if (desired_duration_rate >= 1.0f)
{
// more full than desired
const f32 multiplier = 1.0f / desired_duration_rate;
m_dynamic_period = cfg.maximum_block_period - static_cast<u64>((cfg.maximum_block_period - cfg.audio_block_period) * multiplier);
}
else
{
// not as full as desired
const f32 multiplier = desired_duration_rate * desired_duration_rate; // quite aggressive, but helps more times than it hurts
m_dynamic_period = cfg.minimum_block_period + static_cast<u64>((cfg.audio_block_period - cfg.minimum_block_period) * multiplier);
}
const s64 time_left = m_dynamic_period - time_since_last_period;
if (time_left > cfg.period_comparison_margin)
{
thread_ctrl::wait_for(get_thread_wait_delay(time_left));
continue;
}
// Fast path for 0 ports active
if (active_ports == 0)
{
// no need to mix, just enqueue silence and advance time
cellAudio.trace("enqueuing silence: no active ports, enqueued_buffers=%llu", enqueued_buffers);
ringbuffer->enqueue_silence();
untouched_expected = 0;
advance(timestamp);
continue;
}
// Wait until buffers have been touched
//cellAudio.error("active=%u, in_progress=%u, untouched=%u, incomplete=%u", active_ports, in_progress, untouched, incomplete);
if (untouched > untouched_expected)
{
// Games may sometimes "skip" audio periods entirely if they're falling behind (a sort of "frameskip" for audio)
// As such, if the game doesn't touch buffers for too long we advance time hoping the game recovers
if (
(untouched == active_ports && time_since_last_period > cfg.fully_untouched_timeout) ||
(time_since_last_period > cfg.partially_untouched_timeout) || g_cfg.audio.disable_sampling_skip
)
{
// There's no audio in the buffers, simply advance time and hope the game recovers
cellAudio.trace("advancing time: untouched=%u/%u (expected=%u), enqueued_buffers=%llu", untouched, active_ports, untouched_expected, enqueued_buffers);
untouched_expected = untouched;
advance(timestamp);
continue;
}
cellAudio.trace("waiting: untouched=%u/%u (expected=%u), enqueued_buffers=%llu", untouched, active_ports, untouched_expected, enqueued_buffers);
thread_ctrl::wait_for(1000);
continue;
}
// Fast-path for when there is no audio in the buffers
if (untouched == active_ports)
{
// There's no audio in the buffers, simply advance time
cellAudio.trace("enqueuing silence: untouched=%u/%u (expected=%u), enqueued_buffers=%llu", untouched, active_ports, untouched_expected, enqueued_buffers);
ringbuffer->enqueue_silence();
untouched_expected = untouched;
advance(timestamp);
continue;
}
// Wait for buffer(s) to be completely filled
if (in_progress > 0)
{
cellAudio.trace("waiting: in_progress=%u/%u, enqueued_buffers=%u", in_progress, active_ports, enqueued_buffers);
thread_ctrl::wait_for(500);
continue;
}
//cellAudio.error("active=%u, untouched=%u, in_progress=%d, incomplete=%d, enqueued_buffers=%u", active_ports, untouched, in_progress, incomplete, enqueued_buffers);
// Store number of untouched buffers for future reference
untouched_expected = untouched;
// Log if we enqueued untouched/incomplete buffers
if (untouched > 0 || incomplete > 0)
{
cellAudio.trace("enqueueing: untouched=%u/%u (expected=%u), incomplete=%u/%u enqueued_buffers=%llu", untouched, active_ports, untouched_expected, incomplete, active_ports, enqueued_buffers);
}
}
// Mix
float* buf = ringbuffer->get_current_buffer();
switch (cfg.audio_channels)
{
case 2:
switch (cfg.audio_downmix)
{
case AudioChannelCnt::SURROUND_7_1:
mix<AudioChannelCnt::STEREO, AudioChannelCnt::SURROUND_7_1>(buf);
break;
case AudioChannelCnt::STEREO:
mix<AudioChannelCnt::STEREO, AudioChannelCnt::STEREO>(buf);
break;
case AudioChannelCnt::SURROUND_5_1:
mix<AudioChannelCnt::STEREO, AudioChannelCnt::SURROUND_5_1>(buf);
break;
}
break;
case 6:
switch (cfg.audio_downmix)
{