lv2-worker-0.1.1/.cargo_vcs_info.json0000644000000001121374457177700131230ustar { "git": { "sha1": "c93bfe859a849c5189a27c62c659bd3b724a39b6" } } lv2-worker-0.1.1/Cargo.toml0000644000000016561374457177700111370ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "lv2-worker" version = "0.1.1" authors = ["Amaury ABRIAL aka Yruama_Lairba "] description = "rust-lv2's work offloading library" readme = "README.md" license = "MIT OR Apache-2.0" repository = "https://github.com/RustAudio/rust-lv2" [dependencies.lv2-core] version = "3.0.0" [dependencies.lv2-sys] version = "2.0.0" [dependencies.urid] version = "0.1.0" lv2-worker-0.1.1/Cargo.toml.orig010064400017500001750000000005531374457150200146060ustar 00000000000000[package] name = "lv2-worker" version = "0.1.1" authors = ["Amaury ABRIAL aka Yruama_Lairba "] edition = "2018" license = "MIT OR Apache-2.0" description = "rust-lv2's work offloading library" readme = "README.md" repository = "https://github.com/RustAudio/rust-lv2" [dependencies] lv2-sys = "2.0.0" lv2-core = "3.0.0" urid = "0.1.0" lv2-worker-0.1.1/LICENSE-APACHE010064400017500001731000000251371364504410600136420ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. lv2-worker-0.1.1/LICENSE-MIT010064400017500001731000000017761364504410600133550ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.lv2-worker-0.1.1/README.md010064400017500001750000000016371374457150200132020ustar 00000000000000# Rust-LV2's library to implement LV2 Worker extension. Work scheduling library that allows real-time capable LV2 plugins to execute non-real-time actions. This is a part of [`rust-lv2`](https://crates.io/crates/lv2), a safe, fast, and ergonomic framework to create [LV2 plugins](http://lv2plug.in/) for audio processing, written in Rust. ## Documentation The original LV2 API (in the `C` programming language) is documented by ["the LV2 book"](https://lv2plug.in/book/). This book is in the process of being translated to Rust along with the development of `rust-lv2` [(link)](https://janonard.github.io/rust-lv2-book/) and describes how to properly use `rust-lv2`. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. lv2-worker-0.1.1/src/lib.rs010064400017500001750000000615241374457150200136270ustar 00000000000000//! Work scheduling library that allows real-time capable LV2 plugins to execute non-real-time actions. //! //! This crate allows plugins to schedule work that must be performed in another thread. //! Plugins can use this interface to safely perform work that is not real-time safe, and receive //! the result in the run context. A typical use case is a sampler reading and caching data from //! disk. You can look at the //! [LV2 Worker Specification](https://lv2plug.in/ns/ext/worker/worker.html) for more details. //! //! # Example //!``` //!use std::any::Any; //!use lv2_core::feature::*; //!use lv2_core::prelude::*; //!use urid::*; //!use lv2_worker::*; //! //!#[derive(PortCollection)] //!struct Ports {} //! //!/// Requested features //!#[derive(FeatureCollection)] //!struct AudioFeatures<'a> { //! ///host feature allowing to schedule some work //! schedule: Schedule<'a, EgWorker>, //!} //! //!//custom datatype //!struct WorkMessage { //! cycle: usize, //! task: usize, //!} //! //!/// A plugin that do some work in another thread //!struct EgWorker { //! // The schedule handler needs to know the plugin type in order to access the `WorkData` type. //! cycle: usize, //! end_cycle: usize, //!} //! //!/// URI identifier //!unsafe impl UriBound for EgWorker { //! const URI: &'static [u8] = b"urn:rust-lv2-more-examples:eg-worker-rs\0"; //!} //! //!impl Plugin for EgWorker { //! type Ports = Ports; //! type InitFeatures = (); //! type AudioFeatures = AudioFeatures<'static>; //! //! fn new(_plugin_info: &PluginInfo, _features: &mut Self::InitFeatures) -> Option { //! Some(Self { //! cycle: 0, //! end_cycle: 1, //! }) //! } //! //! fn run(&mut self, _ports: &mut Ports, features: &mut Self::AudioFeatures, _: u32) { //! self.cycle += 1; //! let cycle = self.cycle; //! println!("cycle {} started", cycle); //! for task in 0..10 { //! let work = WorkMessage { cycle, task }; //! // schedule some work, passing some data and check for error //! if let Err(e) = features.schedule.schedule_work(work) { //! eprintln!("Can't schedule work: {}", e); //! } //! } //! } //! //! fn extension_data(uri: &Uri) -> Option<&'static dyn Any> { //! match_extensions![uri, WorkerDescriptor] //! } //!} //! //!/// Implementing the extension. //!impl Worker for EgWorker { //! // data type sent by the schedule handler and received by the `work` method. //! type WorkData = WorkMessage; //! // data type sent by the response handler and received by the `work_response` method. //! type ResponseData = String; //! fn work( //! //response handler need to know the plugin type. //! response_handler: &ResponseHandler, //! data: Self::WorkData, //! ) -> Result<(), WorkerError> { //! println!("work received: cycle {}, task {}", data.cycle, data.task); //! if data.task >= 5 { //! if let Err(e) = response_handler.respond(format!( //! "response to cycle {}, task {}", //! data.cycle, data.task //! )) { //! eprintln!("Can't respond: {}", e); //! } //! }; //! Ok(()) //! } //! //! fn work_response( //! &mut self, //! data: Self::ResponseData, //! _features: &mut Self::AudioFeatures, //! ) -> Result<(), WorkerError> { //! println!("work_response received: {}", data); //! Ok(()) //! } //! //! fn end_run(&mut self, _features: &mut Self::AudioFeatures) -> Result<(), WorkerError> { //! println!("cycle {} ended", self.end_cycle); //! self.end_cycle += 1; //! Ok(()) //! } //!} //!``` use lv2_core::extension::ExtensionDescriptor; use lv2_core::feature::*; use lv2_core::plugin::{Plugin, PluginInstance}; use std::fmt; use std::marker::PhantomData; use std::mem; use std::mem::ManuallyDrop; use std::os::raw::*; //get all common c_type use std::ptr; use urid::*; /// Errors potentially generated by the /// [`Schedule::schedule_work`](struct.Schedule.html#method.schedule_work) method #[derive(PartialEq, Eq, Clone, Copy)] pub enum ScheduleError { /// Unknown or general error Unknown(T), /// Failure due to a lack of space NoSpace(T), /// No `schedule_work` callback was provided by the host /// /// This can only happen with faulty host NoCallback(T), } impl fmt::Debug for ScheduleError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { ScheduleError::Unknown(..) => "Unknown(..)".fmt(f), ScheduleError::NoSpace(..) => "NoSpace(..)".fmt(f), ScheduleError::NoCallback(..) => "NoCallback(..)".fmt(f), } } } impl fmt::Display for ScheduleError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { ScheduleError::Unknown(..) => "unknown error".fmt(f), ScheduleError::NoSpace(..) => "not enough space".fmt(f), ScheduleError::NoCallback(..) => "no callback".fmt(f), } } } /// Host feature providing data to build a ScheduleHandler. #[repr(transparent)] pub struct Schedule<'a, P> { internal: &'a lv2_sys::LV2_Worker_Schedule, phantom: PhantomData<*const P>, } unsafe impl<'a, P> UriBound for Schedule<'a, P> { const URI: &'static [u8] = lv2_sys::LV2_WORKER__schedule; } unsafe impl<'a, P> Feature for Schedule<'a, P> { unsafe fn from_feature_ptr(feature: *const c_void, class: ThreadingClass) -> Option { if class == ThreadingClass::Audio { (feature as *const lv2_sys::LV2_Worker_Schedule) .as_ref() .map(|internal| Self { internal, phantom: PhantomData::<*const P>, }) } else { panic!("The Worker Schedule feature is only allowed in the audio threading class"); } } } impl<'a, P: Worker> Schedule<'a, P> { /// Request the host to call the worker thread. /// /// If this method fails, the data is considered as untransmitted and is returned to the caller. /// /// This method should be called from `run()` context to request that the host call the `work()` /// method in a non-realtime context with the given arguments. /// /// This function is always safe to call from `run()`, but it is not guaranteed that the worker /// is actually called from a different thread. In particular, when free-wheeling (e.g. for /// offline rendering), the worker may be executed immediately. This allows single-threaded /// processing with sample accuracy and avoids timing problems when `run()` is executing much /// faster or slower than real-time. /// /// Plugins SHOULD be written in such a way that if the worker runs immediately, and responses /// from the worker are delivered immediately, the effect of the work takes place immediately /// with sample accuracy. /// /// **Notes about the passed data:** The buffer used to pass data is managed by the host. That /// mean the size is unknown and may be limited. So if you need to pass huge amount of data, /// it's preferable to use another way, for example a sync::mpsc channel. pub fn schedule_work(&self, worker_data: P::WorkData) -> Result<(), ScheduleError> where P::WorkData: 'static + Send, { let worker_data = ManuallyDrop::new(worker_data); let size = mem::size_of_val(&worker_data) as u32; let ptr = &worker_data as *const _ as *const c_void; let schedule_work = if let Some(schedule_work) = self.internal.schedule_work { schedule_work } else { return Err(ScheduleError::NoCallback(ManuallyDrop::into_inner( worker_data, ))); }; match unsafe { (schedule_work)(self.internal.handle, size, ptr) } { lv2_sys::LV2_Worker_Status_LV2_WORKER_SUCCESS => Ok(()), lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN => Err(ScheduleError::Unknown( ManuallyDrop::into_inner(worker_data), )), lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_NO_SPACE => Err(ScheduleError::NoSpace( ManuallyDrop::into_inner(worker_data), )), _ => Err(ScheduleError::Unknown(ManuallyDrop::into_inner( worker_data, ))), } } } /// Errors potentially generated by the /// [`ResponseHandler::respond`](struct.ResponseHandler.html#method.respond) method #[derive(PartialEq, Eq, Clone, Copy)] pub enum RespondError { /// Unknown or general error Unknown(T), /// Failure due to a lack of space NoSpace(T), /// No response callback was provided by the host /// /// This can only happen with faulty host NoCallback(T), } impl fmt::Debug for RespondError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { RespondError::Unknown(..) => "Unknown(..)".fmt(f), RespondError::NoSpace(..) => "NoSpace(..)".fmt(f), RespondError::NoCallback(..) => "NoCallback(..)".fmt(f), } } } impl fmt::Display for RespondError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { RespondError::Unknown(..) => "unknown error".fmt(f), RespondError::NoSpace(..) => "not enough space".fmt(f), RespondError::NoCallback(..) => "no callback".fmt(f), } } } /// Handler available inside the worker function to send a response to the `run()` context. /// /// The `ResponseHandler` needs to know the `Worker` trait implementor as a generic parameter since the /// data, which is send to `work_response`, must be of the `ResponseData` associated type. pub struct ResponseHandler { /// function provided by the host to send response to `run()` response_function: lv2_sys::LV2_Worker_Respond_Function, /// Response handler provided by the host, must be passed to the host provided /// response_function. respond_handle: lv2_sys::LV2_Worker_Respond_Handle, phantom: PhantomData

