You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

lib.rs 17 kB

9 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. // Copyright (c) 2019-2022, The rav1e contributors. All rights reserved
  2. //
  3. // This source code is subject to the terms of the BSD 2 Clause License and
  4. // the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
  5. // was not distributed with this source code in the LICENSE file, you can
  6. // obtain it at www.aomedia.org/license/software. If the Alliance for Open
  7. // Media Patent License 1.0 was not distributed with this source code in the
  8. // PATENTS file, you can obtain it at www.aomedia.org/license/patent.
  9. use std::env::var;
  10. use dora_node_api::arrow::array::{UInt16Array, UInt8Array};
  11. use dora_node_api::dora_core::config::DataId;
  12. use dora_node_api::{DoraNode, Event, IntoArrow, Metadata, Parameter};
  13. use eyre::{Context as EyreContext, Result};
  14. use log::warn;
  15. use rav1e::color::{ColorDescription, MatrixCoefficients};
  16. // Encode the same tiny blank frame 30 times
  17. use rav1e::config::SpeedSettings;
  18. use rav1e::*;
  19. pub fn fill_zeros_toward_center_y_plane_in_place(y: &mut [u16], width: usize, height: usize) {
  20. assert_eq!(y.len(), width * height);
  21. for row in 0..height {
  22. let row_start = row * width;
  23. let center = width / 2;
  24. // --- Fill left half (left to center)
  25. let mut last = 0u16;
  26. for col in 0..center {
  27. let idx = row_start + col;
  28. if y[idx] == 0 {
  29. y[idx] = last;
  30. } else {
  31. last = y[idx];
  32. }
  33. }
  34. // --- Fill right half (right to center)
  35. last = 0u16;
  36. for col in (center..width).rev() {
  37. let idx = row_start + col;
  38. if y[idx] == 0 {
  39. y[idx] = last;
  40. } else {
  41. last = y[idx];
  42. }
  43. }
  44. }
  45. }
  46. fn bgr8_to_yuv420(bgr_data: Vec<u8>, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
  47. let mut y_plane = vec![0; width * height];
  48. let mut u_plane = vec![0; (width / 2) * (height / 2)];
  49. let mut v_plane = vec![0; (width / 2) * (height / 2)];
  50. for y in 0..height {
  51. for x in 0..width {
  52. let bgr_index = (y * width + x) * 3;
  53. let b = bgr_data[bgr_index] as f32;
  54. let g = bgr_data[bgr_index + 1] as f32;
  55. let r = bgr_data[bgr_index + 2] as f32;
  56. // Corrected YUV conversion formulas
  57. let y_value = (0.299 * r + 0.587 * g + 0.114 * b).clamp(0.0, 255.0);
  58. let u_value = (-0.14713 * r - 0.28886 * g + 0.436 * b + 128.0).clamp(0.0, 255.0);
  59. let v_value = (0.615 * r - 0.51499 * g - 0.10001 * b + 128.0).clamp(0.0, 255.0);
  60. let y_index = y * width + x;
  61. y_plane[y_index] = y_value.round() as u8;
  62. if x % 2 == 0 && y % 2 == 0 {
  63. let uv_index = (y / 2) * (width / 2) + (x / 2);
  64. u_plane[uv_index] = u_value.round() as u8;
  65. v_plane[uv_index] = v_value.round() as u8;
  66. }
  67. }
  68. }
  69. (y_plane, u_plane, v_plane)
  70. }
  71. fn get_yuv_planes(buffer: &[u8], width: usize, height: usize) -> (&[u8], &[u8], &[u8]) {
  72. // Calculate sizes of Y, U, and V planes for YUV420 format
  73. let y_size = width * height; // Y has full resolution
  74. let uv_width = width / 2; // U and V are subsampled by 2 in both dimensions
  75. let uv_height = height / 2; // U and V are subsampled by 2 in both dimensions
  76. let uv_size = uv_width * uv_height; // Size for U and V planes
  77. // Ensure the buffer has the correct size
  78. // if buffer.len() != y_size + 2 * uv_size {
  79. // panic!("Invalid buffer size for the given width and height!");
  80. // }
  81. // Extract Y, U, and V planes
  82. let y_plane = &buffer[0..y_size]; //.to_vec();
  83. let u_plane = &buffer[y_size..y_size + uv_size]; //.to_vec();
  84. let v_plane = &buffer[y_size + uv_size..]; //.to_vec();
  85. (y_plane, u_plane, v_plane)
  86. }
  87. fn send_yuv(
  88. y: &[u8],
  89. u: &[u8],
  90. v: &[u8],
  91. enc: EncoderConfig,
  92. width: usize,
  93. height: usize,
  94. node: &mut DoraNode,
  95. id: DataId,
  96. metadata: &mut Metadata,
  97. output_enconding: &str,
  98. ) -> () {
  99. // Create a new Arrow array for the YUV420 data
  100. let cfg = Config::new().with_encoder_config(enc.clone());
  101. let mut ctx: Context<u8> = cfg.new_context().unwrap();
  102. let mut f = ctx.new_frame();
  103. let xdec = f.planes[0].cfg.xdec;
  104. let stride = (width + xdec) >> xdec;
  105. f.planes[0].copy_from_raw_u8(&y, stride, 1);
  106. let xdec = f.planes[1].cfg.xdec;
  107. let stride = (width + xdec) >> xdec;
  108. f.planes[1].copy_from_raw_u8(&u, stride, 1);
  109. let xdec = f.planes[2].cfg.xdec;
  110. let stride = (width + xdec) >> xdec;
  111. f.planes[2].copy_from_raw_u8(&v, stride, 1);
  112. match ctx.send_frame(f) {
  113. Ok(_) => {}
  114. Err(e) => match e {
  115. EncoderStatus::EnoughData => {
  116. warn!("Unable to send frame ");
  117. }
  118. _ => {
  119. warn!("Unable to send frame ");
  120. }
  121. },
  122. }
  123. ctx.flush();
  124. match ctx.receive_packet() {
  125. Ok(pkt) => match output_enconding {
  126. "avif" => {
  127. let data = pkt.data.clone();
  128. metadata.parameters.insert(
  129. "encoding".to_string(),
  130. Parameter::String("avif".to_string()),
  131. );
  132. let matrix_coefficients = if let Some(desc) = enc.color_description {
  133. desc.matrix_coefficients
  134. } else {
  135. MatrixCoefficients::BT709
  136. };
  137. let data = avif_serialize::Aviffy::new()
  138. .set_chroma_subsampling((true, true))
  139. .set_seq_profile(0)
  140. .matrix_coefficients(match matrix_coefficients {
  141. MatrixCoefficients::Identity => {
  142. avif_serialize::constants::MatrixCoefficients::Rgb
  143. }
  144. MatrixCoefficients::BT709 => {
  145. avif_serialize::constants::MatrixCoefficients::Bt709
  146. }
  147. MatrixCoefficients::Unspecified => {
  148. avif_serialize::constants::MatrixCoefficients::Unspecified
  149. }
  150. MatrixCoefficients::BT601 => {
  151. avif_serialize::constants::MatrixCoefficients::Bt601
  152. }
  153. MatrixCoefficients::YCgCo => {
  154. avif_serialize::constants::MatrixCoefficients::Ycgco
  155. }
  156. MatrixCoefficients::BT2020NCL => {
  157. avif_serialize::constants::MatrixCoefficients::Bt2020Ncl
  158. }
  159. MatrixCoefficients::BT2020CL => {
  160. avif_serialize::constants::MatrixCoefficients::Bt2020Cl
  161. }
  162. _ => {
  163. warn!("color matrix coefficients");
  164. avif_serialize::constants::MatrixCoefficients::Rgb
  165. }
  166. })
  167. .to_vec(
  168. &data,
  169. None,
  170. width as u32,
  171. height as u32,
  172. enc.bit_depth as u8,
  173. );
  174. let arrow = data.into_arrow();
  175. node.send_output(id, metadata.parameters.clone(), arrow)
  176. .context("could not send output")
  177. .unwrap();
  178. }
  179. _ => {
  180. metadata
  181. .parameters
  182. .insert("encoding".to_string(), Parameter::String("av1".to_string()));
  183. metadata
  184. .parameters
  185. .insert("height".to_string(), Parameter::Integer(enc.height as i64));
  186. metadata
  187. .parameters
  188. .insert("width".to_string(), Parameter::Integer(enc.width as i64));
  189. let data = pkt.data;
  190. let arrow = data.into_arrow();
  191. node.send_output(id, metadata.parameters.clone(), arrow)
  192. .context("could not send output")
  193. .unwrap();
  194. }
  195. },
  196. Err(e) => match e {
  197. EncoderStatus::LimitReached => {}
  198. EncoderStatus::Encoded => {}
  199. EncoderStatus::NeedMoreData => {}
  200. _ => {
  201. panic!("Unable to receive packet",);
  202. }
  203. },
  204. }
  205. }
  206. pub fn lib_main() -> Result<()> {
  207. let mut height = std::env::var("IMAGE_HEIGHT")
  208. .unwrap_or_else(|_| "480".to_string())
  209. .parse()
  210. .unwrap();
  211. let mut width = std::env::var("IMAGE_WIDTH")
  212. .unwrap_or_else(|_| "640".to_string())
  213. .parse()
  214. .unwrap();
  215. let speed = var("RAV1E_SPEED").map(|s| s.parse().unwrap()).unwrap_or(10);
  216. let output_encoding = var("ENCODING").unwrap_or("av1".to_string());
  217. let mut enc = EncoderConfig {
  218. width,
  219. height,
  220. speed_settings: SpeedSettings::from_preset(speed),
  221. chroma_sampling: color::ChromaSampling::Cs420,
  222. color_description: Some(ColorDescription {
  223. matrix_coefficients: MatrixCoefficients::BT709,
  224. transfer_characteristics: color::TransferCharacteristics::BT709,
  225. color_primaries: color::ColorPrimaries::BT709,
  226. }),
  227. low_latency: true,
  228. ..Default::default()
  229. };
  230. let cfg = Config::new().with_encoder_config(enc.clone());
  231. cfg.validate()?;
  232. let (mut node, mut events) =
  233. DoraNode::init_from_env().context("Could not initialize dora node")?;
  234. loop {
  235. match events.recv() {
  236. Some(Event::Input {
  237. id,
  238. data,
  239. mut metadata,
  240. }) => {
  241. if let Some(Parameter::Integer(h)) = metadata.parameters.get("height") {
  242. height = *h as usize;
  243. };
  244. if let Some(Parameter::Integer(w)) = metadata.parameters.get("width") {
  245. width = *w as usize;
  246. };
  247. let encoding = if let Some(Parameter::String(encoding)) =
  248. metadata.parameters.get("encoding")
  249. {
  250. encoding
  251. } else {
  252. "bgr8"
  253. };
  254. enc = EncoderConfig {
  255. width,
  256. height,
  257. speed_settings: SpeedSettings::from_preset(speed),
  258. low_latency: true,
  259. chroma_sampling: color::ChromaSampling::Cs420,
  260. color_description: Some(ColorDescription {
  261. matrix_coefficients: MatrixCoefficients::BT709,
  262. transfer_characteristics: color::TransferCharacteristics::BT709,
  263. color_primaries: color::ColorPrimaries::BT709,
  264. }),
  265. ..Default::default()
  266. };
  267. match encoding {
  268. "mono16" => {
  269. enc.bit_depth = 12;
  270. enc.chroma_sampling = color::ChromaSampling::Cs400;
  271. }
  272. _ => {}
  273. }
  274. if encoding == "bgr8" {
  275. let buffer: &UInt8Array = data.as_any().downcast_ref().unwrap();
  276. let buffer: Vec<u8> = buffer.values().to_vec();
  277. let (y, u, v) = bgr8_to_yuv420(buffer, width, height);
  278. send_yuv(
  279. &y,
  280. &u,
  281. &v,
  282. enc,
  283. width,
  284. height,
  285. &mut node,
  286. id,
  287. &mut metadata,
  288. &output_encoding,
  289. );
  290. } else if encoding == "yuv420" {
  291. let buffer: &UInt8Array = data.as_any().downcast_ref().unwrap();
  292. let buffer = buffer.values(); //.to_vec();
  293. let (y, u, v) = get_yuv_planes(buffer, width, height);
  294. send_yuv(
  295. &y,
  296. &u,
  297. &v,
  298. enc,
  299. width,
  300. height,
  301. &mut node,
  302. id,
  303. &mut metadata,
  304. &output_encoding,
  305. );
  306. } else if encoding == "mono16" || encoding == "z16" {
  307. let buffer: &UInt16Array = data.as_any().downcast_ref().unwrap();
  308. let mut buffer = buffer.values().to_vec();
  309. if std::env::var("FILL_ZEROS")
  310. .map(|s| s != "false")
  311. .unwrap_or(true)
  312. {
  313. fill_zeros_toward_center_y_plane_in_place(&mut buffer, width, height);
  314. }
  315. let bytes: &[u8] = &bytemuck::cast_slice(&buffer);
  316. let cfg = Config::new().with_encoder_config(enc.clone());
  317. let mut ctx: Context<u16> = cfg.new_context().unwrap();
  318. let mut f = ctx.new_frame();
  319. let xdec = f.planes[0].cfg.xdec;
  320. let stride = (width + xdec) >> xdec;
  321. // Multiply by 2 the stride as it is going to be width * 2 as we're converting 16-bit to 2*8-bit.
  322. f.planes[0].copy_from_raw_u8(bytes, stride * 2, 2);
  323. match ctx.send_frame(f) {
  324. Ok(_) => {}
  325. Err(e) => match e {
  326. EncoderStatus::EnoughData => {
  327. warn!("Unable to send frame ");
  328. }
  329. _ => {
  330. warn!("Unable to send frame ");
  331. }
  332. },
  333. }
  334. ctx.flush();
  335. match ctx.receive_packet() {
  336. Ok(pkt) => {
  337. let data = pkt.data;
  338. match output_encoding.as_str() {
  339. "avif" => {
  340. warn!("avif encoding not supported for mono16");
  341. }
  342. _ => {
  343. metadata.parameters.insert(
  344. "encoding".to_string(),
  345. Parameter::String("av1".to_string()),
  346. );
  347. let arrow = data.into_arrow();
  348. node.send_output(id, metadata.parameters, arrow)
  349. .context("could not send output")
  350. .unwrap();
  351. }
  352. }
  353. }
  354. Err(e) => match e {
  355. EncoderStatus::LimitReached => {}
  356. EncoderStatus::Encoded => {}
  357. EncoderStatus::NeedMoreData => {}
  358. _ => {
  359. panic!("Unable to receive packet",);
  360. }
  361. },
  362. }
  363. } else if encoding == "rgb8" {
  364. let buffer: &UInt8Array = data.as_any().downcast_ref().unwrap();
  365. let buffer: Vec<u8> = buffer.values().to_vec();
  366. let buffer: Vec<u8> =
  367. buffer.chunks(3).flat_map(|x| [x[2], x[1], x[0]]).collect();
  368. let (y, u, v) = bgr8_to_yuv420(buffer, width, height);
  369. send_yuv(
  370. &y,
  371. &u,
  372. &v,
  373. enc,
  374. width,
  375. height,
  376. &mut node,
  377. id,
  378. &mut metadata,
  379. &output_encoding,
  380. );
  381. } else {
  382. unimplemented!("We haven't worked on additional encodings.");
  383. }
  384. }
  385. Some(Event::Error(_e)) => {
  386. continue;
  387. }
  388. _ => break,
  389. };
  390. }
  391. Ok(())
  392. }
  393. #[cfg(feature = "python")]
  394. use pyo3::{
  395. pyfunction, pymodule,
  396. types::{PyModule, PyModuleMethods},
  397. wrap_pyfunction, Bound, PyResult, Python,
  398. };
  399. #[cfg(feature = "python")]
  400. #[pyfunction]
  401. fn py_main(_py: Python) -> eyre::Result<()> {
  402. lib_main()
  403. }
  404. #[cfg(feature = "python")]
  405. #[pymodule]
  406. fn dora_rav1e(_py: Python, m: Bound<'_, PyModule>) -> PyResult<()> {
  407. m.add_function(wrap_pyfunction!(py_main, &m)?)?;
  408. m.add("__version__", env!("CARGO_PKG_VERSION"))?;
  409. Ok(())
  410. }