1use std::fmt;
30
31use rff_codec::CodecRegistry;
32use rff_core::{CodecId, MediaType};
33use rff_format::{FormatRegistry, MuxCaps};
34
35mod json;
36pub use json::matrix_to_json;
37
38#[cfg(test)]
39mod tests;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct SourceStream {
52 pub index: usize,
53 pub media_type: MediaType,
54 pub codec_id: CodecId,
55}
56
57impl SourceStream {
58 pub fn new(index: usize, media_type: MediaType, codec_id: CodecId) -> SourceStream {
59 SourceStream {
60 index,
61 media_type,
62 codec_id,
63 }
64 }
65}
66
67impl From<&rff_format::Stream> for SourceStream {
68 fn from(s: &rff_format::Stream) -> SourceStream {
69 SourceStream {
70 index: s.index,
71 media_type: s.media_type,
72 codec_id: s.codec_id,
73 }
74 }
75}
76
77#[derive(Debug, Clone)]
84pub struct Plan {
85 pub source: Vec<SourceStream>,
87 pub source_format: Option<String>,
89 pub targets: Vec<Target>,
91}
92
93impl Plan {
94 pub fn stream_copies(&self) -> impl Iterator<Item = &Target> {
96 self.targets.iter().filter(|t| t.fidelity == Fidelity::Copy)
97 }
98
99 pub fn of_kind(&self, kind: TargetKind) -> impl Iterator<Item = &Target> + '_ {
101 self.targets.iter().filter(move |t| t.kind == kind)
102 }
103
104 pub fn target(&self, format: &str) -> Option<&Target> {
106 self.targets.iter().find(|t| t.format == format)
107 }
108}
109
110#[derive(Debug, Clone)]
112pub struct Target {
113 pub format: &'static str,
115 pub long_name: &'static str,
116 pub extension: &'static str,
118 pub extensions: &'static [&'static str],
120 pub kind: TargetKind,
121 pub streams: Vec<StreamPlan>,
123 pub fidelity: Fidelity,
124 pub notes: Vec<String>,
127 pub args: Vec<String>,
131}
132
133impl Target {
134 pub fn kept(&self) -> impl Iterator<Item = &StreamPlan> {
136 self.streams.iter().filter(|s| !s.action.is_drop())
137 }
138
139 pub fn dropped(&self) -> impl Iterator<Item = &StreamPlan> {
141 self.streams.iter().filter(|s| s.action.is_drop())
142 }
143
144 pub fn stream_summary(&self) -> String {
146 let mut parts: Vec<String> = self.kept().map(|s| s.summary()).collect();
147 if parts.is_empty() {
148 parts.push("nothing".into());
149 }
150 let mut s = parts.join(" + ");
151 let dropped = self.dropped().count();
152 if dropped > 0 {
153 s.push_str(&format!(", {dropped} dropped"));
154 }
155 s
156 }
157
158 pub fn summary(&self) -> String {
161 format!("{} ({})", self.stream_summary(), self.fidelity)
162 }
163
164 pub fn command(&self, input: &str, output_stem: &str) -> String {
166 let mut s = format!("rff -i {input}");
167 for a in &self.args {
168 s.push(' ');
169 s.push_str(a);
170 }
171 format!("{s} {output_stem}.{}", self.extension)
172 }
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177pub enum TargetKind {
178 Video,
180 Audio,
182 Image,
184 Subtitle,
186}
187
188impl TargetKind {
189 pub fn name(self) -> &'static str {
190 match self {
191 TargetKind::Video => "video",
192 TargetKind::Audio => "audio",
193 TargetKind::Image => "image",
194 TargetKind::Subtitle => "subtitle",
195 }
196 }
197}
198
199impl fmt::Display for TargetKind {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 f.pad(self.name())
202 }
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
209pub enum Fidelity {
210 Copy,
212 Lossless,
214 Lossy,
216}
217
218impl Fidelity {
219 pub fn name(self) -> &'static str {
220 match self {
221 Fidelity::Copy => "copy",
222 Fidelity::Lossless => "lossless",
223 Fidelity::Lossy => "lossy",
224 }
225 }
226}
227
228impl fmt::Display for Fidelity {
229 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230 f.pad(self.name())
231 }
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub struct StreamPlan {
237 pub input_index: usize,
238 pub media_type: MediaType,
239 pub from: CodecId,
240 pub action: Action,
241}
242
243impl StreamPlan {
244 pub fn summary(&self) -> String {
246 match self.action {
247 Action::Copy => format!("{} copy", self.from),
248 Action::Transcode { to, .. } => format!("{}->{}", self.from, to),
249 Action::Drop(reason) => format!("{} dropped ({reason})", self.from),
250 }
251 }
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub enum Action {
257 Copy,
259 Transcode { to: CodecId, lossy: bool },
261 Drop(DropReason),
263}
264
265impl Action {
266 pub fn is_drop(&self) -> bool {
267 matches!(self, Action::Drop(_))
268 }
269}
270
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum DropReason {
274 UnsupportedMedia,
276 NoEncoder,
278 NoDecoder,
280 ContainerFull,
282}
283
284impl DropReason {
285 pub fn name(self) -> &'static str {
287 match self {
288 DropReason::UnsupportedMedia => "unsupported-media",
289 DropReason::NoEncoder => "no-encoder",
290 DropReason::NoDecoder => "no-decoder",
291 DropReason::ContainerFull => "container-full",
292 }
293 }
294
295 fn explain(self) -> &'static str {
296 match self {
297 DropReason::UnsupportedMedia => "container carries no stream of this type",
298 DropReason::NoEncoder => "no encoder for any codec this container accepts",
299 DropReason::NoDecoder => "no decoder for the source codec",
300 DropReason::ContainerFull => "container is full",
301 }
302 }
303}
304
305impl fmt::Display for DropReason {
306 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
307 f.pad(self.explain())
308 }
309}
310
311pub fn is_lossless(id: CodecId) -> bool {
321 matches!(
322 id,
323 CodecId::Png
324 | CodecId::Flac
325 | CodecId::Pcm
326 | CodecId::RawVideo
327 | CodecId::Webp
328 | CodecId::Subrip
329 | CodecId::WebVtt
330 )
331}
332
333fn encodes_stills_only(id: CodecId) -> bool {
337 matches!(id, CodecId::Avif)
338}
339
340fn is_text_subtitle(id: CodecId) -> bool {
343 matches!(id, CodecId::Subrip | CodecId::WebVtt)
344}
345
346fn preference(media: MediaType) -> &'static [CodecId] {
349 match media {
350 MediaType::Video => &[
351 CodecId::H264,
352 CodecId::Vp9,
353 CodecId::Av2,
354 CodecId::Avif,
355 CodecId::Jpeg,
356 CodecId::Png,
357 CodecId::Webp,
358 CodecId::Gif,
359 CodecId::Jxl,
360 CodecId::Exr,
361 CodecId::RawVideo,
362 ],
363 MediaType::Audio => &[
364 CodecId::Opus,
365 CodecId::Aac,
366 CodecId::Flac,
367 CodecId::Mp3,
368 CodecId::Vorbis,
369 CodecId::Pcm,
370 ],
371 MediaType::Subtitle => &[CodecId::Subrip, CodecId::WebVtt],
372 _ => &[],
373 }
374}
375
376fn preferred_override(format: &str, media: MediaType) -> Option<CodecId> {
380 match (format, media) {
381 ("mp4" | "dash", MediaType::Audio) => Some(CodecId::Aac),
382 _ => None,
383 }
384}
385
386const VIDEO_ORDER: &[&str] = &[
391 "mp4",
392 "matroska",
393 "webm",
394 "mpegts",
395 "flv",
396 "avi",
397 "hls",
398 "dash",
399 "ivf",
400 "av2f",
401 "yuv4mpegpipe",
402];
403const AUDIO_ORDER: &[&str] = &[
404 "mp3", "flac", "wav", "ogg", "mp4", "matroska", "webm", "mpegts", "flv", "avi", "hls", "dash",
405];
406const IMAGE_ORDER: &[&str] = &["jpeg", "png", "webp", "avif", "gif", "jpegxl", "av2f"];
407const SUBTITLE_ORDER: &[&str] = &["srt", "webvtt", "matroska", "mp4"];
408
409fn rank(kind: TargetKind, name: &str) -> usize {
411 let order = match kind {
412 TargetKind::Video => VIDEO_ORDER,
413 TargetKind::Audio => AUDIO_ORDER,
414 TargetKind::Image => IMAGE_ORDER,
415 TargetKind::Subtitle => SUBTITLE_ORDER,
416 };
417 order.iter().position(|n| *n == name).unwrap_or(order.len())
418}
419
420const MEDIA_PRIORITY: [MediaType; 3] = [MediaType::Video, MediaType::Audio, MediaType::Subtitle];
422
423fn media_rank(m: MediaType) -> usize {
424 MEDIA_PRIORITY.iter().position(|p| *p == m).unwrap_or(9)
425}
426
427pub fn plan(codecs: &CodecRegistry, formats: &FormatRegistry, source: &[SourceStream]) -> Plan {
438 let mut targets: Vec<Target> = formats
439 .iter()
440 .filter(|f| f.can_mux())
441 .filter_map(|f| {
442 build_target(
443 codecs,
444 f.name,
445 f.long_name,
446 f.extensions,
447 &f.mux_caps,
448 f.muxer_path.is_some(),
449 |ext| formats.by_extension(ext).map(|r| r.name) != Some(f.name),
453 source,
454 )
455 })
456 .collect();
457
458 let source_kind = source_kind(source);
459 targets.sort_by_key(|t| {
460 (
461 (t.kind != source_kind) as u8,
462 t.fidelity,
463 rank(t.kind, t.format),
464 t.format,
465 )
466 });
467
468 Plan {
469 source: source.to_vec(),
470 source_format: None,
471 targets,
472 }
473}
474
475fn source_kind(source: &[SourceStream]) -> TargetKind {
477 if source.iter().any(|s| s.media_type == MediaType::Video) {
478 TargetKind::Video
479 } else if source.iter().any(|s| s.media_type == MediaType::Audio) {
480 TargetKind::Audio
481 } else {
482 TargetKind::Subtitle
483 }
484}
485
486#[allow(clippy::too_many_arguments)]
487fn build_target(
488 codecs: &CodecRegistry,
489 format: &'static str,
490 long_name: &'static str,
491 extensions: &'static [&'static str],
492 caps: &MuxCaps,
493 multi_file: bool,
494 needs_explicit_f: impl Fn(&str) -> bool,
497 source: &[SourceStream],
498) -> Option<Target> {
499 let mut streams: Vec<StreamPlan> = source
501 .iter()
502 .map(|s| StreamPlan {
503 input_index: s.index,
504 media_type: s.media_type,
505 from: s.codec_id,
506 action: decide(codecs, format, caps, s),
507 })
508 .collect();
509
510 if let Some(max) = caps.max_streams {
513 let mut order: Vec<usize> = (0..streams.len())
514 .filter(|&i| !streams[i].action.is_drop())
515 .collect();
516 order.sort_by_key(|&i| (media_rank(streams[i].media_type), streams[i].input_index));
517 for &i in order.iter().skip(max) {
518 streams[i].action = Action::Drop(DropReason::ContainerFull);
519 }
520 }
521
522 if streams.iter().all(|s| s.action.is_drop()) {
523 return None;
524 }
525
526 let fidelity = streams
528 .iter()
529 .filter_map(|s| match s.action {
530 Action::Copy => Some(Fidelity::Copy),
531 Action::Transcode { lossy: false, .. } => Some(Fidelity::Lossless),
532 Action::Transcode { lossy: true, .. } => Some(Fidelity::Lossy),
533 Action::Drop(_) => None,
534 })
535 .max()
536 .unwrap_or(Fidelity::Copy);
537
538 let kind = if caps.still_image {
539 TargetKind::Image
540 } else {
541 match streams
542 .iter()
543 .filter(|s| !s.action.is_drop())
544 .map(|s| s.media_type)
545 .min_by_key(|m| media_rank(*m))
546 {
547 Some(MediaType::Video) => TargetKind::Video,
548 Some(MediaType::Audio) => TargetKind::Audio,
549 _ => TargetKind::Subtitle,
550 }
551 };
552
553 let extension = primary_extension(extensions, &streams, format);
554 Some(Target {
555 format,
556 long_name,
557 extension,
558 extensions,
559 kind,
560 notes: notes(format, caps, multi_file, &streams, kind),
561 args: args(format, needs_explicit_f(extension), &streams),
562 streams,
563 fidelity,
564 })
565}
566
567fn primary_extension(
574 extensions: &'static [&'static str],
575 streams: &[StreamPlan],
576 format: &'static str,
577) -> &'static str {
578 for s in streams {
579 let codec = match s.action {
580 Action::Copy => s.from,
581 Action::Transcode { to, .. } => to,
582 Action::Drop(_) => continue,
583 };
584 if let Some(ext) = extensions.iter().find(|e| **e == codec.name()) {
585 return ext;
586 }
587 }
588 extensions.first().copied().unwrap_or(format)
589}
590
591fn decide(codecs: &CodecRegistry, format: &str, caps: &MuxCaps, s: &SourceStream) -> Action {
593 if !caps.accepts_media(s.media_type) {
594 return Action::Drop(DropReason::UnsupportedMedia);
595 }
596 if caps.accepts(s.codec_id) {
599 return Action::Copy;
600 }
601 if s.media_type == MediaType::Subtitle && is_text_subtitle(s.codec_id) {
603 return match caps
604 .codecs_for(MediaType::Subtitle)
605 .find(|id| is_text_subtitle(*id))
606 {
607 Some(to) => Action::Transcode { to, lossy: false },
608 None => Action::Drop(DropReason::NoEncoder),
609 };
610 }
611 if !codecs.by_id(s.codec_id).is_some_and(|c| c.can_decode()) {
613 return Action::Drop(DropReason::NoDecoder);
614 }
615 match pick_encoder(codecs, format, caps, s.media_type) {
616 Some(to) => Action::Transcode {
617 to,
618 lossy: !is_lossless(to),
619 },
620 None => Action::Drop(DropReason::NoEncoder),
621 }
622}
623
624fn pick_encoder(
628 codecs: &CodecRegistry,
629 format: &str,
630 caps: &MuxCaps,
631 media: MediaType,
632) -> Option<CodecId> {
633 let usable = |id: CodecId| {
634 let shape_fits = caps.still_image || !encodes_stills_only(id);
636 shape_fits && caps.accepts(id) && codecs.by_id(id).is_some_and(|c| c.can_encode())
637 };
638 preferred_override(format, media)
639 .filter(|id| usable(*id))
640 .or_else(|| preference(media).iter().copied().find(|id| usable(*id)))
641}
642
643fn notes(
645 format: &str,
646 caps: &MuxCaps,
647 multi_file: bool,
648 streams: &[StreamPlan],
649 kind: TargetKind,
650) -> Vec<String> {
651 let mut notes = Vec::new();
652
653 if caps.still_image
654 && kind == TargetKind::Image
655 && streams
656 .iter()
657 .any(|s| !s.action.is_drop() && s.media_type == MediaType::Video)
658 {
659 notes.push("holds one picture — only the first frame is written".into());
660 }
661 if multi_file {
662 notes.push("writes a playlist plus segment files, not a single file".into());
663 }
664 for s in streams {
666 if let Action::Transcode { to, lossy: true } = s.action {
667 if !is_lossless(s.from) {
668 notes.push(format!(
669 "{} -> {to} re-encodes already-lossy data (generation loss)",
670 s.from
671 ));
672 }
673 }
674 }
675 for s in streams {
676 if let Action::Drop(reason) = s.action {
677 notes.push(format!(
678 "stream {} ({} {}) is dropped: {reason}",
679 s.input_index, s.media_type, s.from
680 ));
681 }
682 }
683 if format == "av2f" {
684 notes.push(
685 "experimental: the four-character codes are ours, so these files read back \
686 here and nowhere else"
687 .into(),
688 );
689 }
690 notes
691}
692
693fn args(format: &str, needs_f: bool, streams: &[StreamPlan]) -> Vec<String> {
696 let mut args = Vec::new();
697 let mut seen = [false; 3]; for s in streams {
699 let (slot, flag) = match s.media_type {
700 MediaType::Video => (0usize, "-c:v"),
701 MediaType::Audio => (1, "-c:a"),
702 MediaType::Subtitle => (2, "-c:s"),
703 _ => continue,
704 };
705 if seen[slot] {
706 continue;
707 }
708 let codec = match s.action {
709 Action::Copy => "copy".to_string(),
710 Action::Transcode { to, .. } => to.name().to_string(),
711 Action::Drop(_) => continue,
712 };
713 seen[slot] = true;
714 args.push(flag.to_string());
715 args.push(codec);
716 }
717 if needs_f {
718 args.push("-f".into());
719 args.push(format.to_string());
720 }
721 args
722}
723
724#[derive(Debug, Clone)]
731pub struct FormatSupport {
732 pub format: &'static str,
733 pub long_name: &'static str,
734 pub extensions: &'static [&'static str],
735 pub can_read: bool,
736 pub can_write: bool,
737 pub video: Vec<CodecId>,
739 pub audio: Vec<CodecId>,
740 pub subtitle: Vec<CodecId>,
741 pub still_image: bool,
742 pub max_streams: Option<usize>,
743}
744
745pub fn format_matrix(formats: &FormatRegistry) -> Vec<FormatSupport> {
747 let mut rows: Vec<FormatSupport> = formats
748 .iter()
749 .map(|f| FormatSupport {
750 format: f.name,
751 long_name: f.long_name,
752 extensions: f.extensions,
753 can_read: f.can_demux(),
754 can_write: f.can_mux(),
755 video: f.mux_caps.codecs_for(MediaType::Video).collect(),
756 audio: f.mux_caps.codecs_for(MediaType::Audio).collect(),
757 subtitle: f.mux_caps.codecs_for(MediaType::Subtitle).collect(),
758 still_image: f.mux_caps.still_image,
759 max_streams: f.mux_caps.max_streams,
760 })
761 .collect();
762 rows.sort_by_key(|r| (rank(TargetKind::Video, r.format), r.format));
763 rows
764}
765
766pub fn readable_extensions(formats: &FormatRegistry) -> Vec<&'static str> {
769 let mut v: Vec<&'static str> = formats
770 .iter()
771 .filter(|f| f.can_demux())
772 .flat_map(|f| f.extensions.iter().copied())
773 .collect();
774 v.sort_unstable();
775 v.dedup();
776 v
777}