CMBlockBuffer

Struct CMBlockBuffer 

Source
pub struct CMBlockBuffer(/* private fields */);
Expand description

Block buffer containing contiguous media data

CMBlockBuffer is a Core Media type that represents a block of data, commonly used for audio samples or compressed video data. The data is managed by Core Media and released when the buffer is dropped.

Unlike CVPixelBuffer or IOSurface, CMBlockBuffer does not require locking for data access - the data pointer is valid as long as the buffer is retained.

§Examples

use screencapturekit::cm::CMBlockBuffer;

fn process_block_buffer(buffer: &CMBlockBuffer) {
    // Check if there's any data
    if buffer.is_empty() {
        return;
    }

    println!("Buffer has {} bytes", buffer.data_length());

    // Get a pointer to the data
    if let Some((ptr, length)) = buffer.data_pointer(0) {
        println!("Got {} bytes at offset 0", length);
    }

    // Or copy data to a Vec
    if let Some(data) = buffer.copy_data_bytes(0, buffer.data_length()) {
        println!("Copied {} bytes", data.len());
    }
}

Implementations§

Source§

impl CMBlockBuffer

Source

pub fn create(data: &[u8]) -> Option<Self>

Create a new CMBlockBuffer with the given data

§Arguments
  • data - The data to copy into the block buffer
§Returns

Some(CMBlockBuffer) if successful, None if creation failed.

§Examples
use screencapturekit::cm::CMBlockBuffer;

let data = vec![1u8, 2, 3, 4, 5];
let buffer = CMBlockBuffer::create(&data).expect("Failed to create buffer");
assert_eq!(buffer.data_length(), 5);
Source

pub fn create_empty() -> Option<Self>

Create an empty CMBlockBuffer

§Returns

Some(CMBlockBuffer) if successful, None if creation failed.

§Examples
use screencapturekit::cm::CMBlockBuffer;

let buffer = CMBlockBuffer::create_empty().expect("Failed to create empty buffer");
assert!(buffer.is_empty());
Source

pub fn from_raw(ptr: *mut c_void) -> Option<Self>

Create from a raw pointer, returning None if null

Source

pub unsafe fn from_ptr(ptr: *mut c_void) -> Self

§Safety

The caller must ensure the pointer is a valid CMBlockBuffer pointer.

Source

pub fn as_ptr(&self) -> *mut c_void

Get the raw pointer to the block buffer

Source

pub fn data_length(&self) -> usize

Get the total data length of the buffer in bytes

§Examples
use screencapturekit::cm::CMBlockBuffer;

fn check_size(buffer: &CMBlockBuffer) {
    let size = buffer.data_length();
    println!("Buffer contains {} bytes", size);
}
Source

pub fn is_empty(&self) -> bool

Check if the buffer is empty (contains no data)

§Examples
use screencapturekit::cm::CMBlockBuffer;

fn process(buffer: &CMBlockBuffer) {
    if buffer.is_empty() {
        println!("No data to process");
        return;
    }
    // Process data...
}
Source

pub fn is_range_contiguous(&self, offset: usize, length: usize) -> bool

Check if a range of bytes is stored contiguously in memory

§Arguments
  • offset - Starting offset in the buffer
  • length - Length of the range to check
§Returns

true if the specified range is contiguous in memory

Source

pub fn data_pointer(&self, offset: usize) -> Option<(*const u8, usize)>

Get a pointer to the data at the specified offset

Returns a tuple of (data pointer, length available at that offset) if successful. The pointer is valid as long as this CMBlockBuffer is retained.

§Arguments
  • offset - Byte offset into the buffer
§Returns

Some((pointer, length_at_offset)) if the data pointer was obtained successfully, None if the operation failed.

§Examples
use screencapturekit::cm::CMBlockBuffer;

fn read_data(buffer: &CMBlockBuffer) {
    if let Some((ptr, length)) = buffer.data_pointer(0) {
        // SAFETY: ptr is valid for `length` bytes while buffer is alive
        let slice = unsafe { std::slice::from_raw_parts(ptr, length) };
        println!("First byte: {:02x}", slice[0]);
    }
}
Source

pub unsafe fn data_pointer_mut(&self, offset: usize) -> Option<(*mut u8, usize)>

Get a mutable pointer to the data at the specified offset

§Safety

The caller must ensure that modifying the data is safe and that no other references to this data exist.

