main.rs 6.9 KB

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