MCPcopy Create free account
hub / github.com/RustCV/RustCV / stream_handler

Function stream_handler

rustcv-backend-v4l2/examples/web_streaming.rs:142–180  ·  view source on GitHub ↗

视频流处理函数 (MJPEG)

(State(state): State<AppState>)

Source from the content-addressed store, hash-verified

140#[cfg(target_os = "linux")]
141/// 视频流处理函数 (MJPEG)
142async fn stream_handler(State(state): State<AppState>) -> Response {
143 // 1. 创建订阅流
144 let rx = state.tx.subscribe();
145
146 // 2. 构造 MJPEG 数据流
147 let stream = tokio_stream::wrappers::BroadcastStream::new(rx)
148 .filter_map(|result| async move {
149 // 过滤掉 Lagged 错误
150 result.ok()
151 })
152 .map(|bytes| {
153 // 构造 MJPEG 帧
154 let header = format!(
155 "--frame\r\nContent-Type: image/jpeg\r\nContent-Length: {}\r\n\r\n",
156 bytes.len()
157 );
158
159 let mut full_frame = Vec::with_capacity(header.len() + bytes.len() + 2);
160 full_frame.extend_from_slice(header.as_bytes());
161 full_frame.extend_from_slice(&bytes);
162 full_frame.extend_from_slice(b"\r\n");
163
164 Ok::<_, std::io::Error>(Bytes::from(full_frame))
165 });
166
167 // 3. 将流转换为 Body
168 let body = Body::from_stream(stream);
169
170 // 4. 将 Body 转换为 Response
171 let mut response = body.into_response();
172
173 // 5. 【修正】直接在 response 上修改 Header,而不是用 .map()
174 response.headers_mut().insert(
175 "Content-Type",
176 "multipart/x-mixed-replace; boundary=frame".parse().unwrap(),
177 );
178
179 response
180}
181
182#[cfg(target_os = "linux")]
183/// 辅助函数:YUYV -> JPEG

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected