20#include <condition_variable>
34 #include <libavdevice/avdevice.h>
35 #include <libavutil/imgutils.h>
36 #include <libavutil/time.h>
43 #include <audioclient.h>
44 #include <mmdeviceapi.h>
53#if defined(HAVE_WAYLAND_CAPTURE_PLUGIN) && defined(__linux__)
56 using WaylandBackendFactory = std::unique_ptr<ScreenCaptureReader::CaptureBackendReader> (*) (
59 void* load_wayland_capture_backend(std::string& error_message)
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)) {
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)) {
77 const char* error = dlerror();
78 error_message = error ? error :
"unable to load PipeWire support.";
82 void* module = dlopen(
"libopenshot-wayland-capture.so", RTLD_NOW | RTLD_LOCAL);
84 const char* error = dlerror();
85 error_message = error ? error :
"unable to load PipeWire support.";
97 : settings(new_settings) {}
103 if (format_context)
return;
104 avdevice_register_all();
105 AVInputFormat* input_format =
const_cast<AVInputFormat*
>(av_find_input_format(
"pulse"));
107 throw InvalidOptions(
"FFmpeg PulseAudio input is unavailable for system audio capture.");
110 format_context = avformat_alloc_context();
111 if (!format_context) {
112 throw OutOfMemory(
"Unable to allocate system audio capture context.");
114 format_context->interrupt_callback.callback = InterruptCallback;
115 format_context->interrupt_callback.opaque = &close_requested;
117 AVDictionary* options =
nullptr;
118 av_dict_set(&options,
"wallclock",
"1", 0);
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);
132 if (avformat_find_stream_info(format_context,
nullptr) < 0) {
133 throw InvalidFile(
"Unable to read system audio capture stream information.", device);
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);
141 if (audio_stream < 0) {
142 throw InvalidFile(
"No audio stream found in system audio capture input.", device);
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);
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.");
156 settings.audio_sample_rate = codec_context->sample_rate > 0
157 ? codec_context->sample_rate : settings.audio_sample_rate;
159 close_requested =
false;
160 worker = std::thread(&SystemAudioCapture::CaptureLoop,
this);
165 close_requested =
true;
167 if (worker.joinable()) {
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);
176 void AddFrameAudio(
const std::shared_ptr<Frame>& frame, int64_t number,
const Fraction& fps)
178 int sample_count = 0;
179 for (int64_t frame_number = last_output_frame + 1; frame_number <= number; ++frame_number) {
181 frame_number, fps, settings.audio_sample_rate, settings.audio_channels);
183 last_output_frame = std::max(last_output_frame, number);
184 if (!frame || sample_count <= 0)
return;
186 std::unique_lock<std::mutex> lock(queue_mutex);
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);
195 timeline_started =
true;
196 auto samples = audio_buffer.Read(sample_count);
197 frame->SampleRate(settings.audio_sample_rate);
199 for (
int channel = 0; channel < settings.audio_channels; ++channel) {
200 frame->AddAudio(
true, channel, 0, samples[channel].data(), sample_count, 1.0f);
206 std::lock_guard<std::mutex> lock(queue_mutex);
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;
215 int SampleRate()
const {
return settings.audio_sample_rate; }
216 int Channels()
const {
return settings.audio_channels; }
219 static int InterruptCallback(
void* opaque)
221 const auto* requested =
static_cast<std::atomic<bool>*
>(opaque);
222 return requested && requested->load() ? 1 : 0;
225 float SampleAt(
const AVFrame* frame,
int channel,
int sample)
const
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
233 codec_context->channels
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;
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]);
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);
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) {
273 av_frame_unref(decoded_frame);
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);
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);
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 };
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;
314 : settings(new_settings) {}
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; });
326 close_requested =
true;
328 if (worker.joinable()) worker.join();
329 throw InvalidOptions(error.empty() ?
"Unable to open WASAPI system audio loopback capture." : error);
335 close_requested =
true;
337 if (worker.joinable()) worker.join();
341 void AddFrameAudio(
const std::shared_ptr<Frame>& frame, int64_t number,
const Fraction& fps)
343 int sample_count = 0;
344 for (int64_t frame_number = last_output_frame + 1; frame_number <= number; ++frame_number) {
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);
356 timeline_started =
true;
357 auto samples = audio_buffer.Read(sample_count);
358 frame->SampleRate(sample_rate);
360 for (
int channel = 0; channel < channel_count; ++channel) {
361 frame->AddAudio(
true, channel, 0, samples[channel].data(), sample_count, 1.0f);
367 std::lock_guard<std::mutex> lock(queue_mutex);
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;
378 int SampleRate()
const {
return sample_rate; }
379 int Channels()
const {
return channel_count; }
382 template <
typename T>
static void Release(T*& value)
384 if (value) { value->Release(); value =
nullptr; }
387 void Fail(
const std::string& message)
389 std::lock_guard<std::mutex> lock(state_mutex);
392 state_ready.notify_all();
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);
409 if (SUCCEEDED(result)) {
410 result = device->Activate(IID_IAudioClient, CLSCTX_ALL,
nullptr,
reinterpret_cast<void**
>(&client));
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);
417 if (SUCCEEDED(result)) {
418 result = client->GetService(IID_IAudioCaptureClient,
reinterpret_cast<void**
>(&capture));
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();
429 sample_rate =
static_cast<int>(format->nSamplesPerSec);
430 channel_count = std::max(1, std::min(2,
static_cast<int>(format->nChannels)));
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;
438 std::lock_guard<std::mutex> lock(state_mutex);
440 state_ready.notify_all();
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));
450 BYTE* data =
nullptr;
453 UINT64 timestamp_100ns = 0;
454 if (FAILED(capture->GetBuffer(&data, &frames, &flags,
nullptr, ×tamp_100ns)))
break;
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) {
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);
470 samples[channel][frame_index] = sample;
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));
481 capture->ReleaseBuffer(frames);
486 CoTaskMemFree(format);
487 Release(capture); Release(client); Release(device); Release(enumerator);
488 if (uninitialize_com) CoUninitialize();
491 ScreenCaptureSettings settings;
492 std::atomic<bool> close_requested {
false };
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;
524 std::string fraction_to_string(
const Fraction& value)
526 std::stringstream stream;
527 stream << value.
num <<
"/" << value.
den;
531 void set_option(AVDictionary** options,
const std::string& key,
const std::string& value)
533 av_dict_set(options, key.c_str(), value.c_str(), 0);
536 bool option_enabled(
const std::map<std::string, std::string>& options,
const std::string& key)
538 const auto option = options.find(key);
539 if (option == options.end()) {
542 return option->second ==
"1" || option->second ==
"true" || option->second ==
"yes";
545 int option_int(
const std::map<std::string, std::string>& options,
const std::string& key,
int fallback)
547 const auto option = options.find(key);
548 if (option == options.end()) {
552 return std::stoi(option->second);
558 int capture_interrupt_callback(
void* opaque)
560 const auto* reader =
static_cast<std::atomic<bool>*
>(opaque);
561 return reader && reader->load() ? 1 : 0;
564 std::string avfoundation_video_name(
const std::string& input_name)
566 const size_t separator = input_name.find(
':');
567 return separator == std::string::npos ? input_name : input_name.substr(0, separator);
570 std::string avfoundation_audio_name(
const std::string& input_name)
572 const size_t separator = input_name.find(
':');
573 return separator == std::string::npos ?
"none" : input_name.substr(separator + 1);
576 bool resolve_avfoundation_video_index(
577 AVInputFormat* input_format,
578 const std::string& video_name,
579 std::string& video_index)
581 const auto is_digit = [](
unsigned char value) {
582 return std::isdigit(value) != 0;
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)) {
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);
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) {
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)
611 : std::to_string(index);
616 avdevice_free_list_devices(&device_list);
622 : settings(new_settings)
623 , backend_reader(nullptr)
624 , backend_module(nullptr)
629 , format_context(nullptr)
630 , codec_context(nullptr)
631 , source_frame(nullptr)
632 , rgba_frame(nullptr)
634 , sws_context(nullptr)
635 , close_requested(false)
636 , system_audio(nullptr)
639 settings.backend = DefaultBackend();
643#if defined(__linux__) || defined(_WIN32)
644 if (settings.capture_audio) {
645 system_audio = std::make_unique<SystemAudioCapture>(settings);
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: "
656 auto factory =
reinterpret_cast<WaylandBackendFactory
>(
657 dlsym(backend_module,
"OpenShotCreateWaylandScreenCaptureReader"));
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."));
666 backend_reader = factory(settings,
info);
668 dlclose(backend_module);
669 backend_module =
nullptr;
672 if (!backend_reader) {
673 dlclose(backend_module);
674 backend_module =
nullptr;
675 throw InvalidOptions(
"Wayland screen capture backend is unavailable.");
678 throw InvalidOptions(
"Wayland screen capture backend is unavailable in this build.");
686#if defined(__linux__)
687 backend_reader.reset();
688 if (backend_module) {
689 dlclose(backend_module);
690 backend_module =
nullptr;
697 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
698 return backend_reader ? backend_reader->IsOpen() : is_open;
703#if defined(__linux__)
707#if defined(HAVE_WAYLAND_CAPTURE_PLUGIN)
715#elif defined(__APPLE__)
725#if defined(__linux__)
729 avdevice_register_all();
731 && av_find_input_format(
"pulse") !=
nullptr;
742#if defined(__linux__)
743 const char* session = std::getenv(
"XDG_SESSION_TYPE");
747 if (!session || std::string(session) ==
"x11") {
752#elif defined(__APPLE__)
758void ScreenCaptureReader::ValidateSettings()
const
761 throw InvalidOptions(
"Screen capture backend is not supported on this OS or session.");
763 if (!UsesFFmpegDevice() && !UsesWaylandPortal()) {
764 throw InvalidOptions(
"Screen capture backend is not implemented in this build.");
766 if (settings.width <= 0 || settings.height <= 0) {
767 throw InvalidOptions(
"Screen capture requires a positive width and height.");
769 if (settings.fps.num <= 0 || settings.fps.den <= 0) {
770 throw InvalidOptions(
"Screen capture requires a positive frame rate.");
773 throw InvalidOptions(
"System audio capture is not supported by this screen capture backend.");
775 if (settings.audio_sample_rate < 8000) {
776 throw InvalidSampleRate(
"System audio capture requires a sample rate of at least 8000 Hz.");
778 if (settings.audio_channels < 1 || settings.audio_channels > 2) {
779 throw InvalidChannels(
"System audio capture requires one or two channels.");
783bool ScreenCaptureReader::UsesFFmpegDevice()
const
788 || settings.options.count(
"input_format_name");
791bool ScreenCaptureReader::UsesWaylandPortal()
const
796std::string ScreenCaptureReader::InputFormatName()
const
798 const auto override_format = settings.options.find(
"input_format_name");
799 if (override_format != settings.options.end()) {
800 return override_format->second;
809 return "avfoundation";
814std::string ScreenCaptureReader::InputName()
const
816 if (InputFormatName() ==
"v4l2") {
817 return settings.display.empty() ?
"/dev/video0" : settings.display;
819 if (InputFormatName() ==
"dshow") {
820 return settings.display;
822 if (InputFormatName() ==
"gdigrab") {
823 return settings.display.empty() ?
"desktop" : settings.display;
825 if (InputFormatName() ==
"avfoundation") {
826 return settings.display.empty() ?
"Capture screen 0:none" : settings.display;
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";
834 if (InputFormatName() ==
"x11grab" && settings.options.count(
"window_id")) {
838 std::stringstream input;
839 input << display <<
"+" << settings.x <<
"," << settings.y;
843void ScreenCaptureReader::PopulateInfo()
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;
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;
869 info.audio_stream_index = -1;
870 info.audio_timebase = Fraction(1, 1);
875 if (backend_reader) {
876 if (backend_reader->IsOpen())
return;
877 manual_system_audio =
false;
879 system_audio->Open();
880 info.sample_rate = system_audio->SampleRate();
881 info.channels = system_audio->Channels();
885 backend_reader->Open();
887 if (system_audio) system_audio->Close();
895 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
899 manual_system_audio =
false;
900 close_requested =
false;
903 system_audio->Open();
904 info.sample_rate = system_audio->SampleRate();
905 info.channels = system_audio->Channels();
910 if (close_requested) {
911 throw ReaderClosed(
"Capture initialization was cancelled.");
922void ScreenCaptureReader::OpenDevice()
924 avdevice_register_all();
926 AVInputFormat* input_format =
const_cast<AVInputFormat*
>(av_find_input_format(InputFormatName().c_str()));
927 std::string input_name = InputName();
929 throw InvalidOptions(
"FFmpeg input device is not available: " + InputFormatName(), input_name);
932 format_context = avformat_alloc_context();
933 if (!format_context) {
934 throw OutOfMemory(
"Unable to allocate capture format context.", input_name);
936 format_context->interrupt_callback.callback = capture_interrupt_callback;
937 format_context->interrupt_callback.opaque = &close_requested;
938 if (InputFormatName() ==
"dshow") {
941 format_context->flags |= AVFMT_FLAG_NONBLOCK;
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));
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);
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") {
980 set_option(&options, option.first, option.second);
983 const int result = avformat_open_input(&format_context, input_name.c_str(), input_format, &options);
984 av_dict_free(&options);
986 throw InvalidFile(
"Unable to open screen capture input: " + std::string(
av_err2str(result)), input_name);
990void ScreenCaptureReader::OpenDecoder()
992 if (avformat_find_stream_info(format_context,
nullptr) < 0) {
993 throw InvalidFile(
"Unable to read capture stream information.", InputName());
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);
1002 if (video_stream < 0) {
1003 throw InvalidFile(
"No video stream found in capture input.", InputName());
1006 AVStream* stream = format_context->streams[video_stream];
1007 const AVCodec*
codec = avcodec_find_decoder(stream->codecpar->codec_id);
1009 throw InvalidCodec(
"No decoder available for capture stream.", InputName());
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());
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;
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();
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());
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().");
1053 auto frame = backend_reader->GetFrame(number);
1054 if (system_audio && !manual_system_audio) system_audio->AddFrameAudio(frame, number,
info.fps);
1058 throw ReaderClosed(
"The ScreenCaptureReader is closed. Call Open() before GetFrame().");
1061 auto frame = DecodeNextFrame(number);
1062 if (system_audio && !manual_system_audio) system_audio->AddFrameAudio(frame, number,
info.fps);
1069 system_audio->AddFrameAudio(frame, output_frame_number,
info.fps);
1075 manual_system_audio =
true;
1077 system_audio->Reset();
1081std::shared_ptr<Frame> ScreenCaptureReader::DecodeNextFrame(int64_t number)
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));
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: ";
1096 if (packet->stream_index != video_stream) {
1097 av_packet_unref(packet);
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) {
1109 const int receive_result = avcodec_receive_frame(codec_context, source_frame);
1110 if (receive_result == AVERROR(EAGAIN)) {
1113 if (receive_result < 0) {
1114 throw InvalidFile(
"Unable to decode capture frame: " + std::string(
av_err2str(receive_result)), InputName());
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;
1122 if (frame_timestamp == AV_NOPTS_VALUE) {
1123 frame_timestamp = packet_timestamp;
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);
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;
1134 static_cast<PixelFormat>(source_frame->format), src_full_range);
1136 sws_context = sws_getCachedContext(
1149 throw InvalidFile(
"Unable to create capture pixel conversion context.", InputName());
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);
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));
1160 throw OutOfMemory(
"Unable to allocate capture frame buffer.", InputName());
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);
1167 if (scaled_lines <= 0) {
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) {
1184 throw OutOfMemory(
"Unable to allocate cropped capture frame buffer.", InputName());
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);
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);
1202 throw ReaderClosed(
"The ScreenCaptureReader was closed.");
1207 close_requested =
true;
1215 close_requested =
true;
1216 if (backend_reader) {
1217 backend_reader->Close();
1222 const std::lock_guard<std::recursive_mutex> lock(
getFrameMutex);
1224 system_audio->Close();
1227 av_packet_free(&packet);
1230 av_frame_free(&source_frame);
1233 av_frame_free(&rgba_frame);
1236 sws_freeContext(sws_context);
1237 sws_context =
nullptr;
1239 if (codec_context) {
1240 avcodec_free_context(&codec_context);
1242 if (format_context) {
1243 avformat_close_input(&format_context);
1251 if (backend_reader) {
1252 return backend_reader->GetStats();
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;
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;
1297 }
catch (
const std::exception&) {
1298 throw InvalidJSON(
"JSON is invalid (missing keys or invalid data types)");
1304 if (!root[
"backend"].isNull())
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();
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();
1345#if defined(__linux__) || defined(_WIN32)
1346 system_audio.reset();
1347 if (settings.capture_audio) {
1348 system_audio = std::make_unique<SystemAudioCapture>(settings);
Header file for all Exception classes.
AVPixelFormat NormalizeDeprecatedPixFmt(AVPixelFormat pix_fmt, bool &is_full_range)
#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 &)
SystemAudioCapture(const ScreenCaptureSettings &)
This class represents a fraction.
int num
Numerator for the fraction.
int den
Denominator for the fraction.
int GetSamplesPerFrame(openshot::Fraction fps, int sample_rate, int channels)
Calculate the # of samples per video frame (for the current frame number).
Exception for files that can not be found or opened.
Exception for invalid JSON.
Exception when invalid encoding options are used.
Exception when memory could not be allocated.
openshot::ReaderInfo info
Information about the current media file.
virtual Json::Value JsonValue() const =0
Generate Json::Value for this object.
std::recursive_mutex getFrameMutex
Mutex for multiple threads.
Exception when a reader is closed, and a frame is requested.
void SetJson(const std::string value) override
Load JSON string into this object.
bool IsOpen() override
Determine if reader is open or closed.
~ScreenCaptureReader() override
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)
@ SCREEN_CAPTURE_MAC_AVFOUNDATION
@ SCREEN_CAPTURE_WINDOWS_GDI
const Json::Value stringToJson(const std::string value)
This struct contains info about a media file, such as height, width, frames per second,...
ScreenCaptureBackend backend