Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(media-proxy): strip media metadata and probe audio duration

Hampusf3d5bbfc6392
diff --git a/fluxer_media_proxy/build.rs b/fluxer_media_proxy/build.rs
index fcf1e42e8..431e6a365 100644
--- a/fluxer_media_proxy/build.rs
+++ b/fluxer_media_proxy/build.rs
@@ -9,10 +9,11 @@ fn is_distribution_lib_dir(path: &Path) -> bool {
path.starts_with("/usr/lib") || path.starts_with("/lib")
}
-const NATIVE_SHIM_SOURCES: [&str; 17] = [
+const NATIVE_SHIM_SOURCES: [&str; 18] = [
"src/webp_animation.c",
"src/native_shim/hdr_color.c",
"src/native_shim/av_input.c",
+ "src/native_shim/av_strip.c",
"src/native_shim/av_frame_rgba.c",
"src/native_shim/vips_image.c",
"src/native_shim/gif_validation.c",
diff --git a/fluxer_media_proxy/src/media_process/mod.rs b/fluxer_media_proxy/src/media_process/mod.rs
index 6f64af683..ce9df11ea 100644
--- a/fluxer_media_proxy/src/media_process/mod.rs
+++ b/fluxer_media_proxy/src/media_process/mod.rs
@@ -19,12 +19,17 @@ pub(crate) mod native_runtime;
mod nsfw_processing;
mod placeholder;
mod streaming_encoder;
+mod strip;
mod transform;
mod transform_plan;
mod video_thumbnail;
pub use metadata::{MetadataOptions, finish_metadata, prepare_metadata};
pub use native_cost::{NativeCost, av_native_cost, image_transform_cost, metadata_cost};
+pub use strip::{
+ AvContainer, StrippedImage, audio_duration_seconds, av_container, strip_av_metadata,
+ strip_image_metadata, strips_image,
+};
pub use transform::transform_image;
pub use video_thumbnail::extract_video_thumbnail;
diff --git a/fluxer_media_proxy/src/media_process/strip/av.rs b/fluxer_media_proxy/src/media_process/strip/av.rs
new file mode 100644
index 000000000..440f7b4a4
--- /dev/null
+++ b/fluxer_media_proxy/src/media_process/strip/av.rs
@@ -0,0 +1,206 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use super::super::native_runtime::ensure_vips_init;
+use super::super::{MediaError, native_optional_deadline, native_status_error};
+use crate::native::{self, FluxerAVAudioDurationOut, NativeStatus};
+use std::{
+ ffi::{CStr, CString},
+ os::unix::ffi::OsStrExt,
+ path::Path,
+};
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct AvContainer {
+ demuxer: &'static CStr,
+ muxer: &'static CStr,
+ faststart: bool,
+}
+
+pub fn av_container(content_type: &str) -> Option<AvContainer> {
+ let muxer: &'static CStr = if content_type.contains("3gpp") {
+ c"3gp"
+ } else if content_type.contains("mp4") {
+ c"mp4"
+ } else if content_type.contains("webm") {
+ c"webm"
+ } else if content_type.contains("quicktime") {
+ c"mov"
+ } else if content_type.contains("x-matroska") {
+ c"matroska"
+ } else if content_type.contains("x-msvideo") {
+ c"avi"
+ } else if content_type.contains("x-flv") {
+ c"flv"
+ } else if content_type.contains("mp2t") {
+ c"mpegts"
+ } else if content_type.contains("mpeg") {
+ if content_type.starts_with("audio/") {
+ c"mp3"
+ } else {
+ c"mpeg"
+ }
+ } else if content_type.contains("x-ms-wmv") {
+ c"asf"
+ } else if content_type.contains("wav") {
+ c"wav"
+ } else if content_type.contains("flac") {
+ c"flac"
+ } else if content_type.contains("aac") {
+ c"adts"
+ } else if content_type.contains("aiff") {
+ c"aiff"
+ } else if content_type.contains("ogg") {
+ c"ogg"
+ } else {
+ return None;
+ };
+ let demuxer = match muxer.to_bytes() {
+ b"3gp" | b"mov" => c"mp4",
+ b"webm" => c"matroska",
+ b"adts" => c"aac",
+ _ => muxer,
+ };
+ Some(AvContainer {
+ demuxer,
+ muxer,
+ faststart: matches!(muxer.to_bytes(), b"mp4" | b"mov" | b"3gp"),
+ })
+}
+
+pub fn strip_av_metadata(
+ input: &[u8],
+ container: AvContainer,
+ output: &Path,
+ deadline_ms: Option<i64>,
+) -> Result<(), MediaError> {
+ ensure_vips_init()?;
+ if input.is_empty() {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ let output =
+ CString::new(output.as_os_str().as_bytes()).map_err(|_| MediaError::MediaEncodeFailed)?;
+ let rc = unsafe {
+ native::fluxer_av_strip_metadata(
+ input.as_ptr().cast(),
+ input.len(),
+ container.demuxer.as_ptr(),
+ container.muxer.as_ptr(),
+ i32::from(container.faststart),
+ output.as_ptr(),
+ native_optional_deadline(deadline_ms),
+ )
+ };
+ match native_status_error(NativeStatus::from_code(rc), MediaError::MediaDecodeFailed) {
+ Some(error) => Err(error),
+ None => Ok(()),
+ }
+}
+
+fn positive(seconds: f64) -> Option<f64> {
+ (seconds.is_finite() && seconds > 0.0).then_some(seconds)
+}
+
+pub fn audio_duration_seconds(
+ input: &[u8],
+ deadline_ms: Option<i64>,
+) -> Result<Option<f64>, MediaError> {
+ ensure_vips_init()?;
+ if input.is_empty() {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ let mut out = FluxerAVAudioDurationOut::default();
+ let rc = unsafe {
+ native::fluxer_av_audio_duration(
+ input.as_ptr().cast(),
+ input.len(),
+ native_optional_deadline(deadline_ms),
+ &mut out,
+ )
+ };
+ if let Some(error) =
+ native_status_error(NativeStatus::from_code(rc), MediaError::MediaDecodeFailed)
+ {
+ return Err(error);
+ }
+ let frames = (out.frame_count > 0).then_some(out.frames_seconds);
+ Ok(frames
+ .or_else(|| positive(out.stream_seconds))
+ .or_else(|| positive(out.format_seconds)))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn wav_with_info(samples: u32, sample_rate: u32) -> Vec<u8> {
+ let data: Vec<u8> = (0..samples)
+ .flat_map(|i| (((i % 64) as i16 - 32) * 512).to_le_bytes())
+ .collect();
+ let mut info = b"INFO".to_vec();
+ info.extend_from_slice(b"INAM");
+ info.extend_from_slice(&14u32.to_le_bytes());
+ info.extend_from_slice(b"secret title\0\0");
+ let mut body = b"WAVEfmt ".to_vec();
+ body.extend_from_slice(&16u32.to_le_bytes());
+ body.extend_from_slice(&1u16.to_le_bytes());
+ body.extend_from_slice(&1u16.to_le_bytes());
+ body.extend_from_slice(&sample_rate.to_le_bytes());
+ body.extend_from_slice(&(sample_rate * 2).to_le_bytes());
+ body.extend_from_slice(&2u16.to_le_bytes());
+ body.extend_from_slice(&16u16.to_le_bytes());
+ body.extend_from_slice(b"LIST");
+ body.extend_from_slice(&(info.len() as u32).to_le_bytes());
+ body.extend_from_slice(&info);
+ body.extend_from_slice(b"data");
+ body.extend_from_slice(&(data.len() as u32).to_le_bytes());
+ body.extend_from_slice(&data);
+ let mut wav = b"RIFF".to_vec();
+ wav.extend_from_slice(&(body.len() as u32).to_le_bytes());
+ wav.extend_from_slice(&body);
+ wav
+ }
+
+ fn flv_tag(kind: u8, timestamp_ms: u32, data: &[u8]) -> Vec<u8> {
+ let mut tag = vec![kind];
+ tag.extend_from_slice(&(data.len() as u32).to_be_bytes()[1..]);
+ tag.extend_from_slice(&timestamp_ms.to_be_bytes()[1..]);
+ tag.push((timestamp_ms >> 24) as u8);
+ tag.extend_from_slice(&[0, 0, 0]);
+ tag.extend_from_slice(data);
+ tag.extend_from_slice(&(11 + data.len() as u32).to_be_bytes());
+ tag
+ }
+
+ #[test]
+ fn remux_refuses_streams_that_appear_after_probing() {
+ let mut flv = b"FLV\x01\x04\x00\x00\x00\x09\x00\x00\x00\x00".to_vec();
+ let mut audio = vec![0x3E];
+ audio.extend_from_slice(&[0; 8820]);
+ for index in 0..700 {
+ flv.extend(flv_tag(8, index * 100, &audio));
+ }
+ let mut video = vec![0x12];
+ video.extend_from_slice(&[0; 64]);
+ for index in 0..10 {
+ flv.extend(flv_tag(9, 70_000 + index * 100, &video));
+ }
+ let container = av_container("video/x-flv").expect("flv container");
+ let output = tempfile::NamedTempFile::new().expect("output file");
+
+ assert!(strip_av_metadata(&flv, container, output.path(), None).is_err());
+ }
+
+ #[test]
+ fn remux_drops_container_tags_and_keeps_every_sample() {
+ let input = wav_with_info(48_000 * 3 / 2, 48_000);
+ let container = av_container("audio/wav").expect("wav container");
+ let output = tempfile::NamedTempFile::new().expect("output file");
+
+ strip_av_metadata(&input, container, output.path(), None).expect("stripped wav");
+
+ let stripped = std::fs::read(output.path()).expect("stripped bytes");
+ assert!(!stripped.windows(6).any(|window| window == b"secret"));
+ let duration = audio_duration_seconds(&stripped, None).expect("duration");
+ assert_eq!(Some(1.5), duration);
+ }
+}
diff --git a/fluxer_media_proxy/src/media_process/strip/gif.rs b/fluxer_media_proxy/src/media_process/strip/gif.rs
new file mode 100644
index 000000000..c99c9c600
--- /dev/null
+++ b/fluxer_media_proxy/src/media_process/strip/gif.rs
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use super::super::MediaError;
+
+const EXTENSION: u8 = 0x21;
+const IMAGE: u8 = 0x2C;
+const TRAILER: u8 = 0x3B;
+const PLAIN_TEXT: u8 = 0x01;
+const GRAPHIC_CONTROL: u8 = 0xF9;
+const APPLICATION: u8 = 0xFF;
+const KEPT_APPLICATIONS: [&[u8; 11]; 2] = [b"NETSCAPE2.0", b"ANIMEXTS1.0"];
+
+fn colour_table_len(flags: u8) -> usize {
+ if flags & 0x80 == 0 {
+ 0
+ } else {
+ 3 << ((flags & 0x07) + 1)
+ }
+}
+
+fn skip_sub_blocks(input: &[u8], mut offset: usize) -> Result<usize, MediaError> {
+ loop {
+ let size = usize::from(*input.get(offset).ok_or(MediaError::MediaDecodeFailed)?);
+ offset += 1;
+ if size == 0 {
+ return Ok(offset);
+ }
+ offset += size;
+ if offset > input.len() {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ }
+}
+
+fn keeps_extension(input: &[u8], offset: usize) -> bool {
+ match input.get(offset + 1) {
+ Some(&GRAPHIC_CONTROL | &PLAIN_TEXT) => true,
+ Some(&APPLICATION) => {
+ input.get(offset + 2) == Some(&11)
+ && input
+ .get(offset + 3..offset + 14)
+ .is_some_and(|id| KEPT_APPLICATIONS.iter().any(|kept| kept[..] == *id))
+ }
+ _ => false,
+ }
+}
+
+pub(super) fn strip_blocks(input: &[u8]) -> Result<Vec<u8>, MediaError> {
+ if !(input.starts_with(b"GIF87a") || input.starts_with(b"GIF89a")) || input.len() < 13 {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ let header_end = 13 + colour_table_len(input[10]);
+ let mut output = Vec::with_capacity(input.len());
+ output.extend_from_slice(
+ input
+ .get(..header_end)
+ .ok_or(MediaError::MediaDecodeFailed)?,
+ );
+ let mut offset = header_end;
+ loop {
+ match input.get(offset).copied().unwrap_or(TRAILER) {
+ TRAILER => {
+ output.push(TRAILER);
+ return Ok(output);
+ }
+ EXTENSION => {
+ let end = skip_sub_blocks(input, offset + 2)?;
+ if keeps_extension(input, offset) {
+ output.extend_from_slice(&input[offset..end]);
+ }
+ offset = end;
+ }
+ IMAGE => {
+ let flags = *input.get(offset + 9).ok_or(MediaError::MediaDecodeFailed)?;
+ let data_start = offset + 10 + colour_table_len(flags) + 1;
+ let end = skip_sub_blocks(input, data_start)?;
+ output.extend_from_slice(&input[offset..end]);
+ offset = end;
+ }
+ _ => return Err(MediaError::MediaDecodeFailed),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn strip_drops_comments_and_unknown_applications_but_keeps_looping() {
+ let mut input = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff".to_vec();
+ input.extend_from_slice(b"\x21\xff\x0bNETSCAPE2.0\x03\x01\x00\x00\x00");
+ input.extend_from_slice(b"\x21\xfe\x09GPS 59.33\x00");
+ input.extend_from_slice(b"\x21\xff\x0bXMP DataXMP\x04Jane\x00");
+ input.extend_from_slice(b"\x21\xf9\x04\x00\x0a\x00\x00\x00");
+ input.extend_from_slice(b"\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00");
+ input.extend_from_slice(b"\x3btrailing");
+
+ let stripped = strip_blocks(&input).expect("stripped gif");
+
+ let contains = |needle: &[u8]| {
+ stripped
+ .windows(needle.len())
+ .any(|window| window == needle)
+ };
+ assert!(contains(b"NETSCAPE2.0"));
+ assert!(!contains(b"GPS"));
+ assert!(!contains(b"Jane"));
+ assert!(stripped.ends_with(b"\x02\x02\x44\x01\x00\x3b"));
+ }
+}
diff --git a/fluxer_media_proxy/src/media_process/strip/heif.rs b/fluxer_media_proxy/src/media_process/strip/heif.rs
new file mode 100644
index 000000000..cea7f0cfd
--- /dev/null
+++ b/fluxer_media_proxy/src/media_process/strip/heif.rs
@@ -0,0 +1,465 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use super::super::MediaError;
+use std::{collections::HashSet, ops::Range};
+
+const FREE_BOX_HEADER: usize = 8;
+
+struct BoxSpan {
+ kind: [u8; 4],
+ start: usize,
+ body: usize,
+ end: usize,
+}
+
+fn read_uint(input: &[u8], offset: usize, size: usize) -> Result<u64, MediaError> {
+ let bytes = input
+ .get(offset..offset + size)
+ .ok_or(MediaError::MediaDecodeFailed)?;
+ Ok(bytes
+ .iter()
+ .fold(0u64, |value, &byte| (value << 8) | u64::from(byte)))
+}
+
+fn read_box(input: &[u8], start: usize, limit: usize) -> Result<BoxSpan, MediaError> {
+ let size = read_uint(input, start, 4)? as usize;
+ let kind: [u8; 4] = input
+ .get(start + 4..start + 8)
+ .and_then(|kind| kind.try_into().ok())
+ .ok_or(MediaError::MediaDecodeFailed)?;
+ let (body, end) = match size {
+ 0 => (start + 8, limit),
+ 1 => {
+ let large = usize::try_from(read_uint(input, start + 8, 8)?)
+ .map_err(|_| MediaError::MediaDecodeFailed)?;
+ (
+ start + 16,
+ start
+ .checked_add(large)
+ .ok_or(MediaError::MediaDecodeFailed)?,
+ )
+ }
+ size => (
+ start + 8,
+ start
+ .checked_add(size)
+ .ok_or(MediaError::MediaDecodeFailed)?,
+ ),
+ };
+ if body > end || end > limit {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ Ok(BoxSpan {
+ kind,
+ start,
+ body,
+ end,
+ })
+}
+
+fn children(input: &[u8], mut offset: usize, end: usize) -> Result<Vec<BoxSpan>, MediaError> {
+ let mut boxes = Vec::new();
+ while offset < end {
+ let span = read_box(input, offset, end)?;
+ offset = span.end;
+ boxes.push(span);
+ }
+ Ok(boxes)
+}
+
+fn push_box(output: &mut Vec<u8>, kind: &[u8; 4], body: &[u8]) -> Result<(), MediaError> {
+ let size = u32::try_from(body.len() + 8).map_err(|_| MediaError::StreamTooLong)?;
+ output.extend_from_slice(&size.to_be_bytes());
+ output.extend_from_slice(kind);
+ output.extend_from_slice(body);
+ Ok(())
+}
+
+fn metadata_item(input: &[u8], infe: &BoxSpan) -> Result<Option<u32>, MediaError> {
+ let version = *input.get(infe.body).ok_or(MediaError::MediaDecodeFailed)?;
+ if version < 2 {
+ return Err(MediaError::UnsupportedMediaType);
+ }
+ let id_size = if version == 2 { 2 } else { 4 };
+ let id = read_uint(input, infe.body + 4, id_size)? as u32;
+ let type_offset = infe.body + 4 + id_size + 2;
+ let item_type = input
+ .get(type_offset..type_offset + 4)
+ .ok_or(MediaError::MediaDecodeFailed)?;
+ Ok(matches!(item_type, b"Exif" | b"mime").then_some(id))
+}
+
+struct Removal {
+ items: HashSet<u32>,
+ file_ranges: Vec<Range<usize>>,
+ idat_ranges: Vec<Range<usize>>,
+}
+
+fn rewrite_iinf(input: &[u8], span: &BoxSpan, removal: &Removal) -> Result<Vec<u8>, MediaError> {
+ let version = *input.get(span.body).ok_or(MediaError::MediaDecodeFailed)?;
+ let count_size = if version == 0 { 2 } else { 4 };
+ let entries_start = span.body + 4 + count_size;
+ let mut kept = Vec::new();
+ let mut count = 0u32;
+ for entry in children(input, entries_start, span.end)? {
+ let removed = &entry.kind == b"infe"
+ && metadata_item(input, &entry)?.is_some_and(|id| removal.items.contains(&id));
+ if !removed {
+ kept.extend_from_slice(&input[entry.start..entry.end]);
+ count += 1;
+ }
+ }
+ let mut body = input[span.body..span.body + 4].to_vec();
+ if version == 0 {
+ body.extend_from_slice(
+ &u16::try_from(count)
+ .map_err(|_| MediaError::MediaDecodeFailed)?
+ .to_be_bytes(),
+ );
+ } else {
+ body.extend_from_slice(&count.to_be_bytes());
+ }
+ body.extend_from_slice(&kept);
+ Ok(body)
+}
+
+fn rewrite_iloc(
+ input: &[u8],
+ span: &BoxSpan,
+ removal: &mut Removal,
+) -> Result<Vec<u8>, MediaError> {
+ let version = *input.get(span.body).ok_or(MediaError::MediaDecodeFailed)?;
+ let sizes = read_uint(input, span.body + 4, 2)? as usize;
+ let offset_size = sizes >> 12;
+ let length_size = (sizes >> 8) & 0x0F;
+ let base_offset_size = (sizes >> 4) & 0x0F;
+ let index_size = if version == 0 { 0 } else { sizes & 0x0F };
+ let (count_size, id_size) = if version < 2 { (2, 2) } else { (4, 4) };
+ let count = read_uint(input, span.body + 6, count_size)?;
+ let mut offset = span.body + 6 + count_size;
+ let mut kept = Vec::new();
+ let mut kept_count = 0u64;
+ for _ in 0..count {
+ let entry_start = offset;
+ let id = read_uint(input, offset, id_size)? as u32;
+ offset += id_size;
+ let method = if version == 0 {
+ 0
+ } else {
+ let value = read_uint(input, offset, 2)? & 0x0F;
+ offset += 2;
+ value
+ };
+ let reference = read_uint(input, offset, 2)?;
+ let base = read_uint(input, offset + 2, base_offset_size)? as usize;
+ let extents = read_uint(input, offset + 2 + base_offset_size, 2)? as usize;
+ offset += 4 + base_offset_size;
+ let extent_size = index_size + offset_size + length_size;
+ let extents_end = offset + extents * extent_size;
+ if extents_end > span.end {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ if !removal.items.contains(&id) {
+ kept.extend_from_slice(&input[entry_start..extents_end]);
+ kept_count += 1;
+ offset = extents_end;
+ continue;
+ }
+ if reference != 0 || extents == 0 || length_size == 0 {
+ return Err(MediaError::UnsupportedMediaType);
+ }
+ let mut ranges = Vec::with_capacity(extents);
+ for _ in 0..extents {
+ offset += index_size;
+ let start = base.saturating_add(read_uint(input, offset, offset_size)? as usize);
+ let length = read_uint(input, offset + offset_size, length_size)? as usize;
+ offset += offset_size + length_size;
+ ranges.push(start..start.saturating_add(length));
+ }
+ if ranges.iter().any(Range::is_empty) {
+ return Err(MediaError::UnsupportedMediaType);
+ }
+ match method {
+ 0 => removal.file_ranges.extend(ranges),
+ 1 => removal.idat_ranges.extend(ranges),
+ _ => return Err(MediaError::UnsupportedMediaType),
+ }
+ }
+ let mut body = input[span.body..span.body + 6].to_vec();
+ if count_size == 2 {
+ body.extend_from_slice(&(kept_count as u16).to_be_bytes());
+ } else {
+ body.extend_from_slice(&(kept_count as u32).to_be_bytes());
+ }
+ body.extend_from_slice(&kept);
+ Ok(body)
+}
+
+fn rewrite_iref(input: &[u8], span: &BoxSpan, removal: &Removal) -> Result<Vec<u8>, MediaError> {
+ let version = *input.get(span.body).ok_or(MediaError::MediaDecodeFailed)?;
+ let id_size = if version == 0 { 2 } else { 4 };
+ let mut body = input[span.body..span.body + 4].to_vec();
+ for reference in children(input, span.body + 4, span.end)? {
+ let from = read_uint(input, reference.body, id_size)? as u32;
+ if removal.items.contains(&from) {
+ continue;
+ }
+ let count = read_uint(input, reference.body + id_size, 2)? as usize;
+ let mut targets = Vec::new();
+ for index in 0..count {
+ let target_offset = reference.body + id_size + 2 + index * id_size;
+ let target = read_uint(input, target_offset, id_size)? as u32;
+ if !removal.items.contains(&target) {
+ targets.extend_from_slice(&input[target_offset..target_offset + id_size]);
+ }
+ }
+ if targets.is_empty() {
+ continue;
+ }
+ let mut reference_body = input[reference.body..reference.body + id_size].to_vec();
+ reference_body.extend_from_slice(&((targets.len() / id_size) as u16).to_be_bytes());
+ reference_body.extend_from_slice(&targets);
+ push_box(&mut body, &reference.kind, &reference_body)?;
+ }
+ Ok(body)
+}
+
+fn rewrite_ipma(input: &[u8], span: &BoxSpan, removal: &Removal) -> Result<Vec<u8>, MediaError> {
+ let version = *input.get(span.body).ok_or(MediaError::MediaDecodeFailed)?;
+ let flags = read_uint(input, span.body + 1, 3)?;
+ let id_size = if version < 1 { 2 } else { 4 };
+ let association_size = if flags & 1 == 1 { 2 } else { 1 };
+ let count = read_uint(input, span.body + 4, 4)?;
+ let mut offset = span.body + 8;
+ let mut kept = Vec::new();
+ let mut kept_count = 0u32;
+ for _ in 0..count {
+ let entry_start = offset;
+ let id = read_uint(input, offset, id_size)? as u32;
+ let associations = usize::from(
+ *input
+ .get(offset + id_size)
+ .ok_or(MediaError::MediaDecodeFailed)?,
+ );
+ offset += id_size + 1 + associations * association_size;
+ if offset > span.end {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ if !removal.items.contains(&id) {
+ kept.extend_from_slice(&input[entry_start..offset]);
+ kept_count += 1;
+ }
+ }
+ let mut body = input[span.body..span.body + 4].to_vec();
+ body.extend_from_slice(&kept_count.to_be_bytes());
+ body.extend_from_slice(&kept);
+ Ok(body)
+}
+
+fn zero_ranges(target: &mut [u8], ranges: &[Range<usize>]) -> Result<(), MediaError> {
+ for range in ranges {
+ target
+ .get_mut(range.clone())
+ .ok_or(MediaError::MediaDecodeFailed)?
+ .fill(0);
+ }
+ Ok(())
+}
+
+fn rewrite_meta(
+ input: &[u8],
+ meta: &BoxSpan,
+ removal: &mut Removal,
+) -> Result<Vec<u8>, MediaError> {
+ let parts = children(input, meta.body + 4, meta.end)?;
+ for infe in parts
+ .iter()
+ .filter(|part| &part.kind == b"iinf")
+ .map(|iinf| {
+ let version = input.get(iinf.body).copied().unwrap_or(0);
+ let count_size = if version == 0 { 2 } else { 4 };
+ children(input, iinf.body + 4 + count_size, iinf.end)
+ })
+ .collect::<Result<Vec<_>, _>>()?
+ .into_iter()
+ .flatten()
+ .filter(|entry| &entry.kind == b"infe")
+ {
+ if let Some(id) = metadata_item(input, &infe)? {
+ removal.items.insert(id);
+ }
+ }
+ if removal.items.is_empty() {
+ return Ok(input[meta.start..meta.end].to_vec());
+ }
+ let mut body = input[meta.body..meta.body + 4].to_vec();
+ for part in &parts {
+ let rewritten = match &part.kind {
+ b"iinf" => rewrite_iinf(input, part, removal)?,
+ b"iloc" => rewrite_iloc(input, part, removal)?,
+ b"iref" => rewrite_iref(input, part, removal)?,
+ b"iprp" => {
+ let mut iprp = Vec::new();
+ for child in children(input, part.body, part.end)? {
+ if &child.kind == b"ipma" {
+ let ipma = rewrite_ipma(input, &child, removal)?;
+ push_box(&mut iprp, &child.kind, &ipma)?;
+ } else {
+ iprp.extend_from_slice(&input[child.start..child.end]);
+ }
+ }
+ iprp
+ }
+ _ => {
+ body.extend_from_slice(&input[part.start..part.end]);
+ continue;
+ }
+ };
+ push_box(&mut body, &part.kind, &rewritten)?;
+ }
+ let mut output = Vec::new();
+ push_box(&mut output, b"meta", &body)?;
+ Ok(output)
+}
+
+pub(super) fn strip_items(input: &[u8]) -> Result<Vec<u8>, MediaError> {
+ let top = children(input, 0, input.len())?;
+ let meta = top
+ .iter()
+ .find(|span| &span.kind == b"meta")
+ .ok_or(MediaError::MediaDecodeFailed)?;
+ let mut removal = Removal {
+ items: HashSet::new(),
+ file_ranges: Vec::new(),
+ idat_ranges: Vec::new(),
+ };
+ let mut rewritten = rewrite_meta(input, meta, &mut removal)?;
+ if removal.items.is_empty() {
+ return Ok(input.to_vec());
+ }
+ if !removal.idat_ranges.is_empty() {
+ zero_idat(&mut rewritten, &removal.idat_ranges)?;
+ }
+ let original_len = meta.end - meta.start;
+ let padding = original_len
+ .checked_sub(rewritten.len())
+ .filter(|padding| *padding >= FREE_BOX_HEADER)
+ .ok_or(MediaError::UnsupportedMediaType)?;
+ if removal
+ .file_ranges
+ .iter()
+ .any(|range| range.start < meta.end && range.end > meta.start)
+ {
+ return Err(MediaError::UnsupportedMediaType);
+ }
+ let mut output = Vec::with_capacity(input.len());
+ output.extend_from_slice(&input[..meta.start]);
+ output.extend_from_slice(&rewritten);
+ push_box(&mut output, b"free", &vec![0; padding - FREE_BOX_HEADER])?;
+ output.extend_from_slice(&input[meta.end..]);
+ zero_ranges(&mut output, &removal.file_ranges)?;
+ Ok(output)
+}
+
+fn zero_idat(meta: &mut [u8], ranges: &[Range<usize>]) -> Result<(), MediaError> {
+ let parts = children(meta, 12, meta.len())?;
+ let idat = parts
+ .iter()
+ .find(|part| &part.kind == b"idat")
+ .ok_or(MediaError::MediaDecodeFailed)?;
+ let (body, end) = (idat.body, idat.end);
+ zero_ranges(&mut meta[body..end], ranges)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn full_box(kind: &[u8; 4], version: u8, body: &[u8]) -> Vec<u8> {
+ let mut payload = vec![version, 0, 0, 0];
+ payload.extend_from_slice(body);
+ plain_box(kind, &payload)
+ }
+
+ fn plain_box(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
+ let mut out = Vec::new();
+ push_box(&mut out, kind, body).expect("box");
+ out
+ }
+
+ fn infe(id: u16, item_type: &[u8; 4]) -> Vec<u8> {
+ let mut body = id.to_be_bytes().to_vec();
+ body.extend_from_slice(&[0, 0]);
+ body.extend_from_slice(item_type);
+ body.push(0);
+ full_box(b"infe", 2, &body)
+ }
+
+ fn heif_with_exif(image_offset: u32, exif_offset: u32) -> Vec<u8> {
+ heif_with_entries(image_offset, exif_offset, infe(2, b"Exif"))
+ }
+
+ fn heif_with_entries(image_offset: u32, exif_offset: u32, exif_entry: Vec<u8>) -> Vec<u8> {
+ let mut iinf = 2u16.to_be_bytes().to_vec();
+ iinf.extend(infe(1, b"hvc1"));
+ iinf.extend(exif_entry);
+ let mut iloc = vec![0x44, 0x00];
+ iloc.extend_from_slice(&2u16.to_be_bytes());
+ for (id, offset) in [(1u16, image_offset), (2u16, exif_offset)] {
+ iloc.extend_from_slice(&id.to_be_bytes());
+ iloc.extend_from_slice(&[0, 0, 0, 1]);
+ iloc.extend_from_slice(&offset.to_be_bytes());
+ iloc.extend_from_slice(&8u32.to_be_bytes());
+ }
+ let mut cdsc = 2u16.to_be_bytes().to_vec();
+ cdsc.extend_from_slice(&1u16.to_be_bytes());
+ cdsc.extend_from_slice(&1u16.to_be_bytes());
+ let mut ipma = 2u32.to_be_bytes().to_vec();
+ ipma.extend_from_slice(&[0, 1, 1, 0x81]);
+ ipma.extend_from_slice(&[0, 2, 1, 0x81]);
+ let mut iprp = plain_box(b"ipco", &plain_box(b"ispe", &[0; 12]));
+ iprp.extend(full_box(b"ipma", 0, &ipma));
+ let mut meta = full_box(b"hdlr", 0, &[0; 21]);
+ meta.extend(full_box(b"iinf", 0, &iinf));
+ meta.extend(full_box(b"iloc", 0, &iloc));
+ meta.extend(full_box(b"iref", 0, &plain_box(b"cdsc", &cdsc)));
+ meta.extend(plain_box(b"iprp", &iprp));
+ let mut file = plain_box(b"ftyp", b"heic\0\0\0\0mif1heic");
+ file.extend(full_box(b"meta", 0, &meta));
+ file.extend(plain_box(b"mdat", b"IMAGEDATGPS59.33"));
+ file
+ }
+
+ #[test]
+ fn strip_removes_exif_items_without_moving_image_data() {
+ let probe = heif_with_exif(0, 0);
+ let mdat_payload = probe.len() as u32 - 16;
+ let input = heif_with_exif(mdat_payload, mdat_payload + 8);
+
+ let stripped = strip_items(&input).expect("stripped heif");
+
+ assert_eq!(input.len(), stripped.len());
+ let image = mdat_payload as usize;
+ assert_eq!(b"IMAGEDAT", &stripped[image..image + 8]);
+ assert_eq!(&[0u8; 8], &stripped[image + 8..image + 16]);
+ let contains = |needle: &[u8]| {
+ stripped
+ .windows(needle.len())
+ .any(|window| window == needle)
+ };
+ assert!(!contains(b"Exif"));
+ assert!(!contains(b"cdsc"));
+ assert!(contains(b"free"));
+ let top = children(&stripped, 0, stripped.len()).expect("top-level boxes");
+ let kinds: Vec<&[u8; 4]> = top.iter().map(|span| &span.kind).collect();
+ assert_eq!(vec![b"ftyp", b"meta", b"free", b"mdat"], kinds);
+ }
+
+ #[test]
+ fn strip_refuses_item_entries_it_cannot_classify() {
+ let legacy_entry = full_box(b"infe", 0, b"\x00\x02\x00\x00exif\x00application/exif\x00");
+ let input = heif_with_entries(0, 0, legacy_entry);
+
+ assert_eq!(Err(MediaError::UnsupportedMediaType), strip_items(&input));
+ }
+}
diff --git a/fluxer_media_proxy/src/media_process/strip/jpeg.rs b/fluxer_media_proxy/src/media_process/strip/jpeg.rs
new file mode 100644
index 000000000..a7bfc1ed6
--- /dev/null
+++ b/fluxer_media_proxy/src/media_process/strip/jpeg.rs
@@ -0,0 +1,407 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use super::super::image_probe::load_image;
+use super::super::loaded_image::validate_vips_image;
+use super::super::native_runtime::clear_vips_error;
+use super::super::streaming_encoder::write_vips_image_to_vec;
+use super::super::{MediaError, native_status_error};
+use crate::{
+ constants,
+ media_limits::MediaLimits,
+ native::{self, NativeStatus, VipsImageHandle},
+};
+use std::{ffi::CString, ptr};
+
+const SOI: u8 = 0xD8;
+const EOI: u8 = 0xD9;
+const SOS: u8 = 0xDA;
+const DQT: u8 = 0xDB;
+const APP0: u8 = 0xE0;
+const APP2: u8 = 0xE2;
+const APP14: u8 = 0xEE;
+const APP15: u8 = 0xEF;
+const COM: u8 = 0xFE;
+const DEFAULT_REENCODE_QUALITY: u8 = 95;
+
+struct Segment<'a> {
+ marker: u8,
+ bytes: &'a [u8],
+ payload: &'a [u8],
+}
+
+struct JpegLayout<'a> {
+ header: Vec<Segment<'a>>,
+ scan_start: usize,
+ scan_end: usize,
+}
+
+fn is_standalone(marker: u8) -> bool {
+ matches!(marker, 0x01 | 0xD0..=0xD7)
+}
+
+fn read_segment(input: &[u8], offset: usize) -> Result<Segment<'_>, MediaError> {
+ let header = input
+ .get(offset..offset + 4)
+ .ok_or(MediaError::MediaDecodeFailed)?;
+ if header[0] != 0xFF {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ let length = usize::from(u16::from_be_bytes([header[2], header[3]]));
+ if length < 2 {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ let bytes = input
+ .get(offset..offset + 2 + length)
+ .ok_or(MediaError::MediaDecodeFailed)?;
+ Ok(Segment {
+ marker: header[1],
+ bytes,
+ payload: &bytes[4..],
+ })
+}
+
+fn skip_fill_bytes(input: &[u8], mut offset: usize) -> usize {
+ while input.get(offset) == Some(&0xFF) && input.get(offset + 1) == Some(&0xFF) {
+ offset += 1;
+ }
+ offset
+}
+
+fn find_end_of_image(input: &[u8], mut offset: usize) -> Result<usize, MediaError> {
+ loop {
+ let Some(found) = input[offset..].iter().position(|&byte| byte == 0xFF) else {
+ return Ok(input.len());
+ };
+ offset = skip_fill_bytes(input, offset + found);
+ let Some(&marker) = input.get(offset + 1) else {
+ return Ok(input.len());
+ };
+ if marker == 0x00 || is_standalone(marker) {
+ offset += 2;
+ continue;
+ }
+ if marker == EOI {
+ return Ok(offset + 2);
+ }
+ offset += read_segment(input, offset)?.bytes.len();
+ }
+}
+
+fn parse_layout(input: &[u8]) -> Result<JpegLayout<'_>, MediaError> {
+ if input.get(..2) != Some(&[0xFF, SOI]) {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ let mut header = Vec::new();
+ let mut offset = 2;
+ loop {
+ offset = skip_fill_bytes(input, offset);
+ let marker = *input.get(offset + 1).ok_or(MediaError::MediaDecodeFailed)?;
+ if is_standalone(marker) {
+ offset += 2;
+ continue;
+ }
+ if marker == EOI {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ if marker == SOS {
+ let scan_end = find_end_of_image(input, offset)?;
+ return Ok(JpegLayout {
+ header,
+ scan_start: offset,
+ scan_end,
+ });
+ }
+ let segment = read_segment(input, offset)?;
+ offset += segment.bytes.len();
+ header.push(segment);
+ }
+}
+
+fn is_icc(segment: &Segment<'_>) -> bool {
+ segment.marker == APP2 && segment.payload.starts_with(b"ICC_PROFILE\0")
+}
+
+fn keeps_segment(segment: &Segment<'_>) -> bool {
+ match segment.marker {
+ APP0 => segment.payload.starts_with(b"JFIF\0") || segment.payload.starts_with(b"JFXX\0"),
+ APP2 => is_icc(segment),
+ APP14 => segment.payload.starts_with(b"Adobe"),
+ APP0..=APP15 | COM => false,
+ _ => true,
+ }
+}
+
+pub(super) fn strip_segments(input: &[u8]) -> Result<Vec<u8>, MediaError> {
+ let layout = parse_layout(input)?;
+ let mut output = Vec::with_capacity(input.len());
+ output.extend_from_slice(&[0xFF, SOI]);
+ for segment in layout
+ .header
+ .iter()
+ .filter(|segment| keeps_segment(segment))
+ {
+ output.extend_from_slice(segment.bytes);
+ }
+ output.extend_from_slice(&input[layout.scan_start..layout.scan_end]);
+ Ok(output)
+}
+
+const COLOR_HASH: [u16; 100] = [
+ 1020, 1015, 932, 848, 780, 735, 702, 679, 660, 645, 632, 623, 613, 607, 600, 594, 589, 585,
+ 581, 571, 555, 542, 529, 514, 494, 474, 457, 439, 424, 410, 397, 386, 373, 364, 351, 341, 334,
+ 324, 317, 309, 299, 294, 287, 279, 274, 267, 262, 257, 251, 247, 243, 237, 232, 227, 222, 217,
+ 213, 207, 202, 198, 192, 188, 183, 177, 173, 168, 163, 157, 153, 148, 143, 139, 132, 128, 125,
+ 119, 115, 108, 104, 99, 94, 90, 84, 79, 74, 70, 64, 59, 55, 49, 45, 40, 34, 30, 25, 20, 15, 11,
+ 6, 4,
+];
+const COLOR_SUMS: [u32; 100] = [
+ 32640, 32635, 32266, 31495, 30665, 29804, 29146, 28599, 28104, 27670, 27225, 26725, 26210,
+ 25716, 25240, 24789, 24373, 23946, 23572, 22846, 21801, 20842, 19949, 19121, 18386, 17651,
+ 16998, 16349, 15800, 15247, 14783, 14321, 13859, 13535, 13081, 12702, 12423, 12056, 11779,
+ 11513, 11135, 10955, 10676, 10392, 10208, 9928, 9747, 9564, 9369, 9193, 9017, 8822, 8639, 8458,
+ 8270, 8084, 7896, 7710, 7527, 7347, 7156, 6977, 6788, 6607, 6422, 6236, 6054, 5867, 5684, 5495,
+ 5305, 5128, 4945, 4751, 4638, 4442, 4248, 4065, 3888, 3698, 3509, 3326, 3139, 2957, 2775, 2586,
+ 2405, 2216, 2037, 1846, 1666, 1483, 1297, 1109, 927, 735, 554, 375, 201, 128,
+];
+const GREY_HASH: [u16; 100] = [
+ 510, 505, 422, 380, 355, 338, 326, 318, 311, 305, 300, 297, 293, 291, 288, 286, 284, 283, 281,
+ 280, 279, 278, 277, 273, 262, 251, 243, 233, 225, 218, 211, 205, 198, 193, 186, 181, 177, 172,
+ 168, 164, 158, 156, 152, 148, 145, 142, 139, 136, 133, 131, 129, 126, 123, 120, 118, 115, 113,
+ 110, 107, 105, 102, 100, 97, 94, 92, 89, 87, 83, 81, 79, 76, 74, 70, 68, 66, 63, 61, 57, 55,
+ 52, 50, 48, 44, 42, 39, 37, 34, 31, 29, 26, 24, 21, 18, 16, 13, 11, 8, 6, 3, 2,
+];
+const GREY_SUMS: [u32; 100] = [
+ 16320, 16315, 15946, 15277, 14655, 14073, 13623, 13230, 12859, 12560, 12240, 11861, 11456,
+ 11081, 10714, 10360, 10027, 9679, 9368, 9056, 8680, 8331, 7995, 7668, 7376, 7084, 6823, 6562,
+ 6345, 6125, 5939, 5756, 5571, 5421, 5240, 5086, 4976, 4829, 4719, 4616, 4463, 4393, 4280, 4166,
+ 4092, 3980, 3909, 3835, 3755, 3688, 3621, 3541, 3467, 3396, 3323, 3247, 3170, 3096, 3021, 2952,
+ 2874, 2804, 2727, 2657, 2583, 2509, 2437, 2362, 2290, 2211, 2136, 2068, 1996, 1915, 1858, 1773,
+ 1692, 1620, 1552, 1477, 1398, 1326, 1251, 1179, 1109, 1031, 961, 884, 814, 736, 667, 592, 518,
+ 441, 369, 292, 221, 151, 86, 64,
+];
+
+fn estimate_quality(header: &[Segment<'_>]) -> Option<u8> {
+ let mut by_index: [Option<&[u8]>; 4] = [None; 4];
+ for segment in header.iter().filter(|segment| segment.marker == DQT) {
+ let Some(&first) = segment.payload.first() else {
+ continue;
+ };
+ if let Some(slot) = by_index.get_mut(usize::from(first & 0x0F)) {
+ *slot = Some(segment.payload);
+ }
+ }
+ let mut tables: Vec<&[u8]> = Vec::with_capacity(4);
+ let mut sum: u32 = 0;
+ 'segments: for payload in by_index.into_iter().flatten() {
+ let mut offset = 1;
+ while offset + 64 <= payload.len() {
+ let table = &payload[offset..offset + 64];
+ sum += table.iter().map(|&value| u32::from(value)).sum::<u32>();
+ tables.push(table);
+ if tables.len() >= 4 {
+ break 'segments;
+ }
+ offset += 65;
+ }
+ }
+ let first = tables.first()?;
+ let mut qval = u32::from(first[2]) + u32::from(first[53]);
+ let (hash, sums): (&[u16; 100], &[u32; 100]) = match tables.get(1) {
+ Some(second) => {
+ qval += u32::from(second[0]) + u32::from(second[63]);
+ (&COLOR_HASH, &COLOR_SUMS)
+ }
+ None => (&GREY_HASH, &GREY_SUMS),
+ };
+ for i in 0..100 {
+ let hash = u32::from(hash[i]);
+ if qval < hash && sum < sums[i] {
+ continue;
+ }
+ return ((qval <= hash && sum <= sums[i]) || i >= 50).then(|| (i + 1) as u8);
+ }
+ None
+}
+
+struct FrameFacts {
+ components: usize,
+ full_chroma: bool,
+}
+
+fn frame_facts(header: &[Segment<'_>]) -> Result<FrameFacts, MediaError> {
+ let frame = header
+ .iter()
+ .find(|segment| {
+ matches!(segment.marker, 0xC0..=0xCF) && !matches!(segment.marker, 0xC4 | 0xC8 | 0xCC)
+ })
+ .ok_or(MediaError::MediaDecodeFailed)?;
+ let components = usize::from(*frame.payload.get(5).ok_or(MediaError::MediaDecodeFailed)?);
+ let sampling = |index: usize| frame.payload.get(6 + index * 3 + 1).copied();
+ let full_chroma = components == 3 && sampling(0).is_some() && sampling(0) == sampling(1);
+ Ok(FrameFacts {
+ components,
+ full_chroma,
+ })
+}
+
+fn vips_status(rc: libc::c_int) -> Result<(), MediaError> {
+ match native_status_error(
+ NativeStatus::from_code(rc),
+ MediaError::MediaTransformFailed,
+ ) {
+ Some(error) => {
+ clear_vips_error();
+ Err(error)
+ }
+ None => Ok(()),
+ }
+}
+
+fn derive<'source>(
+ image: &VipsImageHandle<'source>,
+ raw: *mut native::VipsImage,
+ rc: libc::c_int,
+) -> Result<VipsImageHandle<'source>, MediaError> {
+ let derived = unsafe { image.adopt_derived_raw(raw) };
+ vips_status(rc)?;
+ derived.ok_or(MediaError::MediaTransformFailed)
+}
+
+fn insert_after_jfif(encoded: Vec<u8>, segments: &[&Segment<'_>]) -> Result<Vec<u8>, MediaError> {
+ let layout = parse_layout(&encoded)?;
+ let mut output =
+ Vec::with_capacity(encoded.len() + segments.iter().map(|s| s.bytes.len()).sum::<usize>());
+ output.extend_from_slice(&[0xFF, SOI]);
+ let jfif = layout
+ .header
+ .iter()
+ .take_while(|segment| segment.marker == APP0)
+ .count();
+ for segment in &layout.header[..jfif] {
+ output.extend_from_slice(segment.bytes);
+ }
+ for segment in segments {
+ output.extend_from_slice(segment.bytes);
+ }
+ for segment in &layout.header[jfif..] {
+ output.extend_from_slice(segment.bytes);
+ }
+ output.extend_from_slice(&encoded[layout.scan_start..layout.scan_end]);
+ Ok(output)
+}
+
+pub(super) fn srgb_without_alpha(
+ image: VipsImageHandle<'_>,
+) -> Result<VipsImageHandle<'_>, MediaError> {
+ let mut raw = ptr::null_mut();
+ let rc = unsafe { native::fluxer_vips_srgb_without_alpha(image.as_ptr(), &mut raw) };
+ derive(&image, raw, rc)
+}
+
+pub(super) fn orientation(image: &VipsImageHandle<'_>) -> i32 {
+ let field = c"orientation";
+ let mut value = 1;
+ let present =
+ unsafe { native::fluxer_vips_image_has_field(image.as_ptr(), field.as_ptr()) } != 0;
+ if present
+ && unsafe { native::fluxer_vips_image_get_int(image.as_ptr(), field.as_ptr(), &mut value) }
+ == 0
+ {
+ value
+ } else {
+ 1
+ }
+}
+
+pub(super) fn reencode_upright(
+ input: &[u8],
+ media_limits: &MediaLimits,
+ deadline_ms: Option<i64>,
+) -> Result<Vec<u8>, MediaError> {
+ let layout = parse_layout(input)?;
+ let facts = frame_facts(&layout.header)?;
+ let quality = estimate_quality(&layout.header).unwrap_or(DEFAULT_REENCODE_QUALITY);
+ let image = load_image(input, "")?;
+ validate_vips_image(media_limits, &image)?;
+ let mut raw = ptr::null_mut();
+ let rc = unsafe { native::fluxer_vips_autorot(image.as_ptr(), 0, &mut raw) };
+ let mut upright = derive(&image, raw, rc)?;
+ let cmyk = facts.components == 4;
+ if cmyk {
+ upright = srgb_without_alpha(upright)?;
+ }
+ let subsample = if facts.full_chroma { "off" } else { "on" };
+ let suffix = CString::new(format!(
+ ".jpg[Q={quality},strip,optimize_coding=true,subsample_mode={subsample}]"
+ ))
+ .map_err(|_| MediaError::MediaEncodeFailed)?;
+ let encoded = write_vips_image_to_vec(
+ &upright,
+ &suffix,
+ constants::MAX_MEDIA_PROXY_BYTES,
+ deadline_ms,
+ )?;
+ let icc: Vec<&Segment<'_>> = if cmyk {
+ Vec::new()
+ } else {
+ layout
+ .header
+ .iter()
+ .filter(|segment| is_icc(segment))
+ .collect()
+ };
+ if icc.is_empty() {
+ return Ok(encoded);
+ }
+ insert_after_jfif(encoded, &icc)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn segment(marker: u8, payload: &[u8]) -> Vec<u8> {
+ let mut out = vec![0xFF, marker];
+ out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
+ out.extend_from_slice(payload);
+ out
+ }
+
+ #[test]
+ fn strip_keeps_jfif_icc_and_adobe_and_drops_the_rest() {
+ let mut input = vec![0xFF, SOI];
+ input.extend(segment(APP0, b"JFIF\0\x01\x01\0\0\x01\0\x01\0\0"));
+ input.extend(segment(0xE1, b"Exif\0\0GPS"));
+ input.extend(segment(APP2, b"ICC_PROFILE\0\x01\x01data"));
+ input.extend(segment(APP2, b"MPF\0data"));
+ input.extend(segment(0xED, b"Photoshop 3.0\0"));
+ input.extend(segment(APP14, b"Adobe\0\x64\0\0\0\0\x02"));
+ input.extend(segment(COM, b"comment"));
+ input.extend(segment(DQT, &[0; 65]));
+ input.extend(segment(SOS, &[1, 1, 0, 0, 63, 0]));
+ input.extend_from_slice(&[0x12, 0xFF, 0x00, 0x34, 0xFF, 0xD0, 0x56]);
+ input.extend_from_slice(&[0xFF, EOI]);
+ input.extend_from_slice(b"trailer-gps");
+
+ let stripped = strip_segments(&input).expect("stripped jpeg");
+ let markers: Vec<u8> = parse_layout(&stripped)
+ .expect("layout")
+ .header
+ .iter()
+ .map(|segment| segment.marker)
+ .collect();
+ assert_eq!(vec![APP0, APP2, APP14, DQT], markers);
+ assert!(stripped.ends_with(&[0x56, 0xFF, EOI]));
+ assert!(!stripped.windows(3).any(|window| window == b"GPS"));
+ }
+
+ #[test]
+ fn quality_estimate_recovers_the_encoder_quality() {
+ for quality in [55, 82, 95] {
+ let encoded =
+ crate::test_fixtures::synthetic_image(64, 48, &format!(".jpg[Q={quality},strip]"));
+ let layout = parse_layout(&encoded).expect("layout");
+ assert_eq!(Some(quality), estimate_quality(&layout.header));
+ }
+ }
+}
diff --git a/fluxer_media_proxy/src/media_process/strip/mod.rs b/fluxer_media_proxy/src/media_process/strip/mod.rs
new file mode 100644
index 000000000..8ef9e22d4
--- /dev/null
+++ b/fluxer_media_proxy/src/media_process/strip/mod.rs
@@ -0,0 +1,113 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+mod av;
+mod gif;
+mod heif;
+mod jpeg;
+mod png;
+mod webp;
+
+pub use av::{AvContainer, audio_duration_seconds, av_container, strip_av_metadata};
+
+use super::image_probe::{load_image, probe_image_dims};
+use super::loaded_image::validate_vips_image;
+use super::native_runtime::{clear_vips_error, ensure_vips_init};
+use super::{MediaError, ensure_deadline_pending};
+use crate::{
+ constants,
+ media_limits::MediaLimits,
+ mime,
+ native::{self, buffer::NativeBuffer},
+};
+use std::ptr;
+
+const TIFF_SUFFIX: &std::ffi::CStr = c".tif[compression=jpeg,Q=80,predictor=horizontal,strip]";
+
+pub struct StrippedImage {
+ pub bytes: Vec<u8>,
+ pub content_type: &'static str,
+ pub width: u32,
+ pub height: u32,
+}
+
+fn reencode_tiff(
+ input: &[u8],
+ media_limits: &MediaLimits,
+ deadline_ms: Option<i64>,
+) -> Result<Vec<u8>, MediaError> {
+ let image = load_image(input, "n=-1")?;
+ validate_vips_image(media_limits, &image)?;
+ let image = jpeg::srgb_without_alpha(image)?;
+ ensure_deadline_pending(deadline_ms)?;
+ let mut buffer = ptr::null_mut();
+ let mut size = 0;
+ let rc = unsafe {
+ native::fluxer_vips_image_write_to_buffer(
+ image.as_ptr(),
+ TIFF_SUFFIX.as_ptr(),
+ &mut buffer,
+ &mut size,
+ )
+ };
+ let encoded = unsafe { NativeBuffer::from_vips_owned(buffer, size) };
+ if rc != 0 {
+ clear_vips_error();
+ return Err(MediaError::MediaEncodeFailed);
+ }
+ let encoded = encoded.ok_or(MediaError::MediaEncodeFailed)?;
+ if encoded.len() > constants::MAX_MEDIA_PROXY_BYTES {
+ return Err(MediaError::StreamTooLong);
+ }
+ encoded
+ .try_to_vec()
+ .map_err(|_| MediaError::AllocationFailed)
+}
+
+pub fn strips_image(sniffed_mime: &str) -> bool {
+ matches!(
+ sniffed_mime,
+ "image/jpeg"
+ | "image/png"
+ | "image/apng"
+ | "image/webp"
+ | "image/gif"
+ | "image/avif"
+ | "image/heic"
+ | "image/heif"
+ | "image/tiff"
+ )
+}
+
+pub fn strip_image_metadata(
+ input: &[u8],
+ media_limits: &MediaLimits,
+ deadline_ms: Option<i64>,
+) -> Result<StrippedImage, MediaError> {
+ ensure_vips_init()?;
+ let sniffed = mime::sniff(input).mime;
+ if !strips_image(sniffed) {
+ return Err(MediaError::UnsupportedMediaType);
+ }
+ let dims = probe_image_dims(media_limits, input)?;
+ let bytes = match sniffed {
+ "image/jpeg" => {
+ let upright = jpeg::orientation(&load_image(input, "")?) <= 1;
+ if upright {
+ jpeg::strip_segments(input)?
+ } else {
+ jpeg::reencode_upright(input, media_limits, deadline_ms)?
+ }
+ }
+ "image/png" | "image/apng" => png::strip_chunks(input)?,
+ "image/webp" => webp::strip_chunks(input)?,
+ "image/gif" => gif::strip_blocks(input)?,
+ "image/avif" | "image/heic" | "image/heif" => heif::strip_items(input)?,
+ _ => reencode_tiff(input, media_limits, deadline_ms)?,
+ };
+ Ok(StrippedImage {
+ bytes,
+ content_type: sniffed,
+ width: dims.width,
+ height: dims.height,
+ })
+}
diff --git a/fluxer_media_proxy/src/media_process/strip/png.rs b/fluxer_media_proxy/src/media_process/strip/png.rs
new file mode 100644
index 000000000..b79fef3ad
--- /dev/null
+++ b/fluxer_media_proxy/src/media_process/strip/png.rs
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use super::super::{MediaError, PNG_SIGNATURE};
+
+const KEPT_ANCILLARY_CHUNKS: [&[u8; 4]; 9] = [
+ b"tRNS", b"gAMA", b"cHRM", b"sRGB", b"iCCP", b"cICP", b"acTL", b"fcTL", b"fdAT",
+];
+
+fn keeps_chunk(kind: &[u8]) -> bool {
+ kind[0].is_ascii_uppercase() || KEPT_ANCILLARY_CHUNKS.iter().any(|kept| kept[..] == *kind)
+}
+
+pub(super) fn strip_chunks(input: &[u8]) -> Result<Vec<u8>, MediaError> {
+ if !input.starts_with(PNG_SIGNATURE) {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ let mut output = Vec::with_capacity(input.len());
+ output.extend_from_slice(PNG_SIGNATURE);
+ let mut offset = PNG_SIGNATURE.len();
+ while let Some(header) = input.get(offset..offset + 8) {
+ let length = u32::from_be_bytes([header[0], header[1], header[2], header[3]]) as usize;
+ let kind = &header[4..8];
+ let end = offset.saturating_add(12).saturating_add(length);
+ if keeps_chunk(kind) {
+ output.extend_from_slice(
+ input
+ .get(offset..end)
+ .ok_or(MediaError::MediaDecodeFailed)?,
+ );
+ }
+ offset = end;
+ if kind == b"IEND" {
+ break;
+ }
+ }
+ Ok(output)
+}
diff --git a/fluxer_media_proxy/src/media_process/strip/webp.rs b/fluxer_media_proxy/src/media_process/strip/webp.rs
new file mode 100644
index 000000000..9dbf7109f
--- /dev/null
+++ b/fluxer_media_proxy/src/media_process/strip/webp.rs
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use super::super::MediaError;
+
+const KEPT_CHUNKS: [&[u8; 4]; 7] = [
+ b"VP8 ", b"VP8L", b"VP8X", b"ALPH", b"ANIM", b"ANMF", b"ICCP",
+];
+const VP8X_EXIF_FLAG: u8 = 0x08;
+const VP8X_XMP_FLAG: u8 = 0x04;
+
+fn read_u32_le(input: &[u8], offset: usize) -> Option<usize> {
+ let bytes = input.get(offset..offset + 4)?;
+ Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize)
+}
+
+pub(super) fn strip_chunks(input: &[u8]) -> Result<Vec<u8>, MediaError> {
+ if input.len() < 12 || &input[..4] != b"RIFF" || &input[8..12] != b"WEBP" {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ let riff_end = input.len().min(
+ read_u32_le(input, 4)
+ .ok_or(MediaError::MediaDecodeFailed)?
+ .saturating_add(8),
+ );
+ let mut output = Vec::with_capacity(input.len());
+ output.extend_from_slice(&input[..12]);
+ let mut offset = 12;
+ while offset + 8 <= riff_end {
+ let length = read_u32_le(input, offset + 4).ok_or(MediaError::MediaDecodeFailed)?;
+ let payload_end = offset.saturating_add(8).saturating_add(length);
+ if payload_end > riff_end {
+ return Err(MediaError::MediaDecodeFailed);
+ }
+ let chunk_end = payload_end.saturating_add(length & 1);
+ let kind = &input[offset..offset + 4];
+ if KEPT_CHUNKS.iter().any(|kept| kept[..] == *kind) {
+ let start = output.len();
+ output.extend_from_slice(&input[offset..chunk_end.min(riff_end)]);
+ if kind == b"VP8X" && length > 0 {
+ output[start + 8] &= !(VP8X_EXIF_FLAG | VP8X_XMP_FLAG);
+ }
+ }
+ offset = chunk_end;
+ }
+ let riff_size = u32::try_from(output.len() - 8).map_err(|_| MediaError::StreamTooLong)?;
+ output[4..8].copy_from_slice(&riff_size.to_le_bytes());
+ Ok(output)
+}
diff --git a/fluxer_media_proxy/src/native/mod.rs b/fluxer_media_proxy/src/native/mod.rs
index 782c88e60..8466325e2 100644
--- a/fluxer_media_proxy/src/native/mod.rs
+++ b/fluxer_media_proxy/src/native/mod.rs
@@ -52,6 +52,15 @@ pub struct WebpAnimLimits {
pub deadline_monotonic_ms: c_longlong,
}
+#[repr(C)]
+#[derive(Default)]
+pub struct FluxerAVAudioDurationOut {
+ pub frames_seconds: c_double,
+ pub frame_count: c_int,
+ pub stream_seconds: c_double,
+ pub format_seconds: c_double,
+}
+
#[repr(C)]
pub struct FluxerAVMetadataOut {
pub has_video: c_int,
@@ -191,6 +200,8 @@ unsafe extern "C" {
deadline_monotonic_ms: c_longlong,
out: *mut *mut VipsImage,
) -> c_int;
+ pub fn fluxer_vips_srgb_without_alpha(input: *mut VipsImage, out: *mut *mut VipsImage)
+ -> c_int;
pub fn fluxer_vips_extract_area(
input: *mut VipsImage,
out: *mut *mut VipsImage,
@@ -298,6 +309,21 @@ unsafe extern "C" {
max_height: c_int,
out: *mut FluxerAVMetadataOut,
) -> c_int;
+ pub fn fluxer_av_strip_metadata(
+ media_data: *const c_void,
+ media_len: size_t,
+ demuxer: *const c_char,
+ muxer: *const c_char,
+ faststart: c_int,
+ output_path: *const c_char,
+ deadline_monotonic_ms: c_longlong,
+ ) -> c_int;
+ pub fn fluxer_av_audio_duration(
+ media_data: *const c_void,
+ media_len: size_t,
+ deadline_monotonic_ms: c_longlong,
+ out: *mut FluxerAVAudioDurationOut,
+ ) -> c_int;
pub fn fluxer_ffmpeg_extract_apng_frames_for_nsfw(
apng_data: *const c_void,
apng_len: size_t,
diff --git a/fluxer_media_proxy/src/native_shim/av_strip.c b/fluxer_media_proxy/src/native_shim/av_strip.c
new file mode 100644
index 000000000..d8e0a2778
--- /dev/null
+++ b/fluxer_media_proxy/src/native_shim/av_strip.c
@@ -0,0 +1,420 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+#include "native_shim_internal.h"
+
+#define FLUXER_AV_STRIP_AVIO_BUFFER_SIZE (64u * 1024u)
+#define FLUXER_AV_STRIP_MAX_MUX_DELAY (7 * AV_TIME_BASE / 10)
+
+typedef struct {
+ struct ff_mem_reader reader;
+ AVIOContext *avio;
+ AVFormatContext *format;
+ long long deadline_monotonic_ms;
+} fluxer_av_strip_input;
+
+static void fluxer_av_strip_input_close(fluxer_av_strip_input *input) {
+ if (input->format != NULL) avformat_close_input(&input->format);
+ if (input->avio != NULL) {
+ if (input->avio->buffer != NULL) av_freep(&input->avio->buffer);
+ avio_context_free(&input->avio);
+ }
+}
+
+static int fluxer_av_strip_input_open(
+ fluxer_av_strip_input *input,
+ const void *media_data,
+ size_t media_len,
+ const char *allowed_formats,
+ long long deadline_monotonic_ms
+) {
+ memset(input, 0, sizeof(*input));
+ if (media_data == NULL || media_len == 0 || allowed_formats == NULL ||
+ deadline_monotonic_ms < 0) {
+ return FLUXER_NATIVE_STATUS_CODEC_FAILURE;
+ }
+ if (media_len > (size_t)INT64_MAX) return FLUXER_NATIVE_STATUS_WORK_LIMIT_EXCEEDED;
+ input->deadline_monotonic_ms = deadline_monotonic_ms;
+ int status = fluxer_native_deadline_status(deadline_monotonic_ms);
+ if (status != FLUXER_NATIVE_STATUS_OK) return status;
+ input->reader.data = (const uint8_t *)media_data;
+ input->reader.len = media_len;
+ unsigned char *buffer = av_malloc(FLUXER_AV_STRIP_AVIO_BUFFER_SIZE);
+ if (buffer == NULL) return FLUXER_NATIVE_STATUS_ALLOCATION_FAILED;
+ input->avio = avio_alloc_context(
+ buffer, FLUXER_AV_STRIP_AVIO_BUFFER_SIZE, 0, &input->reader,
+ ff_mem_read_packet, NULL, ff_mem_seek);
+ if (input->avio == NULL) {
+ av_free(buffer);
+ return FLUXER_NATIVE_STATUS_ALLOCATION_FAILED;
+ }
+ input->format = avformat_alloc_context();
+ if (input->format == NULL) return FLUXER_NATIVE_STATUS_ALLOCATION_FAILED;
+ status = fluxer_restrict_untrusted_av_context(input->format, allowed_formats);
+ if (status != FLUXER_NATIVE_STATUS_OK) return status;
+ av_freep(&input->format->codec_whitelist);
+ input->format->codec_whitelist =
+ av_strdup(FLUXER_ALLOWED_VIDEO_DECODERS "," FLUXER_ALLOWED_AUDIO_DECODERS);
+ if (input->format->codec_whitelist == NULL) return FLUXER_NATIVE_STATUS_ALLOCATION_FAILED;
+ input->format->pb = input->avio;
+ input->format->interrupt_callback.callback = fluxer_ffmpeg_interrupt_deadline;
+ input->format->interrupt_callback.opaque = &input->deadline_monotonic_ms;
+ input->format->flags |= AVFMT_FLAG_CUSTOM_IO;
+ input->format->probesize = 5 * 1024 * 1024;
+ input->format->max_analyze_duration = 5 * AV_TIME_BASE;
+ int rc = avformat_open_input(&input->format, NULL, NULL, NULL);
+ if (rc < 0) {
+ return fluxer_native_status_from_av_error_with_deadline(rc, deadline_monotonic_ms);
+ }
+ rc = input->format->nb_streams > 0
+ ? fluxer_find_stream_info_bounded(input->format)
+ : avformat_find_stream_info(input->format, NULL);
+ if (rc < 0) {
+ return fluxer_native_status_from_av_error_with_deadline(rc, deadline_monotonic_ms);
+ }
+ if (input->format->nb_streams == 0) return FLUXER_NATIVE_STATUS_CODEC_FAILURE;
+ if (input->format->nb_streams > FLUXER_MAX_AV_STREAMS) {
+ return FLUXER_NATIVE_STATUS_WORK_LIMIT_EXCEEDED;
+ }
+ input->format->max_streams = (int)input->format->nb_streams;
+ return FLUXER_NATIVE_STATUS_OK;
+}
+
+static int fluxer_av_strip_copy_stream(AVFormatContext *output, const AVStream *source) {
+ AVStream *stream = avformat_new_stream(output, NULL);
+ if (stream == NULL) return AVERROR(ENOMEM);
+ int rc = avcodec_parameters_copy(stream->codecpar, source->codecpar);
+ if (rc < 0) return rc;
+ AVCodecParameters *par = stream->codecpar;
+ const struct AVCodecTag *const *tags = output->oformat->codec_tag;
+ unsigned int tag = 0;
+ if (tags != NULL && av_codec_get_id(tags, par->codec_tag) != par->codec_id &&
+ av_codec_get_tag2(tags, par->codec_id, &tag)) {
+ par->codec_tag = 0;
+ }
+ if (par->codec_type == AVMEDIA_TYPE_AUDIO) {
+ if (par->codec_id == AV_CODEC_ID_MP3 &&
+ (par->block_align == 1 || par->block_align == 1152 || par->block_align == 576)) {
+ par->block_align = 0;
+ }
+ if (par->codec_id == AV_CODEC_ID_AC3) par->block_align = 0;
+ }
+ if (par->codec_type == AVMEDIA_TYPE_VIDEO) {
+ if (source->sample_aspect_ratio.num > 0) {
+ par->sample_aspect_ratio = source->sample_aspect_ratio;
+ }
+ stream->sample_aspect_ratio = par->sample_aspect_ratio;
+ stream->avg_frame_rate = source->avg_frame_rate;
+ stream->r_frame_rate = source->r_frame_rate;
+ }
+ stream->time_base = source->time_base;
+ stream->disposition = source->disposition;
+ return 0;
+}
+
+static int fluxer_av_strip_map_streams(AVFormatContext *input, AVFormatContext *output, int *map) {
+ static const enum AVMediaType order[] = {
+ AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE,
+ };
+ for (unsigned int i = 0; i < input->nb_streams; i++) map[i] = -1;
+ for (size_t t = 0; t < sizeof(order) / sizeof(order[0]); t++) {
+ for (unsigned int i = 0; i < input->nb_streams; i++) {
+ const AVStream *stream = input->streams[i];
+ if (stream == NULL || stream->codecpar == NULL ||
+ stream->codecpar->codec_type != order[t]) {
+ continue;
+ }
+ int rc = fluxer_av_strip_copy_stream(output, stream);
+ if (rc < 0) return rc;
+ map[i] = (int)output->nb_streams - 1;
+ }
+ }
+ return output->nb_streams > 0 ? 0 : AVERROR_STREAM_NOT_FOUND;
+}
+
+typedef struct {
+ int64_t dts;
+ int64_t next_dts;
+ int64_t last_mux_dts;
+ int saw_first_ts;
+ int started;
+} fluxer_av_strip_track;
+
+static int64_t fluxer_av_strip_estimate_dts(
+ const AVPacket *packet,
+ const AVStream *stream,
+ fluxer_av_strip_track *track
+) {
+ const AVCodecParameters *par = stream->codecpar;
+ AVRational frame_rate = stream->avg_frame_rate;
+ if (!track->saw_first_ts) {
+ track->dts = frame_rate.num > 0 && frame_rate.den > 0
+ ? -(int64_t)par->video_delay * AV_TIME_BASE * frame_rate.den / frame_rate.num
+ : 0;
+ if (packet->pts != AV_NOPTS_VALUE) {
+ track->dts += av_rescale_q(packet->pts, stream->time_base, AV_TIME_BASE_Q);
+ }
+ track->next_dts = track->dts;
+ track->saw_first_ts = 1;
+ }
+ if (packet->dts != AV_NOPTS_VALUE) {
+ track->next_dts = av_rescale_q(packet->dts, stream->time_base, AV_TIME_BASE_Q);
+ }
+ track->dts = track->next_dts;
+ if (packet->duration > 0) {
+ track->next_dts += av_rescale_q(packet->duration, stream->time_base, AV_TIME_BASE_Q);
+ } else if (par->codec_type == AVMEDIA_TYPE_AUDIO && par->sample_rate > 0 && par->frame_size > 0) {
+ track->next_dts += (int64_t)AV_TIME_BASE * par->frame_size / par->sample_rate;
+ } else if (par->codec_type == AVMEDIA_TYPE_VIDEO && frame_rate.num > 0 && frame_rate.den > 0) {
+ track->next_dts += (int64_t)AV_TIME_BASE * frame_rate.den / frame_rate.num;
+ }
+ return track->dts;
+}
+
+static void fluxer_av_strip_retime(
+ AVPacket *packet,
+ const AVStream *source,
+ const AVStream *destination,
+ int64_t start_time,
+ fluxer_av_strip_track *track,
+ int strict_monotonic
+) {
+ int64_t offset = start_time == AV_NOPTS_VALUE
+ ? 0
+ : av_rescale_q(start_time, AV_TIME_BASE_Q, source->time_base);
+ if (packet->pts != AV_NOPTS_VALUE) packet->pts -= offset;
+ if (packet->dts != AV_NOPTS_VALUE) packet->dts -= offset;
+ int64_t estimated_dts = fluxer_av_strip_estimate_dts(packet, source, track);
+ if (packet->dts == AV_NOPTS_VALUE) {
+ packet->dts = av_rescale_q(estimated_dts, AV_TIME_BASE_Q, source->time_base);
+ }
+ av_packet_rescale_ts(packet, source->time_base, destination->time_base);
+ int64_t last = track->last_mux_dts;
+ if (packet->pts != AV_NOPTS_VALUE && packet->dts > packet->pts) {
+ int64_t next = last == AV_NOPTS_VALUE ? packet->dts : last + 1;
+ packet->pts = packet->dts = packet->pts + packet->dts + next -
+ FFMIN3(packet->pts, packet->dts, next) - FFMAX3(packet->pts, packet->dts, next);
+ }
+ if (last != AV_NOPTS_VALUE) {
+ int64_t minimum = last + strict_monotonic;
+ if (packet->dts < minimum) {
+ if (packet->pts != AV_NOPTS_VALUE && packet->pts >= packet->dts) {
+ packet->pts = FFMAX(packet->pts, minimum);
+ }
+ packet->dts = minimum;
+ }
+ }
+ track->last_mux_dts = packet->dts;
+}
+
+static int fluxer_av_strip_remux(
+ fluxer_av_strip_input *input,
+ AVFormatContext *output,
+ int faststart
+) {
+ AVFormatContext *source = input->format;
+ unsigned int mapped_streams = source->nb_streams;
+ int *map = av_calloc(mapped_streams, sizeof(*map));
+ fluxer_av_strip_track *tracks = av_calloc(mapped_streams, sizeof(*tracks));
+ AVPacket *packet = av_packet_alloc();
+ AVDictionary *options = NULL;
+ int rc = map == NULL || tracks == NULL || packet == NULL ? AVERROR(ENOMEM) : 0;
+ if (rc == 0) rc = fluxer_av_strip_map_streams(source, output, map);
+ if (rc == 0 && faststart) rc = av_dict_set(&options, "movflags", "+faststart", 0);
+ if (rc == 0) rc = avio_open2(&output->pb, output->url, AVIO_FLAG_WRITE,
+ &output->interrupt_callback, NULL);
+ if (rc == 0) rc = avformat_write_header(output, &options);
+ int header_written = rc >= 0;
+ if (rc > 0) rc = 0;
+ for (unsigned int i = 0; rc == 0 && i < mapped_streams; i++) {
+ tracks[i].last_mux_dts = AV_NOPTS_VALUE;
+ }
+ int strict_monotonic = !(output->oformat->flags & AVFMT_TS_NONSTRICT);
+ while (rc == 0) {
+ int read_rc = av_read_frame(source, packet);
+ if (read_rc == AVERROR_EOF) break;
+ if (read_rc < 0) {
+ rc = read_rc;
+ break;
+ }
+ int index = packet->stream_index;
+ if (index < 0 || (unsigned int)index >= mapped_streams || map[index] < 0) {
+ av_packet_unref(packet);
+ continue;
+ }
+ fluxer_av_strip_track *track = &tracks[index];
+ if (!track->started && !(packet->flags & AV_PKT_FLAG_KEY)) {
+ av_packet_unref(packet);
+ continue;
+ }
+ track->started = 1;
+ const AVStream *destination = output->streams[map[index]];
+ fluxer_av_strip_retime(packet, source->streams[index], destination,
+ source->start_time, track, strict_monotonic);
+ packet->stream_index = map[index];
+ packet->pos = -1;
+ rc = av_interleaved_write_frame(output, packet);
+ av_packet_unref(packet);
+ }
+ if (header_written) {
+ int trailer_rc = av_write_trailer(output);
+ if (rc == 0) rc = trailer_rc;
+ }
+ if (output->pb != NULL) {
+ int close_rc = avio_closep(&output->pb);
+ if (rc == 0) rc = close_rc;
+ }
+ av_dict_free(&options);
+ av_packet_free(&packet);
+ av_free(tracks);
+ av_free(map);
+ return rc;
+}
+
+int fluxer_av_strip_metadata(
+ const void *media_data,
+ size_t media_len,
+ const char *demuxer,
+ const char *muxer,
+ int faststart,
+ const char *output_path,
+ long long deadline_monotonic_ms
+) {
+ if (demuxer == NULL || muxer == NULL || output_path == NULL ||
+ (faststart != 0 && faststart != 1)) {
+ return FLUXER_NATIVE_STATUS_CODEC_FAILURE;
+ }
+ fluxer_av_strip_input input;
+ int status = fluxer_av_strip_input_open(
+ &input, media_data, media_len, demuxer, deadline_monotonic_ms);
+ if (status != FLUXER_NATIVE_STATUS_OK) {
+ fluxer_av_strip_input_close(&input);
+ return status;
+ }
+ AVFormatContext *output = NULL;
+ int rc = avformat_alloc_output_context2(&output, NULL, muxer, output_path);
+ if (rc >= 0 && output != NULL) {
+ output->interrupt_callback = input.format->interrupt_callback;
+ output->max_delay = FLUXER_AV_STRIP_MAX_MUX_DELAY;
+ output->protocol_whitelist = av_strdup("file");
+ rc = output->protocol_whitelist == NULL
+ ? AVERROR(ENOMEM)
+ : fluxer_av_strip_remux(&input, output, faststart);
+ } else if (rc >= 0) {
+ rc = AVERROR(ENOMEM);
+ }
+ if (output != NULL) avformat_free_context(output);
+ fluxer_av_strip_input_close(&input);
+ return rc < 0
+ ? fluxer_native_status_from_av_error_with_deadline(rc, deadline_monotonic_ms)
+ : FLUXER_NATIVE_STATUS_OK;
+}
+
+static int fluxer_av_audio_decoder_allowed(const AVCodec *decoder) {
+ return decoder != NULL &&
+ av_match_list(decoder->name, FLUXER_ALLOWED_AUDIO_DECODERS, ',') > 0;
+}
+
+static int fluxer_av_sum_audio_frames(
+ fluxer_av_strip_input *input,
+ int stream_index,
+ double *out_seconds,
+ int *out_frames
+) {
+ const AVStream *stream = input->format->streams[stream_index];
+ const AVCodec *decoder = avcodec_find_decoder(stream->codecpar->codec_id);
+ if (!fluxer_av_audio_decoder_allowed(decoder)) return FLUXER_NATIVE_STATUS_UNSUPPORTED;
+ AVCodecContext *context = avcodec_alloc_context3(decoder);
+ AVPacket *packet = av_packet_alloc();
+ AVFrame *frame = av_frame_alloc();
+ int rc = context == NULL || packet == NULL || frame == NULL ? AVERROR(ENOMEM) : 0;
+ if (rc == 0) rc = avcodec_parameters_to_context(context, stream->codecpar);
+ if (rc == 0) {
+ context->pkt_timebase = stream->time_base;
+ context->thread_count = 1;
+ rc = avcodec_open2(context, decoder, NULL);
+ }
+ int64_t total = 0;
+ int counted = 0;
+ int draining = 0;
+ while (rc >= 0) {
+ int status = fluxer_native_deadline_status(input->deadline_monotonic_ms);
+ if (status != FLUXER_NATIVE_STATUS_OK) {
+ avcodec_free_context(&context);
+ av_packet_free(&packet);
+ av_frame_free(&frame);
+ return status;
+ }
+ if (!draining) {
+ int read_rc = av_read_frame(input->format, packet);
+ if (read_rc == AVERROR_EOF) {
+ draining = 1;
+ avcodec_send_packet(context, NULL);
+ } else if (read_rc < 0) {
+ rc = read_rc;
+ break;
+ } else {
+ if (packet->stream_index == stream_index) avcodec_send_packet(context, packet);
+ av_packet_unref(packet);
+ }
+ }
+ for (;;) {
+ int receive_rc = avcodec_receive_frame(context, frame);
+ if (receive_rc < 0) {
+ if (draining || receive_rc == AVERROR_EOF) rc = AVERROR_EOF;
+ break;
+ }
+ if (frame->duration > 0) {
+ total += frame->duration;
+ counted++;
+ }
+ av_frame_unref(frame);
+ }
+ }
+ avcodec_free_context(&context);
+ av_packet_free(&packet);
+ av_frame_free(&frame);
+ if (rc < 0 && rc != AVERROR_EOF) {
+ return fluxer_native_status_from_av_error_with_deadline(rc, input->deadline_monotonic_ms);
+ }
+ *out_frames = counted;
+ *out_seconds = (double)total * av_q2d(stream->time_base);
+ return FLUXER_NATIVE_STATUS_OK;
+}
+
+int fluxer_av_audio_duration(
+ const void *media_data,
+ size_t media_len,
+ long long deadline_monotonic_ms,
+ struct fluxer_av_audio_duration_out *out
+) {
+ if (out == NULL) return FLUXER_NATIVE_STATUS_CODEC_FAILURE;
+ memset(out, 0, sizeof(*out));
+ fluxer_av_strip_input input;
+ int status = fluxer_av_strip_input_open(
+ &input, media_data, media_len, FLUXER_AV_INPUT_FORMATS, deadline_monotonic_ms);
+ int stream_index = -1;
+ if (status == FLUXER_NATIVE_STATUS_OK) {
+ for (unsigned int i = 0; i < input.format->nb_streams; i++) {
+ const AVStream *stream = input.format->streams[i];
+ if (stream != NULL && stream->codecpar != NULL &&
+ stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
+ stream_index = (int)i;
+ break;
+ }
+ }
+ if (stream_index < 0) status = FLUXER_NATIVE_STATUS_UNSUPPORTED;
+ }
+ if (status == FLUXER_NATIVE_STATUS_OK) {
+ const AVStream *stream = input.format->streams[stream_index];
+ if (stream->duration != AV_NOPTS_VALUE) {
+ out->stream_seconds = (double)stream->duration * av_q2d(stream->time_base);
+ }
+ if (input.format->duration != AV_NOPTS_VALUE) {
+ out->format_seconds = (double)input.format->duration / (double)AV_TIME_BASE;
+ }
+ status = fluxer_av_sum_audio_frames(
+ &input, stream_index, &out->frames_seconds, &out->frame_count);
+ }
+ fluxer_av_strip_input_close(&input);
+ return status;
+}
diff --git a/fluxer_media_proxy/src/native_shim/native_shim_internal.h b/fluxer_media_proxy/src/native_shim/native_shim_internal.h
index 53d7626fe..4d18559c3 100644
--- a/fluxer_media_proxy/src/native_shim/native_shim_internal.h
+++ b/fluxer_media_proxy/src/native_shim/native_shim_internal.h
@@ -19,6 +19,7 @@
#include <libavformat/avformat.h>
#include <libavutil/display.h>
#include <libavutil/imgutils.h>
+#include <libavutil/avstring.h>
#include <libavutil/log.h>
#include <libavutil/mem.h>
#include <libavutil/opt.h>
@@ -58,6 +59,12 @@
"gif,apng,h264,hevc,vp8,vp9,libvpx-vp9,av1,libaom-av1,libdav1d," \
"mpeg1video,mpeg2video,mpeg4,h263,theora,flv,vp6,vp6f,vp6a," \
"wmv1,wmv2,wmv3,vc1,mjpeg,bmp"
+#define FLUXER_ALLOWED_AUDIO_DECODERS \
+ "aac,aac_fixed,aac_latm,mp1,mp1float,mp2,mp2float,mp3,mp3float,mp3adu," \
+ "mp3adufloat,vorbis,opus,flac,alac,ac3,ac3_fixed,eac3,wmav1,wmav2,amrnb," \
+ "amrwb,adpcm_ima_wav,adpcm_ms,pcm_alaw,pcm_mulaw,pcm_s8,pcm_u8,pcm_s16le," \
+ "pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be," \
+ "pcm_f64le,pcm_f64be"
#define FLUXER_AV_INPUT_FORMATS \
"mov,matroska,webm,avi,flv,ogg,mpegts,mpeg,mpegvideo,asf,mp3,wav,flac,aac,aiff"
#define FLUXER_AV_BMP_INPUT_FORMAT "bmp_pipe"
diff --git a/fluxer_media_proxy/src/native_shim/vips_image.c b/fluxer_media_proxy/src/native_shim/vips_image.c
index 00d6001cc..8a6894b85 100644
--- a/fluxer_media_proxy/src/native_shim/vips_image.c
+++ b/fluxer_media_proxy/src/native_shim/vips_image.c
@@ -207,6 +207,40 @@ int fluxer_vips_autorot(
return fluxer_vips_operation_status(rc, out);
}
+int fluxer_vips_srgb_without_alpha(VipsImage *in, VipsImage **out) {
+ if (out == NULL) return FLUXER_NATIVE_STATUS_CODEC_FAILURE;
+ *out = NULL;
+ if (in == NULL) return FLUXER_NATIVE_STATUS_CODEC_FAILURE;
+ VipsImage *srgb = NULL;
+ int rc;
+ if (vips_image_get_interpretation(in) == VIPS_INTERPRETATION_CMYK) {
+ rc = vips_icc_transform(
+ in, &srgb, "srgb",
+ "embedded", TRUE,
+ "input_profile", "cmyk",
+ "intent", VIPS_INTENT_RELATIVE,
+ NULL);
+ } else if (vips_image_get_typeof(in, VIPS_META_ICC_NAME) != 0) {
+ rc = vips_icc_transform(
+ in, &srgb, "srgb",
+ "embedded", TRUE,
+ "intent", VIPS_INTENT_RELATIVE,
+ "depth", 8,
+ NULL);
+ } else {
+ rc = vips_colourspace(in, &srgb, VIPS_INTERPRETATION_sRGB, NULL);
+ }
+ int status = fluxer_vips_operation_status(rc, &srgb);
+ if (status != FLUXER_NATIVE_STATUS_OK) return status;
+ if (!vips_image_hasalpha(srgb)) {
+ *out = srgb;
+ return FLUXER_NATIVE_STATUS_OK;
+ }
+ rc = vips_extract_band(srgb, out, 0, "n", vips_image_get_bands(srgb) - 1, NULL);
+ g_object_unref(srgb);
+ return fluxer_vips_operation_status(rc, out);
+}
+
int fluxer_vips_extract_area(VipsImage *in, VipsImage **out, int left, int top, int width, int height) {
if (out == NULL) return FLUXER_NATIVE_STATUS_CODEC_FAILURE;
*out = NULL;
diff --git a/fluxer_media_proxy/src/server/media_operations/failure.rs b/fluxer_media_proxy/src/server/media_operations/failure.rs
index 8cf69379d..5bcf42a9c 100644
--- a/fluxer_media_proxy/src/server/media_operations/failure.rs
+++ b/fluxer_media_proxy/src/server/media_operations/failure.rs
@@ -24,6 +24,10 @@ pub(in crate::server) enum MediaFailure {
MetadataSvgRasterizeTimeout { detail: String },
MetadataSvgRasterizeFailed { detail: String },
MetadataExtractionFailed { detail: String },
+ StripUnsupportedType,
+ StripSpoolExhausted,
+ StripTimeout,
+ StripFailed { detail: String },
}
impl MediaFailure {
@@ -49,6 +53,10 @@ impl MediaFailure {
Self::MetadataSvgRasterizeTimeout { .. } => "metadata_svg_rasterize_timeout",
Self::MetadataSvgRasterizeFailed { .. } => "metadata_svg_rasterize_failed",
Self::MetadataExtractionFailed { .. } => "metadata_extraction_failed",
+ Self::StripUnsupportedType => "strip_unsupported_type",
+ Self::StripSpoolExhausted => "strip_spool_exhausted",
+ Self::StripTimeout => "strip_timeout",
+ Self::StripFailed { .. } => "strip_failed",
}
}
@@ -63,7 +71,11 @@ impl MediaFailure {
| Self::MetadataS3Read
| Self::ExternalSourceBlocked
| Self::MetadataSvgRasterizeFailed { .. }
- | Self::MetadataExtractionFailed { .. } => StatusCode::BAD_REQUEST,
+ | Self::MetadataExtractionFailed { .. }
+ | Self::StripFailed { .. } => StatusCode::BAD_REQUEST,
+ Self::StripUnsupportedType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
+ Self::StripSpoolExhausted => StatusCode::SERVICE_UNAVAILABLE,
+ Self::StripTimeout => StatusCode::GATEWAY_TIMEOUT,
Self::ExternalSourcePayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
Self::ExternalSourceBufferBudgetExhausted
| Self::ExternalSourceBufferAllocationFailed => StatusCode::SERVICE_UNAVAILABLE,
@@ -89,7 +101,8 @@ impl MediaFailure {
match self {
Self::MetadataSvgRasterizeTimeout { detail }
| Self::MetadataSvgRasterizeFailed { detail }
- | Self::MetadataExtractionFailed { detail } => Some(detail),
+ | Self::MetadataExtractionFailed { detail }
+ | Self::StripFailed { detail } => Some(detail),
_ => None,
}
}
diff --git a/fluxer_media_proxy/src/server/media_operations/mod.rs b/fluxer_media_proxy/src/server/media_operations/mod.rs
index 97ae5ab24..416ba3274 100644
--- a/fluxer_media_proxy/src/server/media_operations/mod.rs
+++ b/fluxer_media_proxy/src/server/media_operations/mod.rs
@@ -2,12 +2,14 @@
mod failure;
mod input;
+mod strip;
pub(in crate::server) use failure::MediaFailure;
pub(in crate::server) use input::{
MediaInput, MediaInputLimit, STORED_SNIFF_PREFIX_BYTES, load_media_input, read_sniff_prefix,
spool_stored_media,
};
+pub(in crate::server) use strip::{StrippedMedia, probe_audio_duration, strip_media};
use crate::{
constants::{self, AssetExtension},
diff --git a/fluxer_media_proxy/src/server/media_operations/strip.rs b/fluxer_media_proxy/src/server/media_operations/strip.rs
new file mode 100644
index 000000000..34c972b83
--- /dev/null
+++ b/fluxer_media_proxy/src/server/media_operations/strip.rs
@@ -0,0 +1,184 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+use super::{MediaFailure, MediaInput, MediaInputLimit, load_media_input};
+use crate::{
+ media_process::{self, MediaError},
+ metrics, mime,
+ server::{state::AppState, transform::execution::deadline_instant},
+ upload_relay::{release_spool_budget, try_reserve_spool_budget},
+};
+use bytes::Bytes;
+use memmap2::Mmap;
+
+const AV_STRIP_TIMEOUT_MS: i64 = 10 * 60 * 1000;
+const AUDIO_DURATION_TIMEOUT_MS: i64 = 5_000;
+
+pub(in crate::server) struct StrippedMedia {
+ pub(in crate::server) data: Bytes,
+ pub(in crate::server) content_type: String,
+ pub(in crate::server) dimensions: Option<(u32, u32)>,
+}
+
+struct SpoolReservation(u64);
+
+impl SpoolReservation {
+ fn try_new(bytes: u64, ceiling: u64) -> Option<Self> {
+ try_reserve_spool_budget(bytes, ceiling).then_some(Self(bytes))
+ }
+}
+
+impl Drop for SpoolReservation {
+ fn drop(&mut self) {
+ release_spool_budget(self.0);
+ }
+}
+
+struct StrippedFile {
+ map: Mmap,
+ _reservation: SpoolReservation,
+}
+
+impl AsRef<[u8]> for StrippedFile {
+ fn as_ref(&self) -> &[u8] {
+ &self.map
+ }
+}
+
+fn normalize_content_type(content_type: &str) -> String {
+ content_type
+ .split(';')
+ .next()
+ .unwrap_or_default()
+ .trim()
+ .to_ascii_lowercase()
+}
+
+fn strip_failure(error: &anyhow::Error) -> MediaFailure {
+ match error.downcast_ref::<MediaError>() {
+ Some(MediaError::UnsupportedMediaType) => MediaFailure::StripUnsupportedType,
+ Some(MediaError::RequestTimeout) => MediaFailure::StripTimeout,
+ _ => MediaFailure::StripFailed {
+ detail: format!("{error:?}"),
+ },
+ }
+}
+
+pub(in crate::server) async fn strip_media(
+ app: &AppState,
+ input: MediaInput,
+ content_type: Option<String>,
+) -> Result<StrippedMedia, MediaFailure> {
+ let input = load_media_input(app, input, MediaInputLimit::INTERNAL_REQUEST).await?;
+ let content_type = match content_type {
+ Some(content_type) => normalize_content_type(&content_type),
+ None => mime::sniff(&input.data).mime.to_owned(),
+ };
+ match mime::category(&content_type) {
+ Some(mime::Category::Image) => strip_image(app, input.data).await,
+ Some(mime::Category::Video | mime::Category::Audio) => {
+ strip_av(app, input.data, content_type).await
+ }
+ None => Err(MediaFailure::StripUnsupportedType),
+ }
+}
+
+async fn strip_image(app: &AppState, data: Bytes) -> Result<StrippedMedia, MediaFailure> {
+ if !media_process::strips_image(mime::sniff(&data).mime) {
+ return Err(MediaFailure::StripUnsupportedType);
+ }
+ let runtime = app.media.transforms();
+ let deadline_ms = runtime.transform_deadline_ms();
+ let media_limits = runtime.limits();
+ let cost_data = data.clone();
+ let stripped = runtime
+ .tasks()
+ .run_native(
+ deadline_instant(deadline_ms),
+ move || Ok(media_process::metadata_cost(&cost_data, &media_limits)?),
+ move || {
+ Ok(media_process::strip_image_metadata(
+ &data,
+ &media_limits,
+ deadline_ms,
+ )?)
+ },
+ )
+ .await
+ .map_err(|error| strip_failure(&error))?;
+ Ok(StrippedMedia {
+ data: Bytes::from(stripped.bytes),
+ content_type: stripped.content_type.to_owned(),
+ dimensions: Some((stripped.width, stripped.height)),
+ })
+}
+
+async fn strip_av(
+ app: &AppState,
+ data: Bytes,
+ content_type: String,
+) -> Result<StrippedMedia, MediaFailure> {
+ let container =
+ media_process::av_container(&content_type).ok_or(MediaFailure::StripUnsupportedType)?;
+ let relay = &app.cfg.upload_relay;
+ let reservation = SpoolReservation::try_new(data.len() as u64, relay.spool_max_total_bytes)
+ .ok_or(MediaFailure::StripSpoolExhausted)?;
+ let output = tempfile::NamedTempFile::new_in(&relay.spool_dir).map_err(|error| {
+ MediaFailure::StripFailed {
+ detail: format!("spool file: {error}"),
+ }
+ })?;
+ let path = output.path().to_owned();
+ let deadline_ms = metrics::now_ms() + AV_STRIP_TIMEOUT_MS;
+ let cost = media_process::av_native_cost(data.len());
+ app.media
+ .transforms()
+ .tasks()
+ .run_native(
+ deadline_instant(Some(deadline_ms)),
+ move || Ok(cost),
+ move || {
+ media_process::strip_av_metadata(&data, container, &path, Some(deadline_ms))?;
+ Ok(())
+ },
+ )
+ .await
+ .map_err(|error| strip_failure(&error))?;
+ let map =
+ unsafe { Mmap::map(output.as_file()) }.map_err(|error| MediaFailure::StripFailed {
+ detail: format!("map stripped output: {error}"),
+ })?;
+ drop(output);
+ Ok(StrippedMedia {
+ data: Bytes::from_owner(StrippedFile {
+ map,
+ _reservation: reservation,
+ }),
+ content_type,
+ dimensions: None,
+ })
+}
+
+pub(in crate::server) async fn probe_audio_duration(
+ app: &AppState,
+ input: MediaInput,
+) -> Result<Option<f64>, MediaFailure> {
+ let input = load_media_input(app, input, MediaInputLimit::INTERNAL_REQUEST).await?;
+ let deadline_ms = metrics::now_ms() + AUDIO_DURATION_TIMEOUT_MS;
+ let cost = media_process::av_native_cost(input.data.len());
+ let data = input.data;
+ app.media
+ .transforms()
+ .tasks()
+ .run_native(
+ deadline_instant(Some(deadline_ms)),
+ move || Ok(cost),
+ move || {
+ Ok(media_process::audio_duration_seconds(
+ &data,
+ Some(deadline_ms),
+ )?)
+ },
+ )
+ .await
+ .map_err(|error| strip_failure(&error))
+}
diff --git a/fluxer_media_proxy/src/server/routes/internal.rs b/fluxer_media_proxy/src/server/routes/internal.rs
index 8400b2a7d..91e154af2 100644
--- a/fluxer_media_proxy/src/server/routes/internal.rs
+++ b/fluxer_media_proxy/src/server/routes/internal.rs
@@ -11,7 +11,8 @@ use crate::{
format_policy::is_svg_content_type,
media_operations::{
MediaFailure, MediaInput, MediaInputLimit, MetadataOutput, STORED_SNIFF_PREFIX_BYTES,
- load_media_input, read_sniff_prefix, resolve_metadata,
+ StrippedMedia, load_media_input, probe_audio_duration, read_sniff_prefix,
+ resolve_metadata, strip_media,
},
response::{
GeneratedMediaResponse,
@@ -37,6 +38,9 @@ use bytes::Bytes;
use serde::Deserialize;
use std::sync::Arc;
+const MEDIA_WIDTH_HEADER: &str = "x-fluxer-media-width";
+const MEDIA_HEIGHT_HEADER: &str = "x-fluxer-media-height";
+
#[derive(Debug, Deserialize)]
struct MetadataRequest {
version: Option<i64>,
@@ -109,6 +113,36 @@ impl FramesRequest {
}
}
+#[derive(Debug, Deserialize)]
+struct MediaSourceRequest {
+ #[serde(rename = "type")]
+ typ: String,
+ base64: Option<String>,
+ upload_filename: Option<String>,
+ filename: Option<String>,
+ bucket: Option<String>,
+ key: Option<String>,
+ content_type: Option<String>,
+}
+
+impl MediaSourceRequest {
+ fn into_parts(self) -> (MetadataRequest, Option<String>) {
+ let request = MetadataRequest {
+ version: None,
+ typ: self.typ,
+ nsfw: "allow".to_owned(),
+ base64: self.base64,
+ upload_filename: self.upload_filename,
+ filename: self.filename,
+ bucket: self.bucket,
+ key: self.key,
+ url: None,
+ with_base64: None,
+ };
+ (request, self.content_type)
+ }
+}
+
#[derive(Debug, Deserialize)]
struct UploadFileRequest {
upload_filename: String,
@@ -333,6 +367,75 @@ pub(in crate::server) async fn sniff_handler(
)
}
+async fn read_media_source(
+ app: &AppState,
+ headers: &HeaderMap,
+ request: Request<Body>,
+) -> Result<(MediaInput, Option<String>), Box<Response>> {
+ if !check_internal_auth(headers, app.cfg.secret_key.expose()) {
+ return Err(Box::new(text(StatusCode::UNAUTHORIZED, "Unauthorized")));
+ }
+ let body = read_limited_body(request)
+ .await
+ .map_err(|status| Box::new(text(status, canonical_reason_str(status))))?;
+ let req: MediaSourceRequest = serde_json::from_slice(&body)
+ .map_err(|_| Box::new(text(StatusCode::BAD_REQUEST, "Bad Request")))?;
+ let (request, content_type) = req.into_parts();
+ let input = request
+ .into_media_input()
+ .map_err(|failure| Box::new(failure.into_response()))?;
+ Ok((input, content_type))
+}
+
+pub(in crate::server) async fn strip_handler(
+ State(app): State<Arc<AppState>>,
+ headers: HeaderMap,
+ request: Request<Body>,
+) -> Response {
+ let (input, content_type) = match read_media_source(&app, &headers, request).await {
+ Ok(source) => source,
+ Err(response) => return *response,
+ };
+ let StrippedMedia {
+ data,
+ content_type,
+ dimensions,
+ } = match strip_media(&app, input, content_type).await {
+ Ok(stripped) => stripped,
+ Err(failure) => return failure.into_response(),
+ };
+ let mut builder = Response::builder()
+ .status(StatusCode::OK)
+ .header(header::CONTENT_TYPE, content_type)
+ .header(header::CONTENT_LENGTH, data.len());
+ if let Some((width, height)) = dimensions {
+ builder = builder
+ .header(MEDIA_WIDTH_HEADER, width)
+ .header(MEDIA_HEIGHT_HEADER, height);
+ }
+ builder
+ .body(Body::from(data))
+ .unwrap_or_else(|_| text(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error"))
+}
+
+pub(in crate::server) async fn audio_duration_handler(
+ State(app): State<Arc<AppState>>,
+ headers: HeaderMap,
+ request: Request<Body>,
+) -> Response {
+ let (input, _) = match read_media_source(&app, &headers, request).await {
+ Ok(source) => source,
+ Err(response) => return *response,
+ };
+ match probe_audio_duration(&app, input).await {
+ Ok(duration) => json_response(
+ StatusCode::OK,
+ serde_json::json!({ "duration_seconds": duration }).to_string(),
+ ),
+ Err(failure) => failure.into_response(),
+ }
+}
+
fn check_internal_auth(headers: &HeaderMap, secret: &str) -> bool {
let Some(auth) = headers
.get(header::AUTHORIZATION)
diff --git a/fluxer_media_proxy/src/server/runtime.rs b/fluxer_media_proxy/src/server/runtime.rs
index ec7f4416f..d5e08e3d2 100644
--- a/fluxer_media_proxy/src/server/runtime.rs
+++ b/fluxer_media_proxy/src/server/runtime.rs
@@ -115,6 +115,11 @@ fn build_router(state: Arc<AppState>, drain: HttpRequestDrain) -> Router {
.route("/_sniff", post(routes::internal::sniff_handler))
.route("/_thumbnail", post(routes::internal::thumbnail_handler))
.route("/_frames", post(routes::internal::frames_handler))
+ .route("/_strip", post(routes::internal::strip_handler))
+ .route(
+ "/_audio_duration",
+ post(routes::internal::audio_duration_handler),
+ )
.route(
"/v1/relay/{*key}",
put(routes::relay::relay_put).options(routes::relay::relay_options),
diff --git a/fluxer_media_proxy/src/test_fixtures.rs b/fluxer_media_proxy/src/test_fixtures.rs
index 78b4dfd2f..89187227e 100644
--- a/fluxer_media_proxy/src/test_fixtures.rs
+++ b/fluxer_media_proxy/src/test_fixtures.rs
@@ -35,6 +35,10 @@ pub const ADVERSARIAL_TEXT_INPUTS: &[&str] = &[
];
pub fn synthetic_png(width: u32, height: u32) -> Vec<u8> {
+ synthetic_image(width, height, ".png[strip]")
+}
+
+pub fn synthetic_image(width: u32, height: u32, suffix: &str) -> Vec<u8> {
ensure_vips_init().unwrap();
let mut pixels = vec![0u8; width as usize * height as usize * 4];
for y in 0..height {
@@ -57,7 +61,7 @@ pub fn synthetic_png(width: u32, height: u32) -> Vec<u8> {
)
};
let image = unsafe { native::VipsImageHandle::from_raw_owned(image) }.unwrap();
- let suffix = CString::new(".png[strip]").unwrap();
+ let suffix = CString::new(suffix).unwrap();
let mut out_ptr: *mut c_void = ptr::null_mut();
let mut out_size: size_t = 0;
let rc = unsafe {
diff --git a/fluxer_media_proxy/src/vips_shim.h b/fluxer_media_proxy/src/vips_shim.h
index 5e0948e19..4bb828acf 100644
--- a/fluxer_media_proxy/src/vips_shim.h
+++ b/fluxer_media_proxy/src/vips_shim.h
@@ -57,6 +57,7 @@ int fluxer_vips_set_animation_loop_count(VipsImage *image, int loop_count);
int fluxer_vips_read_delays_ms(VipsImage *image, int n_pages, int **out_delays, int *out_len);
int fluxer_vips_autorot(
VipsImage *in, long long deadline_monotonic_ms, VipsImage **out);
+int fluxer_vips_srgb_without_alpha(VipsImage *in, VipsImage **out);
int fluxer_vips_extract_area(VipsImage *in, VipsImage **out, int left, int top, int width, int height);
int fluxer_vips_resize(VipsImage *in, VipsImage **out, double scale);
int fluxer_vips_join_animation_pages(
@@ -164,6 +165,30 @@ int fluxer_av_metadata(
struct fluxer_av_metadata_out *out
);
+int fluxer_av_strip_metadata(
+ const void *media_data,
+ size_t media_len,
+ const char *demuxer,
+ const char *muxer,
+ int faststart,
+ const char *output_path,
+ long long deadline_monotonic_ms
+);
+
+struct fluxer_av_audio_duration_out {
+ double frames_seconds;
+ int frame_count;
+ double stream_seconds;
+ double format_seconds;
+};
+
+int fluxer_av_audio_duration(
+ const void *media_data,
+ size_t media_len,
+ long long deadline_monotonic_ms,
+ struct fluxer_av_audio_duration_out *out
+);
+
int fluxer_ffmpeg_decode_apng(
const void *apng_data,
size_t apng_len,
diff --git a/fluxer_media_proxy/tools/install-native-deps.sh b/fluxer_media_proxy/tools/install-native-deps.sh
index 088691189..daac69f5e 100755
--- a/fluxer_media_proxy/tools/install-native-deps.sh
+++ b/fluxer_media_proxy/tools/install-native-deps.sh
@@ -22,9 +22,10 @@ LIBHEIF_FLOOR_REASON="src/native_shim/heif_pixels.c compiles a different HEIF de
FFMPEG_BUILD_MODULES="zlib dav1d aom"
LIBHEIF_BUILD_MODULES="libde265 dav1d aom"
-REQUIRED_DECODERS="apng gif h264 hevc vp8 vp9 libdav1d libaom-av1 mjpeg png webp bmp"
+REQUIRED_DECODERS="apng gif h264 hevc vp8 vp9 libdav1d libaom-av1 mjpeg png webp bmp aac mp3float vorbis opus flac alac pcm_s16le"
REQUIRED_ENCODERS="gif"
-REQUIRED_DEMUXERS="apng bmp_pipe gif"
+REQUIRED_DEMUXERS="apng bmp_pipe gif mov,mp4,m4a,3gp,3g2,mj2 matroska,webm avi flv mpegts mpeg asf mp3 wav flac aac aiff ogg"
+REQUIRED_MUXERS="3gp mp4 mov webm matroska avi flv mpegts mpeg asf mp3 wav flac adts aiff ogg"
log() { printf '==> %s\n' "$*" >&2; }
@@ -231,6 +232,8 @@ verify_ffmpeg_codecs() {
require_listed "$listing" encoder "$REQUIRED_ENCODERS"
listing="$(ffmpeg_listing "$binary" -demuxers)"
require_listed "$listing" demuxer "$REQUIRED_DEMUXERS"
+ listing="$(ffmpeg_listing "$binary" -muxers)"
+ require_listed "$listing" muxer "$REQUIRED_MUXERS"
}
if [ "$(uname -s)" = "Darwin" ]; then