提交 f287018f authored 作者: Nazar Mokrynskyi's avatar Nazar Mokrynskyi

Send channel requests to worker with a function call instead of though file…

Send channel requests to worker with a function call instead of though file descriptor in Rust (step 3, old fd-based read code is removed)
上级 1f07ea1b
差异被折叠。
mod channel_read_fn;
mod channel_write_fn;
// Contents of this module is inspired by https://github.com/Srinivasa314/alcro/tree/master/src/chrome
......@@ -6,6 +7,7 @@ use crate::worker::{Channel, PayloadChannel, WorkerId};
use async_executor::Executor;
use async_fs::File;
use async_oneshot::Receiver;
pub(super) use channel_read_fn::{prepare_channel_read_fn, PreparedChannelRead};
pub(super) use channel_write_fn::{
prepare_channel_write_fn, prepare_payload_channel_write_fn, PreparedChannelWrite,
PreparedPayloadChannelWrite,
......@@ -62,18 +64,14 @@ pub(super) fn run_worker_with_channels(
executor: Arc<Executor<'static>>,
args: Vec<String>,
) -> WorkerRunResult {
let [producer_fd_read, producer_fd_write] = pipe();
let [consumer_fd_read, consumer_fd_write] = pipe();
let [producer_payload_fd_read, producer_payload_fd_write] = pipe();
let [consumer_payload_fd_read, consumer_payload_fd_write] = pipe();
let (mut status_sender, status_receiver) = async_oneshot::oneshot();
let producer_file = unsafe { File::from_raw_fd(producer_fd_write) };
let consumer_file = unsafe { File::from_raw_fd(consumer_fd_read) };
let producer_payload_file = unsafe { File::from_raw_fd(producer_payload_fd_write) };
let consumer_payload_file = unsafe { File::from_raw_fd(consumer_payload_fd_read) };
let (channel, prepared_channel_write) = Channel::new(&executor, consumer_file, producer_file);
let (channel, prepared_channel_read, prepared_channel_write) = Channel::new();
let (payload_channel, prepared_payload_channel_write) =
PayloadChannel::new(&executor, consumer_payload_file, producer_payload_file);
let buffer_worker_messages_guard = channel.buffer_messages_for(std::process::id().into());
......@@ -96,6 +94,8 @@ pub(super) fn run_worker_with_channels(
let version = CString::new(env!("CARGO_PKG_VERSION")).unwrap();
let status_code = unsafe {
let (channel_read_fn, channel_read_ctx, _channel_write_callback) =
prepared_channel_read.deconstruct();
let (channel_write_fn, channel_write_ctx, _channel_read_callback) =
prepared_channel_write.deconstruct();
let (
......@@ -108,10 +108,12 @@ pub(super) fn run_worker_with_channels(
argc,
argv.as_ptr(),
version.as_ptr(),
producer_fd_read,
consumer_fd_write,
0,
0,
producer_payload_fd_read,
consumer_payload_fd_write,
channel_read_fn,
channel_read_ctx,
channel_write_fn,
channel_write_ctx,
payload_channel_write_fn,
......@@ -119,6 +121,8 @@ pub(super) fn run_worker_with_channels(
)
};
println!("Status sent {}", status_code);
let _ = status_sender.send(match status_code {
0 => Ok(()),
1 => Err(ExitError::Generic),
......
pub(super) use mediasoup_sys::{ChannelReadCtx, ChannelReadFn};
use mediasoup_sys::{ChannelReadFreeFn, UvAsyncT};
use std::mem;
use std::os::raw::c_void;
pub(super) struct ChannelReadCallback(
Box<dyn (FnMut(UvAsyncT) -> Option<Vec<u8>>) + Send + 'static>,
);
pub(crate) struct PreparedChannelRead {
channel_read_fn: ChannelReadFn,
channel_read_ctx: ChannelReadCtx,
write_callback: ChannelReadCallback,
}
unsafe impl Send for PreparedChannelRead {}
impl PreparedChannelRead {
/// SAFETY:
/// 1) `ChannelReadCallback` returned must be dropped AFTER last usage of returned function and
/// context pointers
/// 2) `ChannelReadCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(self) -> (ChannelReadFn, ChannelReadCtx, ChannelReadCallback) {
let Self {
channel_read_fn,
channel_read_ctx,
write_callback,
} = self;
(channel_read_fn, channel_read_ctx, write_callback)
}
}
unsafe extern "C" fn free_vec(message: *mut u8, message_len: u32, message_capacity: usize) {
Vec::from_raw_parts(message, message_len as usize, message_capacity);
}
/// Given callback function, prepares a pair of channel read function and context, which can be
/// provided to of C++ worker and worker will effectively call the callback whenever it wants to
/// read something from Rust (so it is reading from C++ point of view and writing from Rust).
pub(crate) fn prepare_channel_read_fn<F>(read_callback: F) -> PreparedChannelRead
where
F: (FnMut(UvAsyncT) -> Option<Vec<u8>>) + Send + 'static,
{
unsafe extern "C" fn wrapper<F>(
message: *mut *mut u8,
message_len: *mut u32,
message_capacity: *mut usize,
handle: UvAsyncT,
ChannelReadCtx(ctx): ChannelReadCtx,
) -> ChannelReadFreeFn
where
F: (FnMut(UvAsyncT) -> Option<Vec<u8>>) + Send + 'static,
{
// Call Rust and try to get a new message (if there is any)
let mut new_message = (*(ctx as *mut F))(handle)?;
// Set pointers, give out control over memory to C++
*message = new_message.as_mut_ptr();
*message_len = new_message.len() as u32;
*message_capacity = new_message.capacity();
// Forget about vector in Rust
mem::forget(new_message);
// Function pointer that C++ can use to free vector later
Some(free_vec)
}
// Move to heap to make sure it doesn't change address later on
let read_callback = Box::new(read_callback);
PreparedChannelRead {
channel_read_fn: wrapper::<F>,
channel_read_ctx: ChannelReadCtx(read_callback.as_ref() as *const F as *const c_void),
write_callback: ChannelReadCallback(read_callback),
}
}
......@@ -16,8 +16,8 @@ unsafe impl Send for PreparedChannelWrite {}
impl PreparedChannelWrite {
/// SAFETY:
/// 1) `ReadCallback` returned must be dropped AFTER last usage of returned function and context
/// pointers
/// 1) `ChannelReadCallback` returned must be dropped AFTER last usage of returned function and
/// context pointers
/// 2) `ChannelWriteCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(
self,
......@@ -38,8 +38,11 @@ pub(crate) fn prepare_channel_write_fn<F>(read_callback: F) -> PreparedChannelWr
where
F: FnMut(&[u8]) + Send + 'static,
{
unsafe extern "C" fn wrapper<F>(message: *const u8, message_len: u32, ctx: *const c_void)
where
unsafe extern "C" fn wrapper<F>(
message: *const u8,
message_len: u32,
ChannelWriteCtx(ctx): ChannelWriteCtx,
) where
F: FnMut(&[u8]) + Send + 'static,
{
let message = slice::from_raw_parts(message, message_len as usize);
......@@ -51,7 +54,7 @@ where
PreparedChannelWrite {
channel_write_fn: wrapper::<F>,
channel_write_ctx: read_callback.as_ref() as *const F as *const c_void,
channel_write_ctx: ChannelWriteCtx(read_callback.as_ref() as *const F as *const c_void),
read_callback: ChannelReadCallback(read_callback),
}
}
......@@ -68,8 +71,8 @@ unsafe impl Send for PreparedPayloadChannelWrite {}
impl PreparedPayloadChannelWrite {
/// SAFETY:
/// 1) `ReadCallback` returned must be dropped AFTER last usage of returned function and context
/// pointers
/// 1) `PayloadChannelReadCallback` returned must be dropped AFTER last usage of returned
/// function and context pointers
/// 2) `PayloadChannelWriteCtx` should not be called from multiple threads concurrently
pub(super) unsafe fn deconstruct(
self,
......@@ -99,7 +102,7 @@ where
message_len: u32,
payload: *const u8,
payload_len: u32,
ctx: *const c_void,
PayloadChannelWriteCtx(ctx): PayloadChannelWriteCtx,
) where
F: FnMut(&[u8], &[u8]) + Send + 'static,
{
......@@ -117,7 +120,9 @@ where
PreparedPayloadChannelWrite {
channel_write_fn: wrapper::<F>,
channel_write_ctx: read_callback.as_ref() as *const F as *const c_void,
channel_write_ctx: PayloadChannelWriteCtx(
read_callback.as_ref() as *const F as *const c_void
),
read_callback: PayloadChannelReadCallback(read_callback),
}
}
......@@ -279,6 +279,19 @@ fn produce_succeeds() {
assert_eq!(transport_1_dump.producer_ids, vec![audio_producer.id()]);
assert_eq!(transport_1_dump.consumer_ids, vec![]);
let (mut tx, rx) = async_oneshot::oneshot::<()>();
transport_1
.on_close(Box::new(move || {
let _ = tx.send(());
}))
.detach();
drop(audio_producer);
drop(transport_1);
// This means producer was definitely dropped
rx.await.expect("Failed to receive transport close event");
}
{
......
......@@ -65,7 +65,10 @@ namespace Channel
public:
explicit ChannelSocket(int consumerFd, int producerFd);
explicit ChannelSocket(
int consumerFd, int producerFd, ChannelWriteFn channelWriteFn, ChannelWriteCtx channelWriteCtx);
ChannelReadFn channelReadFn,
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx);
virtual ~ChannelSocket();
public:
......@@ -73,6 +76,7 @@ namespace Channel
void SetListener(Listener* listener);
void Send(json& jsonMessage);
void SendLog(const char* message, uint32_t messageLen);
bool CallbackRead();
private:
void SendImpl(const uint8_t* payload, uint32_t payloadLen);
......@@ -87,11 +91,14 @@ namespace Channel
Listener* listener{ nullptr };
// Others.
bool closed{ false };
ConsumerSocket consumerSocket;
ProducerSocket producerSocket;
ConsumerSocket* consumerSocket{ nullptr };
ProducerSocket* producerSocket{ nullptr };
ChannelReadFn channelReadFn{ nullptr };
ChannelReadCtx channelReadCtx{ nullptr };
ChannelWriteFn channelWriteFn{ nullptr };
ChannelWriteCtx channelWriteCtx{ nullptr };
uint8_t* writeBuffer;
uv_async_t* uvReadHandle{ nullptr };
uint8_t* writeBuffer{ nullptr };
};
} // namespace Channel
......
......@@ -26,9 +26,22 @@ typedef SSIZE_T ssize_t;
#include <sys/socket.h> // struct sockaddr, struct sockaddr_storage, AF_INET, AF_INET6
#endif
using ChannelReadCtx = void*;
using ChannelReadFreeFn = void (*)(uint8_t*, uint32_t, size_t);
// Returns `ChannelReadFree` on successful read that must be used to free `message`
using ChannelReadFn = ChannelReadFreeFn (*)(
uint8_t** /* message */,
uint32_t* /* messageLen */,
size_t* /* messageCapacity */,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is more
// data to read
const void* /* handle */,
ChannelReadCtx /* ctx */);
using ChannelWriteCtx = void*;
using ChannelWriteFn =
void (*)(const uint8_t* /* message */, uint32_t /* messageLen */, ChannelWriteCtx /* ctx */);
using PayloadChannelWriteCtx = void*;
using PayloadChannelWriteFn = void (*)(
const uint8_t* /* message */,
......
......@@ -8,6 +8,8 @@ extern "C" int run_worker(
int producerChannelFd,
int payloadConsumeChannelFd,
int payloadProduceChannelFd,
ChannelReadFn channelReadFn,
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
......
......@@ -2,6 +2,7 @@
// #define MS_LOG_DEV_LEVEL 3
#include "Channel/ChannelSocket.hpp"
#include "DepLibUV.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include <cmath> // std::ceil()
......@@ -11,6 +12,18 @@
namespace Channel
{
/* Static. */
inline static void onAsync(uv_handle_t* handle)
{
while (static_cast<ChannelSocket*>(handle->data)->CallbackRead())
{
// Read while there are new messages
}
}
inline static void onClose(uv_handle_t* handle)
{
delete handle;
}
// Binary length for a 4194304 bytes payload.
static constexpr size_t MessageMaxLen{ 4194308 };
......@@ -18,21 +31,48 @@ namespace Channel
/* Instance methods. */
ChannelSocket::ChannelSocket(int consumerFd, int producerFd)
: consumerSocket(consumerFd, MessageMaxLen, this), producerSocket(producerFd, MessageMaxLen)
: consumerSocket(new ConsumerSocket(consumerFd, MessageMaxLen, this)),
producerSocket(new ProducerSocket(producerFd, MessageMaxLen)),
writeBuffer(static_cast<uint8_t*>(std::malloc(MessageMaxLen)))
{
MS_TRACE_STD();
this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen));
}
ChannelSocket::ChannelSocket(
int consumerFd, int producerFd, ChannelWriteFn channelWriteFn, ChannelWriteCtx channelWriteCtx)
: consumerSocket(consumerFd, MessageMaxLen, this), producerSocket(producerFd, MessageMaxLen),
channelWriteFn(channelWriteFn), channelWriteCtx(channelWriteCtx)
ChannelReadFn channelReadFn,
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx)
: channelReadFn(channelReadFn), channelReadCtx(channelReadCtx), channelWriteFn(channelWriteFn),
channelWriteCtx(channelWriteCtx)
{
MS_TRACE_STD();
this->writeBuffer = static_cast<uint8_t*>(std::malloc(MessageMaxLen));
int err;
this->uvReadHandle = new uv_async_t;
this->uvReadHandle->data = static_cast<void*>(this);
err =
uv_async_init(DepLibUV::GetLoop(), this->uvReadHandle, reinterpret_cast<uv_async_cb>(onAsync));
if (err != 0)
{
delete this->uvReadHandle;
this->uvReadHandle = nullptr;
MS_THROW_ERROR_STD("uv_async_init() failed: %s", uv_strerror(err));
}
err = uv_async_send(this->uvReadHandle);
if (err != 0)
{
delete this->uvReadHandle;
this->uvReadHandle = nullptr;
MS_THROW_ERROR_STD("uv_async_send() failed: %s", uv_strerror(err));
}
}
ChannelSocket::~ChannelSocket()
......@@ -43,6 +83,9 @@ namespace Channel
if (!this->closed)
Close();
delete this->consumerSocket;
delete this->producerSocket;
}
void ChannelSocket::Close()
......@@ -54,8 +97,19 @@ namespace Channel
this->closed = true;
this->consumerSocket.Close();
this->producerSocket.Close();
if (this->uvReadHandle)
{
uv_close(reinterpret_cast<uv_handle_t*>(this->uvReadHandle), static_cast<uv_close_cb>(onClose));
}
if (this->consumerSocket)
{
this->consumerSocket->Close();
}
if (this->producerSocket)
{
this->producerSocket->Close();
}
}
void ChannelSocket::SetListener(Listener* listener)
......@@ -102,6 +156,59 @@ namespace Channel
SendImpl(reinterpret_cast<const uint8_t*>(message), messageLen);
}
bool ChannelSocket::CallbackRead()
{
MS_TRACE_STD();
if (this->closed)
return false;
uint8_t* message{ nullptr };
uint32_t messageLen;
size_t messageCapacity;
auto free = this->channelReadFn(
&message, &messageLen, &messageCapacity, this->uvReadHandle, this->channelReadCtx);
if (free)
{
try
{
json jsonMessage = json::parse(message, message + static_cast<size_t>(messageLen));
auto* request = new Channel::ChannelRequest(this, jsonMessage);
// Notify the listener.
try
{
this->listener->OnChannelRequest(this, request);
}
catch (const MediaSoupTypeError& error)
{
request->TypeError(error.what());
}
catch (const MediaSoupError& error)
{
request->Error(error.what());
}
// Delete the Request.
delete request;
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR_STD("discarding wrong Channel request");
}
free(message, messageLen, messageCapacity);
}
return free != nullptr;
}
inline void ChannelSocket::SendImpl(const uint8_t* payload, uint32_t payloadLen)
{
MS_TRACE_STD();
......@@ -122,7 +229,7 @@ namespace Channel
size_t len = sizeof(uint32_t) + payloadLen;
this->producerSocket.Write(this->writeBuffer, len);
this->producerSocket->Write(this->writeBuffer, len);
}
}
......
......@@ -36,6 +36,8 @@ extern "C" int run_worker(
int producerChannelFd,
int payloadConsumeChannelFd,
int payloadProduceChannelFd,
ChannelReadFn channelReadFn,
ChannelReadCtx channelReadCtx,
ChannelWriteFn channelWriteFn,
ChannelWriteCtx channelWriteCtx,
PayloadChannelWriteFn payloadChannelWriteFn,
......@@ -56,8 +58,15 @@ extern "C" int run_worker(
try
{
channel.reset(new Channel::ChannelSocket(
consumerChannelFd, producerChannelFd, channelWriteFn, channelWriteCtx));
if (channelReadFn)
{
channel.reset(
new Channel::ChannelSocket(channelReadFn, channelReadCtx, channelWriteFn, channelWriteCtx));
}
else
{
channel.reset(new Channel::ChannelSocket(consumerChannelFd, producerChannelFd));
}
}
catch (const MediaSoupError& error)
{
......
use std::os::raw::{c_char, c_int, c_void};
pub type ChannelWriteCtx = *const c_void;
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct UvAsyncT(*const c_void);
unsafe impl Send for UvAsyncT {}
#[repr(transparent)]
pub struct ChannelReadCtx(pub *const c_void);
pub type ChannelReadFreeFn = Option<
unsafe extern "C" fn(
/* message: */ *mut u8,
/* message_len: */ u32,
/* message_capacity: */ usize,
),
>;
pub type ChannelReadFn = unsafe extern "C" fn(
/* message: */ *mut *mut u8,
/* message_len: */ *mut u32,
/* message_capacity: */ *mut usize,
// This is `uv_async_t` handle that can be called later with `uv_async_send()` when there is
// more data to read
/* handle */
UvAsyncT,
/* ctx: */ ChannelReadCtx,
) -> ChannelReadFreeFn;
#[repr(transparent)]
pub struct ChannelWriteCtx(pub *const c_void);
pub type ChannelWriteFn = unsafe extern "C" fn(
/* message: */ *const u8,
/* message_len: */ u32,
/* ctx: */ ChannelWriteCtx,
);
pub type PayloadChannelWriteCtx = *const c_void;
#[repr(transparent)]
pub struct PayloadChannelWriteCtx(pub *const c_void);
pub type PayloadChannelWriteFn = unsafe extern "C" fn(
/* message: */ *const u8,
/* message_len: */ u32,
/* payload: */ *const u8,
/* payload_len: */ u32,
/* ctx: */ ChannelWriteCtx,
/* ctx: */ PayloadChannelWriteCtx,
);
#[link(name = "mediasoup-worker", kind = "static")]
extern "C" {
/// Returns `0` on success, or an error code `< 0` on failure
pub fn uv_async_send(handle: UvAsyncT) -> c_int;
pub fn run_worker(
argc: c_int,
argv: *const *const c_char,
......@@ -26,6 +57,8 @@ extern "C" {
producer_channel_fd: c_int,
payload_consumer_channel_fd: c_int,
payload_producer_channel_fd: c_int,
channel_read_fn: ChannelReadFn,
channel_read_ctx: ChannelReadCtx,
channel_write_fn: ChannelWriteFn,
channel_write_ctx: ChannelWriteCtx,
payload_channel_write_fn: PayloadChannelWriteFn,
......
......@@ -34,6 +34,8 @@ int main(int argc, char* argv[])
nullptr,
nullptr,
nullptr,
nullptr,
nullptr,
nullptr);
switch (statusCode)
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论