-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathsdl_media_manager.cpp
More file actions
402 lines (339 loc) · 11.6 KB
/
sdl_media_manager.cpp
File metadata and controls
402 lines (339 loc) · 11.6 KB
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
/*
* Copyright 2025 LiveKit, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sdl_media_manager.h"
#include "fallback_capture.h"
#include "livekit/livekit.h"
#include "livekit/lk_log.h"
#include "sdl_media.h"
#include "sdl_video_renderer.h"
#include <cstring>
#include <vector>
using namespace livekit;
SDLMediaManager::SDLMediaManager() = default;
SDLMediaManager::~SDLMediaManager() {
stopMic();
stopCamera();
stopSpeaker();
shutdownRenderer();
}
bool SDLMediaManager::ensureSDLInit(Uint32 flags) {
if ((SDL_WasInit(flags) & flags) == flags) {
return true; // already init
}
if (!SDL_InitSubSystem(flags)) {
LK_LOG_ERROR("SDL_InitSubSystem failed (flags={}): {}", flags,
SDL_GetError());
return false;
}
return true;
}
// ---------- Mic control ----------
bool SDLMediaManager::startMic(
const std::shared_ptr<AudioSource> &audio_source) {
stopMic();
if (!audio_source) {
LK_LOG_ERROR("startMic: audioSource is null");
return false;
}
mic_source_ = audio_source;
mic_running_.store(true, std::memory_order_relaxed);
// Try SDL path
if (!ensureSDLInit(SDL_INIT_AUDIO)) {
LK_LOG_WARN("No SDL audio, falling back to noise loop.");
mic_using_sdl_ = false;
mic_thread_ =
std::thread(runNoiseCaptureLoop, mic_source_, std::ref(mic_running_));
return true;
}
int recCount = 0;
SDL_AudioDeviceID *recDevs = SDL_GetAudioRecordingDevices(&recCount);
if (!recDevs || recCount == 0) {
LK_LOG_WARN("No microphone devices found, falling back to noise loop.");
if (recDevs)
SDL_free(recDevs);
mic_using_sdl_ = false;
mic_thread_ =
std::thread(runNoiseCaptureLoop, mic_source_, std::ref(mic_running_));
return true;
}
SDL_free(recDevs);
// We have at least one mic; use SDL
mic_using_sdl_ = true;
mic_sdl_ = std::make_unique<SDLMicSource>(
mic_source_->sample_rate(), mic_source_->num_channels(),
mic_source_->sample_rate() / 100, // ~10ms
[src = mic_source_](const int16_t *samples, int num_samples_per_channel,
int sample_rate, int num_channels) {
AudioFrame frame = AudioFrame::create(sample_rate, num_channels,
num_samples_per_channel);
std::memcpy(frame.data().data(), samples,
num_samples_per_channel * num_channels * sizeof(int16_t));
try {
src->captureFrame(frame);
} catch (const std::exception &e) {
LK_LOG_ERROR("Error in captureFrame (SDL mic): {}", e.what());
}
});
if (!mic_sdl_->init()) {
LK_LOG_WARN("Failed to init SDL mic, falling back to noise loop.");
mic_using_sdl_ = false;
mic_sdl_.reset();
mic_thread_ =
std::thread(runNoiseCaptureLoop, mic_source_, std::ref(mic_running_));
return true;
}
mic_thread_ = std::thread(&SDLMediaManager::micLoopSDL, this);
return true;
}
void SDLMediaManager::micLoopSDL() {
while (mic_running_.load(std::memory_order_relaxed)) {
mic_sdl_->pump();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void SDLMediaManager::stopMic() {
mic_running_.store(false, std::memory_order_relaxed);
if (mic_thread_.joinable()) {
mic_thread_.join();
}
mic_sdl_.reset();
mic_source_.reset();
}
// ---------- Camera control ----------
bool SDLMediaManager::startCamera(
const std::shared_ptr<VideoSource> &video_source) {
stopCamera();
if (!video_source) {
LK_LOG_ERROR("startCamera: videoSource is null");
return false;
}
cam_source_ = video_source;
cam_running_.store(true, std::memory_order_relaxed);
// Try SDL
if (!ensureSDLInit(SDL_INIT_CAMERA)) {
LK_LOG_WARN("No SDL camera subsystem, using fake video loop.");
cam_using_sdl_ = false;
cam_thread_ = std::thread(runFakeVideoCaptureLoop, cam_source_,
std::ref(cam_running_));
return true;
}
int camCount = 0;
SDL_CameraID *cams = SDL_GetCameras(&camCount);
if (!cams || camCount == 0) {
LK_LOG_WARN("No camera devices found, using fake video loop.");
if (cams)
SDL_free(cams);
cam_using_sdl_ = false;
cam_thread_ = std::thread(runFakeVideoCaptureLoop, cam_source_,
std::ref(cam_running_));
return true;
}
SDL_free(cams);
cam_using_sdl_ = true;
can_sdl_ = std::make_unique<SDLCamSource>(
1280, 720, 30,
SDL_PIXELFORMAT_RGBA32, // Note SDL_PIXELFORMAT_RGBA8888 is not compatable
// with Livekit RGBA format.
[src = cam_source_](const uint8_t *pixels, int pitch, int width,
int height, SDL_PixelFormat /*fmt*/,
Uint64 timestampNS) {
auto frame = VideoFrame::create(width, height, VideoBufferType::RGBA);
uint8_t *dst = frame.data();
const int dstPitch = width * 4;
for (int y = 0; y < height; ++y) {
std::memcpy(dst + y * dstPitch, pixels + y * pitch, dstPitch);
}
try {
src->captureFrame(frame, timestampNS / 1000,
VideoRotation::VIDEO_ROTATION_0);
} catch (const std::exception &e) {
LK_LOG_ERROR("Error in captureFrame (SDL cam): {}", e.what());
}
});
if (!can_sdl_->init()) {
LK_LOG_WARN("Failed to init SDL camera, using fake video loop.");
cam_using_sdl_ = false;
can_sdl_.reset();
cam_thread_ = std::thread(runFakeVideoCaptureLoop, cam_source_,
std::ref(cam_running_));
return true;
}
cam_thread_ = std::thread(&SDLMediaManager::cameraLoopSDL, this);
return true;
}
void SDLMediaManager::cameraLoopSDL() {
while (cam_running_.load(std::memory_order_relaxed)) {
can_sdl_->pump();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
void SDLMediaManager::stopCamera() {
cam_running_.store(false, std::memory_order_relaxed);
if (cam_thread_.joinable()) {
cam_thread_.join();
}
can_sdl_.reset();
cam_source_.reset();
}
// ---------- Speaker control (placeholder) ----------
bool SDLMediaManager::startSpeaker(
const std::shared_ptr<AudioStream> &audio_stream) {
stopSpeaker();
if (!audio_stream) {
LK_LOG_ERROR("startSpeaker: audioStream is null");
return false;
}
if (!ensureSDLInit(SDL_INIT_AUDIO)) {
LK_LOG_ERROR("startSpeaker: SDL_INIT_AUDIO failed");
return false;
}
speaker_stream_ = audio_stream;
speaker_running_.store(true, std::memory_order_relaxed);
// Note, we don't open the speaker since the format is unknown yet.
// Instead, open the speaker in the speakerLoopSDL thread with the native
// format.
try {
speaker_thread_ = std::thread(&SDLMediaManager::speakerLoopSDL, this);
} catch (const std::exception &e) {
LK_LOG_ERROR("startSpeaker: failed to start speaker thread: {}", e.what());
speaker_running_.store(false, std::memory_order_relaxed);
speaker_stream_.reset();
return false;
}
return true;
}
void SDLMediaManager::speakerLoopSDL() {
SDL_AudioStream *localStream = nullptr;
SDL_AudioDeviceID dev = 0;
while (speaker_running_.load(std::memory_order_relaxed)) {
if (!speaker_stream_) {
break;
}
livekit::AudioFrameEvent ev;
if (!speaker_stream_->read(ev)) {
// EOS or closed
break;
}
const livekit::AudioFrame &frame = ev.frame;
const auto &data = frame.data();
if (data.empty()) {
continue;
}
// Lazily open SDL audio stream based on the first frame's format, so no
// resampler is needed.
if (!localStream) {
SDL_AudioSpec want{};
want.format = SDL_AUDIO_S16;
want.channels = static_cast<Uint8>(frame.num_channels());
want.freq = frame.sample_rate();
localStream =
SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &want,
/*callback=*/nullptr,
/*userdata=*/nullptr);
if (!localStream) {
LK_LOG_ERROR("speakerLoopSDL: SDL_OpenAudioDeviceStream failed: {}",
SDL_GetError());
break;
}
sdl_audio_stream_ = localStream; // store if you want to inspect later
dev = SDL_GetAudioStreamDevice(localStream);
if (dev == 0) {
LK_LOG_ERROR("speakerLoopSDL: SDL_GetAudioStreamDevice failed: {}",
SDL_GetError());
break;
}
if (!SDL_ResumeAudioDevice(dev)) {
LK_LOG_ERROR("speakerLoopSDL: SDL_ResumeAudioDevice failed: {}",
SDL_GetError());
break;
}
}
// Push PCM to SDL. We assume frames are already S16, interleaved, matching
// sample_rate / channels we used above.
const int numBytes = static_cast<int>(data.size() * sizeof(std::int16_t));
if (!SDL_PutAudioStreamData(localStream, data.data(), numBytes)) {
LK_LOG_ERROR("speakerLoopSDL: SDL_PutAudioStreamData failed: {}",
SDL_GetError());
break;
}
// Tiny sleep to avoid busy loop; SDL buffers internally.
SDL_Delay(2);
}
if (localStream) {
SDL_DestroyAudioStream(localStream);
localStream = nullptr;
sdl_audio_stream_ = nullptr;
}
speaker_running_.store(false, std::memory_order_relaxed);
}
void SDLMediaManager::stopSpeaker() {
speaker_running_.store(false, std::memory_order_relaxed);
if (speaker_thread_.joinable()) {
speaker_thread_.join();
}
if (sdl_audio_stream_) {
SDL_DestroyAudioStream(sdl_audio_stream_);
sdl_audio_stream_ = nullptr;
}
speaker_stream_.reset();
}
// ---------- Renderer control (placeholder) ----------
bool SDLMediaManager::initRenderer(
const std::shared_ptr<VideoStream> &video_stream) {
if (!video_stream) {
LK_LOG_ERROR("startRenderer: videoStream is null");
return false;
}
// Ensure SDL video subsystem is initialized
if (!ensureSDLInit(SDL_INIT_VIDEO)) {
LK_LOG_ERROR("startRenderer: SDL_INIT_VIDEO failed");
return false;
}
renderer_stream_ = video_stream;
renderer_running_.store(true, std::memory_order_relaxed);
// Lazily create the SDLVideoRenderer
if (!sdl_renderer_) {
sdl_renderer_ = std::make_unique<SDLVideoRenderer>();
// You can tune these dimensions or even make them options
if (!sdl_renderer_->init("LiveKit Remote Video", 1280, 720)) {
LK_LOG_ERROR("startRenderer: SDLVideoRenderer::init failed");
sdl_renderer_.reset();
renderer_stream_.reset();
renderer_running_.store(false, std::memory_order_relaxed);
return false;
}
}
// Start the SDL renderer's own render thread
sdl_renderer_->setStream(renderer_stream_);
return true;
}
void SDLMediaManager::shutdownRenderer() {
renderer_running_.store(false, std::memory_order_relaxed);
// Shut down SDL renderer thread if it exists
if (sdl_renderer_) {
sdl_renderer_->shutdown();
}
// Old renderer_thread_ is no longer used, but if you still have it:
if (renderer_thread_.joinable()) {
renderer_thread_.join();
}
renderer_stream_.reset();
}
void SDLMediaManager::render() {
if (renderer_running_.load(std::memory_order_relaxed) && sdl_renderer_) {
sdl_renderer_->render();
}
}