forge
Explore
Log in

Don't you dare go Hollow

Export can be limited to an in/out range (i, o, ctrl+u)

Browse files at this commit

5134b1d5ca1630f74717c5c3ead1dd5765ecab95Ahmet Kaan GümüşParent: c3d3346a5c0bc7
  • feat
    • export can be limited to an in/out range (i, o, ctrl+u)
Show full message
✨ feat(app): export can be limited to an in/out range (i, o, ctrl+u)

# Conflicts:
#	crates/app/src/keymap.rs
crates/app/src/export_ui.rsmodified+3 -0
@@ -887,6 +887,9 @@ pub(crate) fn export_settings(
887 // anybody.887 // anybody.
888 intra_only: false,888 intra_only: false,
889 keep_source_colour: false,889 keep_source_colour: false,
890+ // Set by `start_export`, which knows the player's mark; this helper is
891+ // also asked for the estimate alone, which has no range to give.
892+ range: None,
890 }893 }
891 }894 }
892 895
crates/app/src/keymap.rsmodified+32 -2
@@ -80,6 +80,14 @@ actions! {
80 /// by what they are for.80 /// by what they are for.
81 PrevSyncPoint,81 PrevSyncPoint,
82 NextSyncPoint,82 NextSyncPoint,
83+ /// Marks the playhead as an export's in point. The out point wraps around
84+ /// it if the mark lands past the current out ([`ordered_range`]).
85+ SetIn,
86+ /// The out point's pair. Ordered the same way against whatever in point
87+ /// stands already.
88+ SetOut,
89+ /// Drops the mark: an export goes back to the whole timeline.
90+ ClearRange,
83 Export,91 Export,
84 Save,92 Save,
85 Copy,93 Copy,
@@ -171,6 +179,9 @@ impl ActionId {
171 ActionId::GoEnd => "Go to the last frame",179 ActionId::GoEnd => "Go to the last frame",
172 ActionId::PrevSyncPoint => "Previous sync point (a cut here is copied, not re-encoded)",180 ActionId::PrevSyncPoint => "Previous sync point (a cut here is copied, not re-encoded)",
173 ActionId::NextSyncPoint => "Next sync point (a cut here is copied, not re-encoded)",181 ActionId::NextSyncPoint => "Next sync point (a cut here is copied, not re-encoded)",
182+ ActionId::SetIn => "Mark in (export range)",
183+ ActionId::SetOut => "Mark out (export range)",
184+ ActionId::ClearRange => "Clear the export range",
174 ActionId::Export => "Export",185 ActionId::Export => "Export",
175 ActionId::Save => "Save",186 ActionId::Save => "Save",
176 ActionId::Copy => "Copy",187 ActionId::Copy => "Copy",
@@ -237,6 +248,9 @@ impl ActionId {
237 ActionId::GoEnd => "go-end",248 ActionId::GoEnd => "go-end",
238 ActionId::PrevSyncPoint => "prev-sync-point",249 ActionId::PrevSyncPoint => "prev-sync-point",
239 ActionId::NextSyncPoint => "next-sync-point",250 ActionId::NextSyncPoint => "next-sync-point",
251+ ActionId::SetIn => "set-in",
252+ ActionId::SetOut => "set-out",
253+ ActionId::ClearRange => "clear-range",
240 ActionId::Export => "export",254 ActionId::Export => "export",
241 ActionId::Save => "save",255 ActionId::Save => "save",
242 ActionId::Copy => "copy",256 ActionId::Copy => "copy",
@@ -304,7 +318,10 @@ impl ActionId {
304 | ActionId::GoStart318 | ActionId::GoStart
305 | ActionId::GoEnd319 | ActionId::GoEnd
306 | ActionId::PrevSyncPoint320 | ActionId::PrevSyncPoint
307- | ActionId::NextSyncPoint => Category::Playback,321+ | ActionId::NextSyncPoint
322+ | ActionId::SetIn
323+ | ActionId::SetOut
324+ | ActionId::ClearRange => Category::Playback,
308 ActionId::Copy325 ActionId::Copy
309 | ActionId::Paste326 | ActionId::Paste
310 | ActionId::Select327 | ActionId::Select
@@ -827,6 +844,16 @@ impl Keymap {
827 // step through the same timeline by the source's own grid.844 // step through the same timeline by the source's own grid.
828 b(ActionId::PrevSyncPoint, "[", true),845 b(ActionId::PrevSyncPoint, "[", true),
829 b(ActionId::NextSyncPoint, "]", true),846 b(ActionId::NextSyncPoint, "]", true),
847+ // The mark pair, on the letters every editor already means them
848+ // by: bare, since a mark is set as often as a step and nothing
849+ // else in this table answers to either.
850+ b(ActionId::SetIn, "i", false),
851+ b(ActionId::SetOut, "o", false),
852+ // The clear takes the ctrl chord: not a stroke to hit setting
853+ // one mark and reaching for the other. Free -- "u" bare is the
854+ // silence card, and nothing else in this table answers to
855+ // ctrl+u.
856+ b(ActionId::ClearRange, "u", true),
830 b(ActionId::Export, "e", false),857 b(ActionId::Export, "e", false),
831 b(ActionId::Save, "s", true),858 b(ActionId::Save, "s", true),
832 b(ActionId::Copy, "c", true),859 b(ActionId::Copy, "c", true),
@@ -1238,7 +1265,7 @@ mod tests {
1238 #[test]1265 #[test]
1239 fn every_default_stroke_reaches_its_action() {1266 fn every_default_stroke_reaches_its_action() {
1240 let k = Keymap::defaults();1267 let k = Keymap::defaults();
1241- assert_eq!(k.entries().len(), 58);1268+ assert_eq!(k.entries().len(), 61);
1242 assert_eq!(k.lookup("f11", false), Some(ActionId::Fullscreen));1269 assert_eq!(k.lookup("f11", false), Some(ActionId::Fullscreen));
1243 assert_eq!(k.lookup("w", false), Some(ActionId::Screenshot));1270 assert_eq!(k.lookup("w", false), Some(ActionId::Screenshot));
1244 assert_eq!(k.lookup("y", false), Some(ActionId::SubtitleStyle));1271 assert_eq!(k.lookup("y", false), Some(ActionId::SubtitleStyle));
@@ -1262,6 +1289,9 @@ mod tests {
1262 assert_eq!(k.lookup("]", true), Some(ActionId::NextSyncPoint));1289 assert_eq!(k.lookup("]", true), Some(ActionId::NextSyncPoint));
1263 assert_eq!(k.lookup("[", false), Some(ActionId::SelectPrev));1290 assert_eq!(k.lookup("[", false), Some(ActionId::SelectPrev));
1264 assert_eq!(k.lookup("]", false), Some(ActionId::SelectNext));1291 assert_eq!(k.lookup("]", false), Some(ActionId::SelectNext));
1292+ assert_eq!(k.lookup("i", false), Some(ActionId::SetIn));
1293+ assert_eq!(k.lookup("o", false), Some(ActionId::SetOut));
1294+ assert_eq!(k.lookup("u", true), Some(ActionId::ClearRange));
1265 assert_eq!(k.lookup("e", false), Some(ActionId::Export));1295 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
1266 assert_eq!(k.lookup("s", true), Some(ActionId::Save));1296 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
1267 assert_eq!(k.lookup("c", true), Some(ActionId::Copy));1297 assert_eq!(k.lookup("c", true), Some(ActionId::Copy));
crates/app/src/main.rsmodified+5 -0
@@ -109,6 +109,10 @@ struct Player {
109 /// top on reaching its end instead of stopping there. One flag for both,109 /// top on reaching its end instead of stopping there. One flag for both,
110 /// since only one of them is ever playing at a time.110 /// since only one of them is ever playing at a time.
111 loop_on: bool,111 loop_on: bool,
112+ /// The in/out mark an export is clipped to, half-open `[start, end)` in
113+ /// timeline frames -- `None` for the whole timeline. Session state, like
114+ /// the mark itself: never saved to a `.edith` ([`ExportSettings::range`]).
115+ range: Option<(u32, u32)>,
112 /// Timeline seconds -> frame index, so the clock can be compared to what116 /// Timeline seconds -> frame index, so the clock can be compared to what
113 /// the decoder hands over.117 /// the decoder hands over.
114 fps: f64,118 fps: f64,
@@ -760,6 +764,7 @@ fn main() {
760 preview_playing: false,764 preview_playing: false,
761 player_fullscreen: false,765 player_fullscreen: false,
762 loop_on: false,766 loop_on: false,
767+ range: None,
763 // Full and unmuted, which is what the session it was just768 // Full and unmuted, which is what the session it was just
764 // handed is already set to: nothing to push at startup.769 // handed is already set to: nothing to push at startup.
765 volume: Volume::default(),770 volume: Volume::default(),
crates/app/src/player/actions.rsmodified+56 -0
@@ -76,6 +76,12 @@ impl Player {
76 // where the next one is depends on the file rather than on the rate.76 // where the next one is depends on the file rather than on the rate.
77 ActionId::PrevSyncPoint => self.jump_sync(false, cx),77 ActionId::PrevSyncPoint => self.jump_sync(false, cx),
78 ActionId::NextSyncPoint => self.jump_sync(true, cx),78 ActionId::NextSyncPoint => self.jump_sync(true, cx),
79+ ActionId::SetIn => self.set_in(cx),
80+ ActionId::SetOut => self.set_out(cx),
81+ ActionId::ClearRange => {
82+ self.range = None;
83+ cx.notify();
84+ }
79 ActionId::Export => self.open_export(cx),85 ActionId::Export => self.open_export(cx),
80 ActionId::Save => self.save_project(cx),86 ActionId::Save => self.save_project(cx),
81 ActionId::Copy => self.copy_selected(),87 ActionId::Copy => self.copy_selected(),
@@ -410,6 +416,29 @@ impl Player {
410 cx.notify();416 cx.notify();
411 }417 }
412 418
419+ /// Marks the playhead as an export's in point. `ordered_range` keeps the
420+ /// pair legal whichever one lands past the other.
421+ pub(crate) fn set_in(&mut self, cx: &mut Context<Self>) {
422+ let Some(session) = &self.session else {
423+ return;
424+ };
425+ let at = frame_at(session.now(), self.fps);
426+ let out = self.range.map_or(at, |(_, e)| e);
427+ self.range = Some(ordered_range(at, out));
428+ cx.notify();
429+ }
430+
431+ /// The out point's pair.
432+ pub(crate) fn set_out(&mut self, cx: &mut Context<Self>) {
433+ let Some(session) = &self.session else {
434+ return;
435+ };
436+ let at = frame_at(session.now(), self.fps);
437+ let start = self.range.map_or(at, |(s, _)| s);
438+ self.range = Some(ordered_range(start, at));
439+ cx.notify();
440+ }
441+
413 pub(crate) fn undo(&mut self, cx: &mut Context<Self>) {442 pub(crate) fn undo(&mut self, cx: &mut Context<Self>) {
414 if self.session.as_mut().is_some_and(PlaybackSession::undo) {443 if self.session.as_mut().is_some_and(PlaybackSession::undo) {
415 self.reset_after_reseek();444 self.reset_after_reseek();
@@ -466,3 +495,30 @@ impl Player {
466 self.notify_user(text.into());495 self.notify_user(text.into());
467 }496 }
468 }497 }
498+
499+/// The half-open range a mark and a mark make, in either order: a person's two
500+/// keystrokes are not promised to land in order, so this is what turns
501+/// whichever came second into the pair `Player::start_export` wants a range in
502+/// -- and never an empty one, since a single frame marked in and out twice is
503+/// still a frame to export.
504+pub(crate) fn ordered_range(a: u32, b: u32) -> (u32, u32) {
505+ let (start, end) = if a <= b { (a, b) } else { (b, a) };
506+ if start == end {
507+ (start, start + 1)
508+ } else {
509+ (start, end)
510+ }
511+}
512+
513+#[cfg(test)]
514+mod tests {
515+ use super::ordered_range;
516+
517+ #[test]
518+ fn ordered_range_never_empty_and_swaps_a_reversed_pair() {
519+ assert_eq!(ordered_range(5, 10), (5, 10));
520+ assert_eq!(ordered_range(10, 5), (5, 10));
521+ assert_eq!(ordered_range(7, 7), (7, 8));
522+ assert_eq!(ordered_range(0, 0), (0, 1));
523+ }
524+}
crates/app/src/player/export.rsmodified+1 -0
@@ -650,6 +650,7 @@ impl Player {
650 // Set here rather than inside `export_settings`, which the card also650 // Set here rather than inside `export_settings`, which the card also
651 // calls for the *estimate* and which nothing else needs a subtitle for.651 // calls for the *estimate* and which nothing else needs a subtitle for.
652 settings.subtitles = self.export_subs();652 settings.subtitles = self.export_subs();
653+ settings.range = self.range;
653 let Some(session) = &mut self.session else {654 let Some(session) = &mut self.session else {
654 self.notify_user("NOTHING TO EXPORT — open a file first".into());655 self.notify_user("NOTHING TO EXPORT — open a file first".into());
655 cx.notify();656 cx.notify();
crates/app/src/ui/cards.rsmodified+16 -0
@@ -637,6 +637,22 @@ impl Player {
637 .children(list),637 .children(list),
638 )638 )
639 .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(head))639 .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(head))
640+ // The mark, in and out and how long that is -- only
641+ // when there is one: an unmarked export writes the
642+ // whole timeline, the summary it always had.
643+ .children(self.range.map(|(start, end)| {
644+ div()
645+ .flex_none()
646+ .px(px(6.))
647+ .text_size(px(11.))
648+ .text_color(rgb(FG_SECONDARY()))
649+ .child(format!(
650+ "RANGE {}\u{2013}{} ({})",
651+ timecode(f64::from(start) / self.fps, self.fps),
652+ timecode(f64::from(end) / self.fps, self.fps),
653+ timecode(f64::from(end - start) / self.fps, self.fps),
654+ ))
655+ }))
640 .child(656 .child(
641 div()657 div()
642 .flex_none()658 .flex_none()
crates/app/src/ui/timeline.rsmodified+19 -1
@@ -231,7 +231,25 @@ impl Player {
231 .w(px(filled))231 .w(px(filled))
232 .rounded(px(3.))232 .rounded(px(3.))
233 .bg(rgb(ACCENT_PRIMARY())),233 .bg(rgb(ACCENT_PRIMARY())),
234- ),234+ )
235+ // The export's own mark, in and out: drawn
236+ // over the played fill rather than under it,
237+ // so a range that starts behind the playhead
238+ // still shows -- translucent, the same wash
239+ // the silence marks use, so the ruler under
240+ // it stays readable.
241+ .children(self.range.map(|(start, end)| {
242+ let left = self.scale.px_at(f64::from(start) / self.fps);
243+ let right = self.scale.px_at(f64::from(end) / self.fps);
244+ div()
245+ .absolute()
246+ .top_0()
247+ .h_full()
248+ .left(px(left))
249+ .w(px((right - left).max(1.)))
250+ .rounded(px(3.))
251+ .bg(rgba(ACCENT_WASH()))
252+ })),
235 ),253 ),
236 ),254 ),
237 )255 )
crates/engine/src/export.rsmodified+100 -24
@@ -367,6 +367,11 @@ pub struct ExportSettings {
367 /// A delivery export must leave it off: an mp4 in BT.2020 PQ is a file for367 /// A delivery export must leave it off: an mp4 in BT.2020 PQ is a file for
368 /// this editor to read back, not one to hand anybody.368 /// this editor to read back, not one to hand anybody.
369 pub keep_source_colour: bool,369 pub keep_source_colour: bool,
370+ /// Half-open `[start, end)` in timeline frames, or `None` for the whole
371+ /// timeline -- what every caller wrote before there was a choice, so an
372+ /// export nobody has marked in or out on writes the same bytes it always
373+ /// did. Session state, like the mark itself: never saved to a `.edith`.
374+ pub range: Option<(u32, u32)>,
370 }375 }
371 376
372 struct Shared {377 struct Shared {
@@ -961,7 +966,8 @@ fn lane_subtitles(project: &Project, fps: f64) -> Vec<SubParams> {
961 }966 }
962 967
963 /// The composite spans an export *writes*: [`Project::composite_spans_from`]968 /// The composite spans an export *writes*: [`Project::composite_spans_from`]
964-/// cut to where the media runs out ([`Project::media_frames`]).969+/// cut to where the media runs out ([`Project::media_frames`]), and, with
970+/// `range` set, to that window too.
965 ///971 ///
966 /// The walk itself is the timeline's ([`Project::timeline_frames`]), because a972 /// The walk itself is the timeline's ([`Project::timeline_frames`]), because a
967 /// caption placed past the last picture holds the timeline open under it and973 /// caption placed past the last picture holds the timeline open under it and
@@ -971,13 +977,37 @@ fn lane_subtitles(project: &Project, fps: f64) -> Vec<SubParams> {
971 /// the frame count [`run`] publishes, the cues [`lane_subtitles`] clips and the977 /// the frame count [`run`] publishes, the cues [`lane_subtitles`] clips and the
972 /// blocks [`CopyPlan`] copies are then the same number by construction, which978 /// blocks [`CopyPlan`] copies are then the same number by construction, which
973 /// is what makes [`planned_lanes`]' "cut off there" true of the file.979 /// is what makes [`planned_lanes`]' "cut off there" true of the file.
974-fn export_spans(project: &Project) -> Vec<crate::project::Span> {980+///
981+/// `span.start` stays the *project's* own timeline coordinate throughout --
982+/// what [`Project::composite_color_at`] and its fit sibling are keyed on -- so
983+/// a caller writing a range-relative output shifts it at the one place that
984+/// actually emits a position (`CopyPlan`'s own region, since the encode loop
985+/// counts pictures rather than reading `span.start` for its output clock).
986+/// Trimming the left edge mid-span moves `from`'s source frame by
987+/// [`Speed::source_at`], the same mapping a legal cut is placed by.
988+fn export_spans(project: &Project, range: Option<(u32, u32)>) -> Vec<crate::project::Span> {
975 let end = project.media_frames();989 let end = project.media_frames();
976 let mut spans = project.composite_spans_from(0);990 let mut spans = project.composite_spans_from(0);
977 spans.retain(|span| span.start < end);991 spans.retain(|span| span.start < end);
978 for span in &mut spans {992 for span in &mut spans {
979 span.len = span.len.min(end - span.start);993 span.len = span.len.min(end - span.start);
980 }994 }
995+ let Some((r_start, r_end)) = range else {
996+ return spans;
997+ };
998+ let r_end = r_end.min(end).max(r_start);
999+ spans.retain(|span| span.start < r_end && span.start + span.len > r_start);
1000+ for span in &mut spans {
1001+ if span.start < r_start {
1002+ let cut = r_start - span.start;
1003+ if let Some((source, in_frame)) = span.from {
1004+ span.from = Some((source, in_frame + span.speed.source_at(cut)));
1005+ }
1006+ span.len -= cut;
1007+ span.start = r_start;
1008+ }
1009+ span.len = span.len.min(r_end - span.start);
1010+ }
981 spans1011 spans
982 }1012 }
983 1013
@@ -1311,7 +1341,17 @@ fn copy_audio(
1311 mkv: bool,1341 mkv: bool,
1312 shared: &Shared,1342 shared: &Shared,
1313 sample_rate: Option<u32>,1343 sample_rate: Option<u32>,
1344+ range: Option<(u32, u32)>,
1314 ) -> crate::Result<Option<ExportAudio>> {1345 ) -> crate::Result<Option<ExportAudio>> {
1346+ // A ranged export needs an exact offset and an exact length, which a
1347+ // packet copy cannot give -- it carries whole segments named by
1348+ // `audio_segments_from(0, ..)`, not an arbitrary window into them. The
1349+ // decoded path already resamples per segment, so it is the one that can
1350+ // start and stop anywhere; this falls to it exactly as a speeded or
1351+ // equalized lane already does.
1352+ if range.is_some() {
1353+ return encode_audio(project, meta, kbps, mkv, shared, sample_rate, range);
1354+ }
1315 // The segments name their source, and the copy carries its packet-rounding1355 // The segments name their source, and the copy carries its packet-rounding
1316 // debt across a source join exactly as across a cut, so a timeline spanning1356 // debt across a source join exactly as across a cut, so a timeline spanning
1317 // files stays in sync. A source whose AAC parameters disagree with the1357 // files stays in sync. A source whose AAC parameters disagree with the
@@ -1352,7 +1392,7 @@ fn copy_audio(
1352 }1392 }
1353 }1393 }
1354 let [segments] = &lanes[..] else {1394 let [segments] = &lanes[..] else {
1355- return encode_audio(project, meta, kbps, mkv, shared, sample_rate);1395+ return encode_audio(project, meta, kbps, mkv, shared, sample_rate, None);
1356 };1396 };
1357 // ...and the same list names *which* lane those clips sit on, which is the1397 // ...and the same list names *which* lane those clips sit on, which is the
1358 // only way to ask what has been done to them.1398 // only way to ask what has been done to them.
@@ -1390,7 +1430,7 @@ fn copy_audio(
1390 // such a lane would write it at unity and unlimited, silently.1430 // such a lane would write it at unity and unlimited, silently.
1391 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());1431 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
1392 if speeded || equalized(project) || mastered(project) {1432 if speeded || equalized(project) || mastered(project) {
1393- return encode_audio(project, meta, kbps, mkv, shared, sample_rate);1433+ return encode_audio(project, meta, kbps, mkv, shared, sample_rate, None);
1394 }1434 }
1395 // What is left is a copy the *sources* may still not be able to give: AAC1435 // What is left is a copy the *sources* may still not be able to give: AAC
1396 // inside a Matroska file (readable, but not out of a sample table this walks1436 // inside a Matroska file (readable, but not out of a sample table this walks
@@ -1410,7 +1450,7 @@ fn copy_audio(
1410 // (they are not in a sample table) and every one of them re-encodes.1450 // (they are not in a sample table) and every one of them re-encodes.
1411 opus_pre_skip: None,1451 opus_pre_skip: None,
1412 })),1452 })),
1413- Err(_) => encode_audio(project, meta, kbps, mkv, shared, sample_rate),1453+ Err(_) => encode_audio(project, meta, kbps, mkv, shared, sample_rate, None),
1414 }1454 }
1415 }1455 }
1416 1456
@@ -1471,7 +1511,9 @@ struct CopyRegion {
1471 source: usize,1511 source: usize,
1472 /// Blocks of that source, in the file's own decode order.1512 /// Blocks of that source, in the file's own decode order.
1473 blocks: std::ops::Range<usize>,1513 blocks: std::ops::Range<usize>,
1474- /// The timeline frame the region's first picture is shown at.1514+ /// The *output* frame the region's first picture is shown at -- the
1515+ /// project's own timeline frame less the range's own start, since a
1516+ /// ranged export's file starts a fresh clock at zero.
1475 start: u32,1517 start: u32,
1476 }1518 }
1477 1519
@@ -1489,7 +1531,9 @@ impl CopyPlan {
1489 let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect();1531 let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect();
1490 let mut declared: Option<(Vec<u8>, ColorDescription)> = None;1532 let mut declared: Option<(Vec<u8>, ColorDescription)> = None;
1491 let mut regions: Vec<CopyRegion> = Vec::new();1533 let mut regions: Vec<CopyRegion> = Vec::new();
1492- for span in export_spans(project) {1534+ let r_start = settings.range.map_or(0, |(s, _)| s);
1535+ for span in export_spans(project, settings.range) {
1536+ let out_start = span.start - r_start;
1493 // A gap is black frames, which only an encoder makes.1537 // A gap is black frames, which only an encoder makes.
1494 let (source, in_frame) = span.from?;1538 let (source, in_frame) = span.from?;
1495 if !span.speed.is_normal() {1539 if !span.speed.is_normal() {
@@ -1554,14 +1598,14 @@ impl CopyPlan {
1554 if last.source == source1598 if last.source == source
1555 && last.blocks.end == start1599 && last.blocks.end == start
1556 && last.start + (last.blocks.end - last.blocks.start) as u321600 && last.start + (last.blocks.end - last.blocks.start) as u32
1557- == span.start =>1601+ == out_start =>
1558 {1602 {
1559 last.blocks.end = end;1603 last.blocks.end = end;
1560 }1604 }
1561 _ => regions.push(CopyRegion {1605 _ => regions.push(CopyRegion {
1562 source,1606 source,
1563 blocks: start..end,1607 blocks: start..end,
1564- start: span.start,1608+ start: out_start,
1565 }),1609 }),
1566 }1610 }
1567 }1611 }
@@ -1666,11 +1710,13 @@ fn encode_audio(
1666 mkv: bool,1710 mkv: bool,
1667 shared: &Shared,1711 shared: &Shared,
1668 sample_rate: Option<u32>,1712 sample_rate: Option<u32>,
1713+ range: Option<(u32, u32)>,
1669 ) -> crate::Result<Option<ExportAudio>> {1714 ) -> crate::Result<Option<ExportAudio>> {
1670 let sources = project.audio_sources();1715 let sources = project.audio_sources();
1671- let segs = project.audio_segments_from(0, meta.frame_rate);1716+ let offset = range.map_or(0, |(s, _)| s);
1672- let eqs = project.audio_eqs_from(0, meta.frame_rate);1717+ let segs = project.audio_segments_from(offset, meta.frame_rate);
1673- let speeds = project.audio_speeds_from(0, meta.frame_rate);1718+ let eqs = project.audio_eqs_from(offset, meta.frame_rate);
1719+ let speeds = project.audio_speeds_from(offset, meta.frame_rate);
1674 // Coarse stage timers, in the same voice as `export video: copy` below: an1720 // Coarse stage timers, in the same voice as `export video: copy` below: an
1675 // export of a feature film spends minutes in here before a byte of picture1721 // export of a feature film spends minutes in here before a byte of picture
1676 // is written, and which minutes went where is the first question asked of a1722 // is written, and which minutes went where is the first question asked of a
@@ -1700,10 +1746,12 @@ fn encode_audio(
1700 // whole samples on its own, so the sum can miss by a sample or two and a1746 // whole samples on its own, so the sum can miss by a sample or two and a
1701 // source that ran out early would leave the track short under a picture1747 // source that ran out early would leave the track short under a picture
1702 // that is not. One resize settles both, as [`run_audio`]'s does.1748 // that is not. One resize settles both, as [`run_audio`]'s does.
1703- let total = (f64::from(project.media_frames()) / meta.frame_rate1749+ let out_frames = range.map_or(project.media_frames(), |(s, e)| {
1704- * f64::from(audio.sample_rate))1750+ e.min(project.media_frames()).saturating_sub(s)
1705- .round() as usize1751+ });
1706- * channels;1752+ let total =
1753+ (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as usize
1754+ * channels;
1707 let mut samples: Vec<f32> = Vec::with_capacity(total);1755 let mut samples: Vec<f32> = Vec::with_capacity(total);
1708 for chunk in chunks {1756 for chunk in chunks {
1709 // The only place a cancelled export can be answered before the whole1757 // The only place a cancelled export can be answered before the whole
@@ -2151,7 +2199,12 @@ fn run(
2151 // trailing silence over a frozen last frame. The export ends with the last2199 // trailing silence over a frozen last frame. The export ends with the last
2152 // picture or sound, the cues are cut off there ([`lane_subtitles`]), and2200 // picture or sound, the cues are cut off there ([`lane_subtitles`]), and
2153 // [`planned_subtitles`] says so before the button is pressed.2201 // [`planned_subtitles`] says so before the button is pressed.
2154- let total = project.media_frames();2202+ // The range's own length where one is marked, the media's otherwise --
2203+ // `export_spans` walks the same window, so `done` ends on this `total`
2204+ // exactly as it always did.
2205+ let total = settings
2206+ .range
2207+ .map_or(project.media_frames(), |(s, e)| e.min(project.media_frames()).saturating_sub(s));
2155 // The two preview switches are the H.264 mp4 pair's alone. Only that2208 // The two preview switches are the H.264 mp4 pair's alone. Only that
2156 // container carries a colour of its own back out ([`write_video`] tags it2209 // container carries a colour of its own back out ([`write_video`] tags it
2157 // there), so asking any other for a source-space file would write pictures2210 // there), so asking any other for a source-space file would write pictures
@@ -2211,6 +2264,7 @@ fn run(
2211 settings.format.is_mkv(),2264 settings.format.is_mkv(),
2212 &shared,2265 &shared,
2213 sample_rate,2266 sample_rate,
2267+ settings.range,
2214 )2268 )
2215 })?2269 })?
2216 };2270 };
@@ -2355,7 +2409,7 @@ fn run(
2355 // past it under a trailing caption -- and *which* lane a span comes from is2409 // past it under a trailing caption -- and *which* lane a span comes from is
2356 // `composite_spans_from`'s answer, the same one playback shows, so an2410 // `composite_spans_from`'s answer, the same one playback shows, so an
2357 // export is what was watched.2411 // export is what was watched.
2358- for span in export_spans(project) {2412+ for span in export_spans(project, settings.range) {
2359 // Every clip reopens its own source file at its own in point; the2413 // Every clip reopens its own source file at its own in point; the
2360 // encoder is *not* reopened, so the export is one continuous stream2414 // encoder is *not* reopened, so the export is one continuous stream
2361 // whose GOP boundaries need not line up with the cuts -- nor with the2415 // whose GOP boundaries need not line up with the cuts -- nor with the
@@ -2753,18 +2807,19 @@ fn run_audio(
2753 ) -> crate::Result<()> {2807 ) -> crate::Result<()> {
2754 let format = settings.format;2808 let format = settings.format;
2755 let sources = project.audio_sources();2809 let sources = project.audio_sources();
2756- let segs = project.audio_segments_from(0, meta.frame_rate);2810+ let offset = settings.range.map_or(0, |(s, _)| s);
2811+ let segs = project.audio_segments_from(offset, meta.frame_rate);
2757 // The equalizers with them, so what is written is what is heard down to the2812 // The equalizers with them, so what is written is what is heard down to the
2758 // filter: the worker applies them per segment before the lanes are summed2813 // filter: the worker applies them per segment before the lanes are summed
2759 // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point2814 // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point
2760 // playback's feeder reads from -- there is no second place here that could2815 // playback's feeder reads from -- there is no second place here that could
2761 // apply them differently.2816 // apply them differently.
2762- let eqs = project.audio_eqs_from(0, meta.frame_rate);2817+ let eqs = project.audio_eqs_from(offset, meta.frame_rate);
2763 // ...and the rates with them, for exactly the same reason: a speeded clip is2818 // ...and the rates with them, for exactly the same reason: a speeded clip is
2764 // resampled inside the worker playback feeds from, so a WAV of a timeline at2819 // resampled inside the worker playback feeds from, so a WAV of a timeline at
2765 // 2x is half as long and holds the samples that were heard -- not a2820 // 2x is half as long and holds the samples that were heard -- not a
2766 // second pass here that could disagree with what the ear got.2821 // second pass here that could disagree with what the ear got.
2767- let speeds = project.audio_speeds_from(0, meta.frame_rate);2822+ let speeds = project.audio_speeds_from(offset, meta.frame_rate);
2768 // ...and the mix over both: each lane's volume into the sum, the master2823 // ...and the mix over both: each lane's volume into the sum, the master
2769 // limiter out of it. The same opener playback's feeder reads from, so a2824 // limiter out of it. The same opener playback's feeder reads from, so a
2770 // file is written at the levels it was heard at -- there is no second2825 // file is written at the levels it was heard at -- there is no second
@@ -2785,9 +2840,11 @@ fn run_audio(
2785 // by the line above, so this names the encoder writing it.2840 // by the line above, so this names the encoder writing it.
2786 *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string());2841 *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string());
2787 let channels = usize::from(audio.channels);2842 let channels = usize::from(audio.channels);
2788- let frames = (f64::from(project.media_frames()) / meta.frame_rate2843+ let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| {
2789- * f64::from(audio.sample_rate))2844+ e.min(project.media_frames()).saturating_sub(s)
2790- .round() as u64;2845+ });
2846+ let frames =
2847+ (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as u64;
2791 let total = frames as usize * channels;2848 let total = frames as usize * channels;
2792 // corner-cut: the whole export sits in memory (4 bytes a sample, so ~23 MB2849 // corner-cut: the whole export sits in memory (4 bytes a sample, so ~23 MB
2793 // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and2850 // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and
@@ -4620,6 +4677,25 @@ mod tests {
4620 );4677 );
4621 }4678 }
4622 4679
4680+ #[test]
4681+ fn export_spans_clips_to_the_marked_range_keeping_absolute_start() {
4682+ let project = Project::single("/nonexistent/film.mkv", 150);
4683+ // The whole timeline, unmarked: one span, the source's own length.
4684+ let whole = export_spans(&project, None);
4685+ assert_eq!(whole.len(), 1);
4686+ assert_eq!((whole[0].start, whole[0].len), (0, 150));
4687+ // A range wholly inside the span: `start` stays the timeline's own
4688+ // coordinate ([`composite_color_at`] needs that), and the length is
4689+ // exactly what the mark asked for.
4690+ let clipped = export_spans(&project, Some((30, 100)));
4691+ assert_eq!(clipped.len(), 1);
4692+ assert_eq!((clipped[0].start, clipped[0].len), (30, 70));
4693+ // A range past the end of the media clamps to it rather than reading
4694+ // short on the wrong side.
4695+ let past_end = export_spans(&project, Some((100, 500)));
4696+ assert_eq!((past_end[0].start, past_end[0].len), (100, 50));
4697+ }
4698+
4623 #[test]4699 #[test]
4624 fn bitrate_clamps_at_both_ends() {4700 fn bitrate_clamps_at_both_ends() {
4625 let meta = |width, height, frame_rate| VideoMeta {4701 let meta = |width, height, frame_rate| VideoMeta {