, } impl ResponseHandler

{ /// Send a response to the `run` context. /// /// This method allows the worker to give a response to the `run` context. After calling this /// method, the host will call `worker_response` with the given response data or a copy of it. /// /// If this method fails, the data is considered as untransmitted and is returned to the caller. pub fn respond( &self, response_data: P::ResponseData, ) -> Result<(), RespondError> where P::WorkData: 'static + Send, { let response_data = ManuallyDrop::new(response_data); let size = mem::size_of_val(&response_data) as u32; let ptr = &response_data as *const _ as *const c_void; let response_function = if let Some(response_function) = self.response_function { response_function } else { return Err(RespondError::NoCallback(ManuallyDrop::into_inner( response_data, ))); }; match unsafe { (response_function)(self.respond_handle, size, ptr) } { lv2_sys::LV2_Worker_Status_LV2_WORKER_SUCCESS => Ok(()), lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN => Err(RespondError::Unknown( ManuallyDrop::into_inner(response_data), )), lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_NO_SPACE => Err(RespondError::NoSpace( ManuallyDrop::into_inner(response_data), )), _ => Err(RespondError::Unknown(ManuallyDrop::into_inner( response_data, ))), } } } /// Errors potentially generated by [`Worker`](trait.Worker.html) methods #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum WorkerError { /// Unknown or general error Unknown, /// Failure due to a lack of space NoSpace, } /// The non-realtime working extension for plugins. /// /// This trait and the [`Schedule`](struct.Schedule.html) struct enable plugin creators to use the /// [Worker specification](https://lv2plug.in/doc/html/group__worker.html) for non-realtime working /// tasks. /// /// In order to be used by the host, you need to to export the [`WorkerDescriptor`](struct.WorkerDescriptor.html) /// in the `extension_data` method. You can do that with the `match_extensions` macro from the `lv2-core` crate. pub trait Worker: Plugin { /// Type of data sent to `work` by the schedule handler. type WorkData: 'static + Send; /// Type of data sent to `work_response` by the response handler. type ResponseData: 'static + Send; /// The work to do in a non-real-time context, /// /// This is called by the host in a non-realtime context as requested, probably in a separate /// thread from `run()` and possibly with an arbitrary message to handle. /// /// A response can be sent to `run()` context using the response handler. The plugin MUST NOT make any assumptions /// about which thread calls this method, except that there are no real-time requirements and /// only one call may be executed at a time. That is, the host MAY call this method from any /// non-real-time thread, but MUST NOT make concurrent calls to this method from several /// threads. fn work( response_handler: &ResponseHandler, data: Self::WorkData, ) -> Result<(), WorkerError>; /// Handle a response from the worker. /// /// This is called by the host in the `run()` context when a response from the worker is ready. fn work_response( &mut self, _data: Self::ResponseData, _features: &mut Self::AudioFeatures, ) -> Result<(), WorkerError> { Ok(()) } ///Called when all responses for this cycle have been delivered. /// ///Since work_response() may be called after `run()` finished, this method provides a hook for code that ///must run after the cycle is completed. fn end_run(&mut self, _features: &mut Self::AudioFeatures) -> Result<(), WorkerError> { Ok(()) } } ///Raw wrapper of the [`Worker`](trait.Worker.html) extension. /// /// This is a marker type that has the required external methods for the extension. pub struct WorkerDescriptor { plugin: PhantomData

, } unsafe impl UriBound for WorkerDescriptor

