| 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 "Pipewire.h" |
| 10 | |
| 11 | #include "PipewireContext.h" |
| 12 | #include "PipewireCore.h" |
| 13 | #include "PipewireRegistry.h" |
| 14 | #include "PipewireThreadLoop.h" |
| 15 | #include "commons/ilog.h" |
| 16 | #include "utils/log.h" |
| 17 | |
| 18 | #include <pipewire/pipewire.h> |
| 19 | |
| 20 | using namespace std::chrono_literals; |
| 21 | |
| 22 | using namespace KODI; |
| 23 | using namespace PIPEWIRE; |
| 24 | |
| 25 | CPipewire::CPipewire() |
| 26 | { |
| 27 | pw_init(nullptr, nullptr); |
| 28 | } |
| 29 | |
| 30 | CPipewire::~CPipewire() |
| 31 | { |
| 32 | if (m_loop) |
| 33 | m_loop->Lock(); |
| 34 | |
| 35 | m_registry.reset(); |
| 36 | m_core.reset(); |
| 37 | m_context.reset(); |
| 38 | |
| 39 | if (m_loop) |
| 40 | { |
| 41 | m_loop->Unlock(); |
| 42 | m_loop->Stop(); |
| 43 | } |
| 44 | |
| 45 | m_loop.reset(); |
| 46 | |
| 47 | pw_deinit(); |
| 48 | } |
| 49 | |
| 50 | bool CPipewire::Start() |
| 51 | { |
| 52 | m_loop = std::make_unique<CPipewireThreadLoop>(); |
| 53 | |
| 54 | m_context = std::make_unique<CPipewireContext>(*m_loop); |
| 55 | |
| 56 | PIPEWIRE::CLoopLockGuard lock(*m_loop); |
| 57 | |
| 58 | if (!m_loop->Start()) |
| 59 | { |
| 60 | CLog::Log(LOGERROR, "Pipewire: failed to start threaded mainloop: {}", strerror(errno)); |
| 61 | return false; |
| 62 | } |
| 63 | |
| 64 | try |
| 65 | { |
| 66 | m_core = std::make_unique<CPipewireCore>(*m_context); |
| 67 | } |
| 68 | catch (std::exception& e) |
| 69 | { |
| 70 | CLog::Log(LOGERROR, "Pipewire: failed to connect to server"); |
| 71 | return false; |
| 72 | } |
| 73 | |
| 74 | CLog::Log(LOGINFO, "Pipewire: connected to server"); |
| 75 | |
| 76 | m_registry = std::make_unique<CPipewireRegistry>(*m_core); |
| 77 | |
| 78 | m_core->Sync(); |
| 79 | |
| 80 | int ret = m_loop->Wait(5s); |
| 81 | if (ret == -ETIMEDOUT) |
| 82 | { |
| 83 | CLog::Log(LOGDEBUG, "Pipewire: timed out out waiting for synchronization"); |
| 84 | return false; |
| 85 | } |
| 86 | |
| 87 | return true; |
| 88 | } |
| 89 | |
| 90 | std::unique_ptr<CPipewire> CPipewire::Create() |
| 91 | { |
| 92 | struct PipewireMaker : public CPipewire |
| 93 | { |
| 94 | using CPipewire::CPipewire; |
| 95 | }; |
| 96 | |
| 97 | try |
| 98 | { |
| 99 | auto pipewire = std::make_unique<PipewireMaker>(); |
| 100 | |
| 101 | if (!pipewire->Start()) |
| 102 | return {}; |
| 103 | |
| 104 | return pipewire; |
| 105 | } |
| 106 | catch (const std::exception& e) |
| 107 | { |
| 108 | CLog::Log(LOGWARNING, "Pipewire: Exception in 'Create': {}", e.what()); |
| 109 | return {}; |
| 110 | } |
| 111 | } |