Visual Studio Code, rebuilt in Rust
Rust
feat(media-preview): read media codecs for the player's warnings
rokarturde03cd699125
diff --git a/native/crates/app/src/workbench/media_preview.rs b/native/crates/app/src/workbench/media_preview.rsindex fb5269f328b..8fc7462b714 100644--- a/native/crates/app/src/workbench/media_preview.rs+++ b/native/crates/app/src/workbench/media_preview.rs@@ -7,6 +7,8 @@ use std::time::{SystemTime, UNIX_EPOCH};use gpui::{Context, Window};use serde_json::{Value, json};+mod codecs;+use super::Workbench;use super::custom_editors::{Contribution, CustomEditor, RANK_BUILTIN};use super::webview_panels::{WEBVIEW_PANEL_SCHEME, WebviewPanel};@@ -153,16 +155,30 @@ impl Workbench {panel.html = page;cx.notify();}- // shortcut: no codec or WebM type answers, mediaCodecs.ts (reading the container's tracks) is not ported;- // the page then warns of no codec and plays what WebKit plays.- "get-codecs" => {}- "get-webm-type" => {- if let Some(webview) = &mut panel.webview {- webview.send("message", json!({ "message": { "type": "webm-type" }, "buffers": [] }));- }+ request @ ("get-codecs" | "get-webm-type") => {+ let (request, kind, path, handle) = (request.to_owned(), media.kind, media.path.clone(), handle.to_owned());+ cx.spawn(async move |workbench, cx| {+ let info = cx.background_executor().spawn({+ let path = path.clone();+ async move { codecs::read_file_media_info(&path) }+ })+ .await;+ let message = match request.as_str() {+ "get-codecs" => codecs_message(kind, &path, info),+ _ => Some(webm_type_message(info)),+ };+ let _ = workbench.update(cx, |workbench, _| {+ if let Some(message) = message+ && let Some(webview) = workbench.webview_panel_mut(&handle).and_then(|panel| panel.webview.as_mut())+ {+ webview.send("message", json!({ "message": message, "buffers": [] }));+ }+ });+ })+ .detach();}"reopen-as-text" => drop(self.reopen_active_editor_with(Some("default".into()), window, cx)),- "open-externally" => {+ "open-externally" if can_open_externally(&media.path) => {let path = media.path.clone();cx.open_with_system(&path);}@@ -267,6 +283,66 @@ impl MediaPreview {}}+/// mediaPlayerEditorInput.ts `_postCodecs`: the video (of a video preview) and audio codecs as MIME types, with the+/// warning the page shows when it can play none of a kind; None when the file has no such tracks.+fn codecs_message(kind: MediaKind, path: &Path, info: Option<codecs::MediaInfo>) -> Option<Value> {+ let info = info?;+ let preview_kind = if kind == MediaKind::Audio { "audio" } else { "video" };+ let open_externally: Vec<Value> = match can_open_externally(path) {+ true => vec![json!({ "label": "Open File", "message": "open-externally" })],+ false => Vec::new(),+ };+ let codecs = |track_kind: &str| {+ let tracks: Vec<_> = info.tracks.iter().filter(|track| track.kind == track_kind).collect();+ let first = tracks.first()?;+ let mut actions = open_externally.clone();+ // Only a file whose own kind of track cannot play fails to load.+ if track_kind == preview_kind {+ actions.push(json!({ "label": OPEN_IN_TEXT_EDITOR, "message": "reopen-as-text" }));+ }+ let mime_types: Vec<String> = tracks.iter().map(|track| format!("{track_kind}/{}; codecs=\"{}\"", info.container, track.codec)).collect();+ Some(json!({ "mimeTypes": mime_types, "warning": unsupported_codec_warning(preview_kind, first), "actions": actions }))+ };+ let video = if kind == MediaKind::Video { codecs("video") } else { None };+ let audio = codecs("audio");+ if video.is_none() && audio.is_none() {+ return None;+ }+ Some(json!({ "type": "codecs", "video": video, "audio": audio }))+}++/// mediaPlayerEditorInput.ts `_getUnsupportedCodecWarning`.+fn unsupported_codec_warning(preview_kind: &str, track: &codecs::Track) -> String {+ let (named, unnamed) = match (track.kind, preview_kind) {+ ("video", _) => ("This video uses the {0} codec, which can't be played in the video preview.", "This video uses a codec that can't be played in the video preview."),+ (_, "audio") => ("This audio file uses the {0} codec, which can't be played in the audio preview.", "This audio file uses a codec that can't be played in the audio preview."),+ _ => ("This video's audio uses the {0} codec, which can't be played in the video preview.", "This video's audio uses a codec that can't be played in the video preview."),+ };+ match track.name {+ Some(name) => named.replace("{0}", name),+ None => unnamed.to_owned(),+ }+}++/// mediaPlayerEditorInput.ts `_postWebmType`: a WebM file's type with the codecs of all its tracks, for Media Source+/// Extensions.+fn webm_type_message(info: Option<codecs::MediaInfo>) -> Value {+ let mut codecs: Vec<String> = Vec::new();+ for track in info.iter().filter(|info| info.container == "webm").flat_map(|info| &info.tracks) {+ if !codecs.contains(&track.codec) {+ codecs.push(track.codec.clone());+ }+ }+ let mime_type = (!codecs.is_empty()).then(|| format!("video/webm; codecs=\"{}\"", codecs.join(",")));+ json!({ "type": "webm-type", "mimeType": mime_type })+}++/// mediaPlayerEditorInput.ts `_canOpenExternally`: only files with a media extension, never ones the OS would run.+fn can_open_externally(path: &Path) -> bool {+ let mime_type = crate::webview::mime_type(path);+ mime_type.starts_with("audio/") || mime_type.starts_with("video/")+}+/// mediaPreviewStatusBar.ts `getImageZoomLabel`, None for `fit`.fn zoom_label(scale: Option<f64>) -> String {match scale {@@ -324,6 +400,24 @@ mod tests {assert_eq!(encode_path(Path::new("/a b/c#.png")), "/a%20b/c%23.png");}+ /// mediaPlayerEditorInput.ts `_postCodecs` and `_postWebmType` over the tracks mediaCodecs.ts reads.+ #[test]+ fn answers_the_player_page_with_the_file_s_codecs() {+ let track = |kind, codec: &str, name| codecs::Track { kind, codec: codec.into(), name };+ let info = || Some(codecs::MediaInfo { container: "webm", tracks: vec![track("video", "vp9", Some("VP9")), track("audio", "opus", Some("Opus")), track("audio", "opus", Some("Opus"))] });+ let message = codecs_message(MediaKind::Video, Path::new("/w/a.webm"), info()).unwrap();+ assert_eq!(message["video"]["mimeTypes"], json!(["video/webm; codecs=\"vp9\""]));+ assert_eq!(message["video"]["warning"], "This video uses the VP9 codec, which can't be played in the video preview.");+ assert_eq!(message["video"]["actions"], json!([{ "label": "Open File", "message": "open-externally" }, { "label": "Open in Text Editor", "message": "reopen-as-text" }]));+ assert_eq!(message["audio"]["warning"], "This video's audio uses the Opus codec, which can't be played in the video preview.");+ assert_eq!(message["audio"]["actions"], json!([{ "label": "Open File", "message": "open-externally" }]));+ let audio = codecs_message(MediaKind::Audio, Path::new("/w/a.wav"), Some(codecs::MediaInfo { container: "wav", tracks: vec![track("audio", "17", None)] })).unwrap();+ assert_eq!((audio["video"].clone(), audio["audio"]["warning"].clone()), (Value::Null, json!("This audio file uses a codec that can't be played in the audio preview.")));+ assert_eq!(codecs_message(MediaKind::Video, Path::new("/w/a.mp4"), Some(codecs::MediaInfo { container: "mp4", tracks: vec![] })), None);+ assert_eq!(webm_type_message(info())["mimeType"], "video/webm; codecs=\"vp9,opus\"");+ assert_eq!(webm_type_message(None)["mimeType"], Value::Null);+ }+#[test]fn fills_every_placeholder_of_the_pages() {for kind in [MediaKind::Image, MediaKind::Video, MediaKind::Audio] {diff --git a/native/crates/app/src/workbench/media_preview/codecs.rs b/native/crates/app/src/workbench/media_preview/codecs.rsnew file mode 100644index 00000000000..acc5e9f618d--- /dev/null+++ b/native/crates/app/src/workbench/media_preview/codecs.rs@@ -0,0 +1,560 @@+//! mediaCodecs.ts: the container and the track codecs of an MP4, WebM, Ogg or WAV file, read from the parts of the file+//! that describe them. Browsers drop audio tracks they cannot decode without saying so; the player page warns with these.++use std::collections::HashMap;++const CHUNK_SIZE: u64 = 64 * 1024;+/// Bounds the bytes read to find the codecs.+const MAX_CHUNKS: usize = 32;+/// Bounds the structures visited on each level of a file.+const MAX_ENTRIES: usize = 64;++#[derive(Debug, PartialEq)]+pub struct MediaInfo {+ pub container: &'static str,+ /// Video tracks are read from WebM files only, which play through Media Source Extensions with every codec named.+ pub tracks: Vec<Track>,+}++#[derive(Debug, PartialEq)]+pub struct Track {+ pub kind: &'static str,+ /// The `codecs` parameter of a MIME type, `mp4a.40.2`.+ pub codec: String,+ pub name: Option<&'static str>,+}++/// The read limit was reached or a range could not be read.+struct Unreadable;++/// `readMediaInfo`: None when the file cannot be read or is no supported container. `read_range` reads `length`+/// bytes at `position`, never past `size`.+pub fn read_media_info(size: u64, read_range: impl FnMut(u64, u64) -> std::io::Result<Vec<u8>>) -> Option<MediaInfo> {+ let mut reader = Reader { size, read_range, chunks: HashMap::new() };+ let header = reader.read(0, 12).ok()?;+ if header.len() < 12 {+ return None;+ }+ let (container, tracks) = if ISO_BASE_MEDIA_BOX_TYPES.contains(&ascii(&header, 4, 8).as_str()) {+ ("mp4", read_mp4_tracks(&mut reader))+ } else if u32::from_be_bytes([header[0], header[1], header[2], header[3]]) == EBML_HEADER_ID {+ ("webm", read_webm_tracks(&mut reader))+ } else if ascii(&header, 0, 4) == "OggS" {+ ("ogg", read_ogg_tracks(&mut reader))+ } else if ascii(&header, 0, 4) == "RIFF" && ascii(&header, 8, 12) == "WAVE" {+ ("wav", read_wav_tracks(&mut reader))+ } else {+ return None;+ };+ Some(MediaInfo { container, tracks: tracks.ok()? })+}++/// `readMediaInfo` of a local file, read in ranges.+pub fn read_file_media_info(path: &std::path::Path) -> Option<MediaInfo> {+ use std::io::{Read, Seek, SeekFrom};+ let mut file = std::fs::File::open(path).ok()?;+ let size = file.metadata().ok()?.len();+ read_media_info(size, |position, length| {+ let mut bytes = Vec::new();+ file.seek(SeekFrom::Start(position))?;+ (&mut file).take(length).read_to_end(&mut bytes)?;+ Ok(bytes)+ })+}++/// `ChunkedReader`: the file in cached chunks, so many small structures do not read the same part again.+struct Reader<F> {+ size: u64,+ read_range: F,+ chunks: HashMap<u64, Vec<u8>>,+}++impl<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>> Reader<F> {+ /// `length` bytes, or fewer at the end of the file.+ fn read(&mut self, position: u64, length: u64) -> Result<Vec<u8>, Unreadable> {+ let mut bytes = Vec::new();+ let end = position.saturating_add(length).min(self.size);+ let mut offset = position;+ while offset < end {+ let index = offset / CHUNK_SIZE;+ let chunk = self.chunk(index)?;+ let start = (offset - index * CHUNK_SIZE) as usize;+ let part = chunk.get(start..((end - index * CHUNK_SIZE) as usize).min(chunk.len())).unwrap_or_default();+ // The file may have become shorter since its size was read.+ if part.is_empty() {+ break;+ }+ bytes.extend_from_slice(part);+ offset += part.len() as u64;+ }+ Ok(bytes)+ }++ fn chunk(&mut self, index: u64) -> Result<&Vec<u8>, Unreadable> {+ if !self.chunks.contains_key(&index) {+ if self.chunks.len() >= MAX_CHUNKS {+ return Err(Unreadable);+ }+ let start = index * CHUNK_SIZE;+ let chunk = (self.read_range)(start, CHUNK_SIZE.min(self.size - start)).map_err(|_| Unreadable)?;+ self.chunks.insert(index, chunk);+ }+ Ok(&self.chunks[&index])+ }+}++fn ascii(bytes: &[u8], start: usize, end: usize) -> String {+ bytes.get(start.min(bytes.len())..end.min(bytes.len())).unwrap_or_default().iter().map(|&byte| byte as char).collect()+}++const ISO_BASE_MEDIA_BOX_TYPES: [&str; 6] = ["ftyp", "moov", "mdat", "free", "skip", "wide"];++#[derive(Clone, Copy)]+struct Mp4Box {+ kind: [u8; 4],+ content_start: u64,+ end: u64,+}++/// `readBoxes`: the boxes between `start` and `end`, one `next` at a time.+struct Boxes {+ position: u64,+ end: u64,+ count: usize,+}++impl Boxes {+ fn new(start: u64, end: u64) -> Self {+ Boxes { position: start, end, count: 0 }+ }++ fn next<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(&mut self, reader: &mut Reader<F>) -> Result<Option<Mp4Box>, Unreadable> {+ if self.count >= MAX_ENTRIES || self.position.saturating_add(8) > self.end {+ return Ok(None);+ }+ self.count += 1;+ let header = reader.read(self.position, 16)?;+ if header.len() < 8 {+ self.count = MAX_ENTRIES;+ return Ok(None);+ }+ let kind = [header[4], header[5], header[6], header[7]];+ let mut size = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as u64;+ let mut content_start = self.position + 8;+ if size == 1 {+ if header.len() < 16 {+ self.count = MAX_ENTRIES;+ return Ok(None);+ }+ size = u64::from_be_bytes(header[8..16].try_into().expect("8 bytes"));+ content_start += 8;+ } else if size == 0 {+ // The box extends to the end of the file.+ self.count = MAX_ENTRIES;+ return Ok(Some(Mp4Box { kind, content_start, end: self.end }));+ }+ if self.position.saturating_add(size) < content_start {+ self.count = MAX_ENTRIES;+ return Ok(None);+ }+ let found = Mp4Box { kind, content_start, end: self.position.saturating_add(size).min(self.end) };+ self.position = self.position.saturating_add(size);+ Ok(Some(found))+ }+}++fn find_box<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>, start: u64, end: u64, path: &[&str]) -> Result<Option<Mp4Box>, Unreadable> {+ let (mut start, mut end) = (start, end);+ let mut found = None;+ for kind in path {+ found = None;+ let mut boxes = Boxes::new(start, end);+ while let Some(child) = boxes.next(reader)? {+ if child.kind == kind.as_bytes() {+ found = Some(child);+ break;+ }+ }+ let Some(parent) = found else { return Ok(None) };+ (start, end) = (parent.content_start, parent.end);+ }+ Ok(found)+}++const MP4_AUDIO_SAMPLE_ENTRIES: [(&str, &str, &str); 15] = [+ ("Opus", "opus", "Opus"),+ ("fLaC", "flac", "FLAC"),+ ("ac-3", "ac-3", "AC-3"),+ ("ec-3", "ec-3", "E-AC-3"),+ ("ac-4", "ac-4", "AC-4"),+ ("alac", "alac", "ALAC"),+ ("samr", "samr", "AMR"),+ ("sawb", "sawb", "AMR-WB"),+ ("dtsc", "dtsc", "DTS"),+ ("dtse", "dtse", "DTS"),+ ("dtsh", "dtsh", "DTS"),+ ("dtsl", "dtsl", "DTS"),+ ("dtsx", "dtsx", "DTS"),+ ("mha1", "mha1", "MPEG-H 3D Audio"),+ ("mhm1", "mhm1", "MPEG-H 3D Audio"),+];++/// The object types of an MPEG-4 elementary stream descriptor other than MPEG-4 Audio.+fn mp4_audio_object_type_name(object_type: u8) -> Option<&'static str> {+ match object_type {+ 0x66..=0x68 => Some("AAC"),+ 0x69 | 0x6B => Some("MP3"),+ 0xA5 => Some("AC-3"),+ 0xA6 => Some("E-AC-3"),+ 0xA9..=0xAC => Some("DTS"),+ _ => None,+ }+}++const MPEG4_AUDIO_OBJECT_TYPE: u8 = 0x40;++/// The audio object types of MPEG-4 Audio; others, such as lossless ALS, have no name.+fn mpeg4_audio_object_type_name(audio_object_type: u32) -> Option<&'static str> {+ match audio_object_type {+ 1..=6 | 17 | 19 | 20 | 23 | 29 | 39 => Some("AAC"),+ 32 | 33 => Some("MPEG Audio"),+ 34 => Some("MP3"),+ _ => None,+ }+}++fn read_mp4_tracks<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>) -> Result<Vec<Track>, Unreadable> {+ let Some(moov) = find_box(reader, 0, u64::MAX, &["moov"])? else { return Ok(Vec::new()) };+ let mut tracks = Vec::new();+ let mut traks = Boxes::new(moov.content_start, moov.end);+ while let Some(trak) = traks.next(reader)? {+ if &trak.kind != b"trak" {+ continue;+ }+ let Some(mdia) = find_box(reader, trak.content_start, trak.end, &["mdia"])? else { continue };+ let Some(hdlr) = find_box(reader, mdia.content_start, mdia.end, &["hdlr"])? else { continue };+ // The handler type follows the version, flags and a reserved field.+ if ascii(&reader.read(hdlr.content_start + 8, 4)?, 0, 4) != "soun" {+ continue;+ }+ let Some(stsd) = find_box(reader, mdia.content_start, mdia.end, &["minf", "stbl", "stsd"])? else { continue };+ // The sample entries follow the version, flags and entry count.+ if let Some(entry) = Boxes::new(stsd.content_start + 8, stsd.end).next(reader)?+ && let Some(track) = read_mp4_audio_sample_entry(reader, entry)?+ {+ tracks.push(track);+ }+ }+ Ok(tracks)+}++fn read_mp4_audio_sample_entry<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>, entry: Mp4Box) -> Result<Option<Track>, Unreadable> {+ if let Some((_, codec, name)) = MP4_AUDIO_SAMPLE_ENTRIES.iter().find(|(kind, ..)| kind.as_bytes() == entry.kind) {+ return Ok(Some(Track { kind: "audio", codec: (*codec).into(), name: Some(name) }));+ }+ if &entry.kind != b"mp4a" {+ return Ok(None);+ }+ // The child boxes follow 28 bytes of audio sample entry fields. Versions 1 and 2 of the QuickTime sound sample+ // description add 16 and 36 bytes; version 1 of the ISO audio sample entry adds none.+ let fields = reader.read(entry.content_start, 28)?;+ if fields.len() < 28 {+ return Ok(None);+ }+ let extra_fields_size = match u16::from_be_bytes([fields[8], fields[9]]) {+ 1 => 16,+ 2 => 36,+ _ => 0,+ };+ let mut esds = None;+ let mut children_starts = vec![entry.content_start + 28 + extra_fields_size];+ if extra_fields_size != 0 {+ children_starts.push(entry.content_start + 28);+ }+ for children_start in children_starts {+ esds = match find_box(reader, children_start, entry.end, &["esds"])? {+ Some(found) => Some(found),+ None => find_box(reader, children_start, entry.end, &["wave", "esds"])?,+ };+ if esds.is_some() {+ break;+ }+ }+ let Some(esds) = esds else { return Ok(None) };+ let Some((object_type, audio_object_type)) = parse_esds(&reader.read(esds.content_start, (esds.end - esds.content_start).min(256))?) else { return Ok(None) };+ if object_type == MPEG4_AUDIO_OBJECT_TYPE {+ return Ok(Some(match audio_object_type {+ None => Track { kind: "audio", codec: "mp4a.40".into(), name: None },+ Some(audio_object_type) => Track { kind: "audio", codec: format!("mp4a.40.{audio_object_type}"), name: mpeg4_audio_object_type_name(audio_object_type) },+ }));+ }+ Ok(mp4_audio_object_type_name(object_type).map(|name| Track { kind: "audio", codec: format!("mp4a.{object_type:X}"), name: Some(name) }))+}++/// `parseEsds`: the object type of an elementary stream descriptor and, for MPEG-4 Audio, the audio object type of+/// its decoder specific info.+fn parse_esds(bytes: &[u8]) -> Option<(u8, Option<u32>)> {+ let byte = |offset: usize| bytes.get(offset).copied().unwrap_or(0);+ // Past the version and flags.+ let mut offset = 4;+ let read_descriptor = |offset: &mut usize, tag: u8| -> Option<u32> {+ if bytes.get(*offset) != Some(&tag) {+ return None;+ }+ *offset += 1;+ let mut size = 0;+ for _ in 0..4 {+ let Some(&next) = bytes.get(*offset) else { break };+ *offset += 1;+ size = (size << 7) | (next & 0x7F) as u32;+ if next & 0x80 == 0 {+ break;+ }+ }+ Some(size)+ };+ // ES_Descriptor+ read_descriptor(&mut offset, 0x03)?;+ let flags = byte(offset + 2);+ offset += 3;+ if flags & 0x80 != 0 {+ offset += 2;+ }+ if flags & 0x40 != 0 {+ offset += 1 + byte(offset) as usize;+ }+ if flags & 0x20 != 0 {+ offset += 2;+ }+ // DecoderConfigDescriptor+ read_descriptor(&mut offset, 0x04)?;+ if offset >= bytes.len() {+ return None;+ }+ let object_type = bytes[offset];+ offset += 13;+ // DecoderSpecificInfo, which starts with the AudioSpecificConfig for MPEG-4 Audio.+ let mut audio_object_type = None;+ if object_type == MPEG4_AUDIO_OBJECT_TYPE && read_descriptor(&mut offset, 0x05).is_some() && offset < bytes.len() {+ let mut value = (bytes[offset] >> 3) as u32;+ if value == 31 && offset + 1 < bytes.len() {+ value = 32 + ((((bytes[offset] & 0x07) << 3) | (bytes[offset + 1] >> 5)) as u32);+ }+ audio_object_type = Some(value);+ }+ Some((object_type, audio_object_type))+}++const EBML_HEADER_ID: u32 = 0x1A45DFA3;+const SEGMENT_ID: u64 = 0x18538067;+const TRACKS_ID: u64 = 0x1654AE6B;+const CLUSTER_ID: u64 = 0x1F43B675;+const TRACK_ENTRY_ID: u64 = 0xAE;+const TRACK_TYPE_ID: u64 = 0x83;+const CODEC_ID_ID: u64 = 0x86;++/// `webmCodecs`: codec id, kind, codec and name.+const WEBM_CODECS: [(&str, &str, &str, &str); 13] = [+ ("V_VP8", "video", "vp8", "VP8"),+ ("V_VP9", "video", "vp9", "VP9"),+ // Media Source Extensions need a profile, level and bit depth for AV1: main profile, level 4.0, 8 bits.+ ("V_AV1", "video", "av01.0.08M.08", "AV1"),+ ("A_OPUS", "audio", "opus", "Opus"),+ ("A_VORBIS", "audio", "vorbis", "Vorbis"),+ ("A_FLAC", "audio", "flac", "FLAC"),+ ("A_AAC", "audio", "mp4a.40.2", "AAC"),+ ("A_MPEG/L3", "audio", "mp3", "MP3"),+ ("A_AC3", "audio", "ac-3", "AC-3"),+ ("A_EAC3", "audio", "ec-3", "E-AC-3"),+ ("A_DTS", "audio", "dtsc", "DTS"),+ ("A_TRUEHD", "audio", "mlpa", "Dolby TrueHD"),+ ("A_ALAC", "audio", "alac", "ALAC"),+];++#[derive(Clone, Copy)]+struct EbmlElement {+ id: u64,+ content_start: u64,+ end: u64,+}++/// `readVint`: ids keep their length marker; sizes do not, and all ones is an unknown size (`u64::MAX`).+fn read_vint(bytes: &[u8], offset: usize, is_id: bool) -> Option<(u64, usize)> {+ let first = *bytes.get(offset)?;+ let length = first.leading_zeros() as usize + 1;+ if length > 8 || offset + length > bytes.len() {+ return None;+ }+ let marker = 0x80u8 >> (length - 1);+ let mut value = if is_id { first as u64 } else { (first & (marker.wrapping_sub(1))) as u64 };+ let mut all_ones = value == marker.wrapping_sub(1) as u64;+ for &byte in &bytes[offset + 1..offset + length] {+ value = value * 256 + byte as u64;+ all_ones &= byte == 0xFF;+ }+ Some((if !is_id && all_ones { u64::MAX } else { value }, length))+}++/// `readEbmlElements`, one `next` at a time.+struct EbmlElements {+ position: u64,+ end: u64,+ count: usize,+}++impl EbmlElements {+ fn new(start: u64, end: u64) -> Self {+ EbmlElements { position: start, end, count: 0 }+ }++ fn next<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(&mut self, reader: &mut Reader<F>) -> Result<Option<EbmlElement>, Unreadable> {+ if self.count >= MAX_ENTRIES || self.position >= self.end {+ return Ok(None);+ }+ self.count += 1;+ let header = reader.read(self.position, 12)?;+ let Some((id, id_length)) = read_vint(&header, 0, true) else { return Ok(None) };+ let Some((size, size_length)) = read_vint(&header, id_length, false) else { return Ok(None) };+ let content_start = self.position + (id_length + size_length) as u64;+ let end = content_start.saturating_add(size).min(self.end);+ self.position = end;+ Ok(Some(EbmlElement { id, content_start, end }))+ }+}++fn read_webm_tracks<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>) -> Result<Vec<Track>, Unreadable> {+ let mut segment = None;+ let mut top = EbmlElements::new(0, u64::MAX);+ while let Some(element) = top.next(reader)? {+ if element.id == SEGMENT_ID {+ segment = Some(element);+ break;+ }+ }+ let Some(segment) = segment else { return Ok(Vec::new()) };+ let mut tracks_element = None;+ let mut children = EbmlElements::new(segment.content_start, segment.end);+ while let Some(element) = children.next(reader)? {+ if element.id == TRACKS_ID {+ tracks_element = Some(element);+ break;+ }+ // The tracks are described before the first cluster of media data.+ if element.id == CLUSTER_ID {+ break;+ }+ }+ let Some(tracks_element) = tracks_element else { return Ok(Vec::new()) };+ let mut tracks = Vec::new();+ let mut entries = EbmlElements::new(tracks_element.content_start, tracks_element.end);+ while let Some(entry) = entries.next(reader)? {+ if entry.id != TRACK_ENTRY_ID {+ continue;+ }+ let (mut track_type, mut codec_id) = (None, None);+ let mut fields = EbmlElements::new(entry.content_start, entry.end);+ while let Some(element) = fields.next(reader)? {+ if element.id == TRACK_TYPE_ID {+ let value = reader.read(element.content_start, (element.end - element.content_start).min(8))?;+ track_type = Some(value.iter().fold(0u64, |result, &byte| result * 256 + byte as u64));+ } else if element.id == CODEC_ID_ID {+ let value = reader.read(element.content_start, (element.end - element.content_start).min(64))?;+ codec_id = Some(ascii(&value, 0, value.len()).trim_end_matches('\0').to_owned());+ }+ }+ let kind = match track_type {+ Some(1) => "video",+ Some(2) => "audio",+ _ => continue,+ };+ // Codec ids such as `A_AAC/MPEG4/LC` name the profile after the codec.+ let Some(codec_id) = codec_id.map(|id| if id.starts_with("A_AAC/") { "A_AAC".to_owned() } else { id }) else { continue };+ if let Some(&(_, codec_kind, codec, name)) = WEBM_CODECS.iter().find(|(id, ..)| *id == codec_id)+ && codec_kind == kind+ {+ tracks.push(Track { kind, codec: codec.into(), name: Some(name) });+ }+ }+ Ok(tracks)+}++const OGG_BEGINNING_OF_STREAM: u8 = 0x02;++fn read_ogg_tracks<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>) -> Result<Vec<Track>, Unreadable> {+ let mut tracks = Vec::new();+ let mut position = 0;+ // Each logical stream starts with a page naming its codec, and these pages come before all others.+ for _ in 0..MAX_ENTRIES {+ let header = reader.read(position, 27)?;+ if header.len() < 27 || ascii(&header, 0, 4) != "OggS" || header[5] & OGG_BEGINNING_OF_STREAM == 0 {+ break;+ }+ let segment_count = header[26] as u64;+ let segments = reader.read(position + 27, segment_count)?;+ let data_start = position + 27 + segment_count;+ let signature = ascii(&reader.read(data_start, 8)?, 0, 8);+ let codec = match signature.as_str() {+ "OpusHead" => Some(("opus", "Opus")),+ "Speex " => Some(("speex", "Speex")),+ signature if signature.starts_with("\x01vorbis") => Some(("vorbis", "Vorbis")),+ signature if signature.starts_with("\x7FFLAC") => Some(("flac", "FLAC")),+ _ => None,+ };+ if let Some((codec, name)) = codec {+ tracks.push(Track { kind: "audio", codec: codec.into(), name: Some(name) });+ }+ position = data_start + segments.iter().map(|&size| size as u64).sum::<u64>();+ }+ Ok(tracks)+}++const WAV_EXTENSIBLE_FORMAT: u16 = 0xFFFE;++/// Browsers decode these though `canPlayType` only knows PCM in WAV files: PCM, IEEE float, A-law, mu-law, MP3.+const DECODABLE_WAV_FORMATS: [u16; 5] = [0x0001, 0x0003, 0x0006, 0x0007, 0x0055];++fn wav_format_name(format: u16) -> Option<&'static str> {+ match format {+ 0x0002 => Some("Microsoft ADPCM"),+ 0x0011 => Some("IMA ADPCM"),+ 0x0031 => Some("GSM 6.10"),+ 0x0050 => Some("MPEG Audio"),+ 0x00FF | 0x1610 => Some("AAC"),+ 0x0160..=0x0163 => Some("Windows Media Audio"),+ 0x2000 => Some("AC-3"),+ 0x2001 => Some("DTS"),+ _ => None,+ }+}++fn read_wav_tracks<F: FnMut(u64, u64) -> std::io::Result<Vec<u8>>>(reader: &mut Reader<F>) -> Result<Vec<Track>, Unreadable> {+ // Chunks follow the RIFF header and are padded to an even size.+ let mut position = 12;+ for _ in 0..MAX_ENTRIES {+ let header = reader.read(position, 8)?;+ if header.len() < 8 {+ return Ok(Vec::new());+ }+ let size = u32::from_le_bytes([header[4], header[5], header[6], header[7]]) as u64;+ if ascii(&header, 0, 4) == "fmt " {+ let format = reader.read(position + 8, size.min(26))?;+ if format.len() < 2 {+ return Ok(Vec::new());+ }+ let mut format_tag = u16::from_le_bytes([format[0], format[1]]);+ // The extensible format keeps the actual format at the start of its sub format GUID.+ if format_tag == WAV_EXTENSIBLE_FORMAT && format.len() >= 26 {+ format_tag = u16::from_le_bytes([format[24], format[25]]);+ }+ if DECODABLE_WAV_FORMATS.contains(&format_tag) {+ return Ok(Vec::new());+ }+ return Ok(vec![Track { kind: "audio", codec: format_tag.to_string(), name: wav_format_name(format_tag) }]);+ }+ position += 8 + size + size % 2;+ }+ Ok(Vec::new())+}++#[cfg(test)]+mod tests;diff --git a/native/crates/app/src/workbench/media_preview/codecs/tests.rs b/native/crates/app/src/workbench/media_preview/codecs/tests.rsnew file mode 100644index 00000000000..6fbfc04eff3--- /dev/null+++ b/native/crates/app/src/workbench/media_preview/codecs/tests.rs@@ -0,0 +1,113 @@+//! mediaCodecs.test.ts with the builders of mediaTestFiles.ts.++use super::*;++fn text(value: &str) -> Vec<u8> {+ value.bytes().collect()+}++fn zeros(length: usize) -> Vec<u8> {+ vec![0; length]+}++fn u16_le(value: u16) -> Vec<u8> {+ value.to_le_bytes().to_vec()+}++fn u32_le(value: u32) -> Vec<u8> {+ value.to_le_bytes().to_vec()+}++fn mp4_box(kind: &str, content: &[Vec<u8>]) -> Vec<u8> {+ let body = content.concat();+ [((8 + body.len()) as u32).to_be_bytes().to_vec(), text(kind), body].concat()+}++fn mp4_track(handler_type: &str, sample_entry: Vec<u8>) -> Vec<u8> {+ let stbl = mp4_box("stbl", &[mp4_box("stsd", &[zeros(4), 1u32.to_be_bytes().to_vec(), sample_entry]), mp4_box("stsz", &[zeros(1024)])]);+ let mdia = mp4_box("mdia", &[mp4_box("mdhd", &[zeros(24)]), mp4_box("hdlr", &[zeros(8), text(handler_type), zeros(13)]), mp4_box("minf", &[stbl])]);+ mp4_box("trak", &[mp4_box("tkhd", &[zeros(84)]), mdia])+}++/// An elementary stream descriptor of MPEG-4 Audio with the given AudioSpecificConfig.+fn mpeg4_audio_esds(audio_specific_config: &[u8]) -> Vec<u8> {+ let decoder_specific_info = [vec![0x05, audio_specific_config.len() as u8], audio_specific_config.to_vec()].concat();+ let decoder_config = [vec![0x04, 13 + decoder_specific_info.len() as u8, 0x40, 0x15], zeros(11), decoder_specific_info].concat();+ mp4_box("esds", &[zeros(4), [vec![0x03, 3 + decoder_config.len() as u8, 0, 1, 0], decoder_config].concat()])+}++fn ebml(id: &[u8], content: &[Vec<u8>]) -> Vec<u8> {+ let body = content.concat();+ [id.to_vec(), vec![0x40 | (body.len() >> 8) as u8, (body.len() & 0xFF) as u8], body].concat()+}++/// A WebM file with the given track types and codec ids, in a segment of unknown size as live recordings write.+fn webm(tracks: &[(u8, &str)]) -> Vec<u8> {+ let entries: Vec<Vec<u8>> = tracks.iter().enumerate().map(|(index, (kind, codec_id))| ebml(&[0xAE], &[ebml(&[0xD7], &[vec![index as u8 + 1]]), ebml(&[0x83], &[vec![*kind]]), ebml(&[0x86], &[text(codec_id)])])).collect();+ [+ ebml(&[0x1A, 0x45, 0xDF, 0xA3], &[ebml(&[0x42, 0x82], &[text("webm")])]),+ vec![0x18, 0x53, 0x80, 0x67, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],+ ebml(&[0x15, 0x49, 0xA9, 0x66], &[ebml(&[0x2A, 0xD7, 0xB1], &[vec![0x0F, 0x42, 0x40]])]),+ ebml(&[0x16, 0x54, 0xAE, 0x6B], &entries),+ ebml(&[0x1F, 0x43, 0xB6, 0x75], &[zeros(16)]),+ ]+ .concat()+}++fn ogg_beginning_of_stream_page(packet: Vec<u8>) -> Vec<u8> {+ [text("OggS"), vec![0, 0x02], zeros(20), vec![1, packet.len() as u8], packet].concat()+}++/// An odd sized chunk before the format checks that chunks are padded to an even size.+fn wav(format: Vec<u8>) -> Vec<u8> {+ [text("RIFF"), zeros(4), text("WAVE"), text("LIST"), u32_le(3), zeros(4), text("fmt "), u32_le(format.len() as u32), format, text("data"), zeros(4)].concat()+}++fn info(bytes: &[u8]) -> Option<MediaInfo> {+ read_media_info(bytes.len() as u64, |position, length| Ok(bytes[position as usize..(position + length) as usize].to_vec()))+}++fn audio(codec: &str, name: Option<&'static str>) -> Track {+ Track { kind: "audio", codec: codec.into(), name }+}++#[test]+fn reads_the_container_and_track_codecs() {+ let ftyp = mp4_box("ftyp", &[text("isom"), zeros(4)]);+ // The media data comes before the track descriptions, which start past the first chunk and end in the second.+ let aac_video = [+ ftyp.clone(),+ mp4_box("mdat", &[zeros(100_000)]),+ mp4_box("moov", &[mp4_box("mvhd", &[zeros(100)]), mp4_track("vide", mp4_box("avc1", &[zeros(78)])), mp4_track("soun", mp4_box("mp4a", &[zeros(28), mpeg4_audio_esds(&[0x12, 0x10])]))]),+ ]+ .concat();+ assert_eq!(info(&aac_video), Some(MediaInfo { container: "mp4", tracks: vec![audio("mp4a.40.2", Some("AAC"))] }));+ let ac3 = [ftyp.clone(), mp4_box("moov", &[mp4_track("soun", mp4_box("ac-3", &[zeros(28)]))])].concat();+ assert_eq!(info(&ac3), Some(MediaInfo { container: "mp4", tracks: vec![audio("ac-3", Some("AC-3"))] }));+ // MPEG-4 Audio that is not AAC: lossless ALS, whose object type 36 is escaped.+ let als = [ftyp.clone(), mp4_box("moov", &[mp4_track("soun", mp4_box("mp4a", &[zeros(28), mpeg4_audio_esds(&[0xF8, 0x80])]))])].concat();+ assert_eq!(info(&als), Some(MediaInfo { container: "mp4", tracks: vec![audio("mp4a.40.36", None)] }));+ let silent = [ftyp, mp4_box("moov", &[mp4_track("vide", mp4_box("avc1", &[zeros(78)]))])].concat();+ assert_eq!(info(&silent), Some(MediaInfo { container: "mp4", tracks: vec![] }));+ // The codec id of a subtitle track that matches a video codec is ignored.+ let vp9 = webm(&[(1, "V_VP9"), (2, "A_OPUS"), (2, "A_AAC/MPEG4/LC"), (17, "V_VP8")]);+ let video = Track { kind: "video", codec: "vp9".into(), name: Some("VP9") };+ assert_eq!(info(&vp9), Some(MediaInfo { container: "webm", tracks: vec![video, audio("opus", Some("Opus")), audio("mp4a.40.2", Some("AAC"))] }));+ let speex = [ogg_beginning_of_stream_page([text("Speex "), zeros(72)].concat()), text("OggS"), zeros(23)].concat();+ assert_eq!(info(&speex), Some(MediaInfo { container: "ogg", tracks: vec![audio("speex", Some("Speex"))] }));+ let adpcm = wav([u16_le(0x0011), u16_le(1), u32_le(8000), u32_le(4055), u16_le(256), u16_le(4), u16_le(2), u16_le(505)].concat());+ assert_eq!(info(&adpcm), Some(MediaInfo { container: "wav", tracks: vec![audio("17", Some("IMA ADPCM"))] }));+ // The extensible format with an IEEE float sub format, which browsers decode.+ let float = wav([u16_le(0xFFFE), u16_le(2), u32_le(48000), u32_le(384000), u16_le(8), u16_le(32), u16_le(22), u16_le(32), u32_le(3), u16_le(0x0003), zeros(14)].concat());+ assert_eq!(info(&float), Some(MediaInfo { container: "wav", tracks: vec![] }));+ assert_eq!(info(&text("not a media file")), None);+ assert_eq!(read_file_media_info(std::path::Path::new("/missing.mp4")), None);+}++#[test]+fn stops_at_the_read_limit() {+ // Box headers in 33 chunks before the track descriptions.+ let free = mp4_box("free", &[zeros(CHUNK_SIZE as usize)]);+ let late = [vec![mp4_box("ftyp", &[text("isom"), zeros(4)])], vec![free; MAX_CHUNKS + 1], vec![mp4_box("moov", &[mp4_track("soun", mp4_box("ac-3", &[zeros(28)]))])]].concat().concat();+ assert_eq!(info(&late), None);+}diff --git a/port/ledger.md b/port/ledger.mdindex d94b6fe7dab..ee2236eeb2d 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -508,7 +508,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| workbench/contrib/markdown | workbench contribution | M17 | verified | | workbench/markdown_document.rs renderMarkdownDocument (extension editor, walkthroughs): heading ids, per-caller link protocols, relative images; cargo test -p app markdown_document (markdownDocumentRenderer.test.ts both cases); `MarkedHighlight` code blocks: a fenced block's language by its name or its info string's first word, tokenized by textToHtmlTokenizer.ts `tokenizeToString` into `mtk` spans with the token colors CSS in the extension editor, walkthrough and release notes pages (editor/clipboard.rs `tokenize_to_string`: cargo test -p app fenced_code_blocks_are_tokenized_in_their_language). pulldown-cmark parses the markdown in marked's place (a Rust port has no JavaScript parser) || workbench/contrib/markers | workbench contribution | M13 | verified | | markersTreeViewer.ts `MarkerViewModel`: each marker keeps its quick fixes, asked once, until its resource's markers change (cargo test -p app each_problems_marker_keeps_its_quick_fixes). Indent guides and the focused row's outline apart from the selection (cargo test -p app the_focus_outline_follows). status bar problems entry and tooltip from markers (workbench/diagnostics.rs), its click toggles the Problems view; the Problems panel view (workbench/problems_view.rs: resources by worst severity then path, markers by severity then position, count badges, the tab badge, open on click, Collapse All, `workbench.actions.view.problems` and `toggleProblems`): cargo test -p app problems_view the_debug_console_and_test_results_are_panel_views, ui-pair port/results/problems.md; MarkersFileDecorations (count letter, error/warning color, bubbling, weight over other providers, `problems.decorations.enabled`) on Explorer rows and tabs (workbench/file_decorations.rs): cargo test -p app problems_decorate_the_file; filter box (workbench/view_filter.rs in the panel title at the panel's filter width, markers_filter.rs: markersFilterOptions.test.ts cases; text, `!`, globs, `@source:`, severity, active file and excluded files toggles, filter history, memento), filters menu, related information and multi-line rows, View as Table with column sashes (workbench/problems_table.rs), quick fixes on hovered rows (workbench/problems_quick_fix.rs): cargo test -p app markers_filter problems_view problems_table; ui-pair port/fixtures/problems/steps-filter.json and steps-table.json (port/results/problems.md); the selected row (first marker on focus, Up/Down, Enter and Cmd+Down open, `problems.action.copy`/`copyMessage`/`copyRelatedInformationMessage`, Cmd+. on the selected marker, `problemFocus`/`relatedInformationFocus`): cargo test -p app problems; ui-pair .vscode/settings.json and e.ts quick fix (port/results/language-features.md JSON settings, Problems quick fix). Multi-selection in the tree (`multipleSelectionSupport`: Shift+Up/Down, Cmd+click toggles, Shift+click ranges from the anchor, Copy over `getFocusedSelectedElements`) and open to the side (`problems.action.openToSide` on Ctrl+Enter, Ctrl/Cmd/Alt+click as listService.ts `sideBySide`, into `SIDE_GROUP`): cargo test -p app markers_select_together_and_open_to_the_side. Resource row: name 30px in, count badge 19px round 10px after the label at the line's bottom (cargo test -p app the_resource_name_sits_after_the_twistie_at_its_exact_line_height; ui-pair problems: chevron, icon x, name, description and badge box at the reference's device pixels, the file icon and the badge digit 1 device px low); a hovered marker without a model gets its quick fixes once its file opens (markersTreeViewer.ts `getModel(waitForModel)`; cargo test -p app a_problems_marker_gets_its_quick_fixes_once_its_file_opens) || workbench/contrib/mcp | workbench contribution | | removed | | no sign-in/AI by decision (port/notes.md); not ported |-| workbench/contrib/mediaPreview | workbench contribution | M17 | ported | [3 M] media_preview.rs:101, :156: non-file resources; mediaCodecs.ts | An image or media file previewed in another group gets a preview of its own in the active group (mediaPreview.contribution.ts registers without `singlePerResource`: cargo test -p app an_image_previewed_in_another_group_gets_a_preview_in_the_active_one); image, video and audio previews as built-in editors (workbench/media_preview.rs, pages in media_preview/*.html), resolver priority builtin, zoom commands and Select Zoom Level picker, zoom, dimensions and file size status entries, Reopen as Source Text / Image Preview, the file's tab icon and Explorer reveal; `FIXTURE=media-preview-tests port/tools/webview-check` 6/6 on both apps; cargo test -p app media_preview; ui-pair image, video and audio, the breadcrumbs bar with the editor type control and its Reopen/Set Default menu (editor-type-reopen.json; port/results/webviews.md); cargo test -p app lists_the_editor_types; the focus outline at open (ui-pair media-preview-focus.json, background and foreground); cargo test -p app opens_a_startup_image. Not done: codec probing (mediaCodecs.ts), Copy image, legacy `media-preview` editor migration |+| workbench/contrib/mediaPreview | workbench contribution | M17 | ported | [3 M] media_preview.rs:103: non-file resources (stat, Git LFS pointers, whole-file codec reads) | An image or media file previewed in another group gets a preview of its own in the active group (mediaPreview.contribution.ts registers without `singlePerResource`: cargo test -p app an_image_previewed_in_another_group_gets_a_preview_in_the_active_one); image, video and audio previews as built-in editors (workbench/media_preview.rs, pages in media_preview/*.html), resolver priority builtin, zoom commands and Select Zoom Level picker, zoom, dimensions and file size status entries, Reopen as Source Text / Image Preview, the file's tab icon and Explorer reveal; `FIXTURE=media-preview-tests port/tools/webview-check` 6/6 on both apps; cargo test -p app media_preview; ui-pair image, video and audio, the breadcrumbs bar with the editor type control and its Reopen/Set Default menu (editor-type-reopen.json; port/results/webviews.md); cargo test -p app lists_the_editor_types; the focus outline at open (ui-pair media-preview-focus.json, background and foreground); cargo test -p app opens_a_startup_image. Not done: Copy image, legacy `media-preview` editor migration. The player page's codec warnings and WebM type (mediaCodecs.ts as media_preview/codecs.rs, mediaPlayerEditorInput.ts `_postCodecs`, `_postWebmType`): cargo test -p app media_preview::codecs, answers_the_player_page_with_the_file_s_codecs || workbench/contrib/mergeEditor | workbench contribution | M14 | ported | [3 L] merge_editor_view.rs:5: no base-to-result diff backgrounds in the result, no "Comparing with" highlights in base <br> [3 L] merge_editor_view.rs:962: the inputs are not code editors: a press places a steady cursor, with no selection, cursor keys or blink | merge_editor.rs model (mapping, conflict states, accept/combine) and workbench/editor_view/merge_editor_view.rs (input 1/2, result, base view, layouts, gutter checkboxes, `_open.mergeEditor`, dev commands, the inputs' keyboard focus and Toggle Between Inputs, the active range in the last focused input or the result): cargo test -p app merge || workbench/contrib/meteredConnection | workbench contribution | M19 | verified | | the metered warning status entry and Configure Metered Connection (workbench/power.rs); port/tools/shell-check (port/fixtures/extensions/shell-tests, 6/6); cargo test -p app metered_connection || workbench/contrib/modernUI | workbench contribution | M11 | verified | | the modern layout only: the classic layout (`workbench.experimental.modernUI: false`) is removed by Artur's decision (port/notes.md Modern UI); `window.density.layout` compact and the Manage menu's Layout Density (cargo test -p app -- compact_density layout_density; ui-pair m11/layout-density.json in both densities with SETTINGS `{"window.density.layout": "compact"}`, port/results/layout-density.md) |