{ const URI: &'static [u8] = lv2_sys::LV2_WORKER__interface; } impl WorkerDescriptor

{ /// Extern unsafe version of `work` method actually called by the host unsafe extern "C" fn extern_work( _handle: lv2_sys::LV2_Handle, response_function: lv2_sys::LV2_Worker_Respond_Function, respond_handle: lv2_sys::LV2_Worker_Respond_Handle, size: u32, data: *const c_void, ) -> lv2_sys::LV2_Worker_Status { //build response handler let response_handler = ResponseHandler { response_function, respond_handle, phantom: PhantomData::

, }; //build ref to worker data from raw pointer let worker_data = ptr::read_unaligned(data as *const mem::ManuallyDrop<

::WorkData>); let worker_data = mem::ManuallyDrop::into_inner(worker_data); if size as usize != mem::size_of_val(&worker_data) { return lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN; } match P::work(&response_handler, worker_data) { Ok(()) => lv2_sys::LV2_Worker_Status_LV2_WORKER_SUCCESS, Err(WorkerError::Unknown) => lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN, Err(WorkerError::NoSpace) => lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_NO_SPACE, } } /// Extern unsafe version of `work_response` method actually called by the host unsafe extern "C" fn extern_work_response( handle: lv2_sys::LV2_Handle, size: u32, body: *const c_void, ) -> lv2_sys::LV2_Worker_Status { //deref plugin_instance and get the plugin let plugin_instance = if let Some(plugin_instance) = (handle as *mut PluginInstance

).as_mut() { plugin_instance } else { return lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN; }; //build ref to response data from raw pointer let response_data = ptr::read_unaligned(body as *const mem::ManuallyDrop<

