11#include <libavcodec/avcodec.h>
12#include <libavdevice/avdevice.h>
13#include <libavformat/avformat.h>
14#include <libavutil/dict.h>
15#include <libavutil/frame.h>
16#include <libavutil/imgutils.h>
17#include <libswscale/swscale.h>
33 .get_service<Registry::Service::IOService>()) {
59#ifdef MAYAFLUX_PLATFORM_MACOS
60double macos_camera_max_fps(
const std::string& device_name);
65 constexpr std::string_view PREFERRED_INPUT_FORMAT =
66#ifdef MAYAFLUX_PLATFORM_MACOS
78 AVDictionary* build_options(
const CameraConfig& config,
79 const std::string& input_format,
const OpenHints& hints)
81 AVDictionary* opts =
nullptr;
83 if (hints.fps && config.target_fps > 0.0)
84 av_dict_set(&opts,
"framerate", std::to_string(config.target_fps).c_str(), 0);
85#ifdef MAYAFLUX_PLATFORM_MACOS
86 else if (
const double native = macos_camera_max_fps(config.device_name); native > 0.0)
87 av_dict_set(&opts,
"framerate", std::to_string(native).c_str(), 0);
90 if (hints.size && config.target_width > 0 && config.target_height > 0) {
91 const std::string size_str = std::to_string(config.target_width)
93 + std::to_string(config.target_height);
94 av_dict_set(&opts,
"video_size", size_str.c_str(), 0);
97 if (hints.format && !input_format.empty()) {
98#if defined(MAYAFLUX_PLATFORM_LINUX)
99 av_dict_set(&opts,
"input_format", input_format.c_str(), 0);
100#elif defined(MAYAFLUX_PLATFORM_WINDOWS)
101 const bool raw = av_get_pix_fmt(input_format.c_str()) != AV_PIX_FMT_NONE;
102 av_dict_set(&opts, raw ?
"pixel_format" :
"vcodec", input_format.c_str(), 0);
116 ? std::string(CAMERA_FORMAT)
119 const std::string input_format = config.
input_format.empty()
120 ? std::string(PREFERRED_INPUT_FORMAT)
123 constexpr std::array<OpenHints, 4> ladder { {
124 { .format =
true, .size =
true, .fps =
true },
125 { .format =
false, .size =
true, .fps =
true },
126 { .format =
false, .size =
true, .fps =
false },
127 { .format =
false, .size =
false, .fps =
false },
132 for (
size_t step = 0; step < ladder.size(); ++step) {
133 const OpenHints& hints = ladder.at(step);
134 if (hints.format && input_format.empty())
137 AVDictionary* opts = build_options(config, input_format, hints);
158 if (step > (input_format.empty() ? 1U : 0
U)) {
160 "FFmpegCameraReader::open: '{}' did not accept the requested mode, "
161 "opened with fallback step {}",
166 "FFmpegCameraReader: opened '{}' via {}: {}x{} @{:.1f}fps (scaler deferred)",
181 { .label =
"Device default" },
182 { .label =
"640 x 480 @ 30 fps", .width = 640, .height = 480, .fps = 30.0 },
183 { .label =
"1280 x 720 @ 30 fps", .width = 1280, .height = 720, .fps = 30.0 },
184 { .label =
"1920 x 1080 @ 30 fps", .width = 1920, .height = 1080, .fps = 30.0 },
185 { .label =
"1920 x 1080 @ 60 fps (high-end cameras)", .width = 1920, .height = 1080, .fps = 60.0, .high_end =
true },
186 { .label =
"2560 x 1440 @ 30 fps (high-end cameras)", .width = 2560, .height = 1440, .fps = 30.0, .high_end =
true },
209std::shared_ptr<Kakshya::CameraContainer>
213 if (!
m_video->is_codec_valid()) {
214 m_last_error =
"Cannot create container: reader not open";
220 m_last_error =
"Requested pixel format has no ImageFormat equivalent";
224 return std::make_shared<Kakshya::CameraContainer>(
232 const std::shared_ptr<Kakshya::CameraContainer>& container)
238 if (!
m_video->is_codec_valid())
241 uint8_t* dest = container->mutable_frame_ptr();
245 AVPacket* pkt = av_packet_alloc();
249 AVFrame* frame = av_frame_alloc();
251 av_packet_free(&pkt);
255 bool got_frame =
false;
258 int ret = av_read_frame(
m_demux->format_context, pkt);
262 if (pkt->stream_index !=
m_video->stream_index) {
263 av_packet_unref(pkt);
267 ret = avcodec_send_packet(
m_video->codec_context, pkt);
268 av_packet_unref(pkt);
270 if (ret < 0 && ret != AVERROR(EAGAIN))
273 ret = avcodec_receive_frame(
m_video->codec_context, frame);
274 if (ret == AVERROR(EAGAIN))
280 if (!
m_video->rebuild_scaler_from_frame(
282 static_cast<uint32_t
>(frame->width),
283 static_cast<uint32_t
>(frame->height))) {
285 "FFmpegCameraReader: scaler init failed: {}",
289 const size_t buf_bytes =
static_cast<size_t>(
m_video->out_linesize) *
m_video->out_height;
294 uint8_t* sws_dst[1] = {
m_sws_buf.data() };
295 int sws_stride[1] = {
m_video->out_linesize };
297 sws_scale(
m_video->sws_context,
298 frame->data, frame->linesize,
299 0,
static_cast<int>(
m_video->height),
300 sws_dst, sws_stride);
302 const int packed_stride =
static_cast<int>(
m_video->out_width *
m_video->out_bytes_per_pixel);
304 if (
m_video->out_linesize == packed_stride) {
306 static_cast<size_t>(packed_stride) *
m_video->out_height);
308 for (uint32_t row = 0; row <
m_video->out_height; ++row) {
310 dest +
static_cast<size_t>(row) * packed_stride,
312 static_cast<size_t>(packed_stride));
316 container->mark_ready_for_processing(
true);
320 av_frame_free(&frame);
321 av_packet_free(&pkt);
345 const std::shared_ptr<Kakshya::CameraContainer>& container)
#define MF_INFO(comp, ctx,...)
#define MF_ERROR(comp, ctx,...)
#define MF_WARN(comp, ctx,...)
std::shared_ptr< FFmpegDemuxContext > m_demux
void setup_io_service(uint64_t reader_id) override
Setup an IOService for this reader with the given reader_id.
uint32_t height() const override
Negotiated output height in pixels.
std::vector< uint8_t > m_sws_buf
std::vector< CameraMode > preset_modes() const override
Capture modes this source offers as defaults, ordered from safest to most demanding.
std::weak_ptr< Kakshya::CameraContainer > m_container_ref
void decode_thread_func()
std::condition_variable m_decode_cv
void pull_frame_all() override
Signal the source to pull one frame.
std::shared_ptr< VideoStreamContext > m_video
int m_requested_pixel_format
Pixel format requested at open() time, as an AVPixelFormat int.
const std::string & last_error() const override
Last error string, empty if no error.
std::thread m_decode_thread
std::atomic< bool > m_decode_stop
uint32_t width() const override
Negotiated output width in pixels.
std::mutex m_decode_mutex
std::shared_mutex m_ctx_mutex
std::shared_ptr< Registry::Service::IOService > m_standalone_service
void close() override
Release device, decode, and scratch resources.
~FFmpegCameraReader() override
bool is_open() const override
True if the device is open and ready to deliver frames.
void start_decode_thread()
bool pull_frame(const std::shared_ptr< Kakshya::CameraContainer > &container) override
Produce one frame into the container.
std::atomic< bool > m_frame_requested
std::shared_ptr< Kakshya::CameraContainer > create_container() const override
Create a CameraContainer sized to the negotiated device resolution.
uint64_t m_standalone_reader_id
void stop_decode_thread()
void set_container(const std::shared_ptr< Kakshya::CameraContainer > &container) override
Store a weak reference to the container for IOService dispatch.
double frame_rate() const override
Negotiated frame rate in fps.
std::atomic< bool > m_decode_active
bool open(const CameraConfig &config) override
Open a camera device using the supplied config.
RAII owner of a single AVFormatContext and associated demux state.
RAII owner of one video stream's codec and pixel-format scaler state.
void register_service(ServiceFactory factory)
Register a backend service capability.
static BackendRegistry & instance()
Get the global registry instance.
void unregister_service()
Unregister a service.
std::optional< Portal::Graphics::ImageFormat > to_image_format(int av_pixel_format)
Map an AVPixelFormat to the Portal ImageFormat backing it.
@ FileIO
Filesystem I/O operations.
@ Runtime
General runtime operations (default fallback)
@ IO
Networking, file handling, streaming.
int pixel_format
Target AVPixelFormat as int; negative selects AV_PIX_FMT_RGBA.
std::string device_name
Platform device string.
std::string format_override
Leave empty to use CAMERA_FORMAT for current platform.
std::string input_format
Capture format or codec (e.g. "mjpeg"); empty selects mjpeg where the platform supports it.
uint32_t target_width
Requested width in pixels.
uint32_t target_height
Requested height in pixels.
Configuration for opening a camera device via FFmpeg.
Backend IO streaming service interface.