OpenShot Library | libopenshot 1.1.1
Loading...
Searching...
No Matches
ScreenCaptureReader.cpp
Go to the documentation of this file.
1
8
9// Copyright (c) 2008-2026 OpenShot Studios, LLC
10//
11// SPDX-License-Identifier: LGPL-3.0-or-later
12
13#include "ScreenCaptureReader.h"
14#include "FFmpegColorRange.h"
15#include "CaptureAudioBuffer.h"
16
17#include <algorithm>
18#include <cctype>
19#include <chrono>
20#include <condition_variable>
21#include <cstdlib>
22#include <deque>
23#include <limits>
24#include <mutex>
25#include <sstream>
26#include <thread>
27#include <vector>
28
29#if defined(__linux__)
30 #include <dlfcn.h>
31#endif
32
33extern "C" {
34 #include <libavdevice/avdevice.h>
35 #include <libavutil/imgutils.h>
36 #include <libavutil/time.h>
37}
38
39#if defined(_WIN32)
40 // Instantiate the Core Audio COM GUIDs in this translation unit. Older
41 // MinGW-w64 uuid import libraries do not provide all WASAPI identifiers.
42 #include <initguid.h>
43 #include <audioclient.h>
44 #include <mmdeviceapi.h>
45#endif
46
47#include "Exceptions.h"
48#include "Frame.h"
49#include "QtUtilities.h"
50
51using namespace openshot;
52
53#if defined(HAVE_WAYLAND_CAPTURE_PLUGIN) && defined(__linux__)
54namespace
55{
56 using WaylandBackendFactory = std::unique_ptr<ScreenCaptureReader::CaptureBackendReader> (*) (
58
59 void* load_wayland_capture_backend(std::string& error_message)
60 {
61 Dl_info library_info {};
62 if (dladdr(reinterpret_cast<void*>(load_wayland_capture_backend), &library_info)
63 && library_info.dli_fname) {
64 std::string library_path(library_info.dli_fname);
65 const auto separator = library_path.find_last_of('/');
66 if (separator != std::string::npos) {
67 const std::string private_module_path = library_path.substr(0, separator + 1)
68 + "libopenshot/libopenshot-wayland-capture.so";
69 if (void* module = dlopen(private_module_path.c_str(), RTLD_NOW | RTLD_LOCAL)) {
70 return module;
71 }
72 const std::string module_path = library_path.substr(0, separator + 1)
73 + "libopenshot-wayland-capture.so";
74 if (void* module = dlopen(module_path.c_str(), RTLD_NOW | RTLD_LOCAL)) {
75 return module;
76 }
77 const char* error = dlerror();
78 error_message = error ? error : "unable to load PipeWire support.";
79 return nullptr;
80 }
81 }
82 void* module = dlopen("libopenshot-wayland-capture.so", RTLD_NOW | RTLD_LOCAL);
83 if (!module) {
84 const char* error = dlerror();
85 error_message = error ? error : "unable to load PipeWire support.";
86 }
87 return module;
88 }
89}
90#endif
91
92#if defined(__linux__)
94{
95public:
96 explicit SystemAudioCapture(const ScreenCaptureSettings& new_settings)
97 : settings(new_settings) {}
98
100
101 void Open()
102 {
103 if (format_context) return;
104 avdevice_register_all();
105 AVInputFormat* input_format = const_cast<AVInputFormat*>(av_find_input_format("pulse"));
106 if (!input_format) {
107 throw InvalidOptions("FFmpeg PulseAudio input is unavailable for system audio capture.");
108 }
109
110 format_context = avformat_alloc_context();
111 if (!format_context) {
112 throw OutOfMemory("Unable to allocate system audio capture context.");
113 }
114 format_context->interrupt_callback.callback = InterruptCallback;
115 format_context->interrupt_callback.opaque = &close_requested;
116
117 AVDictionary* options = nullptr;
118 av_dict_set(&options, "wallclock", "1", 0);
119 // Pulse defaults to server-selected buffering, which can deliver large
120 // batches too late for a live video frame. Request 20 ms of default
121 // 16-bit PCM; timestamps still determine placement, not this buffer size.
122 av_dict_set_int(&options, "fragment_size",
123 static_cast<int64_t>(settings.audio_sample_rate) * settings.audio_channels * 2 / 50, 0);
124 av_dict_set(&options, "sample_rate", std::to_string(settings.audio_sample_rate).c_str(), 0);
125 av_dict_set(&options, "channels", std::to_string(settings.audio_channels).c_str(), 0);
126 const std::string device = settings.audio_device.empty() ? "@DEFAULT_MONITOR@" : settings.audio_device;
127 const int open_result = avformat_open_input(&format_context, device.c_str(), input_format, &options);
128 av_dict_free(&options);
129 if (open_result < 0) {
130 throw InvalidFile("Unable to open system audio capture input: " + std::string(av_err2str(open_result)), device);
131 }
132 if (avformat_find_stream_info(format_context, nullptr) < 0) {
133 throw InvalidFile("Unable to read system audio capture stream information.", device);
134 }
135 for (unsigned int index = 0; index < format_context->nb_streams; ++index) {
136 if (format_context->streams[index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
137 audio_stream = static_cast<int>(index);
138 break;
139 }
140 }
141 if (audio_stream < 0) {
142 throw InvalidFile("No audio stream found in system audio capture input.", device);
143 }
144 AVStream* stream = format_context->streams[audio_stream];
145 const AVCodec* codec = avcodec_find_decoder(stream->codecpar->codec_id);
146 codec_context = codec ? ffmpeg_get_codec_context(stream, codec) : nullptr;
147 if (codec_context) codec_context->pkt_timebase = stream->time_base;
148 if (!codec_context || avcodec_open2(codec_context, codec, nullptr) < 0) {
149 throw InvalidCodec("Unable to open system audio capture decoder.", device);
150 }
151 packet = av_packet_alloc();
152 decoded_frame = av_frame_alloc();
153 if (!packet || !decoded_frame) {
154 throw OutOfMemory("Unable to allocate system audio capture buffers.");
155 }
156 settings.audio_sample_rate = codec_context->sample_rate > 0
157 ? codec_context->sample_rate : settings.audio_sample_rate;
158 Reset();
159 close_requested = false;
160 worker = std::thread(&SystemAudioCapture::CaptureLoop, this);
161 }
162
163 void Close()
164 {
165 close_requested = true;
166 ready.notify_all();
167 if (worker.joinable()) {
168 worker.join();
169 }
170 if (decoded_frame) av_frame_free(&decoded_frame);
171 if (packet) av_packet_free(&packet);
172 if (codec_context) avcodec_free_context(&codec_context);
173 if (format_context) avformat_close_input(&format_context);
174 }
175
176 void AddFrameAudio(const std::shared_ptr<Frame>& frame, int64_t number, const Fraction& fps)
177 {
178 int sample_count = 0;
179 for (int64_t frame_number = last_output_frame + 1; frame_number <= number; ++frame_number) {
180 sample_count += Frame::GetSamplesPerFrame(
181 frame_number, fps, settings.audio_sample_rate, settings.audio_channels);
182 }
183 last_output_frame = std::max(last_output_frame, number);
184 if (!frame || sample_count <= 0) return;
185
186 std::unique_lock<std::mutex> lock(queue_mutex);
187 // Wait for capture delivery, but keep its original sample positions. A
188 // timed-out interval becomes silence; late packets cannot move it forward.
189 const auto wait_time = timeline_started
190 ? std::chrono::milliseconds(100)
191 : std::chrono::milliseconds(3000);
192 ready.wait_for(lock, wait_time, [this, sample_count]() {
193 return close_requested || audio_buffer.Covers(sample_count);
194 });
195 timeline_started = true;
196 auto samples = audio_buffer.Read(sample_count);
197 frame->SampleRate(settings.audio_sample_rate);
198 frame->ChannelsLayout(settings.audio_channels == 1 ? LAYOUT_MONO : LAYOUT_STEREO);
199 for (int channel = 0; channel < settings.audio_channels; ++channel) {
200 frame->AddAudio(true, channel, 0, samples[channel].data(), sample_count, 1.0f);
201 }
202 }
203
204 void Reset()
205 {
206 std::lock_guard<std::mutex> lock(queue_mutex);
207 // PulseAudio wallclock PTS uses av_gettime(), corrected for input latency.
208 // Reset the epoch too, so packets buffered before recording are discarded.
209 epoch_us = av_gettime();
210 audio_buffer.Reset(settings.audio_channels, static_cast<int64_t>(settings.audio_sample_rate) * 10);
211 last_output_frame = 0;
212 timeline_started = false;
213 }
214
215 int SampleRate() const { return settings.audio_sample_rate; }
216 int Channels() const { return settings.audio_channels; }
217
218private:
219 static int InterruptCallback(void* opaque)
220 {
221 const auto* requested = static_cast<std::atomic<bool>*>(opaque);
222 return requested && requested->load() ? 1 : 0;
223 }
224
225 float SampleAt(const AVFrame* frame, int channel, int sample) const
226 {
227 const AVSampleFormat format = static_cast<AVSampleFormat>(frame->format);
228 const bool planar = av_sample_fmt_is_planar(format) != 0;
229 const int source_channels = std::max(1,
231 codec_context->ch_layout.nb_channels
232#else
233 codec_context->channels
234#endif
235 );
236 const int source_channel = std::min(channel, source_channels - 1);
237 const uint8_t* data = planar ? frame->extended_data[source_channel] : frame->extended_data[0];
238 const int offset = planar ? sample : sample * source_channels + source_channel;
239 switch (format) {
240 case AV_SAMPLE_FMT_U8: case AV_SAMPLE_FMT_U8P:
241 return (static_cast<const uint8_t*>(static_cast<const void*>(data))[offset] - 128) / 128.0f;
242 case AV_SAMPLE_FMT_S16: case AV_SAMPLE_FMT_S16P:
243 return static_cast<const int16_t*>(static_cast<const void*>(data))[offset] / 32768.0f;
244 case AV_SAMPLE_FMT_S32: case AV_SAMPLE_FMT_S32P:
245 return static_cast<float>(static_cast<const int32_t*>(static_cast<const void*>(data))[offset] / 2147483648.0);
246 case AV_SAMPLE_FMT_FLT: case AV_SAMPLE_FMT_FLTP:
247 return static_cast<const float*>(static_cast<const void*>(data))[offset];
248 case AV_SAMPLE_FMT_DBL: case AV_SAMPLE_FMT_DBLP:
249 return static_cast<float>(static_cast<const double*>(static_cast<const void*>(data))[offset]);
250 default:
251 return 0.0f;
252 }
253 }
254
255 void CaptureLoop()
256 {
257 while (!close_requested) {
258 const int read_result = av_read_frame(format_context, packet);
259 if (read_result == AVERROR(EAGAIN)) continue;
260 if (read_result < 0) break;
261 if (packet->stream_index != audio_stream) {
262 av_packet_unref(packet);
263 continue;
264 }
265 const int send_result = avcodec_send_packet(codec_context, packet);
266 av_packet_unref(packet);
267 if (send_result < 0) continue;
268 while (avcodec_receive_frame(codec_context, decoded_frame) == 0) {
269 const int64_t timestamp = decoded_frame->best_effort_timestamp != AV_NOPTS_VALUE
270 ? decoded_frame->best_effort_timestamp : decoded_frame->pts;
271 if (timestamp == AV_NOPTS_VALUE) {
272 // A packet with unknown capture time cannot be aligned safely.
273 av_frame_unref(decoded_frame);
274 continue;
275 }
276 const int64_t timestamp_us = av_rescale_q(timestamp,
277 format_context->streams[audio_stream]->time_base, AVRational{1, AV_TIME_BASE});
278 std::vector<std::vector<float>> samples(settings.audio_channels,
279 std::vector<float>(decoded_frame->nb_samples));
280 for (int channel = 0; channel < settings.audio_channels; ++channel) {
281 for (int sample = 0; sample < decoded_frame->nb_samples; ++sample) {
282 samples[channel][sample] = SampleAt(decoded_frame, channel, sample);
283 }
284 }
285 std::lock_guard<std::mutex> lock(queue_mutex);
286 audio_buffer.PushTimestamp(timestamp_us, epoch_us, AVRational{1, AV_TIME_BASE},
287 settings.audio_sample_rate, std::move(samples));
288 av_frame_unref(decoded_frame);
289 ready.notify_all();
290 }
291 }
292 }
293
294 ScreenCaptureSettings settings;
295 AVFormatContext* format_context = nullptr;
296 AVCodecContext* codec_context = nullptr;
297 AVPacket* packet = nullptr;
298 AVFrame* decoded_frame = nullptr;
299 int audio_stream = -1;
300 std::atomic<bool> close_requested { false };
301 std::thread worker;
302 std::mutex queue_mutex;
303 std::condition_variable ready;
304 CaptureAudioBuffer audio_buffer;
305 int64_t epoch_us = 0;
306 int64_t last_output_frame = 0;
307 bool timeline_started = false;
308};
309#elif defined(_WIN32)
311{
312public:
313 explicit SystemAudioCapture(const ScreenCaptureSettings& new_settings)
314 : settings(new_settings) {}
315
317
318 void Open()
319 {
320 if (worker.joinable()) return;
321 close_requested = false;
322 worker = std::thread(&SystemAudioCapture::CaptureLoop, this);
323 std::unique_lock<std::mutex> lock(state_mutex);
324 state_ready.wait_for(lock, std::chrono::seconds(5), [this]() { return opened || failed; });
325 if (!opened) {
326 close_requested = true;
327 lock.unlock();
328 if (worker.joinable()) worker.join();
329 throw InvalidOptions(error.empty() ? "Unable to open WASAPI system audio loopback capture." : error);
330 }
331 }
332
333 void Close()
334 {
335 close_requested = true;
336 ready.notify_all();
337 if (worker.joinable()) worker.join();
338 opened = false;
339 }
340
341 void AddFrameAudio(const std::shared_ptr<Frame>& frame, int64_t number, const Fraction& fps)
342 {
343 int sample_count = 0;
344 for (int64_t frame_number = last_output_frame + 1; frame_number <= number; ++frame_number) {
345 sample_count += Frame::GetSamplesPerFrame(frame_number, fps, sample_rate, channel_count);
346 }
347 last_output_frame = std::max(last_output_frame, number);
348 if (!frame || sample_count <= 0) return;
349 std::unique_lock<std::mutex> lock(queue_mutex);
350 const auto wait_time = timeline_started
351 ? std::chrono::milliseconds(100)
352 : std::chrono::milliseconds(3000);
353 ready.wait_for(lock, wait_time, [this, sample_count]() {
354 return close_requested || audio_buffer.Covers(sample_count);
355 });
356 timeline_started = true;
357 auto samples = audio_buffer.Read(sample_count);
358 frame->SampleRate(sample_rate);
359 frame->ChannelsLayout(channel_count == 1 ? LAYOUT_MONO : LAYOUT_STEREO);
360 for (int channel = 0; channel < channel_count; ++channel) {
361 frame->AddAudio(true, channel, 0, samples[channel].data(), sample_count, 1.0f);
362 }
363 }
364
365 void Reset()
366 {
367 std::lock_guard<std::mutex> lock(queue_mutex);
368 // WASAPI returns QPC timestamps already converted to 100 ns units.
369 LARGE_INTEGER counter, frequency;
370 QueryPerformanceCounter(&counter);
371 QueryPerformanceFrequency(&frequency);
372 epoch_100ns = av_rescale(counter.QuadPart, 10000000, frequency.QuadPart);
373 audio_buffer.Reset(channel_count, static_cast<int64_t>(sample_rate) * 10);
374 last_output_frame = 0;
375 timeline_started = false;
376 }
377
378 int SampleRate() const { return sample_rate; }
379 int Channels() const { return channel_count; }
380
381private:
382 template <typename T> static void Release(T*& value)
383 {
384 if (value) { value->Release(); value = nullptr; }
385 }
386
387 void Fail(const std::string& message)
388 {
389 std::lock_guard<std::mutex> lock(state_mutex);
390 error = message;
391 failed = true;
392 state_ready.notify_all();
393 }
394
395 void CaptureLoop()
396 {
397 IMMDeviceEnumerator* enumerator = nullptr;
398 IMMDevice* device = nullptr;
399 IAudioClient* client = nullptr;
400 IAudioCaptureClient* capture = nullptr;
401 WAVEFORMATEX* format = nullptr;
402 const HRESULT com_result = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
403 const bool uninitialize_com = SUCCEEDED(com_result);
404 HRESULT result = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL,
405 IID_IMMDeviceEnumerator, reinterpret_cast<void**>(&enumerator));
406 if (SUCCEEDED(result)) {
407 result = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device);
408 }
409 if (SUCCEEDED(result)) {
410 result = device->Activate(IID_IAudioClient, CLSCTX_ALL, nullptr, reinterpret_cast<void**>(&client));
411 }
412 if (SUCCEEDED(result)) result = client->GetMixFormat(&format);
413 if (SUCCEEDED(result)) {
414 result = client->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK,
415 0, 0, format, nullptr);
416 }
417 if (SUCCEEDED(result)) {
418 result = client->GetService(IID_IAudioCaptureClient, reinterpret_cast<void**>(&capture));
419 }
420 if (SUCCEEDED(result)) result = client->Start();
421 if (FAILED(result) || !format || !capture) {
422 Fail("Unable to initialize WASAPI system audio loopback capture (HRESULT " + std::to_string(result) + ").");
423 if (format) CoTaskMemFree(format);
424 Release(capture); Release(client); Release(device); Release(enumerator);
425 if (uninitialize_com) CoUninitialize();
426 return;
427 }
428
429 sample_rate = static_cast<int>(format->nSamplesPerSec);
430 channel_count = std::max(1, std::min(2, static_cast<int>(format->nChannels)));
431 Reset();
432 bool floating_point = format->wFormatTag == WAVE_FORMAT_IEEE_FLOAT;
433 if (format->wFormatTag == WAVE_FORMAT_EXTENSIBLE && format->cbSize >= 22) {
434 const auto* extensible = reinterpret_cast<const WAVEFORMATEXTENSIBLE*>(format);
435 floating_point = extensible->SubFormat.Data1 == WAVE_FORMAT_IEEE_FLOAT;
436 }
437 {
438 std::lock_guard<std::mutex> lock(state_mutex);
439 opened = true;
440 state_ready.notify_all();
441 }
442
443 while (!close_requested) {
444 UINT32 packet_frames = 0;
445 if (FAILED(capture->GetNextPacketSize(&packet_frames))) break;
446 if (packet_frames == 0) {
447 std::this_thread::sleep_for(std::chrono::milliseconds(2));
448 continue;
449 }
450 BYTE* data = nullptr;
451 UINT32 frames = 0;
452 DWORD flags = 0;
453 UINT64 timestamp_100ns = 0;
454 if (FAILED(capture->GetBuffer(&data, &frames, &flags, nullptr, &timestamp_100ns))) break;
455 {
456 std::vector<std::vector<float>> samples(channel_count, std::vector<float>(frames));
457 for (UINT32 frame_index = 0; frame_index < frames; ++frame_index) {
458 for (int channel = 0; channel < channel_count; ++channel) {
459 float sample = 0.0f;
460 if (!(flags & AUDCLNT_BUFFERFLAGS_SILENT) && data) {
461 const int offset = static_cast<int>(frame_index) * format->nChannels + channel;
462 if (floating_point && format->wBitsPerSample == 32) {
463 sample = reinterpret_cast<const float*>(data)[offset];
464 } else if (format->wBitsPerSample == 16) {
465 sample = reinterpret_cast<const int16_t*>(data)[offset] / 32768.0f;
466 } else if (format->wBitsPerSample == 32) {
467 sample = static_cast<float>(reinterpret_cast<const int32_t*>(data)[offset] / 2147483648.0);
468 }
469 }
470 samples[channel][frame_index] = sample;
471 }
472 }
473 // Preserve timestamp gaps (including silence/discontinuities). Never
474 // invent a new epoch from packet arrival time after a delayed read.
475 if (!(flags & AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR)) {
476 std::lock_guard<std::mutex> lock(queue_mutex);
477 audio_buffer.PushTimestamp(static_cast<int64_t>(timestamp_100ns), epoch_100ns,
478 AVRational{1, 10000000}, sample_rate, std::move(samples));
479 }
480 }
481 capture->ReleaseBuffer(frames);
482 ready.notify_all();
483 }
484
485 client->Stop();
486 CoTaskMemFree(format);
487 Release(capture); Release(client); Release(device); Release(enumerator);
488 if (uninitialize_com) CoUninitialize();
489 }
490
491 ScreenCaptureSettings settings;
492 std::atomic<bool> close_requested { false };
493 std::thread worker;
494 std::mutex queue_mutex;
495 std::condition_variable ready;
496 CaptureAudioBuffer audio_buffer;
497 int64_t epoch_100ns = 0;
498 int64_t last_output_frame = 0;
499 bool timeline_started = false;
500 int sample_rate = 48000;
501 int channel_count = 2;
502 std::mutex state_mutex;
503 std::condition_variable state_ready;
504 bool opened = false;
505 bool failed = false;
506 std::string error;
507};
508#else
510{
511public:
513 void Open() {}
514 void Close() {}
515 void AddFrameAudio(const std::shared_ptr<Frame>&, int64_t, const Fraction&) {}
516 void Reset() {}
517 int SampleRate() const { return 0; }
518 int Channels() const { return 0; }
519};
520#endif
521
522namespace
523{
524 std::string fraction_to_string(const Fraction& value)
525 {
526 std::stringstream stream;
527 stream << value.num << "/" << value.den;
528 return stream.str();
529 }
530
531 void set_option(AVDictionary** options, const std::string& key, const std::string& value)
532 {
533 av_dict_set(options, key.c_str(), value.c_str(), 0);
534 }
535
536 bool option_enabled(const std::map<std::string, std::string>& options, const std::string& key)
537 {
538 const auto option = options.find(key);
539 if (option == options.end()) {
540 return false;
541 }
542 return option->second == "1" || option->second == "true" || option->second == "yes";
543 }
544
545 int option_int(const std::map<std::string, std::string>& options, const std::string& key, int fallback)
546 {
547 const auto option = options.find(key);
548 if (option == options.end()) {
549 return fallback;
550 }
551 try {
552 return std::stoi(option->second);
553 } catch (...) {
554 return fallback;
555 }
556 }
557
558 int capture_interrupt_callback(void* opaque)
559 {
560 const auto* reader = static_cast<std::atomic<bool>*>(opaque);
561 return reader && reader->load() ? 1 : 0;
562 }
563
564 std::string avfoundation_video_name(const std::string& input_name)
565 {
566 const size_t separator = input_name.find(':');
567 return separator == std::string::npos ? input_name : input_name.substr(0, separator);
568 }
569
570 std::string avfoundation_audio_name(const std::string& input_name)
571 {
572 const size_t separator = input_name.find(':');
573 return separator == std::string::npos ? "none" : input_name.substr(separator + 1);
574 }
575
576 bool resolve_avfoundation_video_index(
577 AVInputFormat* input_format,
578 const std::string& video_name,
579 std::string& video_index)
580 {
581 const auto is_digit = [](unsigned char value) {
582 return std::isdigit(value) != 0;
583 };
584 if (video_name.empty()
585 || video_name == "default"
586 || video_name == "none"
587 || std::all_of(video_name.begin(), video_name.end(), is_digit)) {
588 return false;
589 }
590
591 AVDeviceInfoList* device_list = nullptr;
592 const int result = avdevice_list_input_sources(input_format, nullptr, nullptr, &device_list);
593 if (result < 0 || !device_list) {
594 avdevice_free_list_devices(&device_list);
595 return false;
596 }
597
598 bool found = false;
599 for (int index = 0; index < device_list->nb_devices; ++index) {
600 const AVDeviceInfo* device = device_list->devices[index];
601 if (!device || !device->device_name) {
602 continue;
603 }
604 const std::string name = device->device_name;
605 const std::string description = device->device_description
606 ? device->device_description
607 : device->device_name;
608 if (video_name == name || video_name == description) {
609 video_index = std::all_of(name.begin(), name.end(), is_digit)
610 ? name
611 : std::to_string(index);
612 found = true;
613 break;
614 }
615 }
616 avdevice_free_list_devices(&device_list);
617 return found;
618 }
619}
620
622 : settings(new_settings)
623 , backend_reader(nullptr)
624 , backend_module(nullptr)
625 , is_open(false)
626 , video_stream(-1)
627 , frames_read(0)
628 , dropped_packets(0)
629 , format_context(nullptr)
630 , codec_context(nullptr)
631 , source_frame(nullptr)
632 , rgba_frame(nullptr)
633 , packet(nullptr)
634 , sws_context(nullptr)
635 , close_requested(false)
636 , system_audio(nullptr)
637{
638 if (settings.backend == SCREEN_CAPTURE_AUTO) {
639 settings.backend = DefaultBackend();
640 }
641 ValidateSettings();
642 PopulateInfo();
643#if defined(__linux__) || defined(_WIN32)
644 if (settings.capture_audio) {
645 system_audio = std::make_unique<SystemAudioCapture>(settings);
646 }
647#endif
648 if (UsesWaylandPortal()) {
649 #if defined(HAVE_WAYLAND_CAPTURE_PLUGIN) && defined(__linux__)
650 std::string module_error;
651 backend_module = load_wayland_capture_backend(module_error);
652 if (!backend_module) {
653 throw InvalidOptions("Wayland screen capture backend is unavailable: "
654 + module_error);
655 }
656 auto factory = reinterpret_cast<WaylandBackendFactory>(
657 dlsym(backend_module, "OpenShotCreateWaylandScreenCaptureReader"));
658 if (!factory) {
659 const char* error = dlerror();
660 dlclose(backend_module);
661 backend_module = nullptr;
662 throw InvalidOptions("Wayland screen capture backend is invalid: "
663 + std::string(error ? error : "factory function is missing."));
664 }
665 try {
666 backend_reader = factory(settings, info);
667 } catch (...) {
668 dlclose(backend_module);
669 backend_module = nullptr;
670 throw;
671 }
672 if (!backend_reader) {
673 dlclose(backend_module);
674 backend_module = nullptr;
675 throw InvalidOptions("Wayland screen capture backend is unavailable.");
676 }
677 #else
678 throw InvalidOptions("Wayland screen capture backend is unavailable in this build.");
679 #endif
680 }
681}
682
684{
685 Close();
686#if defined(__linux__)
687 backend_reader.reset();
688 if (backend_module) {
689 dlclose(backend_module);
690 backend_module = nullptr;
691 }
692#endif
693}
694
696{
697 const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
698 return backend_reader ? backend_reader->IsOpen() : is_open;
699}
700
702{
703#if defined(__linux__)
704 if (backend == SCREEN_CAPTURE_X11 || backend == SCREEN_CAPTURE_AUTO) {
705 return true;
706 }
707#if defined(HAVE_WAYLAND_CAPTURE_PLUGIN)
708 if (backend == SCREEN_CAPTURE_WAYLAND) {
709 return true;
710 }
711#endif
712 return false;
713#elif defined(_WIN32)
714 return backend == SCREEN_CAPTURE_WINDOWS_GDI || backend == SCREEN_CAPTURE_AUTO;
715#elif defined(__APPLE__)
716 return backend == SCREEN_CAPTURE_MAC_AVFOUNDATION || backend == SCREEN_CAPTURE_AUTO;
717#else
718 (void) backend;
719 return false;
720#endif
721}
722
724{
725#if defined(__linux__)
726 if (backend == SCREEN_CAPTURE_AUTO) {
727 backend = DefaultBackend();
728 }
729 avdevice_register_all();
730 return (backend == SCREEN_CAPTURE_X11 || backend == SCREEN_CAPTURE_WAYLAND)
731 && av_find_input_format("pulse") != nullptr;
732#elif defined(_WIN32)
733 return backend == SCREEN_CAPTURE_AUTO || backend == SCREEN_CAPTURE_WINDOWS_GDI;
734#else
735 (void) backend;
736 return false;
737#endif
738}
739
741{
742#if defined(__linux__)
743 const char* session = std::getenv("XDG_SESSION_TYPE");
744 if (session && std::string(session) == "wayland" && IsBackendSupported(SCREEN_CAPTURE_WAYLAND)) {
746 }
747 if (!session || std::string(session) == "x11") {
748 return SCREEN_CAPTURE_X11;
749 }
750#elif defined(_WIN32)
752#elif defined(__APPLE__)
754#endif
755 return SCREEN_CAPTURE_AUTO;
756}
757
758void ScreenCaptureReader::ValidateSettings() const
759{
760 if (!IsBackendSupported(settings.backend)) {
761 throw InvalidOptions("Screen capture backend is not supported on this OS or session.");
762 }
763 if (!UsesFFmpegDevice() && !UsesWaylandPortal()) {
764 throw InvalidOptions("Screen capture backend is not implemented in this build.");
765 }
766 if (settings.width <= 0 || settings.height <= 0) {
767 throw InvalidOptions("Screen capture requires a positive width and height.");
768 }
769 if (settings.fps.num <= 0 || settings.fps.den <= 0) {
770 throw InvalidOptions("Screen capture requires a positive frame rate.");
771 }
772 if (settings.capture_audio && !IsSystemAudioSupported(settings.backend)) {
773 throw InvalidOptions("System audio capture is not supported by this screen capture backend.");
774 }
775 if (settings.audio_sample_rate < 8000) {
776 throw InvalidSampleRate("System audio capture requires a sample rate of at least 8000 Hz.");
777 }
778 if (settings.audio_channels < 1 || settings.audio_channels > 2) {
779 throw InvalidChannels("System audio capture requires one or two channels.");
780 }
781}
782
783bool ScreenCaptureReader::UsesFFmpegDevice() const
784{
785 return settings.backend == SCREEN_CAPTURE_X11
786 || settings.backend == SCREEN_CAPTURE_WINDOWS_GDI
787 || settings.backend == SCREEN_CAPTURE_MAC_AVFOUNDATION
788 || settings.options.count("input_format_name");
789}
790
791bool ScreenCaptureReader::UsesWaylandPortal() const
792{
793 return settings.backend == SCREEN_CAPTURE_WAYLAND;
794}
795
796std::string ScreenCaptureReader::InputFormatName() const
797{
798 const auto override_format = settings.options.find("input_format_name");
799 if (override_format != settings.options.end()) {
800 return override_format->second;
801 }
802 if (settings.backend == SCREEN_CAPTURE_X11) {
803 return "x11grab";
804 }
805 if (settings.backend == SCREEN_CAPTURE_WINDOWS_GDI) {
806 return "gdigrab";
807 }
808 if (settings.backend == SCREEN_CAPTURE_MAC_AVFOUNDATION) {
809 return "avfoundation";
810 }
811 return "";
812}
813
814std::string ScreenCaptureReader::InputName() const
815{
816 if (InputFormatName() == "v4l2") {
817 return settings.display.empty() ? "/dev/video0" : settings.display;
818 }
819 if (InputFormatName() == "dshow") {
820 return settings.display;
821 }
822 if (InputFormatName() == "gdigrab") {
823 return settings.display.empty() ? "desktop" : settings.display;
824 }
825 if (InputFormatName() == "avfoundation") {
826 return settings.display.empty() ? "Capture screen 0:none" : settings.display;
827 }
828
829 std::string display = settings.display;
830 if (display.empty()) {
831 const char* env_display = std::getenv("DISPLAY");
832 display = env_display ? env_display : ":0.0";
833 }
834 if (InputFormatName() == "x11grab" && settings.options.count("window_id")) {
835 return display;
836 }
837
838 std::stringstream input;
839 input << display << "+" << settings.x << "," << settings.y;
840 return input.str();
841}
842
843void ScreenCaptureReader::PopulateInfo()
844{
845 info.has_video = true;
846 info.has_audio = settings.capture_audio;
847 info.has_single_image = false;
848 info.duration = 60.0f * 60.0f;
849 info.file_size = 0;
850 info.width = settings.width;
851 info.height = settings.height;
852 info.pixel_format = AV_PIX_FMT_RGBA;
853 info.fps = settings.fps;
854 info.video_bit_rate = 0;
855 info.pixel_ratio = Fraction(1, 1);
856 info.display_ratio = Fraction(settings.width, settings.height);
857 info.display_ratio.Reduce();
858 info.vcodec = "rawvideo";
859 info.video_length = static_cast<int64_t>(info.duration * settings.fps.ToFloat());
860 info.video_stream_index = -1;
861 info.video_timebase = settings.fps.Reciprocal();
862 info.interlaced_frame = false;
863 info.top_field_first = false;
864 info.acodec = settings.capture_audio ? "pcm_f32le" : "";
865 info.audio_bit_rate = 0;
866 info.sample_rate = settings.capture_audio ? settings.audio_sample_rate : 0;
867 info.channels = settings.capture_audio ? settings.audio_channels : 0;
868 info.channel_layout = settings.audio_channels == 2 ? LAYOUT_STEREO : LAYOUT_MONO;
869 info.audio_stream_index = -1;
870 info.audio_timebase = Fraction(1, 1);
871}
872
874{
875 if (backend_reader) {
876 if (backend_reader->IsOpen()) return;
877 manual_system_audio = false;
878 if (system_audio) {
879 system_audio->Open();
880 info.sample_rate = system_audio->SampleRate();
881 info.channels = system_audio->Channels();
882 info.channel_layout = info.channels == 1 ? LAYOUT_MONO : LAYOUT_STEREO;
883 }
884 try {
885 backend_reader->Open();
886 } catch (...) {
887 if (system_audio) system_audio->Close();
888 throw;
889 }
890 return;
891 }
892 // Close() may run on the UI thread while a worker is opening the device.
893 // Serialize initialization with frame reads and cleanup to keep FFmpeg's
894 // context alive until avformat_open_input/OpenDecoder have finished.
895 const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
896 if (is_open) {
897 return;
898 }
899 manual_system_audio = false;
900 close_requested = false;
901 try {
902 if (system_audio) {
903 system_audio->Open();
904 info.sample_rate = system_audio->SampleRate();
905 info.channels = system_audio->Channels();
906 info.channel_layout = info.channels == 1 ? LAYOUT_MONO : LAYOUT_STEREO;
907 }
908 OpenDevice();
909 OpenDecoder();
910 if (close_requested) {
911 throw ReaderClosed("Capture initialization was cancelled.");
912 }
913 } catch (...) {
914 // Also release partially initialized device/decoder resources. The
915 // recursive lifecycle lock permits using the normal cleanup path here.
916 Close();
917 throw;
918 }
919 is_open = true;
920}
921
922void ScreenCaptureReader::OpenDevice()
923{
924 avdevice_register_all();
925
926 AVInputFormat* input_format = const_cast<AVInputFormat*>(av_find_input_format(InputFormatName().c_str()));
927 std::string input_name = InputName();
928 if (!input_format) {
929 throw InvalidOptions("FFmpeg input device is not available: " + InputFormatName(), input_name);
930 }
931
932 format_context = avformat_alloc_context();
933 if (!format_context) {
934 throw OutOfMemory("Unable to allocate capture format context.", input_name);
935 }
936 format_context->interrupt_callback.callback = capture_interrupt_callback;
937 format_context->interrupt_callback.opaque = &close_requested;
938 if (InputFormatName() == "dshow") {
939 // DirectShow's blocking packet wait does not check the interrupt callback.
940 // Poll through DecodeNextFrame instead so the owning thread can clean up COM.
941 format_context->flags |= AVFMT_FLAG_NONBLOCK;
942 }
943
944 AVDictionary* options = nullptr;
945 const bool use_device_defaults = settings.options.count("use_device_defaults") > 0;
946 const bool post_capture_crop = option_enabled(settings.options, "crop_after_capture");
947 if (!use_device_defaults && !post_capture_crop) {
948 set_option(&options, "framerate", fraction_to_string(settings.fps));
949 set_option(&options, "video_size", std::to_string(settings.width) + "x" + std::to_string(settings.height));
950 } else if (post_capture_crop) {
951 const int source_width = option_int(settings.options, "crop_source_width", settings.width);
952 const int source_height = option_int(settings.options, "crop_source_height", settings.height);
953 set_option(&options, "framerate", fraction_to_string(settings.fps));
954 set_option(&options, "video_size", std::to_string(source_width) + "x" + std::to_string(source_height));
955 }
956 if (InputFormatName() == "x11grab") {
957 set_option(&options, "draw_mouse", settings.include_cursor ? "1" : "0");
958 set_option(&options, "show_region", settings.show_region ? "1" : "0");
959 } else if (InputFormatName() == "gdigrab") {
960 set_option(&options, "draw_mouse", settings.include_cursor ? "1" : "0");
961 set_option(&options, "show_region", settings.show_region ? "1" : "0");
962 set_option(&options, "offset_x", std::to_string(settings.x));
963 set_option(&options, "offset_y", std::to_string(settings.y));
964 } else if (InputFormatName() == "avfoundation") {
965 set_option(&options, "capture_cursor", settings.include_cursor ? "1" : "0");
966 std::string video_index;
967 if (resolve_avfoundation_video_index(input_format, avfoundation_video_name(input_name), video_index)) {
968 set_option(&options, "video_device_index", video_index);
969 input_name = ":" + avfoundation_audio_name(input_name);
970 }
971 }
972 for (const auto& option : settings.options) {
973 if (option.first == "input_format_name"
974 || option.first == "use_device_defaults"
975 || option.first == "crop_after_capture"
976 || option.first == "crop_source_width"
977 || option.first == "crop_source_height") {
978 continue;
979 }
980 set_option(&options, option.first, option.second);
981 }
982
983 const int result = avformat_open_input(&format_context, input_name.c_str(), input_format, &options);
984 av_dict_free(&options);
985 if (result < 0) {
986 throw InvalidFile("Unable to open screen capture input: " + std::string(av_err2str(result)), input_name);
987 }
988}
989
990void ScreenCaptureReader::OpenDecoder()
991{
992 if (avformat_find_stream_info(format_context, nullptr) < 0) {
993 throw InvalidFile("Unable to read capture stream information.", InputName());
994 }
995
996 for (unsigned int index = 0; index < format_context->nb_streams; ++index) {
997 if (format_context->streams[index]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
998 video_stream = static_cast<int>(index);
999 break;
1000 }
1001 }
1002 if (video_stream < 0) {
1003 throw InvalidFile("No video stream found in capture input.", InputName());
1004 }
1005
1006 AVStream* stream = format_context->streams[video_stream];
1007 const AVCodec* codec = avcodec_find_decoder(stream->codecpar->codec_id);
1008 if (!codec) {
1009 throw InvalidCodec("No decoder available for capture stream.", InputName());
1010 }
1011
1012 codec_context = ffmpeg_get_codec_context(stream, codec);
1013 if (!codec_context || avcodec_open2(codec_context, codec, nullptr) < 0) {
1014 throw InvalidCodec("Unable to open capture stream decoder.", InputName());
1015 }
1016
1017 info.width = codec_context->width > 0 ? codec_context->width : settings.width;
1018 info.height = codec_context->height > 0 ? codec_context->height : settings.height;
1019 if (option_enabled(settings.options, "crop_after_capture")) {
1020 info.width = settings.width;
1021 info.height = settings.height;
1022 }
1023 info.video_stream_index = video_stream;
1024 info.pixel_format = codec_context->pix_fmt;
1025 info.display_ratio = Fraction(info.width, info.height);
1026 info.display_ratio.Reduce();
1027 if (codec_context->framerate.num > 0 && codec_context->framerate.den > 0) {
1028 info.fps = Fraction(codec_context->framerate.num, codec_context->framerate.den);
1029 info.video_timebase = info.fps.Reciprocal();
1030 } else if (stream->avg_frame_rate.num > 0 && stream->avg_frame_rate.den > 0) {
1031 info.fps = Fraction(stream->avg_frame_rate.num, stream->avg_frame_rate.den);
1032 info.video_timebase = info.fps.Reciprocal();
1033 } else if (stream->r_frame_rate.num > 0 && stream->r_frame_rate.den > 0) {
1034 info.fps = Fraction(stream->r_frame_rate.num, stream->r_frame_rate.den);
1035 info.video_timebase = info.fps.Reciprocal();
1036 }
1037
1038 source_frame = av_frame_alloc();
1039 rgba_frame = av_frame_alloc();
1040 packet = av_packet_alloc();
1041 if (!source_frame || !rgba_frame || !packet) {
1042 throw OutOfMemory("Unable to allocate capture decoder frames.", InputName());
1043 }
1044}
1045
1046std::shared_ptr<Frame> ScreenCaptureReader::GetFrame(int64_t number)
1047{
1048 const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
1049 if (backend_reader) {
1050 if (!backend_reader->IsOpen()) {
1051 throw ReaderClosed("The ScreenCaptureReader is closed. Call Open() before GetFrame().");
1052 }
1053 auto frame = backend_reader->GetFrame(number);
1054 if (system_audio && !manual_system_audio) system_audio->AddFrameAudio(frame, number, info.fps);
1055 return frame;
1056 }
1057 if (!is_open) {
1058 throw ReaderClosed("The ScreenCaptureReader is closed. Call Open() before GetFrame().");
1059 }
1060
1061 auto frame = DecodeNextFrame(number);
1062 if (system_audio && !manual_system_audio) system_audio->AddFrameAudio(frame, number, info.fps);
1063 return frame;
1064}
1065
1066void ScreenCaptureReader::AddSystemAudio(std::shared_ptr<Frame> frame, int64_t output_frame_number)
1067{
1068 if (system_audio) {
1069 system_audio->AddFrameAudio(frame, output_frame_number, info.fps);
1070 }
1071}
1072
1074{
1075 manual_system_audio = true;
1076 if (system_audio) {
1077 system_audio->Reset();
1078 }
1079}
1080
1081std::shared_ptr<Frame> ScreenCaptureReader::DecodeNextFrame(int64_t number)
1082{
1083 while (!close_requested) {
1084 const int read_result = av_read_frame(format_context, packet);
1085 if (read_result == AVERROR(EAGAIN)) {
1086 std::this_thread::sleep_for(std::chrono::milliseconds(5));
1087 continue;
1088 }
1089 if (read_result < 0) {
1090 const std::string message = frames_read > 0
1091 ? "Capture input ended after " + std::to_string(frames_read) + " frame(s): "
1092 : "Capture input ended before a frame could be read: ";
1093 throw InvalidFile(message + std::string(av_err2str(read_result)), InputName());
1094 }
1095
1096 if (packet->stream_index != video_stream) {
1097 av_packet_unref(packet);
1098 dropped_packets++;
1099 continue;
1100 }
1101
1102 const int64_t packet_timestamp = packet->pts != AV_NOPTS_VALUE ? packet->pts : packet->dts;
1103 const int send_result = avcodec_send_packet(codec_context, packet);
1104 av_packet_unref(packet);
1105 if (send_result < 0) {
1106 continue;
1107 }
1108
1109 const int receive_result = avcodec_receive_frame(codec_context, source_frame);
1110 if (receive_result == AVERROR(EAGAIN)) {
1111 continue;
1112 }
1113 if (receive_result < 0) {
1114 throw InvalidFile("Unable to decode capture frame: " + std::string(av_err2str(receive_result)), InputName());
1115 }
1116
1117 const AVStream* stream = format_context->streams[video_stream];
1118 int64_t frame_timestamp = source_frame->best_effort_timestamp;
1119 if (frame_timestamp == AV_NOPTS_VALUE) {
1120 frame_timestamp = source_frame->pts;
1121 }
1122 if (frame_timestamp == AV_NOPTS_VALUE) {
1123 frame_timestamp = packet_timestamp;
1124 }
1125 double capture_timestamp = std::numeric_limits<double>::quiet_NaN();
1126 if (frame_timestamp != AV_NOPTS_VALUE && stream) {
1127 capture_timestamp = static_cast<double>(frame_timestamp) * av_q2d(stream->time_base);
1128 }
1129
1130 const int width = source_frame->width > 0 ? source_frame->width : info.width;
1131 const int height = source_frame->height > 0 ? source_frame->height : info.height;
1132 bool src_full_range = source_frame->color_range == AVCOL_RANGE_JPEG;
1133 const PixelFormat src_fmt = NormalizeDeprecatedPixFmt(
1134 static_cast<PixelFormat>(source_frame->format), src_full_range);
1135
1136 sws_context = sws_getCachedContext(
1137 sws_context,
1138 width,
1139 height,
1140 src_fmt,
1141 width,
1142 height,
1143 AV_PIX_FMT_RGBA,
1144 SWS_BILINEAR,
1145 nullptr,
1146 nullptr,
1147 nullptr);
1148 if (!sws_context) {
1149 throw InvalidFile("Unable to create capture pixel conversion context.", InputName());
1150 }
1151
1152 const int* coefficients = sws_getCoefficients(SWS_CS_DEFAULT);
1153 sws_setColorspaceDetails(sws_context, coefficients, src_full_range ? 1 : 0,
1154 coefficients, 1, 0, 1 << 16, 1 << 16);
1155
1156 const int bytes_per_pixel = 4;
1157 const size_t buffer_size = static_cast<size_t>(width) * height * bytes_per_pixel;
1158 unsigned char* buffer = static_cast<unsigned char*>(aligned_malloc(buffer_size));
1159 if (!buffer) {
1160 throw OutOfMemory("Unable to allocate capture frame buffer.", InputName());
1161 }
1162
1163 av_image_fill_arrays(rgba_frame->data, rgba_frame->linesize, buffer, AV_PIX_FMT_RGBA, width, height, 1);
1164 const int scaled_lines = sws_scale(sws_context, source_frame->data, source_frame->linesize, 0, height, rgba_frame->data, rgba_frame->linesize);
1165 av_frame_unref(source_frame);
1166
1167 if (scaled_lines <= 0) {
1168 openshot::aligned_free(buffer);
1169 continue;
1170 }
1171
1172 int output_width = width;
1173 int output_height = height;
1174 unsigned char* output_buffer = buffer;
1175 if (option_enabled(settings.options, "crop_after_capture")) {
1176 const int crop_x = std::max(0, std::min(settings.x, width - 1));
1177 const int crop_y = std::max(0, std::min(settings.y, height - 1));
1178 output_width = std::max(1, std::min(settings.width, width - crop_x));
1179 output_height = std::max(1, std::min(settings.height, height - crop_y));
1180 const size_t output_buffer_size = static_cast<size_t>(output_width) * output_height * bytes_per_pixel;
1181 output_buffer = static_cast<unsigned char*>(aligned_malloc(output_buffer_size));
1182 if (!output_buffer) {
1183 openshot::aligned_free(buffer);
1184 throw OutOfMemory("Unable to allocate cropped capture frame buffer.", InputName());
1185 }
1186 for (int row = 0; row < output_height; ++row) {
1187 const unsigned char* source_row = buffer
1188 + (static_cast<size_t>(crop_y + row) * width + crop_x) * bytes_per_pixel;
1189 unsigned char* dest_row = output_buffer + static_cast<size_t>(row) * output_width * bytes_per_pixel;
1190 std::copy(source_row, source_row + static_cast<size_t>(output_width) * bytes_per_pixel, dest_row);
1191 }
1192 openshot::aligned_free(buffer);
1193 }
1194
1195 auto frame = std::make_shared<Frame>(number, output_width, output_height, "#000000");
1196 frame->capture_timestamp = capture_timestamp;
1197 frame->AddImage(output_width, output_height, bytes_per_pixel, QImage::Format_RGBA8888, output_buffer);
1198 frames_read++;
1199 return frame;
1200 }
1201
1202 throw ReaderClosed("The ScreenCaptureReader was closed.");
1203}
1204
1206{
1207 close_requested = true;
1208}
1209
1211{
1212 // Signal blocking native reads before waiting for GetFrame(). The FFmpeg
1213 // interrupt callback observes close_requested, while backend readers use
1214 // Close() to wake their own blocking waits.
1215 close_requested = true;
1216 if (backend_reader) {
1217 backend_reader->Close();
1218 }
1219
1220 // Open() and GetFrame() own FFmpeg and system-audio use under this mutex.
1221 // Wait for initialization or an interrupted read before releasing resources.
1222 const std::lock_guard<std::recursive_mutex> lock(getFrameMutex);
1223 if (system_audio) {
1224 system_audio->Close();
1225 }
1226 if (packet) {
1227 av_packet_free(&packet);
1228 }
1229 if (source_frame) {
1230 av_frame_free(&source_frame);
1231 }
1232 if (rgba_frame) {
1233 av_frame_free(&rgba_frame);
1234 }
1235 if (sws_context) {
1236 sws_freeContext(sws_context);
1237 sws_context = nullptr;
1238 }
1239 if (codec_context) {
1240 avcodec_free_context(&codec_context);
1241 }
1242 if (format_context) {
1243 avformat_close_input(&format_context);
1244 }
1245 is_open = false;
1246 video_stream = -1;
1247}
1248
1250{
1251 if (backend_reader) {
1252 return backend_reader->GetStats();
1253 }
1254 CaptureReaderStats stats;
1255 stats.is_open = is_open;
1256 stats.frames_read = frames_read;
1257 stats.dropped_packets = dropped_packets;
1258 const double fps = settings.fps.den != 0 ? static_cast<double>(settings.fps.num) / static_cast<double>(settings.fps.den) : 0.0;
1259 stats.duration = fps > 0.0 ? static_cast<double>(frames_read) / fps : 0.0;
1260 return stats;
1261}
1262
1263std::string ScreenCaptureReader::Json() const
1264{
1265 return JsonValue().toStyledString();
1266}
1267
1269{
1270 Json::Value root = ReaderBase::JsonValue();
1271 root["type"] = "ScreenCaptureReader";
1272 root["backend"] = settings.backend;
1273 root["display"] = settings.display;
1274 root["x"] = settings.x;
1275 root["y"] = settings.y;
1276 root["width"] = settings.width;
1277 root["height"] = settings.height;
1278 root["fps"]["num"] = settings.fps.num;
1279 root["fps"]["den"] = settings.fps.den;
1280 root["include_cursor"] = settings.include_cursor;
1281 root["show_region"] = settings.show_region;
1282 root["capture_audio"] = settings.capture_audio;
1283 root["audio_device"] = settings.audio_device;
1284 root["audio_sample_rate"] = settings.audio_sample_rate;
1285 root["audio_channels"] = settings.audio_channels;
1286 root["options"] = Json::Value(Json::objectValue);
1287 for (const auto& option : settings.options) {
1288 root["options"][option.first] = option.second;
1289 }
1290 return root;
1291}
1292
1293void ScreenCaptureReader::SetJson(const std::string value)
1294{
1295 try {
1297 } catch (const std::exception&) {
1298 throw InvalidJSON("JSON is invalid (missing keys or invalid data types)");
1299 }
1300}
1301
1302void ScreenCaptureReader::SetJsonValue(const Json::Value root)
1303{
1304 if (!root["backend"].isNull())
1305 settings.backend = static_cast<ScreenCaptureBackend>(root["backend"].asInt());
1306 if (!root["display"].isNull())
1307 settings.display = root["display"].asString();
1308 if (!root["x"].isNull())
1309 settings.x = root["x"].asInt();
1310 if (!root["y"].isNull())
1311 settings.y = root["y"].asInt();
1312 if (!root["width"].isNull())
1313 settings.width = root["width"].asInt();
1314 if (!root["height"].isNull())
1315 settings.height = root["height"].asInt();
1316 if (!root["fps"].isNull() && root["fps"].isObject()) {
1317 if (!root["fps"]["num"].isNull())
1318 settings.fps.num = root["fps"]["num"].asInt();
1319 if (!root["fps"]["den"].isNull())
1320 settings.fps.den = root["fps"]["den"].asInt();
1321 }
1322 if (!root["include_cursor"].isNull())
1323 settings.include_cursor = root["include_cursor"].asBool();
1324 if (!root["show_region"].isNull())
1325 settings.show_region = root["show_region"].asBool();
1326 if (!root["capture_audio"].isNull())
1327 settings.capture_audio = root["capture_audio"].asBool();
1328 if (!root["audio_device"].isNull())
1329 settings.audio_device = root["audio_device"].asString();
1330 if (!root["audio_sample_rate"].isNull())
1331 settings.audio_sample_rate = root["audio_sample_rate"].asInt();
1332 if (!root["audio_channels"].isNull())
1333 settings.audio_channels = root["audio_channels"].asInt();
1334 if (!root["options"].isNull() && root["options"].isObject()) {
1335 settings.options.clear();
1336 for (const auto& key : root["options"].getMemberNames()) {
1337 settings.options[key] = root["options"][key].asString();
1338 }
1339 }
1340 if (settings.backend == SCREEN_CAPTURE_AUTO) {
1341 settings.backend = DefaultBackend();
1342 }
1343 ValidateSettings();
1344 PopulateInfo();
1345#if defined(__linux__) || defined(_WIN32)
1346 system_audio.reset();
1347 if (settings.capture_audio) {
1348 system_audio = std::make_unique<SystemAudioCapture>(settings);
1349 }
1350#endif
1351}
Header file for all Exception classes.
AVPixelFormat NormalizeDeprecatedPixFmt(AVPixelFormat pix_fmt, bool &is_full_range)
#define PixelFormat
#define HAVE_CH_LAYOUT
#define av_err2str(errnum)
for(auto iter=info.metadata.begin();iter !=info.metadata.end();++iter)
Header file for Frame class.
Header file for QtUtilities (compatibiity overlay).
Header file for live screen capture readers.
void AddFrameAudio(const std::shared_ptr< Frame > &, int64_t, const Fraction &)
This class represents a fraction.
Definition Fraction.h:30
int num
Numerator for the fraction.
Definition Fraction.h:32
int den
Denominator for the fraction.
Definition Fraction.h:33
int GetSamplesPerFrame(openshot::Fraction fps, int sample_rate, int channels)
Calculate the # of samples per video frame (for the current frame number).
Definition Frame.cpp:486
Exception for files that can not be found or opened.
Definition Exceptions.h:194
Exception for invalid JSON.
Definition Exceptions.h:224
Exception when invalid encoding options are used.
Definition Exceptions.h:239
Exception when memory could not be allocated.
Definition Exceptions.h:355
openshot::ReaderInfo info
Information about the current media file.
Definition ReaderBase.h:91
virtual Json::Value JsonValue() const =0
Generate Json::Value for this object.
std::recursive_mutex getFrameMutex
Mutex for multiple threads.
Definition ReaderBase.h:79
Exception when a reader is closed, and a frame is requested.
Definition Exceptions.h:370
void SetJson(const std::string value) override
Load JSON string into this object.
bool IsOpen() override
Determine if reader is open or closed.
void RequestClose()
Signal FFmpeg capture reads to stop; the opening thread must call Close().
openshot::CaptureReaderStats GetStats() const
void Close() override
Close the reader (and any resources it was consuming).
static ScreenCaptureBackend DefaultBackend()
static bool IsBackendSupported(ScreenCaptureBackend backend)
ScreenCaptureReader(const ScreenCaptureSettings &settings)
void SetJsonValue(const Json::Value root) override
Load Json::Value into this object.
void AddSystemAudio(std::shared_ptr< openshot::Frame > frame, int64_t output_frame_number)
Json::Value JsonValue() const override
Generate Json::Value for this object.
std::shared_ptr< openshot::Frame > GetFrame(int64_t number) override
std::string Json() const override
Generate JSON string of this object.
void Open() override
Open the reader (and start consuming resources, such as images or video files).
static bool IsSystemAudioSupported(ScreenCaptureBackend backend)
This namespace is the default namespace for all code in the openshot library.
void aligned_free(void *ptr)
Definition QtUtilities.h:32
@ SCREEN_CAPTURE_MAC_AVFOUNDATION
const Json::Value stringToJson(const std::string value)
Definition Json.cpp:16
This struct contains info about a media file, such as height, width, frames per second,...
Definition ReaderBase.h:39