Debian Codegraph @

xbmc/cores/AudioEngine/Sinks/pipewire/AESinkPipewire.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 2010-2021 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
8
9 #include "AESinkPipewire.h"
10
11 #include "CompileInfo.h"
12 #include "PipewireGlobal.h"
13 #include "cores/AudioEngine/AESinkFactory.h"
14 #include "cores/AudioEngine/Sinks/pipewire/Pipewire.h"
15 #include "cores/AudioEngine/Sinks/pipewire/PipewireCore.h"
16 #include "cores/AudioEngine/Sinks/pipewire/PipewireNode.h"
17 #include "cores/AudioEngine/Sinks/pipewire/PipewireRegistry.h"
18 #include "cores/AudioEngine/Sinks/pipewire/PipewireStream.h"
19 #include "cores/AudioEngine/Sinks/pipewire/PipewireThreadLoop.h"
20 #include "utils/Map.h"
21 #include "utils/StringUtils.h"
22 #include "utils/log.h"
23
24 #include <pipewire/keys.h>
25 #include <spa/param/audio/format-utils.h>
26 #include <spa/param/audio/raw.h>
27 #include <spa/pod/builder.h>
28
29 using namespace std::chrono_literals;
30
31 namespace
32 {
33
34 // clang-format off
35 constexpr std::array<uint32_t, 14> defaultSampleRates = {
36 5512,
37 8000,
38 11025,
39 16000,
40 22050,
41 32000,
42 44100,
43 48000,
44 64000,
45 88200,
46 96000,
47 176400,
48 192000,
49 384000};
50 // clang-format on
51
52 constexpr auto formatMap = make_map<spa_audio_format, AEDataFormat>(
53 {{SPA_AUDIO_FORMAT_ENCODED, AEDataFormat::AE_FMT_RAW},
54 {SPA_AUDIO_FORMAT_U8, AEDataFormat::AE_FMT_U8},
55 {SPA_AUDIO_FORMAT_S16, AEDataFormat::AE_FMT_S16NE},
56 {SPA_AUDIO_FORMAT_S24_32, AEDataFormat::AE_FMT_S24NE4},
57 {SPA_AUDIO_FORMAT_S32, AEDataFormat::AE_FMT_S32NE},
58 {SPA_AUDIO_FORMAT_S24, AEDataFormat::AE_FMT_S24NE3},
59 {SPA_AUDIO_FORMAT_F32, AEDataFormat::AE_FMT_FLOAT}});
60
61 constexpr uint8_t PWFormatToSampleSize(spa_audio_format format)
62 {
63 switch (format)
64 {
65 case SPA_AUDIO_FORMAT_S8:
66 case SPA_AUDIO_FORMAT_U8:
67 return 1;
68 case SPA_AUDIO_FORMAT_ENCODED:
69 case SPA_AUDIO_FORMAT_S16:
70 return 2;
71 case SPA_AUDIO_FORMAT_S24:
72 return 3;
73 case SPA_AUDIO_FORMAT_S24_32:
74 case SPA_AUDIO_FORMAT_S32:
75 case SPA_AUDIO_FORMAT_F32:
76 return 4;
77 default:
78 return 0;
79 }
80 }
81
82 constexpr std::string_view PWFormatToString(spa_audio_format format)
83 {
84 switch (format)
85 {
86 case SPA_AUDIO_FORMAT_ENCODED:
87 return "encoded";
88 case SPA_AUDIO_FORMAT_U8:
89 return "u8";
90 case SPA_AUDIO_FORMAT_S8:
91 return "s8";
92 case SPA_AUDIO_FORMAT_S16:
93 return "s16";
94 case SPA_AUDIO_FORMAT_S24:
95 return "s24";
96 case SPA_AUDIO_FORMAT_S24_32:
97 return "s24_32";
98 case SPA_AUDIO_FORMAT_S32:
99 return "s32";
100 case SPA_AUDIO_FORMAT_F32:
101 return "f32";
102 default:
103 return "(invalid)";
104 }
105 }
106
107 spa_audio_format AEFormatToPWFormat(AEDataFormat& format)
108 {
109 const auto it = std::find_if(formatMap.cbegin(), formatMap.cend(),
110 [&format](auto p) { return p.second == format; });
111 if (it != formatMap.cend())
112 return it->first;
113
114 // default if format not found in map
115 return SPA_AUDIO_FORMAT_F32;
116 }
117
118 constexpr AEDataFormat PWFormatToAEFormat(spa_audio_format& format)
119 {
120 return formatMap.at(format);
121 }
122
123 // clang-format off
124 constexpr auto channelMap = make_map<spa_audio_channel, AEChannel>({
125 {SPA_AUDIO_CHANNEL_FL, AEChannel::AE_CH_FL},
126 {SPA_AUDIO_CHANNEL_FR, AEChannel::AE_CH_FR},
127 {SPA_AUDIO_CHANNEL_FC, AEChannel::AE_CH_FC},
128 {SPA_AUDIO_CHANNEL_LFE, AEChannel::AE_CH_LFE},
129 {SPA_AUDIO_CHANNEL_SL, AEChannel::AE_CH_SL},
130 {SPA_AUDIO_CHANNEL_SR, AEChannel::AE_CH_SR},
131 {SPA_AUDIO_CHANNEL_FLC, AEChannel::AE_CH_FLOC},
132 {SPA_AUDIO_CHANNEL_FRC, AEChannel::AE_CH_FROC},
133 {SPA_AUDIO_CHANNEL_RC, AEChannel::AE_CH_BC},
134 {SPA_AUDIO_CHANNEL_RL, AEChannel::AE_CH_BL},
135 {SPA_AUDIO_CHANNEL_RR, AEChannel::AE_CH_BR},
136 {SPA_AUDIO_CHANNEL_TC, AEChannel::AE_CH_TC},
137 {SPA_AUDIO_CHANNEL_TFL, AEChannel::AE_CH_TFL},
138 {SPA_AUDIO_CHANNEL_TFC, AEChannel::AE_CH_TFC},
139 {SPA_AUDIO_CHANNEL_TFR, AEChannel::AE_CH_TFR},
140 {SPA_AUDIO_CHANNEL_TRL, AEChannel::AE_CH_TBL},
141 {SPA_AUDIO_CHANNEL_TRC, AEChannel::AE_CH_TBC},
142 {SPA_AUDIO_CHANNEL_TRR, AEChannel::AE_CH_TBR},
143 {SPA_AUDIO_CHANNEL_BC, AEChannel::AE_CH_BC},
144 {SPA_AUDIO_CHANNEL_BLC, AEChannel::AE_CH_BLOC},
145 {SPA_AUDIO_CHANNEL_BRC, AEChannel::AE_CH_BROC}});
146 // clang-format on
147
148 std::vector<spa_audio_channel> AEChannelMapToPWChannelMap(CAEChannelInfo& channelInfo)
149 {
150 std::vector<spa_audio_channel> channels;
151 for (uint32_t count = 0; count < channelInfo.Count(); count++)
152 {
153 const auto it =
154 std::find_if(channelMap.cbegin(), channelMap.cend(),
155 [&channelInfo, &count](auto p) { return p.second == channelInfo[count]; });
156
157 if (it != channelMap.cend())
158 channels.emplace_back(it->first);
159 }
160
161 return channels;
162 }
163
164 CAEChannelInfo PWChannelMapToAEChannelMap(std::vector<spa_audio_channel>& channelInfo)
165 {
166 CAEChannelInfo channels;
167 for (const auto& channel : channelInfo)
168 channels += channelMap.at(channel);
169
170 return channels;
171 }
172
173 constexpr auto iec958CodecMap = make_map<CAEStreamInfo::DataType, spa_audio_iec958_codec>({
174 {CAEStreamInfo::STREAM_TYPE_DTS_512, SPA_AUDIO_IEC958_CODEC_DTS},
175 {CAEStreamInfo::STREAM_TYPE_DTS_1024, SPA_AUDIO_IEC958_CODEC_DTS},
176 {CAEStreamInfo::STREAM_TYPE_DTS_2048, SPA_AUDIO_IEC958_CODEC_DTS},
177 {CAEStreamInfo::STREAM_TYPE_DTSHD_CORE, SPA_AUDIO_IEC958_CODEC_DTS},
178
179 {CAEStreamInfo::STREAM_TYPE_AC3, SPA_AUDIO_IEC958_CODEC_AC3},
180
181 {CAEStreamInfo::STREAM_TYPE_EAC3, SPA_AUDIO_IEC958_CODEC_EAC3},
182
183 {CAEStreamInfo::STREAM_TYPE_TRUEHD, SPA_AUDIO_IEC958_CODEC_TRUEHD},
184
185 {CAEStreamInfo::STREAM_TYPE_DTSHD, SPA_AUDIO_IEC958_CODEC_DTSHD},
186 {CAEStreamInfo::STREAM_TYPE_DTSHD_MA, SPA_AUDIO_IEC958_CODEC_DTSHD},
187 });
188
189 constexpr spa_audio_iec958_codec AEStreamInfoDataTypeToPWIEC958Codec(
190 const CAEStreamInfo::DataType& type)
191 {
192 const auto it = iec958CodecMap.find(type);
193 if (it != iec958CodecMap.cend())
194 return it->second;
195
196 return SPA_AUDIO_IEC958_CODEC_UNKNOWN;
197 }
198
199 // constexpr in c++20
200 std::vector<CAEStreamInfo::DataType> PWIEC958CodecToAEStreamInfoDataTypeList(
201 const spa_audio_iec958_codec& codec)
202 {
203 // clang-format off
204 auto codecMap = std::map<spa_audio_iec958_codec, std::vector<CAEStreamInfo::DataType>>({
205 {SPA_AUDIO_IEC958_CODEC_DTS, {CAEStreamInfo::STREAM_TYPE_DTS_512,
206 CAEStreamInfo::STREAM_TYPE_DTS_1024,
207 CAEStreamInfo::STREAM_TYPE_DTS_2048,
208 CAEStreamInfo::STREAM_TYPE_DTSHD_CORE}},
209 {SPA_AUDIO_IEC958_CODEC_AC3, {CAEStreamInfo::STREAM_TYPE_AC3}},
210 {SPA_AUDIO_IEC958_CODEC_EAC3, {CAEStreamInfo::STREAM_TYPE_EAC3}},
211 {SPA_AUDIO_IEC958_CODEC_TRUEHD, {CAEStreamInfo::STREAM_TYPE_TRUEHD}},
212 {SPA_AUDIO_IEC958_CODEC_DTSHD, {CAEStreamInfo::STREAM_TYPE_DTSHD,
213 CAEStreamInfo::STREAM_TYPE_DTSHD_MA}},
214 });
215 // clang-format on
216
217 const auto it = codecMap.find(codec);
218 if (it != codecMap.cend())
219 return it->second;
220
221 return {};
222 }
223
224 std::chrono::duration<double, std::ratio<1>> PWTimeToAEDelay(const pw_time& time,
225 const uint32_t& samplerate)
226 {
227 const auto now = std::chrono::steady_clock::now();
228
229 const int64_t diff = now.time_since_epoch().count() - time.now;
230 const int64_t elapsed = (time.rate.denom * diff) / (time.rate.num * SPA_NSEC_PER_SEC);
231
232 const double fraction = static_cast<double>(time.rate.num) / time.rate.denom;
233
234 const auto delay = std::chrono::duration<double, std::ratio<1>>(
235 (time.buffered * fraction) + ((time.delay - elapsed) * fraction) +
236 (static_cast<double>(time.queued) / samplerate));
237
238 return delay;
239 }
240
241 constexpr std::chrono::duration<double, std::ratio<1>> DEFAULT_BUFFER_DURATION = 0.200s;
242 constexpr int DEFAULT_PERIODS = 4;
243 constexpr std::chrono::duration<double, std::ratio<1>> DEFAULT_PERIOD_DURATION =
244 DEFAULT_BUFFER_DURATION / DEFAULT_PERIODS;
245
246 constexpr int DEFAULT_LATENCY_DIVIDER = 3;
247
248 } // namespace
249
250 using namespace AE::SINK;
251 using namespace KODI;
252
253 std::unique_ptr<PIPEWIRE::CPipewire> pipewire;
254
255 bool CAESinkPipewire::Register()
256 {
257 pipewire = PIPEWIRE::CPipewire::Create();
258 if (!pipewire)
259 return false;
260
261 AE::AESinkRegEntry entry;
262 entry.sinkName = "PIPEWIRE";
263 entry.createFunc = CAESinkPipewire::Create;
264 entry.enumerateFunc = CAESinkPipewire::EnumerateDevicesEx;
265 entry.cleanupFunc = CAESinkPipewire::Destroy;
266 AE::CAESinkFactory::RegisterSink(entry);
267
268 return true;
269 }
270
271 std::unique_ptr<IAESink> CAESinkPipewire::Create(std::string& device, AEAudioFormat& desiredFormat)
272 {
273 auto sink = std::make_unique<CAESinkPipewire>();
274 if (sink->Initialize(desiredFormat, device))
275 return sink;
276
277 return {};
278 }
279
280 void CAESinkPipewire::EnumerateDevicesEx(AEDeviceInfoList& list, bool force)
281 {
282 auto& loop = pipewire->GetThreadLoop();
283
284 PIPEWIRE::CLoopLockGuard lock(loop);
285
286 CAEDeviceInfo defaultDevice;
287 defaultDevice.m_deviceType = AE_DEVTYPE_PCM;
288 defaultDevice.m_deviceName = "Default";
289 defaultDevice.m_displayName = "Default";
290 defaultDevice.m_displayNameExtra = "Default Output Device (PIPEWIRE)";
291 defaultDevice.m_wantsIECPassthrough = true;
292
293 std::for_each(formatMap.cbegin(), formatMap.cend(),
294 [&defaultDevice](const auto& pair)
295 { defaultDevice.m_dataFormats.emplace_back(pair.second); });
296
297 std::for_each(defaultSampleRates.cbegin(), defaultSampleRates.cend(),
298 [&defaultDevice](const auto& rate)
299 { defaultDevice.m_sampleRates.emplace_back(rate); });
300
301 defaultDevice.m_channels = CAEChannelInfo(AE_CH_LAYOUT_2_0);
302
303 list.emplace_back(defaultDevice);
304
305 auto& registry = pipewire->GetRegistry();
306 std::lock_guard lg(registry);
307
308 for (const auto& [id, global] : registry.GetGlobals())
309 {
310 CAEDeviceInfo device;
311 device.m_deviceType = AE_DEVTYPE_PCM;
312 device.m_deviceName = global->GetName();
313 device.m_displayName = global->GetDescription();
314 device.m_displayNameExtra = StringUtils::Format("{} (PIPEWIRE)", global->GetDescription());
315 device.m_wantsIECPassthrough = true;
316
317 std::for_each(formatMap.cbegin(), formatMap.cend(),
318 [&device](const auto& pair) { device.m_dataFormats.emplace_back(pair.second); });
319
320 std::for_each(defaultSampleRates.cbegin(), defaultSampleRates.cend(),
321 [&device](const auto& rate) { device.m_sampleRates.emplace_back(rate); });
322
323 auto& node = global->GetNode();
324 node.EnumerateFormats();
325
326 int ret = loop.Wait(5s);
327 if (ret == -ETIMEDOUT)
328 {
329 CLog::Log(LOGDEBUG,
330 "CAESinkPipewire::{} - timed out out waiting for formats to be enumerated",
331 __FUNCTION__);
332 continue;
333 }
334
335 auto& channels = node.GetChannels();
336 if (channels.size() < 1)
337 continue;
338
339 for (const auto& channel : channels)
340 {
341 const auto ch = channelMap.find(channel);
342 if (ch != channelMap.cend())
343 device.m_channels += ch->second;
344 }
345
346 for (const auto& iec958Codec : node.GetIEC958Codecs())
347 {
348 auto streamTypes = PWIEC958CodecToAEStreamInfoDataTypeList(iec958Codec);
349 device.m_streamTypes.insert(device.m_streamTypes.end(), streamTypes.begin(),
350 streamTypes.end());
351 }
352
353 // If DTS-HD-MA or TrueHD are configured 8 channels are needed
354 bool hasHBRFormat = std::any_of(device.m_streamTypes.cbegin(), device.m_streamTypes.cend(),
355 [](const auto& streamType)
356 {
357 return streamType == CAEStreamInfo::STREAM_TYPE_TRUEHD ||
358 streamType == CAEStreamInfo::STREAM_TYPE_DTSHD_MA;
359 });
360
361 if (!device.m_streamTypes.empty())
362 {
363 device.m_dataFormats.emplace_back(AE_FMT_RAW);
364 if (!hasHBRFormat && device.m_channels.Count() == 2)
365 {
366 device.m_deviceType = AE_DEVTYPE_IEC958;
367 }
368 else
369 {
370 device.m_deviceType = AE_DEVTYPE_HDMI;
371 }
372 }
373
374 list.emplace_back(device);
375 }
376 }
377
378 void CAESinkPipewire::Destroy()
379 {
380 pipewire.reset();
381 }
382
383 bool CAESinkPipewire::Initialize(AEAudioFormat& format, std::string& device)
384 {
385 auto& core = pipewire->GetCore();
386 auto& loop = pipewire->GetThreadLoop();
387
388 PIPEWIRE::CLoopLockGuard lock(loop);
389
390 auto& registry = pipewire->GetRegistry();
391 auto& globals = registry.GetGlobals();
392
393 uint32_t id;
394 if (device == "Default")
395 {
396 id = PW_ID_ANY;
397 }
398 else
399 {
400 auto target = std::find_if(globals.begin(), globals.end(),
401 [&device](const auto& p)
402 {
403 const auto& [globalId, global] = p;
404 return device == global->GetName();
405 });
406 if (target == globals.end())
407 return false;
408
409 id = target->first;
410 }
411
412 bool passthrough = (format.m_dataFormat == AE_FMT_RAW);
413
414 if (passthrough)
415 {
416 format.m_channelLayout = AE_CH_LAYOUT_2_0;
417
418 if (format.m_streamInfo.m_type == CAEStreamInfo::STREAM_TYPE_DTSHD_MA ||
419 format.m_streamInfo.m_type == CAEStreamInfo::STREAM_TYPE_TRUEHD)
420 format.m_channelLayout = AE_CH_LAYOUT_7_1;
421 }
422
423 m_stream = std::make_unique<PIPEWIRE::CPipewireStream>(core);
424
425 m_latency = DEFAULT_BUFFER_DURATION;
426 uint32_t frames = std::nearbyint(DEFAULT_PERIOD_DURATION.count() * format.m_sampleRate);
427 std::string fraction =
428 StringUtils::Format("{}/{}", frames / DEFAULT_LATENCY_DIVIDER, format.m_sampleRate);
429
430 std::string srate = StringUtils::Format("1/{}", format.m_sampleRate);
431
432 std::array<spa_dict_item, 6> items = {
433 SPA_DICT_ITEM_INIT(PW_KEY_MEDIA_TYPE, "Audio"),
434 SPA_DICT_ITEM_INIT(PW_KEY_MEDIA_CATEGORY, "Playback"),
435 SPA_DICT_ITEM_INIT(PW_KEY_APP_NAME, CCompileInfo::GetAppName()),
436 SPA_DICT_ITEM_INIT(PW_KEY_NODE_NAME, CCompileInfo::GetAppName()),
437 SPA_DICT_ITEM_INIT(PW_KEY_NODE_LATENCY, fraction.c_str()),
438 SPA_DICT_ITEM_INIT(PW_KEY_NODE_RATE, srate.c_str())};
439
440 auto properties = SPA_DICT_INIT(items.data(), items.size());
441 m_stream->UpdateProperties(&properties);
442
443 auto pwFormat = AEFormatToPWFormat(format.m_dataFormat);
444 format.m_dataFormat = PWFormatToAEFormat(pwFormat);
445
446 auto pwChannels = AEChannelMapToPWChannelMap(format.m_channelLayout);
447 format.m_channelLayout = PWChannelMapToAEChannelMap(pwChannels);
448
449 std::array<uint8_t, 1024> buffer;
450 auto builder = SPA_POD_BUILDER_INIT(buffer.data(), buffer.size());
451
452 std::vector<const spa_pod*> params;
453
454 // clang-format off
455 params.emplace_back(static_cast<const spa_pod*>(spa_pod_builder_add_object(
456 &builder, SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers,
457 SPA_PARAM_BUFFERS_buffers, SPA_POD_CHOICE_RANGE_Int(20, 16, 24),
458 SPA_PARAM_BUFFERS_blocks, SPA_POD_Int(1),
459 SPA_PARAM_BUFFERS_size, SPA_POD_Int(frames * pwChannels.size() * PWFormatToSampleSize(pwFormat)),
460 SPA_PARAM_BUFFERS_stride, SPA_POD_Int(pwChannels.size() * PWFormatToSampleSize(pwFormat)))));
461 // clang-format on
462
463 pw_stream_flags flags =
464 static_cast<pw_stream_flags>(PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_INACTIVE |
465 PW_STREAM_FLAG_MAP_BUFFERS | PW_STREAM_FLAG_DRIVER);
466
467 if (!passthrough)
468 {
469 spa_audio_info_raw info{};
470 info.format = pwFormat;
471 info.flags = SPA_AUDIO_FLAG_NONE;
472 info.rate = format.m_sampleRate;
473 info.channels = static_cast<uint32_t>(pwChannels.size());
474
475 for (size_t index = 0; index < pwChannels.size(); index++)
476 info.position[index] = pwChannels[index];
477
478 params.emplace_back(spa_format_audio_raw_build(&builder, SPA_PARAM_EnumFormat, &info));
479 }
480
481 if (passthrough)
482 {
483 spa_audio_info_iec958 info{};
484 info.codec = AEStreamInfoDataTypeToPWIEC958Codec(format.m_streamInfo.m_type);
485 info.flags = SPA_AUDIO_FLAG_NONE;
486 info.rate = format.m_sampleRate;
487
488 params.emplace_back(spa_format_audio_iec958_build(&builder, SPA_PARAM_EnumFormat, &info));
489
490 flags = static_cast<pw_stream_flags>(PW_STREAM_FLAG_EXCLUSIVE | static_cast<int>(flags));
491
492 format.m_dataFormat = AE_FMT_S16NE;
493 }
494
495 if (!m_stream->Connect(id, PW_DIRECTION_OUTPUT, params, flags))
496 return false;
497
498 CLog::Log(LOGDEBUG, "CAESinkPipewire::{} - rate: {}", __FUNCTION__, format.m_sampleRate);
499 CLog::Log(LOGDEBUG, "CAESinkPipewire::{} - channels: {}", __FUNCTION__, pwChannels.size());
500 CLog::Log(LOGDEBUG, "CAESinkPipewire::{} - format: {}", __FUNCTION__, PWFormatToString(pwFormat));
501 CLog::Log(LOGDEBUG, "CAESinkPipewire::{} - samplesize: {}", __FUNCTION__,
502 PWFormatToSampleSize(pwFormat));
503 CLog::Log(LOGDEBUG, "CAESinkPipewire::{} - framesize: {}", __FUNCTION__,
504 pwChannels.size() * PWFormatToSampleSize(pwFormat));
505 CLog::Log(LOGDEBUG, "CAESinkPipewire::{} - latency: {}/{} ({:.3f}s)", __FUNCTION__, frames,
506 format.m_sampleRate,
507 static_cast<double>(frames) / DEFAULT_LATENCY_DIVIDER / format.m_sampleRate);
508
509 pw_stream_state state;
510 do
511 {
512 state = m_stream->GetState();
513 if (state == PW_STREAM_STATE_PAUSED)
514 break;
515
516 CLog::Log(LOGDEBUG, "CAESinkPipewire::{} - waiting", __FUNCTION__);
517
518 int ret = loop.Wait(5s);
519 if (ret == -ETIMEDOUT)
520 {
521 CLog::Log(LOGDEBUG, "CAESinkPipewire::{} - timed out waiting for stream to be paused",
522 __FUNCTION__);
523 return false;
524 }
525 } while (state != PW_STREAM_STATE_PAUSED);
526
527 CLog::Log(LOGDEBUG, "CAESinkPipewire::{} - initialized", __FUNCTION__);
528
529 format.m_frameSize = pwChannels.size() * PWFormatToSampleSize(pwFormat);
530 format.m_frames = frames;
531
532 m_format = format;
533
534 return true;
535 }
536
537 void CAESinkPipewire::Deinitialize()
538 {
539 auto& loop = pipewire->GetThreadLoop();
540
541 PIPEWIRE::CLoopLockGuard lock(loop);
542
543 m_stream->Flush(false);
544
545 m_stream.reset();
546 }
547
548 double CAESinkPipewire::GetCacheTotal()
549 {
550 return m_latency.count();
551 }
552
553 unsigned int CAESinkPipewire::AddPackets(uint8_t** data, unsigned int frames, unsigned int offset)
554 {
555 const auto start = std::chrono::steady_clock::now();
556
557 auto& loop = pipewire->GetThreadLoop();
558
559 PIPEWIRE::CLoopLockGuard lock(loop);
560
561 if (m_stream->GetState() == PW_STREAM_STATE_PAUSED)
562 m_stream->SetActive(true);
563
564 pw_buffer* pwBuffer = nullptr;
565 while (!pwBuffer)
566 {
567 pwBuffer = m_stream->DequeueBuffer();
568 if (pwBuffer)
569 break;
570
571 int ret = loop.Wait(1s);
572 if (ret == -ETIMEDOUT)
573 return 0;
574 }
575
576 pwBuffer->size = frames;
577
578 spa_buffer* spaBuffer = pwBuffer->buffer;
579 spa_data* spaData = &spaBuffer->datas[0];
580
581 size_t length = frames * m_format.m_frameSize;
582
583 void* buffer = data[0] + offset * m_format.m_frameSize;
584
585 std::memcpy(spaData->data, buffer, length);
586
587 spaData->chunk->offset = 0;
588 spaData->chunk->stride = m_format.m_frameSize;
589 spaData->chunk->size = length;
590
591 m_stream->QueueBuffer(pwBuffer);
592
593 const auto period = std::chrono::duration<double, std::ratio<1>>(static_cast<double>(frames) /
594 m_format.m_sampleRate);
595
596 do
597 {
598 pw_time time = m_stream->GetTime();
599
600 const std::chrono::duration<double, std::ratio<1>> delay =
601 PWTimeToAEDelay(time, m_format.m_sampleRate);
602
603 const auto now = std::chrono::steady_clock::now();
604
605 if ((delay <= (DEFAULT_BUFFER_DURATION - DEFAULT_PERIOD_DURATION)) || ((now - start) >= period))
606 break;
607
608 loop.Wait(5ms);
609
610 } while (true);
611
612 if (m_stream->IsDriving())
613 m_stream->TriggerProcess();
614
615 return frames;
616 }
617
618 void CAESinkPipewire::GetDelay(AEDelayStatus& status)
619 {
620 auto& loop = pipewire->GetThreadLoop();
621
622 PIPEWIRE::CLoopLockGuard lock(loop);
623
624 pw_stream_state state = m_stream->GetState();
625
626 pw_time time = m_stream->GetTime();
627
628 if (state != PW_STREAM_STATE_STREAMING)
629 return;
630
631 const std::chrono::duration<double, std::ratio<1>> delay =
632 PWTimeToAEDelay(time, m_format.m_sampleRate);
633
634 status.SetDelay(delay.count());
635 }
636
637 void CAESinkPipewire::Drain()
638 {
639 auto& loop = pipewire->GetThreadLoop();
640
641 PIPEWIRE::CLoopLockGuard lock(loop);
642
643 m_stream->Flush(true);
644
645 int ret = loop.Wait(1s);
646 if (ret == -ETIMEDOUT)
647 {
648 CLog::Log(LOGDEBUG, "CAESinkPipewire::{} - wait timed out, already drained?", __FUNCTION__);
649 }
650 }