Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions cpp/ffmpeg_ram/ffmpeg_ram_decode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ extern "C" {
#include <libavutil/hwcontext_d3d11va.h>
#endif

#ifdef __APPLE__
#include <CoreVideo/CVPixelBuffer.h>
#include <CoreVideo/CVPixelBufferIOSurface.h>
#endif

#include "common.h"
#include "system.h"

Expand All @@ -29,6 +34,28 @@ typedef void (*RamDecodeCallback)(const void *obj, int width, int height,
enum AVPixelFormat pixfmt,
int linesize[AV_NUM_DATA_POINTERS],
uint8_t *data[AV_NUM_DATA_POINTERS], int key);
typedef void (*RamDecodeHwBufferCallback)(const void *obj, int width,
int height, void *hw_buffer,
int key);

#ifdef __APPLE__
// True if the VideoToolbox output is an IOSurface-backed bi-planar 8-bit 4:2:0
// buffer, which Metal can sample without a copy. The size check makes cropped
// frames fall back to the copy path, which honours the frame's visible size.
bool is_directly_renderable(const AVFrame *frame) {
if (frame->format != AV_PIX_FMT_VIDEOTOOLBOX || !frame->data[3])
return false;
CVPixelBufferRef pb = (CVPixelBufferRef)frame->data[3];
OSType fmt = CVPixelBufferGetPixelFormatType(pb);
if (fmt != kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange &&
fmt != kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)
return false;
if (!CVPixelBufferGetIOSurface(pb))
return false;
return (int)CVPixelBufferGetWidth(pb) == frame->width &&
(int)CVPixelBufferGetHeight(pb) == frame->height;
}
#endif

class FFmpegRamDecoder {
public:
Expand All @@ -43,6 +70,8 @@ class FFmpegRamDecoder {
AVHWDeviceType device_type_ = AV_HWDEVICE_TYPE_NONE;
int thread_count_ = 1;
RamDecodeCallback callback_ = NULL;
RamDecodeHwBufferCallback hw_buffer_callback_ = NULL;
int hw_buffer_direct_ = -1; // last logged decision, -1 before the first frame
DataFormat data_format_;

#ifdef CFG_PKG_TRACE
Expand Down Expand Up @@ -197,6 +226,34 @@ class FFmpegRamDecoder {
LOG_ERROR(std::string("hw_frames_ctx is NULL"));
goto _exit;
}
#ifdef __APPLE__
if (hw_buffer_callback_) {
bool direct = is_directly_renderable(frame_);
if ((int)direct != hw_buffer_direct_) {
hw_buffer_direct_ = direct;
LOG_INFO(std::string("VideoToolbox output ") +
(direct ? "passed through as CVPixelBuffer"
: "not directly renderable, copying to memory"));
}
if (direct) {
#if FF_API_FRAME_KEY
int key_frame = frame_->flags & AV_FRAME_FLAG_KEY;
#else
int key_frame = frame_->key_frame;
#endif
decoded = true;
#ifdef CFG_PKG_TRACE
out_++;
LOG_DEBUG(std::string("delay DO: in:") + in_ + " out:" + out_);
#endif
// frame_ keeps the buffer alive during the call; the receiver
// must retain it to keep it longer.
hw_buffer_callback_(obj, frame_->width, frame_->height,
frame_->data[3], key_frame);
continue;
}
}
#endif
if ((sw_frame_->width != 0 || sw_frame_->height != 0) &&
(sw_frame_->width != frame_->width ||
sw_frame_->height != frame_->height)) {
Expand Down Expand Up @@ -319,6 +376,21 @@ ffmpeg_ram_new_decoder(const char *name, int device_type, int thread_count,
return NULL;
}

extern "C" void
ffmpeg_ram_decoder_set_hw_buffer_callback(FFmpegRamDecoder *decoder,
RamDecodeHwBufferCallback callback) {
if (!decoder)
return;
#ifdef __APPLE__
if (decoder->device_type_ == AV_HWDEVICE_TYPE_VIDEOTOOLBOX) {
decoder->hw_buffer_callback_ = callback;
decoder->hw_buffer_direct_ = -1;
}
#else
(void)callback;
#endif
}

extern "C" int ffmpeg_ram_decode(FFmpegRamDecoder *decoder, const uint8_t *data,
int length, const void *obj) {
try {
Expand Down
11 changes: 11 additions & 0 deletions cpp/ffmpeg_ram/ffmpeg_ram_ffi.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ typedef void (*RamDecodeCallback)(const void *obj, int width, int height,
uint8_t *data[AV_NUM_DATA_POINTERS], int key);
typedef void (*RamEncodeCallback)(const uint8_t *data, int len, int64_t pts,
int key, const void *obj);
// hw_buffer is borrowed and only valid during the call (macOS: CVPixelBufferRef).
typedef void (*RamDecodeHwBufferCallback)(const void *obj, int width,
int height, void *hw_buffer,
int key);

void *ffmpeg_ram_new_encoder(const char *name, const char *mc_name, int width,
int height, int pixfmt, int align, int fps,
Expand All @@ -26,6 +30,13 @@ int ffmpeg_ram_decode(void *decoder, const uint8_t *data, int length,
const void *obj);
void ffmpeg_ram_free_encoder(void *encoder);
void ffmpeg_ram_free_decoder(void *decoder);
// Apple VideoToolbox decoders only, no-op for other decoders and platforms.
// With a non-NULL callback, frames whose CVPixelBuffer can be sampled directly
// by Metal (IOSurface-backed 8-bit NV12) go to the callback instead of being
// copied to system memory. Other frames still use RamDecodeCallback. NULL
// restores the default behaviour.
void ffmpeg_ram_decoder_set_hw_buffer_callback(
void *decoder, RamDecodeHwBufferCallback callback);
int ffmpeg_ram_get_linesize_offset_length(int pix_fmt, int width, int height,
int align, int *linesize, int *offset,
int *length);
Expand Down
87 changes: 87 additions & 0 deletions src/ffmpeg_ram/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,51 @@ pub struct DecodeFrame {
pub data: Vec<Vec<u8>>,
pub linesize: Vec<i32>,
pub key: bool,
/// Set instead of `data`/`linesize` for frames passed through by
/// [`Decoder::set_output_cv_pixel_buffer`]. `pixfmt` is then NV12 (video or
/// full range); check this field before reading `data`.
#[cfg(target_os = "macos")]
pub cv_pixel_buffer: Option<CVPixelBuffer>,
}

#[cfg(target_os = "macos")]
pub use cv_pixel_buffer::CVPixelBuffer;

#[cfg(target_os = "macos")]
mod cv_pixel_buffer {
use std::ffi::c_void;

extern "C" {
fn CFRetain(cf: *const c_void) -> *const c_void;
fn CFRelease(cf: *const c_void);
}

/// An owned reference to a `CVPixelBufferRef`.
pub struct CVPixelBuffer(*mut c_void);

// CoreFoundation reference counting is thread safe, and the decoder never
// writes to a buffer after handing it out.
unsafe impl Send for CVPixelBuffer {}
unsafe impl Sync for CVPixelBuffer {}

impl CVPixelBuffer {
/// # Safety
/// `ptr` must be a valid, non-null `CVPixelBufferRef`.
pub(super) unsafe fn retain(ptr: *mut c_void) -> Self {
CFRetain(ptr);
Self(ptr)
}

pub fn as_ptr(&self) -> *mut c_void {
self.0
}
}

impl Drop for CVPixelBuffer {
fn drop(&mut self) {
unsafe { CFRelease(self.0) }
}
}
}

impl std::fmt::Display for DecodeFrame {
Expand Down Expand Up @@ -105,6 +150,46 @@ impl Decoder {
}
}

/// VideoToolbox frames that Metal can sample directly come out in
/// [`DecodeFrame::cv_pixel_buffer`] instead of being copied to `data`.
#[cfg(target_os = "macos")]
pub fn set_output_cv_pixel_buffer(&mut self, enable: bool) {
unsafe {
crate::ffmpeg_ram::ffmpeg_ram_decoder_set_hw_buffer_callback(
self.codec,
if enable {
Some(Decoder::hw_buffer_callback)
} else {
None
},
);
}
}

#[cfg(target_os = "macos")]
unsafe extern "C" fn hw_buffer_callback(
obj: *const c_void,
width: c_int,
height: c_int,
hw_buffer: *mut c_void,
key: c_int,
) {
if hw_buffer.is_null() {
return;
}
let frames = &mut *(obj as *mut Vec<DecodeFrame>);
frames.push(DecodeFrame {
pixfmt: AVPixelFormat::AV_PIX_FMT_NV12,
width,
height,
data: vec![],
linesize: vec![],
key: key != 0,
// Borrowed for the duration of this call only.
cv_pixel_buffer: Some(CVPixelBuffer::retain(hw_buffer)),
});
}

unsafe extern "C" fn callback(
obj: *const c_void,
width: c_int,
Expand All @@ -125,6 +210,8 @@ impl Decoder {
data: vec![],
linesize: vec![],
key: key != 0,
#[cfg(target_os = "macos")]
cv_pixel_buffer: None,
};

if pixfmt == AVPixelFormat::AV_PIX_FMT_YUV420P as c_int {
Expand Down