Source

pub fn copy_data_bytes(&self, offset: usize, length: usize) -> Option<Vec<u8>>

Copy data bytes from the buffer into a new Vec<u8>

This is the safest way to access buffer data as it copies the bytes into owned memory.

§Arguments
  • offset - Starting offset in the buffer
  • length - Number of bytes to copy
§Returns

Some(Vec<u8>) containing the copied data, or None if the copy failed.

§Examples
use screencapturekit::cm::CMBlockBuffer;

fn extract_data(buffer: &CMBlockBuffer) -> Option<Vec<u8>> {
    // Copy all data from the buffer
    buffer.copy_data_bytes(0, buffer.data_length())
}
Source

pub fn copy_data_bytes_into( &self, offset: usize, destination: &mut [u8], ) -> Result<(), i32>

Copy data bytes from the buffer into an existing slice

§Arguments
  • offset - Starting offset in the buffer
  • destination - Mutable slice to copy data into
§Errors

Returns a Core Media error code if the copy fails.

§Examples
use screencapturekit::cm::CMBlockBuffer;

fn read_header(buffer: &CMBlockBuffer) -> Result<[u8; 4], i32> {
    let mut header = [0u8; 4];
    buffer.copy_data_bytes_into(0, &mut header)?;
    Ok(header)
}
Source

pub fn as_slice(&self) -> Option<&[u8]>

Get a slice view of the data if the entire buffer is contiguous

This is a zero-copy way to access the data, but only works if the buffer’s data is stored contiguously in memory.

§Returns

Some(&[u8]) if the buffer is contiguous, None otherwise.

§Examples
use screencapturekit::cm::CMBlockBuffer;

fn process_contiguous(buffer: &CMBlockBuffer) {
    if let Some(data) = buffer.as_slice() {
        println!("Processing {} contiguous bytes", data.len());
    } else {
        // Fall back to copying
        if let Some(data) = buffer.copy_data_bytes(0, buffer.data_length()) {
            println!("Processing {} copied bytes", data.len());
        }
    }
}
Source

pub fn cursor(&self) -> Option<Cursor<Vec<u8>>>

Access buffer with a standard std::io::Cursor

Returns a cursor over a copy of the buffer data. The cursor implements Read and Seek traits for convenient sequential data access.

Note: This copies the data because CMBlockBuffer may not be contiguous. For zero-copy access to contiguous buffers, use as_slice().

§Returns

Some(Cursor) if data could be copied, None if the copy failed.

§Examples
use std::io::{Read, Seek, SeekFrom};
use screencapturekit::cm::CMBlockBuffer;

fn read_data(buffer: &CMBlockBuffer) {
    if let Some(mut cursor) = buffer.cursor() {
        // Read first 4 bytes
        let mut header = [0u8; 4];
        cursor.read_exact(&mut header).unwrap();

        // Seek to a position
        cursor.seek(SeekFrom::Start(100)).unwrap();

        // Read more data
        let mut buf = [0u8; 16];
        cursor.read_exact(&mut buf).unwrap();
    }
}
Source

pub fn cursor_ref(&self) -> Option<Cursor<&[u8]>>

Access contiguous buffer with a zero-copy std::io::Cursor

Returns a cursor over the buffer data without copying, but only works if the buffer is contiguous in memory.

§Returns

Some(Cursor) if the buffer is contiguous, None otherwise.

§Examples
use std::io::{Read, Seek, SeekFrom};
use screencapturekit::cm::CMBlockBuffer;

fn read_contiguous(buffer: &CMBlockBuffer) {
    // Try zero-copy first
    if let Some(mut cursor) = buffer.cursor_ref() {
        let mut header = [0u8; 4];
        cursor.read_exact(&mut header).unwrap();
    } else {
        // Fall back to copying cursor
        if let Some(mut cursor) = buffer.cursor() {
            let mut header = [0u8; 4];
            cursor.read_exact(&mut header).unwrap();
        }
    }
}

Trait Implementations§

Source§

impl Clone for CMBlockBuffer

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CMBlockBuffer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for CMBlockBuffer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for CMBlockBuffer

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Hash for CMBlockBuffer

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for CMBlockBuffer

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for CMBlockBuffer

Source§

impl Send for CMBlockBuffer

Source§

impl Sync for CMBlockBuffer

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.