main.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
  5. use http::{header::*, response::Builder as ResponseBuilder, status::StatusCode};
  6. use http_range::HttpRange;
  7. use std::sync::{Arc, Mutex};
  8. use std::{
  9. io::{Read, Seek, SeekFrom, Write},
  10. path::PathBuf,
  11. process::{Command, Stdio},
  12. };
  13. fn main() {
  14. let video_file = PathBuf::from("test_video.mp4");
  15. let video_url =
  16. "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
  17. if !video_file.exists() {
  18. // Downloading with curl this saves us from adding
  19. // a Rust HTTP client dependency.
  20. println!("Downloading {video_url}");
  21. let status = Command::new("curl")
  22. .arg("-L")
  23. .arg("-o")
  24. .arg(&video_file)
  25. .arg(video_url)
  26. .stdout(Stdio::inherit())
  27. .stderr(Stdio::inherit())
  28. .output()
  29. .unwrap();
  30. assert!(status.status.success());
  31. assert!(video_file.exists());
  32. }
  33. // NOTE: for production use `rand` crate to generate a random boundary
  34. let boundary_id = Arc::new(Mutex::new(0));
  35. tauri::Builder::default()
  36. .invoke_handler(tauri::generate_handler![video_uri])
  37. .register_asynchronous_uri_scheme_protocol("stream", move |_app, request, responder| {
  38. match get_stream_response(request, &boundary_id) {
  39. Ok(http_response) => responder.respond(http_response),
  40. Err(e) => responder.respond(
  41. ResponseBuilder::new()
  42. .status(StatusCode::BAD_REQUEST)
  43. .header(CONTENT_TYPE, "text/plain")
  44. .body(e.to_string().as_bytes().to_vec())
  45. .unwrap(),
  46. ),
  47. }
  48. })
  49. .run(tauri::generate_context!(
  50. "../../examples/streaming/tauri.conf.json"
  51. ))
  52. .expect("error while running tauri application");
  53. }
  54. // returns the scheme and the path of the video file
  55. // we're using this just to allow using the custom `stream` protocol or tauri built-in `asset` protocol
  56. #[tauri::command]
  57. fn video_uri() -> (&'static str, std::path::PathBuf) {
  58. #[cfg(feature = "protocol-asset")]
  59. {
  60. let mut path = std::env::current_dir().unwrap();
  61. path.push("test_video.mp4");
  62. ("asset", path)
  63. }
  64. #[cfg(not(feature = "protocol-asset"))]
  65. ("stream", "test_video.mp4".into())
  66. }
  67. fn get_stream_response(
  68. request: http::Request<Vec<u8>>,
  69. boundary_id: &Arc<Mutex<i32>>,
  70. ) -> Result<http::Response<Vec<u8>>, Box<dyn std::error::Error>> {
  71. // skip leading `/`
  72. let path = percent_encoding::percent_decode(request.uri().path()[1..].as_bytes())
  73. .decode_utf8_lossy()
  74. .to_string();
  75. if path != "test_video.mp4" {
  76. // return error 404 if it's not our video
  77. return Ok(ResponseBuilder::new().status(404).body(Vec::new())?);
  78. }
  79. let mut file = std::fs::File::open(&path)?;
  80. // get file length
  81. let len = {
  82. let old_pos = file.stream_position()?;
  83. let len = file.seek(SeekFrom::End(0))?;
  84. file.seek(SeekFrom::Start(old_pos))?;
  85. len
  86. };
  87. let mut resp = ResponseBuilder::new().header(CONTENT_TYPE, "video/mp4");
  88. // if the webview sent a range header, we need to send a 206 in return
  89. // Actually only macOS and Windows are supported. Linux will ALWAYS return empty headers.
  90. let http_response = if let Some(range_header) = request.headers().get("range") {
  91. let not_satisfiable = || {
  92. ResponseBuilder::new()
  93. .status(StatusCode::RANGE_NOT_SATISFIABLE)
  94. .header(CONTENT_RANGE, format!("bytes */{len}"))
  95. .body(vec![])
  96. };
  97. // parse range header
  98. let ranges = if let Ok(ranges) = HttpRange::parse(range_header.to_str()?, len) {
  99. ranges
  100. .iter()
  101. // map the output back to spec range <start-end>, example: 0-499
  102. .map(|r| (r.start, r.start + r.length - 1))
  103. .collect::<Vec<_>>()
  104. } else {
  105. return Ok(not_satisfiable()?);
  106. };
  107. /// The Maximum bytes we send in one range
  108. const MAX_LEN: u64 = 1000 * 1024;
  109. if ranges.len() == 1 {
  110. let &(start, mut end) = ranges.first().unwrap();
  111. // check if a range is not satisfiable
  112. //
  113. // this should be already taken care of by HttpRange::parse
  114. // but checking here again for extra assurance
  115. if start >= len || end >= len || end < start {
  116. return Ok(not_satisfiable()?);
  117. }
  118. // adjust end byte for MAX_LEN
  119. end = start + (end - start).min(len - start).min(MAX_LEN - 1);
  120. // calculate number of bytes needed to be read
  121. let bytes_to_read = end + 1 - start;
  122. // allocate a buf with a suitable capacity
  123. let mut buf = Vec::with_capacity(bytes_to_read as usize);
  124. // seek the file to the starting byte
  125. file.seek(SeekFrom::Start(start))?;
  126. // read the needed bytes
  127. file.take(bytes_to_read).read_to_end(&mut buf)?;
  128. resp = resp.header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}"));
  129. resp = resp.header(CONTENT_LENGTH, end + 1 - start);
  130. resp = resp.status(StatusCode::PARTIAL_CONTENT);
  131. resp.body(buf)
  132. } else {
  133. let mut buf = Vec::new();
  134. let ranges = ranges
  135. .iter()
  136. .filter_map(|&(start, mut end)| {
  137. // filter out unsatisfiable ranges
  138. //
  139. // this should be already taken care of by HttpRange::parse
  140. // but checking here again for extra assurance
  141. if start >= len || end >= len || end < start {
  142. None
  143. } else {
  144. // adjust end byte for MAX_LEN
  145. end = start + (end - start).min(len - start).min(MAX_LEN - 1);
  146. Some((start, end))
  147. }
  148. })
  149. .collect::<Vec<_>>();
  150. let mut id = boundary_id.lock().unwrap();
  151. *id += 1;
  152. let boundary = format!("sadasq2e{id}");
  153. let boundary_sep = format!("\r\n--{boundary}\r\n");
  154. let boundary_closer = format!("\r\n--{boundary}\r\n");
  155. resp = resp.header(
  156. CONTENT_TYPE,
  157. format!("multipart/byteranges; boundary={boundary}"),
  158. );
  159. for (end, start) in ranges {
  160. // a new range is being written, write the range boundary
  161. buf.write_all(boundary_sep.as_bytes())?;
  162. // write the needed headers `Content-Type` and `Content-Range`
  163. buf.write_all(format!("{CONTENT_TYPE}: video/mp4\r\n").as_bytes())?;
  164. buf.write_all(format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes())?;
  165. // write the separator to indicate the start of the range body
  166. buf.write_all("\r\n".as_bytes())?;
  167. // calculate number of bytes needed to be read
  168. let bytes_to_read = end + 1 - start;
  169. let mut local_buf = vec![0_u8; bytes_to_read as usize];
  170. file.seek(SeekFrom::Start(start))?;
  171. file.read_exact(&mut local_buf)?;
  172. buf.extend_from_slice(&local_buf);
  173. }
  174. // all ranges have been written, write the closing boundary
  175. buf.write_all(boundary_closer.as_bytes())?;
  176. resp.body(buf)
  177. }
  178. } else {
  179. resp = resp.header(CONTENT_LENGTH, len);
  180. let mut buf = Vec::with_capacity(len as usize);
  181. file.read_to_end(&mut buf)?;
  182. resp.body(buf)
  183. };
  184. http_response.map_err(Into::into)
  185. }