::ResponseData>); let response_data = mem::ManuallyDrop::into_inner(response_data); if size as usize != mem::size_of_val(&response_data) { return lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN; } let (instance, features) = plugin_instance.audio_class_handle(); match instance.work_response(response_data, features) { Ok(()) => lv2_sys::LV2_Worker_Status_LV2_WORKER_SUCCESS, Err(WorkerError::Unknown) => lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN, Err(WorkerError::NoSpace) => lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_NO_SPACE, } } /// Extern unsafe version of `end_run` method actually called by the host unsafe extern "C" fn extern_end_run(handle: lv2_sys::LV2_Handle) -> lv2_sys::LV2_Worker_Status { if let Some(plugin_instance) = (handle as *mut PluginInstance

).as_mut() { let (instance, features) = plugin_instance.audio_class_handle(); match instance.end_run(features) { Ok(()) => lv2_sys::LV2_Worker_Status_LV2_WORKER_SUCCESS, Err(WorkerError::Unknown) => lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN, Err(WorkerError::NoSpace) => lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_NO_SPACE, } } else { lv2_sys::LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN } } } // Implementing the trait that contains the interface. impl ExtensionDescriptor for WorkerDescriptor

{ type ExtensionInterface = lv2_sys::LV2_Worker_Interface; const INTERFACE: &'static lv2_sys::LV2_Worker_Interface = &lv2_sys::LV2_Worker_Interface { work: Some(Self::extern_work), work_response: Some(Self::extern_work_response), end_run: Some(Self::extern_end_run), }; } #[cfg(test)] mod tests { use super::*; use lv2_core::prelude::*; use lv2_sys::*; use std::fmt; use std::mem; use std::ops; use std::ptr; // structure to test drooping issue struct HasDrop { drop_count: u32, drop_limit: u32, } impl HasDrop { fn new(val: u32) -> Self { Self { drop_count: 0, drop_limit: val, } } } impl ops::Drop for HasDrop { fn drop(&mut self) { if self.drop_count >= self.drop_limit { panic!("Dropped more than {} time", self.drop_limit); } else { self.drop_count += 1; } } } impl fmt::Display for HasDrop { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "HasDrop variable") } } #[derive(PortCollection)] struct Ports {} struct TestDropWorker; // URI identifier unsafe impl<'a> UriBound for TestDropWorker { const URI: &'static [u8] = b"not relevant\0"; } impl Plugin for TestDropWorker { type Ports = Ports; type InitFeatures = (); type AudioFeatures = (); fn new(_plugin_info: &PluginInfo, _features: &mut Self::InitFeatures) -> Option { Some(Self {}) } fn run(&mut self, _ports: &mut Ports, _features: &mut Self::InitFeatures, _: u32) {} } impl Worker for TestDropWorker { type WorkData = HasDrop; type ResponseData = HasDrop; fn work( _response_handler: &ResponseHandler, _data: HasDrop, ) -> Result<(), WorkerError> { Ok(()) } fn work_response( &mut self, _data: HasDrop, _features: &mut Self::AudioFeatures, ) -> Result<(), WorkerError> { Ok(()) } } extern "C" fn extern_schedule( _handle: LV2_Worker_Schedule_Handle, _size: u32, _data: *const c_void, ) -> LV2_Worker_Status { LV2_Worker_Status_LV2_WORKER_SUCCESS } extern "C" fn faulty_schedule( _handle: LV2_Worker_Schedule_Handle, _size: u32, _data: *const c_void, ) -> LV2_Worker_Status { LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN } extern "C" fn extern_respond( _handle: LV2_Worker_Respond_Handle, _size: u32, _data: *const c_void, ) -> LV2_Worker_Status { LV2_Worker_Status_LV2_WORKER_SUCCESS } extern "C" fn faulty_respond( _handle: LV2_Worker_Respond_Handle, _size: u32, _data: *const c_void, ) -> LV2_Worker_Status { LV2_Worker_Status_LV2_WORKER_ERR_UNKNOWN } #[test] fn schedule_must_not_drop() { let hd = HasDrop::new(0); let internal = lv2_sys::LV2_Worker_Schedule { handle: ptr::null_mut(), schedule_work: Some(extern_schedule), }; let schedule = Schedule { internal: &internal, phantom: PhantomData::<*const TestDropWorker>, }; let _ = schedule.schedule_work(hd); } #[test] #[should_panic(expected = "Dropped")] fn schedule_must_enable_drop_on_error() { let hd = HasDrop::new(0); let internal = lv2_sys::LV2_Worker_Schedule { handle: ptr::null_mut(), schedule_work: Some(faulty_schedule), }; let schedule = Schedule { internal: &internal, phantom: PhantomData::<*const TestDropWorker>, }; let _ = schedule.schedule_work(hd); } #[test] fn respond_must_not_drop() { let hd = HasDrop::new(0); let respond = ResponseHandler { response_function: Some(extern_respond), respond_handle: ptr::null_mut(), phantom: PhantomData::, }; let _ = respond.respond(hd); } #[test] #[should_panic(expected = "Dropped")] fn respond_must_enable_drop_on_error() { let hd = HasDrop::new(0); let respond = ResponseHandler { response_function: Some(faulty_respond), respond_handle: ptr::null_mut(), phantom: PhantomData::, }; let _ = respond.respond(hd); } #[test] #[should_panic(expected = "Dropped")] fn extern_work_should_drop() { let hd = mem::ManuallyDrop::new(HasDrop::new(0)); let ptr_hd = &hd as *const _ as *const c_void; let size = mem::size_of_val(&hd) as u32; let mut tdw = TestDropWorker {}; let ptr_tdw = &mut tdw as *mut _ as *mut c_void; //trash trick i use Plugin ptr insteas of Pluginstance ptr unsafe { WorkerDescriptor::::extern_work( ptr_tdw, Some(extern_respond), ptr::null_mut(), size, ptr_hd, ); } } #[test] fn extern_work_should_not_drop_twice() { let hd = mem::ManuallyDrop::new(HasDrop::new(1)); let ptr_hd = &hd as *const _ as *const c_void; let size = mem::size_of_val(&hd) as u32; let mut tdw = TestDropWorker {}; let ptr_tdw = &mut tdw as *mut _ as *mut c_void; //trash trick i use Plugin ptr insteas of Pluginstance ptr unsafe { WorkerDescriptor::::extern_work( ptr_tdw, Some(extern_respond), ptr::null_mut(), size, ptr_hd, ); } } #[test] #[should_panic(expected = "Dropped")] fn extern_work_response_should_drop() { let hd = mem::ManuallyDrop::new(HasDrop::new(0)); let ptr_hd = &hd as *const _ as *const c_void; let size = mem::size_of_val(&hd) as u32; let mut tdw = TestDropWorker {}; let ptr_tdw = &mut tdw as *mut _ as *mut c_void; //trash trick i use Plugin ptr insteas of Pluginstance ptr unsafe { WorkerDescriptor::::extern_work_response(ptr_tdw, size, ptr_hd); } } #[test] fn extern_work_response_should_not_drop_twice() { let hd = mem::ManuallyDrop::new(HasDrop::new(1)); let ptr_hd = &hd as *const _ as *const c_void; let size = mem::size_of_val(&hd) as u32; let mut tdw = TestDropWorker {}; let ptr_tdw = &mut tdw as *mut _ as *mut c_void; //trash trick i use Plugin ptr insteas of Pluginstance ptr unsafe { WorkerDescriptor::::extern_work_response(ptr_tdw, size, ptr_hd); } } }