edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching·0 forks·Rust·18.3 MiB·ff99ad6·Tahinli·6 days ago·1055 commits
| 1 | //! One timeline over one or more files: the decode workers, the audio output |
| 2 | //! and the master clock wired together so a front-end only has to render and |
| 3 | //! call [`tick`]. |
| 4 | //! |
| 5 | //! [`tick`]: PlaybackSession::tick |
| 6 | //! |
| 7 | //! Everything degrades to silent-but-correct: no audio track, no plugin, no |
| 8 | //! PipeWire daemon and an unusable format all end up in [`ClockSource::Wall`], |
| 9 | //! where the video is paced by real time instead of by the device. |
| 10 | //! |
| 11 | //! Drift policy stays with the caller -- this type answers "what time is it", |
| 12 | //! the renderer decides which frame that means. |
| 13 | |
| 14 | use std::borrow::Cow; |
| 15 | use std::path::{Path, PathBuf}; |
| 16 | use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering}; |
| 17 | use std::sync::mpsc::{Receiver, TryRecvError}; |
| 18 | use std::sync::{Arc, Mutex}; |
| 19 | use std::thread; |
| 20 | use std::time::{Duration, Instant}; |
| 21 | |
| 22 | use crate::ao::AoSession; |
| 23 | use crate::audio::{AudioChunk, AudioSession}; |
| 24 | use crate::clock::{ClockSource, PlaybackClock}; |
| 25 | use crate::color::ColorParams; |
| 26 | use crate::colorspace::{ColorDescription, ContentLight}; |
| 27 | use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; |
| 28 | use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta}; |
| 29 | use crate::eq::EqParams; |
| 30 | use crate::project::{ |
| 31 | Clip, Edge, GainKey, GapSweep, Lane, LaneKind, Project, ProjectSettings, Rate, RedoCheckpoint, Source, |
| 32 | SourceWalls, Span, Speed, SubClip, TrimWalls, WallBound, STILL_DEFAULT_SECS, |
| 33 | }; |
| 34 | use crate::scale::{Composer, FitPolicy}; |
| 35 | use crate::transform::TransformParams; |
| 36 | |
| 37 | /// How long the feeder waits out a full ring. The ring holds a second, so this |
| 38 | /// only has to be short next to that; it costs one wakeup per 10 ms of audio. |
| 39 | const RING_FULL_WAIT: Duration = Duration::from_millis(10); |
| 40 | |
| 41 | /// How long the feeder waits out a ring that took *nothing*: the flush of a |
| 42 | /// restart, which only the device's own callback can clear (`engine-audio` |
| 43 | /// refuses a write queued behind one). Short, because this is the gap at the |
| 44 | /// head of every restart and the ear is in it -- one wakeup per millisecond, |
| 45 | /// for the millisecond or two it lasts. |
| 46 | const FLUSH_WAIT: Duration = Duration::from_millis(1); |
| 47 | |
| 48 | /// How long [`try_frame`](PlaybackSession::try_frame) blocks the caller |
| 49 | /// waiting for B's first picture when the playhead lands in a dissolve |
| 50 | /// window before B's eager-opened decoder ([`start_span`](PlaybackSession::start_span)) |
| 51 | /// has one ready -- a seek straight into the window, mostly. Above the 98 ms |
| 52 | /// worst-case VA-API init measured for a picture open, so an eager-opened B |
| 53 | /// almost never actually waits the full budget; a source B cannot decode at |
| 54 | /// all pays this once per span rather than freezing the preview outright. |
| 55 | const DISSOLVE_B_TIMEOUT: Duration = Duration::from_millis(200); |
| 56 | |
| 57 | /// How long a dead output is left alone before another open is attempted. A |
| 58 | /// PipeWire daemon restart takes a moment, and the ask that makes the attempt |
| 59 | /// runs once per rendered frame: a second is long enough that a restart lands |
| 60 | /// inside it, and short enough that a play pressed after one does not wait. |
| 61 | const AUDIO_REARM_AFTER: Duration = Duration::from_secs(1); |
| 62 | |
| 63 | /// The reason a session gives for having gone quiet when its output dies |
| 64 | /// ([`PlaybackSession::tick`]), through the same door a file's own refusal |
| 65 | /// reaches a front-end by ([`PlaybackSession::audio_disabled_reason`]). |
| 66 | /// |
| 67 | /// That door is read where a notice is *built* -- at open and at load -- so this |
| 68 | /// is fetchable rather than announced: the engine sets the reason and clears it |
| 69 | /// again when the output comes back, and a front-end that reads the door after |
| 70 | /// the session is open (a per-frame check, or one at the next load) is what |
| 71 | /// shows it. Nothing here pushes a notice. |
| 72 | const AUDIO_LOST: &str = "output device went away -- reconnecting the timeline's sound"; |
| 73 | |
| 74 | /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 -- |
| 75 | /// nothing was shot on it, so it is the canvas a *later* import meets rather |
| 76 | /// than a description of the song. H.264 because it is the one codec that |
| 77 | /// decodes without the plugin, 30 fps because a rounded-up audio length is what |
| 78 | /// the frame count means and a whole number of frames per second keeps it |
| 79 | /// honest; both are what a video imported onto such a timeline is held to |
| 80 | /// ([`matches_timeline`]). |
| 81 | /// |
| 82 | /// corner-cut: a 25 fps video imported onto an audio-only timeline it could have |
| 83 | /// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read |
| 84 | /// through [`Rate`] like any other file shot at another rate rather than |
| 85 | /// defining one. Upgrade path is adopting the first *picture's* rate and codec |
| 86 | /// on import, which means retiming every audio clip already placed in frames. |
| 87 | const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); |
| 88 | |
| 89 | /// The frame rate a timeline scaffolded from a still image runs at, for |
| 90 | /// [`AUDIO_ONLY_CANVAS`]'s reason: nothing was shot on it. The *size* is not |
| 91 | /// invented the same way -- an image has a picture of its own, and that picture |
| 92 | /// is the canvas a later import meets. |
| 93 | const IMAGE_ONLY_RATE: f64 = 30.0; |
| 94 | |
| 95 | /// How long a still image *is*, in seconds: the wall a trim may drag its edge |
| 96 | /// out to, since an image has no length of its own to be walled by. Ten |
| 97 | /// minutes, which is a title card nobody will run out of and still a finite |
| 98 | /// number -- a `u32::MAX` sentinel here would make [`Self::trim_room`] hand a |
| 99 | /// drag a wall past what the timeline can hold. |
| 100 | /// |
| 101 | /// corner-cut: a still cannot be held longer than this. Upgrade path is a |
| 102 | /// per-source length the project file carries, which every `counts` reader |
| 103 | /// would then have to take from the document rather than from the file. |
| 104 | const IMAGE_MAX_SECS: f64 = 600.0; |
| 105 | |
| 106 | /// The output half of a session: the device, plus what the feeder has handed it. |
| 107 | /// Cloned into the feeder thread; every field that matters is shared. |
| 108 | #[derive(Clone)] |
| 109 | struct Audio { |
| 110 | /// Shared because `write` runs on the feeder thread while `position` and |
| 111 | /// `set_active` are called from the caller's. The plugin serialises those |
| 112 | /// itself (atomics and a channel), but the lock is what makes it sayable in |
| 113 | /// Rust and it is never held for more than a memcpy. |
| 114 | ao: Arc<Mutex<AoSession>>, |
| 115 | sample_rate: u32, |
| 116 | channels: u64, |
| 117 | /// Interleaved samples accepted by the device so far. |
| 118 | fed: Arc<AtomicU64>, |
| 119 | /// The decoder ran out and `fed` is final. |
| 120 | fed_all: Arc<AtomicBool>, |
| 121 | /// The output plugin failed mid-stream. Its position is frozen from here on, |
| 122 | /// so it can never satisfy [`Audio::played_out`] -- the flag is what lets |
| 123 | /// [`PlaybackSession::tick`] hand the timeline to wall time instead. |
| 124 | died: Arc<AtomicBool>, |
| 125 | /// Bumped by every seek. A feeder only owns the device while this still |
| 126 | /// matches the value it started with; see [`feed`]. |
| 127 | epoch: Arc<AtomicU64>, |
| 128 | /// The device position the *current* stream's first real sample was queued |
| 129 | /// at, `-1` until the feeder has queued one. Written by the feeder under the |
| 130 | /// device lock, read by [`tick`](PlaybackSession::tick). |
| 131 | /// |
| 132 | /// This is what keeps a restart out of the timeline. Between a flush and the |
| 133 | /// first sample of the new stream the device plays silence -- a decoder open |
| 134 | /// is tens of milliseconds -- and that silence is elapsed *device* time |
| 135 | /// ([`crate::ao`] counts it, as it must: it really was played). It is not |
| 136 | /// elapsed *timeline* time, and a clock anchored on the first poll after a |
| 137 | /// seek counts it as such, which is a permanent offset between the picture |
| 138 | /// and the sound, re-rolled by every edit made while playing. |
| 139 | content_at: Arc<AtomicI64>, |
| 140 | /// The monitoring gain this session's device is running at, as f32 bits. |
| 141 | /// |
| 142 | /// The device is the owner -- [`PlaybackSession::gain`] reads the level |
| 143 | /// back out of it -- and this is the *only* reason a session knows what to |
| 144 | /// restore: the device object is replaced from under the session whenever |
| 145 | /// the output dies ([`Self::rearm_audio`]) or is armed late |
| 146 | /// ([`Self::arm_audio`]), and a fresh one comes up at 1.0. Without this a |
| 147 | /// muted session that lost its device came back at full volume while the |
| 148 | /// control still said muted. Written by [`PlaybackSession::set_gain`] |
| 149 | /// alone, so it cannot drift from the knob: whatever the caller last |
| 150 | /// pushed is exactly what the next device is told. |
| 151 | gain: Arc<AtomicU32>, |
| 152 | /// The timeline is *meant* to be playing: what a play or a seek-while-playing |
| 153 | /// asks for, and what the feeder turns into a running device the moment it |
| 154 | /// has a real sample to play ([`Audio::set_playing`], [`feed`]). |
| 155 | /// |
| 156 | /// The device is not started by the intent, because an inactive stream has |
| 157 | /// no callbacks and therefore no starved quanta: between the flush of a seek |
| 158 | /// and the first sample of the new stream -- seconds, on a cold 25 GB film |
| 159 | /// whose decoder is opened on the feeder -- a device started here would play |
| 160 | /// its own silence and count every quantum of it as an underrun. |
| 161 | /// |
| 162 | /// Written and read under the device lock, beside the [`Audio::content_at`] |
| 163 | /// stamp, and that is the whole race: whichever of the two sides takes the |
| 164 | /// lock first, the other sees its half (a stamp already there, or an intent |
| 165 | /// already set), so the device is started exactly once and a pause landing |
| 166 | /// during an open can never be overtaken by a late activation. |
| 167 | wants_active: Arc<AtomicBool>, |
| 168 | /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest |
| 169 | /// first: what a meter or an analyser draws. Written by the feeder, which |
| 170 | /// is not the device's own callback -- the plugin's RT thread never sees |
| 171 | /// this lock, and the feeder holds it for one memcpy per write. |
| 172 | tap: Arc<Mutex<Vec<f32>>>, |
| 173 | /// The highest sample magnitude handed to the device since it was last read |
| 174 | /// ([`PlaybackSession::levels`]), as f32 bits. Non-negative floats order the |
| 175 | /// same as their bits, so the feeder raises it with a `fetch_max`. Taken |
| 176 | /// after the mix and the limiter, before the device's own volume: the |
| 177 | /// meter reads what the device is given, not what the speakers are told. |
| 178 | peak: Arc<AtomicU32>, |
| 179 | /// [`Self::peak`] per side, left then right (a mono stream fills both), read and cleared |
| 180 | /// together with it for the stereo meter. |
| 181 | peak_lr: Arc<[AtomicU32; 2]>, |
| 182 | /// Feeder threads started and not yet returned. They are detached, so there |
| 183 | /// is no handle to count instead, and a scrub leaves dozens of them exiting |
| 184 | /// at once -- which is precisely what |
| 185 | /// [`live_workers`](PlaybackSession::live_workers) is asked about. |
| 186 | feeders: Arc<AtomicUsize>, |
| 187 | /// When this device was last opened *again* after dying |
| 188 | /// ([`PlaybackSession::rearm_audio`]). A dead output is offered one open a |
| 189 | /// second and no more, because the ask that makes the attempt runs once per |
| 190 | /// rendered frame: a daemon restart takes a moment, and a device that is |
| 191 | /// gone for good must not be opened sixty times a second for the rest of |
| 192 | /// the session. |
| 193 | rearm_at: Arc<Mutex<Option<Instant>>>, |
| 194 | } |
| 195 | |
| 196 | /// How much of the played signal the tap keeps. A power of two, because what |
| 197 | /// reads it transforms it, and long enough that the lowest band the editor |
| 198 | /// draws (20 Hz) has a whole cycle in the window at any rate we open. |
| 199 | const TAP_SAMPLES: usize = 2048; |
| 200 | |
| 201 | /// `gains` (one per audio lane, in `audio`'s order) with every lane outside |
| 202 | /// `solo` silenced. A solo naming no lane in `audio` is no solo at all, so a |
| 203 | /// stale handle cannot silence everything. |
| 204 | fn soloed_gains(mut gains: Vec<f32>, audio: &[Lane], solo: &[Lane]) -> Vec<f32> { |
| 205 | if !audio.iter().any(|lane| solo.contains(lane)) { |
| 206 | return gains; |
| 207 | } |
| 208 | for (gain, lane) in gains.iter_mut().zip(audio) { |
| 209 | if !solo.contains(lane) { |
| 210 | *gain = 0.0; |
| 211 | } |
| 212 | } |
| 213 | gains |
| 214 | } |
| 215 | |
| 216 | /// The level meters' reading: [`PlaybackSession::levels`]. Linear peaks in |
| 217 | /// `0.0..=1.0` since the last read, one per audio lane in the lanes' own order, |
| 218 | /// and the master. |
| 219 | #[derive(Clone, Debug, Default, PartialEq)] |
| 220 | pub struct Levels { |
| 221 | pub lanes: Vec<f32>, |
| 222 | pub master: f32, |
| 223 | /// The master's peak on the left and on the right (a mono stream reads the same on both). |
| 224 | pub master_lr: [f32; 2], |
| 225 | } |
| 226 | |
| 227 | impl Audio { |
| 228 | /// Whether the device has played everything there will ever be, i.e. the |
| 229 | /// audio clock is about to stop meaning anything. |
| 230 | fn played_out(&self, position: i64) -> bool { |
| 231 | self.fed_all.load(Ordering::Acquire) |
| 232 | && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) |
| 233 | } |
| 234 | |
| 235 | /// Says whether the timeline is playing, and starts or stops the device for |
| 236 | /// it: `true` runs it *if there is already something to play*, and otherwise |
| 237 | /// leaves it to the feeder's first sample ([`Audio::wants_active`]). `false` |
| 238 | /// stops it at once -- a pause is never deferred, whatever an open in flight |
| 239 | /// is about to find. |
| 240 | fn set_playing(&self, playing: bool) { |
| 241 | // The lock, not the atomics, is what orders this against the feeder's |
| 242 | // stamp: the store below and the load after it are one critical section, |
| 243 | // and so is the feeder's pair. |
| 244 | let ao = self.ao.lock().unwrap(); |
| 245 | self.wants_active.store(playing, Ordering::Release); |
| 246 | if !playing || self.content_at.load(Ordering::Acquire) >= 0 { |
| 247 | ao.set_active(playing); |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | /// Keeps the newest [`TAP_SAMPLES`] of what was just queued, downmixed to |
| 252 | /// mono. Called from the feeder only, once per accepted write. |
| 253 | fn note_tap(&self, accepted: &[f32]) { |
| 254 | // Every sample, not just the tail the tap keeps: a peak that falls |
| 255 | // outside the window is still a peak the ear heard. |
| 256 | let peak = accepted.iter().fold(0.0f32, |m, s| m.max(s.abs())); |
| 257 | self.peak.fetch_max(peak.to_bits(), Ordering::Relaxed); |
| 258 | let channels = self.channels.max(1) as usize; |
| 259 | let side = |at: usize| { |
| 260 | accepted.iter().skip(at.min(channels - 1)).step_by(channels).fold(0.0f32, |m, s| m.max(s.abs())) |
| 261 | }; |
| 262 | self.peak_lr[0].fetch_max(side(0).to_bits(), Ordering::Relaxed); |
| 263 | self.peak_lr[1].fetch_max(side(1).to_bits(), Ordering::Relaxed); |
| 264 | let mut tap = self.tap.lock().unwrap(); |
| 265 | // Only the tail can survive anyway: a big write replaces the window |
| 266 | // outright rather than being summed into it and then thrown away. |
| 267 | let from = accepted.len().saturating_sub(TAP_SAMPLES * channels); |
| 268 | for frame in accepted[from..].chunks_exact(channels) { |
| 269 | tap.push(frame.iter().sum::<f32>() / channels as f32); |
| 270 | } |
| 271 | let over = tap.len().saturating_sub(TAP_SAMPLES); |
| 272 | tap.drain(..over); |
| 273 | } |
| 274 | |
| 275 | /// Starts a feeder for the current epoch, draining `rx` into the device. |
| 276 | /// `false` if the thread would not start, i.e. nothing will ever be fed. |
| 277 | fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool { |
| 278 | self.spawn_feeder_deferred(move || Some(rx)) |
| 279 | } |
| 280 | |
| 281 | /// As [`spawn_feeder`](Self::spawn_feeder), but the *stream* is opened on |
| 282 | /// the feeder too: `open` runs on that thread, so nothing here touches the |
| 283 | /// disk and the caller pays a thread spawn instead of a demux -- seconds off |
| 284 | /// a cold cache on a big film, which is what a seek used to cost the UI |
| 285 | /// thread ([`crate::DecodeSession::open_worker_deferred`] is the picture's |
| 286 | /// half of the same move). |
| 287 | /// |
| 288 | /// The price is the same one: there is no [`crate::audio::AudioMeta`] to |
| 289 | /// hand back and no synchronous answer to "will anything play". `None` from |
| 290 | /// `open` -- a silent timeline, a source that will not open -- is a feeder |
| 291 | /// with nothing to feed, which ends exactly as a played-out stream does and |
| 292 | /// hands the clock to wall time ([`tick`](PlaybackSession::tick)). |
| 293 | /// |
| 294 | /// The epoch is captured *here*, at the seek, not when the open returns: a |
| 295 | /// scrub abandons opens by the dozen and every one of them must still be |
| 296 | /// the stale stream it was started as, however late it lands. |
| 297 | /// |
| 298 | /// corner-cut: an abandoned open is not *cancelled*, though the machinery |
| 299 | /// for it exists ([`crate::demux::with_cancel`], which the import's Cancel |
| 300 | /// uses): it runs to the end and its answer is dropped. Tried, and left |
| 301 | /// out for want of evidence -- 200 cold scrub steps over the 25 GB HEVC |
| 302 | /// remux measured 101, 137 and 14 live workers on three runs of the *same* |
| 303 | /// build, so the machine decides that number and not this. There is a |
| 304 | /// reason to expect it to hurt, too: a Matroska walk writes its sidecar |
| 305 | /// index only when it finishes (`demux::mkv_blocks`), so a drag that |
| 306 | /// cancels every step's walk would never write one and every step would |
| 307 | /// walk the segment again from the top. Ceiling: an abandoned open keeps |
| 308 | /// reading, and the decoder threads it started live until it does. Upgrade |
| 309 | /// path is an index the walk publishes as it goes -- then cancelling costs |
| 310 | /// nothing and can be measured on an idle machine. |
| 311 | fn spawn_feeder_deferred( |
| 312 | &self, |
| 313 | open: impl FnOnce() -> Option<Receiver<AudioChunk>> + Send + 'static, |
| 314 | ) -> bool { |
| 315 | let me = self.clone(); |
| 316 | let epoch = self.epoch.load(Ordering::Acquire); |
| 317 | // Counted before the spawn, so the count is never behind the thread. |
| 318 | self.feeders.fetch_add(1, Ordering::Release); |
| 319 | let started = thread::Builder::new() |
| 320 | .name("audio-feed".into()) |
| 321 | .spawn(move || { |
| 322 | // Superseded before this thread was even scheduled: do not open |
| 323 | // anything at all. A scrub leaves all but the last one here. |
| 324 | if me.epoch.load(Ordering::Acquire) == epoch { |
| 325 | if let Some(rx) = open() { |
| 326 | feed(rx, &me, epoch); |
| 327 | } |
| 328 | // Only the current feeder gets to declare the end of the |
| 329 | // audio: a superseded one is finished, the stream is not. |
| 330 | if me.epoch.load(Ordering::Acquire) == epoch { |
| 331 | me.fed_all.store(true, Ordering::Release); |
| 332 | } |
| 333 | } |
| 334 | me.feeders.fetch_sub(1, Ordering::Release); |
| 335 | }) |
| 336 | .is_ok(); |
| 337 | if !started { |
| 338 | self.feeders.fetch_sub(1, Ordering::Release); |
| 339 | } |
| 340 | started |
| 341 | } |
| 342 | |
| 343 | /// Feeder threads still running; see [`Self::feeders`]. |
| 344 | fn live_feeders(&self) -> usize { |
| 345 | self.feeders.load(Ordering::Acquire) |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | /// Where the picture of the current span is decoded from. `Cached` is a render |
| 350 | /// cache segment ([`crate::render_cache`]) that already holds the span's frames |
| 351 | /// composed, so the decoder reads that file and nothing else is applied. |
| 352 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 353 | enum Feed { |
| 354 | /// The live path: the project's clips, composed as they play. |
| 355 | Live, |
| 356 | /// A render-cache segment at `segment`, read from its own first frame. |
| 357 | Cached { segment: PathBuf }, |
| 358 | } |
| 359 | |
| 360 | /// How the pictures of a span played backward are numbered (see |
| 361 | /// [`PlaybackSession::stamp`]). Backward the span is the stretch of its clip |
| 362 | /// *up to* the playhead, and its pictures are wanted from the playhead down. |
| 363 | #[derive(Clone, Copy, PartialEq, Debug)] |
| 364 | enum Back { |
| 365 | /// Forward play, or a span (a still, a stack, a visualizer) that is drawn |
| 366 | /// forward whichever way the clock runs. |
| 367 | Off, |
| 368 | /// A forward clip decoded last frame first ([`DecodeSession::open_reversed`] |
| 369 | /// over the file frames ending at `top`). |
| 370 | Mirror { top: u32 }, |
| 371 | /// A reversed clip, whose backward is the file's forward. |
| 372 | Forward, |
| 373 | /// A gap: black numbered from zero, counted down from the span's last frame. |
| 374 | Gap, |
| 375 | } |
| 376 | |
| 377 | /// The cross-dissolve a span's tail owes its successor, tracked from the |
| 378 | /// moment [`PlaybackSession::start_span`] opens A's own decoder until a later |
| 379 | /// `start_span` throws it away. What decides there *is* one mirrors |
| 380 | /// [`crate::export::dissolve_window`] exactly, on the very same span, so a |
| 381 | /// preview blends the window an export would render -- but B's own decoder |
| 382 | /// opens only once the playhead actually reaches it |
| 383 | /// ([`PlaybackSession::open_dissolve_b`]), rather than for the whole span: |
| 384 | /// most of a dissolving clip is never in the window, and a viewer who pauses |
| 385 | /// or seeks away before the tail never pays for a decoder nobody sees. |
| 386 | struct Dissolve { |
| 387 | /// The first *timeline* frame inside the window. |
| 388 | tail_start: u32, |
| 389 | /// How many output frames the blend ramps across. |
| 390 | window: u32, |
| 391 | b_source: usize, |
| 392 | b_in_frame: u32, |
| 393 | /// Where B sits on the timeline -- what its own grade and fit are keyed |
| 394 | /// on ([`Project::composite_color_at`], `composite_fit_at`), the same |
| 395 | /// `b_start` [`crate::export`] grades B's side of the same dissolve by. |
| 396 | b_start: u32, |
| 397 | /// How the picture is blended ([`crate::transitions`]). |
| 398 | kind: crate::transitions::TransitionKind, |
| 399 | /// B's live decode, once open; `None` before the playhead reaches the |
| 400 | /// window. |
| 401 | b: Option<DissolveB>, |
| 402 | } |
| 403 | |
| 404 | /// B's own worker, decoding beside A's for the length of the window. |
| 405 | struct DissolveB { |
| 406 | frames: Receiver<Frame>, |
| 407 | worker: Worker, |
| 408 | /// The last frame B handed over: a tick that lands between two of B's |
| 409 | /// pictures still has one to blend A against, the same "keep showing the |
| 410 | /// last one" policy A's own channel gets from the app's own pump -- done |
| 411 | /// here instead, because B never leaves the engine to be pumped. |
| 412 | held: Option<Frame>, |
| 413 | } |
| 414 | |
| 415 | /// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`]. |
| 416 | /// One track that has ended: where it was, and what it did to its mask. |
| 417 | #[derive(Clone, Debug, PartialEq)] |
| 418 | pub struct TrackDone { |
| 419 | pub lane: Lane, |
| 420 | pub idx: usize, |
| 421 | pub slot: usize, |
| 422 | /// The keys written and the first and last source frame of the path, or why it stopped. |
| 423 | pub result: Result<TrackOutcome, String>, |
| 424 | } |
| 425 | |
| 426 | /// What a finished track wrote: how many keys, the frames it covered, and the frame it |
| 427 | /// was lost at when it stopped early. |
| 428 | #[derive(Clone, Debug, PartialEq)] |
| 429 | pub struct TrackOutcome { |
| 430 | pub keys: usize, |
| 431 | pub from: u32, |
| 432 | pub to: u32, |
| 433 | pub lost_at: Option<u32>, |
| 434 | } |
| 435 | |
| 436 | /// A mask track in progress: the job ([`crate::track::start`]) and the mask it writes to. |
| 437 | #[derive(Clone, Debug, PartialEq)] |
| 438 | pub struct TrackJob { |
| 439 | pub lane: Lane, |
| 440 | pub idx: usize, |
| 441 | pub slot: usize, |
| 442 | pub id: crate::track::JobId, |
| 443 | /// The source frame the track starts from, where its path begins. |
| 444 | pub from: u32, |
| 445 | /// The mask's centre at `from`, in canvas fractions. |
| 446 | pub anchor: (f32, f32), |
| 447 | } |
| 448 | |
| 449 | pub struct PlaybackSession { |
| 450 | /// The thread that plays scrub snippets, made by the first [`PlaybackSession::scrub_audio`]. |
| 451 | scrub: Scrub, |
| 452 | /// The *timeline's* parameters, not any one file's: its frame rate and codec |
| 453 | /// come from source 0 and are what every other source is held to, while |
| 454 | /// `width`/`height` are the **project resolution** -- source 0's picture to |
| 455 | /// begin with, and whatever [`PlaybackSession::set_resolution`] or a saved |
| 456 | /// `resolution` line makes it after that. Every clip is composed onto it, so |
| 457 | /// a file of another size is a placed picture rather than a refusal. |
| 458 | meta: VideoMeta, |
| 459 | /// What source 0's own file declared about how bright it gets |
| 460 | /// ([`crate::colorspace::ContentLight`]) -- MaxCLL/MaxFALL and the |
| 461 | /// mastering display's peak/black, read once at open exactly as `native` |
| 462 | /// is, since the value is a property of the file and never changes under |
| 463 | /// a running session. [`ContentLight::default()`] (every field `None`) |
| 464 | /// for an SDR file and for a song or a still, neither of which is graded. |
| 465 | content_light: ContentLight, |
| 466 | /// Source 0's own picture, kept from the open: the project resolution |
| 467 | /// starts here, and a caller offering sizes to pick from needs the media's |
| 468 | /// own among them or a project moved off it could never come back. |
| 469 | native: (u32, u32), |
| 470 | /// ...and the scaffolding source's own frame rate, kept for exactly that |
| 471 | /// reason: the project rate starts here, and the list a caller offers rates |
| 472 | /// from needs the media's own on it or a project moved off it has no way |
| 473 | /// back ([`PlaybackSession::set_frame_rate`] is not an undo step either). |
| 474 | native_fps: f64, |
| 475 | frames: Receiver<Frame>, |
| 476 | /// The current decode worker. |
| 477 | worker: Worker, |
| 478 | /// What that worker opened -- hardware, software, a still, a gap -- written |
| 479 | /// by the worker itself and read by [`decode_backend`](Self::decode_backend). |
| 480 | /// Replaced with the stream at every seek, so it always describes the |
| 481 | /// pictures currently arriving and never the clip before them. |
| 482 | backend: BackendCell, |
| 483 | /// Why the current span stopped before the end of its range, if it did. |
| 484 | /// Replaced with the stream at every seek for the same reason `backend` is, |
| 485 | /// and read by [`video_failure_reason`](Self::video_failure_reason). |
| 486 | video_failure: crate::decode::DecodeFailure, |
| 487 | /// Workers cancelled by a seek or a clip change, waiting to be reaped. |
| 488 | /// Joining one inline costs whatever VA-API init it is still inside (98 ms |
| 489 | /// measured worst case), which is a visible hitch on the caller's thread; |
| 490 | /// parking it here instead makes that free, and [`retire`] drops the ones |
| 491 | /// that have already returned every time it adds another. |
| 492 | /// |
| 493 | /// Never a leak, and that is the invariant: everything in here is joined |
| 494 | /// when the session drops (`Vec<Worker>`'s own drop does it, one |
| 495 | /// [`Worker::drop`] each), so no decode worker can outlive the session and |
| 496 | /// meet Mesa's `atexit` handlers from inside libva. |
| 497 | /// |
| 498 | /// [`retire`]: PlaybackSession::retire |
| 499 | retired: Vec<Worker>, |
| 500 | /// Picture workers that replaced another one, i.e. every restart the |
| 501 | /// session's first worker did not cost: a seek, a resync, a clip boundary. |
| 502 | /// Each carries a demuxer reopen and a VA-API init, so this is what a |
| 503 | /// playback measurement counts to say how often the picture was thrown away |
| 504 | /// ([`restarts`](Self::restarts)). |
| 505 | restarts: u64, |
| 506 | clock: PlaybackClock, |
| 507 | audio: Option<Audio>, |
| 508 | /// Why this timeline is silent, when the file itself is not: an audio track |
| 509 | /// we cannot decode is a session that plays perfectly and says nothing about |
| 510 | /// it otherwise. `None` for a file that has usable audio *and* for one that |
| 511 | /// has none at all, which is not a surprise worth a notice. |
| 512 | audio_disabled: Option<String>, |
| 513 | /// The edit list. Everything a caller says in seconds is a *timeline* |
| 514 | /// position; only this maps it onto the file. |
| 515 | project: Project, |
| 516 | /// How many frames each source actually holds, indexed exactly as |
| 517 | /// [`Project::sources`] is and grown with it. The project itself does not |
| 518 | /// know -- a clip names a source by index and carries its own range -- and |
| 519 | /// [`Self::trim_clip`] is the one edit that could ask for frames past the |
| 520 | /// end of a file, which is a save that would not open again |
| 521 | /// ([`Self::open_project`] refuses one by name). Append-only for |
| 522 | /// `sources`'s reason: an index handed out stays valid, undone import or |
| 523 | /// not -- with the single exception `sources` itself has, |
| 524 | /// [`Self::remove_source`], which takes the same entry out of both. |
| 525 | counts: Vec<u32>, |
| 526 | /// What a load had to change to open the file, one line per change: a clip that |
| 527 | /// ran past its source is clamped to the source's end rather than refused (see |
| 528 | /// [`PlaybackSession::load_warnings`]). Empty for a project that opened as saved. |
| 529 | load_warnings: Vec<String>, |
| 530 | /// Audio headers already read, by the `(path, stream)` they were read for. |
| 531 | /// Every door that checks a file against the timeline asks the same two |
| 532 | /// questions -- what this file's sound is, and what the timeline's first |
| 533 | /// source's is ([`audio_matches`], [`first_audio_of`]) -- and each answer is |
| 534 | /// a container open. Warm that is 5-10 ms; on a film whose pages have been |
| 535 | /// evicted it is **1.7 s** (measured, 3.1 GB HEVC mkv), and both of those |
| 536 | /// are spent on the thread that draws, because placing and importing are |
| 537 | /// what a drag lands on. A header does not change while a session holds the |
| 538 | /// file, so it is read once and remembered. Errors are not kept: a file that |
| 539 | /// failed to open is asked again next time. |
| 540 | probes: std::collections::HashMap<(std::path::PathBuf, usize), Option<crate::AudioProbe>>, |
| 541 | /// What each source's own frame rate is against this timeline's, indexed |
| 542 | /// and grown exactly as [`Self::counts`] is (and shortened with it by |
| 543 | /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the |
| 544 | /// timeline's rate -- and for a still and a song, which have no rate of |
| 545 | /// their own -- so a single-rate project converts nothing anywhere. |
| 546 | /// |
| 547 | /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that |
| 548 | /// knows which frames of the file those are, and only |
| 549 | /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask. |
| 550 | rates: Vec<Rate>, |
| 551 | /// The rate of the source the current worker is decoding, kept beside |
| 552 | /// [`Self::span`] because the frames coming back are numbered in *its* |
| 553 | /// file's frames and nothing else can put them back on the timeline. |
| 554 | span_rate: Rate, |
| 555 | /// What the current video worker was opened for: where it sits on the |
| 556 | /// timeline, how long it runs, and which source frame it started at -- |
| 557 | /// together they rewrite a source frame index into a timeline one. Not a |
| 558 | /// clip index: a `split` cuts the clip under a running worker, and only the |
| 559 | /// mapping survives that. A span with no source is a *gap*, and the worker |
| 560 | /// feeding it emits black frames indexed from zero. |
| 561 | /// |
| 562 | /// `None` is the *emptied* timeline -- no clip on any lane, so there is no |
| 563 | /// stretch to be inside of. It is a state, not a failure: the picture is |
| 564 | /// black ([`start_span`](Self::start_span) feeds one black frame for it), |
| 565 | /// the sound is silence, the duration is zero, and placing anything reseeks |
| 566 | /// straight back out of it. |
| 567 | span: Option<Span>, |
| 568 | /// Whether the span now decoding still owes its first picture: set by |
| 569 | /// every span start ([`start_span`](Self::start_span)), cleared by the |
| 570 | /// first frame that span hands over ([`try_frame`](Self::try_frame)). |
| 571 | /// This is the window a clip boundary -- or any picture restart -- spends |
| 572 | /// reopening the decoder, and a front-end must not answer a picture that |
| 573 | /// is late by exactly this window's length with another restart of it |
| 574 | /// ([`picture_priming`](Self::picture_priming)). |
| 575 | span_priming: bool, |
| 576 | /// Where the picture of the current span is decoded from ([`Feed`]). |
| 577 | feed: Feed, |
| 578 | /// How the stream feeding the current span is numbered when the clock runs |
| 579 | /// backward ([`Back`]); `Off` at every forward rate. |
| 580 | back: Back, |
| 581 | /// The cross-dissolve the current span's tail owes its successor, if any |
| 582 | /// ([`crate::export::dissolve_window`], the same test an export makes of |
| 583 | /// the same span) -- and, once the playhead has reached the window, B's |
| 584 | /// own decoder, opened beside A's exactly as [`crate::export`] opens one |
| 585 | /// for the render. `None` for a span with no dissolve out, which is every |
| 586 | /// span most of the time. |
| 587 | dissolve: Option<Dissolve>, |
| 588 | /// The last clip has been played out; see [`PlaybackSession::is_eos`]. |
| 589 | /// The size a front-end showing this session *on screen* wants its |
| 590 | /// pictures at, in device pixels ([`Self::set_view_size`]). `None` is the |
| 591 | /// project's own -- every file-level caller, every test, and an export, |
| 592 | /// which has a seat of its own ([`crate::export`]) and never comes here. |
| 593 | view: Option<(u32, u32)>, |
| 594 | eos: bool, |
| 595 | /// Where the timeline ended (seconds) when `eos` was set. The clock runs on |
| 596 | /// past it on wall time, so an edit at the end reseeks here, not to |
| 597 | /// wherever the wall clock has drifted -- which, after a slow drain, can be |
| 598 | /// past the very clip a paste just appended. |
| 599 | eos_end: f64, |
| 600 | /// The mix the running mixer is reading, when there is one: what lets a |
| 601 | /// fader and the master ceiling move without rebuilding the audio pipeline |
| 602 | /// at all ([`crate::audio::MixControls`]). `None` for a timeline that is |
| 603 | /// not mixed -- one audio lane at unity with the limiter off, which is the |
| 604 | /// bit-exact single-stream path -- and the first move off that reopens the |
| 605 | /// stream once, mixed, and lives from there. |
| 606 | mix: Option<Arc<crate::audio::MixControls>>, |
| 607 | /// The audio lanes soloed for listening: while any is set, the other audio |
| 608 | /// lanes are silent in the sound this session plays. Monitoring only -- it |
| 609 | /// is not in the [`Project`], is not saved, and an export never reads it |
| 610 | /// ([`Self::mix_gains`]). Empty is no solo at all. |
| 611 | solo: Vec<Lane>, |
| 612 | /// An audio stream has been started and has not yet played a sample: the |
| 613 | /// window [`tick`](Self::tick) holds the clock still through, so the silence |
| 614 | /// of a restart is never counted as timeline time. See |
| 615 | /// [`Audio::content_at`]. |
| 616 | priming: bool, |
| 617 | /// Whether the decode worker may drop a picture whose moment has already |
| 618 | /// passed ([`Self::drop_late_pictures`]). Off unless a caller says it is |
| 619 | /// watching this in real time. |
| 620 | drop_late: bool, |
| 621 | /// Whether the picture is decoded from the stand-ins rather than from the |
| 622 | /// films ([`crate::proxy`]). One switch for the whole project, saved with |
| 623 | /// it, and *only* the picture: the sound is always the film's own, and so |
| 624 | /// is everything an export reads. |
| 625 | /// |
| 626 | /// Which sources have a stand-in is not kept here -- it is asked of the |
| 627 | /// cache when a span opens ([`Self::picture_path`]), one `stat` against a |
| 628 | /// file open that already costs milliseconds, so a proxy made (or deleted) |
| 629 | /// mid-session is picked up at the next seek and nothing can go stale. |
| 630 | proxies: bool, |
| 631 | /// Whether a source that wants a stand-in gets one made for it as it |
| 632 | /// arrives ([`crate::proxy::wanted`]). On unless a project says otherwise, |
| 633 | /// which is what every project did before the switch existed. Saved with |
| 634 | /// the project like the one above it, and read by the front end: the engine |
| 635 | /// starts no encode of its own. |
| 636 | auto_proxies: bool, |
| 637 | /// Which encoder an export of this project writes its picture with |
| 638 | /// ([`crate::export::EncoderSeat`]). The project's, saved with it like the |
| 639 | /// two switches above, and read by the front end: the engine starts no |
| 640 | /// export of its own. |
| 641 | encoder_seat: crate::export::EncoderSeat, |
| 642 | /// The rate this project's mix was picked to run at |
| 643 | /// ([`crate::edith::Document::sample_rate`]), overriding the one the first |
| 644 | /// audio source would otherwise hand the mixer. `None` -- every project |
| 645 | /// before the field existed, and any project nobody has picked one for -- |
| 646 | /// leaves the derived rate alone. Saved with the project like the switches |
| 647 | /// above it, and read by the front end: the engine picks no rate of its own. |
| 648 | /// |
| 649 | /// Setting it takes effect at the next audio rebuild (a seek, an edit, a |
| 650 | /// reopen); there is no live resample of an audio device already playing. |
| 651 | sample_rate: Option<u32>, |
| 652 | } |
| 653 | |
| 654 | /// What an edit dirtied -- which half of the pipeline has to be rebuilt for the |
| 655 | /// change to be seen or heard, and, far more to the point, which half must not |
| 656 | /// be. |
| 657 | /// |
| 658 | /// Rebuilding a half is expensive and *audible*: the video worker costs a |
| 659 | /// decoder open (98 ms of VA-API init, worst case, measured) and the audio one |
| 660 | /// costs a flush, a re-open and a hole in the sound. A grade changes no sample |
| 661 | /// and a fader changes no picture, so neither may pay the other's price -- that |
| 662 | /// is the whole of this type. |
| 663 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 664 | enum Dirty { |
| 665 | /// The picture only: a grade, a fit policy, the project resolution. The |
| 666 | /// sound keeps playing, untouched, and the clock never moves. |
| 667 | Picture, |
| 668 | /// The sound only: a clip's equalizer. The picture keeps playing. |
| 669 | Sound, |
| 670 | /// The timeline itself -- what is where, how long, how fast. Both halves |
| 671 | /// are rebuilt, because both are decoding the wrong thing. |
| 672 | Both, |
| 673 | } |
| 674 | |
| 675 | /// How [`PlaybackSession::make_multicam_at`] lines the cameras up. |
| 676 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 677 | pub enum MulticamSync { |
| 678 | /// By the loudness curve of each camera's sound. |
| 679 | Audio, |
| 680 | /// Every camera starts at the same moment. |
| 681 | Start, |
| 682 | } |
| 683 | |
| 684 | /// How one angle was placed. |
| 685 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 686 | pub enum AngleSync { |
| 687 | /// The camera the others were lined up with. |
| 688 | Reference, |
| 689 | /// Matched by sound with this normalised correlation (0 to 1). |
| 690 | Audio { score: f32 }, |
| 691 | /// Placed at the start: that was asked for. |
| 692 | Start, |
| 693 | /// Placed at the start: its sound did not match the reference well enough. |
| 694 | Weak { score: f32 }, |
| 695 | /// Placed at the start: the file has no sound. |
| 696 | NoSound, |
| 697 | } |
| 698 | |
| 699 | /// What [`PlaybackSession::make_multicam_at`] did. |
| 700 | #[derive(Clone, Debug)] |
| 701 | pub struct MulticamReport { |
| 702 | pub made: crate::project::MulticamMade, |
| 703 | /// Per angle, how it was placed. |
| 704 | pub how: Vec<AngleSync>, |
| 705 | /// Per angle, seconds later than the reference that its sound happens (0 for unmatched ones). |
| 706 | pub offsets_secs: Vec<f64>, |
| 707 | /// Per angle, where its first frame sits in the multicam clip, in timeline frames. |
| 708 | pub starts: Vec<u32>, |
| 709 | } |
| 710 | |
| 711 | /// One camera of a [`MulticamJob`]. |
| 712 | #[derive(Clone, Debug)] |
| 713 | pub struct MulticamJobSource { |
| 714 | pub index: usize, |
| 715 | pub path: std::path::PathBuf, |
| 716 | pub audio_stream: usize, |
| 717 | pub frames: u32, |
| 718 | } |
| 719 | |
| 720 | /// The reading half of making a multicam clip ([`PlaybackSession::multicam_job`]): the cameras' |
| 721 | /// loudness curves are measured and matched, which takes a while and touches no project state. |
| 722 | #[derive(Clone, Debug)] |
| 723 | pub struct MulticamJob { |
| 724 | sources: Vec<MulticamJobSource>, |
| 725 | sync: MulticamSync, |
| 726 | fps: f64, |
| 727 | } |
| 728 | |
| 729 | /// What [`MulticamJob::run`] found, ready for [`PlaybackSession::apply_multicam`]. |
| 730 | #[derive(Clone, Debug)] |
| 731 | pub struct MulticamPlan { |
| 732 | sources: Vec<MulticamJobSource>, |
| 733 | angles: Vec<crate::project::AngleSpec>, |
| 734 | how: Vec<AngleSync>, |
| 735 | offsets: Vec<f64>, |
| 736 | } |
| 737 | |
| 738 | impl MulticamJob { |
| 739 | /// Measures and matches the cameras. `progress` runs 0..=1000; setting `cancel` stops it at the |
| 740 | /// next camera with an error. |
| 741 | pub fn run(&self, progress: &std::sync::atomic::AtomicU32, cancel: &std::sync::atomic::AtomicBool) -> crate::Result<MulticamPlan> { |
| 742 | use std::sync::atomic::Ordering; |
| 743 | let n = self.sources.len().max(1) as u32; |
| 744 | let range = match self.sync { |
| 745 | MulticamSync::Audio => (0.0, crate::multisync::SYNC_SECS), |
| 746 | MulticamSync::Start => (0.0, 0.5), |
| 747 | }; |
| 748 | let mut curves: Vec<Option<Vec<f32>>> = Vec::new(); |
| 749 | for (i, src) in self.sources.iter().enumerate() { |
| 750 | if cancel.load(Ordering::Relaxed) { |
| 751 | return Err("stopped".into()); |
| 752 | } |
| 753 | let levels = if crate::is_image(&src.path) { None } else { crate::silence::levels(&src.path, src.audio_stream, range).ok().flatten() }; |
| 754 | curves.push(levels); |
| 755 | progress.store((i as u32 + 1) * 900 / n, Ordering::Relaxed); |
| 756 | } |
| 757 | let mut how = vec![AngleSync::Start; self.sources.len()]; |
| 758 | let mut offsets = vec![0.0f64; self.sources.len()]; |
| 759 | if self.sync == MulticamSync::Audio { |
| 760 | let reference = curves.iter().position(Option::is_some); |
| 761 | for (i, c) in curves.iter().enumerate() { |
| 762 | match (reference, c) { |
| 763 | (_, None) => how[i] = AngleSync::NoSound, |
| 764 | (Some(r), Some(_)) if r == i => how[i] = AngleSync::Reference, |
| 765 | (Some(r), Some(c)) => { |
| 766 | let lag = curves[r].as_deref().and_then(|a| crate::multisync::best_lag(a, c, crate::multisync::MAX_LAG_SECS)); |
| 767 | match lag { |
| 768 | Some(l) if l.score >= crate::multisync::MIN_SCORE => { |
| 769 | offsets[i] = l.secs; |
| 770 | how[i] = AngleSync::Audio { score: l.score }; |
| 771 | } |
| 772 | Some(l) => how[i] = AngleSync::Weak { score: l.score }, |
| 773 | None => how[i] = AngleSync::Weak { score: 0.0 }, |
| 774 | } |
| 775 | } |
| 776 | (None, Some(_)) => {} |
| 777 | } |
| 778 | } |
| 779 | } |
| 780 | // `offsets[i]`: the same sound happens that much later in camera i, so camera i started |
| 781 | // that much earlier on the common clock, so it starts at `top - offset`; the earliest at 0. |
| 782 | let top = offsets.iter().copied().fold(0.0, f64::max); |
| 783 | let angles = self |
| 784 | .sources |
| 785 | .iter() |
| 786 | .enumerate() |
| 787 | .map(|(i, s)| crate::project::AngleSpec { |
| 788 | source: s.index, |
| 789 | name: s.path.file_stem().map(|x| x.to_string_lossy().into_owned()).unwrap_or_default(), |
| 790 | frames: s.frames, |
| 791 | start: secs_to_frame(top - offsets[i], self.fps), |
| 792 | audio: curves[i].is_some(), |
| 793 | }) |
| 794 | .collect(); |
| 795 | progress.store(1000, Ordering::Relaxed); |
| 796 | Ok(MulticamPlan { sources: self.sources.clone(), angles, how, offsets }) |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | /// What an import is held to, off a timeline that is already up: the sources |
| 801 | /// its sound has to agree with and the meta its rate is read against. Owned and |
| 802 | /// `Send`, so the check itself can run on a worker with no session in reach -- |
| 803 | /// which is the whole point ([`PlaybackSession::probe_import`]). |
| 804 | #[derive(Clone, Debug, PartialEq)] |
| 805 | pub struct ImportGate { |
| 806 | sources: Vec<Source>, |
| 807 | timeline: VideoMeta, |
| 808 | } |
| 809 | |
| 810 | /// A file read and accepted, waiting to be registered: what |
| 811 | /// [`PlaybackSession::probe_import`] found and |
| 812 | /// [`PlaybackSession::import_probed`] pushes. Carries the gate it was decided |
| 813 | /// against, so a timeline that moved under it can be noticed rather than |
| 814 | /// trusted. |
| 815 | #[derive(Clone, Debug)] |
| 816 | pub struct ImportProbe { |
| 817 | gate: ImportGate, |
| 818 | meta: VideoMeta, |
| 819 | rate: Rate, |
| 820 | } |
| 821 | |
| 822 | /// The project sound rates a person can pick, slowest first: the export sheet and the MCP |
| 823 | /// `project_settings sample_rate` both offer these. "Source" (no pick) is `None`, not a row here. |
| 824 | pub const SAMPLE_RATES: [u32; 3] = [44_100, 48_000, 96_000]; |
| 825 | |
| 826 | /// How long one scrub snippet plays ([`PlaybackSession::scrub_audio`]): long enough to hear |
| 827 | /// what a word or a beat is, short enough that a drag across a second of sound is a run of |
| 828 | /// clicks rather than a smear. |
| 829 | pub const SCRUB_SECS: f64 = 0.07; |
| 830 | /// The fade at each end of a scrub snippet, in seconds ([`scrub_snippet`]). |
| 831 | const SCRUB_FADE_SECS: f64 = 0.01; |
| 832 | |
| 833 | /// One scrub snippet's samples: the window `src` holds (interleaved, `channels` wide) with a |
| 834 | /// raised-cosine fade of `fade` frames at each end, so the snippet starts and stops at silence |
| 835 | /// and no edge of it can click. The fade is held to half the window, and the result is the |
| 836 | /// window's length. |
| 837 | pub fn scrub_snippet(src: &[f32], channels: usize, fade: usize) -> Vec<f32> { |
| 838 | let channels = channels.max(1); |
| 839 | let frames = src.len() / channels; |
| 840 | let mut out = src[..frames * channels].to_vec(); |
| 841 | let fade = fade.min(frames / 2); |
| 842 | for f in 0..fade { |
| 843 | // Rising from just above silence to just below unity over `fade` frames. |
| 844 | let g = 0.5 - 0.5 * (std::f32::consts::PI * (f as f32 + 0.5) / fade as f32).cos(); |
| 845 | for c in 0..channels { |
| 846 | out[f * channels + c] *= g; |
| 847 | out[(frames - 1 - f) * channels + c] *= g; |
| 848 | } |
| 849 | } |
| 850 | out |
| 851 | } |
| 852 | |
| 853 | /// A piece of scrub work: opening and reading a snippet's audio, which happens off the caller's |
| 854 | /// thread. It hands back the device's rate and width and the faded samples. |
| 855 | type ScrubWork = Box<dyn FnOnce() -> Option<(u32, u32, Vec<f32>)> + Send>; |
| 856 | |
| 857 | /// The scrub thread's handle: `None` until the first snippet is asked for. |
| 858 | #[derive(Default)] |
| 859 | struct Scrub { |
| 860 | tx: Option<std::sync::mpsc::Sender<ScrubWork>>, |
| 861 | /// How many snippets have been asked for ([`PlaybackSession::scrub_requests`]). |
| 862 | requests: u64, |
| 863 | } |
| 864 | |
| 865 | /// The scrub thread. It owns one output stream for as long as the rate and width hold, and |
| 866 | /// plays only the newest request: a drag that outruns the decoder skips the ones it left behind. |
| 867 | fn scrub_thread(rx: Receiver<ScrubWork>) { |
| 868 | let mut out: Option<(u32, u32, AoSession)> = None; |
| 869 | while let Ok(mut work) = rx.recv() { |
| 870 | while let Ok(newer) = rx.try_recv() { |
| 871 | work = newer; |
| 872 | } |
| 873 | let Some((rate, channels, samples)) = work() else { |
| 874 | continue; |
| 875 | }; |
| 876 | if out.as_ref().is_none_or(|(r, c, _)| *r != rate || *c != channels) { |
| 877 | out = AoSession::open(rate, channels).map(|ao| (rate, channels, ao)); |
| 878 | } |
| 879 | if let Some((_, _, ao)) = out.as_mut() { |
| 880 | // A snippet replaces the one still sounding, so the newest is heard at once. |
| 881 | ao.flush(); |
| 882 | ao.set_active(true); |
| 883 | ao.write(&samples); |
| 884 | } |
| 885 | } |
| 886 | } |
| 887 | |
| 888 | impl PlaybackSession { |
| 889 | /// Opens `path` and starts both decode workers. Only video failure is fatal: |
| 890 | /// a file we cannot hear is still a file we can watch. |
| 891 | pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> { |
| 892 | Self::open_stream(path, 0) |
| 893 | } |
| 894 | |
| 895 | /// Opens `path` exactly as [`open`](Self::open) does, but binds `stream` -- |
| 896 | /// the index a library row names ([`crate::probe`]'s own numbering of a |
| 897 | /// file's audio tracks) -- as the one that keeps the clock and plays, |
| 898 | /// rather than always the first. What a library preview asks for when the |
| 899 | /// row *is* a particular stream, so a remux with several audio tracks |
| 900 | /// previews the one that was clicked. |
| 901 | pub fn open_with_audio_stream( |
| 902 | path: impl AsRef<Path>, |
| 903 | audio_stream: usize, |
| 904 | ) -> crate::Result<Self> { |
| 905 | Self::open_stream(path, audio_stream) |
| 906 | } |
| 907 | |
| 908 | fn open_stream(path: impl AsRef<Path>, audio_stream: usize) -> crate::Result<Self> { |
| 909 | // Canonical from the first byte: the project canonicalizes every |
| 910 | // source ([`Source::new`]), and [`Worker::reseek`] reuses a decoder |
| 911 | // only when the paths match textually -- a raw path here would make |
| 912 | // every later picture edit pay a full reopen instead of a seek. |
| 913 | let path = crate::project::canonical(path.as_ref()); |
| 914 | // A timeline is normally scaffolded from source 0's picture -- its size, |
| 915 | // its frame rate, its clock. A song has none of that, so it scaffolds |
| 916 | // the *canvas* instead and its own sound keeps the clock: an audio-only |
| 917 | // project is a project like any other, it simply plays black. |
| 918 | if crate::is_audio(&path) { |
| 919 | return Self::open_audio_only(&path, audio_stream); |
| 920 | } |
| 921 | // A still is the other source with no timeline in it: it has a picture |
| 922 | // (which becomes the canvas) but no rate and no length, so it too |
| 923 | // scaffolds rather than describes. |
| 924 | // A numbered run opens as one clip of its frames, the same as an import of it. |
| 925 | if let Some(run) = crate::sequence::Run::parse(&path).or_else(|| crate::sequence::Run::detect(&path)) { |
| 926 | return Self::open_image_only(&run.spelled(), Some(run.count)); |
| 927 | } |
| 928 | if crate::is_image(&path) { |
| 929 | return Self::open_image_only(&path, None); |
| 930 | } |
| 931 | // `open_worker` rather than `open` purely for the worker handle: the |
| 932 | // field has to exist from the start for the first seek to use it. |
| 933 | // Ungraded: a file just opened has one clip per lane and nothing has |
| 934 | // graded it yet. Every later span is opened by `start_span`, which asks |
| 935 | // the project. |
| 936 | // Passthrough: a freshly opened file *is* the project resolution, so |
| 937 | // there is nothing to place it on. Every later span goes through |
| 938 | // `start_span`, which builds the canvas from the project. |
| 939 | let opened = DecodeSession::open_worker( |
| 940 | &path, |
| 941 | 0, |
| 942 | u32::MAX, |
| 943 | ColorParams::default(), |
| 944 | TransformParams::default(), |
| 945 | Composer::passthrough(), |
| 946 | // The default rendition: a file just opened is a project nobody has |
| 947 | // picked one for, exactly as it is a project nobody has graded. |
| 948 | crate::tonemap::Preset::default(), |
| 949 | ); |
| 950 | // `is_audio` above is the extension's word, and an extension can lie: a |
| 951 | // song muxed into an `.mp4` reads as a film until the header is actually |
| 952 | // walked. The demuxer's own `NoVideoTrack` is that walk saying there was |
| 953 | // never a picture in it, and the fallback is the same audio-only door the |
| 954 | // extension check would have taken up front -- not a fault, a type. |
| 955 | let (meta, stream) = match opened { |
| 956 | Ok(opened) => opened, |
| 957 | Err(e) if NoVideoTrack::is_it(&e) => return Self::open_audio_only(&path, audio_stream), |
| 958 | Err(e) => return Err(e), |
| 959 | }; |
| 960 | // A file is opened on its first audio stream by default, like |
| 961 | // `Project::single` names it -- unless a caller through |
| 962 | // `open_with_audio_stream` picked another. |
| 963 | let (audio, audio_disabled) = open_audio(&path, audio_stream); |
| 964 | let source = match audio { |
| 965 | Some(_) => ClockSource::Audio, |
| 966 | None => ClockSource::Wall, |
| 967 | }; |
| 968 | // One clip per lane covering the file, so timeline == source until the |
| 969 | // first edit -- and the range opened above is exactly that clip's. |
| 970 | // The grouped pair runs one length: the sound's when the file's sound is shorter |
| 971 | // than its picture (the walls the save and the load check the audio lane to), so |
| 972 | // the take is sound_held_frames long from the start, not the picture's count. |
| 973 | let held = sound_held_frames(&path, 0, meta.frame_count, meta.frame_rate); |
| 974 | let project = Project::single(&path, held); |
| 975 | let span = crate::export::stack_span_at(&project, 0); |
| 976 | // A second, header-only open purely for the light level: `open_worker` |
| 977 | // above already read one to hand the decode thread its own, but never |
| 978 | // hands it back out. The same trade the audio header cache above this |
| 979 | // makes -- a second container open, paid once at open rather than never |
| 980 | // -- since nothing here decodes a single picture. |
| 981 | let content_light = Demuxer::open(&path) |
| 982 | .map(|(_, d)| d.light()) |
| 983 | .unwrap_or_default(); |
| 984 | Ok(Self { |
| 985 | scrub: Scrub::default(), |
| 986 | load_warnings: Vec::new(), |
| 987 | meta, |
| 988 | content_light, |
| 989 | native: (meta.width, meta.height), |
| 990 | native_fps: meta.frame_rate, |
| 991 | frames: stream.frames, |
| 992 | worker: stream.worker, |
| 993 | backend: stream.backend, |
| 994 | video_failure: stream.failure, |
| 995 | retired: Vec::new(), |
| 996 | restarts: 0, |
| 997 | clock: PlaybackClock::new(source), |
| 998 | audio, |
| 999 | audio_disabled, |
| 1000 | project, |
| 1001 | counts: vec![meta.frame_count], |
| 1002 | probes: std::collections::HashMap::new(), |
| 1003 | // Source 0 *is* the timeline's rate: it defined it. |
| 1004 | rates: vec![Rate::REAL_TIME], |
| 1005 | span_rate: Rate::REAL_TIME, |
| 1006 | span, |
| 1007 | span_priming: true, |
| 1008 | feed: Feed::Live, |
| 1009 | back: Back::Off, |
| 1010 | dissolve: None, |
| 1011 | view: None, |
| 1012 | eos: false, |
| 1013 | eos_end: 0.0, |
| 1014 | mix: None, |
| 1015 | solo: Vec::new(), |
| 1016 | priming: false, |
| 1017 | drop_late: false, |
| 1018 | // A file just opened is a project nobody has picked stand-ins for. |
| 1019 | proxies: false, |
| 1020 | auto_proxies: false, |
| 1021 | encoder_seat: crate::export::EncoderSeat::default(), |
| 1022 | sample_rate: None, |
| 1023 | }) |
| 1024 | } |
| 1025 | |
| 1026 | /// Opens `path` into the **library alone**: everything |
| 1027 | /// [`open`](Self::open) scaffolds from it -- the resolution, the frame |
| 1028 | /// rate, the clock, the source entry and its length -- over an *empty* |
| 1029 | /// timeline. What an import into a window that has no session yet makes, |
| 1030 | /// since an import registers a source and never places a clip |
| 1031 | /// ([`import`](Self::import)); the file reaches a lane when it is dragged |
| 1032 | /// there. |
| 1033 | /// |
| 1034 | /// Nothing to undo, like the import it stands in for: the lanes start |
| 1035 | /// empty rather than being emptied, so no snapshot is pushed. |
| 1036 | pub fn open_library(path: impl AsRef<Path>) -> crate::Result<Self> { |
| 1037 | let mut session = Self::open(path)?; |
| 1038 | // The pair of lanes an opened file comes up with (`Project::single`, |
| 1039 | // `open_audio_only`), emptied -- the source list and so the noted |
| 1040 | // counts are carried over untouched, which is what keeps a library row |
| 1041 | // placeable at its full length. |
| 1042 | session.project = Project::from_parts( |
| 1043 | session.project.sources().to_vec(), |
| 1044 | vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())], |
| 1045 | Vec::new(), |
| 1046 | Vec::new(), |
| 1047 | Vec::new(), |
| 1048 | )?; |
| 1049 | // Onto the emptied mapping: black picture, silence, zero duration. |
| 1050 | session.seek(0.); |
| 1051 | Ok(session) |
| 1052 | } |
| 1053 | |
| 1054 | /// A timeline with no file behind it: a `width` x `height` canvas at `fps`, |
| 1055 | /// no sources and no clips, for a project started from nothing. Its picture |
| 1056 | /// is the black of an uncovered canvas, its length is zero, and the first |
| 1057 | /// import sets the sources the way it does on any session. |
| 1058 | pub fn empty(width: u32, height: u32, fps: f64) -> crate::Result<Self> { |
| 1059 | if width == 0 || height == 0 || fps <= 0.0 { |
| 1060 | return Err(format!("empty timeline: {width}x{height} at {fps} fps").into()); |
| 1061 | } |
| 1062 | let meta = VideoMeta { |
| 1063 | width, |
| 1064 | height, |
| 1065 | frame_rate: fps, |
| 1066 | frame_count: 0, |
| 1067 | codec: Codec::H264, |
| 1068 | color: ColorDescription::default(), |
| 1069 | matrix_assumed: false, |
| 1070 | rotation: Rotation::None, |
| 1071 | coded_width: width, |
| 1072 | coded_height: height, |
| 1073 | pixel_aspect: crate::demux::PixelAspect::SQUARE, |
| 1074 | }; |
| 1075 | let stream = DecodeSession::open_black(width, height, 0); |
| 1076 | Ok(Self { |
| 1077 | scrub: Scrub::default(), |
| 1078 | load_warnings: Vec::new(), |
| 1079 | meta, |
| 1080 | content_light: ContentLight::default(), |
| 1081 | native: (width, height), |
| 1082 | native_fps: fps, |
| 1083 | frames: stream.frames, |
| 1084 | worker: stream.worker, |
| 1085 | backend: stream.backend, |
| 1086 | video_failure: stream.failure, |
| 1087 | retired: Vec::new(), |
| 1088 | restarts: 0, |
| 1089 | clock: PlaybackClock::new(ClockSource::Wall), |
| 1090 | audio: None, |
| 1091 | audio_disabled: None, |
| 1092 | project: Project::from_parts( |
| 1093 | Vec::new(), |
| 1094 | vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())], |
| 1095 | Vec::new(), |
| 1096 | Vec::new(), |
| 1097 | Vec::new(), |
| 1098 | )?, |
| 1099 | counts: Vec::new(), |
| 1100 | probes: std::collections::HashMap::new(), |
| 1101 | rates: Vec::new(), |
| 1102 | span_rate: Rate::REAL_TIME, |
| 1103 | span: None, |
| 1104 | span_priming: true, |
| 1105 | feed: Feed::Live, |
| 1106 | back: Back::Off, |
| 1107 | dissolve: None, |
| 1108 | view: None, |
| 1109 | eos: false, |
| 1110 | eos_end: 0.0, |
| 1111 | mix: None, |
| 1112 | solo: Vec::new(), |
| 1113 | priming: false, |
| 1114 | drop_late: false, |
| 1115 | proxies: false, |
| 1116 | auto_proxies: false, |
| 1117 | encoder_seat: crate::export::EncoderSeat::default(), |
| 1118 | sample_rate: None, |
| 1119 | }) |
| 1120 | } |
| 1121 | |
| 1122 | /// Opens a standalone audio file ([`crate::is_audio`]) as a timeline of its |
| 1123 | /// own: one clip on `A1`, nothing on the video lane, and a picture that is |
| 1124 | /// the black of an uncovered canvas ([`AUDIO_ONLY_CANVAS`]) for as long as |
| 1125 | /// the song runs. Its own sound keeps the clock, exactly as a video's does. |
| 1126 | /// |
| 1127 | /// Refused when the file has no sound to time it by: a source with neither a |
| 1128 | /// picture nor a playable length is not a timeline, and that is what |
| 1129 | /// [`audio_frames`] answers -- the *device* is a different question, and a |
| 1130 | /// machine without one opens this like any other session, silently. |
| 1131 | fn open_audio_only(path: &Path, stream: usize) -> crate::Result<Self> { |
| 1132 | let (width, height, frame_rate) = AUDIO_ONLY_CANVAS; |
| 1133 | let meta = VideoMeta { |
| 1134 | width, |
| 1135 | height, |
| 1136 | frame_rate, |
| 1137 | // Rounded up to whole frames, which is the only frame count a |
| 1138 | // source with no picture has -- the same length `import_audio` |
| 1139 | // gives a song joining a timeline of video. The demuxer's words are |
| 1140 | // named with the file, since this is the door a file that is not |
| 1141 | // really audio at all comes to. |
| 1142 | frame_count: audio_frames(path, frame_rate) |
| 1143 | .map_err(|e| format!("{}: {e}", path.display()))?, |
| 1144 | codec: Codec::H264, |
| 1145 | // A canvas this engine drew itself, not a stream that was read: |
| 1146 | // the default description is what it is drawn in. |
| 1147 | color: ColorDescription::default(), |
| 1148 | matrix_assumed: false, |
| 1149 | rotation: Rotation::None, |
| 1150 | // No container said anything about these: the canvas this engine drew |
| 1151 | // itself is square pixels at the size it was drawn at. |
| 1152 | coded_width: width, |
| 1153 | coded_height: height, |
| 1154 | pixel_aspect: crate::demux::PixelAspect::SQUARE, |
| 1155 | }; |
| 1156 | let (audio, audio_disabled) = open_audio(path, stream); |
| 1157 | // Through `from_parts` rather than `Project::single`, which is the |
| 1158 | // *video* open's pair of grouped clips: here there is no picture to |
| 1159 | // group the sound with, so the video lane starts empty. |
| 1160 | let clip = Clip { |
| 1161 | speed_keys: Vec::new(), |
| 1162 | reversed: false, |
| 1163 | stabilise: None, deinterlace: Default::default(), mark: Default::default(), |
| 1164 | angle: Default::default(), |
| 1165 | fade_in: 0, |
| 1166 | fade_out: 0, |
| 1167 | transition_out: 0, |
| 1168 | transition_kind: Default::default(), |
| 1169 | visualizer: 0, |
| 1170 | viz_paint: 0, |
| 1171 | gain_db: 0.0, |
| 1172 | gain_keys: Vec::new(), |
| 1173 | pan: 0, |
| 1174 | transform_keys: Vec::new(), |
| 1175 | opacity_keys: Vec::new(), |
| 1176 | color_keys: Vec::new(), |
| 1177 | effects: Vec::new(), |
| 1178 | start: 0, |
| 1179 | in_frame: 0, |
| 1180 | out_frame: meta.frame_count, |
| 1181 | source: 0, |
| 1182 | link: None, |
| 1183 | eq: None, |
| 1184 | color: None, |
| 1185 | transform: None, |
| 1186 | fit: FitPolicy::default(), |
| 1187 | speed: Speed::NORMAL, |
| 1188 | pitch: 0.0, |
| 1189 | }; |
| 1190 | let project = Project::from_parts( |
| 1191 | vec![Source::new(path, 0)], |
| 1192 | vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, vec![clip])], |
| 1193 | Vec::new(), |
| 1194 | Vec::new(), |
| 1195 | Vec::new(), |
| 1196 | )?; |
| 1197 | // Every frame of this timeline is a gap, since no video lane covers |
| 1198 | // anything: `composite_span_at` says so and the black worker |
| 1199 | // `start_span` would open is opened here instead, for the reason `open` |
| 1200 | // opens its decoder inline -- the field has to exist for the first seek. |
| 1201 | let span = crate::export::stack_span_at(&project, 0); |
| 1202 | let stream = DecodeSession::open_black(width, height, span.map_or(1, |s| s.len)); |
| 1203 | Ok(Self { |
| 1204 | scrub: Scrub::default(), |
| 1205 | load_warnings: Vec::new(), |
| 1206 | meta, |
| 1207 | content_light: ContentLight::default(), |
| 1208 | native: (width, height), |
| 1209 | native_fps: frame_rate, |
| 1210 | frames: stream.frames, |
| 1211 | worker: stream.worker, |
| 1212 | backend: stream.backend, |
| 1213 | video_failure: stream.failure, |
| 1214 | retired: Vec::new(), |
| 1215 | restarts: 0, |
| 1216 | // The song keeps the clock, as a video's own sound does -- and wall |
| 1217 | // time keeps it on a machine with no device, where the picture |
| 1218 | // (black) still has to move at some rate. |
| 1219 | clock: PlaybackClock::new(match audio { |
| 1220 | Some(_) => ClockSource::Audio, |
| 1221 | None => ClockSource::Wall, |
| 1222 | }), |
| 1223 | audio, |
| 1224 | audio_disabled, |
| 1225 | project, |
| 1226 | counts: vec![meta.frame_count], |
| 1227 | probes: std::collections::HashMap::new(), |
| 1228 | // Source 0 *is* the timeline's rate: it defined it. |
| 1229 | rates: vec![Rate::REAL_TIME], |
| 1230 | span_rate: Rate::REAL_TIME, |
| 1231 | span, |
| 1232 | span_priming: true, |
| 1233 | feed: Feed::Live, |
| 1234 | back: Back::Off, |
| 1235 | dissolve: None, |
| 1236 | view: None, |
| 1237 | eos: false, |
| 1238 | eos_end: 0.0, |
| 1239 | mix: None, |
| 1240 | solo: Vec::new(), |
| 1241 | priming: false, |
| 1242 | drop_late: false, |
| 1243 | // A file just opened is a project nobody has picked stand-ins for. |
| 1244 | proxies: false, |
| 1245 | auto_proxies: false, |
| 1246 | encoder_seat: crate::export::EncoderSeat::default(), |
| 1247 | sample_rate: None, |
| 1248 | }) |
| 1249 | } |
| 1250 | |
| 1251 | /// Opens a still image ([`crate::is_image`]) as a timeline of its own: one |
| 1252 | /// clip on `V1`, [`STILL_DEFAULT_SECS`] long, over silence. The *canvas* is |
| 1253 | /// the image's own picture -- unlike a song, a still has one, and inventing |
| 1254 | /// a 1080p canvas around a 640x360 PNG would letterbox it against nothing. |
| 1255 | /// The frame rate is [`IMAGE_ONLY_RATE`], for the reason an audio-only |
| 1256 | /// timeline has one at all: nothing was shot on it. |
| 1257 | /// |
| 1258 | /// Wall time keeps the clock, as it does for any silent source. |
| 1259 | /// `frames` is the length of a numbered run (its spelling is `path`), or `None` for one picture, |
| 1260 | /// which is held and placed for [`image_frames`] and [`IMAGE_PLACE_SECS`]. |
| 1261 | fn open_image_only(path: &Path, frames: Option<u32>) -> crate::Result<Self> { |
| 1262 | // Decoded here rather than probed: this is the door a `.png` that is |
| 1263 | // not one comes to, and the picture is wanted a line later anyway. |
| 1264 | let still = crate::decode::Still::open(path)?; |
| 1265 | let meta = VideoMeta { |
| 1266 | width: still.width, |
| 1267 | height: still.height, |
| 1268 | frame_rate: IMAGE_ONLY_RATE, |
| 1269 | // Its length is the wall a trim is held to, exactly as a song's |
| 1270 | // playing time is -- see [`image_frames`]. |
| 1271 | frame_count: frames.unwrap_or_else(|| image_frames(IMAGE_ONLY_RATE)), |
| 1272 | codec: Codec::H264, |
| 1273 | color: ColorDescription::default(), |
| 1274 | matrix_assumed: false, |
| 1275 | // `Rotation::None` is honest, not a shrug: a still's own turn was |
| 1276 | // made in `Still::open`, before these planes were written, so the |
| 1277 | // pair below is already the displayed one and there is nothing left |
| 1278 | // for a consumer to make. |
| 1279 | rotation: Rotation::None, |
| 1280 | // No container said anything about these: the picture this engine |
| 1281 | // decoded itself is square pixels at the size it was decoded at. |
| 1282 | coded_width: still.width, |
| 1283 | coded_height: still.height, |
| 1284 | pixel_aspect: crate::demux::PixelAspect::SQUARE, |
| 1285 | }; |
| 1286 | let clip = Clip { |
| 1287 | speed_keys: Vec::new(), |
| 1288 | reversed: false, |
| 1289 | stabilise: None, deinterlace: Default::default(), mark: Default::default(), |
| 1290 | angle: Default::default(), |
| 1291 | fade_in: 0, |
| 1292 | fade_out: 0, |
| 1293 | transition_out: 0, |
| 1294 | transition_kind: Default::default(), |
| 1295 | visualizer: 0, |
| 1296 | viz_paint: 0, |
| 1297 | gain_db: 0.0, |
| 1298 | gain_keys: Vec::new(), |
| 1299 | pan: 0, |
| 1300 | transform_keys: Vec::new(), |
| 1301 | opacity_keys: Vec::new(), |
| 1302 | color_keys: Vec::new(), |
| 1303 | effects: Vec::new(), |
| 1304 | start: 0, |
| 1305 | in_frame: 0, |
| 1306 | out_frame: place_frames(meta.frame_count, IMAGE_ONLY_RATE, STILL_DEFAULT_SECS), |
| 1307 | source: 0, |
| 1308 | link: None, |
| 1309 | eq: None, |
| 1310 | color: None, |
| 1311 | transform: None, |
| 1312 | fit: FitPolicy::default(), |
| 1313 | speed: Speed::NORMAL, |
| 1314 | pitch: 0.0, |
| 1315 | }; |
| 1316 | // No group and no audio clip: a still is silent, and a clip on `A1` |
| 1317 | // playing from a PNG is a source the audio worker cannot open. |
| 1318 | let project = Project::from_parts( |
| 1319 | vec![Source::new(path, 0)], |
| 1320 | vec![(LaneKind::Video, vec![clip]), (LaneKind::Audio, Vec::new())], |
| 1321 | Vec::new(), |
| 1322 | Vec::new(), |
| 1323 | Vec::new(), |
| 1324 | )?; |
| 1325 | let span = crate::export::stack_span_at(&project, 0); |
| 1326 | // The placeholder the first seek supersedes, opened here for `open`'s |
| 1327 | // reason: the field has to exist before anything can seek. |
| 1328 | let stream = DecodeSession::open_still( |
| 1329 | path, |
| 1330 | 0, |
| 1331 | span.map_or(1, |s| s.len), |
| 1332 | ColorParams::default(), |
| 1333 | TransformParams::default(), |
| 1334 | Composer::passthrough(), |
| 1335 | )?; |
| 1336 | Ok(Self { |
| 1337 | scrub: Scrub::default(), |
| 1338 | load_warnings: Vec::new(), |
| 1339 | meta, |
| 1340 | content_light: ContentLight::default(), |
| 1341 | native: (meta.width, meta.height), |
| 1342 | native_fps: IMAGE_ONLY_RATE, |
| 1343 | frames: stream.frames, |
| 1344 | worker: stream.worker, |
| 1345 | backend: stream.backend, |
| 1346 | video_failure: stream.failure, |
| 1347 | retired: Vec::new(), |
| 1348 | restarts: 0, |
| 1349 | clock: PlaybackClock::new(ClockSource::Wall), |
| 1350 | audio: None, |
| 1351 | audio_disabled: None, |
| 1352 | project, |
| 1353 | counts: vec![meta.frame_count], |
| 1354 | probes: std::collections::HashMap::new(), |
| 1355 | // Source 0 *is* the timeline's rate: it defined it. |
| 1356 | rates: vec![Rate::REAL_TIME], |
| 1357 | span_rate: Rate::REAL_TIME, |
| 1358 | span, |
| 1359 | span_priming: true, |
| 1360 | feed: Feed::Live, |
| 1361 | back: Back::Off, |
| 1362 | dissolve: None, |
| 1363 | view: None, |
| 1364 | eos: false, |
| 1365 | eos_end: 0.0, |
| 1366 | mix: None, |
| 1367 | solo: Vec::new(), |
| 1368 | priming: false, |
| 1369 | drop_late: false, |
| 1370 | // A file just opened is a project nobody has picked stand-ins for. |
| 1371 | proxies: false, |
| 1372 | auto_proxies: false, |
| 1373 | encoder_seat: crate::export::EncoderSeat::default(), |
| 1374 | sample_rate: None, |
| 1375 | }) |
| 1376 | } |
| 1377 | |
| 1378 | /// Opens a project file written by [`save_project`](Self::save_project): |
| 1379 | /// the whole timeline, restored to where its playhead stood, paused like |
| 1380 | /// [`open`](Self::open). |
| 1381 | /// |
| 1382 | /// A *new* session rather than a reload of this one, so a load that fails |
| 1383 | /// leaves the caller's current session untouched -- atomic by |
| 1384 | /// construction. Every named file is opened and checked here: the |
| 1385 | /// *scaffolding* source -- the first that is not a still, since a picture |
| 1386 | /// carries no rate -- defines the timeline exactly as `open` does, every |
| 1387 | /// other source has to match it the way [`import`](Self::import) demands |
| 1388 | /// (a save renumbers, so which index that is says nothing), and every clip |
| 1389 | /// has to still be inside the file it plays from. A source that vanished or |
| 1390 | /// shrank since the save is a refusal naming it, not a silently shorter |
| 1391 | /// timeline -- the disappearing-file tolerance elsewhere in this type |
| 1392 | /// applies only *after* a project has loaded. |
| 1393 | /// |
| 1394 | /// The undo history is not saved: `undo` is `false` on a fresh load. |
| 1395 | pub fn open_project(path: &Path) -> crate::Result<Self> { |
| 1396 | Self::open_project_relinked(path, &[]) |
| 1397 | } |
| 1398 | |
| 1399 | /// What the last load changed to open the file, one line per clip it clamped |
| 1400 | /// (a clip that ran past its source). Empty for a project that opened as saved. |
| 1401 | pub fn load_warnings(&self) -> &[String] { |
| 1402 | &self.load_warnings |
| 1403 | } |
| 1404 | |
| 1405 | /// [`open_project`](Self::open_project) with some saved paths replaced: |
| 1406 | /// each `(saved, found)` pair points the source the project saved at `saved` |
| 1407 | /// at `found` before anything is checked. A source whose file is still |
| 1408 | /// missing is **offline**: its clips stay on the timeline, nothing is read |
| 1409 | /// from it, and [`offline_sources`](Self::offline_sources) names it. Only a |
| 1410 | /// project with no present source at all is refused. |
| 1411 | /// A project none of whose sources is on disk: the timeline is the canvas and rate it was saved |
| 1412 | /// with, every clip stays, and every source is offline. Each source's length is the furthest |
| 1413 | /// frame a clip reaches into it, which is what a relink is checked against. |
| 1414 | fn open_all_offline(doc: crate::edith::Document) -> crate::Result<Self> { |
| 1415 | let (width, height) = doc.resolution.unwrap_or((1920, 1080)); |
| 1416 | let fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0).unwrap_or(30.0); |
| 1417 | let counts: Vec<u32> = (0..doc.sources.len()) |
| 1418 | .map(|i| { |
| 1419 | doc.lanes |
| 1420 | .iter() |
| 1421 | .flat_map(|(_, clips)| clips) |
| 1422 | .filter(|clip| clip.source == i) |
| 1423 | .map(|clip| clip.out_frame) |
| 1424 | .max() |
| 1425 | .unwrap_or(0) |
| 1426 | }) |
| 1427 | .collect(); |
| 1428 | let rates = vec![Rate::REAL_TIME; doc.sources.len()]; |
| 1429 | let mut session = Self::empty(width, height, fps)?; |
| 1430 | session.project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)? |
| 1431 | .with_mix(&doc.gains, doc.limiter) |
| 1432 | .with_ducks(&doc.ducks) |
| 1433 | .with_voices(&doc.voices) |
| 1434 | .with_lane_names(&doc.names) |
| 1435 | .with_bins(doc.bins) |
| 1436 | .with_lane_flags(&doc.flags) |
| 1437 | .with_tone(doc.tone) |
| 1438 | .with_notes(doc.notes) |
| 1439 | .with_still_secs(doc.still_secs) |
| 1440 | .with_speech(doc.speech_model, doc.speech_device); |
| 1441 | session.counts = counts; |
| 1442 | session.rates = rates; |
| 1443 | Ok(session) |
| 1444 | } |
| 1445 | |
| 1446 | pub fn open_project_relinked(path: &Path, relinks: &[(PathBuf, PathBuf)]) -> crate::Result<Self> { |
| 1447 | let mut doc = crate::edith::load(path)?; |
| 1448 | for source in doc.sources.iter_mut() { |
| 1449 | if let Some((_, found)) = relinks |
| 1450 | .iter() |
| 1451 | .find(|(saved, _)| crate::project::canonical(saved) == source.path) |
| 1452 | { |
| 1453 | *source = Source { fav: source.fav, bin: source.bin, ..Source::new(found, source.audio_stream) }; |
| 1454 | } |
| 1455 | } |
| 1456 | if doc.sources.iter().all(|s| !crate::source_present(&s.path)) && !doc.sources.is_empty() { |
| 1457 | return Self::open_all_offline(doc); |
| 1458 | } |
| 1459 | // *Which* source scaffolds it: the first that is not a still, and index |
| 1460 | // 0 only when there is no other. A still defines no frame rate -- it is |
| 1461 | // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps |
| 1462 | // footage off a PNG that was imported first and so sits at index 0 |
| 1463 | // (`Project::without_orphan_sources` keeps every source in session |
| 1464 | // order, so whatever was imported first is saved first) reads the |
| 1465 | // timeline as 30 fps and then refuses every file on it for not |
| 1466 | // matching. The rule this and |
| 1467 | // [`audio_source_of`] share: nothing may assume what source 0 *is*. |
| 1468 | // |
| 1469 | // A v9 file says what rate it was cut at, and that answer beats the |
| 1470 | // scaffold's *where the scaffold has none to give*: a still and a song |
| 1471 | // are both given a made-up rate (`IMAGE_ONLY_RATE`, |
| 1472 | // `AUDIO_ONLY_CANVAS`), so a timeline of nothing but those used to come |
| 1473 | // back at 30 fps however it was cut. A scaffold with a picture keeps |
| 1474 | // defining the timeline as it always did -- it is the file every clip |
| 1475 | // on the lane was conformed to, and the two agree by construction. |
| 1476 | let saved_fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0); |
| 1477 | // An offline source cannot scaffold: the first present non-still does, |
| 1478 | // then the first present anything. |
| 1479 | let scaffold = doc |
| 1480 | .sources |
| 1481 | .iter() |
| 1482 | .position(|s| !crate::is_image(&s.path) && crate::source_present(&s.path)) |
| 1483 | .or_else(|| doc.sources.iter().position(|s| crate::source_present(&s.path))) |
| 1484 | .unwrap_or(0); |
| 1485 | // Owned: the sources move into the `Project` below, and the device is |
| 1486 | // opened after that (see the comment there). |
| 1487 | let first = doc |
| 1488 | .sources |
| 1489 | .get(scaffold) |
| 1490 | .cloned() |
| 1491 | .ok_or("the project names no sources")?; |
| 1492 | // The scaffolding source both defines the timeline and is what the |
| 1493 | // playhead's first picture comes from, so it is opened for playback |
| 1494 | // rather than merely probed. |
| 1495 | // One value, not two locals: everything below this line can refuse, and |
| 1496 | // locals drop in reverse declaration order -- a bare worker would join |
| 1497 | // its decode thread while the receiver next to it was still holding |
| 1498 | // that thread parked in `send`, which is a hang (see [`FrameStream`]). |
| 1499 | // Ungraded, and superseded before a frame of it is shown: the `seek` at |
| 1500 | // the end of this function reopens the playhead's span through |
| 1501 | // `start_span`, which is where a saved grade reaches the picture. |
| 1502 | // ...unless it has no picture to open: a project whose source 0 is a |
| 1503 | // song scaffolds the canvas the same way a fresh audio-only open does |
| 1504 | // ([`open_audio_only`](Self::open_audio_only)), and the placeholder |
| 1505 | // black stream is superseded by the `seek` at the end of this function |
| 1506 | // like every other worker opened here. |
| 1507 | // What source 0's own file declares about its light level, read the |
| 1508 | // same way [`open_stream`](Self::open_stream) reads it for a fresh |
| 1509 | // open: [`ContentLight::default()`] for a song or a still, neither of |
| 1510 | // which is graded. |
| 1511 | let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) { |
| 1512 | ContentLight::default() |
| 1513 | } else { |
| 1514 | Demuxer::open(&first.path) |
| 1515 | .map(|(_, d)| d.light()) |
| 1516 | .unwrap_or_default() |
| 1517 | }; |
| 1518 | // The extension's word, corrected below the moment the header disagrees |
| 1519 | // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every |
| 1520 | // later question in this function about source 0 asks *this*, not |
| 1521 | // `crate::is_audio` again, so a discovered song stays one for the rest |
| 1522 | // of the scaffold. |
| 1523 | let mut audio_only = crate::is_audio(&first.path); |
| 1524 | let (mut meta, stream) = match audio_only { |
| 1525 | true => { |
| 1526 | let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS; |
| 1527 | let frame_rate = saved_fps.unwrap_or(canvas_fps); |
| 1528 | let meta = VideoMeta { |
| 1529 | width, |
| 1530 | height, |
| 1531 | frame_rate, |
| 1532 | frame_count: audio_frames(&first.path, frame_rate) |
| 1533 | .map_err(|e| format!("source {}: {e}", first.path.display()))?, |
| 1534 | codec: Codec::H264, |
| 1535 | color: ColorDescription::default(), |
| 1536 | matrix_assumed: false, |
| 1537 | rotation: Rotation::None, |
| 1538 | // No container said anything about these: the canvas this engine drew |
| 1539 | // itself is square pixels at the size it was drawn at. |
| 1540 | coded_width: width, |
| 1541 | coded_height: height, |
| 1542 | pixel_aspect: crate::demux::PixelAspect::SQUARE, |
| 1543 | }; |
| 1544 | (meta, DecodeSession::open_black(width, height, 1)) |
| 1545 | } |
| 1546 | // ...and a still scaffolds its own picture as the canvas, exactly |
| 1547 | // as a fresh `open_image_only` does, with the same placeholder |
| 1548 | // stream the `seek` at the end supersedes. |
| 1549 | false if crate::is_image(&first.path) => { |
| 1550 | let still = crate::decode::Still::open(&first.path) |
| 1551 | .map_err(|e| format!("source {}: {e}", first.path.display()))?; |
| 1552 | let frame_rate = saved_fps.unwrap_or(IMAGE_ONLY_RATE); |
| 1553 | let meta = VideoMeta { |
| 1554 | width: still.width, |
| 1555 | height: still.height, |
| 1556 | frame_rate, |
| 1557 | frame_count: image_frames(frame_rate), |
| 1558 | codec: Codec::H264, |
| 1559 | color: ColorDescription::default(), |
| 1560 | matrix_assumed: false, |
| 1561 | // `Rotation::None` is honest, not a shrug: `Still::open` |
| 1562 | // made the file's own turn before these planes were |
| 1563 | // written, so the pair below is already the displayed one. |
| 1564 | rotation: Rotation::None, |
| 1565 | // No container said anything about these: the picture this |
| 1566 | // engine decoded itself is square pixels at its own size. |
| 1567 | coded_width: still.width, |
| 1568 | coded_height: still.height, |
| 1569 | pixel_aspect: crate::demux::PixelAspect::SQUARE, |
| 1570 | }; |
| 1571 | let stream = DecodeSession::open_still( |
| 1572 | &first.path, |
| 1573 | 0, |
| 1574 | 1, |
| 1575 | ColorParams::default(), |
| 1576 | TransformParams::default(), |
| 1577 | Composer::passthrough(), |
| 1578 | )?; |
| 1579 | (meta, stream) |
| 1580 | } |
| 1581 | false => match DecodeSession::open_worker( |
| 1582 | &first.path, |
| 1583 | 0, |
| 1584 | u32::MAX, |
| 1585 | ColorParams::default(), |
| 1586 | TransformParams::default(), |
| 1587 | Composer::passthrough(), |
| 1588 | // The saved rendition, from the document rather than from the |
| 1589 | // project (which is built below): this placeholder is what the |
| 1590 | // window shows until the `seek` at the end reopens the span. |
| 1591 | doc.tone, |
| 1592 | ) { |
| 1593 | Ok(opened) => opened, |
| 1594 | // A saved source whose extension named a film but whose header |
| 1595 | // names no picture: the same door a fresh open falls to |
| 1596 | // (`open_stream`), so a project first cut around a song muxed |
| 1597 | // into an `.mp4` reloads instead of refusing on a track that was |
| 1598 | // never there to begin with. |
| 1599 | Err(e) if NoVideoTrack::is_it(&e) => { |
| 1600 | audio_only = true; |
| 1601 | let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS; |
| 1602 | let frame_rate = saved_fps.unwrap_or(canvas_fps); |
| 1603 | let meta = VideoMeta { |
| 1604 | width, |
| 1605 | height, |
| 1606 | frame_rate, |
| 1607 | frame_count: audio_frames(&first.path, frame_rate) |
| 1608 | .map_err(|e| format!("source {}: {e}", first.path.display()))?, |
| 1609 | codec: Codec::H264, |
| 1610 | color: ColorDescription::default(), |
| 1611 | matrix_assumed: false, |
| 1612 | rotation: Rotation::None, |
| 1613 | // No container said anything about these: the canvas this engine drew |
| 1614 | // itself is square pixels at the size it was drawn at. |
| 1615 | coded_width: width, |
| 1616 | coded_height: height, |
| 1617 | pixel_aspect: crate::demux::PixelAspect::SQUARE, |
| 1618 | }; |
| 1619 | (meta, DecodeSession::open_black(width, height, 1)) |
| 1620 | } |
| 1621 | Err(e) => return Err(format!("source {}: {e}", first.path.display()).into()), |
| 1622 | }, |
| 1623 | }; |
| 1624 | // The project's own resolution, which is source 0's picture unless the |
| 1625 | // file says otherwise -- every dialect before v7 had no way to say it, |
| 1626 | // and that default is exactly what those projects meant. |
| 1627 | let native = (meta.width, meta.height); |
| 1628 | if let Some((width, height)) = doc.resolution { |
| 1629 | meta.width = width; |
| 1630 | meta.height = height; |
| 1631 | } |
| 1632 | // ...and the project's own *rate*, which is the scaffold's unless the |
| 1633 | // file says otherwise. The two made-up rates above already took the |
| 1634 | // saved one (their counts are computed from it); a scaffold with a |
| 1635 | // picture keeps its own here, so a project cut at a rate nobody picked |
| 1636 | // is the file it always was -- and one where a rate *was* picked |
| 1637 | // ([`set_frame_rate`](Self::set_frame_rate)) comes back at it rather |
| 1638 | // than at the media's, which would leave every clip number counted in |
| 1639 | // frames the timeline no longer has. |
| 1640 | let native_fps = match audio_only { |
| 1641 | true => AUDIO_ONLY_CANVAS.2, |
| 1642 | false if crate::is_image(&first.path) => IMAGE_ONLY_RATE, |
| 1643 | false => meta.frame_rate, |
| 1644 | }; |
| 1645 | if let Some(fps) = saved_fps { |
| 1646 | meta.frame_rate = fps; |
| 1647 | } |
| 1648 | // A song and a still have no rate of their own to be conformed from: |
| 1649 | // their length above was counted in the timeline's frames already, |
| 1650 | // whatever those are. A file with pictures is read through [`Rate`] like |
| 1651 | // any other source when the project is cut at another rate. |
| 1652 | let made_up = audio_only || crate::is_image(&first.path); |
| 1653 | let scaffold_rate = match made_up || native_fps == meta.frame_rate { |
| 1654 | true => Rate::REAL_TIME, |
| 1655 | false => Rate::from_fps(native_fps, meta.frame_rate) |
| 1656 | .map_err(|e| format!("source {}: {e}", first.path.display()))?, |
| 1657 | }; |
| 1658 | let first_audio = first_audio_of(&doc.sources)?; |
| 1659 | |
| 1660 | // In source order, with the scaffold's own count in its own slot: the |
| 1661 | // clip check below indexes this list by source, so it must line up with |
| 1662 | // `doc.sources` whichever entry the scaffolding came from. |
| 1663 | let mut counts = Vec::with_capacity(doc.sources.len()); |
| 1664 | // Beside it, one entry per source, grown at every `push` below: the |
| 1665 | // scaffold defines the rate, so it is read frame for frame; every other |
| 1666 | // one is however long it is *in this timeline's frames*, which is the |
| 1667 | // length `import` noted for it and the wall the clip check below holds |
| 1668 | // it to. |
| 1669 | let mut rates = Vec::with_capacity(doc.sources.len()); |
| 1670 | for (i, source) in doc.sources.iter().enumerate() { |
| 1671 | if i == scaffold { |
| 1672 | counts.push(scaffold_rate.timeline_at(meta.frame_count)); |
| 1673 | rates.push(scaffold_rate); |
| 1674 | continue; |
| 1675 | } |
| 1676 | // Offline: nothing to check it against. Its length is the furthest |
| 1677 | // frame a clip reaches into it, so the clip check below holds. |
| 1678 | if !crate::source_present(&source.path) { |
| 1679 | let reach = doc |
| 1680 | .lanes |
| 1681 | .iter() |
| 1682 | .flat_map(|(_, clips)| clips) |
| 1683 | .filter(|clip| clip.source == i) |
| 1684 | .map(|clip| clip.out_frame) |
| 1685 | .max() |
| 1686 | .unwrap_or(0); |
| 1687 | counts.push(reach); |
| 1688 | rates.push(Rate::REAL_TIME); |
| 1689 | continue; |
| 1690 | } |
| 1691 | // A still has neither a rate to match nor a track to match with: |
| 1692 | // its length is the one it is held to, recomputed exactly as the |
| 1693 | // import that first noted it did ([`image_frames`]), which is what |
| 1694 | // makes the clip check below meaningful on a reload. |
| 1695 | if crate::is_image(&source.path) { |
| 1696 | crate::decode::image_size(&source.path) |
| 1697 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 1698 | counts.push(image_frames(meta.frame_rate)); |
| 1699 | rates.push(Rate::REAL_TIME); |
| 1700 | continue; |
| 1701 | } |
| 1702 | // A source with no picture is checked on what it does have, and |
| 1703 | // its length is its playing time -- the same two answers `import` |
| 1704 | // gave it when it first joined the timeline. |
| 1705 | if crate::is_audio(&source.path) { |
| 1706 | audio_matches(source, &first_audio) |
| 1707 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 1708 | counts.push(audio_frames(&source.path, meta.frame_rate)?); |
| 1709 | rates.push(Rate::REAL_TIME); |
| 1710 | continue; |
| 1711 | } |
| 1712 | // A container with sound but no picture (an audio-only mp4 behind a |
| 1713 | // video extension) is held and counted exactly as `import_audio` holds |
| 1714 | // and counts it when it first joins the timeline -- the same door |
| 1715 | // `import` takes, so a file that imports always reopens. |
| 1716 | let (other, _) = match Demuxer::open(&source.path) { |
| 1717 | Ok(opened) => opened, |
| 1718 | Err(e) if NoVideoTrack::is_it(&e) => { |
| 1719 | audio_matches(source, &first_audio) |
| 1720 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 1721 | counts.push(audio_frames(&source.path, meta.frame_rate)?); |
| 1722 | rates.push(Rate::REAL_TIME); |
| 1723 | continue; |
| 1724 | } |
| 1725 | Err(e) => return Err(format!("source {}: {e}", source.path.display()).into()), |
| 1726 | }; |
| 1727 | let rate = matches_timeline(source, &other, &meta, &first_audio) |
| 1728 | .map_err(|e| format!("source {}: {e}", source.path.display()))?; |
| 1729 | counts.push(rate.timeline_at(other.frame_count)); |
| 1730 | rates.push(rate); |
| 1731 | } |
| 1732 | // A still is silent, so a clip playing one on an audio lane is a |
| 1733 | // segment the audio worker would open a PNG for. Refused by name |
| 1734 | // here, which is the one door it can arrive through |
| 1735 | // (`place_stream_at` never puts one there). An audio file on a |
| 1736 | // *video* lane used to be refused the same way; it plays as a |
| 1737 | // waveform visualizer now ([`DecodeSession::open_visualizer`]). |
| 1738 | for (kind, clip) in doc |
| 1739 | .lanes |
| 1740 | .iter() |
| 1741 | .chain(doc.sequences.iter().flat_map(|s| s.doc.lanes.iter())) |
| 1742 | .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip))) |
| 1743 | .filter(|(_, clip)| !crate::project::is_sequence_source(clip.source)) |
| 1744 | { |
| 1745 | let path = &doc.sources[clip.source].path; |
| 1746 | if kind == LaneKind::Audio && crate::is_image(path) { |
| 1747 | return Err(format!( |
| 1748 | "{} is a still image: it can only play on a video lane", |
| 1749 | path.display() |
| 1750 | ) |
| 1751 | .into()); |
| 1752 | } |
| 1753 | } |
| 1754 | // Each lane is held to the length its own clips are walled by ([`wall_table`]). |
| 1755 | // A clip that runs past its source is clamped to the source's end and |
| 1756 | // reported in `warnings`, not refused: a project that was saved with one |
| 1757 | // (a placement or a trim that used the wrong length) must still open, and |
| 1758 | // the clamp is the one change that keeps every later edit's walls true. |
| 1759 | let audio_walls = wall_table(&doc.sources, &counts, meta.frame_rate, Lane::A1); |
| 1760 | let mut warnings = Vec::new(); |
| 1761 | let mut i = 0; |
| 1762 | let sources = doc.sources.clone(); |
| 1763 | for (kind, clips) in doc |
| 1764 | .lanes |
| 1765 | .iter_mut() |
| 1766 | .chain(doc.sequences.iter_mut().flat_map(|s| s.doc.lanes.iter_mut())) |
| 1767 | { |
| 1768 | let walls: &[u32] = if *kind == LaneKind::Audio { &audio_walls } else { &counts }; |
| 1769 | for clip in clips.iter_mut() { |
| 1770 | let n = i; |
| 1771 | i += 1; |
| 1772 | if crate::project::is_sequence_source(clip.source) { |
| 1773 | continue; |
| 1774 | } |
| 1775 | let wall = walls[clip.source]; |
| 1776 | if clip.out_frame > wall && wall > 0 { |
| 1777 | warnings.push(format!( |
| 1778 | "clip {n} ended at frame {} but {} has {wall} frames: clamped to {wall}", |
| 1779 | clip.out_frame, |
| 1780 | sources[clip.source].path.display(), |
| 1781 | )); |
| 1782 | clip.out_frame = wall; |
| 1783 | if clip.in_frame >= clip.out_frame { |
| 1784 | clip.in_frame = clip.out_frame - 1; |
| 1785 | } |
| 1786 | } |
| 1787 | } |
| 1788 | } |
| 1789 | // The subtitle files are read here rather than in the parser: a |
| 1790 | // `.edith` names them and holds no cues. One that has gone missing, or |
| 1791 | // whose track is a codec of pictures, comes back listed and refused by |
| 1792 | // name ([`crate::subtitle::open_all`]) -- a project does not stop |
| 1793 | // opening over a subtitle, and a re-save does not lose the row. |
| 1794 | // |
| 1795 | // All of them in one call, in saved order, because a file is walked |
| 1796 | // whole to reach one track: a film whose project names many of its |
| 1797 | // tracks is one walk here rather than one per row. |
| 1798 | let playhead = doc.playhead; |
| 1799 | let (proxy, auto_proxy, encoder, sample_rate) = (doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate); |
| 1800 | let seq_active = doc.seq_active.take(); |
| 1801 | let seq_order = std::mem::take(&mut doc.seq_order); |
| 1802 | let seq_docs = std::mem::take(&mut doc.sequences); |
| 1803 | let mcams = std::mem::take(&mut doc.mcams); |
| 1804 | let mut project = project_of(doc, &meta)?; |
| 1805 | if let Some((active, name)) = seq_active { |
| 1806 | // The fresh project's placeholder sequence is not the file's: the file's |
| 1807 | // sequences (the active one by `set_sequence_meta`) are all there is. |
| 1808 | project.clear_sequences(); |
| 1809 | for sd in seq_docs { |
| 1810 | let other = project_of(sd.doc, &meta)?; |
| 1811 | project.absorb_sequence(sd.id, &sd.name, other)?; |
| 1812 | } |
| 1813 | project.set_sequence_meta(active, &name, &seq_order); |
| 1814 | project.set_multicam(&mcams)?; |
| 1815 | project.check_sequences()?; |
| 1816 | } |
| 1817 | let span = crate::export::stack_span_at(&project.render_view(), 0); |
| 1818 | // Last, because it is the one thing here that cannot be taken back: the |
| 1819 | // feeder thread outlives the `Audio` value (it holds its own clones) and |
| 1820 | // only a session's `drop` retires it, so a refusal above this line would |
| 1821 | // leave a PipeWire stream and a thread behind for a project that never |
| 1822 | // opened. Nothing before it needs the device. |
| 1823 | // |
| 1824 | // On the source the timeline's *sound* is defined by, which is the |
| 1825 | // scaffold unless that one is a still ([`audio_source_of`]): opening a |
| 1826 | // PNG as the device is a session with no audio at all, however many |
| 1827 | // clips with sound are on its lanes. |
| 1828 | // |
| 1829 | // `audio_source_of` alone only rules out a still; it says nothing |
| 1830 | // about whether the file it lands on actually *has* a track. A device |
| 1831 | // pinned to the first candidate that opens silent (no track, or one |
| 1832 | // the decoder refuses) would leave every later clip's sound unheard |
| 1833 | // for the rest of the session, however many other sources on the |
| 1834 | // timeline have real audio -- so this walks forward past a silent |
| 1835 | // candidate to the first source that really opens a device, and keeps |
| 1836 | // only the last attempt's reason when none of them do (a later |
| 1837 | // source's silence is not worth reporting over an earlier one's). |
| 1838 | let (audio, audio_disabled) = { |
| 1839 | let mut opened = (None, None); |
| 1840 | for source in project |
| 1841 | .sources() |
| 1842 | .iter() |
| 1843 | .filter(|s| !crate::is_image(&s.path) && crate::source_present(&s.path)) |
| 1844 | { |
| 1845 | opened = open_audio(&source.path, source.audio_stream); |
| 1846 | if opened.0.is_some() { |
| 1847 | break; |
| 1848 | } |
| 1849 | } |
| 1850 | opened |
| 1851 | }; |
| 1852 | let mut session = Self { |
| 1853 | scrub: Scrub::default(), |
| 1854 | meta, |
| 1855 | load_warnings: warnings, |
| 1856 | content_light, |
| 1857 | native, |
| 1858 | native_fps, |
| 1859 | frames: stream.frames, |
| 1860 | worker: stream.worker, |
| 1861 | backend: stream.backend, |
| 1862 | video_failure: stream.failure, |
| 1863 | retired: Vec::new(), |
| 1864 | restarts: 0, |
| 1865 | clock: PlaybackClock::new(match audio { |
| 1866 | Some(_) => ClockSource::Audio, |
| 1867 | None => ClockSource::Wall, |
| 1868 | }), |
| 1869 | audio, |
| 1870 | audio_disabled, |
| 1871 | project, |
| 1872 | counts, |
| 1873 | probes: std::collections::HashMap::new(), |
| 1874 | rates, |
| 1875 | span_rate: Rate::REAL_TIME, |
| 1876 | span, |
| 1877 | span_priming: true, |
| 1878 | feed: Feed::Live, |
| 1879 | back: Back::Off, |
| 1880 | dissolve: None, |
| 1881 | view: None, |
| 1882 | eos: false, |
| 1883 | eos_end: 0.0, |
| 1884 | mix: None, |
| 1885 | solo: Vec::new(), |
| 1886 | priming: false, |
| 1887 | drop_late: false, |
| 1888 | // What the file says, and `false` for every dialect before v12: |
| 1889 | // a project cut on the films themselves opens on them. |
| 1890 | proxies: proxy, |
| 1891 | // ...and what it says about making them, which is "yes" for every |
| 1892 | // dialect before v13 and for one that leaves the line out. |
| 1893 | auto_proxies: auto_proxy, |
| 1894 | // ...and which encoder it exports with, which is the seat this |
| 1895 | // machine has for every dialect before v14. |
| 1896 | encoder_seat: encoder, |
| 1897 | sample_rate, |
| 1898 | }; |
| 1899 | // The scaffolding above opened source 0 from its first frame and the |
| 1900 | // whole of its audio; this puts both onto the clip the playhead is |
| 1901 | // actually in -- a seek replaces the decoder and supersedes the audio |
| 1902 | // worker by epoch, exactly as it does after an edit. It also clamps, |
| 1903 | // so a playhead past a hand-shortened timeline lands on the last frame. |
| 1904 | session.seek(f64::from(playhead) / meta.frame_rate); |
| 1905 | Ok(session) |
| 1906 | } |
| 1907 | |
| 1908 | pub fn meta(&self) -> &VideoMeta { |
| 1909 | &self.meta |
| 1910 | } |
| 1911 | |
| 1912 | /// What the pictures now arriving are being decoded by: the clip under the |
| 1913 | /// playhead, since one video worker feeds the composite at a time. An |
| 1914 | /// atomic load -- a front-end may ask it every repaint -- and it is what |
| 1915 | /// *opened*, so a clip whose hardware session fell back to software reads |
| 1916 | /// [`Backend::Software`] from the frame that fallback happened. |
| 1917 | pub fn decode_backend(&self) -> Backend { |
| 1918 | self.backend.get() |
| 1919 | } |
| 1920 | |
| 1921 | /// What an export of this timeline would encode the *sound* with, before |
| 1922 | /// one is started: the copy an mp4 normally makes, or the software encoder |
| 1923 | /// the format (or an equalized lane) forces. Pure -- no probe, no file |
| 1924 | /// opened -- so a card may ask it per repaint; the picture's half costs a |
| 1925 | /// plugin open and lives in [`crate::export::planned_video`]. |
| 1926 | pub fn planned_audio(&self, format: crate::export::Format, ranged: bool) -> &'static str { |
| 1927 | crate::export::planned_audio(&self.project.render_view(), format, ranged) |
| 1928 | } |
| 1929 | |
| 1930 | /// The timeline an export started right now would be run against, owned: |
| 1931 | /// what lets a front-end ask [`crate::export::planned_seats`] what that |
| 1932 | /// export would open *off* its render thread, which is the only way to ask |
| 1933 | /// a question that opens files. The very snapshot |
| 1934 | /// [`export_to_with`](Self::export_to_with) hands the worker, so the answer |
| 1935 | /// is about the export that would really start. |
| 1936 | pub fn export_snapshot(&self) -> (crate::project::Project, VideoMeta) { |
| 1937 | (self.project.export_snapshot(), self.meta) |
| 1938 | } |
| 1939 | |
| 1940 | /// The timeline's frame rate: what an editor timeline is read at ([`crate::interchange::otio::read`]). |
| 1941 | pub fn timeline_frame_rate(&self) -> f64 { |
| 1942 | self.meta.frame_rate |
| 1943 | } |
| 1944 | |
| 1945 | /// The active sequence as an editor timeline, for the interchange formats ([`crate::interchange`]). |
| 1946 | pub fn timeline_snapshot(&self) -> crate::interchange::Timeline { |
| 1947 | let (project, meta) = self.export_snapshot(); |
| 1948 | crate::interchange::of_project(&project, meta.frame_rate, (meta.width, meta.height)) |
| 1949 | } |
| 1950 | |
| 1951 | /// The composed picture at timeline `frame`, headless and exact: what |
| 1952 | /// export writes for that frame, scaled to fit `width` x `height`. Does not |
| 1953 | /// touch the playback clock. See [`crate::export::compose_at`]. |
| 1954 | pub fn compose_at( |
| 1955 | &self, |
| 1956 | frame: u32, |
| 1957 | width: u32, |
| 1958 | height: u32, |
| 1959 | ) -> crate::Result<crate::decode::Frame> { |
| 1960 | let (project, meta) = self.export_snapshot(); |
| 1961 | crate::export::compose_at(&project, &meta, frame, width, height) |
| 1962 | } |
| 1963 | |
| 1964 | /// What an export would do about the tracks at `picks` -- |
| 1965 | /// [`crate::export::planned_subtitles`], asked of the project a front-end is |
| 1966 | /// holding, and pure for the same reason. `picks` is any run of rows of |
| 1967 | /// [`subtitles`](Self::subtitles): the whole |
| 1968 | /// [`ExportSettings::subtitles`](crate::export::ExportSettings::subtitles) |
| 1969 | /// list a card is about to send (`picks.iter().copied()`) as much as a |
| 1970 | /// single `Some(row)`. |
| 1971 | pub fn planned_subtitles( |
| 1972 | &self, |
| 1973 | format: crate::export::Format, |
| 1974 | picks: impl IntoIterator<Item = usize>, |
| 1975 | ) -> String { |
| 1976 | crate::export::planned_subtitles(&self.project.render_view(), format, picks) |
| 1977 | } |
| 1978 | |
| 1979 | /// Where the cues of the track at `pick` land on *this* timeline -- |
| 1980 | /// [`crate::export::timeline_cues`], the very map an export writes the file |
| 1981 | /// with, so a front-end that draws these draws what the file will say. On a |
| 1982 | /// rippled or cut timeline that is the whole point: an embedded track rides |
| 1983 | /// the spans that still play it, and a standalone `.srt` keeps the |
| 1984 | /// timeline's own clock, clipped to its length. |
| 1985 | /// |
| 1986 | /// Empty for a row that is not there and for a track that could not be read. |
| 1987 | /// Pure and file-free, so it may be asked per repaint; the cost is a walk of |
| 1988 | /// the spans and of the cues. |
| 1989 | pub fn timeline_cues(&self, pick: usize) -> Vec<crate::subtitle::Cue> { |
| 1990 | self.project |
| 1991 | .subtitles() |
| 1992 | .get(pick) |
| 1993 | .map_or_else(Vec::new, |t| { |
| 1994 | crate::export::timeline_cues(&self.project.render_view(), t, self.meta.frame_rate) |
| 1995 | }) |
| 1996 | } |
| 1997 | |
| 1998 | /// Why the sound's rate is not a choice for this timeline in this format -- |
| 1999 | /// [`crate::export::audio_rate_refusal`], asked of the project a front-end |
| 2000 | /// is holding, and pure for the same reason. |
| 2001 | pub fn audio_rate_refusal( |
| 2002 | &self, |
| 2003 | format: crate::export::Format, |
| 2004 | ranged: bool, |
| 2005 | reencode: bool, |
| 2006 | ) -> Option<&'static str> { |
| 2007 | crate::export::audio_rate_refusal(&self.project.render_view(), format, ranged, reencode) |
| 2008 | } |
| 2009 | |
| 2010 | /// Why this session plays silent although the file has sound -- an audio |
| 2011 | /// track in a codec we cannot decode, or one the decoder refused. `None` |
| 2012 | /// when there is audio, and for a file that never had any. A front-end |
| 2013 | /// shows it once, at open: without it the whole thing is a stderr line. |
| 2014 | pub fn audio_disabled_reason(&self) -> Option<&str> { |
| 2015 | self.audio_disabled.as_deref() |
| 2016 | } |
| 2017 | |
| 2018 | /// Why the picture stopped short of the end of its range, if it did -- the |
| 2019 | /// video twin of [`Self::audio_disabled_reason`], and the reason a corrupt |
| 2020 | /// file used to be indistinguishable from a finished one. |
| 2021 | /// |
| 2022 | /// A closed frame channel is not an answer: a span that ran to the end of |
| 2023 | /// the file and a span that gave up on a broken packet both drop the |
| 2024 | /// sender, and [`Self::try_frame`] returns `None` for either. The app read |
| 2025 | /// that as end-of-stream, so a file with a damaged middle froze on its last |
| 2026 | /// good picture and the transport said ENDED -- no notice, no banner, and |
| 2027 | /// nothing on the screen to say the film had stopped being the film. |
| 2028 | /// |
| 2029 | /// `None` for a span that played its whole range, which is the ordinary |
| 2030 | /// case and the one that must stay silent: a notice that fires on every |
| 2031 | /// film is a notice nobody reads. The reason is the engine's own words, for |
| 2032 | /// the same reason the sound one is. |
| 2033 | pub fn video_failure_reason(&self) -> Option<String> { |
| 2034 | self.video_failure.reason() |
| 2035 | } |
| 2036 | |
| 2037 | /// The files this timeline plays from, index 0 first -- a caller needs it |
| 2038 | /// to name an export or a window after the media rather than the project. |
| 2039 | pub fn sources(&self) -> &[Source] { |
| 2040 | self.project.sources() |
| 2041 | } |
| 2042 | |
| 2043 | /// The subtitle tracks on this timeline, in the order they were added: what |
| 2044 | /// a front-end lists and what [`save_project`](Self::save_project) writes. |
| 2045 | /// A track that could not be read is *in* this list, saying why |
| 2046 | /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not |
| 2047 | /// dropped. |
| 2048 | pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] { |
| 2049 | self.project.subtitles() |
| 2050 | } |
| 2051 | |
| 2052 | /// Adds subtitles from `path`: every subtitle track of a Matroska file, or |
| 2053 | /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many |
| 2054 | /// were added -- 0 for a file whose tracks are all on the timeline already, |
| 2055 | /// since importing the same file twice is the same subtitles. |
| 2056 | /// |
| 2057 | /// An error only when the file cannot be read *at all*; a track this cannot |
| 2058 | /// parse is added refused by name, for the reason |
| 2059 | /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves: |
| 2060 | /// subtitles are not clips and land on no lane. |
| 2061 | pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> { |
| 2062 | let tracks = Self::parse_subtitles(path)?; |
| 2063 | // A file that was walked and carries none is refused as *that*, because |
| 2064 | // the alternative -- 0 added -- is the very sentence a file whose tracks |
| 2065 | // are already on this timeline gets, and the two are opposite answers a |
| 2066 | // person acts differently on. Said only after the walk actually looked |
| 2067 | // ([`crate::subtitle::of_media`]); a *file* that is not a container at |
| 2068 | // all never reaches here, [`parse_subtitles`](Self::parse_subtitles) |
| 2069 | // refuses it in its own words. |
| 2070 | if tracks.is_empty() { |
| 2071 | return Err(Self::no_subtitles_in(path)); |
| 2072 | } |
| 2073 | Ok(self.add_subtitle_tracks(tracks)) |
| 2074 | } |
| 2075 | |
| 2076 | /// The reading half of [`import_subtitles`](Self::import_subtitles), with no |
| 2077 | /// session in it: every subtitle track of a Matroska file, or the one track |
| 2078 | /// a standalone `.srt`/`.vtt`/`.ass` is, cues and all. Same refusal rule. |
| 2079 | /// |
| 2080 | /// This is the half that costs -- a walk of the whole container, measured at |
| 2081 | /// 210 ms on a 25 GB 35-track file and 1.3 s on a 3 GB one whose pages were |
| 2082 | /// cold -- so a front-end runs *this* on its background executor and hands |
| 2083 | /// what comes back to [`add_subtitle_tracks`](Self::add_subtitle_tracks), |
| 2084 | /// which costs a push. Both doors are this one function, so the import |
| 2085 | /// button and the background one cannot drift apart. |
| 2086 | pub fn parse_subtitles(path: &Path) -> crate::Result<Vec<crate::subtitle::SubtitleTrack>> { |
| 2087 | // The containers that carry subtitle tracks *inside* them: every |
| 2088 | // Matroska one ([`crate::demux::is_matroska`], which is where `.mks` -- |
| 2089 | // the subtitles alone -- comes in) and the mp4 family, whose `tx3g` |
| 2090 | // timed text is what an mp4 export of this project's own writes, so a |
| 2091 | // file edith wrote is a file edith imports back. A transport stream |
| 2092 | // carries Blu-ray/AVCHD PGS bitmaps the same way. |
| 2093 | let tracks = match crate::demux::is_matroska(path) |
| 2094 | || crate::demux::is_mpegts(path) |
| 2095 | || path.extension().is_some_and(|e| { |
| 2096 | matches!( |
| 2097 | e.to_string_lossy().to_ascii_lowercase().as_str(), |
| 2098 | "mp4" | "m4v" | "mov" | "3gp" | "3g2" |
| 2099 | ) |
| 2100 | }) { |
| 2101 | true => crate::subtitle::of_media(path)?, |
| 2102 | false => vec![crate::subtitle::open(path, None)], |
| 2103 | }; |
| 2104 | // A standalone file that could not be parsed is a refusal here rather |
| 2105 | // than a row nobody asked for: the import is the moment to say so, and |
| 2106 | // the load is the moment to keep it. |
| 2107 | if let [one] = &tracks[..] |
| 2108 | && one.track.is_none() |
| 2109 | && let Some(why) = &one.refused |
| 2110 | { |
| 2111 | return Err(why.clone().into()); |
| 2112 | } |
| 2113 | Ok(tracks) |
| 2114 | } |
| 2115 | |
| 2116 | /// What a file the walk found no subtitle track in is refused with, |
| 2117 | /// wherever the refusal is worded: the engine's own door |
| 2118 | /// ([`import_subtitles`](Self::import_subtitles)) and a front-end that |
| 2119 | /// splits the walk from the push ([`parse_subtitles`](Self::parse_subtitles) |
| 2120 | /// then [`add_subtitle_tracks`](Self::add_subtitle_tracks)) must not tell a |
| 2121 | /// person two different stories about the same file. |
| 2122 | pub fn no_subtitles_in(path: &Path) -> crate::Error { |
| 2123 | format!("no subtitle tracks in {}", path.display()).into() |
| 2124 | } |
| 2125 | |
| 2126 | /// Puts tracks already read by [`parse_subtitles`](Self::parse_subtitles) |
| 2127 | /// on this timeline, in the order given. Hands back how many actually went |
| 2128 | /// on: [`Project::add_subtitles`] drops the ones already here -- same file, |
| 2129 | /// same track number -- so 0 is "this file's subtitles are on the timeline |
| 2130 | /// already", which is the sentence a front-end says. |
| 2131 | /// |
| 2132 | /// The whole of what an import costs the thread that calls it, which is why |
| 2133 | /// the parse is a separate door: nothing here opens, seeks or decodes. |
| 2134 | /// Subtitles are not clips and land on no lane, so nothing playable changes |
| 2135 | /// and no undo step is pushed ([`Project::remove_subtitles`] says why). |
| 2136 | /// [`import_subtitles`](Self::import_subtitles) with a language on its tracks: `lang` as a |
| 2137 | /// person typed it, on every track, or else a standalone file's own name |
| 2138 | /// ([`crate::subtitle::import_language`]). Returns the count added and the language with where |
| 2139 | /// it came from, `None` when none was set. One undo step, as the import is. |
| 2140 | pub fn import_subtitles_as( |
| 2141 | &mut self, |
| 2142 | path: &Path, |
| 2143 | lang: Option<&str>, |
| 2144 | ) -> crate::Result<(usize, Option<(String, &'static str)>)> { |
| 2145 | let mut tracks = Self::parse_subtitles(path)?; |
| 2146 | if tracks.is_empty() { |
| 2147 | return Err(Self::no_subtitles_in(path)); |
| 2148 | } |
| 2149 | let standalone = tracks.iter().all(|t| t.track.is_none()); |
| 2150 | let named = if lang.is_some() || standalone { |
| 2151 | crate::subtitle::import_language(path, lang)? |
| 2152 | } else { |
| 2153 | None |
| 2154 | }; |
| 2155 | if let Some((code, _)) = &named { |
| 2156 | for t in &mut tracks { |
| 2157 | if lang.is_some() || t.track.is_none() { |
| 2158 | crate::subtitle::set_language(t, code); |
| 2159 | } |
| 2160 | } |
| 2161 | } |
| 2162 | let n = self.add_subtitle_tracks(tracks); |
| 2163 | Ok((n, named)) |
| 2164 | } |
| 2165 | |
| 2166 | /// Names the language of subtitle track `track` ([`Project::set_subtitle_language`]). One undo step. |
| 2167 | pub fn set_subtitle_language(&mut self, track: usize, code: &str) -> bool { |
| 2168 | self.project.set_subtitle_language(track, code) |
| 2169 | } |
| 2170 | |
| 2171 | pub fn add_subtitle_tracks(&mut self, tracks: Vec<crate::subtitle::SubtitleTrack>) -> usize { |
| 2172 | // One undo step for the whole import (see [`Project::add_subtitles_all`]). |
| 2173 | self.project.add_subtitles_all(&tracks) |
| 2174 | } |
| 2175 | |
| 2176 | /// Takes the track at `idx` off this timeline -- the door a subtitle row's |
| 2177 | /// own remove goes through, the way [`import_subtitles`]( |
| 2178 | /// Self::import_subtitles) is the door that puts one on. Refused in |
| 2179 | /// [`Project::remove_subtitles`]'s words for a row this timeline does not |
| 2180 | /// have, and for one a caption on a subtitle lane still plays -- delete |
| 2181 | /// those placements first, or the words under them would change. |
| 2182 | /// |
| 2183 | /// Nothing playable changes and no worker was opened against a cue, so |
| 2184 | /// unlike [`remove_source`](Self::remove_source) this does not reseek. Rows |
| 2185 | /// past `idx` move down by one: a caller holding a picked row (the export's |
| 2186 | /// subtitle pick) has to fix it up or drop it; the placements on the lanes |
| 2187 | /// are walked down with it and need no fixing. |
| 2188 | /// |
| 2189 | /// One undo step, and the reindex with it ([`Project::remove_subtitles`]'s |
| 2190 | /// own entry): every step in the history names its tracks by index into the |
| 2191 | /// palette, so an entry carries the palette it was taken beside its lanes -- |
| 2192 | /// which is what lets a `z` put this row back, and every placement that |
| 2193 | /// moved down with it. What that entry cannot bring back is the *pick*: it |
| 2194 | /// is the caller's, and a caller holding one fixes it up or drops it |
| 2195 | /// ([`crate::subs::sub_pick_after_restore`]). |
| 2196 | pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> { |
| 2197 | self.project.remove_subtitles(idx) |
| 2198 | } |
| 2199 | |
| 2200 | /// Writes the timeline to `path` as a `.edith`, atomically (see |
| 2201 | /// [`crate::edith`]). Sources no clip plays from are left out, and the |
| 2202 | /// playhead is saved with it so a reopened project resumes where it stood. |
| 2203 | /// |
| 2204 | /// Refused, writing nothing, for a session whose library is empty (every |
| 2205 | /// row removed, [`Project::remove_source`]): a file naming no source has no |
| 2206 | /// timeline in it and [`open_project`](Self::open_project) could only |
| 2207 | /// refuse it, so the refusal belongs here, where nothing has been |
| 2208 | /// overwritten yet. |
| 2209 | pub fn save_project(&self, path: &Path) -> crate::Result<()> { |
| 2210 | if self.project.sources().is_empty() { |
| 2211 | return Err("this project names no file: there is nothing to save".into()); |
| 2212 | } |
| 2213 | self.save_project_noted(path).map(|_| ()) |
| 2214 | } |
| 2215 | |
| 2216 | /// [`save_project`](Self::save_project) that also returns what it had to change |
| 2217 | /// to write the file, one plain sentence per clip, for the front-end to show. A |
| 2218 | /// clip that runs past its source's end (a placement or an edit that used the |
| 2219 | /// wrong length, or a project saved before the walls held) is shortened to the |
| 2220 | /// source's end on the way out, never refused: the user's work is saved, and the |
| 2221 | /// note says what was shortened. |
| 2222 | pub fn save_project_noted(&self, path: &Path) -> crate::Result<Vec<String>> { |
| 2223 | if self.project.sources().is_empty() { |
| 2224 | return Err("this project names no file: there is nothing to save".into()); |
| 2225 | } |
| 2226 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 2227 | let mut notes = Vec::new(); |
| 2228 | let mut main = self.project.clone(); |
| 2229 | notes.extend(self.wall_notes(&main.clamp_to_walls(&picture, &sound), None)); |
| 2230 | // The parked sequences are saved whole too, so they are held to the same walls. |
| 2231 | let mut parked = Vec::new(); |
| 2232 | for (id, name, active) in self.project.sequence_rows() { |
| 2233 | if !active { |
| 2234 | let mut other = self.project.as_sequence(id)?; |
| 2235 | notes.extend(self.wall_notes(&other.clamp_to_walls(&picture, &sound), Some(&name))); |
| 2236 | parked.push((id, other)); |
| 2237 | } |
| 2238 | } |
| 2239 | self.write_project(path, &main, &parked)?; |
| 2240 | Ok(notes) |
| 2241 | } |
| 2242 | |
| 2243 | /// One plain sentence per clip [`Project::clamp_to_walls`] shortened, naming the |
| 2244 | /// clip by its file's name and its lane. `seq` names a parked sequence. |
| 2245 | fn wall_notes(&self, clamps: &[crate::project::WallClamp], seq: Option<&str>) -> Vec<String> { |
| 2246 | let of = seq.map_or_else(String::new, |n| format!(" in sequence \"{n}\"")); |
| 2247 | clamps |
| 2248 | .iter() |
| 2249 | .map(|c| { |
| 2250 | let path = &self.project.sources()[c.source].path; |
| 2251 | let name = path.file_stem().map_or_else( |
| 2252 | || path.display().to_string(), |
| 2253 | |s| s.to_string_lossy().into_owned(), |
| 2254 | ); |
| 2255 | let what = match c.lane.kind { |
| 2256 | LaneKind::Audio => "sound", |
| 2257 | _ => "picture", |
| 2258 | }; |
| 2259 | format!( |
| 2260 | "The {what} of \"{name}\" on {} runs past the end of its file{of}. It was shortened to fit.", |
| 2261 | c.lane.label(), |
| 2262 | ) |
| 2263 | }) |
| 2264 | .collect() |
| 2265 | } |
| 2266 | |
| 2267 | /// Writes the timeline to `path` for an autosave: exactly what |
| 2268 | /// [`save_project`](Self::save_project) writes, minus its wall check. A clip |
| 2269 | /// that runs past its source is written as it is, not refused, so an |
| 2270 | /// autosave can never fail on a session's state -- the one place a refusal |
| 2271 | /// would lose the edits it was meant to keep. [`open_project`](Self::open_project) |
| 2272 | /// already clamps such a clip to its source with a warning when the file is |
| 2273 | /// read back, so the file still opens. |
| 2274 | /// |
| 2275 | /// The one refusal kept is an empty library ([`save_project`](Self::save_project)): |
| 2276 | /// a file that names no source has no timeline in it to write. |
| 2277 | pub fn save_autosave(&self, path: &Path) -> crate::Result<()> { |
| 2278 | if self.project.sources().is_empty() { |
| 2279 | return Err("this project names no file: there is nothing to save".into()); |
| 2280 | } |
| 2281 | let mut parked = Vec::new(); |
| 2282 | for (id, _, active) in self.project.sequence_rows() { |
| 2283 | if !active { |
| 2284 | parked.push((id, self.project.as_sequence(id)?)); |
| 2285 | } |
| 2286 | } |
| 2287 | self.write_project(path, &self.project, &parked) |
| 2288 | } |
| 2289 | |
| 2290 | /// The write [`save_project`](Self::save_project) and |
| 2291 | /// [`save_autosave`](Self::save_autosave) share: the project as it stands, |
| 2292 | /// atomically, with its playhead and settings. |
| 2293 | /// `main` is the active sequence as it is to be written and `parked` the others, |
| 2294 | /// by id, already held to their walls. |
| 2295 | fn write_project(&self, path: &Path, main: &Project, parked: &[(u32, Project)]) -> crate::Result<()> { |
| 2296 | let dir = crate::edith::project_dir(path); |
| 2297 | let playhead = secs_to_frame(self.now(), self.meta.frame_rate) |
| 2298 | .min(main.timeline_frames().saturating_sub(1)); |
| 2299 | let main_bytes = self.encode_sequence(&dir, main, playhead); |
| 2300 | let main_bytes = crate::edith::binned(main_bytes, self.project.sources(), self.project.bins()); |
| 2301 | let main_bytes = crate::edith::noted(main_bytes, self.project.notes(), self.project.still_secs(), self.project.speech_model(), self.project.speech_device()); |
| 2302 | if !self.project.uses_sequences() { |
| 2303 | return crate::edith::write_atomic(path, &main_bytes); |
| 2304 | } |
| 2305 | // Several sequences: the active one is the body, the others follow as blocks of |
| 2306 | // their own, each a whole document (v45). |
| 2307 | let mut blocks = Vec::new(); |
| 2308 | for (id, name, active) in self.project.sequence_rows() { |
| 2309 | if active { |
| 2310 | continue; |
| 2311 | } |
| 2312 | let Some((_, other)) = parked.iter().find(|(p, _)| *p == id) else { continue }; |
| 2313 | let at = playhead.min(other.timeline_frames().saturating_sub(1)); |
| 2314 | blocks.push(crate::edith::SeqBlock { id, name, bytes: self.encode_sequence(&dir, other, at) }); |
| 2315 | } |
| 2316 | let order: Vec<u32> = self.project.sequence_rows().iter().map(|r| r.0).collect(); |
| 2317 | let active = self.project.active_sequence(); |
| 2318 | let name = self.project.sequence_name(active).unwrap_or("Sequence").to_string(); |
| 2319 | let bytes = crate::edith::sequenced(main_bytes, (active, &name), &order, &blocks, &self.project.multicam_rows()); |
| 2320 | crate::edith::write_atomic(path, &bytes) |
| 2321 | } |
| 2322 | |
| 2323 | /// One sequence as the bytes of a standalone project document: `project` has that |
| 2324 | /// sequence active. |
| 2325 | fn encode_sequence(&self, dir: &Path, project: &Project, playhead: u32) -> Vec<u8> { |
| 2326 | let (sources, lanes, eq, color, transform) = project.without_orphan_sources(); |
| 2327 | crate::edith::encode_flagged( |
| 2328 | dir, |
| 2329 | &sources, |
| 2330 | &lanes, |
| 2331 | // The lane volumes and the limiter with them: a mix that vanished |
| 2332 | // on a reload would be a mix nobody could keep, and both are the |
| 2333 | // project's, not this machine's (the monitoring volume is not |
| 2334 | // written and never will be). |
| 2335 | &project.lane_gains(), |
| 2336 | // ...and what is placed on each lane, in the same order again: the |
| 2337 | // captions, which are the only thing a subtitle lane holds. |
| 2338 | &project.lane_subs(), |
| 2339 | // The subtitle tracks with them, by reference: which file the cues |
| 2340 | // are in, never the cues (see [`crate::edith`]). |
| 2341 | project.subtitles(), |
| 2342 | &eq, |
| 2343 | &color, |
| 2344 | &transform, |
| 2345 | (self.meta.width, self.meta.height), |
| 2346 | // ...and the rate it was cut at, which nothing else in the file |
| 2347 | // says: a timeline of stills and songs used to come back at |
| 2348 | // whatever its scaffold implied (`open_project`). |
| 2349 | Some(self.meta.frame_rate), |
| 2350 | // ...and which rendition its HDR media is watched in, for the same |
| 2351 | // reason: a picked look that vanished on a reload is a look nobody |
| 2352 | // could keep. |
| 2353 | project.tone(), |
| 2354 | // ...and whether it is cut on the stand-ins, for the same reason. |
| 2355 | // *Which* files have one is not saved: [`crate::proxy`] finds that |
| 2356 | // out from the film itself, so nothing here can go stale. |
| 2357 | self.proxies, |
| 2358 | // ...and whether it makes them by itself, which is a different |
| 2359 | // question from whether it cuts on them and the only one an import |
| 2360 | // asks ([`Self::auto_proxies`]). |
| 2361 | self.auto_proxies, |
| 2362 | // ...and which encoder an export of it opens, for the same reason: |
| 2363 | // a project delivered on the software encoder is delivered on it |
| 2364 | // again after a reload. |
| 2365 | self.encoder_seat, |
| 2366 | project.limiter(), |
| 2367 | // ...and the rate the mix was picked to run at, for the same |
| 2368 | // reason: a project delivered at a chosen rate is delivered at it |
| 2369 | // again after a reload. |
| 2370 | self.sample_rate, |
| 2371 | playhead, |
| 2372 | // ...and each lane's switches, hidden, muted or locked, which a |
| 2373 | // reload has to hand back as they were left. |
| 2374 | &project.lane_flags(), |
| 2375 | // ...and each audio lane's duck, by the key lane it names, in the |
| 2376 | // same order again: a ducked music bed that came back unducked |
| 2377 | // would be a mix nobody could keep. |
| 2378 | &project.lane_ducks(), |
| 2379 | // ...and the cues somebody retyped, which live in no file: the words |
| 2380 | // a reload has to hand back as they were typed. |
| 2381 | project.cue_edits(), |
| 2382 | // ...and the cues added to a track, which no file has. |
| 2383 | project.cue_adds(), |
| 2384 | // ...and the title cards and text overlays, which are the project's own. |
| 2385 | project.titles(), |
| 2386 | // ...and the chapter markers, which are the project's own too. |
| 2387 | project.chapters(), |
| 2388 | // ...and the comment markers. |
| 2389 | project.markers(), |
| 2390 | &project.caption_style(), |
| 2391 | // ...and each audio lane's voice processors, which a reload has to |
| 2392 | // hand back as they were left (the noise profile included: it is |
| 2393 | // learned from the sound, and re-learning it would not be the same). |
| 2394 | &project.lane_voices(), |
| 2395 | // ...and the names the user gave the lanes. |
| 2396 | &project.lane_names(), |
| 2397 | ) |
| 2398 | } |
| 2399 | |
| 2400 | /// The next decoded frame, its `index` rewritten from a source frame to a |
| 2401 | /// *timeline* frame -- the only frame space that leaves the engine, and the |
| 2402 | /// one [`PlaybackSession::now`] is in. |
| 2403 | /// |
| 2404 | /// `None` means "nothing right now": the decoder is behind, or a clip |
| 2405 | /// boundary is being reopened -- and *that* now happens entirely on the new |
| 2406 | /// worker ([`DecodeSession::open_worker_deferred`]), so it costs this |
| 2407 | /// thread a thread spawn and the caller simply keeps showing its last frame |
| 2408 | /// for however long the source takes to open (hundreds of milliseconds on a |
| 2409 | /// big film, seconds off a cold cache). End of stream is |
| 2410 | /// [`PlaybackSession::is_eos`]. |
| 2411 | pub fn try_frame(&mut self) -> Option<Frame> { |
| 2412 | self.publish_playhead(); |
| 2413 | loop { |
| 2414 | match self.frames.try_recv() { |
| 2415 | Ok(mut frame) => { |
| 2416 | // A gap's worker indexes from zero, a decoder's from its in |
| 2417 | // point, and the span itself knows which: [`Span::timeline_at`] |
| 2418 | // is the *stamp*, and it is the ceil half of the pair whose |
| 2419 | // floor half an export encodes with -- so the frame the pump |
| 2420 | // is holding at any timeline frame is the very frame the |
| 2421 | // export writes there, at every rate |
| 2422 | // (`speed_maps_both_ways`). An empty timeline has no span, |
| 2423 | // and its one black frame is frame 0. Real time is the |
| 2424 | // arithmetic this always did, frame for frame. |
| 2425 | // ...through the file's own rate first, which is the ceil |
| 2426 | // half of *that* pair: the picture at source frame `i` is |
| 2427 | // due at the first timeline-rate frame that shows it, and a |
| 2428 | // slower file's picture is therefore held for the frames in |
| 2429 | // between. Real time for a gap and for a single-rate |
| 2430 | // project, where this is the identity. |
| 2431 | frame.index = self.stamp(frame.index); |
| 2432 | // The first picture out of the span now decoding ends its |
| 2433 | // prime ([`Self::span_priming`]). |
| 2434 | self.span_priming = false; |
| 2435 | // Inside the dissolve window this span's tail owes its |
| 2436 | // successor, if any: B's own decoder, graded and placed |
| 2437 | // exactly as an export would place it, blended over A's |
| 2438 | // already-converted picture -- the one blend point every |
| 2439 | // path to the screen goes through, playing or scrubbed, |
| 2440 | // since both drain this same channel one frame at a time. |
| 2441 | if self |
| 2442 | .dissolve |
| 2443 | .as_ref() |
| 2444 | .is_some_and(|d| frame.index >= d.tail_start) |
| 2445 | { |
| 2446 | self.open_dissolve_b(); |
| 2447 | } |
| 2448 | if let Some(d) = self.dissolve.as_mut() |
| 2449 | && frame.index >= d.tail_start |
| 2450 | && let Some(b) = d.b.as_mut() |
| 2451 | { |
| 2452 | while let Ok(bf) = b.frames.try_recv() { |
| 2453 | b.held = Some(bf); |
| 2454 | } |
| 2455 | // The window's first tick, with B's decoder not yet |
| 2456 | // caught up: a paused or scrubbed preview gets no |
| 2457 | // later tick to correct itself on (nothing is due |
| 2458 | // while the clock is frozen -- `Player::pump`), so |
| 2459 | // this is the one chance to blend rather than show A |
| 2460 | // alone. Bounded so a source B cannot decode never |
| 2461 | // freezes the preview -- eager-opened in |
| 2462 | // `start_span`, B is normally already warm here and |
| 2463 | // this waits on nothing at all. |
| 2464 | if b.held.is_none() { |
| 2465 | b.held = b.frames.recv_timeout(DISSOLVE_B_TIMEOUT).ok(); |
| 2466 | } |
| 2467 | if let Some(bf) = &b.held { |
| 2468 | let idx_in_window = (frame.index - d.tail_start).min(d.window - 1); |
| 2469 | let t = crate::export::dissolve_weight(idx_in_window, d.window); |
| 2470 | frame.bgra = match d.kind { |
| 2471 | crate::transitions::TransitionKind::Dissolve => { |
| 2472 | blend_bgra(&frame.bgra, &bf.bgra, t) |
| 2473 | } |
| 2474 | kind => crate::transitions::blend_bgra( |
| 2475 | kind, |
| 2476 | &frame.bgra, |
| 2477 | &bf.bgra, |
| 2478 | t, |
| 2479 | frame.width as usize, |
| 2480 | frame.height as usize, |
| 2481 | ), |
| 2482 | }; |
| 2483 | } |
| 2484 | } |
| 2485 | // A picture fade is drawn toward black, the way export draws |
| 2486 | // it ([`crate::export::picture_fade_at`]): black is zero in |
| 2487 | // every colour channel of BGRA, the alpha byte left alone. |
| 2488 | // A layered picture's fades were applied per clip by its worker. |
| 2489 | let fade = match self.span.is_some_and(|s| { |
| 2490 | crate::export::layered_at(&self.project.render_view(), s.start) |
| 2491 | }) { |
| 2492 | true => None, |
| 2493 | false => crate::export::picture_fade_at(&self.project.render_view(), frame.index), |
| 2494 | }; |
| 2495 | if let Some(k) = fade { |
| 2496 | for px in frame.bgra.as_chunks_mut::<4>().0 { |
| 2497 | for c in &mut px[..3] { |
| 2498 | *c = (f32::from(*c) * k).round() as u8; |
| 2499 | } |
| 2500 | } |
| 2501 | } |
| 2502 | return Some(frame); |
| 2503 | } |
| 2504 | Err(TryRecvError::Empty) => return None, |
| 2505 | // The worker stopped: at the end of its range, or on a decode |
| 2506 | // error -- which is why this skips the rest of a broken clip |
| 2507 | // rather than stalling on it. |
| 2508 | Err(TryRecvError::Disconnected) => { |
| 2509 | if !self.next_clip() { |
| 2510 | self.eos = true; |
| 2511 | self.eos_end = |
| 2512 | f64::from(self.project.timeline_frames()) / self.meta.frame_rate; |
| 2513 | return None; |
| 2514 | } |
| 2515 | } |
| 2516 | } |
| 2517 | } |
| 2518 | } |
| 2519 | |
| 2520 | /// Whether the timeline has been played out: the picture worker ran to the |
| 2521 | /// end and there was no next clip. It is exactly that and nothing more, |
| 2522 | /// which is what decides who clears it -- **starting a picture does** |
| 2523 | /// (`start_picture`), so a seek clears it and so does every edit that |
| 2524 | /// rebuilds the picture (`Dirty::Picture`, `Dirty::Both` -- a paste or a |
| 2525 | /// placement past the end revives the session, and it has a new picture to |
| 2526 | /// show for it). |
| 2527 | /// |
| 2528 | /// A **sound-only** edit does not (`Dirty::Sound`: an equalizer, a fader): |
| 2529 | /// it rebuilds the sound where the playhead stands and starts no picture |
| 2530 | /// worker, so the last frame is still the last frame and this is still the |
| 2531 | /// end. A front-end's `Ended` therefore survives an EQ tweak made after the |
| 2532 | /// timeline ran out -- the parameters are on the project either way, and the |
| 2533 | /// next press restarts from the top with them, which is what `Ended` means. |
| 2534 | pub fn is_eos(&self) -> bool { |
| 2535 | self.eos |
| 2536 | } |
| 2537 | |
| 2538 | /// Tells the decode worker which frame of its *file* the clock has reached, |
| 2539 | /// so the pictures it is holding that are already behind the playhead are |
| 2540 | /// dropped where they are cheap to drop -- before the conversion and before |
| 2541 | /// the queue -- instead of being converted, queued and thrown away by the |
| 2542 | /// caller one repaint later. The whole of the late-frame policy: a decoder |
| 2543 | /// that has fallen behind catches up by not painting what nobody can see, |
| 2544 | /// rather than by being restarted every two seconds (`Player::pump`). |
| 2545 | /// |
| 2546 | /// The stamp is the exact inverse of the one [`try_frame`](Self::try_frame) |
| 2547 | /// puts on a decoded frame: timeline frame -> the clip's own frames |
| 2548 | /// ([`Span::speed`]) -> the file's ([`Rate`]). A gap and the emptied |
| 2549 | /// timeline have no file to be inside of, and publish nothing. |
| 2550 | fn publish_playhead(&self) { |
| 2551 | // Backward the worker is not walking toward the clock but away from where |
| 2552 | // it started, and a stale picture is dropped by the pump instead. |
| 2553 | if !self.drop_late || self.backward() { |
| 2554 | return; |
| 2555 | } |
| 2556 | let Some(span) = self.span else { return }; |
| 2557 | let Some((_, in_frame)) = span.from else { |
| 2558 | return; |
| 2559 | }; |
| 2560 | let now = secs_to_frame(self.clock.now(), self.meta.frame_rate); |
| 2561 | let offset = now.saturating_sub(span.start).min(span.len); |
| 2562 | self.worker.playhead( |
| 2563 | self.span_rate |
| 2564 | .source_at(in_frame + span.source_offset(offset)), |
| 2565 | ); |
| 2566 | } |
| 2567 | |
| 2568 | /// Whether the clock runs backward: the picture is then drawn from the |
| 2569 | /// playhead down ([`Back`]) and a pump presents what is *at or after* the |
| 2570 | /// clock instead of at or before it. |
| 2571 | pub fn backward(&self) -> bool { |
| 2572 | self.clock.rate() < 0.0 |
| 2573 | } |
| 2574 | |
| 2575 | /// The playback rate: 1.0 is real time, negative is backward. |
| 2576 | pub fn rate(&self) -> f64 { |
| 2577 | self.clock.rate() |
| 2578 | } |
| 2579 | |
| 2580 | /// The timeline frame a decoded frame numbered `idx` is due at, in the numbering |
| 2581 | /// the current worker was opened with ([`Back`]). Forward it is the ceil half |
| 2582 | /// of the pair an export encodes with ([`Span::timeline_at`]) through the |
| 2583 | /// file's own rate; backward the same mapping read off the file frame the |
| 2584 | /// stream really holds, so the stamps fall as the stream goes on. |
| 2585 | fn stamp(&self, idx: u32) -> u32 { |
| 2586 | let Some(s) = self.span else { return idx }; |
| 2587 | let rate = self.span_rate; |
| 2588 | match self.back { |
| 2589 | Back::Off => s.timeline_at(rate.timeline_at(idx)), |
| 2590 | Back::Mirror { top } => { |
| 2591 | s.timeline_at(rate.timeline_at((2 * top).saturating_sub(idx))) |
| 2592 | } |
| 2593 | Back::Forward => { |
| 2594 | let first = s.from.map_or(0, |(_, f)| f); |
| 2595 | s.timeline_at((2 * first).saturating_sub(rate.timeline_at(idx))) |
| 2596 | } |
| 2597 | Back::Gap => s.start + s.len.saturating_sub(1).saturating_sub(idx), |
| 2598 | } |
| 2599 | } |
| 2600 | |
| 2601 | /// Installs `replacement` as the decode worker, parking the outgoing one in |
| 2602 | /// [`retired`](Self::retired) rather than joining it here, and reaping the |
| 2603 | /// parked ones that have already returned. |
| 2604 | /// |
| 2605 | /// The sweep is what bounds the list: every worker in it was cancelled |
| 2606 | /// before this ran, and a cancelled worker is out within an access unit |
| 2607 | /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's |
| 2608 | /// worker on this seek and the list stays a handful long. Nothing waits. |
| 2609 | fn retire(&mut self, replacement: Worker) { |
| 2610 | // A *replacement*, which is now the narrow case: a seek onto the file |
| 2611 | // the worker already has open steers it instead ([`Worker::reseek`]) |
| 2612 | // and never comes here, so this count is the picture restarts that |
| 2613 | // really cost a thread and a decoder open -- which is what makes it |
| 2614 | // worth counting. |
| 2615 | self.restarts += 1; |
| 2616 | let mut outgoing = std::mem::replace(&mut self.worker, replacement); |
| 2617 | // Terminal, unlike the [`Worker::abandon`] a seek does: this worker is |
| 2618 | // being replaced rather than steered, so its thread has to end -- and |
| 2619 | // the cancel is what drops its command channel, without which a worker |
| 2620 | // parked between spans would sit in `recv` forever, never reaped here |
| 2621 | // and never joined in any bounded time at exit. |
| 2622 | outgoing.cancel(); |
| 2623 | self.retired.push(outgoing); |
| 2624 | self.retired.retain(|w| !w.is_finished()); |
| 2625 | } |
| 2626 | |
| 2627 | /// Picture restarts so far; see [`restarts`](Self::restarts). The one place |
| 2628 | /// a worker is ever replaced counts them, so a seek, a resync and a clip |
| 2629 | /// boundary all land here and a measurement need not guess which it saw. |
| 2630 | #[doc(hidden)] |
| 2631 | pub fn restarts(&self) -> u64 { |
| 2632 | self.restarts |
| 2633 | } |
| 2634 | |
| 2635 | /// Whether the picture span now decoding has yet to hand over a frame: |
| 2636 | /// true from the moment a span is started -- a seek, a clip boundary, a |
| 2637 | /// picture restart -- until that span's first frame arrives. Whatever |
| 2638 | /// lateness that first frame carries is the span's own reopen, not a |
| 2639 | /// decoder falling behind, so a front-end gating its late-picture restart |
| 2640 | /// on this answers a prime with the decode already on its way rather than |
| 2641 | /// with another restart of it. |
| 2642 | pub fn picture_priming(&self) -> bool { |
| 2643 | self.span_priming |
| 2644 | } |
| 2645 | |
| 2646 | /// Whether the picture now playing is read off a render-cache segment |
| 2647 | /// ([`crate::render_cache`]) rather than composed live. |
| 2648 | pub fn playing_from_cache(&self) -> bool { |
| 2649 | matches!(self.feed, Feed::Cached { .. }) |
| 2650 | } |
| 2651 | |
| 2652 | /// The part of `span` a render-cache segment can stand in for, with the |
| 2653 | /// segment it comes from: the span's first frame must be inside a segment |
| 2654 | /// that matches the timeline now, and the span must be a forward clip at |
| 2655 | /// 1x through no dissolve. The returned span keeps the span's own start and |
| 2656 | /// its length up to the segment's end, and reads from the segment's own |
| 2657 | /// first frame ([`Feed::Cached`]), at real time, so the stamp is the identity. |
| 2658 | fn cached_cut( |
| 2659 | &self, |
| 2660 | span: Option<Span>, |
| 2661 | backward: bool, |
| 2662 | ) -> Option<(Span, crate::render_cache::Segment)> { |
| 2663 | let span = span?; |
| 2664 | if backward |
| 2665 | || self.dissolve.is_some() |
| 2666 | || span.reverse |
| 2667 | || span.ramp.is_some() |
| 2668 | || span.speed != Speed::NORMAL |
| 2669 | { |
| 2670 | return None; |
| 2671 | } |
| 2672 | let (source, _) = span.from?; |
| 2673 | let segment = crate::render_cache::at(&self.project, &self.meta, span.start)?; |
| 2674 | let len = span.end().min(segment.to) - span.start; |
| 2675 | let cut = Span { |
| 2676 | len, |
| 2677 | from: Some((source, span.start - segment.from)), |
| 2678 | ..span |
| 2679 | }; |
| 2680 | Some((cut, segment)) |
| 2681 | } |
| 2682 | |
| 2683 | /// Starved audio callbacks since the device opened, and how far into the |
| 2684 | /// device's own playback (seconds) the last of them was -- `None` for a |
| 2685 | /// session with no device at all. The counter the plugin prints on drop, |
| 2686 | /// readable while the session runs: read it either side of a seek and the |
| 2687 | /// difference is what that seek cost the ear. |
| 2688 | #[doc(hidden)] |
| 2689 | pub fn audio_underruns(&self) -> Option<(u64, Option<f64>)> { |
| 2690 | let audio = self.audio.as_ref()?; |
| 2691 | let (count, last) = audio.ao.lock().unwrap().underruns(); |
| 2692 | Some((count, last.map(|p| p as f64 / f64::from(audio.sample_rate)))) |
| 2693 | } |
| 2694 | |
| 2695 | /// How many threads this session still has running of its own: the decode |
| 2696 | /// worker, every retired one that has not returned yet, and the audio |
| 2697 | /// feeders still in the air. One for a session playing along quietly. |
| 2698 | /// |
| 2699 | /// The oracle a seek storm is judged by. `/proc/self/status` counts the |
| 2700 | /// *process*, and a suite decoding twenty files at once moves that number |
| 2701 | /// under a test that never touched them -- this counts only what the |
| 2702 | /// session in hand owns, so it says the same thing alone and in a crowd. |
| 2703 | #[doc(hidden)] |
| 2704 | pub fn live_workers(&self) -> usize { |
| 2705 | usize::from(!self.worker.is_finished()) |
| 2706 | + self.retired.iter().filter(|w| !w.is_finished()).count() |
| 2707 | + self.audio.as_ref().map_or(0, Audio::live_feeders) |
| 2708 | } |
| 2709 | |
| 2710 | /// Starts feeding whatever follows the current span on the timeline -- |
| 2711 | /// another clip, or a gap, which is black frames from a worker that opens no |
| 2712 | /// file. `false` past the end. The next timeline frame is derived rather |
| 2713 | /// than remembered as a clip index, because a `split` while playing cuts the |
| 2714 | /// clip under the running worker and only the mapping stays true. |
| 2715 | fn next_clip(&mut self) -> bool { |
| 2716 | // No span is the emptied timeline: it was played out the moment its one |
| 2717 | // black frame went by, and there is no "next" to walk to. |
| 2718 | let backward = self.backward(); |
| 2719 | let span = match (self.span, backward) { |
| 2720 | (None, _) => return false, |
| 2721 | // Backward the next stretch to draw is the one that ends just before |
| 2722 | // this one starts, and the start of the timeline is where it ends. |
| 2723 | (Some(span), true) => match span.start.checked_sub(1) { |
| 2724 | Some(frame) => back_span_at(&self.project.render_view(), frame), |
| 2725 | None => return false, |
| 2726 | }, |
| 2727 | (Some(span), false) => crate::export::stack_span_at(&self.project.render_view(), span.end()), |
| 2728 | }; |
| 2729 | let Some(span) = span else { return false }; |
| 2730 | // We only get here on a disconnect, so the old span is already done; |
| 2731 | // abandon anyway, so `start_span` treats every path alike -- and the |
| 2732 | // *worker* is kept, because the next clip is very often the same file |
| 2733 | // (a split cuts one clip in two) and it already has it open. |
| 2734 | self.worker.abandon(); |
| 2735 | self.start_span(Some(span)); |
| 2736 | true |
| 2737 | } |
| 2738 | |
| 2739 | /// Points the video worker at `span`: a decoder over its source range, or a |
| 2740 | /// black-frame generator for a gap -- and for `None`, the emptied timeline, |
| 2741 | /// which is one frame of black so the viewer shows the nothing that is |
| 2742 | /// there rather than the last picture of the clip that was deleted. The old |
| 2743 | /// worker must already have been cancelled -- this is the half both `seek` |
| 2744 | /// and `next_clip` share. |
| 2745 | /// |
| 2746 | /// A source that will not open leaves the *span* installed anyway: the |
| 2747 | /// timeline still moves, there are simply no more pictures, and the |
| 2748 | /// disconnected receiver carries the session on to the next span. For a |
| 2749 | /// video that is now the worker's own doing -- it opens the file, so it is |
| 2750 | /// the one that finds out -- and nothing on this thread waits to hear it. |
| 2751 | fn start_span(&mut self, span: Option<Span>) { |
| 2752 | // The viewer's own size, once one has said it ([`Self::set_view_size`]): |
| 2753 | // every picture below is painted at *this*, and the project's |
| 2754 | // resolution otherwise. |
| 2755 | let (canvas_w, canvas_h) = self.view_size(); |
| 2756 | // The outgoing span's own dissolve, if it ever opened B's decoder: |
| 2757 | // that decoder's pictures were for a window this span is leaving |
| 2758 | // (played through, paused before, or seeked away from), and never |
| 2759 | // for the one about to start -- parked in `retired` exactly like the |
| 2760 | // picture worker below, so joining it costs this thread nothing. |
| 2761 | if let Some(Dissolve { b: Some(b), .. }) = self.dissolve.take() { |
| 2762 | let mut worker = b.worker; |
| 2763 | worker.cancel(); |
| 2764 | self.retired.push(worker); |
| 2765 | self.retired.retain(|w| !w.is_finished()); |
| 2766 | } |
| 2767 | // What the *new* span's own tail owes its successor -- checked here, |
| 2768 | // once, rather than every tick: adjacency can only change on an edit, |
| 2769 | // and every edit that could touches this span starts it over |
| 2770 | // ([`crate::export::dissolve_window`] makes the identical check for |
| 2771 | // the same reason, on export). |
| 2772 | let backward = self.backward(); |
| 2773 | self.back = Back::Off; |
| 2774 | self.dissolve = span.filter(|_| !backward).and_then(|s| { |
| 2775 | crate::export::dissolve_window(&self.project.render_view(), &s).map( |
| 2776 | |(b_source, b_in_frame, window, b_start)| Dissolve { |
| 2777 | tail_start: s.start + s.len - window, |
| 2778 | window, |
| 2779 | b_source, |
| 2780 | b_in_frame, |
| 2781 | b_start, |
| 2782 | kind: crate::transitions::kind_at(&self.project.render_view(), s.start), |
| 2783 | b: None, |
| 2784 | }, |
| 2785 | ) |
| 2786 | }); |
| 2787 | // B's decoder opens now, at the start of the *span*, rather than |
| 2788 | // waiting for the playhead to reach the window: the window is about a |
| 2789 | // second, which is exactly the head start a decoder open (VA-API |
| 2790 | // init measured 98ms worst case) needs to have a first picture ready |
| 2791 | // by the time playback -- or a seek straight into the window -- asks |
| 2792 | // for one. Without this a paused seek into the window met a `held` |
| 2793 | // that was still `None` and nothing ever asked again |
| 2794 | // (`try_frame`'s bounded wait below is the last-resort backstop for a |
| 2795 | // seek that lands inside the window before this head start pays off). |
| 2796 | if self.dissolve.is_some() { |
| 2797 | self.open_dissolve_b(); |
| 2798 | } |
| 2799 | // Which file's frames the worker about to be opened will number its |
| 2800 | // pictures in: the span's own source, and real time for a gap, whose |
| 2801 | // black worker counts timeline frames already. Set before the open, |
| 2802 | // because the open is the first thing that converts with it. |
| 2803 | // A layered span's worker numbers its frames on the timeline itself |
| 2804 | // ([`crate::export::layered_stream`]), so it is read at real time. |
| 2805 | let layered = span.is_some_and(|s| crate::export::layered_at(&self.project.render_view(), s.start)); |
| 2806 | // A field-mode clip of an interlaced file is decoded as fields, two to a |
| 2807 | // frame: the decoder's frame numbers are field numbers, so the file's |
| 2808 | // rate against the timeline doubles ([`crate::deinterlace::fields_rate`]). |
| 2809 | let deint = match span.and_then(|s| s.from) { |
| 2810 | Some((source, _)) if !layered => self.deint_at(source, span.map_or(0, |s| s.start)), |
| 2811 | _ => crate::project::Deinterlace::Frame, |
| 2812 | }; |
| 2813 | self.span_rate = match span.and_then(|s| s.from) { |
| 2814 | Some((source, _)) if !layered => { |
| 2815 | let rate = self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME); |
| 2816 | crate::deinterlace::counted_rate(deint, rate) |
| 2817 | } |
| 2818 | _ => Rate::REAL_TIME, |
| 2819 | }; |
| 2820 | // The new span owes its first picture from the moment it is asked for: |
| 2821 | // every path below, the reused worker as much as a fresh one |
| 2822 | // ([`Self::span_priming`]). |
| 2823 | self.span_priming = true; |
| 2824 | // A render-cache segment over this span's first frame plays the render |
| 2825 | // instead of compositing it ([`Feed::Cached`]). Only forward at 1x and |
| 2826 | // never through a dissolve; every other span stays on the live path. |
| 2827 | self.feed = Feed::Live; |
| 2828 | if let Some((cut, segment)) = self.cached_cut(span, backward) { |
| 2829 | let source_frame = cut.from.map_or(0, |(_, f)| f); |
| 2830 | let end = source_frame + cut.len; |
| 2831 | self.span_rate = Rate::REAL_TIME; |
| 2832 | // The render already holds the grade, transform, fit, tone and |
| 2833 | // effects, so the decoder applies none of them. |
| 2834 | let stream = DecodeSession::open_worker_deferred_with( |
| 2835 | &segment.path, |
| 2836 | source_frame, |
| 2837 | end, |
| 2838 | ColorParams::default(), |
| 2839 | TransformParams::default(), |
| 2840 | Composer::new(canvas_w, canvas_h, FitPolicy::default()), |
| 2841 | self.project.tone(), |
| 2842 | Speed::NORMAL, |
| 2843 | crate::project::Deinterlace::Frame, |
| 2844 | ); |
| 2845 | self.frames = stream.frames; |
| 2846 | self.backend = stream.backend; |
| 2847 | self.retire(stream.worker); |
| 2848 | self.span = Some(cut); |
| 2849 | self.feed = Feed::Cached { segment: segment.path }; |
| 2850 | return; |
| 2851 | } |
| 2852 | let opened = match span { |
| 2853 | // Two or more clips cover the span: its composed pictures come from a |
| 2854 | // stream of their own, each clip drawn over the ones beneath it as an |
| 2855 | // export draws them, at the viewer's size. |
| 2856 | Some(span) if layered => { |
| 2857 | let mut view_meta = self.meta; |
| 2858 | view_meta.width = canvas_w; |
| 2859 | view_meta.height = canvas_h; |
| 2860 | // Each clip's picture comes off its stand-in when the project is |
| 2861 | // cut on stand-ins, the way a single clip's does ([`picture_path`]). |
| 2862 | let paths = self.proxies.then(|| { |
| 2863 | self.project |
| 2864 | .sources() |
| 2865 | .iter() |
| 2866 | .map(|s| crate::proxy::cached(&s.path).unwrap_or_else(|| s.path.clone())) |
| 2867 | .collect() |
| 2868 | }); |
| 2869 | Ok(crate::export::layered_stream( |
| 2870 | self.project.export_snapshot(), |
| 2871 | view_meta, |
| 2872 | crate::colorspace::ColorDescription::output_sized(self.meta.width, self.meta.height), |
| 2873 | span, |
| 2874 | paths, |
| 2875 | )) |
| 2876 | } |
| 2877 | // The grade is the composite's at this frame -- the same clip the |
| 2878 | // span itself came from -- and it is constant across the span, so |
| 2879 | // the worker carries it and every frame it converts wears it. |
| 2880 | Some(Span { |
| 2881 | start, |
| 2882 | from: Some((source, in_frame)), |
| 2883 | .. |
| 2884 | }) if crate::is_image(&self.project.sources()[source].path) => { |
| 2885 | // A still: the same grade and the same canvas as any other |
| 2886 | // clip, over a picture decoded once and repeated for the span. |
| 2887 | // As many pictures as the span reads *source* frames, so a still |
| 2888 | // is numbered like a decoder's output and a speed reaches it |
| 2889 | // through the same rewrite (`try_frame`) as any other clip. |
| 2890 | DecodeSession::open_still( |
| 2891 | &self.project.sources()[source].path, |
| 2892 | in_frame, |
| 2893 | span.expect("matched above").source_len(), |
| 2894 | self.project |
| 2895 | .composite_color_at(start) |
| 2896 | .copied() |
| 2897 | .unwrap_or_default(), |
| 2898 | self.project |
| 2899 | .composite_transform_at(start) |
| 2900 | .copied() |
| 2901 | .unwrap_or_default(), |
| 2902 | Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(start)), |
| 2903 | ) |
| 2904 | .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}")) |
| 2905 | } |
| 2906 | Some(Span { |
| 2907 | start, |
| 2908 | from: Some((source, in_frame)), |
| 2909 | .. |
| 2910 | }) if crate::is_audio(&self.project.sources()[source].path) |
| 2911 | || self.project.render_view().composite_visualizer_at(start) & 1 != 0 => |
| 2912 | { |
| 2913 | let (path, stream) = { |
| 2914 | let src = &self.project.sources()[source]; |
| 2915 | (src.path.clone(), src.audio_stream) |
| 2916 | }; |
| 2917 | DecodeSession::open_visualizer( |
| 2918 | &path, |
| 2919 | stream, |
| 2920 | in_frame, |
| 2921 | span.expect("matched above").source_len(), |
| 2922 | self.meta.frame_rate, |
| 2923 | self.project |
| 2924 | .composite_color_at(start) |
| 2925 | .copied() |
| 2926 | .unwrap_or_default(), |
| 2927 | self.project |
| 2928 | .composite_transform_at(start) |
| 2929 | .copied() |
| 2930 | .unwrap_or_default(), |
| 2931 | Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(start)), |
| 2932 | self.project.render_view().composite_visualizer_at(start), |
| 2933 | self.project.render_view().composite_viz_paint_at(start), |
| 2934 | ) |
| 2935 | .inspect_err(|e| eprintln!("timeline frame {start}: visualizer open failed: {e}")) |
| 2936 | } |
| 2937 | Some(Span { |
| 2938 | start, |
| 2939 | from: Some((source, in_frame)), |
| 2940 | speed, |
| 2941 | .. |
| 2942 | }) => { |
| 2943 | // The stand-in where there is one and the switch is on, the |
| 2944 | // film itself otherwise -- the one place the picture's file is |
| 2945 | // decided ([`Self::picture_path`]). The sound is opened |
| 2946 | // elsewhere and is always the film's. |
| 2947 | // |
| 2948 | // It decides for the reuse door below as well, and that is what |
| 2949 | // makes the switch flippable while watching: a worker holding |
| 2950 | // the film is asked for a span of the stand-in, declines on the |
| 2951 | // path it already has ([`Worker::reseek`]), and the seek |
| 2952 | // [`Self::set_proxies`] does becomes a respawn on the other |
| 2953 | // file. Asking the *project* here instead would have left every |
| 2954 | // proxied span opening a worker from scratch. |
| 2955 | let path = self.picture_path(source); |
| 2956 | // The file's own frames, which is the only place they exist: a |
| 2957 | // clip counts the timeline's ([`Rate`]). |
| 2958 | let start_frame = self.span_rate.source_at(in_frame); |
| 2959 | // Source frames, which a speed makes more (or fewer) than the |
| 2960 | // timeline frames the span covers -- and which a file shot at |
| 2961 | // another rate makes fewer (or more) again. One past the last |
| 2962 | // frame this span shows, not one past its length: at another |
| 2963 | // rate those are two different frames. |
| 2964 | let end_frame = self.span_rate.source_at( |
| 2965 | in_frame + span.expect("matched above").source_len().saturating_sub(1), |
| 2966 | ) + 1; |
| 2967 | let color = self |
| 2968 | .project |
| 2969 | .composite_color_at(start) |
| 2970 | .copied() |
| 2971 | .unwrap_or_default(); |
| 2972 | let transform = self |
| 2973 | .project |
| 2974 | .composite_transform_at(start) |
| 2975 | .copied() |
| 2976 | .unwrap_or_default(); |
| 2977 | // ...and the canvas it is placed on: the project's resolution |
| 2978 | // and this clip's own fit policy, constant across the span for |
| 2979 | // the reason the grade is. Built where it is handed over rather |
| 2980 | // than kept in a local, because a `Composer` owns the scratch |
| 2981 | // buffers it places through -- the value is not copied about. |
| 2982 | let fit = self.project.render_view().composite_fit_at(start); |
| 2983 | let canvas = || Composer::new(canvas_w, canvas_h, fit); |
| 2984 | // ...and the rendition an HDR source among them is mapped to, |
| 2985 | // the project's own and constant across the span for that |
| 2986 | // reason too. |
| 2987 | let tone = self.project.tone(); |
| 2988 | // At faster than real time several source frames decode to the |
| 2989 | // same timeline frame ([`Speed::timeline_at`]) and only the last |
| 2990 | // of a run is ever shown; the worker skips converting the rest |
| 2991 | // ([`crate::decode::skip_for_speed`]) rather than paying a full |
| 2992 | // colour convert and scale for a picture nothing displays. |
| 2993 | // |
| 2994 | // corner-cut: correct only when this file plays at the |
| 2995 | // timeline's own rate -- `skip_for_speed`'s own math is in the |
| 2996 | // file's frame numbers, which a `Rate` conversion would make a |
| 2997 | // different sequence than the timeline's. `Speed::NORMAL` (never |
| 2998 | // skip) covers that rarer case exactly as every frame was |
| 2999 | // delivered before this. |
| 3000 | let decode_speed = if self.span_rate.is_real_time() { |
| 3001 | speed |
| 3002 | } else { |
| 3003 | Speed::NORMAL |
| 3004 | }; |
| 3005 | // Playing backward the span is the clip up to the playhead, drawn from |
| 3006 | // the playhead down: a forward clip is served last frame first, and a |
| 3007 | // reversed one -- whose backward is the file's forward -- first frame |
| 3008 | // first, in both cases over the window the span reads. |
| 3009 | let backward_window = backward.then(|| { |
| 3010 | let sp = span.expect("matched above"); |
| 3011 | let (_, lo, hi) = sp.source_window().expect("a clip's span has a window"); |
| 3012 | ( |
| 3013 | self.span_rate.source_at(lo), |
| 3014 | self.span_rate.source_at(hi.saturating_sub(1)) + 1, |
| 3015 | ) |
| 3016 | }); |
| 3017 | if let Some((lo, hi)) = backward_window |
| 3018 | && !span.is_some_and(|s| s.reverse) |
| 3019 | { |
| 3020 | self.back = Back::Mirror { top: hi - 1 }; |
| 3021 | let stream = DecodeSession::open_reversed_with( |
| 3022 | &path, |
| 3023 | hi - 1, |
| 3024 | hi - lo, |
| 3025 | color, |
| 3026 | transform, |
| 3027 | canvas(), |
| 3028 | tone, |
| 3029 | deint, |
| 3030 | ); |
| 3031 | self.frames = stream.frames; |
| 3032 | self.backend = stream.backend; |
| 3033 | self.retire(stream.worker); |
| 3034 | self.span = span; |
| 3035 | return; |
| 3036 | } |
| 3037 | // ...and a reversed clip's backward is the file's forward: the same |
| 3038 | // worker as any clip, over the window, numbered by the file. |
| 3039 | let (start_frame, end_frame, decode_speed) = match backward_window { |
| 3040 | Some((lo, hi)) => { |
| 3041 | self.back = Back::Forward; |
| 3042 | (lo, hi, Speed::NORMAL) |
| 3043 | } |
| 3044 | None => (start_frame, end_frame, decode_speed), |
| 3045 | }; |
| 3046 | // A reversed clip is served backwards from the file frame the span |
| 3047 | // starts on, a block at a time ([`DecodeSession::open_reversed`]); its |
| 3048 | // frames are numbered as a forward stream's would be, so the stamps |
| 3049 | // and drops below need no case of their own. |
| 3050 | if !backward && span.is_some_and(|s| s.reverse) { |
| 3051 | let stream = DecodeSession::open_reversed_with( |
| 3052 | &path, |
| 3053 | start_frame, |
| 3054 | end_frame.saturating_sub(start_frame).max(1), |
| 3055 | color, |
| 3056 | transform, |
| 3057 | canvas(), |
| 3058 | tone, |
| 3059 | deint, |
| 3060 | ); |
| 3061 | self.frames = stream.frames; |
| 3062 | self.backend = stream.backend; |
| 3063 | self.retire(stream.worker); |
| 3064 | self.span = span; |
| 3065 | return; |
| 3066 | } |
| 3067 | // The worker already decoding this very file takes the new span |
| 3068 | // itself: no thread, no container parse, no VA-API init -- the |
| 3069 | // whole of what a seek used to cost. It answers `None` for any |
| 3070 | // other file (and for a worker whose thread has ended), and the |
| 3071 | // deferred opener below is then exactly the path it always was. |
| 3072 | if let Some((frames, backend)) = self.worker.reseek_with( |
| 3073 | &path, |
| 3074 | start_frame, |
| 3075 | end_frame, |
| 3076 | color, |
| 3077 | transform, |
| 3078 | canvas(), |
| 3079 | tone, |
| 3080 | decode_speed, |
| 3081 | deint, |
| 3082 | ) { |
| 3083 | self.frames = frames; |
| 3084 | self.backend = backend; |
| 3085 | self.span = span; |
| 3086 | return; |
| 3087 | } |
| 3088 | Ok(DecodeSession::open_worker_deferred_with( |
| 3089 | &path, |
| 3090 | start_frame, |
| 3091 | end_frame, |
| 3092 | color, |
| 3093 | transform, |
| 3094 | canvas(), |
| 3095 | tone, |
| 3096 | decode_speed, |
| 3097 | deint, |
| 3098 | )) |
| 3099 | } |
| 3100 | // A gap: black for as long as it runs. An emptied timeline has no |
| 3101 | // span at all and gets one frame of it -- enough to put black on |
| 3102 | // screen, and it ends where the timeline does, at once. |
| 3103 | gap => { |
| 3104 | if backward && gap.is_some() { |
| 3105 | self.back = Back::Gap; |
| 3106 | } |
| 3107 | Ok(DecodeSession::open_black( |
| 3108 | canvas_w, |
| 3109 | canvas_h, |
| 3110 | gap.map_or(1, |s| s.len), |
| 3111 | )) |
| 3112 | } |
| 3113 | }; |
| 3114 | let Ok(stream) = opened else { |
| 3115 | // The file would not open. The span still goes in -- the timeline |
| 3116 | // moves on, there are simply no more pictures -- but the *frames* |
| 3117 | // must not: the old channel's pictures are numbered in the old |
| 3118 | // source's frames, and presenting them under the new mapping would |
| 3119 | // put the wrong picture at the wrong time (and leave |
| 3120 | // [`decode_backend`](Self::decode_backend) describing a worker that |
| 3121 | // is no longer feeding anything). A dead receiver instead, which is |
| 3122 | // what carries the session on to the next span. The old worker stays |
| 3123 | // parked in `self.worker`, where the caller has already abandoned |
| 3124 | // the span it was decoding ([`Worker::abandon`]) without ending the |
| 3125 | // thread; the next span reseeks it or retires it. |
| 3126 | self.frames = std::sync::mpsc::channel().1; |
| 3127 | self.backend = BackendCell::new(Backend::Gap); |
| 3128 | self.span = span; |
| 3129 | return; |
| 3130 | }; |
| 3131 | // Receiver first, worker second: the drop of the *old* receiver is |
| 3132 | // what wakes the outgoing worker if it is parked in `send`, and only |
| 3133 | // then can it return and be reaped by a later sweep. Nothing here |
| 3134 | // joins, so this ordering costs the seek nothing. |
| 3135 | self.frames = stream.frames; |
| 3136 | self.backend = stream.backend; |
| 3137 | self.retire(stream.worker); |
| 3138 | self.span = span; |
| 3139 | } |
| 3140 | |
| 3141 | /// The deinterlace setting of the clip on screen at `frame`, as it applies to |
| 3142 | /// the file `source`'s picture is decoded from (the stand-in when there is one): |
| 3143 | /// `Frame` for anything but interlaced H.264, which ignores the setting. |
| 3144 | fn deint_at(&self, source: usize, frame: u32) -> crate::project::Deinterlace { |
| 3145 | let mode = self.project.composite_clip_at(frame).map_or(crate::project::Deinterlace::Frame, |(lane, idx)| { |
| 3146 | self.project.deinterlace_of(lane, idx) |
| 3147 | }); |
| 3148 | let path = &self.project.sources()[source].path; |
| 3149 | let file = self.proxies.then(|| crate::proxy::cached(path)).flatten().unwrap_or_else(|| path.clone()); |
| 3150 | crate::deinterlace::effective(mode, &file) |
| 3151 | } |
| 3152 | |
| 3153 | /// Opens B's own decoder for the current span's dissolve, the first time |
| 3154 | /// [`try_frame`](Self::try_frame) sees the playhead inside the window -- |
| 3155 | /// a no-op once it is already open, or if this span has no dissolve at |
| 3156 | /// all. Everything [`start_span`](Self::start_span) works out for A's own |
| 3157 | /// decoder, worked out again for B: the stand-in switch |
| 3158 | /// ([`Self::picture_path`]), the file's own frame numbering |
| 3159 | /// ([`Self::rates`]), and B's *own* grade and fit, asked at B's own start |
| 3160 | /// on the timeline rather than at the position the blend writes to |
| 3161 | /// (still inside A's span) -- the same asymmetry |
| 3162 | /// [`crate::export`]'s own `Dissolve` is built with. |
| 3163 | fn open_dissolve_b(&mut self) { |
| 3164 | let (canvas_w, canvas_h) = self.view_size(); |
| 3165 | let Some(d) = &self.dissolve else { return }; |
| 3166 | if d.b.is_some() { |
| 3167 | return; |
| 3168 | } |
| 3169 | let (source, in_frame, window, b_start) = (d.b_source, d.b_in_frame, d.window, d.b_start); |
| 3170 | let path = self.picture_path(source); |
| 3171 | // B takes one picture per timeline frame: `Field` is its `Frame`; a clip with its |
| 3172 | // pulldown removed counts film frames. |
| 3173 | let b_deint = match self.deint_at(source, b_start) { |
| 3174 | crate::project::Deinterlace::Off => crate::project::Deinterlace::Off, |
| 3175 | crate::project::Deinterlace::Ivtc => crate::project::Deinterlace::Ivtc, |
| 3176 | _ => crate::project::Deinterlace::Frame, |
| 3177 | }; |
| 3178 | let rate = crate::deinterlace::counted_rate(b_deint, self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME)); |
| 3179 | let start_frame = rate.source_at(in_frame); |
| 3180 | let end_frame = rate.source_at(in_frame + window); |
| 3181 | let color = self |
| 3182 | .project |
| 3183 | .composite_color_at(b_start) |
| 3184 | .copied() |
| 3185 | .unwrap_or_default(); |
| 3186 | let transform = self |
| 3187 | .project |
| 3188 | .composite_transform_at(b_start) |
| 3189 | .copied() |
| 3190 | .unwrap_or_default(); |
| 3191 | let canvas = Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(b_start)); |
| 3192 | let tone = self.project.tone(); |
| 3193 | let stream = DecodeSession::open_worker_deferred_with( |
| 3194 | &path, |
| 3195 | start_frame, |
| 3196 | end_frame, |
| 3197 | color, |
| 3198 | transform, |
| 3199 | canvas, |
| 3200 | tone, |
| 3201 | Speed::NORMAL, |
| 3202 | b_deint, |
| 3203 | ); |
| 3204 | if let Some(d) = self.dissolve.as_mut() { |
| 3205 | d.b = Some(DissolveB { |
| 3206 | frames: stream.frames, |
| 3207 | worker: stream.worker, |
| 3208 | held: None, |
| 3209 | }); |
| 3210 | } |
| 3211 | } |
| 3212 | |
| 3213 | /// Length of the edited timeline in seconds -- what a ruler shows, and it |
| 3214 | /// shrinks with every delete. |
| 3215 | pub fn timeline_duration(&self) -> f64 { |
| 3216 | f64::from(self.project.timeline_frames()) / self.meta.frame_rate |
| 3217 | } |
| 3218 | |
| 3219 | /// Whether no lane holds anything: the emptied timeline, which plays black |
| 3220 | /// and silent and is zero seconds long. A state, not a failure -- but the |
| 3221 | /// one a caller with nothing to render (an export) has to refuse by name |
| 3222 | /// rather than write a file of no frames. |
| 3223 | pub fn is_empty(&self) -> bool { |
| 3224 | self.project.timeline_frames() == 0 |
| 3225 | } |
| 3226 | |
| 3227 | /// `(start, len)` per clip in timeline seconds, in order: what a clips lane |
| 3228 | /// needs to lay itself out. Selection is the caller's business. |
| 3229 | pub fn clip_spans(&self) -> Vec<(f64, f64)> { |
| 3230 | let fps = self.meta.frame_rate; |
| 3231 | self.project |
| 3232 | .clip_spans() |
| 3233 | .iter() |
| 3234 | .map(|&(start, len)| (f64::from(start) / fps, f64::from(len) / fps)) |
| 3235 | .collect() |
| 3236 | } |
| 3237 | |
| 3238 | /// [`clip_spans`](Self::clip_spans) plus the index into |
| 3239 | /// [`Project::sources`] each clip plays from -- what a lane needs to colour |
| 3240 | /// an imported clip differently from the file the session was opened with. |
| 3241 | pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> { |
| 3242 | self.lane_spans_by_source(Lane::V1) |
| 3243 | } |
| 3244 | |
| 3245 | /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane, |
| 3246 | /// with each clip's group id -- what a two-lane front-end draws. The holes |
| 3247 | /// between consecutive entries are the gaps. |
| 3248 | pub fn lane_spans_by_source(&self, lane: Lane) -> Vec<(f64, f64, usize)> { |
| 3249 | let fps = self.meta.frame_rate; |
| 3250 | self.project |
| 3251 | .lane(lane) |
| 3252 | .iter() |
| 3253 | .map(|c| (f64::from(c.start) / fps, f64::from(c.len()) / fps, c.source)) |
| 3254 | .collect() |
| 3255 | } |
| 3256 | |
| 3257 | /// Every placement of one lane, in timeline order. What a two-lane |
| 3258 | /// front-end draws and nothing |
| 3259 | /// [`lane_spans_by_source`](Self::lane_spans_by_source) can answer: a clip |
| 3260 | /// carries its group id (which halves a click marks together) and its |
| 3261 | /// source range (where a waveform reads its peaks from) as well as its |
| 3262 | /// span. The holes between consecutive clips are the gaps. |
| 3263 | pub fn lane_clips(&self, lane: Lane) -> &[Clip] { |
| 3264 | self.project.lane(lane) |
| 3265 | } |
| 3266 | |
| 3267 | /// The empty stretch of `lane` covering `frame`, or `None` when `frame` |
| 3268 | /// is inside a clip/caption placement or past the last one |
| 3269 | /// ([`Project::gap_at`]). What a right-click on empty bench space asks |
| 3270 | /// before offering to close it. |
| 3271 | pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> { |
| 3272 | self.project.gap_at(lane, frame) |
| 3273 | } |
| 3274 | |
| 3275 | /// The gap a Close gap verb closes on `lane` at `frame`: [`gap_at`](Self::gap_at), but |
| 3276 | /// only a gap that starts after frame 0. A lead-in before a lane's first clip is empty |
| 3277 | /// time, not a gap a hand made, so it is never closed. |
| 3278 | pub fn closable_gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> { |
| 3279 | self.gap_at(lane, frame).filter(|&(start, _)| start > 0) |
| 3280 | } |
| 3281 | |
| 3282 | /// Closes the gap `(start, frames)` on `lane` and, when it borders a take, on the take's |
| 3283 | /// other lane too: the scope [`gap_take_scope`](Self::gap_take_scope) names, cut out by |
| 3284 | /// [`cut_regions`](Self::cut_regions). Returns that scope, so a caller can say what moved. |
| 3285 | /// The `Err` names what is in the way and nothing changes. |
| 3286 | pub fn close_gap_at(&mut self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> { |
| 3287 | let scope = self.gap_take_scope(lane, start, frames)?; |
| 3288 | self.cut_regions(&[(start, frames)], &scope)?; |
| 3289 | Ok(scope) |
| 3290 | } |
| 3291 | |
| 3292 | /// How many bounded gaps that same right-click lane holds. The tail after |
| 3293 | /// the last placement is not counted, because nothing would ripple there. |
| 3294 | pub fn gap_count(&self, lane: Lane) -> usize { |
| 3295 | self.project.gap_count(lane) |
| 3296 | } |
| 3297 | |
| 3298 | /// Every lane's handle, in display order -- what a front-end lays out top to |
| 3299 | /// bottom, and the list [`add_lane`](Self::add_lane) grows. |
| 3300 | pub fn lanes(&self) -> Vec<Lane> { |
| 3301 | self.project.lanes() |
| 3302 | } |
| 3303 | |
| 3304 | /// The offline sources an export of `span` reads, as `(index, path)`, each source once and |
| 3305 | /// in the order the timeline meets them. `span` is the marked range, `None` for the whole |
| 3306 | /// timeline. A clip wholly outside the span does not count, so a file only such clips use |
| 3307 | /// does not stop the export. |
| 3308 | pub fn offline_in_span(&self, span: Option<(u32, u32)>) -> Vec<(usize, PathBuf)> { |
| 3309 | let offline = self.offline_sources(); |
| 3310 | let mut out: Vec<(usize, PathBuf)> = Vec::new(); |
| 3311 | if offline.is_empty() { |
| 3312 | return out; |
| 3313 | } |
| 3314 | for lane in self.lanes() { |
| 3315 | for clip in self.lane_clips(lane) { |
| 3316 | let (start, end) = (clip.start, clip.start.saturating_add(clip.frames())); |
| 3317 | if let Some((from, to)) = span |
| 3318 | && (end <= from || start >= to) |
| 3319 | { |
| 3320 | continue; |
| 3321 | } |
| 3322 | if let Some((i, path)) = offline.iter().find(|(i, _)| *i == clip.source) |
| 3323 | && !out.iter().any(|(_, p)| p == path) |
| 3324 | { |
| 3325 | out.push((*i, path.clone())); |
| 3326 | } |
| 3327 | } |
| 3328 | } |
| 3329 | out |
| 3330 | } |
| 3331 | |
| 3332 | /// The sources whose files are not on disk, as `(index, saved path)`. Their |
| 3333 | /// clips stay on the timeline; a frame or an export that reads one is |
| 3334 | /// refused naming it. |
| 3335 | pub fn offline_sources(&self) -> Vec<(usize, PathBuf)> { |
| 3336 | self.project |
| 3337 | .sources() |
| 3338 | .iter() |
| 3339 | .enumerate() |
| 3340 | .filter(|(_, s)| !crate::source_present(&s.path)) |
| 3341 | .map(|(i, s)| (i, s.path.clone())) |
| 3342 | .collect() |
| 3343 | } |
| 3344 | |
| 3345 | /// Points source `index` at `path`, which must be the same material: the |
| 3346 | /// same kind (picture, sound or still), and a picture or sound at least as |
| 3347 | /// long as the furthest frame a clip reaches into the source (within a |
| 3348 | /// frame). Returns warnings: a length that differs by more than a frame from |
| 3349 | /// the file it replaces. The playhead is reopened on it. One undo step |
| 3350 | /// ([`Project::relink_source`]): undo points the source back at the old file |
| 3351 | /// and reads its length again. Nothing changes on a refusal. |
| 3352 | pub fn relink_source(&mut self, index: usize, path: &Path) -> crate::Result<Vec<String>> { |
| 3353 | let Some(old) = self.project.sources().get(index).cloned() else { |
| 3354 | return Err(format!("there is no source {index}").into()); |
| 3355 | }; |
| 3356 | if !path.is_file() { |
| 3357 | return Err(format!("{} is not a file", path.display()).into()); |
| 3358 | } |
| 3359 | let kind = |p: &Path| { |
| 3360 | if crate::is_image(p) { |
| 3361 | "a still" |
| 3362 | } else if crate::is_audio(p) { |
| 3363 | "a sound file" |
| 3364 | } else { |
| 3365 | "a picture" |
| 3366 | } |
| 3367 | }; |
| 3368 | if kind(&old.path) != kind(path) { |
| 3369 | return Err(format!( |
| 3370 | "source {index} is {} but {} is {}", |
| 3371 | kind(&old.path), |
| 3372 | path.display(), |
| 3373 | kind(path) |
| 3374 | ) |
| 3375 | .into()); |
| 3376 | } |
| 3377 | let candidate = Source::new(path, old.audio_stream); |
| 3378 | let (have, rate) = self.measure_source(&candidate)?; |
| 3379 | let expected = self.counts[index]; |
| 3380 | // What the clips actually read: the furthest out-point any clip on any |
| 3381 | // lane takes from this source. A clip reading part of a source needs only |
| 3382 | // that part, so refusal is against the reach, not the whole length. Both |
| 3383 | // are in timeline-rate frames, the unit `have` is counted in. |
| 3384 | let reach = self |
| 3385 | .lanes() |
| 3386 | .into_iter() |
| 3387 | .flat_map(|lane| { |
| 3388 | self.lane_clips(lane) |
| 3389 | .iter() |
| 3390 | .filter(|c| c.source == index) |
| 3391 | .map(|c| c.out_frame) |
| 3392 | .collect::<Vec<_>>() |
| 3393 | }) |
| 3394 | .max() |
| 3395 | .unwrap_or(0); |
| 3396 | if have + 1 < reach { |
| 3397 | return Err(format!( |
| 3398 | "{} has {have} frames but the clips on source {index} reach frame {reach}", |
| 3399 | path.display() |
| 3400 | ) |
| 3401 | .into()); |
| 3402 | } |
| 3403 | let mut warnings = Vec::new(); |
| 3404 | if crate::source_present(&old.path) && have.abs_diff(expected) > 1 { |
| 3405 | warnings.push(format!( |
| 3406 | "{} has {have} frames; the file it replaces had {expected}", |
| 3407 | path.display() |
| 3408 | )); |
| 3409 | } |
| 3410 | self.project.relink_source(index, path)?; |
| 3411 | self.counts[index] = have; |
| 3412 | self.rates[index] = rate; |
| 3413 | let at = self.now(); |
| 3414 | self.seek(at); |
| 3415 | Ok(warnings) |
| 3416 | } |
| 3417 | |
| 3418 | /// Points several sources at copies of the same files ([`crate::collect`]) as one undo |
| 3419 | /// step. The copies are not measured against the clips: they are the same bytes. Their |
| 3420 | /// lengths are read again as an undo reads them, and the playhead is reopened. Returns how |
| 3421 | /// many sources moved. |
| 3422 | pub fn relink_all(&mut self, pairs: &[(usize, PathBuf)]) -> usize { |
| 3423 | let before = self.project.sources().to_vec(); |
| 3424 | let moved = self.project.relink_sources(pairs); |
| 3425 | if moved > 0 { |
| 3426 | self.reread_sources(&before); |
| 3427 | self.invalidate(Dirty::Both); |
| 3428 | } |
| 3429 | moved |
| 3430 | } |
| 3431 | |
| 3432 | /// Appends an empty lane and hands back its handle. One undo step |
| 3433 | /// ([`Project::add_lane`]), and no reseek: an empty lane changes nothing |
| 3434 | /// that plays until something is placed on it. |
| 3435 | pub fn add_lane(&mut self, kind: LaneKind) -> Lane { |
| 3436 | self.project.add_lane(kind) |
| 3437 | } |
| 3438 | |
| 3439 | /// Drops that empty lane again, in [`Project::remove_lane`]'s words when it |
| 3440 | /// refuses. One undo step, and no reseek for the same reason the add needs |
| 3441 | /// none: an empty lane was playing nothing. |
| 3442 | pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> { |
| 3443 | self.project.remove_lane(lane) |
| 3444 | } |
| 3445 | |
| 3446 | /// Moves a whole track to display position `to`, clips and all |
| 3447 | /// ([`Project::move_lane`]), and hands back the handle it answers to |
| 3448 | /// afterwards -- `None` when nothing moved. One undo step. |
| 3449 | /// |
| 3450 | /// A *video* track that moves rebuilds the picture where the playhead |
| 3451 | /// stands, because display order is the stack and the frame on screen may |
| 3452 | /// be another lane's from here on; the sound plays on through it, untouched |
| 3453 | /// -- a mix is a sum, and a lane's gain travelled with it. |
| 3454 | pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> { |
| 3455 | let moved = self.project.move_lane(lane, to)?; |
| 3456 | if lane.kind == LaneKind::Video { |
| 3457 | self.invalidate(Dirty::Picture); |
| 3458 | } |
| 3459 | Some(moved) |
| 3460 | } |
| 3461 | |
| 3462 | /// The subtitle lanes in display order -- `S1..Sn`, the rows a front-end |
| 3463 | /// lays out beside the picture and sound ones |
| 3464 | /// ([`Project::subtitle_lanes`]). Empty until something adds one, which is |
| 3465 | /// [`add_lane`](Self::add_lane) with [`LaneKind::Subtitle`], and they come |
| 3466 | /// off, move and reorder through the very same doors every other lane does. |
| 3467 | pub fn subtitle_lanes(&self) -> Vec<Lane> { |
| 3468 | self.project.subtitle_lanes() |
| 3469 | } |
| 3470 | |
| 3471 | /// What is placed on one subtitle lane, in timeline order: what a front-end |
| 3472 | /// draws as clips, each naming the palette row it plays |
| 3473 | /// ([`Self::subtitles`]) and the window of it it keeps |
| 3474 | /// ([`Project::sub_lane`]). |
| 3475 | pub fn sub_lane(&self, lane: Lane) -> &[SubClip] { |
| 3476 | self.project.sub_lane(lane) |
| 3477 | } |
| 3478 | |
| 3479 | /// Places a stretch of a subtitle track on `lane` at timeline frame `at` |
| 3480 | /// ([`Project::place_sub`], whose words a refusal is shown in). One undo |
| 3481 | /// step. |
| 3482 | /// |
| 3483 | /// No reseek and no invalidation, which is what the whole wrapper layer is |
| 3484 | /// here for: cues are drawn from [`sub_lane_cues`](Self::sub_lane_cues) |
| 3485 | /// over whatever picture is on screen, so nothing already decoded stops |
| 3486 | /// being right. |
| 3487 | pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> { |
| 3488 | self.project.place_sub(lane, at, sub) |
| 3489 | } |
| 3490 | |
| 3491 | /// Drags a placement to another subtitle lane or another frame |
| 3492 | /// ([`Project::move_sub`]). One undo step, and `Ok` with none for a drop |
| 3493 | /// that changed nothing. A caption in a group drags the group's clips with |
| 3494 | /// it -- a mapping change -- so this reseeks like a clip's drag does; a |
| 3495 | /// caption in no group moves nothing that plays and disturbs nothing. |
| 3496 | pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> { |
| 3497 | let grouped = self.caption_grouped_with_clips(from, idx); |
| 3498 | let moved = self.project.move_sub(from, idx, to, start); |
| 3499 | if moved.is_ok() && grouped { |
| 3500 | self.invalidate(Dirty::Both); |
| 3501 | } |
| 3502 | moved |
| 3503 | } |
| 3504 | |
| 3505 | /// Drags one edge of a placement to timeline frame `to` |
| 3506 | /// ([`Project::trim_sub`]), **at this timeline's own frame rate** -- a |
| 3507 | /// placement's position is in frames while its words are in microseconds, |
| 3508 | /// and the rate that joins them is the one thing a [`Project`] does not |
| 3509 | /// know. That is why a front-end trims through this door and never converts |
| 3510 | /// a cue's microseconds itself. One undo step. A caption in a group trims |
| 3511 | /// the group's clips with it, and that half reseeked; a lone caption's trim |
| 3512 | /// changes only the words, which are drawn over whatever is decoded. |
| 3513 | pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> { |
| 3514 | let grouped = self.caption_grouped_with_clips(lane, idx); |
| 3515 | let trimmed = self |
| 3516 | .project |
| 3517 | .trim_sub(lane, idx, edge, to, self.meta.frame_rate); |
| 3518 | if trimmed.is_ok() && grouped { |
| 3519 | self.invalidate(Dirty::Both); |
| 3520 | } |
| 3521 | trimmed |
| 3522 | } |
| 3523 | |
| 3524 | /// How far that edge may travel, `(first, last)` timeline frame inclusive |
| 3525 | /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during |
| 3526 | /// a drag asks, at this timeline's rate. |
| 3527 | pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> { |
| 3528 | self.project |
| 3529 | .trim_sub_room(lane, idx, edge, self.meta.frame_rate) |
| 3530 | } |
| 3531 | |
| 3532 | /// Takes one placement off a subtitle lane, leaving a gap |
| 3533 | /// ([`Project::lift_sub`]). One undo step; the palette row it played stays |
| 3534 | /// on this timeline's list. |
| 3535 | pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool { |
| 3536 | self.project.lift_sub(lane, idx) |
| 3537 | } |
| 3538 | |
| 3539 | /// What that subtitle lane shows on *this* timeline, in start order |
| 3540 | /// ([`Project::sub_lane_cues`] at this timeline's rate) -- the placed-clip |
| 3541 | /// counterpart of [`timeline_cues`](Self::timeline_cues), which carries a |
| 3542 | /// whole palette track through the spans that play its media. Pure, so a |
| 3543 | /// front-end may ask it per repaint. |
| 3544 | pub fn sub_lane_cues(&self, lane: Lane) -> Vec<crate::subtitle::Cue> { |
| 3545 | self.project.sub_lane_cues(lane, self.meta.frame_rate) |
| 3546 | } |
| 3547 | |
| 3548 | /// Every cue on the subtitle lanes, in start order: the captions that File > Export |
| 3549 | /// captions and `export_captions` write as SRT or WebVTT ([`crate::subtitle::write_srt`]). |
| 3550 | pub fn caption_cues(&self) -> Vec<crate::subtitle::Cue> { |
| 3551 | let mut cues: Vec<crate::subtitle::Cue> = self.subtitle_lanes().into_iter().flat_map(|l| self.sub_lane_cues(l)).collect(); |
| 3552 | cues.sort_by_key(|c| c.start_us); |
| 3553 | cues |
| 3554 | } |
| 3555 | |
| 3556 | /// [`sub_lane_cues`](Self::sub_lane_cues) with the cue each one is, as |
| 3557 | /// `(start_us, end_us, track, cue)` in the same order ([`Project::sub_lane_cue_refs`]): |
| 3558 | /// what a front-end hit-tests a drawn cue against to find the words to edit. |
| 3559 | pub fn sub_lane_cue_refs(&self, lane: Lane) -> Vec<(i64, i64, usize, usize)> { |
| 3560 | self.project.sub_lane_cue_refs(lane, self.meta.frame_rate) |
| 3561 | } |
| 3562 | |
| 3563 | /// [`sub_lane_cue_refs`](Self::sub_lane_cue_refs) with the part of each cue's own clock that |
| 3564 | /// is shown ([`Project::sub_lane_cue_spans`]), which its word times are moved by. |
| 3565 | pub fn sub_lane_cue_spans(&self, lane: Lane) -> Vec<crate::project::CueSpan> { |
| 3566 | self.project.sub_lane_cue_spans(lane, self.meta.frame_rate) |
| 3567 | } |
| 3568 | |
| 3569 | /// Retypes one cue's words ([`Project::set_cue_text`]). One undo step, and |
| 3570 | /// `false` with none for a cue that is not there or already reads this. |
| 3571 | /// No invalidation: the picture's captions are drawn per repaint from the |
| 3572 | /// palette ([`sub_lane_cues`](Self::sub_lane_cues)), so the new words are on |
| 3573 | /// the next frame without a reseek. |
| 3574 | pub fn set_cue_text(&mut self, track: usize, cue: usize, text: &str) -> bool { |
| 3575 | self.project.set_cue_text(track, cue, text) |
| 3576 | } |
| 3577 | |
| 3578 | /// Removes one cue from its track ([`Project::delete_cue`]): gone from every |
| 3579 | /// placement of the track, nothing moves. One undo step, and `false` with |
| 3580 | /// none for a cue that is not there. |
| 3581 | pub fn delete_cue(&mut self, track: usize, cue: usize) -> bool { |
| 3582 | self.project.delete_cue(track, cue) |
| 3583 | } |
| 3584 | |
| 3585 | /// The room a cue has on the track's own clock ([`Project::cue_room`]). |
| 3586 | pub fn cue_room(&self, track: usize, cue: usize) -> Option<(i64, i64)> { |
| 3587 | self.project.cue_room(track, cue) |
| 3588 | } |
| 3589 | |
| 3590 | /// Where timeline time `tl_us` is on the track's clock, through the placement on `lane` |
| 3591 | /// that shows the cue ([`Project::cue_track_us_at`]). |
| 3592 | pub fn cue_track_us_at(&self, lane: Lane, track: usize, cue: usize, tl_us: i64) -> Option<i64> { |
| 3593 | self.project.cue_track_us_at(lane, track, cue, tl_us, self.meta.frame_rate) |
| 3594 | } |
| 3595 | |
| 3596 | /// Moves or trims one cue ([`Project::set_cue_times`]). One undo step. |
| 3597 | pub fn set_cue_times(&mut self, track: usize, cue: usize, start_us: i64, end_us: i64) -> crate::Result<bool> { |
| 3598 | self.project.set_cue_times(track, cue, start_us, end_us) |
| 3599 | } |
| 3600 | |
| 3601 | /// Joins a cue with the one after it ([`Project::merge_cue_next`]). One undo step. |
| 3602 | pub fn merge_cue_next(&mut self, track: usize, cue: usize) -> crate::Result<()> { |
| 3603 | self.project.merge_cue_next(track, cue) |
| 3604 | } |
| 3605 | |
| 3606 | /// Divides the cue straddling `t_us` on the track's clock ([`Project::split_cues_at`]). One undo step. |
| 3607 | pub fn split_cues_at(&mut self, track: usize, t_us: i64) -> bool { |
| 3608 | self.project.split_cues_at(track, t_us) |
| 3609 | } |
| 3610 | |
| 3611 | /// Adds a cue to a track on the track's own clock ([`Project::add_cue`]): kept |
| 3612 | /// in the project and saved with it. One undo step; the index it lands at, or |
| 3613 | /// the refusal, which changes nothing. |
| 3614 | pub fn add_cue(&mut self, track: usize, start_us: i64, end_us: i64, text: &str, overwrite: bool) -> crate::Result<usize> { |
| 3615 | self.project.add_cue(track, start_us, end_us, text, overwrite) |
| 3616 | } |
| 3617 | |
| 3618 | /// The title cards and text overlays, in draw order ([`Project::titles`]). |
| 3619 | pub fn titles(&self) -> &[crate::project::Title] { |
| 3620 | self.project.titles() |
| 3621 | } |
| 3622 | |
| 3623 | /// The chapter markers, sorted by frame, at most one per frame |
| 3624 | /// ([`Project::chapters`]). |
| 3625 | pub fn chapters(&self) -> &[crate::project::Chapter] { |
| 3626 | self.project.chapters() |
| 3627 | } |
| 3628 | |
| 3629 | /// The chapters as a YouTube description listing, `00:00 Intro` a line each, and the |
| 3630 | /// warnings its rules call for ([`chapter_listing`]). The whole timeline, never a range. |
| 3631 | pub fn youtube_chapters(&self) -> (String, Vec<String>) { |
| 3632 | let fps = self.meta.frame_rate; |
| 3633 | let end = (self.timeline_duration() * fps).round() as u32; |
| 3634 | let chapters: Vec<(u32, String)> = self.chapters().iter().map(|c| (c.frame, c.title.clone())).collect(); |
| 3635 | chapter_listing(&chapters, fps, end) |
| 3636 | } |
| 3637 | |
| 3638 | /// Adds a chapter at `frame` named `title`, and returns its index in |
| 3639 | /// [`chapters`](Self::chapters). One undo step; refused, with nothing changed, |
| 3640 | /// for a name the project refuses or a frame that already has a chapter. |
| 3641 | pub fn add_chapter(&mut self, frame: u32, title: &str) -> crate::Result<usize> { |
| 3642 | self.project.add_chapter(crate::project::Chapter { frame, title: title.to_string() }) |
| 3643 | } |
| 3644 | |
| 3645 | /// Takes the chapter at `idx` off the list. One undo step; `false`, with |
| 3646 | /// nothing changed, for an index that is not there. |
| 3647 | pub fn remove_chapter(&mut self, idx: usize) -> bool { |
| 3648 | self.project.remove_chapter(idx) |
| 3649 | } |
| 3650 | |
| 3651 | /// Renames the chapter at `idx`. One undo step; `false` for an index that |
| 3652 | /// is not there, a name the project refuses, or the name it already has. |
| 3653 | pub fn set_chapter_title(&mut self, idx: usize, title: &str) -> bool { |
| 3654 | self.project.set_chapter_title(idx, title) |
| 3655 | } |
| 3656 | |
| 3657 | /// Moves the chapter at `idx` to `frame`, and returns its new index. One undo |
| 3658 | /// step; refused for a frame another chapter already holds. |
| 3659 | pub fn move_chapter(&mut self, idx: usize, frame: u32) -> crate::Result<usize> { |
| 3660 | self.project.move_chapter(idx, frame) |
| 3661 | } |
| 3662 | |
| 3663 | /// Maps every chapter's frame through `map` as one undo step, for an edit that |
| 3664 | /// moves time (see [`Project::remap_chapters`]). Returns how many chapters a |
| 3665 | /// landing on another's frame dropped. |
| 3666 | pub fn remap_chapters(&mut self, map: impl Fn(u32) -> u32) -> usize { |
| 3667 | self.project.remap_chapters(map) |
| 3668 | } |
| 3669 | |
| 3670 | /// How burned captions animate ([`crate::captionanim`]). |
| 3671 | pub fn caption_style(&self) -> crate::captionanim::CaptionStyle { |
| 3672 | self.project.caption_style() |
| 3673 | } |
| 3674 | |
| 3675 | /// Gives a caption track's cues the word times they were written from |
| 3676 | /// ([`Project::attach_cue_words`]); `auto_captions` calls it right after the import. |
| 3677 | pub fn attach_cue_words(&mut self, track: usize, timed: &[crate::subtitle::Cue]) { |
| 3678 | self.project.attach_cue_words(track, timed); |
| 3679 | } |
| 3680 | |
| 3681 | /// Sets how burned captions animate; one undo step, `false` when it is already so. |
| 3682 | pub fn set_caption_style(&mut self, style: crate::captionanim::CaptionStyle) -> bool { |
| 3683 | self.project.set_caption_style(style) |
| 3684 | } |
| 3685 | |
| 3686 | /// The comment markers, sorted by frame ([`Project::markers`]). |
| 3687 | pub fn markers(&self) -> &[crate::project::Marker] { |
| 3688 | self.project.markers() |
| 3689 | } |
| 3690 | |
| 3691 | /// Adds a marker and returns its index in [`markers`](Self::markers). One undo step; |
| 3692 | /// refused, with nothing changed, for a marker the project refuses. |
| 3693 | pub fn add_marker(&mut self, marker: crate::project::Marker) -> crate::Result<usize> { |
| 3694 | self.project.add_marker(marker) |
| 3695 | } |
| 3696 | |
| 3697 | /// Takes the marker at `idx` off. One undo step; `false` for an index that is not there. |
| 3698 | pub fn remove_marker(&mut self, idx: usize) -> bool { |
| 3699 | self.project.remove_marker(idx) |
| 3700 | } |
| 3701 | |
| 3702 | /// Replaces the marker at `idx` and returns its new index. One undo step; refused for |
| 3703 | /// a marker the project refuses or one that changes nothing. |
| 3704 | pub fn set_marker(&mut self, idx: usize, marker: crate::project::Marker) -> crate::Result<usize> { |
| 3705 | self.project.set_marker(idx, marker) |
| 3706 | } |
| 3707 | |
| 3708 | /// Maps every marker's start and end through `map` as one undo step, for an edit that |
| 3709 | /// moves time (see [`Project::remap_markers`]). `false` when nothing moved. |
| 3710 | pub fn remap_markers(&mut self, map: impl Fn(u32) -> u32) -> bool { |
| 3711 | self.project.remap_markers(map) |
| 3712 | } |
| 3713 | |
| 3714 | /// The markers as a chapter list for an export of `range`, as [`chapter_list_ns`](Self::chapter_list_ns) |
| 3715 | /// lists chapters: `(start_ns, name)` pairs in frame order, the first marker on a frame |
| 3716 | /// winning when several share one (a chapter list holds one per instant). |
| 3717 | pub fn marker_list_ns(&self, range: Option<(u32, u32)>) -> Vec<(u64, String)> { |
| 3718 | let (from, to) = range.unwrap_or((0, u32::MAX)); |
| 3719 | let fps = self.meta.frame_rate; |
| 3720 | let mut out: Vec<(u64, String)> = Vec::new(); |
| 3721 | for m in self.project.markers().iter().filter(|m| m.frame >= from && m.frame < to) { |
| 3722 | let ns = (f64::from(m.frame - from) / fps * 1e9).round() as u64; |
| 3723 | if out.last().is_none_or(|(last, _)| *last != ns) { |
| 3724 | out.push((ns, m.name.clone())); |
| 3725 | } |
| 3726 | } |
| 3727 | out |
| 3728 | } |
| 3729 | |
| 3730 | /// The chapter list an export of `range` (frames, as [`ExportSettings::range`] |
| 3731 | /// names it) writes: `(start_ns, name)` pairs in frame order. A chapter's time |
| 3732 | /// is measured from the start of the range, so an export that starts at frame |
| 3733 | /// 100 writes a chapter at frame 100 as the first one, at 0 ns. Chapters before |
| 3734 | /// the range or at or past its end are left out; with no range every chapter |
| 3735 | /// is listed from the start of the timeline. |
| 3736 | /// |
| 3737 | /// Ready for an export's chapter list: the codecs writers take the pairs as |
| 3738 | /// they are. |
| 3739 | pub fn chapter_list_ns(&self, range: Option<(u32, u32)>) -> Vec<(u64, String)> { |
| 3740 | let (from, to) = range.unwrap_or((0, u32::MAX)); |
| 3741 | let fps = self.meta.frame_rate; |
| 3742 | self.project |
| 3743 | .chapters() |
| 3744 | .iter() |
| 3745 | .filter(|c| c.frame >= from && c.frame < to) |
| 3746 | .map(|c| { |
| 3747 | let ns = f64::from(c.frame - from) / fps * 1e9; |
| 3748 | (ns.round() as u64, c.title.clone()) |
| 3749 | }) |
| 3750 | .collect() |
| 3751 | } |
| 3752 | |
| 3753 | /// Adds a title card or text overlay and recomposes the picture at the |
| 3754 | /// playhead. The index it lands at, or the refusal of [`Project::add_title`], |
| 3755 | /// which changes nothing. |
| 3756 | pub fn add_title(&mut self, title: crate::project::Title) -> crate::Result<usize> { |
| 3757 | let idx = self.project.add_title(title)?; |
| 3758 | self.invalidate(Dirty::Picture); |
| 3759 | Ok(idx) |
| 3760 | } |
| 3761 | |
| 3762 | /// Replaces the title at `idx` -- see [`Project::set_title`]. One undo step |
| 3763 | /// and a recomposed picture. |
| 3764 | pub fn set_title(&mut self, idx: usize, title: crate::project::Title) -> bool { |
| 3765 | self.edit(Dirty::Picture, |p| p.set_title(idx, title)) |
| 3766 | } |
| 3767 | |
| 3768 | /// Takes the title at `idx` off -- see [`Project::remove_title`]. One undo |
| 3769 | /// step and a recomposed picture. |
| 3770 | pub fn remove_title(&mut self, idx: usize) -> bool { |
| 3771 | self.edit(Dirty::Picture, |p| p.remove_title(idx)) |
| 3772 | } |
| 3773 | |
| 3774 | /// Splits every lane at `timeline_secs`, so the two sides become two |
| 3775 | /// groups. Metadata only: a split never changes the timeline->source |
| 3776 | /// mapping, so the running decoder stays correct and playback does not |
| 3777 | /// blink. `false` at a clip start, in a gap and past the end, where there |
| 3778 | /// would be nothing to split off. |
| 3779 | pub fn cut_at(&mut self, timeline_secs: f64) -> bool { |
| 3780 | self.project |
| 3781 | .split(secs_to_frame(timeline_secs, self.meta.frame_rate)) |
| 3782 | } |
| 3783 | |
| 3784 | /// The frame nearest `frame` within `reach` frames at which [`cut_at`](Self::cut_at) |
| 3785 | /// lands cleanly on every lane ([`Project::cut_frame_near`]); `None` when none is that near. |
| 3786 | pub fn cut_frame_near(&self, frame: u32, reach: u32) -> Option<u32> { |
| 3787 | self.project.cut_frame_near(frame, reach) |
| 3788 | } |
| 3789 | |
| 3790 | /// [`cut_at`](Self::cut_at) on the lanes in `lanes` only; the others keep |
| 3791 | /// their clips whole across the cut. Metadata only, like `cut_at`. |
| 3792 | pub fn cut_at_lanes(&mut self, timeline_secs: f64, lanes: &[Lane]) -> bool { |
| 3793 | self.project |
| 3794 | .split_on(secs_to_frame(timeline_secs, self.meta.frame_rate), lanes) |
| 3795 | } |
| 3796 | |
| 3797 | /// The inverse of [`cut_at`](Self::cut_at): rejoins the clips that meet at |
| 3798 | /// `timeline_secs` in every lane and puts them back in one group. `false` |
| 3799 | /// unless a split could have produced what is there. Metadata only, like the |
| 3800 | /// split -- no reseek. |
| 3801 | pub fn regroup_at(&mut self, timeline_secs: f64) -> bool { |
| 3802 | self.project |
| 3803 | .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate)) |
| 3804 | } |
| 3805 | |
| 3806 | /// Takes that clip out of its group, so its picture and its sound are edited |
| 3807 | /// apart from here on. Metadata only like a cut -- no reseek -- and one undo |
| 3808 | /// step. `false` for a bad index and for a clip that is not grouped with |
| 3809 | /// anything, which is already detached. |
| 3810 | pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool { |
| 3811 | self.project.ungroup(lane, idx) |
| 3812 | } |
| 3813 | |
| 3814 | /// Puts two clips covering the same frames back into one group: the regroup |
| 3815 | /// of what [`ungroup`](Self::ungroup) took apart. Metadata only, one undo |
| 3816 | /// step, and the error says why when it refuses. |
| 3817 | pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> { |
| 3818 | self.project.group(a, a_idx, b, b_idx) |
| 3819 | } |
| 3820 | |
| 3821 | /// Puts every placement the picks name into one group |
| 3822 | /// ([`Project::group_all`]) -- the ctrl-click selection's own door, which |
| 3823 | /// may name clips and captions alike. Metadata only like the pair above: |
| 3824 | /// no reseek, one undo step, and the error says why when it refuses. |
| 3825 | pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> { |
| 3826 | self.project.group_all(picks) |
| 3827 | } |
| 3828 | |
| 3829 | /// [`delete_clip`](Self::delete_clip) for the caption the pick named: a |
| 3830 | /// caption in no group lifts exactly as [`lift_sub`](Self::lift_sub) lifts |
| 3831 | /// it -- no reseek, because nothing that plays has changed -- and a caption |
| 3832 | /// in a group takes the group with it, which ripples every member's own |
| 3833 | /// lane and reseeks like a delete. `false` for a bad index. |
| 3834 | pub fn delete_sub(&mut self, lane: Lane, idx: usize) -> bool { |
| 3835 | // Which of the two, asked before anything moves: the reseek a grouped |
| 3836 | // delete owes is the whole difference between the paths. A group of |
| 3837 | // captions alone (no clip on another lane) still ripples every |
| 3838 | // member's *own* sub lane closed (`Project::delete_sub_in`, since |
| 3839 | // cdc53a6), and a sub lane counts toward `timeline_frames` exactly |
| 3840 | // like a clip lane does -- so the timeline can shrink out from under |
| 3841 | // the playhead from a caption-only group too, not only a media one. |
| 3842 | // `caption_grouped_with_clips` answers a narrower question than the |
| 3843 | // one this dispatch needs; a caption carries a link at all only once |
| 3844 | // grouped (`place_sub` always starts one at `None`), so that alone is |
| 3845 | // "this delete ripples more than its own lane". |
| 3846 | match self |
| 3847 | .sub_lane(lane) |
| 3848 | .get(idx) |
| 3849 | .is_some_and(|s| s.link.is_some()) |
| 3850 | { |
| 3851 | true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)), |
| 3852 | // A caption in no group is the plain lift that touches nothing |
| 3853 | // else: no reseek owed. |
| 3854 | false => self.project.delete_sub_in(lane, idx), |
| 3855 | } |
| 3856 | } |
| 3857 | |
| 3858 | /// Whether the caption at `idx` of `lane` is grouped with clips on other |
| 3859 | /// lanes: the one question every caption edit that can move media has to |
| 3860 | /// ask first, because the answer is whether the edit owes a reseek -- and |
| 3861 | /// the front-end owes the same answer, asked before the edit moves the |
| 3862 | /// indices, so its flag reset matches the engine's reseek exactly. |
| 3863 | pub fn caption_grouped_with_clips(&self, lane: Lane, idx: usize) -> bool { |
| 3864 | self.project |
| 3865 | .sub_lane(lane) |
| 3866 | .get(idx) |
| 3867 | .and_then(|s| s.link) |
| 3868 | .is_some_and(|id| { |
| 3869 | self.project |
| 3870 | .lanes() |
| 3871 | .into_iter() |
| 3872 | .any(|l| l != lane && self.project.lane(l).iter().any(|c| c.link == Some(id))) |
| 3873 | }) |
| 3874 | } |
| 3875 | |
| 3876 | /// What the clip at `idx` of `lane` is equalized with, or `None` for one |
| 3877 | /// that plays flat -- what a card shows before it lets anyone drag a band. |
| 3878 | pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> { |
| 3879 | self.project.eq_of(lane, idx) |
| 3880 | } |
| 3881 | |
| 3882 | /// Gives that clip an equalizer, or takes it off with `None`. One undo step, |
| 3883 | /// like every other edit -- and it rebuilds the **sound** where the playhead |
| 3884 | /// is, so a band changed during playback is heard from the next chunk on |
| 3885 | /// rather than at the next play. The picture is not touched: the video |
| 3886 | /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or |
| 3887 | /// a non-finite band, and nothing changes. |
| 3888 | /// |
| 3889 | /// corner-cut: the audio rebuild is what makes it live, so the cost of a |
| 3890 | /// change is a decoder restart -- inaudible at a drag's end, but too much to |
| 3891 | /// call once per pointer sample (a caller commits one change per gesture). |
| 3892 | /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`], |
| 3893 | /// which the lane worker would poll per chunk the way the mixer polls the |
| 3894 | /// gains. |
| 3895 | pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool { |
| 3896 | self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params)) |
| 3897 | } |
| 3898 | |
| 3899 | /// The clip's own gain in dB at `idx` of `lane`, or `None` for an index |
| 3900 | /// that is not there ([`Project::clip_gain`]). |
| 3901 | pub fn clip_gain_of(&self, lane: Lane, idx: usize) -> Option<f32> { |
| 3902 | self.project.clip_gain(lane, idx) |
| 3903 | } |
| 3904 | |
| 3905 | /// Sets that clip's gain in dB, clamped to the clip-gain range. One undo |
| 3906 | /// step, and the sound is rebuilt where the playhead is, as for |
| 3907 | /// [`set_eq`](Self::set_eq). `false` for a video lane, a bad index, a |
| 3908 | /// non-finite value, or a value already set. |
| 3909 | pub fn set_clip_gain(&mut self, lane: Lane, idx: usize, db: f32) -> bool { |
| 3910 | self.edit(Dirty::Sound, |p| p.set_clip_gain(lane, idx, db)) |
| 3911 | } |
| 3912 | |
| 3913 | /// Plays the timeline's sound at `at` (timeline seconds) for [`SCRUB_SECS`]: the audible |
| 3914 | /// half of a ruler scrub while paused. The decode happens on the scrub thread and nothing |
| 3915 | /// here waits for it, so a drag never stalls on the file; a request that arrives while an |
| 3916 | /// earlier one is still being read replaces it. Silent, and a no-op, past the end of the |
| 3917 | /// timeline or where nothing plays. |
| 3918 | pub fn scrub_audio(&mut self, at: f64) { |
| 3919 | if !(at.is_finite() && at >= 0.) { |
| 3920 | return; |
| 3921 | } |
| 3922 | let fps = self.meta.frame_rate; |
| 3923 | let target = (at * fps) as u32; |
| 3924 | let view = self.project.render_view(); |
| 3925 | let segs = view.audio_segments_from(target, fps); |
| 3926 | if segs.is_empty() { |
| 3927 | return; |
| 3928 | } |
| 3929 | let eqs = view.audio_eqs_from(target, fps); |
| 3930 | let speeds = view.audio_speeds_from(target, fps); |
| 3931 | let fades = view.audio_fades_from(target, fps); |
| 3932 | let sources = self.project.audio_sources(); |
| 3933 | let gains = self.mix_gains(); |
| 3934 | let ducks = view.audio_ducks(); |
| 3935 | let voices = view.audio_voices(); |
| 3936 | let limiter = self.project.limiter(); |
| 3937 | let sample_rate = self.sample_rate; |
| 3938 | let work: ScrubWork = Box::new(move || { |
| 3939 | let (meta, rx) = AudioSession::open_mixed_streams_live_fade( |
| 3940 | &sources, |
| 3941 | &segs, |
| 3942 | &eqs, |
| 3943 | &speeds, |
| 3944 | &fades, |
| 3945 | fps, |
| 3946 | &gains, |
| 3947 | &ducks, |
| 3948 | &voices, |
| 3949 | limiter, |
| 3950 | None, |
| 3951 | sample_rate, |
| 3952 | ) |
| 3953 | .ok()??; |
| 3954 | let channels = usize::from(meta.channels).max(1); |
| 3955 | let want = (SCRUB_SECS * f64::from(meta.sample_rate)) as usize * channels; |
| 3956 | let mut buf = Vec::with_capacity(want); |
| 3957 | while buf.len() < want { |
| 3958 | match rx.recv_timeout(std::time::Duration::from_millis(500)) { |
| 3959 | Ok(chunk) => buf.extend_from_slice(&chunk.samples), |
| 3960 | Err(_) => break, |
| 3961 | } |
| 3962 | } |
| 3963 | buf.truncate(want); |
| 3964 | if buf.is_empty() { |
| 3965 | return None; |
| 3966 | } |
| 3967 | let fade = (SCRUB_FADE_SECS * f64::from(meta.sample_rate)) as usize; |
| 3968 | let samples = scrub_snippet(&buf, channels, fade); |
| 3969 | Some((meta.sample_rate, u32::from(meta.channels), samples)) |
| 3970 | }); |
| 3971 | let tx = self.scrub.tx.get_or_insert_with(|| { |
| 3972 | let (tx, rx) = std::sync::mpsc::channel(); |
| 3973 | let _ = std::thread::Builder::new() |
| 3974 | .name("audio-scrub".into()) |
| 3975 | .spawn(move || scrub_thread(rx)); |
| 3976 | tx |
| 3977 | }); |
| 3978 | let _ = tx.send(work); |
| 3979 | self.scrub.requests += 1; |
| 3980 | } |
| 3981 | |
| 3982 | /// How many scrub snippets have been asked for on this session: the count a test reads to see |
| 3983 | /// that a drag did, or did not, play sound ([`PlaybackSession::scrub_audio`]). |
| 3984 | pub fn scrub_requests(&self) -> u64 { |
| 3985 | self.scrub.requests |
| 3986 | } |
| 3987 | |
| 3988 | /// The clip's pitch shift in semitones at `idx` of `lane` ([`Project::clip_pitch`]). |
| 3989 | pub fn clip_pitch_of(&self, lane: Lane, idx: usize) -> Option<f32> { |
| 3990 | self.project.clip_pitch(lane, idx) |
| 3991 | } |
| 3992 | |
| 3993 | /// Sets that clip's pitch in semitones, clamped to `-12..=12`. One undo step; the |
| 3994 | /// sound is rebuilt where the playhead is, as for [`set_clip_gain`](Self::set_clip_gain). |
| 3995 | /// `false` for a video lane, a bad index, or a value already set. |
| 3996 | pub fn set_clip_pitch(&mut self, lane: Lane, idx: usize, semitones: f32) -> bool { |
| 3997 | self.edit(Dirty::Sound, |p| p.set_clip_pitch(lane, idx, semitones)) |
| 3998 | } |
| 3999 | |
| 4000 | /// The clip's pan at `idx` of `lane`, `-1.0..=1.0` ([`Project::clip_pan`]). |
| 4001 | pub fn clip_pan_of(&self, lane: Lane, idx: usize) -> Option<f32> { |
| 4002 | self.project.clip_pan(lane, idx) |
| 4003 | } |
| 4004 | |
| 4005 | /// Sets that clip's pan. One undo step; the sound is rebuilt where the playhead is, as for |
| 4006 | /// [`set_clip_gain`](Self::set_clip_gain). `false` for a video lane, a bad index, a |
| 4007 | /// non-finite value, or a value already set. |
| 4008 | pub fn set_clip_pan(&mut self, lane: Lane, idx: usize, pan: f32) -> bool { |
| 4009 | self.edit(Dirty::Sound, |p| p.set_clip_pan(lane, idx, pan)) |
| 4010 | } |
| 4011 | |
| 4012 | /// An audio lane's pan, `-1.0..=1.0` ([`Project::lane_pan`]). |
| 4013 | pub fn lane_pan(&self, lane: Lane) -> f32 { |
| 4014 | self.project.lane_pan(lane) |
| 4015 | } |
| 4016 | |
| 4017 | /// Sets it. One undo step; the pan rides in each clip's envelope, so the sound is rebuilt |
| 4018 | /// where the playhead is (a caller commits one change per gesture). |
| 4019 | pub fn set_lane_pan(&mut self, lane: Lane, pan: f32) -> bool { |
| 4020 | self.edit(Dirty::Sound, |p| p.set_lane_pan(lane, pan)) |
| 4021 | } |
| 4022 | |
| 4023 | /// How loud that lane plays, in dB -- everything on it, every frequency of |
| 4024 | /// it. See [`Project::lane_gain_db`] for what it is *not*. |
| 4025 | pub fn lane_gain_db(&self, lane: Lane) -> f32 { |
| 4026 | self.project.lane_gain_db(lane) |
| 4027 | } |
| 4028 | |
| 4029 | /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume |
| 4030 | /// lives at the sum, so the running mixer is handed the new number and |
| 4031 | /// picks it up at its next block ([`crate::audio::MixControls`]). A fader |
| 4032 | /// held down under an arrow key therefore moves the level and nothing else: |
| 4033 | /// no flush, no decoder restart, no hole in the sound and no blink in the |
| 4034 | /// picture. |
| 4035 | /// |
| 4036 | /// The one exception is the timeline that is not mixed at all -- a single |
| 4037 | /// audio lane at unity with the limiter off, which plays through the |
| 4038 | /// bit-exact single-stream path and has no mixer to talk to. Moving *that* |
| 4039 | /// off unity opens one, once; every move after it is live. |
| 4040 | pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { |
| 4041 | if !self.project.set_lane_gain_db(lane, db) { |
| 4042 | return false; |
| 4043 | } |
| 4044 | self.push_mix(); |
| 4045 | true |
| 4046 | } |
| 4047 | |
| 4048 | /// Sets or clears the auto-duck on an audio lane -- see |
| 4049 | /// [`Project::set_lane_duck`]. Live exactly as a volume is: the running |
| 4050 | /// mixer is handed the new duck and picks it up at its next block, and |
| 4051 | /// nothing is rebuilt. |
| 4052 | pub fn set_lane_duck(&mut self, lane: Lane, duck: Option<crate::duck::Duck>) -> bool { |
| 4053 | if !self.project.set_lane_duck(lane, duck) { |
| 4054 | return false; |
| 4055 | } |
| 4056 | self.push_mix(); |
| 4057 | true |
| 4058 | } |
| 4059 | |
| 4060 | /// The duck on `lane`, if it has one -- see [`Project::lane_duck`]. |
| 4061 | pub fn lane_duck(&self, lane: Lane) -> Option<crate::duck::Duck> { |
| 4062 | self.project.lane_duck(lane) |
| 4063 | } |
| 4064 | |
| 4065 | /// Every duck on `lane`, one per key -- see [`Project::lane_duck_list`]. |
| 4066 | pub fn lane_duck_list(&self, lane: Lane) -> Vec<crate::duck::Duck> { |
| 4067 | self.project.lane_duck_list(lane) |
| 4068 | } |
| 4069 | |
| 4070 | /// Removes the duck `lane` has under the key `under` (the key's |
| 4071 | /// [`Lane::ord`]) and keeps its others -- see [`Project::clear_lane_duck`]. |
| 4072 | /// Live like [`set_lane_duck`](Self::set_lane_duck). |
| 4073 | pub fn clear_lane_duck(&mut self, lane: Lane, under: usize) -> bool { |
| 4074 | if !self.project.clear_lane_duck(lane, under) { |
| 4075 | return false; |
| 4076 | } |
| 4077 | self.push_mix(); |
| 4078 | true |
| 4079 | } |
| 4080 | |
| 4081 | /// The voice processors on `lane` -- see [`Project::lane_voice`]. |
| 4082 | pub fn lane_voice(&self, lane: Lane) -> crate::voice::VoiceFx { |
| 4083 | self.project.lane_voice(lane) |
| 4084 | } |
| 4085 | |
| 4086 | /// Sets the voice processors of an audio lane -- see [`Project::set_lane_voice`]. |
| 4087 | /// One undo step. Not live: the processors run on the lane's own stream, so the |
| 4088 | /// sound is rebuilt where the playhead is, as for [`set_eq`](Self::set_eq). |
| 4089 | pub fn set_lane_voice(&mut self, lane: Lane, voice: crate::voice::VoiceFx) -> bool { |
| 4090 | self.edit(Dirty::Sound, |p| p.set_lane_voice(lane, voice)) |
| 4091 | } |
| 4092 | |
| 4093 | /// Learns a noise profile from `lane` -- the quietest half second of it, or the |
| 4094 | /// `range` (lane seconds) -- see [`crate::voice::learn_noise`]. Reads the lane as it |
| 4095 | /// plays and changes nothing. |
| 4096 | pub fn learn_noise( |
| 4097 | &self, |
| 4098 | lane: Lane, |
| 4099 | range: Option<(f64, f64)>, |
| 4100 | ) -> crate::Result<crate::voice::Learned> { |
| 4101 | crate::voice::learn_noise(&self.project, lane, self.meta.frame_rate, self.sample_rate, range) |
| 4102 | } |
| 4103 | |
| 4104 | /// Whether the lane is hidden -- see [`Project::lane_hidden`]. |
| 4105 | pub fn lane_hidden(&self, lane: Lane) -> bool { |
| 4106 | self.project.lane_hidden(lane) |
| 4107 | } |
| 4108 | |
| 4109 | /// Whether the lane is muted -- see [`Project::lane_muted`]. |
| 4110 | pub fn lane_muted(&self, lane: Lane) -> bool { |
| 4111 | self.project.lane_muted(lane) |
| 4112 | } |
| 4113 | |
| 4114 | /// Whether the lane is locked -- see [`Project::lane_locked`]. Nothing here |
| 4115 | /// refuses an edit on it; the front-end does. |
| 4116 | pub fn lane_locked(&self, lane: Lane) -> bool { |
| 4117 | self.project.lane_locked(lane) |
| 4118 | } |
| 4119 | |
| 4120 | /// Hides or shows a lane, live. A video lane's picture is recomposed at the |
| 4121 | /// playhead, the one rebuild this costs ([`Dirty::Picture`]); the sound keeps |
| 4122 | /// playing. A subtitle lane is drawn from the project at every repaint, so |
| 4123 | /// nothing is rebuilt for it at all. |
| 4124 | pub fn set_lane_hidden(&mut self, lane: Lane, hidden: bool) -> bool { |
| 4125 | if !self.project.set_lane_hidden(lane, hidden) { |
| 4126 | return false; |
| 4127 | } |
| 4128 | if lane.kind == LaneKind::Video { |
| 4129 | self.invalidate(Dirty::Picture); |
| 4130 | } |
| 4131 | true |
| 4132 | } |
| 4133 | |
| 4134 | /// Mutes or unmutes an audio lane, live: the mix is handed its new gain at |
| 4135 | /// the next block exactly as a fader is ([`push_mix`](Self::push_mix)). |
| 4136 | pub fn set_lane_muted(&mut self, lane: Lane, muted: bool) -> bool { |
| 4137 | if !self.project.set_lane_muted(lane, muted) { |
| 4138 | return false; |
| 4139 | } |
| 4140 | self.push_mix(); |
| 4141 | true |
| 4142 | } |
| 4143 | |
| 4144 | /// Locks or unlocks a lane. Nothing plays differently, so nothing is |
| 4145 | /// touched -- it is in the lane list, so it is one undo step like the rest. |
| 4146 | pub fn set_lane_locked(&mut self, lane: Lane, locked: bool) -> bool { |
| 4147 | self.project.set_lane_locked(lane, locked) |
| 4148 | } |
| 4149 | |
| 4150 | /// Names a lane ([`Project::set_lane_name`]). A label only: nothing is rebuilt. |
| 4151 | pub fn set_lane_name(&mut self, lane: Lane, name: &str) -> Result<bool, String> { |
| 4152 | self.project.set_lane_name(lane, name) |
| 4153 | } |
| 4154 | |
| 4155 | /// The name given to a lane, `None` for none ([`Project::lane_name`]). |
| 4156 | pub fn lane_name(&self, lane: Lane) -> Option<&str> { |
| 4157 | self.project.lane_name(lane) |
| 4158 | } |
| 4159 | |
| 4160 | /// What a lane header shows: the name, else the address ([`Project::lane_title`]). |
| 4161 | pub fn lane_title(&self, lane: Lane) -> String { |
| 4162 | self.project.lane_title(lane) |
| 4163 | } |
| 4164 | |
| 4165 | /// Solos audio lanes for listening: while any is soloed, every other audio |
| 4166 | /// lane is silent in what this session plays. Monitoring only -- it is not |
| 4167 | /// project state, is not saved, and an export never reads it. Lanes that |
| 4168 | /// are not audio lanes are ignored, and an empty list clears the solo. |
| 4169 | /// `false` when nothing changes. A [`Lane`] is a handle into the lane list, |
| 4170 | /// so solo again after a lane is removed or moved. |
| 4171 | pub fn set_solo(&mut self, lanes: &[Lane]) -> bool { |
| 4172 | let solo: Vec<Lane> = self |
| 4173 | .project |
| 4174 | .audio_lanes() |
| 4175 | .into_iter() |
| 4176 | .filter(|lane| lanes.contains(lane)) |
| 4177 | .collect(); |
| 4178 | if solo == self.solo { |
| 4179 | return false; |
| 4180 | } |
| 4181 | self.solo = solo; |
| 4182 | self.push_mix(); |
| 4183 | true |
| 4184 | } |
| 4185 | |
| 4186 | /// The audio lanes soloed for listening, as [`set_solo`](Self::set_solo) took them. |
| 4187 | pub fn soloed(&self) -> &[Lane] { |
| 4188 | &self.solo |
| 4189 | } |
| 4190 | |
| 4191 | /// The gains the sound plays: the project's own, with the audio lanes |
| 4192 | /// outside a solo silenced. A solo that names no audio lane any more is no |
| 4193 | /// solo, so a stale handle cannot silence everything. The export reads |
| 4194 | /// [`Project::audio_gains`] directly and never comes through here. |
| 4195 | fn mix_gains(&self) -> Vec<f32> { |
| 4196 | soloed_gains( |
| 4197 | self.project.render_view().audio_gains(), |
| 4198 | &self.project.render_view().audio_lanes(), |
| 4199 | &self.solo, |
| 4200 | ) |
| 4201 | } |
| 4202 | |
| 4203 | /// The level meters, as the sound has reached them since the last call, and |
| 4204 | /// starts them over: the highest level each audio lane reached after its own |
| 4205 | /// gain (mute and solo read as silence) and the master peak after the |
| 4206 | /// limiter, before the device's volume. The flat single-lane path has no |
| 4207 | /// mixer, and its one lane is the master. Cheap: atomics and one short lock, |
| 4208 | /// nothing on the device's callback. |
| 4209 | pub fn levels(&self) -> Levels { |
| 4210 | let master = self.audio.as_ref().map_or(0.0, |audio| { |
| 4211 | f32::from_bits(audio.peak.swap(0, Ordering::Relaxed)) |
| 4212 | }); |
| 4213 | let master_lr = self.master_peaks_lr(); |
| 4214 | let mut lanes = match self.mix.as_ref() { |
| 4215 | Some(mix) => mix.take_lane_peaks(), |
| 4216 | None => vec![master], |
| 4217 | }; |
| 4218 | lanes.resize(self.project.audio_lanes().len(), 0.0); |
| 4219 | Levels { lanes, master, master_lr } |
| 4220 | } |
| 4221 | |
| 4222 | /// The master's left and right peaks since the last read (of this or of [`levels`](Self::levels)), |
| 4223 | /// and starts them over: the stereo transport meter's own door, which leaves the lane peaks and |
| 4224 | /// the mono master the mix card reads alone. |
| 4225 | pub fn master_peaks_lr(&self) -> [f32; 2] { |
| 4226 | self.audio.as_ref().map_or([0.0; 2], |audio| { |
| 4227 | [0, 1].map(|i| f32::from_bits(audio.peak_lr[i].swap(0, Ordering::Relaxed))) |
| 4228 | }) |
| 4229 | } |
| 4230 | |
| 4231 | /// Hands the mix the running mixer is reading its new settings -- the whole |
| 4232 | /// of what a fader and a ceiling cost. With no mixer listening (the |
| 4233 | /// single-lane flat path, and a session with no sound at all) the sound is |
| 4234 | /// rebuilt instead, which is what opens one. |
| 4235 | fn push_mix(&mut self) { |
| 4236 | let gains = self.mix_gains(); |
| 4237 | let ducks = self.project.render_view().audio_ducks(); |
| 4238 | let limiter = self.project.limiter(); |
| 4239 | // A mixer reading these, or an open on its way to being one: either way |
| 4240 | // the number is heard without a rebuild, and *that* is what a handle |
| 4241 | // left over from an open that found nothing cannot do |
| 4242 | // ([`crate::audio::MixControls::is_reachable`]). |
| 4243 | if let Some(mix) = self.mix.as_ref().filter(|mix| mix.is_reachable()) { |
| 4244 | mix.set(gains, ducks, limiter); |
| 4245 | return; |
| 4246 | } |
| 4247 | // Nothing to hand it to. Only a setting that *needs* a mixer is worth |
| 4248 | // the flush and the re-open: a ceiling dragged with the limiter off, or |
| 4249 | // a fader put back to unity, changes not one sample of the flat |
| 4250 | // single-stream path the timeline is already playing |
| 4251 | // ([`AudioSession::is_mixed`]), and reseeking per nudge was a hole in |
| 4252 | // the sound for a change nobody could hear. |
| 4253 | if crate::audio::AudioSession::is_mixed(gains.len(), &gains, limiter, &self.project.render_view().audio_voices()) { |
| 4254 | self.reseek_audio(); |
| 4255 | } |
| 4256 | } |
| 4257 | |
| 4258 | /// The master limiter the whole mix is summed through. |
| 4259 | pub fn limiter(&self) -> crate::limiter::Limiter { |
| 4260 | self.project.limiter() |
| 4261 | } |
| 4262 | |
| 4263 | /// Sets it, live like a lane volume and for the same reason -- the ceiling |
| 4264 | /// a person is dragging has to be the ceiling they are hearing. Nothing is |
| 4265 | /// rebuilt: the running limiter is *retuned* between two blocks |
| 4266 | /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps |
| 4267 | /// running and the sample count the master clock is made of does not move. |
| 4268 | /// |
| 4269 | /// corner-cut: not an undo step, and deliberately -- [`Project::undo`] |
| 4270 | /// restores the lane list, and the limiter is not in it, so snapshotting |
| 4271 | /// here would push a step whose undo changes nothing a person can see or |
| 4272 | /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is* |
| 4273 | /// undoable only because a lane volume lives in that list). The project |
| 4274 | /// resolution is outside undo for the same reason and says so. Upgrade path |
| 4275 | /// is a history that carries the mix beside the lanes, which every existing |
| 4276 | /// snapshot site would then have to fill in. |
| 4277 | pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool { |
| 4278 | if !self.project.set_limiter(limiter) { |
| 4279 | return false; |
| 4280 | } |
| 4281 | self.push_mix(); |
| 4282 | true |
| 4283 | } |
| 4284 | |
| 4285 | /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, |
| 4286 | /// silence on the audio one, and nothing else moves. Reseeks, because what |
| 4287 | /// the playhead sits on has changed. `false` for a bad index -- the lift of |
| 4288 | /// the last placement there is empties the timeline, which is a state |
| 4289 | /// ([`is_empty`](Self::is_empty)) and one undo away. |
| 4290 | pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool { |
| 4291 | self.edit(Dirty::Both, |p| p.lift(lane, idx)) |
| 4292 | } |
| 4293 | |
| 4294 | /// [`swap_clips`](Self::swap_clips) without the ripple: each clip takes the |
| 4295 | /// other's head and nothing between them moves ([`Project::swap_in_place`]). |
| 4296 | /// The `Err` names the clip the longer one would overlap, and nothing changes. |
| 4297 | pub fn swap_clips_in_place(&mut self, lane: Lane, a: usize, b: usize) -> crate::Result<()> { |
| 4298 | self.project.swap_in_place(lane, a, b)?; |
| 4299 | self.invalidate(Dirty::Both); |
| 4300 | Ok(()) |
| 4301 | } |
| 4302 | |
| 4303 | /// Swaps two placements of one lane ([`Project::swap`]): `b` takes `a`'s |
| 4304 | /// start and the ones between them ripple by the difference. One undo step. |
| 4305 | pub fn swap_clips(&mut self, lane: Lane, a: usize, b: usize) -> bool { |
| 4306 | self.edit(Dirty::Both, |p| p.swap(lane, a, b)) |
| 4307 | } |
| 4308 | |
| 4309 | /// Moves that clip onto lane `to` with its head at timeline frame `start` -- |
| 4310 | /// the drag that carries a take along its track or onto another one, and its |
| 4311 | /// whole group with it. See [`Project::move_clip`] for the walls `start` is |
| 4312 | /// clamped to and the ways a drop is refused. One undo step, and it reseeks |
| 4313 | /// like every other edit: which lane a clip sits on is what the compositor's |
| 4314 | /// topmost-lane-wins rule reads, and where it starts is what the playhead |
| 4315 | /// reads, so the frame on screen is recomposed at once. |
| 4316 | /// |
| 4317 | /// A *frame*, where the rest of this type takes seconds, for |
| 4318 | /// [`trim_clip`](Self::trim_clip)'s reason: the drag has already put the |
| 4319 | /// pointer on a frame, and converting it back through seconds would be a |
| 4320 | /// rounding step between the box let go of and the box committed. |
| 4321 | /// |
| 4322 | /// Across kinds (a picture onto an audio lane or back) the clip must fit |
| 4323 | /// the new lane's wall ([`held_to_lane`](Self::held_to_lane)): a clip past |
| 4324 | /// it is refused rather than cut, since a move is not an edit of its length. |
| 4325 | pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool { |
| 4326 | if from.kind != to.kind { |
| 4327 | let Some(clip) = self.lane_clips(from).get(idx).cloned() else { |
| 4328 | return false; |
| 4329 | }; |
| 4330 | if self.held_to_lane(to, clip.clone()).out_frame != clip.out_frame { |
| 4331 | return false; |
| 4332 | } |
| 4333 | } |
| 4334 | self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start)) |
| 4335 | } |
| 4336 | |
| 4337 | /// [`move_clip_to`](Self::move_clip_to)'s general form: every one of |
| 4338 | /// `picks` travels the same frame delta as the dragged clip at `idx` of |
| 4339 | /// `from`, all-or-nothing, one undo step for the lot -- what a hand drags |
| 4340 | /// on a selection rather than a lone clip. See |
| 4341 | /// [`Project::move_selection`] for the clamp that makes it all-or-nothing. |
| 4342 | pub fn move_selection_to( |
| 4343 | &mut self, |
| 4344 | picks: &[(Lane, usize)], |
| 4345 | from: Lane, |
| 4346 | idx: usize, |
| 4347 | to: Lane, |
| 4348 | start: u32, |
| 4349 | ) -> bool { |
| 4350 | self.edit(Dirty::Both, |p| { |
| 4351 | p.move_selection(picks, from, idx, to, start) |
| 4352 | }) |
| 4353 | } |
| 4354 | |
| 4355 | /// [`trim_clip`](Self::trim_clip) as a ripple trim ([`Project::ripple_trim`]): the hole the |
| 4356 | /// edge leaves closes, or opens, and what follows moves with it. One undo step. |
| 4357 | pub fn ripple_trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool { |
| 4358 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4359 | if !self.project.ripple_trim_with_walls(lane, idx, edge, to, SourceWalls { picture: &picture, sound: &sound }) { |
| 4360 | return false; |
| 4361 | } |
| 4362 | let now = self.now(); |
| 4363 | self.seek(now); |
| 4364 | true |
| 4365 | } |
| 4366 | |
| 4367 | /// Drags one end of that clip to timeline frame `to`, changing how much of |
| 4368 | /// its source it plays and nothing else on the lane -- see [`Project::trim`] |
| 4369 | /// for the walls it is clamped by, which this fills the source lengths in |
| 4370 | /// for. One undo step per call, so a front-end calls it once, at the release |
| 4371 | /// of the drag. Reseeks like every other edit, which is what makes the |
| 4372 | /// picture (and the sound) follow a new in-point straight away. `false` for |
| 4373 | /// a bad index and for an edge already where it was asked to go. |
| 4374 | /// |
| 4375 | /// A *frame*, where the rest of this type takes seconds: a drag has already |
| 4376 | /// asked [`trim_room`](Self::trim_room) where the edge may land, and that |
| 4377 | /// answer is in frames -- converting it back through seconds would be a |
| 4378 | /// rounding step between the width drawn and the width committed. |
| 4379 | pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool { |
| 4380 | // Spelled out rather than through `edit`, whose closure cannot hold a |
| 4381 | // second borrow of the session while it has the project. |
| 4382 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4383 | if !self.project.trim_with_walls(lane, idx, edge, to, SourceWalls { picture: &picture, sound: &sound }) { |
| 4384 | return false; |
| 4385 | } |
| 4386 | let now = self.now(); |
| 4387 | self.seek(now); |
| 4388 | true |
| 4389 | } |
| 4390 | |
| 4391 | /// **Roll**: moves the cut at the end of the clip at `idx` of `lane` to timeline |
| 4392 | /// frame `to` ([`Project::roll`]): the out-point of that clip and the in-point of |
| 4393 | /// the one behind it move together. Returns where the cut is now; `None` for a |
| 4394 | /// clip with nothing abutting behind it. Reseeks, one undo step. |
| 4395 | pub fn roll_clip(&mut self, lane: Lane, idx: usize, to: u32) -> Option<u32> { |
| 4396 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4397 | let at = self.project.roll(lane, idx, to, SourceWalls { picture: &picture, sound: &sound })?; |
| 4398 | let now = self.now(); |
| 4399 | self.seek(now); |
| 4400 | Some(at) |
| 4401 | } |
| 4402 | |
| 4403 | /// Where that cut may travel, `(first, last)` frame inclusive ([`Project::roll_room`]). |
| 4404 | pub fn roll_room(&self, lane: Lane, idx: usize) -> Option<(u32, u32)> { |
| 4405 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4406 | self.project.roll_room(lane, idx, SourceWalls { picture: &picture, sound: &sound }) |
| 4407 | } |
| 4408 | |
| 4409 | /// **Slide**: starts that clip at timeline frame `to` between its neighbours |
| 4410 | /// ([`Project::slide`]). Returns where it starts now; `None` for a clip |
| 4411 | /// without a neighbour on both sides. Reseeks, one undo step. |
| 4412 | pub fn slide_clip(&mut self, lane: Lane, idx: usize, to: u32) -> Option<u32> { |
| 4413 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4414 | let at = self.project.slide(lane, idx, to, SourceWalls { picture: &picture, sound: &sound })?; |
| 4415 | let now = self.now(); |
| 4416 | self.seek(now); |
| 4417 | Some(at) |
| 4418 | } |
| 4419 | |
| 4420 | /// Where that clip may start when slid, `(first, last)` frame inclusive ([`Project::slide_room`]). |
| 4421 | pub fn slide_room(&self, lane: Lane, idx: usize) -> Option<(u32, u32)> { |
| 4422 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4423 | self.project.slide_room(lane, idx, SourceWalls { picture: &picture, sound: &sound }) |
| 4424 | } |
| 4425 | |
| 4426 | /// **Slip**: shifts that clip's source window by `by` source frames |
| 4427 | /// ([`Project::slip`]; [`slip_source_delta`](Self::slip_source_delta) turns timeline |
| 4428 | /// frames into them). Returns the frames it moved; `None` for a bad index or a |
| 4429 | /// still. Reseeks, one undo step. |
| 4430 | pub fn slip_clip(&mut self, lane: Lane, idx: usize, by: i64) -> Option<i64> { |
| 4431 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4432 | let moved = self.project.slip(lane, idx, by, SourceWalls { picture: &picture, sound: &sound })?; |
| 4433 | if moved != 0 { |
| 4434 | let now = self.now(); |
| 4435 | self.seek(now); |
| 4436 | } |
| 4437 | Some(moved) |
| 4438 | } |
| 4439 | |
| 4440 | /// How far that clip may slip, `(back, forward)` source frames ([`Project::slip_room`]). |
| 4441 | pub fn slip_room(&self, lane: Lane, idx: usize) -> Option<(i64, i64)> { |
| 4442 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4443 | self.project.slip_room(lane, idx, SourceWalls { picture: &picture, sound: &sound }) |
| 4444 | } |
| 4445 | |
| 4446 | /// The source frames `by` timeline frames are worth for that clip ([`Project::slip_source_delta`]). |
| 4447 | pub fn slip_source_delta(&self, lane: Lane, idx: usize, by: i64) -> Option<i64> { |
| 4448 | self.project.slip_source_delta(lane, idx, by) |
| 4449 | } |
| 4450 | |
| 4451 | /// How fast the clip at `idx` of `lane` plays -- what a card shows before |
| 4452 | /// anyone drags it. |
| 4453 | pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed { |
| 4454 | self.project.speed_of(lane, idx) |
| 4455 | } |
| 4456 | |
| 4457 | /// Sets it, for that clip and its whole group ([`Project::set_speed`]): one |
| 4458 | /// undo step for the lot. Reseeks like every other edit, so the picture runs |
| 4459 | /// -- and the sound is resampled -- from the next frame on rather than at the |
| 4460 | /// next play. The `Err` names the clip in the way when slowing one down |
| 4461 | /// would run it into its neighbour, and nothing changes. |
| 4462 | pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> { |
| 4463 | // Spelled out rather than through `edit`, whose closure hands back a |
| 4464 | // bool and would drop the refusal's own words. The playhead moves |
| 4465 | let at = self.project.speeded_playhead( |
| 4466 | lane, |
| 4467 | idx, |
| 4468 | speed, |
| 4469 | secs_to_frame(self.now(), self.meta.frame_rate), |
| 4470 | ); |
| 4471 | self.project.set_speed(lane, idx, speed)?; |
| 4472 | let now = at.map_or_else( |
| 4473 | || self.now(), |
| 4474 | |frame| f64::from(frame) / self.meta.frame_rate, |
| 4475 | ); |
| 4476 | self.seek(now); |
| 4477 | Ok(()) |
| 4478 | } |
| 4479 | |
| 4480 | /// Whether the clip at `idx` of `lane` plays backwards ([`Project::reversed_of`]). |
| 4481 | pub fn reversed_of(&self, lane: Lane, idx: usize) -> bool { |
| 4482 | self.project.reversed_of(lane, idx) |
| 4483 | } |
| 4484 | |
| 4485 | /// Plays the clip and its whole group backwards, or forwards again |
| 4486 | /// ([`Project::set_reverse`]): one undo step, and a reseek at the playhead so |
| 4487 | /// the picture and the sound run the new way from the next frame on. |
| 4488 | pub fn set_reverse(&mut self, lane: Lane, idx: usize, on: bool) -> crate::Result<()> { |
| 4489 | self.project.set_reverse(lane, idx, on)?; |
| 4490 | let now = self.now(); |
| 4491 | self.seek(now); |
| 4492 | Ok(()) |
| 4493 | } |
| 4494 | |
| 4495 | /// Gives the clip at `idx` of `lane` (and its group) a speed ramp, or clears it |
| 4496 | /// with empty `keys` ([`Project::set_speed_ramp`]). Reseeks like |
| 4497 | /// [`set_speed`](Self::set_speed), and the playhead holds where it stood. |
| 4498 | pub fn set_speed_ramp( |
| 4499 | &mut self, |
| 4500 | lane: Lane, |
| 4501 | idx: usize, |
| 4502 | keys: &[crate::project::SpeedKey], |
| 4503 | ) -> crate::Result<()> { |
| 4504 | self.project.set_speed_ramp(lane, idx, keys)?; |
| 4505 | let now = self.now(); |
| 4506 | self.seek(now); |
| 4507 | Ok(()) |
| 4508 | } |
| 4509 | |
| 4510 | /// [`set_speed`](Self::set_speed) without the undo step -- the samples inside |
| 4511 | /// one drag ([`Project::set_speed_live`]). Reseeks like the committing one, |
| 4512 | /// which is what makes the bar move the picture under the hand. |
| 4513 | pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> { |
| 4514 | // The mapping on every sample, not just at the commit: the bar moves |
| 4515 | // the rate live, and the scene has to stay put across the whole |
| 4516 | // gesture or the last picture before the release is not the one the |
| 4517 | // commit lands on. |
| 4518 | let at = self.project.speeded_playhead( |
| 4519 | lane, |
| 4520 | idx, |
| 4521 | speed, |
| 4522 | secs_to_frame(self.now(), self.meta.frame_rate), |
| 4523 | ); |
| 4524 | self.project.set_speed_live(lane, idx, speed)?; |
| 4525 | let now = at.map_or_else( |
| 4526 | || self.now(), |
| 4527 | |frame| f64::from(frame) / self.meta.frame_rate, |
| 4528 | ); |
| 4529 | self.seek(now); |
| 4530 | Ok(()) |
| 4531 | } |
| 4532 | |
| 4533 | /// The picture's source frame at `timeline_secs`: which source, and which |
| 4534 | /// frame of it -- the composite a viewer is looking at, through the same |
| 4535 | /// span math the decoder walks. What a test asks to prove a reseek kept |
| 4536 | /// the scene, and nothing in the editor itself reads. |
| 4537 | pub fn video_source_frame_at(&self, timeline_secs: f64) -> Option<(usize, u32)> { |
| 4538 | crate::export::stack_span_at(&self.project.render_view(), secs_to_frame(timeline_secs, self.meta.frame_rate)) |
| 4539 | .and_then(|s| s.from) |
| 4540 | } |
| 4541 | |
| 4542 | /// The lanes closing the gap `(start, frames)` on `lane` must ripple |
| 4543 | /// together to keep every media take crossing it in sync |
| 4544 | /// ([`Project::gap_take_scope`]) -- what a right-click on empty bench |
| 4545 | /// space asks before offering to close it. Subtitle gaps stay on their own |
| 4546 | /// lane because captions are not A/V take halves. |
| 4547 | pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> { |
| 4548 | self.project.gap_take_scope(lane, start, frames) |
| 4549 | } |
| 4550 | |
| 4551 | /// Closes every bounded gap on one lane. Media lanes keep linked takes |
| 4552 | /// whole when the other half has the matching empty stretch and report the |
| 4553 | /// gaps that were not safe to close; subtitle lanes ripple captions only. |
| 4554 | pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> { |
| 4555 | let report = self.project.close_all_gaps_on_lane(lane)?; |
| 4556 | if report.closed > 0 { |
| 4557 | let now = self.now(); |
| 4558 | self.seek(now); |
| 4559 | } |
| 4560 | Ok(report) |
| 4561 | } |
| 4562 | |
| 4563 | /// Cuts every one of `regions` -- `(start, len)` in timeline frames -- out |
| 4564 | /// of the lanes in `scope` and closes each hole, as **one** edit |
| 4565 | /// ([`Project::cut_regions`]): the jumpcut a silence scan |
| 4566 | /// ([`crate::silence`]) asks for, one undo press however many silences it |
| 4567 | /// found. A lane outside `scope` does not move. Reseeks like every other |
| 4568 | /// edit, so what plays is the cut timeline from the playhead on. The `Err` |
| 4569 | /// names what is in the way and nothing changes. |
| 4570 | pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> { |
| 4571 | // Spelled out rather than through `edit`, whose closure hands back a |
| 4572 | // bool and would drop the refusal's own words. |
| 4573 | self.project.cut_regions(regions, scope)?; |
| 4574 | let now = self.now(); |
| 4575 | self.seek(now); |
| 4576 | Ok(()) |
| 4577 | } |
| 4578 | |
| 4579 | /// Plays every one of those regions at `speed` instead of cutting them, |
| 4580 | /// closing the room each one no longer needs ([`Project::speed_regions`]) -- |
| 4581 | /// one edit, one undo press, and the same scope rule. The `Err` names the |
| 4582 | /// lane and frame in the way and nothing changes. |
| 4583 | pub fn speed_regions( |
| 4584 | &mut self, |
| 4585 | regions: &[(u32, u32)], |
| 4586 | speed: Speed, |
| 4587 | scope: &[Lane], |
| 4588 | ) -> crate::Result<()> { |
| 4589 | self.project.speed_regions(regions, speed, scope)?; |
| 4590 | let now = self.now(); |
| 4591 | self.seek(now); |
| 4592 | Ok(()) |
| 4593 | } |
| 4594 | |
| 4595 | // The length of each source on a picture lane and on an audio lane |
| 4596 | // ([`wall_table`]): a linked take drags both edges together, so a trim |
| 4597 | // measures each lane's members against that lane's own length. |
| 4598 | |
| 4599 | /// Where that edge may land, `(first, last)` timeline frame inclusive: what |
| 4600 | /// a drag clamps the pointer to so the box it draws is the box |
| 4601 | /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index. |
| 4602 | pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> { |
| 4603 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4604 | self.project.trim_room_with_walls(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound }) |
| 4605 | } |
| 4606 | |
| 4607 | /// [`trim_room`](Self::trim_room) with the walls named: which of the two is |
| 4608 | /// the source's media limit, so a drag that stops there can say so. `None` |
| 4609 | /// for a bad index. |
| 4610 | pub fn trim_walls(&self, lane: Lane, idx: usize, edge: Edge) -> Option<TrimWalls> { |
| 4611 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4612 | self.project.trim_walls_with_walls(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound }) |
| 4613 | } |
| 4614 | |
| 4615 | /// [`trim_walls`](Self::trim_walls) with each wall's bound named |
| 4616 | /// ([`Project::trim_bounds`]): the source, a neighbour at a frame, the |
| 4617 | /// timeline's first frame, a clip's minimum length or a still's cap. Asked |
| 4618 | /// before a trim, so the names are for the walls the trim is measured to. |
| 4619 | /// `None` for a bad index. |
| 4620 | pub fn trim_bounds(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(WallBound, WallBound)> { |
| 4621 | let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 4622 | self.project |
| 4623 | .trim_bounds(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound }) |
| 4624 | } |
| 4625 | |
| 4626 | /// Records how long a source is and what rate it was shot at, for a source |
| 4627 | /// index that may be one `Project::import` just made or one it handed back. |
| 4628 | /// See [`Self::counts`] and [`Self::rates`], which are one table in two |
| 4629 | /// vectors and grow together. |
| 4630 | fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) { |
| 4631 | if source == self.counts.len() { |
| 4632 | self.counts.push(frames); |
| 4633 | self.rates.push(rate); |
| 4634 | } |
| 4635 | debug_assert_eq!(self.counts.len(), self.project.sources().len()); |
| 4636 | debug_assert_eq!(self.rates.len(), self.counts.len()); |
| 4637 | // A source just joined, which is the one moment the session's audio |
| 4638 | // device may need arming ([`Self::arm_audio`]). |
| 4639 | self.arm_audio(); |
| 4640 | } |
| 4641 | |
| 4642 | /// Opens the audio device for the first source in the library that has a |
| 4643 | /// track, when this session has none. |
| 4644 | /// |
| 4645 | /// A session opened silent -- its first file carried no sound, so |
| 4646 | /// [`Self::open_library`]/[`Self::open`] had no track to open a device on |
| 4647 | /// -- must not stay silent once a source *with* sound joins it: every later |
| 4648 | /// clip's audio would go unheard for the rest of the session. That is |
| 4649 | /// exactly what the walk [`Self::open_project`] makes at open prevents for |
| 4650 | /// a loaded project (c581d41); this is the same walk at the add door, and |
| 4651 | /// [`Self::note_frames`] is the one place a source joins. |
| 4652 | /// |
| 4653 | /// A no-op once a device is open, so it costs a scan of `is_some` on every |
| 4654 | /// later import. The clock stays on wall time until the next seek |
| 4655 | /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end |
| 4656 | /// makes as it places the file it just imported. |
| 4657 | fn arm_audio(&mut self) { |
| 4658 | // A device that is there but *dead* is not a device: the walk below |
| 4659 | // opens another one, which is also what clears the notice a death put up |
| 4660 | // ([`Self::tick`]). |
| 4661 | let carried = self |
| 4662 | .audio |
| 4663 | .as_ref() |
| 4664 | .map(|audio| audio.gain.load(Ordering::Acquire)); |
| 4665 | if let Some(audio) = &self.audio |
| 4666 | && !audio.died.load(Ordering::Acquire) |
| 4667 | { |
| 4668 | return; |
| 4669 | } |
| 4670 | for source in self |
| 4671 | .project |
| 4672 | .sources() |
| 4673 | .iter() |
| 4674 | .filter(|s| !crate::is_image(&s.path)) |
| 4675 | { |
| 4676 | let (audio, disabled) = open_audio(&source.path, source.audio_stream); |
| 4677 | if let Some(audio) = audio { |
| 4678 | // The device is being replaced under a session that may already |
| 4679 | // be running at a level the user chose, so that level comes |
| 4680 | // across with it ([`Audio::gain`]) rather than the fresh |
| 4681 | // stream's 1.0. |
| 4682 | if let Some(bits) = carried { |
| 4683 | audio.gain.store(bits, Ordering::Release); |
| 4684 | audio.ao.lock().unwrap().set_volume(f32::from_bits(bits)); |
| 4685 | } |
| 4686 | self.audio = Some(audio); |
| 4687 | self.audio_disabled = disabled; |
| 4688 | return; |
| 4689 | } |
| 4690 | } |
| 4691 | } |
| 4692 | |
| 4693 | /// Opens the output again for a stream that died, at the rate and channel |
| 4694 | /// count it carried, and clears the flag that stopped the session feeding. |
| 4695 | /// |
| 4696 | /// An output that goes away -- a PipeWire daemon restarting, a sink node |
| 4697 | /// removed and put back -- leaves every stream that was open on it dead for |
| 4698 | /// good: its position is frozen, so the clock can only fall to wall time, and |
| 4699 | /// a session that never opens another device is silent for the rest of its |
| 4700 | /// life, through every seek and every pause/play, with nothing said about it. |
| 4701 | /// |
| 4702 | /// The device *only*, never the file: the feeder is [`Self::start_audio`]'s, |
| 4703 | /// at the seek that follows. That is what lets [`Self::tick`] call this too, |
| 4704 | /// once a frame -- a tick is not a seek and must not reseek the timeline. The |
| 4705 | /// clock is on wall time by then and stays there until a seek comes, which is |
| 4706 | /// the seek whose feeder opens in step with the picture. |
| 4707 | /// |
| 4708 | /// `if_idle_for` is the cooldown: a tick passes [`AUDIO_REARM_AFTER`], because |
| 4709 | /// sixty opens a second against a device that is gone for good is a spin; a |
| 4710 | /// seek passes zero, because that one is a person asking. |
| 4711 | /// |
| 4712 | /// `false` when there is nothing to open, nothing came back, or the cooldown |
| 4713 | /// has not passed -- and the flag stays standing for the next attempt. |
| 4714 | fn rearm_audio(&mut self, if_idle_for: Duration) -> bool { |
| 4715 | let Some(audio) = &self.audio else { |
| 4716 | return false; |
| 4717 | }; |
| 4718 | if !audio.died.load(Ordering::Acquire) { |
| 4719 | return true; |
| 4720 | } |
| 4721 | { |
| 4722 | let mut at = audio.rearm_at.lock().unwrap(); |
| 4723 | if at.is_some_and(|at| at.elapsed() < if_idle_for) { |
| 4724 | return false; |
| 4725 | } |
| 4726 | *at = Some(Instant::now()); |
| 4727 | } |
| 4728 | let Some(ao) = AoSession::open(audio.sample_rate, audio.channels as u32) else { |
| 4729 | return false; |
| 4730 | }; |
| 4731 | // A stream comes up streaming and a session starts paused: the fresh one |
| 4732 | // is silenced until the seek that feeds it says otherwise, which is the |
| 4733 | // same two steps [`open_audio`] takes on the way in. |
| 4734 | ao.set_active(false); |
| 4735 | // A fresh stream comes up at full volume, so the level this session was |
| 4736 | // already running at is put back onto it before it is installed: a |
| 4737 | // muted session that lost its device to a daemon restart would |
| 4738 | // otherwise come back loud while the window still reads "muted". |
| 4739 | ao.set_volume(f32::from_bits(audio.gain.load(Ordering::Acquire))); |
| 4740 | // Replacing the session is what closes the dead stream, so it is done |
| 4741 | // under the device lock the feeder writes through. |
| 4742 | *audio.ao.lock().unwrap() = ao; |
| 4743 | // The clock anchor and the played-out arithmetic both belong to the |
| 4744 | // stream that died: the new one stamps its own first sample |
| 4745 | // ([`Audio::content_at`]), and `start_audio` re-bases the count from the |
| 4746 | // device's own position. |
| 4747 | audio.content_at.store(-1, Ordering::Release); |
| 4748 | audio.died.store(false, Ordering::Release); |
| 4749 | if self.audio_disabled.as_deref() == Some(AUDIO_LOST) { |
| 4750 | self.audio_disabled = None; |
| 4751 | } |
| 4752 | true |
| 4753 | } |
| 4754 | |
| 4755 | /// The rate noted for whichever source plays `path`, by |
| 4756 | /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however |
| 4757 | /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session |
| 4758 | /// has never taken in. |
| 4759 | fn file_rate(&self, path: &Path) -> Rate { |
| 4760 | self.source_of(path) |
| 4761 | .map_or(Rate::REAL_TIME, |i| self.rates[i]) |
| 4762 | } |
| 4763 | |
| 4764 | /// Which file this source's **picture** is decoded from: its stand-in when |
| 4765 | /// the project is cut on stand-ins and one has been made for it, and the |
| 4766 | /// film itself in every other case ([`crate::proxy`]). |
| 4767 | /// |
| 4768 | /// One `stat` per span open, against a decoder open that costs milliseconds |
| 4769 | /// -- so a proxy that appeared (or was deleted) since the last seek is |
| 4770 | /// picked up at this one, and no table of attachments exists to disagree |
| 4771 | /// with the cache. |
| 4772 | /// |
| 4773 | /// The sound never comes through here: [`open_audio`] is given the |
| 4774 | /// project's own source path, so a mix is the film's however this answers. |
| 4775 | pub fn picture_path(&self, source: usize) -> PathBuf { |
| 4776 | let path = &self.project.sources()[source].path; |
| 4777 | let Some(proxy) = self.proxies.then(|| crate::proxy::cached(path)).flatten() else { |
| 4778 | return path.clone(); |
| 4779 | }; |
| 4780 | // Said out loud, once per span opened, because "the picture came off |
| 4781 | // the stand-in and the delivery did not" is a claim somebody has to be |
| 4782 | // able to check: `export` prints the file *it* reads by the same rule. |
| 4783 | eprintln!("picture: proxy {}", proxy.display()); |
| 4784 | proxy |
| 4785 | } |
| 4786 | |
| 4787 | /// Whether the picture comes off the stand-ins ([`Self::set_proxies`]). |
| 4788 | pub fn proxies(&self) -> bool { |
| 4789 | self.proxies |
| 4790 | } |
| 4791 | |
| 4792 | /// Cut on the stand-ins, or on the films themselves. Reseeks, so the very |
| 4793 | /// next picture comes from the other file -- which is what makes this a |
| 4794 | /// switch a person can flip while watching. |
| 4795 | /// |
| 4796 | /// Says nothing about *which* films have one: a source with no stand-in |
| 4797 | /// keeps playing its own pictures either way, and one made while this is on |
| 4798 | /// is picked up at the next seek. |
| 4799 | /// |
| 4800 | /// One undo step ([`Project::push_settings_step`]), and the seek below is |
| 4801 | /// what makes the undo of it land on the picture: it reopens the span |
| 4802 | /// through [`picture_path`](Self::picture_path), which reads this switch. |
| 4803 | pub fn set_proxies(&mut self, on: bool) { |
| 4804 | if self.proxies == on { |
| 4805 | return; |
| 4806 | } |
| 4807 | let from = self.settings_value(); |
| 4808 | self.proxies = on; |
| 4809 | self.step_settings(from); |
| 4810 | let now = self.now(); |
| 4811 | self.seek(now); |
| 4812 | } |
| 4813 | |
| 4814 | /// Which encoder an export of this project would open its picture on |
| 4815 | /// ([`crate::export::EncoderSeat`]). What a front-end puts into the |
| 4816 | /// [`ExportSettings`](crate::export::ExportSettings) it starts an export |
| 4817 | /// with -- and what the export card shows -- so the pick, the prediction |
| 4818 | /// and the file are one answer. |
| 4819 | pub fn encoder_seat(&self) -> crate::export::EncoderSeat { |
| 4820 | self.encoder_seat |
| 4821 | } |
| 4822 | |
| 4823 | /// Gives a loaded project the window's seat when it carries none of its own: nobody |
| 4824 | /// picked it, so it is no undo step. Its own copy of the settings is kept in step with |
| 4825 | /// the session, as [`Self::set_encoder_seat`] keeps it, and nothing else moves. |
| 4826 | pub fn default_encoder_seat(&mut self, seat: crate::export::EncoderSeat) { |
| 4827 | if self.encoder_seat == seat { |
| 4828 | return; |
| 4829 | } |
| 4830 | self.encoder_seat = seat; |
| 4831 | self.project.mirror_settings(self.settings_value()); |
| 4832 | } |
| 4833 | |
| 4834 | /// Pick the seat. Nothing to reseek and nothing to re-probe here: this |
| 4835 | /// decides what an *export* opens, never what plays. One undo step, like |
| 4836 | /// every other pick on the project. |
| 4837 | pub fn set_encoder_seat(&mut self, seat: crate::export::EncoderSeat) { |
| 4838 | if self.encoder_seat == seat { |
| 4839 | return; |
| 4840 | } |
| 4841 | let from = self.settings_value(); |
| 4842 | self.encoder_seat = seat; |
| 4843 | self.step_settings(from); |
| 4844 | } |
| 4845 | |
| 4846 | /// The rate this project's mix was picked to run at |
| 4847 | /// ([`Self::set_sample_rate`]), or `None` for the rate the first audio |
| 4848 | /// source derives it to. |
| 4849 | pub fn sample_rate(&self) -> Option<u32> { |
| 4850 | self.sample_rate |
| 4851 | } |
| 4852 | |
| 4853 | /// Pick the mix's own rate, overriding the derived one. Nothing to reseek |
| 4854 | /// here: it takes effect at the next audio rebuild (a seek, an edit, a |
| 4855 | /// reopen), not on the device already playing. One undo step, like every |
| 4856 | /// other pick on the project. |
| 4857 | pub fn set_sample_rate(&mut self, rate: Option<u32>) { |
| 4858 | if self.sample_rate == rate { |
| 4859 | return; |
| 4860 | } |
| 4861 | let from = self.settings_value(); |
| 4862 | self.sample_rate = rate; |
| 4863 | self.step_settings(from); |
| 4864 | } |
| 4865 | |
| 4866 | /// Whether an imported film that wants a stand-in gets one made for it |
| 4867 | /// there and then ([`Self::set_auto_proxies`]). |
| 4868 | pub fn auto_proxies(&self) -> bool { |
| 4869 | self.auto_proxies |
| 4870 | } |
| 4871 | |
| 4872 | /// Make the stand-ins on import, or make none until asked. Nothing to |
| 4873 | /// reseek: this decides what is *started*, never what is decoded -- a proxy |
| 4874 | /// already in the cache is still cut on while [`Self::proxies`] is on. |
| 4875 | /// |
| 4876 | /// One undo step, like every other switch on the project. |
| 4877 | pub fn set_auto_proxies(&mut self, on: bool) { |
| 4878 | if self.auto_proxies == on { |
| 4879 | return; |
| 4880 | } |
| 4881 | let from = self.settings_value(); |
| 4882 | self.auto_proxies = on; |
| 4883 | self.step_settings(from); |
| 4884 | } |
| 4885 | |
| 4886 | /// Which source `path` is, canonicalising only if it has to: a source's own |
| 4887 | /// path is canonical ([`Source::new`]), so a caller handing one back from |
| 4888 | /// [`sources`](Self::sources) -- which is every library row -- hits on the |
| 4889 | /// first walk and never pays for the `canonicalize` syscall the second one |
| 4890 | /// makes. One rule, so a path that names a length names a rate too. |
| 4891 | fn source_of(&self, path: &Path) -> Option<usize> { |
| 4892 | let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); |
| 4893 | at(path).or_else(|| at(&Source::new(path, 0).path)) |
| 4894 | } |
| 4895 | |
| 4896 | /// How long the whole of `path` is, in timeline frames: the length noted |
| 4897 | /// when it became a source, so a file sitting in the library with no clip |
| 4898 | /// anywhere still knows how much of itself there is to place. `0` for a |
| 4899 | /// file this session has never taken in. |
| 4900 | /// |
| 4901 | /// By path and not by stream, because a file is one length however many |
| 4902 | /// audio tracks it carries -- the picture's frame count for an mp4, the |
| 4903 | /// playing time for a song. |
| 4904 | pub fn file_frames(&self, path: &Path) -> u32 { |
| 4905 | self.source_of(path).map_or(0, |i| self.counts[i]) |
| 4906 | } |
| 4907 | |
| 4908 | /// What rate the file at `path` was *shot* at, in frames per second -- which |
| 4909 | /// is the timeline's own rate for every source that shares it, and is not |
| 4910 | /// for one placed at another ([`Rate`]). By path like |
| 4911 | /// [`file_frames`](Self::file_frames), and the timeline's rate for a file |
| 4912 | /// this session has never taken in (and for a still and a song, which were |
| 4913 | /// shot at no rate at all). |
| 4914 | /// |
| 4915 | /// What a library row names the file with: the timeline's rate there would |
| 4916 | /// be a lie about a 23.976 fps file the moment one can join. |
| 4917 | pub fn file_fps(&self, path: &Path) -> f64 { |
| 4918 | self.file_rate(path).as_f64() * self.meta.frame_rate |
| 4919 | } |
| 4920 | |
| 4921 | /// The clip the picture is coming from at `timeline_secs`: the lane it sits |
| 4922 | /// on and its index there, by the same topmost-lane-wins rule the decoder |
| 4923 | /// follows. `None` over a gap and past the end. What a card that grades |
| 4924 | /// "this clip" opens on when nothing has been clicked. |
| 4925 | pub fn video_clip_at(&self, timeline_secs: f64) -> Option<(Lane, usize)> { |
| 4926 | self.project |
| 4927 | .composite_clip_at(secs_to_frame(timeline_secs, self.meta.frame_rate)) |
| 4928 | } |
| 4929 | |
| 4930 | /// Which clip of `lane` sits at `timeline_secs`, by the same rule |
| 4931 | /// [`video_clip_at`](Self::video_clip_at) picks the picture's with -- per |
| 4932 | /// lane, so a keyboard walking the lanes for something to select asks the |
| 4933 | /// engine rather than re-deriving where a clip ends. |
| 4934 | pub fn lane_clip_at(&self, lane: Lane, timeline_secs: f64) -> Option<usize> { |
| 4935 | self.project |
| 4936 | .lane_clip_at(lane, secs_to_frame(timeline_secs, self.meta.frame_rate)) |
| 4937 | } |
| 4938 | |
| 4939 | /// How the clip at `idx` of `lane` is graded, or `None` for one that plays |
| 4940 | /// as it was shot -- what a colour card reads when it opens. |
| 4941 | pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> { |
| 4942 | self.project.color_of(lane, idx) |
| 4943 | } |
| 4944 | |
| 4945 | /// Grades that clip, or takes the grade off with `None`. One undo step like |
| 4946 | /// every other edit, and it reseeks like one too -- which is what puts the |
| 4947 | /// new grade on the frame that is already on screen, paused or playing, |
| 4948 | /// without the caller having to nudge the playhead itself. `false` for an |
| 4949 | /// index that is not there and for a value that is not finite. |
| 4950 | pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool { |
| 4951 | self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params)) |
| 4952 | } |
| 4953 | |
| 4954 | /// The same grade and the same reseek without the undo step |
| 4955 | /// ([`Project::set_color_live`]): what the samples inside one slider drag go |
| 4956 | /// through, so the frame regrades under the hand and the whole gesture is |
| 4957 | /// still a single `z`. |
| 4958 | pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool { |
| 4959 | self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params)) |
| 4960 | } |
| 4961 | |
| 4962 | /// [`Project::lut_problems`]: the `.cube` files clips name that cannot be used, and why. |
| 4963 | pub fn lut_problems(&self) -> Vec<(PathBuf, String)> { |
| 4964 | self.project.lut_problems() |
| 4965 | } |
| 4966 | |
| 4967 | /// [`Project::luts`]: every `.cube` file a clip's grade names. |
| 4968 | pub fn luts(&self) -> Vec<crate::cube::LutRef> { |
| 4969 | self.project.luts() |
| 4970 | } |
| 4971 | |
| 4972 | /// [`Project::relink_lut`], with the reseek every picture edit makes. |
| 4973 | pub fn relink_lut(&mut self, from: &std::path::Path, to: &std::path::Path) -> usize { |
| 4974 | let mut n = 0; |
| 4975 | self.edit(Dirty::Picture, |p| { |
| 4976 | n = p.relink_lut(from, to); |
| 4977 | n > 0 |
| 4978 | }); |
| 4979 | n |
| 4980 | } |
| 4981 | |
| 4982 | /// Where the clip at `idx` of `lane` is placed -- [`color_of`](Self::color_of)'s |
| 4983 | /// twin for geometry instead of grade. |
| 4984 | pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> { |
| 4985 | self.project.transform_of(lane, idx) |
| 4986 | } |
| 4987 | |
| 4988 | /// Moves/scales/rotates/crops that clip, or takes the placement off with |
| 4989 | /// `None` -- [`set_color`](Self::set_color)'s twin, one undo step and one |
| 4990 | /// reseek. |
| 4991 | pub fn set_transform( |
| 4992 | &mut self, |
| 4993 | lane: Lane, |
| 4994 | idx: usize, |
| 4995 | params: Option<TransformParams>, |
| 4996 | ) -> bool { |
| 4997 | self.edit(Dirty::Picture, |p| p.set_transform(lane, idx, params)) |
| 4998 | } |
| 4999 | |
| 5000 | /// The placement animation of the clip at `idx` of `lane`, in source order |
| 5001 | /// ([`Project::transform_keys_of`]). |
| 5002 | pub fn transform_keys_of(&self, lane: Lane, idx: usize) -> &[crate::transform::TransformKey] { |
| 5003 | self.project.transform_keys_of(lane, idx) |
| 5004 | } |
| 5005 | |
| 5006 | /// Replaces the clip's placement animation, or clears it with an empty list |
| 5007 | /// ([`Project::set_transform_keys`]). One undo step and one reseek. |
| 5008 | pub fn set_transform_keys( |
| 5009 | &mut self, |
| 5010 | lane: Lane, |
| 5011 | idx: usize, |
| 5012 | keys: Vec<crate::transform::TransformKey>, |
| 5013 | ) -> bool { |
| 5014 | self.edit(Dirty::Picture, |p| p.set_transform_keys(lane, idx, keys)) |
| 5015 | } |
| 5016 | |
| 5017 | /// The opacity animation of the clip at `idx` of `lane`, in source order |
| 5018 | /// ([`Project::opacity_keys_of`]). |
| 5019 | pub fn opacity_keys_of(&self, lane: Lane, idx: usize) -> &[crate::transform::OpacityKey] { |
| 5020 | self.project.opacity_keys_of(lane, idx) |
| 5021 | } |
| 5022 | |
| 5023 | /// Replaces the clip's opacity animation, or clears it with an empty list |
| 5024 | /// ([`Project::set_opacity_keys`]). One undo step and one reseek. |
| 5025 | pub fn set_opacity_keys( |
| 5026 | &mut self, |
| 5027 | lane: Lane, |
| 5028 | idx: usize, |
| 5029 | keys: Vec<crate::transform::OpacityKey>, |
| 5030 | ) -> bool { |
| 5031 | self.edit(Dirty::Picture, |p| p.set_opacity_keys(lane, idx, keys)) |
| 5032 | } |
| 5033 | |
| 5034 | /// The colour animation of the clip at `idx` of `lane`, in source order |
| 5035 | /// ([`Project::color_keys_of`]). |
| 5036 | pub fn color_keys_of(&self, lane: Lane, idx: usize) -> &[crate::color::ColorKey] { |
| 5037 | self.project.color_keys_of(lane, idx) |
| 5038 | } |
| 5039 | |
| 5040 | /// Replaces the clip's colour animation, or clears it with an empty list |
| 5041 | /// ([`Project::set_color_keys`]). One undo step and one reseek. |
| 5042 | pub fn set_color_keys( |
| 5043 | &mut self, |
| 5044 | lane: Lane, |
| 5045 | idx: usize, |
| 5046 | keys: Vec<crate::color::ColorKey>, |
| 5047 | ) -> bool { |
| 5048 | self.edit(Dirty::Picture, |p| p.set_color_keys(lane, idx, keys)) |
| 5049 | } |
| 5050 | |
| 5051 | /// The effects stack of the clip at `idx` of `lane` ([`Project::effects_of`]). |
| 5052 | pub fn effects_of(&self, lane: Lane, idx: usize) -> &[crate::effects::Effect] { |
| 5053 | self.project.effects_of(lane, idx) |
| 5054 | } |
| 5055 | |
| 5056 | /// The keys of the effect at stack position `slot` ([`Project::effect_keys_of`]). |
| 5057 | pub fn effect_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::EffectKey] { |
| 5058 | self.project.effect_keys_of(lane, idx, slot) |
| 5059 | } |
| 5060 | |
| 5061 | /// Replaces the keys of the effect at stack position `slot`, or clears them with an |
| 5062 | /// empty list ([`Project::set_effect_keys`]). One undo step and one reseek. |
| 5063 | pub fn set_effect_keys(&mut self, lane: Lane, idx: usize, slot: usize, keys: Vec<crate::effects::EffectKey>) -> bool { |
| 5064 | self.edit(Dirty::Picture, |p| p.set_effect_keys(lane, idx, slot, keys)) |
| 5065 | } |
| 5066 | |
| 5067 | /// Replaces the clip's effects stack ([`Project::set_effects`]). One undo |
| 5068 | /// step and one reseek. |
| 5069 | pub fn set_effects(&mut self, lane: Lane, idx: usize, effects: Vec<crate::effects::Effect>) -> bool { |
| 5070 | self.edit(Dirty::Picture, |p| p.set_effects(lane, idx, effects)) |
| 5071 | } |
| 5072 | |
| 5073 | /// [`Project::key_source_frame`]. |
| 5074 | pub fn key_source_frame(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<u32> { |
| 5075 | self.project.key_source_frame(lane, idx, timeline_frame) |
| 5076 | } |
| 5077 | |
| 5078 | /// [`Project::is_keyed`]. |
| 5079 | pub fn is_keyed(&self, lane: Lane, idx: usize, kind: crate::project::KeyKind) -> bool { |
| 5080 | self.project.is_keyed(lane, idx, kind) |
| 5081 | } |
| 5082 | |
| 5083 | /// [`Project::key_ease_at`]. |
| 5084 | pub fn key_ease_at( |
| 5085 | &self, |
| 5086 | lane: Lane, |
| 5087 | idx: usize, |
| 5088 | kind: crate::project::KeyKind, |
| 5089 | timeline_frame: u32, |
| 5090 | ) -> Option<crate::transform::KeyEase> { |
| 5091 | self.project.key_ease_at(lane, idx, kind, timeline_frame) |
| 5092 | } |
| 5093 | |
| 5094 | /// The stopwatch ([`Project::toggle_key`]). One undo step and one reseek. |
| 5095 | pub fn toggle_key( |
| 5096 | &mut self, |
| 5097 | lane: Lane, |
| 5098 | idx: usize, |
| 5099 | kind: crate::project::KeyKind, |
| 5100 | timeline_frame: u32, |
| 5101 | ) -> Option<bool> { |
| 5102 | let mut out = None; |
| 5103 | self.edit(Dirty::Picture, |p| { |
| 5104 | out = p.toggle_key(lane, idx, kind, timeline_frame); |
| 5105 | out.is_some() |
| 5106 | }); |
| 5107 | out |
| 5108 | } |
| 5109 | |
| 5110 | /// [`Project::set_key_ease_at`]. One undo step and one reseek. |
| 5111 | pub fn set_key_ease_at( |
| 5112 | &mut self, |
| 5113 | lane: Lane, |
| 5114 | idx: usize, |
| 5115 | kind: crate::project::KeyKind, |
| 5116 | timeline_frame: u32, |
| 5117 | ease: crate::transform::KeyEase, |
| 5118 | ) -> bool { |
| 5119 | self.edit(Dirty::Picture, |p| p.set_key_ease_at(lane, idx, kind, timeline_frame, ease)) |
| 5120 | } |
| 5121 | |
| 5122 | /// [`Project::put_transform_key_at`]; `snapshot` false is the live write of a drag. |
| 5123 | pub fn put_transform_key_at( |
| 5124 | &mut self, |
| 5125 | lane: Lane, |
| 5126 | idx: usize, |
| 5127 | timeline_frame: u32, |
| 5128 | params: TransformParams, |
| 5129 | snapshot: bool, |
| 5130 | ) -> bool { |
| 5131 | self.edit(Dirty::Picture, |p| p.put_transform_key_at(lane, idx, timeline_frame, params, snapshot)) |
| 5132 | } |
| 5133 | |
| 5134 | /// [`Project::put_opacity_key_at`]; `snapshot` false is the live write of a drag. |
| 5135 | pub fn put_opacity_key_at( |
| 5136 | &mut self, |
| 5137 | lane: Lane, |
| 5138 | idx: usize, |
| 5139 | timeline_frame: u32, |
| 5140 | opacity: f32, |
| 5141 | snapshot: bool, |
| 5142 | ) -> bool { |
| 5143 | self.edit(Dirty::Picture, |p| p.put_opacity_key_at(lane, idx, timeline_frame, opacity, snapshot)) |
| 5144 | } |
| 5145 | |
| 5146 | /// [`Project::put_color_key_at`]; `snapshot` false is the live write of a drag. |
| 5147 | pub fn put_color_key_at( |
| 5148 | &mut self, |
| 5149 | lane: Lane, |
| 5150 | idx: usize, |
| 5151 | timeline_frame: u32, |
| 5152 | params: ColorParams, |
| 5153 | snapshot: bool, |
| 5154 | ) -> bool { |
| 5155 | self.edit(Dirty::Picture, |p| p.put_color_key_at(lane, idx, timeline_frame, params, snapshot)) |
| 5156 | } |
| 5157 | |
| 5158 | /// The placement the clip shows at timeline `timeline_frame`, keys evaluated |
| 5159 | /// ([`Project::transform_at`]). |
| 5160 | pub fn transform_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<TransformParams> { |
| 5161 | self.project.transform_at(lane, idx, timeline_frame) |
| 5162 | } |
| 5163 | |
| 5164 | /// The grade the clip shows at `timeline_frame`, keys evaluated ([`Project::color_at`]). |
| 5165 | pub fn color_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<ColorParams> { |
| 5166 | self.project.color_at(lane, idx, timeline_frame) |
| 5167 | } |
| 5168 | |
| 5169 | /// The opacity the clip shows at `timeline_frame`, keys evaluated, fades not |
| 5170 | /// counted ([`Project::opacity_at`]). |
| 5171 | pub fn opacity_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> f32 { |
| 5172 | self.project.opacity_at(lane, idx, timeline_frame) |
| 5173 | } |
| 5174 | |
| 5175 | /// The same placement and the same reseek without the undo step |
| 5176 | /// ([`Project::set_transform_live`]) -- [`set_color_live`](Self::set_color_live)'s |
| 5177 | /// twin for a slider drag. |
| 5178 | pub fn set_transform_live( |
| 5179 | &mut self, |
| 5180 | lane: Lane, |
| 5181 | idx: usize, |
| 5182 | params: Option<TransformParams>, |
| 5183 | ) -> bool { |
| 5184 | self.edit(Dirty::Picture, |p| p.set_transform_live(lane, idx, params)) |
| 5185 | } |
| 5186 | |
| 5187 | /// The project's resolution: what every clip is composed onto, what the |
| 5188 | /// window is sized to and what an export writes -- *not* any one file's. |
| 5189 | /// It starts as source 0's picture, which is what a project meant before it |
| 5190 | /// could have a resolution of its own. |
| 5191 | pub fn resolution(&self) -> (u32, u32) { |
| 5192 | (self.meta.width, self.meta.height) |
| 5193 | } |
| 5194 | |
| 5195 | /// Source 0's own picture size -- what the project resolution started as, |
| 5196 | /// and the one size a caller offering a list of them must not leave out. |
| 5197 | pub fn native_resolution(&self) -> (u32, u32) { |
| 5198 | self.native |
| 5199 | } |
| 5200 | |
| 5201 | /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on |
| 5202 | /// screen is recomposed at the new size at once, paused or playing -- and |
| 5203 | /// the sound is not touched at all: the size of the canvas is not something |
| 5204 | /// a sample can carry, so resizing a 4K film mid-play costs neither a hole |
| 5205 | /// in the audio nor an offset against it ([`Dirty`]). `false` for a size |
| 5206 | /// that is not a picture -- zero either way, or past 8K, which is where the |
| 5207 | /// per-frame buffers stop being a sane thing to allocate from a keystroke. |
| 5208 | /// |
| 5209 | /// One undo step: the resolution is the project's own, so it rides in the |
| 5210 | /// entry beside the lanes and a `z` takes the canvas back to the size it |
| 5211 | /// was ([`Project::push_settings_step`]). |
| 5212 | pub fn set_resolution(&mut self, width: u32, height: u32) -> bool { |
| 5213 | if !crate::is_resolution(width, height) { |
| 5214 | return false; |
| 5215 | } |
| 5216 | if (width, height) == (self.meta.width, self.meta.height) { |
| 5217 | return false; |
| 5218 | } |
| 5219 | let from = self.settings_value(); |
| 5220 | self.meta.width = width; |
| 5221 | self.meta.height = height; |
| 5222 | self.step_settings(from); |
| 5223 | self.invalidate(Dirty::Picture); |
| 5224 | true |
| 5225 | } |
| 5226 | |
| 5227 | /// Which HDR-to-SDR rendition this project is watched and exported in |
| 5228 | /// ([`crate::tonemap::Preset`]) -- the reference one until somebody picks |
| 5229 | /// another, and a setting on the project rather than on any clip. |
| 5230 | pub fn tone(&self) -> crate::tonemap::Preset { |
| 5231 | self.project.tone() |
| 5232 | } |
| 5233 | |
| 5234 | /// The project's notes ([`Project::notes`]). |
| 5235 | pub fn notes(&self) -> &str { |
| 5236 | self.project.notes() |
| 5237 | } |
| 5238 | |
| 5239 | /// Sets the project's notes ([`Project::set_notes`]): one undo step, `false` for the text |
| 5240 | /// already in force. |
| 5241 | pub fn set_notes(&mut self, notes: &str) -> bool { |
| 5242 | self.project.set_notes(notes) |
| 5243 | } |
| 5244 | |
| 5245 | /// How long a still is placed for, in seconds ([`Project::still_secs`]). |
| 5246 | pub fn still_secs(&self) -> f64 { |
| 5247 | self.project.still_secs() |
| 5248 | } |
| 5249 | |
| 5250 | /// Sets the still length ([`Project::set_still_secs`]): one undo step, `false` for the length |
| 5251 | /// already in force. Stills placed after this take it; clips already on the timeline keep theirs. |
| 5252 | pub fn set_still_secs(&mut self, secs: f64) -> bool { |
| 5253 | self.project.set_still_secs(secs) |
| 5254 | } |
| 5255 | |
| 5256 | /// The speech model the project names, or `None` for the one picked ([`Project::speech_model`]). |
| 5257 | pub fn speech_model(&self) -> Option<&str> { |
| 5258 | self.project.speech_model() |
| 5259 | } |
| 5260 | |
| 5261 | /// Sets it ([`Project::set_speech_model`]). |
| 5262 | pub fn set_speech_model(&mut self, model: Option<&str>) -> bool { |
| 5263 | self.project.set_speech_model(model) |
| 5264 | } |
| 5265 | |
| 5266 | /// The device the speech model runs on ([`Project::speech_device`]). |
| 5267 | pub fn speech_device(&self) -> crate::speech::DeviceChoice { |
| 5268 | self.project.speech_device() |
| 5269 | } |
| 5270 | |
| 5271 | /// Sets it ([`Project::set_speech_device`]). |
| 5272 | pub fn set_speech_device(&mut self, device: crate::speech::DeviceChoice) -> bool { |
| 5273 | self.project.set_speech_device(device) |
| 5274 | } |
| 5275 | |
| 5276 | /// What source 0's own file declared about how bright it gets |
| 5277 | /// ([`ContentLight`]): a property of the film, read once at open, and |
| 5278 | /// entirely absent (every field `None`) for an SDR file, a song or a |
| 5279 | /// still. Read-only -- the number a file carries, never a project setting |
| 5280 | /// a user can override, since nothing in [`Project`] holds one to persist. |
| 5281 | pub fn content_light(&self) -> ContentLight { |
| 5282 | self.content_light |
| 5283 | } |
| 5284 | |
| 5285 | /// Picks one. Rebuilds the **picture** where the playhead is, exactly as |
| 5286 | /// [`set_resolution`](Self::set_resolution) does -- the frame on screen is |
| 5287 | /// remapped at once, paused or playing, and the sound is not touched: a |
| 5288 | /// rendition is not something a sample can carry. `false` for the rendition |
| 5289 | /// already in force. |
| 5290 | /// |
| 5291 | /// An SDR project is unmoved by this by construction: no clip of it builds a |
| 5292 | /// tone map at all ([`crate::tonemap`]), so the reseek recomposes the very |
| 5293 | /// same bytes. |
| 5294 | /// |
| 5295 | /// corner-cut: not an undo step, for the reason the resolution is not |
| 5296 | /// ([`Project::set_tone`]). |
| 5297 | pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool { |
| 5298 | if !self.project.set_tone(preset) { |
| 5299 | return false; |
| 5300 | } |
| 5301 | self.invalidate(Dirty::Picture); |
| 5302 | true |
| 5303 | } |
| 5304 | |
| 5305 | /// The scaffolding source's own frame rate -- what the project rate started |
| 5306 | /// as, and the one rate a caller offering a list of them must not leave out |
| 5307 | /// ([`native_resolution`](Self::native_resolution)'s reason). |
| 5308 | pub fn native_frame_rate(&self) -> f64 { |
| 5309 | self.native_fps |
| 5310 | } |
| 5311 | |
| 5312 | /// Cuts this timeline at `fps` from here on: every clip is *conformed* to |
| 5313 | /// the new rate ([`Project::retime`]), every source is read through a |
| 5314 | /// [`Rate`] against it, and an export written from this session comes out at |
| 5315 | /// it. The edit survives as the same seconds of the same footage on a finer |
| 5316 | /// or coarser grid -- a 30 fps take on a timeline moved to 24 keeps its |
| 5317 | /// length and its sync, it is simply counted in 24ths now. |
| 5318 | /// |
| 5319 | /// Reseeks like [`set_resolution`](Self::set_resolution), so the picture and |
| 5320 | /// the sound under the playhead are already the new rate's when this |
| 5321 | /// returns. `false` -- changing nothing -- for a rate that is not a rate, for |
| 5322 | /// the one already in force, and for one no timescale can name |
| 5323 | /// ([`crate::mux::frame_timing`], the same wall a file of an unnameable rate |
| 5324 | /// is refused at). |
| 5325 | /// |
| 5326 | /// One undo step, and the entry it takes is the whole of the change: the |
| 5327 | /// lanes as they were in the *old* rate's numbering, with that rate beside |
| 5328 | /// them, so a `z` restores the two together ([`Project::retime`]). The |
| 5329 | /// step is taken before the retime rather than after, since this is the one |
| 5330 | /// settings door that moves the lanes the step holds. Picking the old rate |
| 5331 | /// back is still within a frame of where it started rather than on it: the |
| 5332 | /// *lanes* come home exactly out of the entry, and the per-source lengths |
| 5333 | /// are the half that goes through the map twice |
| 5334 | /// ([`PlaybackSession::adopt_settings`]). |
| 5335 | pub fn set_frame_rate(&mut self, fps: f64) -> bool { |
| 5336 | if !fps.is_finite() || fps <= 0.0 || fps == self.meta.frame_rate || self.project.rate_locked() { |
| 5337 | return false; |
| 5338 | } |
| 5339 | // Old timeline frames per new one, exactly -- the one map every frame |
| 5340 | // number on every lane goes through. Built before anything is touched, |
| 5341 | // since a rate no timescale can name is a refusal and not a half-retimed |
| 5342 | // project. |
| 5343 | let Ok(k) = Rate::from_fps(self.meta.frame_rate, fps) else { |
| 5344 | return false; |
| 5345 | }; |
| 5346 | let from = self.settings_value(); |
| 5347 | self.project.push_settings_step(from.clone(), from); |
| 5348 | // Lengths first: the retime holds every clip inside its source's *new* |
| 5349 | // length, so a clip that played to the last frame of its file still |
| 5350 | // does rather than naming one past the end. |
| 5351 | for count in &mut self.counts { |
| 5352 | *count = k.timeline_nearest(*count).max(1); |
| 5353 | } |
| 5354 | self.project.retime(k, &self.counts); |
| 5355 | // A file's own rate has not changed; what it is *against* has. |
| 5356 | for rate in &mut self.rates { |
| 5357 | *rate = rate.then(k); |
| 5358 | } |
| 5359 | self.meta.frame_rate = fps; |
| 5360 | self.meta.frame_count = k.timeline_nearest(self.meta.frame_count).max(1); |
| 5361 | // The copy the project keeps, now that the change has landed: what the |
| 5362 | // next lane edit's entry carries. |
| 5363 | self.project.mirror_settings(self.settings_value()); |
| 5364 | let now = self.now(); |
| 5365 | self.seek(now); |
| 5366 | true |
| 5367 | } |
| 5368 | |
| 5369 | /// How the clip at `idx` of `lane` meets a project canvas of another shape. |
| 5370 | pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy { |
| 5371 | self.project.fit_of(lane, idx) |
| 5372 | } |
| 5373 | |
| 5374 | /// Sets that clip's fit policy. One undo step and a reseek, exactly like a |
| 5375 | /// grade: the picture on screen is recomposed through the new policy without |
| 5376 | /// the caller nudging the playhead. `false` for an index that is not there. |
| 5377 | pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool { |
| 5378 | self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit)) |
| 5379 | } |
| 5380 | |
| 5381 | /// [`Project::set_stabilise`]. Reseeks like a grade. The analysis it needs is |
| 5382 | /// started in the background ([`Self::stabilise_start`]); until it is done the |
| 5383 | /// clip plays as it is. |
| 5384 | pub fn set_stabilise(&mut self, lane: Lane, idx: usize, st: Option<crate::stabilise::Stabilise>) -> bool { |
| 5385 | let done = self.edit(Dirty::Picture, |p| p.set_stabilise(lane, idx, st)); |
| 5386 | if done && st.is_some() { |
| 5387 | self.stabilise_start(lane, idx); |
| 5388 | } |
| 5389 | done |
| 5390 | } |
| 5391 | |
| 5392 | /// The generator of kind `name` ([`crate::generate::KINDS`]) at its defaults, drawn for this |
| 5393 | /// timeline's canvas and rate. |
| 5394 | pub fn generator_named(&self, name: &str) -> Option<crate::generate::Gen> { |
| 5395 | crate::generate::Gen::named(name, self.meta.width, self.meta.height, self.meta.frame_rate) |
| 5396 | } |
| 5397 | |
| 5398 | /// Places a generated clip ([`crate::generate`]) `secs` long on the video lane `onto` (`V1` |
| 5399 | /// when none), at `timeline_secs`, like a still. A countdown with no length asked for runs |
| 5400 | /// its own count. Overwrites what the stretch lands on, as a still does. `false` when the |
| 5401 | /// lane or the place is refused. |
| 5402 | pub fn place_generated(&mut self, spec: crate::generate::Gen, timeline_secs: f64, secs: Option<f64>, onto: Option<Lane>) -> crate::Result<bool> { |
| 5403 | let fps = self.meta.frame_rate; |
| 5404 | let source = self.generator_source(spec); |
| 5405 | let secs = secs.unwrap_or(match spec.kind { |
| 5406 | crate::generate::Kind::Countdown { from, .. } => f64::from(from), |
| 5407 | _ => self.project.still_secs(), |
| 5408 | }); |
| 5409 | let wall = self.counts[source]; |
| 5410 | let out = ((secs * fps).round() as u32).clamp(1, wall.max(1)); |
| 5411 | let lane = match onto { |
| 5412 | Some(lane) if lane.kind == LaneKind::Video => lane, |
| 5413 | Some(_) => return Err("a generated clip goes on a video lane".into()), |
| 5414 | None => Lane::V1, |
| 5415 | }; |
| 5416 | if self.project.lane(lane).is_empty() && !self.project.lanes().contains(&lane) { |
| 5417 | return Err(format!("{lane:?} is not a lane of this timeline").into()); |
| 5418 | } |
| 5419 | Ok(self.place_at(lane, timeline_secs, Clip::source_range(source, 0, out))) |
| 5420 | } |
| 5421 | |
| 5422 | /// Places a test tone ([`crate::generate::Tone`]) `secs` long on the audio lane `onto` (`A1` |
| 5423 | /// when none), at `timeline_secs`, as a sound file's stream is placed. The tone's file is made |
| 5424 | /// in `dir` the first time (the project's folder for a saved project, else the data folder). |
| 5425 | /// `false` when the place is refused. |
| 5426 | pub fn place_tone(&mut self, tone: crate::generate::Tone, timeline_secs: f64, secs: u32, onto: Option<Lane>, dir: &std::path::Path) -> crate::Result<bool> { |
| 5427 | let path = tone.write(dir, secs)?; |
| 5428 | let lane = match onto { |
| 5429 | Some(lane) if lane.kind == LaneKind::Audio => lane, |
| 5430 | Some(_) => return Err("a tone goes on an audio lane".into()), |
| 5431 | None => Lane::A1, |
| 5432 | }; |
| 5433 | // A tone is a standalone audio file: taken into the library the first time it is |
| 5434 | // placed (as a song is), so the placement below finds it. |
| 5435 | if self.file_frames(&path) == 0 { |
| 5436 | self.import(&path)?; |
| 5437 | } |
| 5438 | self.place_stream_at(timeline_secs, &path, 0, Some(lane)) |
| 5439 | } |
| 5440 | |
| 5441 | /// The source index of `spec`, taken into the library the first time it is used. |
| 5442 | fn generator_source(&mut self, spec: crate::generate::Gen) -> usize { |
| 5443 | let source = self.project.import(spec.path(), 0); |
| 5444 | self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME); |
| 5445 | source |
| 5446 | } |
| 5447 | |
| 5448 | /// Changes the generator the clip at `idx` of `lane` is, keeping its place and length. |
| 5449 | /// One undo step; `false` for a clip that is not there or no change. |
| 5450 | pub fn set_generator(&mut self, lane: Lane, idx: usize, spec: crate::generate::Gen) -> bool { |
| 5451 | let source = self.generator_source(spec); |
| 5452 | self.edit(Dirty::Picture, |p| p.set_clip_source(lane, idx, source)) |
| 5453 | } |
| 5454 | |
| 5455 | /// The generator the clip at `idx` of `lane` is, `None` for a clip made from a file. |
| 5456 | pub fn generator_of(&self, lane: Lane, idx: usize) -> Option<crate::generate::Gen> { |
| 5457 | let src = self.project.sources().get(self.project.lane(lane).get(idx)?.source)?; |
| 5458 | crate::generate::Gen::parse(&src.path) |
| 5459 | } |
| 5460 | |
| 5461 | /// [`Project::set_label`]. |
| 5462 | pub fn set_label(&mut self, lane: Lane, idx: usize, label: u8) -> bool { |
| 5463 | self.project.set_label(lane, idx, label) |
| 5464 | } |
| 5465 | |
| 5466 | /// [`Project::set_enabled`]: a switched-off clip is skipped by picture and sound. |
| 5467 | pub fn set_enabled(&mut self, lane: Lane, idx: usize, enabled: bool) -> bool { |
| 5468 | self.edit(Dirty::Both, |p| p.set_enabled(lane, idx, enabled)) |
| 5469 | } |
| 5470 | |
| 5471 | /// [`Project::mark_of`]. |
| 5472 | pub fn mark_of(&self, lane: Lane, idx: usize) -> crate::project::ClipMark { |
| 5473 | self.project.mark_of(lane, idx) |
| 5474 | } |
| 5475 | |
| 5476 | /// [`Project::set_deinterlace`]. Stored only; the render reads it once the engine acts on it. |
| 5477 | pub fn set_deinterlace(&mut self, lane: Lane, idx: usize, mode: crate::project::Deinterlace) -> bool { |
| 5478 | self.project.set_deinterlace(lane, idx, mode) |
| 5479 | } |
| 5480 | |
| 5481 | /// [`Project::deinterlace_of`]. |
| 5482 | pub fn deinterlace_of(&self, lane: Lane, idx: usize) -> crate::project::Deinterlace { |
| 5483 | self.project.deinterlace_of(lane, idx) |
| 5484 | } |
| 5485 | |
| 5486 | /// [`Project::stabilise_of`]. |
| 5487 | pub fn stabilise_of(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Stabilise> { |
| 5488 | self.project.stabilise_of(lane, idx) |
| 5489 | } |
| 5490 | |
| 5491 | /// The source and file-frame range the clip at `idx` of `lane` is analysed |
| 5492 | /// over, `None` for no clip or one that is not footage (a still, a song). |
| 5493 | pub fn stabilise_range(&self, lane: Lane, idx: usize) -> Option<(std::path::PathBuf, u32, u32)> { |
| 5494 | let c = self.project.lane(lane).get(idx)?; |
| 5495 | let path = &self.project.sources().get(c.source)?.path; |
| 5496 | if crate::is_image(path) || crate::is_audio(path) { |
| 5497 | return None; |
| 5498 | } |
| 5499 | let (lo, hi) = crate::stabilise::clip_range(path, c, self.meta.frame_rate); |
| 5500 | Some((path.clone(), lo, hi)) |
| 5501 | } |
| 5502 | |
| 5503 | /// Where the clip's stabilisation analysis stands ([`crate::stabilise::status`]). |
| 5504 | pub fn stabilise_status(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Status> { |
| 5505 | let (path, lo, hi) = self.stabilise_range(lane, idx)?; |
| 5506 | Some(crate::stabilise::status(&path, lo, hi)) |
| 5507 | } |
| 5508 | |
| 5509 | /// Starts the clip's stabilisation analysis in the background unless it is |
| 5510 | /// cached or running ([`crate::stabilise::start`]). |
| 5511 | pub fn stabilise_start(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Status> { |
| 5512 | let (path, lo, hi) = self.stabilise_range(lane, idx)?; |
| 5513 | Some(crate::stabilise::start(&path, lo, hi)) |
| 5514 | } |
| 5515 | |
| 5516 | /// Stops the clip's running analysis. `false` when none runs. |
| 5517 | pub fn stabilise_cancel(&self, lane: Lane, idx: usize) -> bool { |
| 5518 | self.stabilise_range(lane, idx).is_some_and(|(path, lo, hi)| crate::stabilise::cancel(&path, lo, hi)) |
| 5519 | } |
| 5520 | |
| 5521 | /// What auto reframe needs of the clip at `idx` of `lane`: its file range and the |
| 5522 | /// geometry its keys are made for ([`crate::reframe`]). `None` for no clip, a |
| 5523 | /// still or a song. |
| 5524 | pub fn reframe_job(&self, lane: Lane, idx: usize) -> Option<crate::reframe::ReframeJob> { |
| 5525 | let (path, lo, hi) = self.stabilise_range(lane, idx)?; |
| 5526 | let c = self.project.lane(lane).get(idx)?; |
| 5527 | let shown = crate::demux::Demuxer::open(&path).ok()?.0; |
| 5528 | let target = crate::reframe::Target { |
| 5529 | src_w: shown.width, |
| 5530 | src_h: shown.height, |
| 5531 | canvas_w: self.meta.width, |
| 5532 | canvas_h: self.meta.height, |
| 5533 | base: self.project.transform_of(lane, idx).copied().unwrap_or_default(), |
| 5534 | in_frame: c.in_frame, |
| 5535 | out_frame: c.out_frame, |
| 5536 | }; |
| 5537 | Some(crate::reframe::ReframeJob { path, lo, hi, target }) |
| 5538 | } |
| 5539 | |
| 5540 | /// Writes reframe `keys` on the clip, and puts it on [`FitPolicy::Fit`] -- the |
| 5541 | /// placement they are made for. One undo step; `false` when the keys are refused. |
| 5542 | pub fn apply_reframe(&mut self, lane: Lane, idx: usize, keys: Vec<crate::transform::TransformKey>) -> bool { |
| 5543 | self.begin_batch(); |
| 5544 | self.set_fit(lane, idx, FitPolicy::Fit); |
| 5545 | let done = self.set_transform_keys(lane, idx, keys); |
| 5546 | self.end_batch(); |
| 5547 | done |
| 5548 | } |
| 5549 | |
| 5550 | /// Redraws the picture once an analysis finished, so a stabilised clip shows |
| 5551 | /// its correction without an edit. |
| 5552 | pub fn stabilise_refresh(&mut self) { |
| 5553 | self.invalidate(Dirty::Picture); |
| 5554 | } |
| 5555 | |
| 5556 | /// Starts following the rect or ellipse mask at stack position `slot` of the clip at |
| 5557 | /// `idx` of `lane` ([`crate::track`]) from source frame `from` to `to`, either order. |
| 5558 | /// The mask's centre at `from` is where the feature is; [`Self::track_mask_apply`] |
| 5559 | /// writes the path back once the track has finished. |
| 5560 | pub fn track_mask_start(&self, lane: Lane, idx: usize, slot: usize, from: u32, to: u32) -> Result<TrackJob, String> { |
| 5561 | use crate::effects::EffectKind; |
| 5562 | let c = self.project.lane(lane).get(idx).ok_or("there is no clip there")?; |
| 5563 | let e = c.effects.get(slot).ok_or("there is no effect in that stack position")?; |
| 5564 | if !matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask) { |
| 5565 | return Err("only a rect or ellipse mask can be tracked".into()); |
| 5566 | } |
| 5567 | let (path, lo, hi) = self.stabilise_range(lane, idx).ok_or("a still or a song has no picture to track")?; |
| 5568 | let (from, to) = (from.clamp(lo, hi - 1), to.clamp(lo, hi - 1)); |
| 5569 | if from == to { |
| 5570 | return Err("a track needs two frames: from and to are the same frame".into()); |
| 5571 | } |
| 5572 | let forward = to > from; |
| 5573 | let range = if forward { (from, to + 1) } else { (to, from + 1) }; |
| 5574 | let at = e.posed(f64::from(from)); |
| 5575 | let (x, y) = (at.values[0], at.values[1]); |
| 5576 | let region = crate::track::Region { x, y, w: at.values[2], h: at.values[3] }; |
| 5577 | // The placement the renderer gives the clip, so the track's points land on the canvas |
| 5578 | // where the mask is drawn: the base transform and its keys, on this canvas. |
| 5579 | let pose = crate::track::Pose { |
| 5580 | base: self.transform_of(lane, idx).copied().unwrap_or_default(), |
| 5581 | keys: self.transform_keys_of(lane, idx).to_vec(), |
| 5582 | canvas: self.resolution(), |
| 5583 | fit: crate::scale::FitPolicy::default(), |
| 5584 | }; |
| 5585 | let id = crate::track::start(&path, range, from, forward, region, pose); |
| 5586 | Ok(TrackJob { lane, idx, slot, id, from, anchor: (x, y) }) |
| 5587 | } |
| 5588 | |
| 5589 | /// Writes every finished track in `jobs` onto its mask ([`Self::track_mask_apply`]) and |
| 5590 | /// takes it out of `jobs`; running ones stay. Each landing is one undo step. Returns one |
| 5591 | /// entry per track that ended. |
| 5592 | pub fn track_settle(&mut self, jobs: &mut Vec<TrackJob>) -> Vec<TrackDone> { |
| 5593 | let mut done = Vec::new(); |
| 5594 | let mut running = Vec::new(); |
| 5595 | for job in std::mem::take(jobs) { |
| 5596 | let result = match crate::track::status(job.id) { |
| 5597 | crate::track::Status::Running(_) => { |
| 5598 | running.push(job); |
| 5599 | continue; |
| 5600 | } |
| 5601 | crate::track::Status::Gone => continue, |
| 5602 | crate::track::Status::Finished => match crate::track::take(job.id) { |
| 5603 | None => continue, |
| 5604 | Some(Err(e)) => Err(e), |
| 5605 | Some(Ok(t)) => self.track_mask_apply(&job, &t).map(|keys| { |
| 5606 | let frames = t.points.iter().map(|p| p.0); |
| 5607 | TrackOutcome { |
| 5608 | keys, |
| 5609 | from: frames.clone().min().unwrap_or(job.from), |
| 5610 | to: frames.max().unwrap_or(job.from), |
| 5611 | lost_at: t.lost_at, |
| 5612 | } |
| 5613 | }), |
| 5614 | }, |
| 5615 | }; |
| 5616 | done.push(TrackDone { lane: job.lane, idx: job.idx, slot: job.slot, result }); |
| 5617 | } |
| 5618 | *jobs = running; |
| 5619 | done |
| 5620 | } |
| 5621 | |
| 5622 | /// Writes a finished track onto its mask: the mask's centre moves by the feature's |
| 5623 | /// displacement from where it was at the start, and its size and soft edge keep the |
| 5624 | /// values they have at each frame. Keys inside the tracked frames are replaced and |
| 5625 | /// keys outside them stay. Returns how many keys were written. One undo step. |
| 5626 | pub fn track_mask_apply(&mut self, job: &TrackJob, track: &crate::track::Track) -> Result<usize, String> { |
| 5627 | use crate::effects::EffectKey; |
| 5628 | use crate::track::{KEY_TOLERANCE, simplify}; |
| 5629 | use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS}; |
| 5630 | let Some(&(_, x0, y0)) = track.points.first() else { |
| 5631 | return Err("the track has no points".into()); |
| 5632 | }; |
| 5633 | let mut pts: Vec<(u32, f32, f32)> = track |
| 5634 | .points |
| 5635 | .iter() |
| 5636 | .map(|&(f, x, y)| (f, job.anchor.0 + x - x0, job.anchor.1 + y - y0)) |
| 5637 | .collect(); |
| 5638 | pts.sort_by_key(|p| p.0); |
| 5639 | let (first, last) = (pts[0].0, pts[pts.len() - 1].0); |
| 5640 | let outside: Vec<EffectKey> = |
| 5641 | self.effect_keys_of(job.lane, job.idx, job.slot).iter().filter(|k| k.at < first || k.at > last).copied().collect(); |
| 5642 | let room = MAX_TRANSFORM_KEYS.saturating_sub(outside.len()).max(2); |
| 5643 | let mut tolerance = KEY_TOLERANCE; |
| 5644 | let mut kept = simplify(&pts, tolerance); |
| 5645 | while kept.len() > room { |
| 5646 | tolerance *= 2.0; |
| 5647 | kept = simplify(&pts, tolerance); |
| 5648 | } |
| 5649 | let mut keys = { |
| 5650 | let e = self |
| 5651 | .project |
| 5652 | .lane(job.lane) |
| 5653 | .get(job.idx) |
| 5654 | .and_then(|c| c.effects.get(job.slot)) |
| 5655 | .ok_or("the mask is gone")?; |
| 5656 | kept.iter() |
| 5657 | .map(|&i| { |
| 5658 | let (f, x, y) = pts[i]; |
| 5659 | let mut values = e.posed(f64::from(f)).values; |
| 5660 | values[0] = x; |
| 5661 | values[1] = y; |
| 5662 | EffectKey { at: f, values, ease: KeyEase::Linear } |
| 5663 | }) |
| 5664 | .collect::<Vec<_>>() |
| 5665 | }; |
| 5666 | keys.extend(outside); |
| 5667 | keys.sort_by_key(|k| k.at); |
| 5668 | let count = keys.len(); |
| 5669 | if !self.set_effect_keys(job.lane, job.idx, job.slot, keys) { |
| 5670 | return Err("the engine refused the keys (is the mask still there?)".into()); |
| 5671 | } |
| 5672 | Ok(count) |
| 5673 | } |
| 5674 | |
| 5675 | /// Waveform flags on a visualizer clip. Reseeks like a grade: the |
| 5676 | /// painter reads them on the next picture. |
| 5677 | pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool { |
| 5678 | self.edit(Dirty::Picture, |p| p.set_visualizer(lane, idx, flags)) |
| 5679 | } |
| 5680 | |
| 5681 | pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool { |
| 5682 | self.edit(Dirty::Picture, |p| p.set_viz_paint(lane, idx, paint)) |
| 5683 | } |
| 5684 | |
| 5685 | /// The same look and the same repaint without the undo step |
| 5686 | /// ([`Project::set_viz_paint_live`]): what the samples inside one drag |
| 5687 | /// across the colour wheel go through, so the picture follows the hand and |
| 5688 | /// the whole gesture is still a single `z`. |
| 5689 | pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool { |
| 5690 | self.edit(Dirty::Picture, |p| p.set_viz_paint_live(lane, idx, paint)) |
| 5691 | } |
| 5692 | |
| 5693 | /// Timeline frames of ramp-up from silence at the start of the clip at |
| 5694 | /// `idx` of `lane`. `0` for an index that is not there. |
| 5695 | pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 { |
| 5696 | self.project.fade_in_of(lane, idx) |
| 5697 | } |
| 5698 | |
| 5699 | /// The volume envelope of the clip at `idx` of `lane` |
| 5700 | /// ([`Project::gain_keys_of`]). |
| 5701 | pub fn gain_keys_of(&self, lane: Lane, idx: usize) -> &[GainKey] { |
| 5702 | self.project.gain_keys_of(lane, idx) |
| 5703 | } |
| 5704 | |
| 5705 | /// Replaces the clip's whole volume envelope ([`Project::set_gain_keys`]). |
| 5706 | /// A sound-only edit: no reseek of the picture. |
| 5707 | pub fn set_gain_keys(&mut self, lane: Lane, idx: usize, keys: Vec<GainKey>) -> bool { |
| 5708 | self.edit(Dirty::Sound, |p| p.set_gain_keys(lane, idx, keys)) |
| 5709 | } |
| 5710 | |
| 5711 | /// Puts one point into the clip's volume envelope ([`Project::add_gain_key`]). |
| 5712 | pub fn add_gain_key(&mut self, lane: Lane, idx: usize, key: GainKey) -> bool { |
| 5713 | self.edit(Dirty::Sound, |p| p.add_gain_key(lane, idx, key)) |
| 5714 | } |
| 5715 | |
| 5716 | /// Takes the point at source frame `at` out of the clip's volume envelope |
| 5717 | /// ([`Project::remove_gain_key`]). |
| 5718 | pub fn remove_gain_key(&mut self, lane: Lane, idx: usize, at: u32) -> bool { |
| 5719 | self.edit(Dirty::Sound, |p| p.remove_gain_key(lane, idx, at)) |
| 5720 | } |
| 5721 | |
| 5722 | /// The effective envelope dB at a timeline frame, keys and clip gain but not |
| 5723 | /// the fades ([`Project::gain_db_at`]). |
| 5724 | pub fn gain_db_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<f32> { |
| 5725 | self.project.gain_db_at(lane, idx, timeline_frame) |
| 5726 | } |
| 5727 | |
| 5728 | /// Sets that clip's fade-in, clamped to its own length. A sound-only |
| 5729 | /// edit, same as an equalizer or a fader: no reseek needed. |
| 5730 | pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { |
| 5731 | self.edit(Dirty::Sound, |p| p.set_fade_in(lane, idx, frames)) |
| 5732 | } |
| 5733 | |
| 5734 | /// Timeline frames of ramp-down to silence at the end of the clip at |
| 5735 | /// `idx` of `lane`. `0` for an index that is not there. |
| 5736 | pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 { |
| 5737 | self.project.fade_out_of(lane, idx) |
| 5738 | } |
| 5739 | |
| 5740 | /// Sets that clip's fade-out. Same promises as [`Self::set_fade_in`]. |
| 5741 | pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { |
| 5742 | self.edit(Dirty::Sound, |p| p.set_fade_out(lane, idx, frames)) |
| 5743 | } |
| 5744 | |
| 5745 | /// Crossfades the audio clip at `idx` of `lane` into its neighbour, over |
| 5746 | /// `frames`. Same promises as [`Project::crossfade`]. |
| 5747 | pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { |
| 5748 | self.edit(Dirty::Sound, |p| p.crossfade(lane, idx, frames)) |
| 5749 | } |
| 5750 | |
| 5751 | /// Timeline frames of dissolve at the end of the clip at `idx` of `lane`, |
| 5752 | /// into its neighbour. `0` for an index that is not there. |
| 5753 | pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 { |
| 5754 | self.project.transition_out_of(lane, idx) |
| 5755 | } |
| 5756 | |
| 5757 | /// The kind of the transition that clip plays into its neighbour. |
| 5758 | pub fn transition_kind_of(&self, lane: Lane, idx: usize) -> crate::transitions::TransitionKind { |
| 5759 | self.project.transition_kind_of(lane, idx) |
| 5760 | } |
| 5761 | |
| 5762 | /// Sets that clip's transition into its neighbour, kind and length in one |
| 5763 | /// undo step. A picture edit, like [`Self::set_transition_out`]. |
| 5764 | pub fn set_transition( |
| 5765 | &mut self, |
| 5766 | lane: Lane, |
| 5767 | idx: usize, |
| 5768 | kind: crate::transitions::TransitionKind, |
| 5769 | frames: u32, |
| 5770 | ) -> bool { |
| 5771 | self.edit(Dirty::Picture, |p| p.set_transition(lane, idx, kind, frames)) |
| 5772 | } |
| 5773 | |
| 5774 | /// Sets that clip's dissolve into its neighbour, clamped to its own |
| 5775 | /// length. A picture edit -- same as a grade or fit policy. |
| 5776 | pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool { |
| 5777 | self.edit(Dirty::Picture, |p| p.set_transition_out(lane, idx, frames)) |
| 5778 | } |
| 5779 | |
| 5780 | /// The clip at `idx` -- what a caller copies. It is a pair of source frame |
| 5781 | /// numbers and nothing else, so a copy stays valid after the clip it came |
| 5782 | /// from is deleted. `None` past the end. |
| 5783 | pub fn clip_at(&self, idx: usize) -> Option<Clip> { |
| 5784 | self.project.clips().get(idx).cloned() |
| 5785 | } |
| 5786 | |
| 5787 | /// Inserts `clip` at the playhead, splitting the clip under it. Like a |
| 5788 | /// delete this moves every following frame, so the session reseeks; past |
| 5789 | /// the end of the timeline the clip is appended. One undo step. |
| 5790 | pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool { |
| 5791 | // The clipboard's own rule, and only the clipboard's: a paste past the |
| 5792 | // end is an append, never a clip with black in front of it. The frame |
| 5793 | // itself is honoured in [`Project::paste`], because a *drop* names a |
| 5794 | // place on the bed and means it. |
| 5795 | let at = |
| 5796 | secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames()); |
| 5797 | let clip = self.held_to_take(clip); |
| 5798 | self.edit(Dirty::Both, |p| p.paste(at, clip)) |
| 5799 | } |
| 5800 | |
| 5801 | /// [`paste_at`](Self::paste_at)'s general form: [`Project::paste_set`]'s |
| 5802 | /// door, clamped to the timeline's own end the same way -- a set let go |
| 5803 | /// past the last frame lands there rather than carrying black in front of |
| 5804 | /// it, exactly as a lone clip's paste does. |
| 5805 | pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool { |
| 5806 | let at = |
| 5807 | secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames()); |
| 5808 | // Each item is held to its own lane's wall, as a lone placement is. |
| 5809 | let items: Vec<(Lane, Clip)> = items |
| 5810 | .iter() |
| 5811 | .map(|(lane, clip)| (*lane, self.held_to_lane(*lane, clip.clone()))) |
| 5812 | .collect(); |
| 5813 | self.edit(Dirty::Both, |p| p.paste_set(at, &items)) |
| 5814 | } |
| 5815 | |
| 5816 | /// Places the whole of `path` played on its audio `stream` at |
| 5817 | /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy -- |
| 5818 | /// the door a library row goes through, and the only way a stream other |
| 5819 | /// than the one an import brought in reaches the timeline. The `(file, |
| 5820 | /// stream)` pair becomes a source if it is not one already. |
| 5821 | /// |
| 5822 | /// Refused, changing nothing, unless that stream can join *this* timeline: |
| 5823 | /// same audio parameters as the first source, in the same words |
| 5824 | /// [`import`](Self::import) refuses a file with. One output device and one |
| 5825 | /// copied AAC track mean one *layout* for the whole timeline, so a mono |
| 5826 | /// track cannot join a stereo one. Its sample rate may be its own: the |
| 5827 | /// segment's resampler conforms it at the decoder's door. |
| 5828 | /// A front-end greys such a row out; this is the backstop that keeps a |
| 5829 | /// stale one from making the whole timeline silent. |
| 5830 | /// |
| 5831 | /// Which lane it lands on is decided here, from the file and from `onto` -- |
| 5832 | /// the lane it was let go over, if it was let go over one at all: a file |
| 5833 | /// with a picture asked for by no lane, or for one of the first pair, is |
| 5834 | /// pasted across `V1` and `A1` as a grouped take; asked for by a further |
| 5835 | /// *video* lane it is *placed* there with its sound on that lane's own audio |
| 5836 | /// row (`V2` -> `A2`, added if it is not there yet), overwriting what the two |
| 5837 | /// halves land on and rippling nothing; asked for by a further audio lane it |
| 5838 | /// is that file's sound alone. A file with no picture ([`crate::is_audio`]) is placed |
| 5839 | /// on the audio lane it was asked for, or on `A1`, and never on a video |
| 5840 | /// lane. A still image ([`crate::is_image`]) is its mirror: the video lane |
| 5841 | /// it was asked for or `V1`, never an audio one, and it goes down |
| 5842 | /// the project's still length ([`Project::still_secs`]) long rather than at the length it is |
| 5843 | /// *allowed* to be trimmed out to. A caller never has to ask. |
| 5844 | pub fn place_stream_at( |
| 5845 | &mut self, |
| 5846 | timeline_secs: f64, |
| 5847 | path: &Path, |
| 5848 | stream: usize, |
| 5849 | onto: Option<Lane>, |
| 5850 | ) -> crate::Result<bool> { |
| 5851 | self.place_stream_mode(timeline_secs, path, stream, onto, None) |
| 5852 | } |
| 5853 | |
| 5854 | /// [`place_stream_at`](Self::place_stream_at) as an **overwrite**: what the file lands on |
| 5855 | /// is replaced for its length and nothing is pushed along ([`SourceEdit::Overwrite`]). The |
| 5856 | /// lanes it lands on are chosen exactly as `place_stream_at` chooses them, and a refusal |
| 5857 | /// comes back with the engine's own words. |
| 5858 | pub fn place_stream_overwrite_at( |
| 5859 | &mut self, |
| 5860 | timeline_secs: f64, |
| 5861 | path: &Path, |
| 5862 | stream: usize, |
| 5863 | onto: Option<Lane>, |
| 5864 | ) -> crate::Result<bool> { |
| 5865 | self.place_stream_mode(timeline_secs, path, stream, onto, Some(crate::SourceEdit::Overwrite)) |
| 5866 | } |
| 5867 | |
| 5868 | /// The one placement behind both doors: `overwrite` of `None` is the insert-and-paste |
| 5869 | /// `place_stream_at` has always made; `Some` replaces what is there through |
| 5870 | /// [`edit_from_source_at`](Self::edit_from_source_at). |
| 5871 | fn place_stream_mode( |
| 5872 | &mut self, |
| 5873 | timeline_secs: f64, |
| 5874 | path: &Path, |
| 5875 | stream: usize, |
| 5876 | onto: Option<Lane>, |
| 5877 | overwrite: Option<crate::SourceEdit>, |
| 5878 | ) -> crate::Result<bool> { |
| 5879 | let wanted = Source::new(path, stream); |
| 5880 | // Another stream of a file this session has taken in: that is what a |
| 5881 | // library row is, and it is why nothing here has to check dimensions or |
| 5882 | // frame rate -- the file passed that at import. Its length is the one |
| 5883 | // the import noted, so a source that has never been placed is as |
| 5884 | // placeable as one that is already on a lane. |
| 5885 | let frames = self.file_frames(&wanted.path); |
| 5886 | if frames == 0 { |
| 5887 | return Err(format!("{} is not on this timeline", path.display()).into()); |
| 5888 | } |
| 5889 | // A still has no sound to hold to the timeline's -- and no length |
| 5890 | // either, so it goes down at the project's still length rather than at the |
| 5891 | // ten minutes it is *allowed* to be dragged out to. |
| 5892 | let image = crate::is_image(path); |
| 5893 | if !image { |
| 5894 | let first = self.first_audio()?; |
| 5895 | self.audio_matches_cached(&wanted, &first)?; |
| 5896 | } |
| 5897 | let rate = self.file_rate(&wanted.path); |
| 5898 | let source = self.project.import(path, stream); |
| 5899 | self.note_frames(source, frames, rate); |
| 5900 | let clip = Clip { |
| 5901 | speed_keys: Vec::new(), |
| 5902 | reversed: false, |
| 5903 | stabilise: None, deinterlace: Default::default(), mark: Default::default(), |
| 5904 | angle: Default::default(), |
| 5905 | fade_in: 0, |
| 5906 | fade_out: 0, |
| 5907 | transition_out: 0, |
| 5908 | transition_kind: Default::default(), |
| 5909 | visualizer: 0, |
| 5910 | viz_paint: 0, |
| 5911 | gain_db: 0.0, |
| 5912 | gain_keys: Vec::new(), |
| 5913 | pan: 0, |
| 5914 | transform_keys: Vec::new(), |
| 5915 | opacity_keys: Vec::new(), |
| 5916 | color_keys: Vec::new(), |
| 5917 | effects: Vec::new(), |
| 5918 | start: 0, |
| 5919 | in_frame: 0, |
| 5920 | out_frame: match image { |
| 5921 | true if !crate::is_still(path) => frames, |
| 5922 | true => place_frames(frames, self.meta.frame_rate, self.project.still_secs()), |
| 5923 | false => sound_held_frames(path, stream, frames, self.meta.frame_rate), |
| 5924 | }, |
| 5925 | source, |
| 5926 | link: None, |
| 5927 | eq: None, |
| 5928 | color: None, |
| 5929 | transform: None, |
| 5930 | fit: FitPolicy::default(), |
| 5931 | speed: Speed::NORMAL, |
| 5932 | pitch: 0.0, |
| 5933 | }; |
| 5934 | // Which lane a source may land on is decided here and only here, so a |
| 5935 | // front-end never has to make the same call twice: a file with no |
| 5936 | // picture goes on an audio lane alone, overwriting and rippling |
| 5937 | // nothing, because there is nothing on the video lane to move along |
| 5938 | // with it. A lane of the source's own kind takes it as it is dropped; |
| 5939 | // only `V1` means the grouped take, since that is the pair the paste |
| 5940 | // spans and a second video lane is a layer of its own. |
| 5941 | // ...and a still is the mirror of a song: a picture and no sound, so a |
| 5942 | // video lane and nothing else -- never the grouped take, which would |
| 5943 | // put a clip on `A1` for a source the audio worker cannot open. |
| 5944 | if image { |
| 5945 | let lane = match onto { |
| 5946 | Some(lane) if lane.kind == LaneKind::Video => lane, |
| 5947 | _ => Lane::V1, |
| 5948 | }; |
| 5949 | if let Some(edit) = overwrite { |
| 5950 | self.edit_from_source_at(edit, timeline_secs, &[(lane, clip)])?; |
| 5951 | return Ok(true); |
| 5952 | } |
| 5953 | return Ok(self.place_at(lane, timeline_secs, clip)); |
| 5954 | } |
| 5955 | let onto = match (sound_only(path), onto) { |
| 5956 | // No picture: an audio lane and nothing else, whichever one was |
| 5957 | // asked for -- `A1` when none was. |
| 5958 | (true, Some(lane)) if lane.kind == LaneKind::Audio => Some(lane), |
| 5959 | (true, _) => Some(Lane::A1), |
| 5960 | // A picture: the lane it was let go over, unless that is one of the |
| 5961 | // first pair. Those two are the grouped take a paste spans, and a |
| 5962 | // further lane is a layer of its own -- its picture on `V2`, its |
| 5963 | // sound on `A2` (below). |
| 5964 | (false, Some(lane)) if lane.ord > 0 => Some(lane), |
| 5965 | (false, _) => None, |
| 5966 | }; |
| 5967 | // An overwrite lays the same lanes down as an insert would, replacing what is under |
| 5968 | // them: a picture and its sound as one take (a link on both halves), a sound alone |
| 5969 | // on its audio lane. |
| 5970 | if let Some(edit) = overwrite { |
| 5971 | let items: Vec<(Lane, Clip)> = match onto { |
| 5972 | Some(lane) if lane.kind == LaneKind::Audio => vec![(lane, clip)], |
| 5973 | Some(lane) if lane.kind == LaneKind::Video => vec![ |
| 5974 | (lane, clip.clone()), |
| 5975 | (Lane::new(LaneKind::Audio, lane.ord), clip), |
| 5976 | ], |
| 5977 | _ => vec![(Lane::V1, clip.clone()), (Lane::A1, clip)], |
| 5978 | }; |
| 5979 | self.edit_from_source_at(edit, timeline_secs, &items)?; |
| 5980 | return Ok(true); |
| 5981 | } |
| 5982 | Ok(match onto { |
| 5983 | // A picture let go over a further *video* track lands there with the |
| 5984 | // sound it came with -- `V2`'s picture, `A2`'s sound, one take and |
| 5985 | // one undo step ([`Project::place_take`]). Dropped on a further |
| 5986 | // audio lane it is the sound alone, which is what asking an audio |
| 5987 | // row for an mp4 means. |
| 5988 | Some(lane) if lane.kind == LaneKind::Video => { |
| 5989 | let at = secs_to_frame(timeline_secs, self.meta.frame_rate); |
| 5990 | let clip = self.held_to_take(clip); |
| 5991 | self.edit(Dirty::Both, |p| p.place_take(lane, at, clip)) |
| 5992 | } |
| 5993 | Some(lane) => self.place_at(lane, timeline_secs, clip), |
| 5994 | // The grouped take, at the frame it was let go on -- past the last |
| 5995 | // clip included, where the bed is black and the ghost was drawn. |
| 5996 | // Not [`Self::paste_at`]: that door clamps to the end for the |
| 5997 | // clipboard, and a drop that named a place is not a paste. |
| 5998 | None => { |
| 5999 | let at = secs_to_frame(timeline_secs, self.meta.frame_rate); |
| 6000 | let clip = self.held_to_take(clip); |
| 6001 | self.edit(Dirty::Both, |p| p.paste(at, clip)) |
| 6002 | } |
| 6003 | }) |
| 6004 | } |
| 6005 | |
| 6006 | /// Takes `path` played on `stream` out of the library -- the door a library |
| 6007 | /// row's own remove goes through, naming the row exactly as |
| 6008 | /// [`place_stream_at`](Self::place_stream_at) does. Refused in |
| 6009 | /// [`Project::remove_source`]'s words while a clip still plays from it, and |
| 6010 | /// for a row this timeline does not have. |
| 6011 | /// |
| 6012 | /// Reseeks like an edit even though nothing playable changed: the clip |
| 6013 | /// indexes into the source list have just moved, and the running workers |
| 6014 | /// were opened against the old numbering. |
| 6015 | /// |
| 6016 | /// The index that went, because everything past it moved down: a caller |
| 6017 | /// holding a source index of its own (a clipboard) has to fix it up or drop |
| 6018 | /// it, or it names a different file afterwards. The **last** row goes like |
| 6019 | /// any other and leaves a session with an empty library -- silent, empty of |
| 6020 | /// clips, and unsaveable ([`save_project`](Self::save_project)); a |
| 6021 | /// front-end showing one is showing an empty window. |
| 6022 | /// [`remove_source`](Self::remove_source) for the one source that may go |
| 6023 | /// without clearing undo: the **last** entry, when no clip and no undo or |
| 6024 | /// redo step names it ([`Project::remove_unused_source`]). Nothing playable |
| 6025 | /// changes, so there is no reseek and the timeline and its history stay as |
| 6026 | /// they were. Used to roll back a batch that imported a source and then |
| 6027 | /// failed, where clearing history would also wipe the user's undo. |
| 6028 | pub fn remove_unused_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> { |
| 6029 | let wanted = Source::new(path, stream); |
| 6030 | let idx = self |
| 6031 | .project |
| 6032 | .sources() |
| 6033 | .iter() |
| 6034 | .position(|s| *s == wanted) |
| 6035 | .ok_or_else(|| format!("{} is not on this timeline", path.display()))?; |
| 6036 | self.project.remove_unused_source(idx)?; |
| 6037 | if idx < self.counts.len() { |
| 6038 | self.counts.remove(idx); |
| 6039 | self.rates.remove(idx); |
| 6040 | } |
| 6041 | Ok(idx) |
| 6042 | } |
| 6043 | |
| 6044 | pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> { |
| 6045 | let wanted = Source::new(path, stream); |
| 6046 | let idx = self |
| 6047 | .project |
| 6048 | .sources() |
| 6049 | .iter() |
| 6050 | .position(|s| *s == wanted) |
| 6051 | .ok_or_else(|| format!("{} is not on this timeline", path.display()))?; |
| 6052 | self.project.remove_source(idx)?; |
| 6053 | // The one thing that shortens the source list, so the one place |
| 6054 | // [`Self::counts`] shortens with it: left behind, the gone file's length |
| 6055 | // would become the wall a *surviving* source is trimmed against |
| 6056 | // ([`trim_room`](Self::trim_room)) and the next import would land its |
| 6057 | // count one index late. |
| 6058 | if idx < self.counts.len() { |
| 6059 | self.counts.remove(idx); |
| 6060 | self.rates.remove(idx); |
| 6061 | } |
| 6062 | let now = self.now(); |
| 6063 | self.seek(now); |
| 6064 | Ok(idx) |
| 6065 | } |
| 6066 | |
| 6067 | /// What the timeline's audio *is*: the chosen stream of the first source |
| 6068 | /// that could have any ([`audio_source_of`]), probed. Every other source is |
| 6069 | /// held to it. |
| 6070 | /// |
| 6071 | /// Through the session's own memo ([`probes`](Self::probes)), because this |
| 6072 | /// is asked on the render thread: the free [`first_audio_of`] is the one a |
| 6073 | /// worker with no session to reach for calls. |
| 6074 | fn first_audio(&mut self) -> crate::Result<Option<crate::AudioProbe>> { |
| 6075 | match audio_source_of(self.project.sources()) { |
| 6076 | Some(first) => { |
| 6077 | let (path, stream) = (first.path.clone(), first.audio_stream); |
| 6078 | self.probe_cached(&path, stream) |
| 6079 | } |
| 6080 | None => Ok(None), |
| 6081 | } |
| 6082 | } |
| 6083 | |
| 6084 | /// One audio header, read at most once per session per `(path, stream)`. |
| 6085 | fn probe_cached( |
| 6086 | &mut self, |
| 6087 | path: &Path, |
| 6088 | stream: usize, |
| 6089 | ) -> crate::Result<Option<crate::AudioProbe>> { |
| 6090 | let key = (path.to_path_buf(), stream); |
| 6091 | if let Some(probe) = self.probes.get(&key) { |
| 6092 | return Ok(*probe); |
| 6093 | } |
| 6094 | let probe = AudioSession::probe(path, stream)?; |
| 6095 | self.probes.insert(key, probe); |
| 6096 | Ok(probe) |
| 6097 | } |
| 6098 | |
| 6099 | /// [`audio_matches`] with this session's memo behind the new file's own |
| 6100 | /// header too -- the second of the two opens a place or an import pays. |
| 6101 | fn audio_matches_cached( |
| 6102 | &mut self, |
| 6103 | source: &Source, |
| 6104 | first: &Option<crate::AudioProbe>, |
| 6105 | ) -> crate::Result<()> { |
| 6106 | let probe = self.probe_cached(&source.path, source.audio_stream)?; |
| 6107 | audio_matches_probed(probe, first) |
| 6108 | } |
| 6109 | |
| 6110 | /// Places `clip` on `lane` alone at the playhead, overwriting what it lands |
| 6111 | /// on and rippling nothing -- the one-lane insert a source with no picture |
| 6112 | /// makes, and the only way an audio-only file reaches the timeline. The |
| 6113 | /// placement belongs to no group (see [`Project::place`]). One undo step, |
| 6114 | /// and it reseeks like every other edit. |
| 6115 | /// |
| 6116 | /// The clip is held to `lane`'s own wall first ([`held_to_lane`](Self::held_to_lane)): |
| 6117 | /// a caller's `out_frame` past the source's length on that lane is cut back |
| 6118 | /// to it, so no door places a clip the save would refuse. |
| 6119 | pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool { |
| 6120 | let at = secs_to_frame(timeline_secs, self.meta.frame_rate); |
| 6121 | let clip = self.held_to_lane(lane, clip); |
| 6122 | self.edit(Dirty::Both, |p| p.place(lane, at, clip)) |
| 6123 | } |
| 6124 | |
| 6125 | /// [`Project::edit_from_source`]'s door: an insert or an overwrite of the |
| 6126 | /// halves in `items` at `timeline_secs`. Each half is held to its own lane's |
| 6127 | /// wall -- and a take of a picture and its sound to the shorter of the two, |
| 6128 | /// so the halves run the same length and stay one link. One undo step; it |
| 6129 | /// reseeks like every other edit. The error says why it refused. |
| 6130 | pub fn edit_from_source_at( |
| 6131 | &mut self, |
| 6132 | kind: crate::SourceEdit, |
| 6133 | timeline_secs: f64, |
| 6134 | items: &[(Lane, Clip)], |
| 6135 | ) -> crate::Result<()> { |
| 6136 | let at = secs_to_frame(timeline_secs, self.meta.frame_rate); |
| 6137 | let both = items.iter().any(|(l, _)| l.kind == LaneKind::Video) |
| 6138 | && items.iter().any(|(l, _)| l.kind == LaneKind::Audio); |
| 6139 | let items: Vec<(Lane, Clip)> = items |
| 6140 | .iter() |
| 6141 | .map(|(lane, clip)| { |
| 6142 | let held = if both { |
| 6143 | self.held_to_take(clip.clone()) |
| 6144 | } else { |
| 6145 | self.held_to_lane(*lane, clip.clone()) |
| 6146 | }; |
| 6147 | (*lane, held) |
| 6148 | }) |
| 6149 | .collect(); |
| 6150 | let mut result = Ok(()); |
| 6151 | let done = self.edit(Dirty::Both, |p| match p.edit_from_source(kind, at, &items) { |
| 6152 | Ok(()) => true, |
| 6153 | Err(e) => { |
| 6154 | result = Err(e); |
| 6155 | false |
| 6156 | } |
| 6157 | }); |
| 6158 | match (done, result) { |
| 6159 | (_, Err(e)) => Err(e), |
| 6160 | (false, Ok(())) => Err("the edit changed nothing".into()), |
| 6161 | (true, Ok(())) => Ok(()), |
| 6162 | } |
| 6163 | } |
| 6164 | |
| 6165 | /// The longest `clip` may run on `lane`: its source's length on that lane's |
| 6166 | /// kind -- the picture's on a video lane, the sound's on an audio lane |
| 6167 | /// ([`lane_walls`]), the two tables [`save_project`](Self::save_project) |
| 6168 | /// checks each lane against. `out_frame` is held to that wall; a clip the |
| 6169 | /// wall leaves no frame of is one [`Project::place`] refuses. |
| 6170 | fn held_to_lane(&self, lane: Lane, mut clip: Clip) -> Clip { |
| 6171 | let (picture, sound) = |
| 6172 | lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 6173 | let table = match lane.kind { |
| 6174 | LaneKind::Audio => sound, |
| 6175 | _ => picture, |
| 6176 | }; |
| 6177 | if let Some(&wall) = table.get(clip.source) { |
| 6178 | clip.out_frame = clip.out_frame.min(wall); |
| 6179 | } |
| 6180 | clip |
| 6181 | } |
| 6182 | |
| 6183 | /// [`held_to_lane`](Self::held_to_lane) for a clip placed as one take: a |
| 6184 | /// picture on a video lane and its sound on an audio lane, so it is held to |
| 6185 | /// the shorter of the source's two walls. Both halves of a take share the |
| 6186 | /// one clip, so neither may run past its own lane. |
| 6187 | fn held_to_take(&self, mut clip: Clip) -> Clip { |
| 6188 | let (picture, sound) = |
| 6189 | lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate); |
| 6190 | let wall = [picture.get(clip.source), sound.get(clip.source)] |
| 6191 | .into_iter() |
| 6192 | .flatten() |
| 6193 | .min(); |
| 6194 | if let Some(&wall) = wall { |
| 6195 | clip.out_frame = clip.out_frame.min(wall); |
| 6196 | } |
| 6197 | clip |
| 6198 | } |
| 6199 | |
| 6200 | /// Places a waveform-visualizer clip of `path`'s audio on a video lane. |
| 6201 | /// The picture is painted from the sound ([`DecodeSession::open_visualizer`]); |
| 6202 | /// this does not also put a copy on an audio lane. |
| 6203 | pub fn place_visualizer( |
| 6204 | &mut self, |
| 6205 | start: u32, |
| 6206 | path: &Path, |
| 6207 | stream: usize, |
| 6208 | in_frame: u32, |
| 6209 | out_frame: u32, |
| 6210 | onto: Option<Lane>, |
| 6211 | ) -> crate::Result<bool> { |
| 6212 | if out_frame <= in_frame { |
| 6213 | return Err("visualizer clip is empty".into()); |
| 6214 | } |
| 6215 | let wanted = Source::new(path, stream); |
| 6216 | let first = self.first_audio()?; |
| 6217 | self.audio_matches_cached(&wanted, &first)?; |
| 6218 | let frames = match self.file_frames(&wanted.path) { |
| 6219 | 0 => { |
| 6220 | let n = audio_frames(path, self.meta.frame_rate)?; |
| 6221 | let source = self.project.import(path, stream); |
| 6222 | self.note_frames(source, n, Rate::REAL_TIME); |
| 6223 | n |
| 6224 | } |
| 6225 | n => n, |
| 6226 | }; |
| 6227 | let out_frame = out_frame.min(frames); |
| 6228 | if out_frame <= in_frame { |
| 6229 | return Err("visualizer clip is empty".into()); |
| 6230 | } |
| 6231 | let source = self.project.import(path, stream); |
| 6232 | let clip = Clip { |
| 6233 | speed_keys: Vec::new(), |
| 6234 | reversed: false, |
| 6235 | stabilise: None, deinterlace: Default::default(), mark: Default::default(), |
| 6236 | angle: Default::default(), |
| 6237 | fade_in: 0, |
| 6238 | fade_out: 0, |
| 6239 | transition_out: 0, |
| 6240 | transition_kind: Default::default(), |
| 6241 | visualizer: 1, |
| 6242 | viz_paint: 0, |
| 6243 | gain_db: 0.0, |
| 6244 | gain_keys: Vec::new(), |
| 6245 | pan: 0, |
| 6246 | transform_keys: Vec::new(), |
| 6247 | opacity_keys: Vec::new(), |
| 6248 | color_keys: Vec::new(), |
| 6249 | effects: Vec::new(), |
| 6250 | start: 0, |
| 6251 | in_frame, |
| 6252 | out_frame, |
| 6253 | source, |
| 6254 | link: None, |
| 6255 | eq: None, |
| 6256 | color: None, |
| 6257 | transform: None, |
| 6258 | fit: FitPolicy::default(), |
| 6259 | speed: Speed::NORMAL, |
| 6260 | pitch: 0.0, |
| 6261 | }; |
| 6262 | let end = start + clip.frames(); |
| 6263 | let overlaps = |lane: Lane| { |
| 6264 | self.project |
| 6265 | .lane(lane) |
| 6266 | .iter() |
| 6267 | .any(|c| c.start < end && start < c.end()) |
| 6268 | }; |
| 6269 | let lane = match onto { |
| 6270 | Some(lane) if lane.kind == LaneKind::Video && !overlaps(lane) => lane, |
| 6271 | _ => self |
| 6272 | .project |
| 6273 | .lanes() |
| 6274 | .into_iter() |
| 6275 | .filter(|l| l.kind == LaneKind::Video) |
| 6276 | .find(|&l| !overlaps(l)) |
| 6277 | .unwrap_or_else(|| self.add_lane(LaneKind::Video)), |
| 6278 | }; |
| 6279 | let clip = self.held_to_lane(lane, clip); |
| 6280 | Ok(self.edit(Dirty::Both, |p| p.place(lane, start, clip))) |
| 6281 | } |
| 6282 | |
| 6283 | /// Removes `lane`'s clip at `idx` and everything under it, closing the gap |
| 6284 | /// on every lane. Unlike a split this *does* move every following frame, so |
| 6285 | /// the session reseeks to wherever the playhead now points. |
| 6286 | /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead. |
| 6287 | /// `false` for a bad index; the last remaining clip goes like any other and |
| 6288 | /// leaves the timeline empty ([`is_empty`](Self::is_empty)). |
| 6289 | /// |
| 6290 | /// The lane travels because the index is a lane's own: `V2`'s third clip is |
| 6291 | /// not `V1`'s, and a front-end that could only say "the third clip" would |
| 6292 | /// delete the wrong one the moment a second lane exists. |
| 6293 | pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool { |
| 6294 | self.edit(Dirty::Both, |p| p.delete_in(lane, idx)) |
| 6295 | } |
| 6296 | |
| 6297 | /// Undoes the last successful edit, and reseeks like a delete. A step on |
| 6298 | /// the project's own settings comes back the same way: the canvas, the |
| 6299 | /// rate and the switches are put back on the session here |
| 6300 | /// ([`Self::adopt_settings`]), so a `z` after a resolution pick, an |
| 6301 | /// encoder pick or a proxy switch lands exactly as one after a cut does. |
| 6302 | pub fn undo(&mut self) -> bool { |
| 6303 | self.restored_step(Project::undo) |
| 6304 | } |
| 6305 | |
| 6306 | /// Redoes the last edit [`undo`](Self::undo) took back, and reseeks like |
| 6307 | /// a delete -- settings included, exactly as `undo` takes them back. |
| 6308 | pub fn redo(&mut self) -> bool { |
| 6309 | self.restored_step(Project::redo) |
| 6310 | } |
| 6311 | |
| 6312 | /// Every sequence in tab order ([`Project::sequences`]). |
| 6313 | pub fn sequences(&self) -> Vec<crate::project::SequenceInfo> { |
| 6314 | self.project.sequences() |
| 6315 | } |
| 6316 | |
| 6317 | /// The active sequence's id. |
| 6318 | pub fn active_sequence(&self) -> u32 { |
| 6319 | self.project.active_sequence() |
| 6320 | } |
| 6321 | |
| 6322 | /// The name of sequence `id`. |
| 6323 | pub fn sequence_name(&self, id: u32) -> Option<String> { |
| 6324 | self.project.sequence_name(id).map(str::to_string) |
| 6325 | } |
| 6326 | |
| 6327 | /// The sequence called `name`. |
| 6328 | pub fn sequence_named(&self, name: &str) -> Option<u32> { |
| 6329 | self.project.sequence_named(name) |
| 6330 | } |
| 6331 | |
| 6332 | /// See [`Project::source_uses_parked`]. |
| 6333 | pub fn source_uses_parked(&self, source: usize) -> Vec<(u32, usize)> { |
| 6334 | self.project.source_uses_parked(source) |
| 6335 | } |
| 6336 | |
| 6337 | /// See [`Project::compound_pieces`]. |
| 6338 | pub fn compound_pieces(&self, kind: LaneKind, clip: &Clip) -> Vec<Clip> { |
| 6339 | self.project.compound_pieces(kind, clip) |
| 6340 | } |
| 6341 | |
| 6342 | /// The sequence the compound clip at `lane`/`idx` plays. |
| 6343 | pub fn compound_at(&self, lane: Lane, idx: usize) -> Option<u32> { |
| 6344 | self.project.compound_at(lane, idx) |
| 6345 | } |
| 6346 | |
| 6347 | /// The angle names of sequence `id` when it is a multicam source ([`Project::angle_names`]). |
| 6348 | pub fn angle_names(&self, id: u32) -> Option<Vec<String>> { |
| 6349 | self.project.angle_names(id).map(<[String]>::to_vec) |
| 6350 | } |
| 6351 | |
| 6352 | /// The multicam source the clip at `lane`/`idx` plays and its angle names, when it is a |
| 6353 | /// multicam clip. |
| 6354 | pub fn multicam_at(&self, lane: Lane, idx: usize) -> Option<(u32, Vec<String>)> { |
| 6355 | let c = self.project.lane(lane).get(idx)?; |
| 6356 | self.project.multicam_of(c).map(|(id, n)| (id, n.to_vec())) |
| 6357 | } |
| 6358 | |
| 6359 | /// Whether the rate and other time-scaled settings are fixed because the |
| 6360 | /// project holds more than one sequence. |
| 6361 | pub fn rate_locked(&self) -> bool { |
| 6362 | self.project.rate_locked() |
| 6363 | } |
| 6364 | |
| 6365 | /// An edit that can be refused with a reason: the picture and the sound are |
| 6366 | /// rebuilt when it was made. |
| 6367 | fn edit_try<T>(&mut self, f: impl FnOnce(&mut Project) -> crate::Result<T>) -> crate::Result<T> { |
| 6368 | let made = f(&mut self.project)?; |
| 6369 | self.invalidate(Dirty::Both); |
| 6370 | Ok(made) |
| 6371 | } |
| 6372 | |
| 6373 | /// Adds an empty sequence; see [`Project::new_sequence`]. Not switched to. |
| 6374 | pub fn new_sequence(&mut self, name: Option<&str>) -> crate::Result<u32> { |
| 6375 | self.edit_try(|p| p.new_sequence(name)) |
| 6376 | } |
| 6377 | |
| 6378 | /// Makes an editor timeline a new sequence and switches to it ([`crate::interchange::build`]). |
| 6379 | /// Each file it names is taken in as a library file is; one that is gone is offline, as a |
| 6380 | /// missing file is in a saved project. One undo step. |
| 6381 | pub fn import_timeline(&mut self, t: &crate::interchange::Timeline) -> crate::Result<u32> { |
| 6382 | let mut reach: Vec<(PathBuf, u32)> = Vec::new(); |
| 6383 | for item in t.tracks.iter().flat_map(|tr| &tr.items) { |
| 6384 | if let crate::interchange::Item::Clip(c) = item { |
| 6385 | match reach.iter_mut().find(|(p, _)| *p == c.path) { |
| 6386 | Some((_, r)) => *r = (*r).max(c.out_frame), |
| 6387 | None => reach.push((c.path.clone(), c.out_frame)), |
| 6388 | } |
| 6389 | } |
| 6390 | } |
| 6391 | for (path, furthest) in &reach { |
| 6392 | if self.source_of(path).is_some() { |
| 6393 | continue; |
| 6394 | } |
| 6395 | if crate::source_present(path) { |
| 6396 | self.import(path)?; |
| 6397 | } else { |
| 6398 | let source = self.project.import(path, 0); |
| 6399 | self.note_frames(source, *furthest, Rate::REAL_TIME); |
| 6400 | } |
| 6401 | } |
| 6402 | self.begin_batch(); |
| 6403 | let made = self.edit_try(|p| crate::interchange::build(p, t)); |
| 6404 | self.end_batch(); |
| 6405 | made |
| 6406 | } |
| 6407 | |
| 6408 | /// See [`Project::rename_sequence`]. |
| 6409 | pub fn rename_sequence(&mut self, id: u32, name: &str) -> crate::Result<()> { |
| 6410 | self.edit_try(|p| p.rename_sequence(id, name)) |
| 6411 | } |
| 6412 | |
| 6413 | /// See [`Project::duplicate_sequence`]. |
| 6414 | pub fn duplicate_sequence(&mut self, id: u32) -> crate::Result<u32> { |
| 6415 | self.edit_try(|p| p.duplicate_sequence(id)) |
| 6416 | } |
| 6417 | |
| 6418 | /// See [`Project::delete_sequence`]. The picture and sound follow the |
| 6419 | /// sequence that is active afterwards. |
| 6420 | pub fn delete_sequence(&mut self, id: u32) -> crate::Result<u32> { |
| 6421 | self.edit_try(|p| p.delete_sequence(id)) |
| 6422 | } |
| 6423 | |
| 6424 | /// Makes `id` the sequence on the timeline and in the picture and sound. Not an undo step. |
| 6425 | pub fn switch_sequence(&mut self, id: u32) -> crate::Result<()> { |
| 6426 | if id == self.project.active_sequence() { |
| 6427 | return Ok(()); |
| 6428 | } |
| 6429 | self.edit_try(|p| p.switch_sequence(id)) |
| 6430 | } |
| 6431 | |
| 6432 | /// See [`Project::nest`]. |
| 6433 | pub fn nest(&mut self, picks: &[(Lane, usize)], name: Option<&str>) -> crate::Result<crate::project::Nested> { |
| 6434 | self.edit_try(|p| p.nest(picks, name)) |
| 6435 | } |
| 6436 | |
| 6437 | /// See [`Project::break_apart`]. |
| 6438 | pub fn break_apart(&mut self, picks: &[(Lane, usize)]) -> crate::Result<Vec<(Lane, usize)>> { |
| 6439 | self.edit_try(|p| p.break_apart(picks)) |
| 6440 | } |
| 6441 | |
| 6442 | /// Syncs the sources `picks` and makes a multicam clip of them at `timeline_secs` on `lane` |
| 6443 | /// ([`Project::make_multicam`]). With [`MulticamSync::Audio`] every camera is lined up with |
| 6444 | /// the first one that has sound by the loudness curve of its track |
| 6445 | /// ([`crate::multisync`]); a camera that cannot be matched (no sound, or too weak a match) |
| 6446 | /// starts with the others and the report says so. One undo step. |
| 6447 | pub fn make_multicam_at( |
| 6448 | &mut self, |
| 6449 | picks: &[usize], |
| 6450 | sync: MulticamSync, |
| 6451 | name: Option<&str>, |
| 6452 | lane: Lane, |
| 6453 | timeline_secs: f64, |
| 6454 | ) -> crate::Result<MulticamReport> { |
| 6455 | let job = self.multicam_job(picks, sync)?; |
| 6456 | let plan = job.run(&std::sync::atomic::AtomicU32::new(0), &std::sync::atomic::AtomicBool::new(false))?; |
| 6457 | self.apply_multicam(&plan, name, lane, timeline_secs) |
| 6458 | } |
| 6459 | |
| 6460 | /// The part of [`make_multicam_at`](Self::make_multicam_at) that only reads the sources, as a |
| 6461 | /// value that can be run on a thread of its own ([`MulticamJob::run`]) while the window stays |
| 6462 | /// live; [`apply_multicam`](Self::apply_multicam) then makes the clip, one undo step. |
| 6463 | pub fn multicam_job(&self, picks: &[usize], sync: MulticamSync) -> crate::Result<MulticamJob> { |
| 6464 | let mut seen = Vec::new(); |
| 6465 | let mut sources = Vec::new(); |
| 6466 | for &p in picks { |
| 6467 | let Some(src) = self.project.sources().get(p) else { |
| 6468 | return Err(format!("source {p} is not in the project").into()); |
| 6469 | }; |
| 6470 | if seen.contains(&p) { |
| 6471 | return Err(format!("source {p} is picked twice: an angle is one camera").into()); |
| 6472 | } |
| 6473 | seen.push(p); |
| 6474 | sources.push(MulticamJobSource { |
| 6475 | index: p, |
| 6476 | path: src.path.clone(), |
| 6477 | audio_stream: src.audio_stream, |
| 6478 | frames: self.counts.get(p).copied().unwrap_or(0).max(1), |
| 6479 | }); |
| 6480 | } |
| 6481 | Ok(MulticamJob { sources, sync, fps: self.meta.frame_rate }) |
| 6482 | } |
| 6483 | |
| 6484 | /// The library's bins ([`Project::bins`]). |
| 6485 | pub fn bins(&self) -> &[crate::project::Bin] { |
| 6486 | self.project.bins() |
| 6487 | } |
| 6488 | |
| 6489 | /// Makes a bin; see [`Project::create_bin`]. A label only: nothing is rebuilt. |
| 6490 | pub fn create_bin(&mut self, name: &str, parent: u32) -> Result<u32, String> { |
| 6491 | self.project.create_bin(name, parent) |
| 6492 | } |
| 6493 | |
| 6494 | /// See [`Project::rename_bin`]. |
| 6495 | pub fn rename_bin(&mut self, id: u32, name: &str) -> Result<bool, String> { |
| 6496 | self.project.rename_bin(id, name) |
| 6497 | } |
| 6498 | |
| 6499 | /// See [`Project::remove_bin`]. |
| 6500 | pub fn remove_bin(&mut self, id: u32) -> Result<usize, String> { |
| 6501 | self.project.remove_bin(id) |
| 6502 | } |
| 6503 | |
| 6504 | /// See [`Project::move_to_bin`]. |
| 6505 | pub fn move_to_bin(&mut self, srcs: &[usize], bin: u32) -> Result<usize, String> { |
| 6506 | self.project.move_to_bin(srcs, bin) |
| 6507 | } |
| 6508 | |
| 6509 | /// See [`Project::set_favourite`]. |
| 6510 | pub fn set_favourite(&mut self, srcs: &[usize], on: bool) -> Result<usize, String> { |
| 6511 | self.project.set_favourite(srcs, on) |
| 6512 | } |
| 6513 | |
| 6514 | /// Makes the multicam clip a [`MulticamJob::run`] measured, at `timeline_secs` on `lane`. One |
| 6515 | /// undo step. Refused when the project's sources are no longer the ones that were measured. |
| 6516 | pub fn apply_multicam(&mut self, plan: &MulticamPlan, name: Option<&str>, lane: Lane, timeline_secs: f64) -> crate::Result<MulticamReport> { |
| 6517 | for a in &plan.sources { |
| 6518 | if self.project.sources().get(a.index).map(|s| &s.path) != Some(&a.path) { |
| 6519 | return Err("the media list changed while the angles were being synced".into()); |
| 6520 | } |
| 6521 | } |
| 6522 | let fps = self.meta.frame_rate; |
| 6523 | let at = secs_to_frame(timeline_secs, fps); |
| 6524 | let made = self.edit_try(|p| p.make_multicam(name, &plan.angles, lane, at))?; |
| 6525 | Ok(MulticamReport { made, how: plan.how.clone(), offsets_secs: plan.offsets.clone(), starts: plan.angles.iter().map(|a| a.start).collect() }) |
| 6526 | } |
| 6527 | |
| 6528 | /// See [`Project::switch_angle`], at `timeline_secs`. |
| 6529 | pub fn switch_angle_at( |
| 6530 | &mut self, |
| 6531 | lane: Option<Lane>, |
| 6532 | timeline_secs: f64, |
| 6533 | video: Option<u8>, |
| 6534 | audio: Option<Option<u8>>, |
| 6535 | ) -> crate::Result<Vec<(Lane, u32)>> { |
| 6536 | let at = secs_to_frame(timeline_secs, self.meta.frame_rate); |
| 6537 | self.edit_try(|p| p.switch_angle(lane, at, video, audio)) |
| 6538 | } |
| 6539 | |
| 6540 | /// The multicam clip under timeline `frame`, if any ([`Project::multicam_under`]). |
| 6541 | pub fn multicam_under(&self, frame: u32) -> Option<crate::project::MulticamUnder> { |
| 6542 | self.project.multicam_under(frame) |
| 6543 | } |
| 6544 | |
| 6545 | /// One flattened project per angle of the multicam clip under `frame` and the timeline meta |
| 6546 | /// to compose them with ([`crate::export::compose_at`]): the angle monitor's tiles, composed |
| 6547 | /// off the window's thread. |
| 6548 | pub fn angle_views(&self, frame: u32) -> Option<(crate::project::MulticamUnder, Vec<crate::project::Project>, VideoMeta)> { |
| 6549 | self.project.angle_views(frame).map(|(u, v)| (u, v, self.meta)) |
| 6550 | } |
| 6551 | |
| 6552 | /// See [`Project::flatten_multicam`]. |
| 6553 | pub fn flatten_multicam(&mut self, lane: Lane, idx: usize) -> crate::Result<Vec<(Lane, usize)>> { |
| 6554 | self.edit_try(|p| p.flatten_multicam(lane, idx)) |
| 6555 | } |
| 6556 | |
| 6557 | /// See [`Project::place_sequence`], at `timeline_secs`. |
| 6558 | pub fn place_sequence_at(&mut self, seq: u32, lane: Lane, timeline_secs: f64) -> crate::Result<()> { |
| 6559 | let at = secs_to_frame(timeline_secs, self.meta.frame_rate); |
| 6560 | self.edit_try(|p| p.place_sequence(seq, lane, at)) |
| 6561 | } |
| 6562 | |
| 6563 | /// The project as an edit sees it, compound clips and all, with the undo history left out |
| 6564 | /// (what a "did this batch change anything" comparison reads; [`export_snapshot`](Self::export_snapshot) |
| 6565 | /// is the expanded one a render reads). |
| 6566 | pub fn raw_snapshot(&self) -> (crate::project::Project, VideoMeta) { |
| 6567 | (self.project.raw_snapshot(), self.meta) |
| 6568 | } |
| 6569 | |
| 6570 | /// [`export_snapshot`](Self::export_snapshot) of sequence `seq` (the active one for `None`). |
| 6571 | pub fn export_snapshot_of(&self, seq: Option<u32>) -> crate::Result<(crate::project::Project, VideoMeta)> { |
| 6572 | Ok((self.project.render_snapshot(seq)?, self.meta)) |
| 6573 | } |
| 6574 | |
| 6575 | /// Starts a batch: the edits until [`end_batch`](Self::end_batch) are one |
| 6576 | /// undo step, taken before the first of them. Only the caller that opens a |
| 6577 | /// batch sees the difference; the GUI never calls this, so its steps stay one per edit. |
| 6578 | pub fn begin_batch(&mut self) { |
| 6579 | self.project.begin_batch(); |
| 6580 | } |
| 6581 | |
| 6582 | /// Ends the batch [`begin_batch`](Self::begin_batch) opened. |
| 6583 | pub fn end_batch(&mut self) { |
| 6584 | self.project.end_batch(); |
| 6585 | } |
| 6586 | |
| 6587 | /// The mark an action takes before it edits, for [`Self::name_step`]. |
| 6588 | pub fn step_mark(&mut self) -> u64 { |
| 6589 | self.project.step_mark() |
| 6590 | } |
| 6591 | |
| 6592 | /// Names the step the action that took `mark` pushed, so Undo and Redo can say what |
| 6593 | /// they take back. An action that pushed nothing names nothing. |
| 6594 | pub fn name_step(&mut self, mark: u64, label: &str) { |
| 6595 | self.project.name_step(mark, label); |
| 6596 | } |
| 6597 | |
| 6598 | /// What [`undo`](Self::undo) takes back, when the step was named. |
| 6599 | pub fn undo_label(&self) -> Option<&str> { |
| 6600 | self.project.undo_label() |
| 6601 | } |
| 6602 | |
| 6603 | /// What [`redo`](Self::redo) walks forward to, when the step was named. |
| 6604 | pub fn redo_label(&self) -> Option<&str> { |
| 6605 | self.project.redo_label() |
| 6606 | } |
| 6607 | |
| 6608 | /// The names of the steps [`undo`](Self::undo) can take back, oldest first |
| 6609 | /// ([`Project::undo_labels`]). |
| 6610 | pub fn undo_labels(&self) -> Vec<Option<String>> { |
| 6611 | self.project.undo_labels() |
| 6612 | } |
| 6613 | |
| 6614 | /// The names of the steps [`redo`](Self::redo) can walk forward to, the next one last |
| 6615 | /// ([`Project::redo_labels`]). |
| 6616 | pub fn redo_labels(&self) -> Vec<Option<String>> { |
| 6617 | self.project.redo_labels() |
| 6618 | } |
| 6619 | |
| 6620 | /// Moves through the undo history by `index` steps from where it stands: negative undoes that |
| 6621 | /// many, positive redoes. Each step goes through [`undo`](Self::undo) or [`redo`](Self::redo), |
| 6622 | /// so it reseeks like them. Returns how many steps were taken; it stops early at either end. |
| 6623 | pub fn jump_to(&mut self, index: isize) -> usize { |
| 6624 | let mut taken = 0; |
| 6625 | for _ in 0..index.unsigned_abs() { |
| 6626 | let moved = match index < 0 { |
| 6627 | true => self.undo(), |
| 6628 | false => self.redo(), |
| 6629 | }; |
| 6630 | if !moved { |
| 6631 | break; |
| 6632 | } |
| 6633 | taken += 1; |
| 6634 | } |
| 6635 | taken |
| 6636 | } |
| 6637 | |
| 6638 | /// How many steps [`undo`](Self::undo) can still take. |
| 6639 | pub fn undo_depth(&self) -> usize { |
| 6640 | self.project.history_len() |
| 6641 | } |
| 6642 | |
| 6643 | /// How many steps [`redo`](Self::redo) can still take. |
| 6644 | pub fn redo_depth(&self) -> usize { |
| 6645 | self.project.redo_len() |
| 6646 | } |
| 6647 | |
| 6648 | /// Which state the timeline is in ([`Project::revision`]): equal before and |
| 6649 | /// after an undo means the undo walked back to the same timeline, so a save |
| 6650 | /// taken at one can tell whether the timeline has since moved off it. |
| 6651 | pub fn revision(&self) -> u64 { |
| 6652 | self.project.revision() |
| 6653 | } |
| 6654 | |
| 6655 | /// Every undo snapshot the session has pushed, including those the |
| 6656 | /// [`HISTORY_CAP`](crate::project) has since dropped. Unlike |
| 6657 | /// [`undo_depth`](Self::undo_depth) it keeps rising at the cap, so a caller |
| 6658 | /// counts a batch's steps as the difference of two reads of it. |
| 6659 | pub fn history_pushes(&self) -> u64 { |
| 6660 | self.project.history_pushes() |
| 6661 | } |
| 6662 | |
| 6663 | /// Drops the redo stack with no step taken. For a caller that rolled its own |
| 6664 | /// trial edits back: the undone states they left are not a branch to redo. |
| 6665 | pub fn clear_redo(&mut self) { |
| 6666 | self.project.clear_redo(); |
| 6667 | } |
| 6668 | |
| 6669 | /// Moves the redo stack out ([`RedoCheckpoint`]) with no step taken, for a |
| 6670 | /// caller whose trial edits may be rolled back. The trial's own edits clear |
| 6671 | /// it and its rollback fills it, so [`restore_redo`](Self::restore_redo) |
| 6672 | /// puts back exactly what was there before the trial. |
| 6673 | pub fn take_redo(&mut self) -> RedoCheckpoint { |
| 6674 | self.project.take_redo() |
| 6675 | } |
| 6676 | |
| 6677 | /// Puts back the redo stack [`take_redo`](Self::take_redo) took out. |
| 6678 | pub fn restore_redo(&mut self, cp: RedoCheckpoint) { |
| 6679 | self.project.restore_redo(cp); |
| 6680 | } |
| 6681 | |
| 6682 | /// Opens (`true`) or closes (`false`) a trial batch's hold on the undo cap: |
| 6683 | /// while held, its steps evict nothing, so a rolled-back trial leaves the |
| 6684 | /// history exactly as it found it. Closing trims back to the cap. |
| 6685 | pub fn hold_history(&mut self, hold: bool) { |
| 6686 | self.project.hold_history(hold); |
| 6687 | } |
| 6688 | |
| 6689 | /// Takes `path` into the **library**: it becomes a source of this session, |
| 6690 | /// with its length noted ([`file_frames`](Self::file_frames)), and nothing |
| 6691 | /// is placed on any lane. What reaches the timeline is decided afterwards, |
| 6692 | /// by dragging the row onto a lane |
| 6693 | /// ([`place_stream_at`](Self::place_stream_at)) -- importing a file is not |
| 6694 | /// a decision about where it plays. |
| 6695 | /// |
| 6696 | /// The source index, new or the one this file already had: importing twice |
| 6697 | /// registers once. *Not* an undo step -- a source entry alone changes |
| 6698 | /// nothing playable, so there is nothing for [`undo`](Self::undo) to take |
| 6699 | /// back, and nothing reseeks. |
| 6700 | /// |
| 6701 | /// Refused unless it can join the timeline -- a decoder this machine can |
| 6702 | /// open, and audio parameters that agree or none at all; the `Err` names |
| 6703 | /// the property that disagrees, |
| 6704 | /// for a caller to show. Nothing is changed by a refusal. A *resolution* of |
| 6705 | /// its own is not a refusal: the clip is placed on the project canvas by its |
| 6706 | /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame |
| 6707 | /// rate* of its own: the file is placed for the seconds it lasts and read at |
| 6708 | /// [`Rate`] against the timeline's rate, so it plays at the speed it was |
| 6709 | /// shot at. |
| 6710 | /// [`import`](Self::import), with what the import cannot do for the file |
| 6711 | /// said back as warnings rather than left on stderr. A file whose sound is in |
| 6712 | /// a codec this build does not decode (DTS, say) imports with its picture and |
| 6713 | /// plays silent: the one warning is that sentence, naming the track. Empty |
| 6714 | /// for a file with nothing to warn about. |
| 6715 | pub fn import_with_warnings(&mut self, path: &Path) -> crate::Result<(usize, Vec<String>)> { |
| 6716 | let source = self.import(path)?; |
| 6717 | let warnings = AudioSession::unsupported(path) |
| 6718 | .ok() |
| 6719 | .flatten() |
| 6720 | .map(|why| format!("{}: {why}; its sound will be silent", path.display())) |
| 6721 | .into_iter() |
| 6722 | .collect(); |
| 6723 | Ok((source, warnings)) |
| 6724 | } |
| 6725 | |
| 6726 | pub fn import(&mut self, path: &Path) -> crate::Result<usize> { |
| 6727 | if crate::is_audio(path) { |
| 6728 | return self.import_audio(path); |
| 6729 | } |
| 6730 | // One frame of a numbered run is the whole run: a clip of its frames, asked nothing. |
| 6731 | if let Some(run) = crate::sequence::Run::parse(path).or_else(|| crate::sequence::Run::detect(path)) { |
| 6732 | return self.import_run(&run); |
| 6733 | } |
| 6734 | if crate::is_image(path) { |
| 6735 | return self.import_image(path); |
| 6736 | } |
| 6737 | // Both halves on this thread, which is what a caller with nothing else |
| 6738 | // to do wants; a front-end splits them across a worker instead |
| 6739 | // ([`probe_import`](Self::probe_import)). |
| 6740 | // A container with sound but no picture is a song wearing a video |
| 6741 | // extension -- the same fallback `open_stream` and the project |
| 6742 | // scaffold make, so every door in agrees on what the file is. |
| 6743 | match Self::probe_import(self.import_gate(), path) { |
| 6744 | Ok(probe) => Ok(self.take_probe(path, probe)), |
| 6745 | Err(e) if crate::demux::NoVideoTrack::is_it(&e) => self.import_audio(path), |
| 6746 | Err(e) => Err(e), |
| 6747 | } |
| 6748 | } |
| 6749 | |
| 6750 | /// Everything an import is *checked against*, taken off this timeline in |
| 6751 | /// one owned piece: the sources its audio must agree with and the meta its |
| 6752 | /// rate is read against. Costs two clones and touches no disk, so the |
| 6753 | /// thread holding the session can hand it to a worker and go on painting. |
| 6754 | pub fn import_gate(&self) -> ImportGate { |
| 6755 | ImportGate { |
| 6756 | sources: self.project.sources().to_vec(), |
| 6757 | timeline: self.meta, |
| 6758 | } |
| 6759 | } |
| 6760 | |
| 6761 | /// The reading half of [`import`](Self::import), with no session in it: the |
| 6762 | /// container's header, the decoder this machine would open it with, and the |
| 6763 | /// audio check against the gate -- every read an import pays. |
| 6764 | /// |
| 6765 | /// This is the half that costs. Measured on a 24 GB 4K HEVC remux: 21.4 s of |
| 6766 | /// header with the pages cold, 429 ms warm, plus 1-4 s of probing the |
| 6767 | /// timeline's own first source. So a front-end runs *this* on its background |
| 6768 | /// executor and hands what comes back to |
| 6769 | /// [`import_probed`](Self::import_probed), which costs a push -- the same |
| 6770 | /// split [`parse_subtitles`](Self::parse_subtitles) makes, for the same |
| 6771 | /// reason. |
| 6772 | /// |
| 6773 | /// The container fork only: a song and a still fork before the demuxer |
| 6774 | /// ([`import`](Self::import)) and pay a header read of their own. |
| 6775 | /// |
| 6776 | /// The `Err` is the refusal [`import`](Self::import) would have given, in |
| 6777 | /// the same words -- nothing is refused twice and nothing is worded twice. |
| 6778 | pub fn probe_import(gate: ImportGate, path: &Path) -> crate::Result<ImportProbe> { |
| 6779 | let (meta, _) = Demuxer::open(path)?; |
| 6780 | let first = first_audio_of(&gate.sources)?; |
| 6781 | // Stream 0: an import brings a file in on its first audio track, and |
| 6782 | // [`place_stream_at`](Self::place_stream_at) is how any other one of |
| 6783 | // its streams reaches the timeline afterwards. |
| 6784 | // ...and the rate it will be read at comes back from the check that |
| 6785 | // accepted it, so the number the refusal was decided on is the number |
| 6786 | // the file is played by. |
| 6787 | let rate = matches_timeline(&Source::new(path, 0), &meta, &gate.timeline, &first)?; |
| 6788 | Ok(ImportProbe { gate, meta, rate }) |
| 6789 | } |
| 6790 | |
| 6791 | /// Registers a file already read by [`probe_import`](Self::probe_import). |
| 6792 | /// The whole of what an import costs the thread that calls it: a source |
| 6793 | /// entry and its length, no open, no seek, no decode -- which is why the |
| 6794 | /// probe is a separate door. |
| 6795 | /// |
| 6796 | /// The timeline may have moved while the worker read: a source removed or a |
| 6797 | /// file opened is a different set of things the probe was checked against, |
| 6798 | /// so the probe is re-read here ([`ImportGate`]) and a stale one is simply |
| 6799 | /// imported the slow way rather than trusted. Same answer either way, so no |
| 6800 | /// caller has to know which arm it took. |
| 6801 | pub fn import_probed(&mut self, path: &Path, probe: ImportProbe) -> crate::Result<usize> { |
| 6802 | match probe.gate.sources == self.project.sources() && probe.gate.timeline == self.meta { |
| 6803 | true => Ok(self.take_probe(path, probe)), |
| 6804 | false => self.import(path), |
| 6805 | } |
| 6806 | } |
| 6807 | |
| 6808 | /// The push both import doors end at. |
| 6809 | fn take_probe(&mut self, path: &Path, probe: ImportProbe) -> usize { |
| 6810 | let source = self.project.import(path, 0); |
| 6811 | // Its length *on this timeline*: a file shot slower than the timeline |
| 6812 | // runs covers more frames than it holds, which is the whole of what |
| 6813 | // placing it at another rate means ([`Rate`]). |
| 6814 | self.note_frames( |
| 6815 | source, |
| 6816 | probe.rate.timeline_at(probe.meta.frame_count), |
| 6817 | probe.rate, |
| 6818 | ); |
| 6819 | source |
| 6820 | } |
| 6821 | |
| 6822 | /// The same registration for a standalone audio file: a song has no |
| 6823 | /// picture, so the length noted for it is its playing time rounded up to |
| 6824 | /// whole frames, which is the only frame count such a source has. |
| 6825 | /// |
| 6826 | /// Refused in the same words as any other import when its layout disagrees |
| 6827 | /// with the timeline's track -- one output device, one layout. A silent |
| 6828 | /// timeline has no track to disagree with, so a song joins it and *is* its |
| 6829 | /// sound ([`Self::arm_audio`]). Nothing is changed by a refusal. |
| 6830 | fn import_audio(&mut self, path: &Path) -> crate::Result<usize> { |
| 6831 | let first = self.first_audio()?; |
| 6832 | // Stream 0, and there is no other: a standalone audio file carries one |
| 6833 | // track (`AudioSession::probe_streams`), so nothing here has a stream |
| 6834 | // to pick the way `place_stream_at` does for an mp4. |
| 6835 | self.audio_matches_cached(&Source::new(path, 0), &first)?; |
| 6836 | let frames = audio_frames(path, self.meta.frame_rate)?; |
| 6837 | let source = self.project.import(path, 0); |
| 6838 | self.note_frames(source, frames, Rate::REAL_TIME); |
| 6839 | Ok(source) |
| 6840 | } |
| 6841 | |
| 6842 | /// The registration of a numbered run ([`crate::sequence`]): one source named for the whole |
| 6843 | /// run, held to as many frames as the run holds, at the timeline's rate. The first frame is |
| 6844 | /// what a refusal is decided on -- a run of pictures this engine cannot compose is refused in |
| 6845 | /// the words a single still would be. |
| 6846 | fn import_run(&mut self, run: &crate::sequence::Run) -> crate::Result<usize> { |
| 6847 | let (width, height) = crate::decode::image_size(&run.frame(0))?; |
| 6848 | if !crate::is_resolution(width, height) { |
| 6849 | return Err(format!( |
| 6850 | "{} is {width}x{height}, which is not a picture this engine composes", |
| 6851 | run.frame(0).display() |
| 6852 | ) |
| 6853 | .into()); |
| 6854 | } |
| 6855 | let source = self.project.import(run.spelled(), 0); |
| 6856 | self.note_frames(source, run.count, Rate::REAL_TIME); |
| 6857 | Ok(source) |
| 6858 | } |
| 6859 | |
| 6860 | /// The same registration for a still image, and the shortest of the three: |
| 6861 | /// a picture has nothing to agree with. No frame rate (it is one picture), |
| 6862 | /// no audio (it is silent), and a resolution of its own is what every |
| 6863 | /// import is allowed -- the clip is placed on the project canvas by its fit |
| 6864 | /// policy. The one refusal left is a file that is not a picture at all, or |
| 6865 | /// one too big to compose ([`crate::is_resolution`]), and the header alone |
| 6866 | /// answers both. |
| 6867 | /// |
| 6868 | /// The length noted is the wall a trim is held to, not a duration the file |
| 6869 | /// has: see [`image_frames`]. |
| 6870 | fn import_image(&mut self, path: &Path) -> crate::Result<usize> { |
| 6871 | let (width, height) = crate::decode::image_size(path)?; |
| 6872 | if !crate::is_resolution(width, height) { |
| 6873 | return Err(format!( |
| 6874 | "{} is {width}x{height}, which is not a picture this engine composes", |
| 6875 | path.display() |
| 6876 | ) |
| 6877 | .into()); |
| 6878 | } |
| 6879 | let source = self.project.import(path, 0); |
| 6880 | self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME); |
| 6881 | Ok(source) |
| 6882 | } |
| 6883 | |
| 6884 | /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing |
| 6885 | /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new |
| 6886 | /// duration and keeps playing playing, so a delete that shortens the |
| 6887 | /// timeline past the playhead lands on the last frame. A grade or a fit |
| 6888 | /// policy rebuilds the picture where it stands, with the sound running |
| 6889 | /// through it untouched -- no flush, no re-open, no hole -- and an |
| 6890 | /// equalizer the other way round. |
| 6891 | /// The project's own settings as this session has them now |
| 6892 | /// ([`ProjectSettings`]): the canvas and the rate are `meta`'s, the |
| 6893 | /// switches are this session's own fields, and the rendition and the |
| 6894 | /// limiter are the project's -- two halves of one header, which is what |
| 6895 | /// every history entry carries beside the lanes ([`Project::snapshot`]). |
| 6896 | fn settings_value(&self) -> ProjectSettings { |
| 6897 | ProjectSettings { |
| 6898 | resolution: (self.meta.width, self.meta.height), |
| 6899 | frame_rate: self.meta.frame_rate, |
| 6900 | encoder_seat: self.encoder_seat, |
| 6901 | sample_rate: self.sample_rate, |
| 6902 | proxies: self.proxies, |
| 6903 | auto_proxies: self.auto_proxies, |
| 6904 | tone: self.project.tone(), |
| 6905 | limiter: self.project.limiter(), |
| 6906 | caption_style: self.project.caption_style(), |
| 6907 | notes: self.project.notes().to_string(), |
| 6908 | still_secs: self.project.still_secs(), |
| 6909 | speech_model: self.project.speech_model().map(str::to_string), |
| 6910 | speech_device: self.project.speech_device(), |
| 6911 | } |
| 6912 | } |
| 6913 | |
| 6914 | /// One undo step for a change to the project's own settings, taken after |
| 6915 | /// the change: `from` is the state the door found, and what the project |
| 6916 | /// does with the two values is [`Project::push_settings_step`]'s. |
| 6917 | fn step_settings(&mut self, from: ProjectSettings) { |
| 6918 | let now = self.settings_value(); |
| 6919 | self.project.push_settings_step(from, now); |
| 6920 | } |
| 6921 | |
| 6922 | /// Puts the project's settings back on this session -- what a step that |
| 6923 | /// restored them leaves for the player to take up. The canvas, the rate and |
| 6924 | /// the switches live here, and the rendition and the limiter are the |
| 6925 | /// project's own, already back in place by the time this runs. Every lane |
| 6926 | /// edit's entry comes through here too and moves nothing, which is the |
| 6927 | /// common case; the *rate* is the one that needs more than the fields, |
| 6928 | /// because every source's frame count is held against it and the conform |
| 6929 | /// that scaled them is not in the entry. |
| 6930 | fn adopt_settings(&mut self) { |
| 6931 | let s = self.project.settings_now(); |
| 6932 | // A project nobody has handed a canvas to: a fresh [`Project`] carries |
| 6933 | // the placeholder ([`ProjectSettings::placeholder`]) and no session is |
| 6934 | // on one -- the entries pushed before the first settings door hold lane |
| 6935 | // edits and that placeholder, and adopting it would zero the canvas. |
| 6936 | if s.frame_rate <= 0.0 { |
| 6937 | return; |
| 6938 | } |
| 6939 | let was = self.meta.frame_rate; |
| 6940 | self.meta.width = s.resolution.0; |
| 6941 | self.meta.height = s.resolution.1; |
| 6942 | self.meta.frame_rate = s.frame_rate; |
| 6943 | self.encoder_seat = s.encoder_seat; |
| 6944 | self.sample_rate = s.sample_rate; |
| 6945 | self.proxies = s.proxies; |
| 6946 | self.auto_proxies = s.auto_proxies; |
| 6947 | if s.frame_rate != was { |
| 6948 | // Within a frame, like the way out ([`Self::set_frame_rate`]'s own |
| 6949 | // caveat): the lane frame numbers came home exactly, out of the |
| 6950 | // entry, and only the per-source lengths are re-derived through the |
| 6951 | // map back. |
| 6952 | let Ok(k) = Rate::from_fps(was, s.frame_rate) else { |
| 6953 | return; |
| 6954 | }; |
| 6955 | for count in &mut self.counts { |
| 6956 | *count = k.timeline_nearest(*count).max(1); |
| 6957 | } |
| 6958 | for rate in &mut self.rates { |
| 6959 | *rate = rate.then(k); |
| 6960 | } |
| 6961 | self.meta.frame_count = k.timeline_nearest(self.meta.frame_count).max(1); |
| 6962 | } |
| 6963 | } |
| 6964 | |
| 6965 | /// [`Self::undo`] and [`Self::redo`] themselves: the project's own step, |
| 6966 | /// and then whatever it restored for the session to take up |
| 6967 | /// ([`Self::adopt_settings`]). Reseeks both halves, so a canvas that moved |
| 6968 | /// is repainted and a proxy switch that flipped reopens the file. |
| 6969 | fn restored_step(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool { |
| 6970 | let before = self.project.sources().to_vec(); |
| 6971 | if !f(&mut self.project) { |
| 6972 | return false; |
| 6973 | } |
| 6974 | // Adopted *before* the reseek below, never after it: everything the |
| 6975 | // reseek reads is one of the settings the entry just put back -- |
| 6976 | // `landing` the rate and the frame count, `picture_path` the switches, |
| 6977 | // the sound the sample rate -- so a landing computed from the values |
| 6978 | // the step *undid* lands on the wrong frame of the right project (and |
| 6979 | // reopens the file through the switch that just went back). |
| 6980 | self.adopt_settings(); |
| 6981 | // A step that put a relinked file's old path back is read again here, |
| 6982 | // before the reseek opens it. |
| 6983 | self.reread_sources(&before); |
| 6984 | self.invalidate(Dirty::Both); |
| 6985 | true |
| 6986 | } |
| 6987 | |
| 6988 | /// Takes `other`'s timeline over as one undo step ([`Project::adopt_as_step`]), |
| 6989 | /// the way a recovery puts an autosave's edits on the saved project it opened. |
| 6990 | /// The settings are adopted and the sources read again exactly as an undo |
| 6991 | /// does it. `false`, with nothing changed, when the project refuses it. |
| 6992 | pub fn adopt_as_step(&mut self, other: &PlaybackSession) -> bool { |
| 6993 | let before = self.project.sources().to_vec(); |
| 6994 | if !self.project.adopt_as_step(&other.project) { |
| 6995 | return false; |
| 6996 | } |
| 6997 | self.adopt_settings(); |
| 6998 | self.reread_sources(&before); |
| 6999 | self.invalidate(Dirty::Both); |
| 7000 | true |
| 7001 | } |
| 7002 | |
| 7003 | /// Measures the sources a step moved or added, against the timeline as it |
| 7004 | /// stands. `before` is the list the step started from: a source whose path |
| 7005 | /// or stream differs from it (a relink undone or redone, an entry adopted |
| 7006 | /// from another project) has its length and rate read again, and so does |
| 7007 | /// one past the end of the counts. A file that can no longer be read keeps |
| 7008 | /// the length it had, or a whole picture's for an entry it never had. |
| 7009 | fn reread_sources(&mut self, before: &[Source]) { |
| 7010 | let now = self.project.sources().to_vec(); |
| 7011 | self.counts.truncate(now.len()); |
| 7012 | self.rates.truncate(now.len()); |
| 7013 | for (i, source) in now.iter().enumerate() { |
| 7014 | if i < self.counts.len() && before.get(i) == Some(source) { |
| 7015 | continue; |
| 7016 | } |
| 7017 | let (count, rate) = match self.measure_source(source) { |
| 7018 | Ok(measured) => measured, |
| 7019 | Err(_) => ( |
| 7020 | self.counts.get(i).copied().unwrap_or(self.meta.frame_count), |
| 7021 | self.rates.get(i).copied().unwrap_or(Rate::REAL_TIME), |
| 7022 | ), |
| 7023 | }; |
| 7024 | if i < self.counts.len() { |
| 7025 | self.counts[i] = count; |
| 7026 | self.rates[i] = rate; |
| 7027 | } else { |
| 7028 | self.counts.push(count); |
| 7029 | self.rates.push(rate); |
| 7030 | } |
| 7031 | } |
| 7032 | } |
| 7033 | |
| 7034 | /// The frame count and the rate `source`'s file has on this timeline: what a |
| 7035 | /// relink measures a new file by, and what an undo measures the file it puts |
| 7036 | /// back by. The file must be the kind and the material the timeline holds, |
| 7037 | /// as [`Self::relink_source`] checks it. |
| 7038 | fn measure_source(&mut self, source: &Source) -> crate::Result<(u32, Rate)> { |
| 7039 | let path = source.path.as_path(); |
| 7040 | let first = self.first_audio()?; |
| 7041 | if crate::is_image(path) { |
| 7042 | crate::decode::image_size(path)?; |
| 7043 | Ok((image_frames(self.meta.frame_rate), Rate::REAL_TIME)) |
| 7044 | } else if crate::is_audio(path) { |
| 7045 | audio_matches(source, &first)?; |
| 7046 | Ok((audio_frames(path, self.meta.frame_rate)?, Rate::REAL_TIME)) |
| 7047 | } else { |
| 7048 | let (other, _) = Demuxer::open(path)?; |
| 7049 | let rate = matches_timeline(source, &other, &self.meta, &first)?; |
| 7050 | Ok((rate.timeline_at(other.frame_count), rate)) |
| 7051 | } |
| 7052 | } |
| 7053 | |
| 7054 | fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool { |
| 7055 | let done = f(&mut self.project); |
| 7056 | self.project.settle(); |
| 7057 | if !done { |
| 7058 | return false; |
| 7059 | } |
| 7060 | self.invalidate(dirty); |
| 7061 | true |
| 7062 | } |
| 7063 | |
| 7064 | /// Where an edit rebuilds from: the clock, except at the end of a played-out |
| 7065 | /// timeline, where the clock has kept running on wall time and the edit |
| 7066 | /// resumes at the end the viewer saw (so a paste there plays the pasted clip). |
| 7067 | fn playhead(&self) -> f64 { |
| 7068 | match self.eos { |
| 7069 | true => self.now().min(self.eos_end), |
| 7070 | false => self.now(), |
| 7071 | } |
| 7072 | } |
| 7073 | |
| 7074 | /// Rebuilds the dirtied half (or both) at the playhead. |
| 7075 | fn invalidate(&mut self, dirty: Dirty) { |
| 7076 | match dirty { |
| 7077 | Dirty::Picture => { |
| 7078 | let (_, target) = self.landing(self.playhead()); |
| 7079 | self.start_picture(target); |
| 7080 | } |
| 7081 | Dirty::Sound => self.reseek_audio(), |
| 7082 | Dirty::Both => { |
| 7083 | let now = self.playhead(); |
| 7084 | self.seek(now); |
| 7085 | } |
| 7086 | } |
| 7087 | } |
| 7088 | |
| 7089 | /// Says how big the picture is on screen, in device pixels -- what a |
| 7090 | /// front-end showing this session pushes once it knows where the picture |
| 7091 | /// actually lands. Rendering a 1080p project's visualizer for a 600 px |
| 7092 | /// preview costs nine times the pixels for nothing the eye can see; a |
| 7093 | /// window that is fullscreen gets the project's own size back by pushing |
| 7094 | /// it. `true` when the size moved enough to be worth a new picture: under |
| 7095 | /// 8 px on both axes is a resize nobody can see, and a window being |
| 7096 | /// dragged would otherwise restart the picture every tick. |
| 7097 | pub fn set_view_size(&mut self, width: u32, height: u32) -> bool { |
| 7098 | let want = self.view_want(width, height); |
| 7099 | match self.view { |
| 7100 | Some(now) if now.0.abs_diff(want.0) < 8 && now.1.abs_diff(want.1) < 8 => false, |
| 7101 | _ => { |
| 7102 | self.view = Some(want); |
| 7103 | true |
| 7104 | } |
| 7105 | } |
| 7106 | } |
| 7107 | |
| 7108 | /// [`Self::set_view_size`] with no deadband: what asks for the *exact* |
| 7109 | /// size rather than one within 8 px of it. A still saved at the project's |
| 7110 | /// own pixels is a file whose dimensions are read back, so "close enough |
| 7111 | /// to be invisible" is not close enough to be right. `true` when the view |
| 7112 | /// moved, `false` when it was already there -- which is also the answer |
| 7113 | /// that lets a caller skip waiting for a frame it already has. |
| 7114 | pub fn set_view_size_exact(&mut self, width: u32, height: u32) -> bool { |
| 7115 | let want = self.view_want(width, height); |
| 7116 | match self.view { |
| 7117 | Some(now) if now == want => false, |
| 7118 | _ => { |
| 7119 | self.view = Some(want); |
| 7120 | true |
| 7121 | } |
| 7122 | } |
| 7123 | } |
| 7124 | |
| 7125 | /// The size a push of `(width, height)` settles on: even on both axes |
| 7126 | /// (YUV 4:2:0 has no odd chroma) and never past the project's own. |
| 7127 | fn view_want(&self, width: u32, height: u32) -> (u32, u32) { |
| 7128 | let fit = |n: u32, cap: u32| (n & !1).clamp(2, cap.max(2)); |
| 7129 | (fit(width, self.meta.width), fit(height, self.meta.height)) |
| 7130 | } |
| 7131 | |
| 7132 | /// The canvas a span's pictures are painted at: [`Self::set_view_size`]'s |
| 7133 | /// size once one has been pushed, the project's own otherwise. |
| 7134 | pub fn view_size(&self) -> (u32, u32) { |
| 7135 | self.view.unwrap_or((self.meta.width, self.meta.height)) |
| 7136 | } |
| 7137 | |
| 7138 | /// Current timeline position in seconds. |
| 7139 | pub fn now(&self) -> f64 { |
| 7140 | self.clock.now() |
| 7141 | } |
| 7142 | |
| 7143 | pub fn is_playing(&self) -> bool { |
| 7144 | self.clock.is_playing() |
| 7145 | } |
| 7146 | |
| 7147 | pub fn play(&mut self) { |
| 7148 | if self.clock.is_playing() { |
| 7149 | return; |
| 7150 | } |
| 7151 | // Invariant: the clock is positioned *before* audio restarts. Audio |
| 7152 | // reports are relative to the first one after that, so a seek would go |
| 7153 | // here too -- `clock.seek_to(t)` and then `set_active(true)`. |
| 7154 | self.clock.play(); |
| 7155 | // Above or below 1x the sound stays off: `set_rate(1.0)` brings it back. |
| 7156 | if let Some(audio) = self.audio.as_ref().filter(|_| self.clock.rate() == 1.0) { |
| 7157 | audio.set_playing(true); |
| 7158 | } |
| 7159 | } |
| 7160 | |
| 7161 | /// Sets the playback speed: 1.0 is real time, 2/4/8 forward, -1/-2 backward. |
| 7162 | /// |
| 7163 | /// Anything but 1x runs the clock on wall time at that rate and keeps the |
| 7164 | /// sound silent -- audio cannot play backward or fast without a stretch the |
| 7165 | /// engine does not do here. Going back to 1x reopens the sound at the |
| 7166 | /// current position, as a seek does. Drawing the picture backward is not |
| 7167 | /// done for the sound; the picture is, from the playhead down ([`Back`]), and |
| 7168 | /// turning the clock round restarts it there. |
| 7169 | pub fn set_rate(&mut self, rate: f64) { |
| 7170 | if !rate.is_finite() || rate == 0.0 || rate == self.clock.rate() { |
| 7171 | return; |
| 7172 | } |
| 7173 | let was_backward = self.backward(); |
| 7174 | if rate != 1.0 { |
| 7175 | if let Some(audio) = &self.audio { |
| 7176 | audio.set_playing(false); |
| 7177 | } |
| 7178 | self.clock.set_rate(rate); |
| 7179 | } else { |
| 7180 | self.clock.set_rate(1.0); |
| 7181 | if self.audio.is_some() { |
| 7182 | self.reseek_audio(); |
| 7183 | } |
| 7184 | } |
| 7185 | if was_backward != self.backward() { |
| 7186 | let (_, target) = self.landing(self.now()); |
| 7187 | self.start_picture(target); |
| 7188 | } |
| 7189 | } |
| 7190 | |
| 7191 | pub fn pause(&mut self) { |
| 7192 | if !self.clock.is_playing() { |
| 7193 | return; |
| 7194 | } |
| 7195 | if let Some(audio) = &self.audio { |
| 7196 | audio.set_playing(false); |
| 7197 | } |
| 7198 | self.clock.pause(); |
| 7199 | } |
| 7200 | |
| 7201 | pub fn toggle(&mut self) { |
| 7202 | if self.clock.is_playing() { |
| 7203 | self.pause() |
| 7204 | } else { |
| 7205 | self.play() |
| 7206 | } |
| 7207 | } |
| 7208 | |
| 7209 | /// Stops the transport where the timeline stops: the clock is paused and put |
| 7210 | /// on the out point. |
| 7211 | /// |
| 7212 | /// Playing past the last frame is wall time counting on past the end of the |
| 7213 | /// media -- there is no picture left to pace it -- so a session left at EOF |
| 7214 | /// reports a `now()` that walks off the end of the timeline in real time, |
| 7215 | /// and a caller that reads the playhead (a cut, a paste, an insert) then |
| 7216 | /// acts at a position no clip is at. How far off depends only on how long |
| 7217 | /// the window was left open, so no clamp in a caller is worth writing. |
| 7218 | /// |
| 7219 | /// End of stream is deliberately left set: the picture is still the last |
| 7220 | /// frame and this is still the end. That is what makes it safe to call on |
| 7221 | /// the crossing into it -- the state the transport shows does not change, |
| 7222 | /// only the running clock stops. |
| 7223 | /// Carries the clock on past the last frame, on wall time from where it stands, for a |
| 7224 | /// take that runs longer than the timeline. The audio is stopped with it: nothing is |
| 7225 | /// left to play. A no-op unless the clock runs on the audio device. |
| 7226 | pub fn run_past_end(&mut self) { |
| 7227 | if self.clock.source() != ClockSource::Audio { |
| 7228 | return; |
| 7229 | } |
| 7230 | if let Some(audio) = &self.audio { |
| 7231 | audio.set_playing(false); |
| 7232 | } |
| 7233 | self.clock.switch_to_wall(); |
| 7234 | } |
| 7235 | |
| 7236 | pub fn halt_at_end(&mut self) { |
| 7237 | self.pause(); |
| 7238 | // Played backward the end it ran into is the start, and the rate goes back |
| 7239 | // to real time there: the next press plays on from the top. |
| 7240 | if self.backward() { |
| 7241 | self.set_rate(1.0); |
| 7242 | self.clock.seek_to(0.0); |
| 7243 | // The picture restart above cleared it; this is still the end. |
| 7244 | self.eos = true; |
| 7245 | return; |
| 7246 | } |
| 7247 | self.clock.seek_to(self.timeline_duration()); |
| 7248 | } |
| 7249 | |
| 7250 | /// The gain this session's device is running at, read back from the device |
| 7251 | /// rather than remembered here: `None` with no audio output, or a plugin |
| 7252 | /// too old to answer -- the two cases where a remembered answer would be a |
| 7253 | /// claim nothing can check. |
| 7254 | pub fn gain(&self) -> Option<f32> { |
| 7255 | self.audio.as_ref()?.ao.lock().unwrap().gain() |
| 7256 | } |
| 7257 | |
| 7258 | /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0: |
| 7259 | /// one knob, because muting and turning it down are the same thing to the |
| 7260 | /// device, and *which* the user meant is a question only the UI can answer |
| 7261 | /// -- it keeps the level to come back to. |
| 7262 | /// |
| 7263 | /// The level is remembered for as long as this session lives |
| 7264 | /// ([`Audio::gain`]) and only so that a device which is *replaced* under |
| 7265 | /// the session -- re-armed after a death, armed by a late import -- comes |
| 7266 | /// back at the level the session was already running at. It is still not |
| 7267 | /// project state: a fresh session starts at 1.0, so a caller still pushes |
| 7268 | /// it once per session, and an export -- which renders the file rather |
| 7269 | /// than what the speakers are doing -- can never pick it up. Silent with |
| 7270 | /// no audio device, which is also the only honest answer there. |
| 7271 | /// |
| 7272 | /// Mute is not pause: the samples are still consumed and the device clock |
| 7273 | /// still runs, so the picture keeps playing against it. |
| 7274 | pub fn set_gain(&self, gain: f32) -> bool { |
| 7275 | match &self.audio { |
| 7276 | // The device is the owner and is told first: a remembered level |
| 7277 | // that says something the device does not agree with is worse |
| 7278 | // than no memory at all, because the next replacement would |
| 7279 | // restore the wrong number. |
| 7280 | Some(audio) if audio.ao.lock().unwrap().set_volume(gain) => { |
| 7281 | audio.gain.store(gain.to_bits(), Ordering::Release); |
| 7282 | true |
| 7283 | } |
| 7284 | _ => false, |
| 7285 | } |
| 7286 | } |
| 7287 | |
| 7288 | /// A copy of the most recent mono samples the device was handed, and the |
| 7289 | /// rate they play at: the signal *after* every clip's equalizer, speed and |
| 7290 | /// the mix, which is what an analyser drawn behind an EQ curve has to show. |
| 7291 | /// `None` with no audio output at all, and empty until the feeder has |
| 7292 | /// written once (right after a seek, for instance). |
| 7293 | /// |
| 7294 | /// Never blocks anything that matters: the feeder holds this lock for one |
| 7295 | /// memcpy and the device's own callback lives in the plugin, on the far |
| 7296 | /// side of a ring buffer, where it cannot see this at all. |
| 7297 | pub fn audio_tap(&self) -> Option<(Vec<f32>, u32)> { |
| 7298 | let audio = self.audio.as_ref()?; |
| 7299 | let tap = audio.tap.lock().unwrap().clone(); |
| 7300 | Some((tap, audio.sample_rate)) |
| 7301 | } |
| 7302 | |
| 7303 | /// Says that this session is being **watched in real time**, so a picture |
| 7304 | /// whose moment has passed is worth nothing and the decode worker may drop |
| 7305 | /// it where it is cheap to drop -- before the conversion (a full BGRA pass |
| 7306 | /// over 8 MB at 1080p) and before the queue. |
| 7307 | /// |
| 7308 | /// Off by default, and that is the contract every *pull* consumer relies on: |
| 7309 | /// an export, the file-level [`DecodeSession`] API and a test draining as |
| 7310 | /// fast as it can all ask for a range of frames and must be given every one |
| 7311 | /// of them, in order. Only a viewer has a moment for a picture to be past. |
| 7312 | /// |
| 7313 | /// A front-end that turns this on was dropping those very frames itself, one |
| 7314 | /// repaint later (`Player::pump` takes everything due and shows the last): |
| 7315 | /// what changes is where the work stops, and therefore how quickly a decoder |
| 7316 | /// that fell behind catches up. |
| 7317 | /// |
| 7318 | /// It does not replace [`resync_picture`](Self::resync_picture): both |
| 7319 | /// mechanisms are live and this one is the first line. It catches up without |
| 7320 | /// restarting anything, which is why the front-end's resync -- a picture |
| 7321 | /// restart, once per `RESYNC_GAP` -- now fires only where dropping was not |
| 7322 | /// enough (a decoder so far behind that even one picture in nine |
| 7323 | /// ([`crate::decode`]'s `LATE_RUN`) cannot close the gap). |
| 7324 | pub fn drop_late_pictures(&mut self, on: bool) { |
| 7325 | self.drop_late = on; |
| 7326 | } |
| 7327 | |
| 7328 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode |
| 7329 | /// workers are replaced rather than steered: a fresh channel cannot hold a |
| 7330 | /// stale frame, and it works just as well after EOF, where the old workers |
| 7331 | /// have already exited. |
| 7332 | /// |
| 7333 | /// Playing stays playing and paused stays paused -- but a paused seek still |
| 7334 | /// decodes, so the caller can show the frame it landed on. |
| 7335 | pub fn seek(&mut self, secs: f64) { |
| 7336 | let (t, target) = self.landing(secs); |
| 7337 | let was_playing = self.clock.is_playing(); |
| 7338 | self.stop_audio(); |
| 7339 | self.start_picture(target); |
| 7340 | if self.clock.rate() != 1.0 { |
| 7341 | // Sound stays silent off-speed; `set_rate(1.0)` reopens it here. |
| 7342 | self.clock.seek_to(t); |
| 7343 | return; |
| 7344 | } |
| 7345 | let audio_running = self.start_audio(target); |
| 7346 | // Same invariant as `play`: position the clock before audio restarts. |
| 7347 | if audio_running && self.clock.source() != ClockSource::Audio { |
| 7348 | self.clock.switch_to_audio(); |
| 7349 | } |
| 7350 | self.clock.seek_to(t); |
| 7351 | self.resume(was_playing); |
| 7352 | } |
| 7353 | |
| 7354 | /// Abandons whatever the picture worker still owes and restarts it at the |
| 7355 | /// clock. The sound and the clock are untouched -- this is the *video* |
| 7356 | /// catching up to its master, not a seek -- so nothing the ear is following |
| 7357 | /// moves, and a caller that is behind by more than it can watch calls this |
| 7358 | /// instead of waiting for a decoder that only falls further back |
| 7359 | /// (`Player::pump`). |
| 7360 | pub fn resync_picture(&mut self) { |
| 7361 | self.invalidate(Dirty::Picture); |
| 7362 | } |
| 7363 | |
| 7364 | /// Where a seek to `secs` lands: the clamped timeline position and the |
| 7365 | /// timeline frame it means. The one place the clamp lives, so every |
| 7366 | /// invalidation below lands on the same frame a seek would. |
| 7367 | fn landing(&self, secs: f64) -> (f64, u32) { |
| 7368 | let fps = self.meta.frame_rate; |
| 7369 | let total = self.project.timeline_frames(); |
| 7370 | let t = secs.clamp(0.0, f64::from(total) / fps); |
| 7371 | (t, secs_to_frame(t, fps).min(total.saturating_sub(1))) |
| 7372 | } |
| 7373 | |
| 7374 | /// Rebuilds the **picture** at `target` and touches nothing else: the sound |
| 7375 | /// keeps playing out of the same stream, the clock keeps running, and a |
| 7376 | /// grade dragged during playback is therefore silent. |
| 7377 | fn start_picture(&mut self, target: u32) { |
| 7378 | // Abandon first, drop second: the old worker may be parked in `send` on |
| 7379 | // the bounded channel, where only the disconnect wakes it -- and it |
| 7380 | // then finds the span already superseded. The *thread* is kept, and |
| 7381 | // with it the open file and the open decoder, so a seek onto the same |
| 7382 | // source costs a demuxer seek and a decoder flush rather than the |
| 7383 | // VA-API init (98 ms) a new worker would pay; a worker that cannot take |
| 7384 | // the new span is retired by [`retire`](Self::retire) instead, and |
| 7385 | // nothing on this thread joins either way. |
| 7386 | self.worker.abandon(); |
| 7387 | // The span runs from `target` to the end of whatever it landed in -- a |
| 7388 | // clip, or a gap, which starts a black-frame worker instead. `None` is |
| 7389 | // the emptied timeline, black too, and `start_span` says so. |
| 7390 | let span = match self.backward() { |
| 7391 | true => back_span_at(&self.project.render_view(), target), |
| 7392 | false => crate::export::stack_span_at(&self.project.render_view(), target), |
| 7393 | }; |
| 7394 | self.start_span(span); |
| 7395 | self.eos = false; |
| 7396 | } |
| 7397 | |
| 7398 | /// Silences the device and supersedes whatever is feeding it: the first half |
| 7399 | /// of every audio restart, and the only thing that ever discards queued |
| 7400 | /// sound. |
| 7401 | fn stop_audio(&mut self) { |
| 7402 | self.mix = None; |
| 7403 | if let Some(audio) = &self.audio { |
| 7404 | let ao = audio.ao.lock().unwrap(); |
| 7405 | ao.set_active(false); |
| 7406 | // Bumped and flushed while holding the device lock, because the |
| 7407 | // feeder re-checks the epoch inside that same lock: whatever it is |
| 7408 | // carrying can no longer reach the ring after this point. |
| 7409 | audio.epoch.fetch_add(1, Ordering::Release); |
| 7410 | // Nothing of the new stream has been played yet, by definition. |
| 7411 | audio.content_at.store(-1, Ordering::Release); |
| 7412 | ao.flush(); |
| 7413 | // The flushed samples are not being played any more, so nothing may |
| 7414 | // still be drawn from them. |
| 7415 | audio.tap.lock().unwrap().clear(); |
| 7416 | } |
| 7417 | } |
| 7418 | |
| 7419 | /// Puts the device back where it was: playing if it was playing, and with |
| 7420 | /// the clock held until the new stream is really audible (see |
| 7421 | /// [`Audio::content_at`]). |
| 7422 | /// |
| 7423 | /// Only the *intent* is set here: the open runs on the feeder |
| 7424 | /// ([`start_audio`](Self::start_audio)), so the device is started by that |
| 7425 | /// stream's first real sample instead ([`Audio::wants_active`]). A device |
| 7426 | /// made active over an empty ring plays its own silence and counts one |
| 7427 | /// underrun per starved quantum -- a scripted cold play-seek-scrub session |
| 7428 | /// used to go from 5 to 1721 of them -- while the ear hears the same silence |
| 7429 | /// either way, so nothing is gained for the count that is lost. |
| 7430 | fn resume(&mut self, was_playing: bool) { |
| 7431 | self.priming = true; |
| 7432 | if let Some(audio) = &self.audio { |
| 7433 | audio.set_playing(was_playing); |
| 7434 | } |
| 7435 | } |
| 7436 | |
| 7437 | /// Rebuilds the **sound** from `target` -- the second half of a restart -- |
| 7438 | /// and says whether a feeder took the job. Not whether it will find |
| 7439 | /// anything to play: the stream is opened on that feeder |
| 7440 | /// ([`Audio::spawn_feeder_deferred`]), so a silent timeline is heard of |
| 7441 | /// there, not here. Nothing on this thread reads the file. |
| 7442 | /// |
| 7443 | /// The clock is unaffected by the wait, which is the reason it may be a |
| 7444 | /// long one: it holds where the seek put it until the *first real sample* |
| 7445 | /// is queued ([`Audio::content_at`], [`tick`](Self::tick)), whether that is |
| 7446 | /// ten milliseconds later or ten seconds. |
| 7447 | /// |
| 7448 | /// `true` is therefore *optimistic*, and the callers' `switch_to_audio` with |
| 7449 | /// it: a timeline that turns out to have nothing to play ends its feeder at |
| 7450 | /// once, which sets `fed_all` and hands the clock back to wall time at the |
| 7451 | /// next tick, from where it stood ([`PlaybackClock::switch_to_wall`] is |
| 7452 | /// continuous, so nothing jumps). |
| 7453 | fn start_audio(&mut self, target: u32) -> bool { |
| 7454 | let fps = self.meta.frame_rate; |
| 7455 | let mut audio_running = false; |
| 7456 | let mut live = None; |
| 7457 | // A dead output gets an attempt here without waiting out the cooldown: a |
| 7458 | // seek is a person asking, and this is the one moment the sound can come |
| 7459 | // back into step with the picture, because the feeder opened below starts |
| 7460 | // at the target. If it does not come back the flag stands and the guard |
| 7461 | // under it leaves the clock on wall time. |
| 7462 | self.rearm_audio(Duration::ZERO); |
| 7463 | if let Some(audio) = &self.audio |
| 7464 | && !audio.died.load(Ordering::Acquire) |
| 7465 | { |
| 7466 | // The device position keeps counting across a flush, so re-basing |
| 7467 | // `fed` on it is what keeps `played_out` exact for the new stream. |
| 7468 | let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64; |
| 7469 | audio.fed.store(played * audio.channels, Ordering::Relaxed); |
| 7470 | audio.fed_all.store(false, Ordering::Release); |
| 7471 | // One worker for the whole rest of the timeline, so the joins |
| 7472 | // between clips are gapless: the video reopens at a boundary, the |
| 7473 | // ear never hears it -- and a join between two *files* is just |
| 7474 | // another segment, because every segment names its own source. |
| 7475 | // One play list per audio lane, summed by the mixer: what the ear |
| 7476 | // hears is every lane at once, and a lane's own gaps are silence in |
| 7477 | // it rather than a hole in the count the master clock keeps. |
| 7478 | let segs = self.project.render_view().audio_segments_from(target, fps); |
| 7479 | // The equalizers beside them, one per segment: the worker filters a |
| 7480 | // segment's own samples before the mix, so a clip's curve reaches |
| 7481 | // that clip and stops. Rebuilt on every seek, which is what makes an |
| 7482 | // EQ edit audible at once -- `edit` reseeks, so the drag that |
| 7483 | // changed a band restarts the workers with the new curve already in |
| 7484 | // them, and no live channel has to reach into a running one. |
| 7485 | let eqs = self.project.render_view().audio_eqs_from(target, fps); |
| 7486 | // ...and the rates, the same way again: a speeded segment is |
| 7487 | // resampled inside its own worker, before the mix, so what the ear |
| 7488 | // hears is what the timeline shows. Empty for a project nobody has |
| 7489 | // speeded, which is the path that decodes the same samples it always |
| 7490 | // did. |
| 7491 | let speeds = self.project.render_view().audio_speeds_from(target, fps); |
| 7492 | // ...and the fades, the same way again: a clip's own envelope runs |
| 7493 | // inside its worker, after the rate and the equalizer, so a fade |
| 7494 | // edit is audible at once exactly as an EQ edit is. |
| 7495 | let fades = self.project.render_view().audio_fades_from(target, fps); |
| 7496 | // Each source on the stream it was placed with: what plays is what |
| 7497 | // the library row said, and what an export copies (`export::run`). |
| 7498 | let sources = self.project.audio_sources(); |
| 7499 | // ...and the mix settings over the lot: each lane's own volume on |
| 7500 | // its way into the sum and the master limiter over the sum. These |
| 7501 | // two are handed over *live* as well as at the open: they sit at |
| 7502 | // the sum, where nothing is decoded, so a fader moved later is a |
| 7503 | // number the running mixer picks up rather than a stream rebuilt |
| 7504 | // under the ear ([`crate::audio::MixControls`]). |
| 7505 | let gains = self.mix_gains(); |
| 7506 | let ducks = self.project.render_view().audio_ducks(); |
| 7507 | // ...and the voice processors, which are not live: an edit to one |
| 7508 | // rebuilds the sound like an equalizer edit does. |
| 7509 | let voices = self.project.render_view().audio_voices(); |
| 7510 | let limiter = self.project.limiter(); |
| 7511 | let controls = crate::audio::MixControls::new(gains.clone(), ducks.clone(), limiter); |
| 7512 | // Only a mixed timeline has a mixer to talk to; the single-lane |
| 7513 | // flat path is the bit-exact one and has none. Decided here from |
| 7514 | // the very lists the open is about to be handed |
| 7515 | // ([`AudioSession::is_mixed`]) rather than read off the handle |
| 7516 | // afterwards, because there *is* no afterwards on this thread any |
| 7517 | // more -- the open runs on the feeder. |
| 7518 | let mixed = crate::audio::AudioSession::is_mixed(segs.len(), &gains, limiter, &voices); |
| 7519 | let worker_controls = Arc::clone(&controls); |
| 7520 | // ...and the rate the mix runs at, if the project picked one: the |
| 7521 | // same override [`crate::edith::save`] writes and [`Self::open_project`] |
| 7522 | // reads back. |
| 7523 | let sample_rate = self.sample_rate; |
| 7524 | // ...and the open itself -- every track a segment names, its packet |
| 7525 | // table, its priming -- happens there too. That is the whole point: |
| 7526 | // one `pread` on a cold 25 GB film is seconds, and this is called |
| 7527 | // from a ruler drag ([`Audio::spawn_feeder_deferred`]). |
| 7528 | audio_running = audio.spawn_feeder_deferred(move || { |
| 7529 | match AudioSession::open_mixed_streams_live_fade( |
| 7530 | &sources, |
| 7531 | &segs, |
| 7532 | &eqs, |
| 7533 | &speeds, |
| 7534 | &fades, |
| 7535 | fps, |
| 7536 | &gains, |
| 7537 | &ducks, |
| 7538 | &voices, |
| 7539 | limiter, |
| 7540 | Some(&worker_controls), |
| 7541 | sample_rate, |
| 7542 | ) { |
| 7543 | Ok(Some((_, rx))) => Some(rx), |
| 7544 | // A silent timeline, and a source that will not open: both |
| 7545 | // feed nothing, which the feeder itself reports by ending. |
| 7546 | // The mix goes with them -- no mixer was started, so a fader |
| 7547 | // moved later must rebuild the sound rather than hand its |
| 7548 | // number to a thread that does not exist |
| 7549 | // ([`crate::audio::MixControls::detach`]). |
| 7550 | Ok(None) => { |
| 7551 | worker_controls.detach(); |
| 7552 | None |
| 7553 | } |
| 7554 | Err(e) => { |
| 7555 | worker_controls.detach(); |
| 7556 | // A read this session abandoned on purpose -- the seek |
| 7557 | // after it, or the session going away -- is not a file |
| 7558 | // that would not open, and says nothing. |
| 7559 | if !crate::demux::is_cancelled(&e) && std::env::var_os("EDITH_DEBUG").is_some() { |
| 7560 | eprintln!("timeline audio open failed: {e}"); |
| 7561 | } |
| 7562 | None |
| 7563 | } |
| 7564 | } |
| 7565 | }); |
| 7566 | live = (audio_running && mixed).then_some(controls); |
| 7567 | if !audio_running { |
| 7568 | // Nothing will ever be fed again; let `tick` fall to wall time |
| 7569 | // instead of waiting on a device that has no more work coming. |
| 7570 | audio.fed_all.store(true, Ordering::Release); |
| 7571 | } |
| 7572 | } |
| 7573 | self.mix = live; |
| 7574 | audio_running |
| 7575 | } |
| 7576 | |
| 7577 | /// Rebuilds the sound alone, from where the playhead is: what a change that |
| 7578 | /// no picture can show goes through. The video worker is left decoding, so |
| 7579 | /// the picture does not blink -- and the clock, held still by |
| 7580 | /// [`resume`](Self::resume) until the new stream is audible, puts the sound |
| 7581 | /// back exactly where the picture already is. |
| 7582 | /// |
| 7583 | /// End of stream is deliberately left alone -- no picture worker is started |
| 7584 | /// here, so a timeline that was played out still is; see |
| 7585 | /// [`is_eos`](Self::is_eos). |
| 7586 | fn reseek_audio(&mut self) { |
| 7587 | if self.clock.rate() != 1.0 { |
| 7588 | // Off-speed the sound is silent and `set_rate(1.0)` rebuilds it, so a |
| 7589 | // change to it now has nothing to rebuild. |
| 7590 | return; |
| 7591 | } |
| 7592 | let (t, target) = self.landing(self.now()); |
| 7593 | let was_playing = self.clock.is_playing(); |
| 7594 | self.stop_audio(); |
| 7595 | let audio_running = self.start_audio(target); |
| 7596 | if audio_running && self.clock.source() != ClockSource::Audio { |
| 7597 | self.clock.switch_to_audio(); |
| 7598 | } |
| 7599 | self.clock.seek_to(t); |
| 7600 | self.resume(was_playing); |
| 7601 | } |
| 7602 | |
| 7603 | /// Renders the edited timeline to `out` on a worker thread. The session is |
| 7604 | /// untouched -- the export decodes the source file for itself -- but a |
| 7605 | /// caller should still [`pause`](PlaybackSession::pause) first, because |
| 7606 | /// playback and export otherwise fight over the same decoder hardware. |
| 7607 | /// |
| 7608 | /// Later edits do not reach a running export: it works from a snapshot of |
| 7609 | /// the edit list taken here. |
| 7610 | /// |
| 7611 | /// corner-cut: this defaults the settings; the app still calls it that way, |
| 7612 | /// and the export options card replaces the call with |
| 7613 | /// [`export_to_with`](PlaybackSession::export_to_with). |
| 7614 | pub fn export_to(&self, out: &Path) -> crate::ExportHandle { |
| 7615 | self.export_to_with(out, &crate::export::ExportSettings::default()) |
| 7616 | } |
| 7617 | |
| 7618 | /// [`export_to`](PlaybackSession::export_to) with the output settings spelled |
| 7619 | /// out rather than defaulted. |
| 7620 | pub fn export_to_with( |
| 7621 | &self, |
| 7622 | out: &Path, |
| 7623 | settings: &crate::export::ExportSettings, |
| 7624 | ) -> crate::ExportHandle { |
| 7625 | // The chapter marks, measured from the export's own start (the range's |
| 7626 | // `from`, the same clock `chapter_list_ns` uses). A caller's list wins. |
| 7627 | let mut settings = settings.clone(); |
| 7628 | if settings.chapters.is_empty() { |
| 7629 | settings.chapters = self.chapter_list_ns(settings.range); |
| 7630 | } |
| 7631 | let mut snapshot = self.project.export_snapshot(); |
| 7632 | // A range that never reads a missing file is written without opening it. |
| 7633 | if let Some(range) = settings.range { |
| 7634 | snapshot.drop_offline_outside(range, crate::source_present); |
| 7635 | } |
| 7636 | crate::export::start(snapshot, self.meta, out, &settings, self.sample_rate) |
| 7637 | } |
| 7638 | |
| 7639 | /// Moves the clock forward; the caller runs this once per rendered frame. |
| 7640 | /// Costs an atomic load, and once per session a mode switch. |
| 7641 | pub fn tick(&mut self) { |
| 7642 | // Before every early return below: where the playhead stands is what the |
| 7643 | // decode worker drops its stale pictures against, and a front-end that |
| 7644 | // repaints without draining (a slow frame, a busy render thread) must |
| 7645 | // still be moving it -- otherwise the queue fills with pictures whose |
| 7646 | // moment passed while nobody was taking them. |
| 7647 | self.publish_playhead(); |
| 7648 | // Before the clock-source guard below, and not after it: a dead output is |
| 7649 | // what *puts* the clock on wall time, so this branch has to keep running |
| 7650 | // while it is there -- the one attempt that can bring the sound back is |
| 7651 | // in it. |
| 7652 | if self |
| 7653 | .audio |
| 7654 | .as_ref() |
| 7655 | .is_some_and(|audio| audio.died.load(Ordering::Acquire)) |
| 7656 | { |
| 7657 | // Output died mid-stream: its position will never reach `fed`, so the |
| 7658 | // EOF comparison below is unreachable. Wall time takes over from |
| 7659 | // wherever the clock last stood, and the session says so rather than |
| 7660 | // going silent for good without a word: a front-end already has a |
| 7661 | // line for a silent session ([`Self::audio_disabled_reason`]). |
| 7662 | if self.audio_disabled.is_none() { |
| 7663 | self.audio_disabled = Some(AUDIO_LOST.to_string()); |
| 7664 | } |
| 7665 | self.clock.switch_to_wall(); |
| 7666 | // ...and the output is offered another open, once a second: a |
| 7667 | // restarting daemon takes a moment, and this runs once a frame. A |
| 7668 | // re-arm that takes is what clears the notice, and the next seek |
| 7669 | // feeds it. |
| 7670 | self.rearm_audio(AUDIO_REARM_AFTER); |
| 7671 | return; |
| 7672 | } |
| 7673 | let Some(audio) = &self.audio else { |
| 7674 | return; // wall time from the start, nothing to poll |
| 7675 | }; |
| 7676 | if self.clock.source() != ClockSource::Audio { |
| 7677 | return; |
| 7678 | } |
| 7679 | // `None` until the device's first callback: the clock holds at its |
| 7680 | // anchor rather than guessing, which is why playback starts on time |
| 7681 | // instead of a quantum early. |
| 7682 | let Some(position) = audio.ao.lock().unwrap().position() else { |
| 7683 | return; |
| 7684 | }; |
| 7685 | if audio.played_out(position) { |
| 7686 | // Audio EOF. Wall time carries the same timeline on from here, with |
| 7687 | // no jump, and this branch cannot be reached again. |
| 7688 | // |
| 7689 | // The device is stopped with it: nothing will ever be queued for |
| 7690 | // this stream again, so every quantum it would go on playing is |
| 7691 | // silence counted as a decoder that fell behind -- the tail of a |
| 7692 | // stream, where [`crate::ao`]'s own `primed` covers the head of |
| 7693 | // one. A seek from here starts it again like any other |
| 7694 | // ([`resume`](Self::resume)), which is why the stamp goes with it: |
| 7695 | // there is no sample of *this* stream left to start on. |
| 7696 | audio.set_playing(false); |
| 7697 | audio.content_at.store(-1, Ordering::Release); |
| 7698 | self.clock.switch_to_wall(); |
| 7699 | return; |
| 7700 | } |
| 7701 | if self.priming { |
| 7702 | // A stream that has been started and has not been heard yet: the |
| 7703 | // device is playing the silence of its own restart, and none of it |
| 7704 | // is timeline time ([`Audio::content_at`]). The clock holds where |
| 7705 | // the seek left it -- so the picture holds too, on the frame it |
| 7706 | // landed on, rather than sliding ahead of a sound that has not |
| 7707 | // started. |
| 7708 | let started = audio.content_at.load(Ordering::Acquire); |
| 7709 | if started < 0 { |
| 7710 | return; |
| 7711 | } |
| 7712 | // ...and then the *first sample of the stream* becomes the |
| 7713 | // reference, not whatever position this poll happened to catch: the |
| 7714 | // clock's own anchor is its first report ([`PlaybackClock`]), and |
| 7715 | // anchoring it here is what makes a mid-play edit cost no offset. |
| 7716 | // |
| 7717 | // corner-cut: `started` is the position when the sample was queued, |
| 7718 | // and it is heard at the next callback -- up to one quantum (5-21 |
| 7719 | // ms) later, so that much of the restart is still counted. Upgrade |
| 7720 | // path is the position at the first *pop* of real audio, which only |
| 7721 | // the plugin's RT thread can see. |
| 7722 | self.clock |
| 7723 | .set_audio_position(started as u64, audio.sample_rate); |
| 7724 | self.priming = false; |
| 7725 | } |
| 7726 | self.clock |
| 7727 | .set_audio_position(position as u64, audio.sample_rate); |
| 7728 | } |
| 7729 | } |
| 7730 | |
| 7731 | impl Drop for PlaybackSession { |
| 7732 | /// The video workers -- the running one and every cancelled one still in |
| 7733 | /// [`retired`](PlaybackSession::retired) -- cancel and join themselves when |
| 7734 | /// those fields drop right after this, the running one behind its receiver |
| 7735 | /// so a `send` cannot hold the join. *That* is what a session must not exit |
| 7736 | /// without: no decode worker outlives it, so none can be inside libva when |
| 7737 | /// Mesa's `atexit` handlers free the state under it. |
| 7738 | /// |
| 7739 | /// This is the audio half: bumping the epoch retires the feeder at its next write, |
| 7740 | /// which drops the decode receiver with it. Neither is waited for -- no |
| 7741 | /// driver state is torn down on the audio side. |
| 7742 | fn drop(&mut self) { |
| 7743 | if let Some(audio) = &self.audio { |
| 7744 | audio.epoch.fetch_add(1, Ordering::Release); |
| 7745 | } |
| 7746 | } |
| 7747 | } |
| 7748 | |
| 7749 | /// Whether `path`, already demuxed to `meta`, may join a timeline whose |
| 7750 | /// parameters are `timeline` and whose audio probes as `first`: a decoder this |
| 7751 | /// machine can open, audio parameters that agree (or no audio at all), and a |
| 7752 | /// frame rate that can be named |
| 7753 | /// against the timeline's. The [`Rate`] it will be read at comes back with the |
| 7754 | /// answer, so the number the check was decided on is the number it plays by. |
| 7755 | /// |
| 7756 | /// *Not* the same size any more. A project has its own resolution |
| 7757 | /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its |
| 7758 | /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a |
| 7759 | /// letterboxed clip rather than a refusal, and so is a frame rate of its own: |
| 7760 | /// the timeline keeps its own rate and the file is read at [`Rate`] against it |
| 7761 | /// ([`PlaybackSession::import`] notes how long it is *here*). Nor the same |
| 7762 | /// codec: every clip opens its own decoder, so a mixed-codec timeline is a |
| 7763 | /// decoder each rather than a refusal. |
| 7764 | /// |
| 7765 | /// The `Err` names the property that disagrees, and those strings are what a |
| 7766 | /// front-end shows verbatim; [`PlaybackSession::import`] and |
| 7767 | /// [`PlaybackSession::open_project`] share them so a file refused at import is |
| 7768 | /// refused in the same words at load. |
| 7769 | fn matches_timeline( |
| 7770 | source: &Source, |
| 7771 | meta: &VideoMeta, |
| 7772 | timeline: &VideoMeta, |
| 7773 | first: &Option<crate::AudioProbe>, |
| 7774 | ) -> crate::Result<Rate> { |
| 7775 | // The codec is *not* held to the timeline's -- every clip opens its own |
| 7776 | // decoder, so an H.264 take and an HEVC one play on one timeline. What the |
| 7777 | // codec gate was really protecting against stays, in the one place that |
| 7778 | // can actually answer it: on a machine without the VA-API plugin an HEVC |
| 7779 | // or VP8 clip would be black frames with the refusal on stderr alone, |
| 7780 | // so the file is asked for a decoder *here*, at the door, where the `Err` |
| 7781 | // is still something a front-end can show. A zero-length range probes and |
| 7782 | // starts no |
| 7783 | // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`] |
| 7784 | // only enters VA-API off that path. |
| 7785 | DecodeSession::open_worker( |
| 7786 | &source.path, |
| 7787 | 0, |
| 7788 | 0, |
| 7789 | ColorParams::default(), |
| 7790 | TransformParams::default(), |
| 7791 | Composer::passthrough(), |
| 7792 | // A zero-length range decodes nothing, so no table is built and the |
| 7793 | // rendition cannot matter here. |
| 7794 | crate::tonemap::Preset::default(), |
| 7795 | )?; |
| 7796 | // The frame rate is *not* a refusal any more: a file shot at another rate is |
| 7797 | // placed for the seconds it lasts and read through [`Rate`] at the |
| 7798 | // decoder's door, so it plays at the speed it was shot at on a timeline |
| 7799 | // that counts frames faster or slower. |
| 7800 | // |
| 7801 | // A rate that cannot be *named* still is, and this is the one place it is |
| 7802 | // caught: `Rate::from_fps` builds itself out of the muxer's own timescales, |
| 7803 | // and a file whose rate has none of those (a container that says nothing and |
| 7804 | // holds one block, so the demuxer measures 0 fps) would otherwise be read |
| 7805 | // 1:1 in silence -- the old rate gate refused those too, by arithmetic |
| 7806 | // accident. The `Err` is `mux::frame_timing`'s own words. |
| 7807 | let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?; |
| 7808 | audio_matches(source, first)?; |
| 7809 | Ok(rate) |
| 7810 | } |
| 7811 | |
| 7812 | /// Whether a candidate's audio may join a timeline whose first source probes as |
| 7813 | /// `first`: same layout -- or no audio of its own at all, which is silence over |
| 7814 | /// the clip's span and agrees with everything. One output device and one |
| 7815 | /// exported track is all there is, so one width; the *rate* is conformed rather |
| 7816 | /// than matched ([`crate::audio::Resample`]), which is why it is not asked |
| 7817 | /// about here. |
| 7818 | /// |
| 7819 | /// The audio half of [`matches_timeline`], which a stream placed on its own |
| 7820 | /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it |
| 7821 | /// comes with is already on the timeline. |
| 7822 | /// |
| 7823 | /// The format itself is deliberately *not* part of this: an mp3 that agrees on |
| 7824 | /// layout plays alongside a timeline of mp4s perfectly well. What it |
| 7825 | /// cannot do is be copied into an export, which is a refusal of its own, at |
| 7826 | /// export time (`AudioSession::copy_multi_streams`). |
| 7827 | /// What a timeline's audio is held to: the probe of the first source that could |
| 7828 | /// have any track. |
| 7829 | /// |
| 7830 | /// The probe of the first source that really **has a track**, walking forward |
| 7831 | /// past a still (no track by definition) and past a source whose file carries |
| 7832 | /// none (a screen recording with no sound). A silent leading source must not |
| 7833 | /// pin the timeline's layout: pinned to it, a later file with sound could never |
| 7834 | /// be admitted, and the layout a *following* file is held to would be the |
| 7835 | /// silent source's `None`. This is the same walk |
| 7836 | /// [`PlaybackSession::open_project`] makes when it opens the device -- the two |
| 7837 | /// have to agree, so probing and opening can never name different sources. |
| 7838 | /// |
| 7839 | /// `Ok(None)` for a timeline with no track anywhere: nothing but stills, with |
| 7840 | /// no file at all, or every non-still source silent. That is a silent timeline, |
| 7841 | /// and a file with sound is admitted onto it -- it *becomes* the timeline's |
| 7842 | /// sound ([`PlaybackSession::arm_audio`] opens the device for it), exactly the |
| 7843 | /// c581d41 rule ("a later source with real audio must be heard") at the add |
| 7844 | /// door. |
| 7845 | fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> { |
| 7846 | for source in sources |
| 7847 | .iter() |
| 7848 | .filter(|s| !crate::is_image(&s.path) && crate::source_present(&s.path)) |
| 7849 | { |
| 7850 | if let Some(probe) = AudioSession::probe(&source.path, source.audio_stream)? { |
| 7851 | return Ok(Some(probe)); |
| 7852 | } |
| 7853 | } |
| 7854 | Ok(None) |
| 7855 | } |
| 7856 | |
| 7857 | /// Whether a file is sound and no picture, which decides the lane it goes on. |
| 7858 | /// The extension answers for a song; an mp4 or Matroska file is asked of its |
| 7859 | /// header the way [`PlaybackSession::import`] asks it, so an audio-only mp4 |
| 7860 | /// lands on an audio lane exactly as it imports and reopens. |
| 7861 | fn sound_only(path: &Path) -> bool { |
| 7862 | if crate::is_audio(path) { |
| 7863 | return true; |
| 7864 | } |
| 7865 | if crate::is_image(path) { |
| 7866 | return false; |
| 7867 | } |
| 7868 | matches!(Demuxer::open(path), Err(ref e) if NoVideoTrack::is_it(e)) |
| 7869 | } |
| 7870 | |
| 7871 | /// *Which* source that is: the first one that is not a still. The single answer |
| 7872 | /// to "what does this timeline's sound come from", so that probing it |
| 7873 | /// ([`first_audio_of`]) and opening the device on it |
| 7874 | /// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only |
| 7875 | /// the scaffolding file until a save renumbers it or a library removal takes it |
| 7876 | /// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the |
| 7877 | /// device is a timeline that plays silent although every clip on it has sound. |
| 7878 | /// |
| 7879 | /// `None` for a library of nothing but stills, and for one with no file at all: |
| 7880 | /// both are silent timelines. |
| 7881 | fn audio_source_of(sources: &[Source]) -> Option<&Source> { |
| 7882 | sources |
| 7883 | .iter() |
| 7884 | .find(|s| !crate::is_image(&s.path) && crate::source_present(&s.path)) |
| 7885 | } |
| 7886 | |
| 7887 | fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> { |
| 7888 | let probe = AudioSession::probe(&source.path, source.audio_stream)?; |
| 7889 | audio_matches_probed(probe, first) |
| 7890 | } |
| 7891 | |
| 7892 | /// The verdict alone, once the file's own header is in hand: the half a session |
| 7893 | /// with a memo behind it ([`PlaybackSession::audio_matches_cached`]) does not |
| 7894 | /// have to open the file for. |
| 7895 | fn audio_matches_probed( |
| 7896 | probe: Option<crate::AudioProbe>, |
| 7897 | first: &Option<crate::AudioProbe>, |
| 7898 | ) -> crate::Result<()> { |
| 7899 | // The layout, which the audio worker holds every source to anyway -- and not |
| 7900 | // the rate any more: a file written at another one is resampled to the |
| 7901 | // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as |
| 7902 | // a file shot at another frame rate is read through [`Rate`]. Both silent is |
| 7903 | // a match. |
| 7904 | if probe.map(|p| p.channels) == first.map(|p| p.channels) { |
| 7905 | return Ok(()); |
| 7906 | } |
| 7907 | // A mono file joins a wider timeline: [`crate::audio::widen`] duplicates |
| 7908 | // its one channel into every channel the timeline carries, the inverse of |
| 7909 | // the [`crate::audio::downmix`] a wider file already folds through. A |
| 7910 | // wider file onto a mono timeline -- beyond a stereo pair -- stays refused |
| 7911 | // below; the stereo pair is narrowed by [`crate::audio::widen`] (below). |
| 7912 | if let (Some(p), Some(b)) = (probe, first) |
| 7913 | && p.channels == 1 |
| 7914 | && b.channels > 1 |
| 7915 | { |
| 7916 | return Ok(()); |
| 7917 | } |
| 7918 | // ...and a stereo file joins a mono timeline: [`crate::audio::widen`] |
| 7919 | // averages its pair into the one channel the timeline carries. Import and |
| 7920 | // open both come through here, so a project this accepts always reopens. |
| 7921 | if let (Some(p), Some(b)) = (probe, first) |
| 7922 | && p.channels == 2 |
| 7923 | && b.channels == 1 |
| 7924 | { |
| 7925 | return Ok(()); |
| 7926 | } |
| 7927 | // ...and a *silent* file joins whatever the timeline is: it contributes |
| 7928 | // silence over its span, which is the very thing both audio paths already |
| 7929 | // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays |
| 7930 | // it, `AudioSession::copy_multi_streams` writes it). There is no rate and |
| 7931 | // no layout to disagree about, so there is nothing left to refuse. |
| 7932 | let Some(probe) = probe else { |
| 7933 | return Ok(()); |
| 7934 | }; |
| 7935 | // The timeline has no track anywhere (nothing but stills, or every |
| 7936 | // non-image source silent): there is no layout to disagree with, and the |
| 7937 | // arriving file with sound *becomes* the timeline's sound -- |
| 7938 | // [`PlaybackSession::arm_audio`] opens the device for it, exactly the walk |
| 7939 | // [`PlaybackSession::open_project`] makes. Refusing here ("the file has |
| 7940 | // audio, the timeline is silent") pinned the timeline to its silent first |
| 7941 | // source for good: remove that file and add another, and the second file's |
| 7942 | // sound could never be heard. |
| 7943 | let Some(b) = first else { |
| 7944 | return Ok(()); |
| 7945 | }; |
| 7946 | Err(format!( |
| 7947 | "audio {} ch does not match the timeline's {} ch", |
| 7948 | probe.channels, b.channels |
| 7949 | ) |
| 7950 | .into()) |
| 7951 | } |
| 7952 | |
| 7953 | /// How many timeline frames a still image is *held to*: [`IMAGE_MAX_SECS`] of |
| 7954 | /// them, since an image has no length of its own. The number a source's own |
| 7955 | /// entry in [`PlaybackSession::counts`] gets, so a trim may drag an image out |
| 7956 | /// to ten minutes and no further -- and so a saved project reloads, because |
| 7957 | /// [`PlaybackSession::open_project`] recomputes exactly this and refuses a clip |
| 7958 | /// that ends past it. |
| 7959 | fn image_frames(fps: f64) -> u32 { |
| 7960 | ((IMAGE_MAX_SECS * fps) |
| 7961 | .ceil() |
| 7962 | .clamp(1.0, f64::from(u32::MAX))) as u32 |
| 7963 | } |
| 7964 | |
| 7965 | /// How long a still is placed for: `secs` (the project's still length), never past the length |
| 7966 | /// it is held to and never zero (a clip is never empty). |
| 7967 | fn place_frames(count: u32, fps: f64, secs: f64) -> u32 { |
| 7968 | ((secs * fps) |
| 7969 | .ceil() |
| 7970 | .clamp(1.0, f64::from(count.max(1)))) as u32 |
| 7971 | } |
| 7972 | |
| 7973 | /// The project one document of a file describes, on the canvas and rate `meta` gives it. |
| 7974 | fn project_of(doc: crate::edith::Document, meta: &VideoMeta) -> crate::Result<Project> { |
| 7975 | let subtitles = crate::subtitle::open_all(&doc.subtitles); |
| 7976 | Ok( |
| 7977 | Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)? |
| 7978 | .with_mix(&doc.gains, doc.limiter) |
| 7979 | .with_ducks(&doc.ducks) |
| 7980 | .with_voices(&doc.voices) |
| 7981 | .with_lane_names(&doc.names) |
| 7982 | .with_bins(doc.bins) |
| 7983 | .with_lane_flags(&doc.flags) |
| 7984 | .with_tone(doc.tone) |
| 7985 | .with_notes(doc.notes) |
| 7986 | .with_still_secs(doc.still_secs) |
| 7987 | .with_speech(doc.speech_model, doc.speech_device) |
| 7988 | // The palette before what is placed on it: a caption names a row of |
| 7989 | // it, and [`Project::with_subs`] refuses one naming a row that is |
| 7990 | // not there. |
| 7991 | .with_subtitles(subtitles) |
| 7992 | .with_sub_langs(&doc.sub_langs) |
| 7993 | // The cue overrides, over the words the files gave: a retyped |
| 7994 | // cue comes back as it was typed. |
| 7995 | .with_cue_edits(&doc.cue_edits) |
| 7996 | // ...and the cues added to a track, after the file's own, each at |
| 7997 | // its start (see [`crate::edith`]'s `cueadd` lines). |
| 7998 | .with_cue_adds(&doc.cue_adds) |
| 7999 | // The title cards and text overlays, in the order the file has them. |
| 8000 | .with_titles(doc.titles) |
| 8001 | // The chapter markers, in frame order (see [`crate::edith`]'s `chapter` lines). |
| 8002 | .with_chapters(doc.chapters) |
| 8003 | // The comment markers, in frame order (`marker` lines). |
| 8004 | .with_markers(doc.markers) |
| 8005 | .with_cue_words(&doc.cue_words) |
| 8006 | .with_caption_style(doc.caption_style) |
| 8007 | .with_subs(doc.subs)? |
| 8008 | // The header a load puts back: the canvas and rate above, which a |
| 8009 | // save's own `resolution`/`fps` lines may have moved off the |
| 8010 | // scaffold's, and the switches the literal below carries -- handed |
| 8011 | // in here because they are the project's own and a door that moved |
| 8012 | // one after this would snapshot whatever copy it holds, which until |
| 8013 | // this line is the placeholder's. No undo step for |
| 8014 | // [`Project::with_mix`]'s reason: a project that arrived one `z` |
| 8015 | // from a state it was never in is a project whose first undo is a |
| 8016 | // surprise. |
| 8017 | .with_canvas(meta.width, meta.height, meta.frame_rate) |
| 8018 | .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate) |
| 8019 | ) |
| 8020 | } |
| 8021 | |
| 8022 | /// The two tables a trim measures by, `(picture, sound)`: [`wall_table`] for a |
| 8023 | /// video lane and for an audio one, so a linked take's members each meet their |
| 8024 | /// own lane's length. Borrows `counts` only, so the caller may hold them across |
| 8025 | /// a `&mut` to the project. |
| 8026 | fn lane_walls<'a>( |
| 8027 | sources: &[Source], |
| 8028 | counts: &'a [u32], |
| 8029 | fps: f64, |
| 8030 | ) -> (Cow<'a, [u32]>, Cow<'a, [u32]>) { |
| 8031 | ( |
| 8032 | wall_table(sources, counts, fps, Lane::V1), |
| 8033 | wall_table(sources, counts, fps, Lane::A1), |
| 8034 | ) |
| 8035 | } |
| 8036 | |
| 8037 | /// The length each source's clips are walled by on `lane`, in timeline frames. |
| 8038 | /// A clip on an audio lane takes the sound, so a video source's own audio stream |
| 8039 | /// sets its length there (the picture's frame count is the length everywhere |
| 8040 | /// else, and `counts` is that table). Stills and audio files already are their |
| 8041 | /// sound's length in `counts`, and a source with no audio stream keeps its |
| 8042 | /// `counts` entry. Mirrors the length `place` gives an audio-lane placement in |
| 8043 | /// the MCP (`source_frames`). |
| 8044 | fn wall_table<'a>(sources: &[Source], counts: &'a [u32], fps: f64, lane: Lane) -> Cow<'a, [u32]> { |
| 8045 | if lane.kind != LaneKind::Audio { |
| 8046 | return Cow::Borrowed(counts); |
| 8047 | } |
| 8048 | Cow::Owned( |
| 8049 | sources |
| 8050 | .iter() |
| 8051 | .zip(counts) |
| 8052 | .map(|(source, &frames)| { |
| 8053 | if crate::is_image(&source.path) || crate::is_audio(&source.path) { |
| 8054 | return frames; |
| 8055 | } |
| 8056 | match audio_stream_secs(&source.path, source.audio_stream) { |
| 8057 | Some(secs) if secs > 0.0 => (secs * fps).ceil().clamp(1.0, f64::from(u32::MAX)) as u32, |
| 8058 | _ => frames, |
| 8059 | } |
| 8060 | }) |
| 8061 | .collect(), |
| 8062 | ) |
| 8063 | } |
| 8064 | |
| 8065 | /// How long a placed file's clip is: its picture's frame count, held to the length |
| 8066 | /// its sound is walled by ([`wall_table`]) when it has one. A grouped take puts the |
| 8067 | /// same clip on the picture lane and the sound lane, so a 2.002 s picture beside a |
| 8068 | /// 2.000 s sound is 60 frames, not 61 -- the sound's own wall is what the load and |
| 8069 | /// save checks hold the audio lane to, and one clip must satisfy both lanes. |
| 8070 | fn sound_held_frames(path: &Path, stream: usize, frames: u32, fps: f64) -> u32 { |
| 8071 | if crate::is_image(path) || crate::is_audio(path) { |
| 8072 | return frames.max(1); |
| 8073 | } |
| 8074 | match audio_stream_secs(path, stream) { |
| 8075 | Some(secs) if secs > 0.0 => { |
| 8076 | let held = (secs * fps).ceil().clamp(1.0, f64::from(u32::MAX)) as u32; |
| 8077 | frames.min(held).max(1) |
| 8078 | } |
| 8079 | _ => frames.max(1), |
| 8080 | } |
| 8081 | } |
| 8082 | |
| 8083 | /// [`AudioSession::stream_duration_secs`] for one stream, remembered per file: |
| 8084 | /// a trim asks for it on every drag step. Only a found length is kept; a file |
| 8085 | /// that cannot be read now may be back in a moment. |
| 8086 | fn audio_stream_secs(path: &Path, stream: usize) -> Option<f64> { |
| 8087 | static SECS: std::sync::OnceLock<Mutex<std::collections::HashMap<(PathBuf, usize), f64>>> = |
| 8088 | std::sync::OnceLock::new(); |
| 8089 | let cache = SECS.get_or_init(Default::default); |
| 8090 | let key = (path.to_path_buf(), stream); |
| 8091 | if let Some(&secs) = cache.lock().ok()?.get(&key) { |
| 8092 | return Some(secs); |
| 8093 | } |
| 8094 | let secs = AudioSession::stream_duration_secs(path, stream).ok()??; |
| 8095 | cache.lock().ok()?.insert(key, secs); |
| 8096 | Some(secs) |
| 8097 | } |
| 8098 | |
| 8099 | /// How many timeline frames a standalone audio file occupies: its playing time |
| 8100 | /// rounded *up*, so the last partial frame is still covered rather than cut off, |
| 8101 | /// and never zero (a clip is never empty). |
| 8102 | fn audio_frames(path: &Path, fps: f64) -> crate::Result<u32> { |
| 8103 | let secs = AudioSession::duration_secs(path)? |
| 8104 | .ok_or_else(|| format!("{} has no audio track", path.display()))?; |
| 8105 | let frames = (secs * fps).ceil(); |
| 8106 | if !frames.is_finite() || frames < 0.0 || frames > f64::from(u32::MAX) { |
| 8107 | return Err(format!( |
| 8108 | "{} is {secs} s long, which is not a timeline", |
| 8109 | path.display() |
| 8110 | ) |
| 8111 | .into()); |
| 8112 | } |
| 8113 | Ok((frames as u32).max(1)) |
| 8114 | } |
| 8115 | |
| 8116 | /// `None` for a silent session -- no audio track, no plugin, no daemon, or a |
| 8117 | /// track the decoder refuses. Dropping the receiver on the way out stops the |
| 8118 | /// audio decode worker, so a failure here leaves nothing running. |
| 8119 | /// |
| 8120 | /// The second half is why, for the cases the *file* is to blame for: those are |
| 8121 | /// a surprise worth showing (see |
| 8122 | /// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a |
| 8123 | /// file with no audio at all and a machine with no output device are not. |
| 8124 | fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) { |
| 8125 | let sources = [(path.to_path_buf(), stream)]; |
| 8126 | let (meta, rx) = |
| 8127 | match AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) { |
| 8128 | Ok(Some(opened)) => opened, |
| 8129 | // No AAC track: silent by nature, or sound in a codec we do not |
| 8130 | // have -- and only the second of those is worth a word. |
| 8131 | Ok(None) => { |
| 8132 | let reason = AudioSession::unsupported(path).ok().flatten(); |
| 8133 | if let Some(reason) = &reason { |
| 8134 | crate::audio::debug_once(format!("audio disabled: {reason}")); |
| 8135 | } |
| 8136 | return (None, reason); |
| 8137 | } |
| 8138 | Err(e) => { |
| 8139 | crate::audio::debug_once(format!("audio disabled: {e}")); |
| 8140 | return (None, Some(e.to_string())); |
| 8141 | } |
| 8142 | }; |
| 8143 | let Some(ao) = AoSession::open(meta.sample_rate, u32::from(meta.channels)) else { |
| 8144 | return (None, None); // no device: the machine's business, not the file's |
| 8145 | }; |
| 8146 | // The stream comes up streaming; a session starts paused, so silence the |
| 8147 | // device until `play`. The feeder still fills the ring in the meantime. |
| 8148 | ao.set_active(false); |
| 8149 | |
| 8150 | let audio = Audio { |
| 8151 | ao: Arc::new(Mutex::new(ao)), |
| 8152 | sample_rate: meta.sample_rate, |
| 8153 | channels: u64::from(meta.channels), |
| 8154 | fed: Arc::new(AtomicU64::new(0)), |
| 8155 | fed_all: Arc::new(AtomicBool::new(false)), |
| 8156 | died: Arc::new(AtomicBool::new(false)), |
| 8157 | epoch: Arc::new(AtomicU64::new(0)), |
| 8158 | content_at: Arc::new(AtomicI64::new(-1)), |
| 8159 | gain: Arc::new(AtomicU32::new(1.0f32.to_bits())), |
| 8160 | wants_active: Arc::new(AtomicBool::new(false)), |
| 8161 | tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))), |
| 8162 | peak: Arc::new(AtomicU32::new(0)), |
| 8163 | peak_lr: Arc::new([AtomicU32::new(0), AtomicU32::new(0)]), |
| 8164 | feeders: Arc::new(AtomicUsize::new(0)), |
| 8165 | rearm_at: Arc::new(Mutex::new(None)), |
| 8166 | }; |
| 8167 | (audio.spawn_feeder(rx).then_some(audio), None) |
| 8168 | } |
| 8169 | |
| 8170 | /// Pours decoded chunks into the device, keeping whatever the ring would not |
| 8171 | /// take. Ends when the decoder is done, the output dies, or a seek supersedes |
| 8172 | /// this feeder. |
| 8173 | fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) { |
| 8174 | let mut pending: Vec<f32> = Vec::new(); |
| 8175 | loop { |
| 8176 | if pending.is_empty() { |
| 8177 | match rx.recv() { |
| 8178 | Ok(chunk) => pending = chunk.samples, |
| 8179 | Err(_) => { |
| 8180 | // Decoder finished or went away. What is in the ring still |
| 8181 | // plays out; what comes after it is the end of the timeline |
| 8182 | // and not a decoder that fell behind, so the device is told |
| 8183 | // to stop counting it. Under the lock and past the epoch, |
| 8184 | // like every other word this thread has with the device: a |
| 8185 | // superseded feeder must not say this about the stream that |
| 8186 | // replaced it. |
| 8187 | let ao = audio.ao.lock().unwrap(); |
| 8188 | if audio.epoch.load(Ordering::Acquire) == epoch { |
| 8189 | ao.stream_ended(); |
| 8190 | } |
| 8191 | return; |
| 8192 | } |
| 8193 | } |
| 8194 | } |
| 8195 | let accepted = { |
| 8196 | let mut ao = audio.ao.lock().unwrap(); |
| 8197 | // Under the lock, immediately before the write: `seek` bumps the |
| 8198 | // epoch and flushes the ring holding this very lock, so past this |
| 8199 | // check no stale sample can be queued behind the flush. |
| 8200 | if audio.epoch.load(Ordering::Acquire) != epoch { |
| 8201 | return; |
| 8202 | } |
| 8203 | let accepted = match ao.write(&pending) { |
| 8204 | Some(n) => n, |
| 8205 | None => { |
| 8206 | // Output died; flag it so `tick` moves the clock to wall time. |
| 8207 | audio.died.store(true, Ordering::Release); |
| 8208 | return; |
| 8209 | } |
| 8210 | }; |
| 8211 | // The first sample of this stream to reach the ring, stamped with |
| 8212 | // what the device had played by then: everything before it was the |
| 8213 | // silence of the restart, and [`PlaybackSession::tick`] anchors the |
| 8214 | // clock here so that silence is never timeline time. Under the |
| 8215 | // device lock, with the epoch already checked, so the stamp and the |
| 8216 | // sample belong to the same stream. |
| 8217 | if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 { |
| 8218 | let at = ao.position().unwrap_or(0).max(0); |
| 8219 | audio.content_at.store(at, Ordering::Release); |
| 8220 | // ...and the device position this stream's samples are counted |
| 8221 | // from ([`Audio::played_out`]). Rebased *here* rather than at |
| 8222 | // the seek, because the open runs on this thread now: every |
| 8223 | // millisecond it took is device time nobody fed, and counting |
| 8224 | // it would make the stream read as played out that long before |
| 8225 | // it really is -- an early hand-off to wall time at the end of |
| 8226 | // the timeline. The seek's own rebase still stands for the |
| 8227 | // stream that never queues a sample at all. |
| 8228 | audio |
| 8229 | .fed |
| 8230 | .store(at as u64 * audio.channels, Ordering::Relaxed); |
| 8231 | // ...and *this* is where a playing timeline's device starts: on |
| 8232 | // the first sample there is to play, under the same lock and |
| 8233 | // past the same epoch check as the stamp, so the silence of the |
| 8234 | // open was never played and never counted |
| 8235 | // ([`Audio::wants_active`]). |
| 8236 | if audio.wants_active.load(Ordering::Acquire) { |
| 8237 | ao.set_active(true); |
| 8238 | } |
| 8239 | } else if accepted == 0 && audio.content_at.load(Ordering::Acquire) < 0 { |
| 8240 | // Nothing taken with nothing yet queued is the *flush* of the |
| 8241 | // restart still standing: the ring refuses a write until a |
| 8242 | // callback has consumed the flag (`engine_audio::accept`), and |
| 8243 | // only a running device has callbacks. So the device is started |
| 8244 | // here too -- there is a sample in hand, which is what the wait |
| 8245 | // was for -- and the quantum or two of that handshake is the |
| 8246 | // silence `Shared::primed` does not count. |
| 8247 | if audio.wants_active.load(Ordering::Acquire) { |
| 8248 | ao.set_active(true); |
| 8249 | } |
| 8250 | } |
| 8251 | accepted |
| 8252 | }; |
| 8253 | audio.fed.fetch_add(accepted as u64, Ordering::Relaxed); |
| 8254 | audio.note_tap(&pending[..accepted]); |
| 8255 | pending.drain(..accepted); |
| 8256 | if !pending.is_empty() { |
| 8257 | // Ring full: nothing to do but let the device drain it. Except when |
| 8258 | // *nothing* was taken, which after a flush means the ring is still |
| 8259 | // waiting for the device to consume the flush flag rather than |
| 8260 | // being full: that is the head of a restart, and every millisecond |
| 8261 | // spent parked there is a millisecond of silence. |
| 8262 | match accepted { |
| 8263 | 0 => thread::sleep(FLUSH_WAIT), |
| 8264 | _ => thread::sleep(RING_FULL_WAIT), |
| 8265 | } |
| 8266 | } |
| 8267 | } |
| 8268 | } |
| 8269 | |
| 8270 | /// The stretch of the timeline that ends at `frame` (inclusive) and starts where |
| 8271 | /// whatever is shown there starts: [`crate::export::stack_span_at`] at that |
| 8272 | /// start, cut short at `frame`. What a backward play draws, from `frame` down. |
| 8273 | fn back_span_at(project: &Project, frame: u32) -> Option<crate::project::Span> { |
| 8274 | let mut lo = 0; |
| 8275 | let visible = project |
| 8276 | .lanes() |
| 8277 | .into_iter() |
| 8278 | .filter(|lane| lane.kind == LaneKind::Video && !project.lane_hidden(*lane)); |
| 8279 | for lane in visible { |
| 8280 | let clips = project.lane(lane); |
| 8281 | let from = match project.lane_clip_at(lane, frame) { |
| 8282 | Some(idx) => clips[idx].start, |
| 8283 | None => clips.iter().rfind(|c| c.end() <= frame).map_or(0, |c| c.end()), |
| 8284 | }; |
| 8285 | lo = lo.max(from); |
| 8286 | } |
| 8287 | let mut span = crate::export::stack_span_at(project, lo)?; |
| 8288 | span.len = span.len.min(frame + 1 - lo); |
| 8289 | Some(span) |
| 8290 | } |
| 8291 | |
| 8292 | /// Timeline seconds to a 0-based frame index, floor semantics: position `t` |
| 8293 | /// shows the frame whose interval contains it. The epsilon absorbs float error |
| 8294 | /// at exact frame boundaries -- `123.0/30.0 * 30.0` is `122.999...`, and a |
| 8295 | /// bare truncation would land one frame early (S6 finding: 4 of every 300 |
| 8296 | /// frames round-trip wrong through `clip_spans()` seconds without this). |
| 8297 | fn secs_to_frame(secs: f64, fps: f64) -> u32 { |
| 8298 | (secs * fps + 1e-6).floor().max(0.0) as u32 |
| 8299 | } |
| 8300 | |
| 8301 | /// Per-byte lerp of two same-sized BGRA8 frames -- [`crate::scale::blend_i420`]'s |
| 8302 | /// interleaved-buffer twin. By the time a picture reaches [`try_frame`] |
| 8303 | /// (`PlaybackSession::try_frame`) it is already colour-converted for the |
| 8304 | /// screen, so there are no separate Y/U/V planes left to blend, only the one |
| 8305 | /// buffer; straight alpha survives the lerp untouched (255 against 255 is |
| 8306 | /// still 255). `t` is B's weight, [`crate::export::dissolve_weight`]'s own |
| 8307 | /// convention. |
| 8308 | fn blend_bgra(a: &[u8], b: &[u8], t: f32) -> Vec<u8> { |
| 8309 | let t = t.clamp(0.0, 1.0); |
| 8310 | assert_eq!(a.len(), b.len(), "blend_bgra: mismatched frame sizes"); |
| 8311 | a.iter() |
| 8312 | .zip(b) |
| 8313 | .map(|(&av, &bv)| (av as f32 + (bv as f32 - av as f32) * t).round() as u8) |
| 8314 | .collect() |
| 8315 | } |
| 8316 | |
| 8317 | /// A chapter time as YouTube writes one in a description: `MM:SS`, or `H:MM:SS` from an hour on. |
| 8318 | /// The frame is floored to whole seconds. |
| 8319 | pub fn youtube_time(frame: u32, fps: f64) -> String { |
| 8320 | let secs = (f64::from(frame) / fps).floor() as u64; |
| 8321 | let (h, m, sec) = (secs / 3600, (secs % 3600) / 60, secs % 60); |
| 8322 | if h > 0 { |
| 8323 | format!("{h}:{m:02}:{sec:02}") |
| 8324 | } else { |
| 8325 | format!("{m:02}:{sec:02}") |
| 8326 | } |
| 8327 | } |
| 8328 | |
| 8329 | /// The YouTube description listing for `chapters` (frame, name, sorted by frame) and the warnings |
| 8330 | /// its rules call for: the first chapter at 00:00, each chapter at least 10 seconds long (the last |
| 8331 | /// runs to `end`), and at least 3 chapters. Empty when there are none. |
| 8332 | pub fn chapter_listing(chapters: &[(u32, String)], fps: f64, end: u32) -> (String, Vec<String>) { |
| 8333 | if chapters.is_empty() { |
| 8334 | return (String::new(), Vec::new()); |
| 8335 | } |
| 8336 | let listing = chapters |
| 8337 | .iter() |
| 8338 | .map(|(f, t)| format!("{} {t}", youtube_time(*f, fps))) |
| 8339 | .collect::<Vec<_>>() |
| 8340 | .join("\n"); |
| 8341 | let mut warnings = Vec::new(); |
| 8342 | if chapters[0].0 != 0 { |
| 8343 | warnings.push(format!( |
| 8344 | "the first chapter starts at {}, not 00:00: YouTube needs one at 00:00", |
| 8345 | youtube_time(chapters[0].0, fps) |
| 8346 | )); |
| 8347 | } |
| 8348 | for (i, (frame, title)) in chapters.iter().enumerate() { |
| 8349 | let next = chapters.get(i + 1).map_or(end, |c| c.0); |
| 8350 | let secs = f64::from(next.saturating_sub(*frame)) / fps; |
| 8351 | if secs < 10.0 { |
| 8352 | warnings.push(format!("chapter \"{title}\" at {} lasts {secs:.1} s: YouTube wants 10 s or more", youtube_time(*frame, fps))); |
| 8353 | } |
| 8354 | } |
| 8355 | if chapters.len() < 3 { |
| 8356 | warnings.push(format!("YouTube needs at least 3 chapters; this timeline has {}", chapters.len())); |
| 8357 | } |
| 8358 | (listing, warnings) |
| 8359 | } |
| 8360 | |
| 8361 | #[cfg(test)] |
| 8362 | mod tests { |
| 8363 | use super::{ |
| 8364 | SCRUB_SECS, scrub_snippet, AUDIO_LOST, Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of, |
| 8365 | blend_bgra, secs_to_frame, |
| 8366 | }; |
| 8367 | use std::path::PathBuf; |
| 8368 | use std::sync::atomic::Ordering; |
| 8369 | |
| 8370 | fn asset(name: &str) -> PathBuf { |
| 8371 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 8372 | .join("../../assets") |
| 8373 | .join(name) |
| 8374 | } |
| 8375 | |
| 8376 | /// A scrub snippet is the window it was cut from, as long as [`SCRUB_SECS`], and it rises |
| 8377 | /// from silence and falls to it again over its fades, so no edge of it can click. |
| 8378 | #[test] |
| 8379 | fn a_scrub_snippet_is_the_window_long_and_faded_at_both_ends() { |
| 8380 | let rate = 48_000u32; |
| 8381 | let frames = (SCRUB_SECS * f64::from(rate)) as usize; |
| 8382 | assert_eq!(frames, 3360, "70 ms at 48 kHz"); |
| 8383 | let fade = (0.01 * f64::from(rate)) as usize; |
| 8384 | let src = vec![1.0f32; frames * 2]; |
| 8385 | let out = scrub_snippet(&src, 2, fade); |
| 8386 | assert_eq!(out.len(), frames * 2, "the window's length, both channels"); |
| 8387 | assert!(out[0].abs() < 0.01 && out[1].abs() < 0.01, "starts at silence: {:?}", &out[..2]); |
| 8388 | let last = out.len() - 2; |
| 8389 | assert!(out[last].abs() < 0.01 && out[last + 1].abs() < 0.01, "ends at silence"); |
| 8390 | let mid = frames / 2 * 2; |
| 8391 | assert_eq!((out[mid], out[mid + 1]), (1.0, 1.0), "the middle is untouched"); |
| 8392 | for f in 1..fade { |
| 8393 | assert!(out[2 * f] >= out[2 * (f - 1)], "the fade in rises at frame {f}"); |
| 8394 | let tail = out.len() - 2 * (f + 1); |
| 8395 | assert!(out[tail] >= out[tail + 2], "the fade out falls toward the end at frame {f}"); |
| 8396 | } |
| 8397 | // A window shorter than twice the fade has its fade held to half of it. |
| 8398 | let short = scrub_snippet(&[1.0; 8], 1, 100); |
| 8399 | assert_eq!(short.len(), 8); |
| 8400 | assert!(short[0].abs() < 0.5 && short[7].abs() < 0.5, "{short:?}"); |
| 8401 | assert!(scrub_snippet(&[1.0; 8], 0, 2).len() == 8, "a zero width is read as mono"); |
| 8402 | } |
| 8403 | |
| 8404 | /// The crash path: a saved project with several sequences (one of them a compound clip |
| 8405 | /// over another, plus a marker) is written as an autosave and read back, and the autosave |
| 8406 | /// on top of the saved file recovers to the same sequences, compound clips and markers. |
| 8407 | #[test] |
| 8408 | fn autosave_round_trips_every_sequence_compound_and_marker() { |
| 8409 | let dir = crate::scratch::Scratch::dir("ve_sidecar_round_trip"); |
| 8410 | let media = dir.join("film.mp4"); |
| 8411 | std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture"); |
| 8412 | let path = dir.join("proj.edith"); |
| 8413 | let s = PlaybackSession::open(&media).expect("open the fixture"); |
| 8414 | s.set_gain(0.0); |
| 8415 | s.save_project_noted(&path).expect("save the base"); |
| 8416 | let mut s = PlaybackSession::open_project(&path).expect("reopen the base"); |
| 8417 | let b = s.new_sequence(Some("Cut B")).expect("a second sequence"); |
| 8418 | s.switch_sequence(b).expect("switch to it"); |
| 8419 | assert!(s.place_stream_at(0.0, &media, 0, None).expect("placeable")); |
| 8420 | let copy = s.duplicate_sequence(b).expect("duplicate it"); |
| 8421 | s.switch_sequence(copy).expect("switch to the copy"); |
| 8422 | s.nest(&[(Lane::V1, 0)], Some("Inner")).expect("nest a clip"); |
| 8423 | assert_eq!(s.project.sequences().len(), 4, "the base, B, its copy and the nested one"); |
| 8424 | s.add_marker(crate::project::Marker { |
| 8425 | frame: 3, |
| 8426 | length: 0, |
| 8427 | name: "beat".into(), |
| 8428 | note: String::new(), |
| 8429 | color: crate::project::MarkerColor::Red, |
| 8430 | }) |
| 8431 | .expect("a marker"); |
| 8432 | assert_eq!(s.project.markers().len(), 1, "the marker is on the sequence being edited"); |
| 8433 | let sidecar = dir.join("proj.autosave.edith"); |
| 8434 | s.save_autosave(&sidecar).expect("the autosave"); |
| 8435 | let back = PlaybackSession::open_project(&sidecar).expect("the autosave opens"); |
| 8436 | assert_eq!(back.project.sequences(), s.project.sequences(), "the same sequences, in order"); |
| 8437 | assert_eq!(back.project.active_sequence(), s.project.active_sequence()); |
| 8438 | assert_eq!(back.project.markers().len(), 1, "the marker comes back"); |
| 8439 | assert_eq!(back.project.markers()[0].name, "beat"); |
| 8440 | // The recovery path: the saved file, with the autosave on top of it. |
| 8441 | let mut saved = PlaybackSession::open_project(&path).expect("the saved file"); |
| 8442 | assert!(saved.adopt_as_step(&back), "the autosave lands on the saved file"); |
| 8443 | assert_eq!(saved.project.sequences(), s.project.sequences(), "recovery holds every sequence"); |
| 8444 | assert_eq!(saved.project.markers().len(), 1, "and the marker"); |
| 8445 | } |
| 8446 | |
| 8447 | /// A clip past its source's end in a parked sequence is shortened on save, just as in the |
| 8448 | /// active one, and the save says which sequence it was in. It is never refused. |
| 8449 | #[test] |
| 8450 | fn save_shortens_the_parked_sequences_over_wall_clips() { |
| 8451 | let dir = crate::scratch::Scratch::dir("ve_save_parked_walls"); |
| 8452 | let media = dir.join("film.mp4"); |
| 8453 | std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture"); |
| 8454 | let mut s = PlaybackSession::open(&media).expect("open the fixture"); |
| 8455 | s.set_gain(0.0); |
| 8456 | let copy = s.duplicate_sequence(s.project.active_sequence()).expect("duplicate"); |
| 8457 | let copy_name = s.project.sequence_name(copy).expect("the copy is named").to_string(); |
| 8458 | let path = dir.join("proj.edith"); |
| 8459 | assert!(s.save_project_noted(&path).expect("whole walls save").is_empty()); |
| 8460 | s.counts[0] = 1; |
| 8461 | let notes = s.save_project_noted(&path).expect("the save never refuses"); |
| 8462 | assert!(notes.iter().any(|n| n.contains(&format!("in sequence \"{copy_name}\""))), "{notes:?}"); |
| 8463 | assert!(notes.iter().all(|n| !n.contains("frame")), "no frame numbers in a note: {notes:?}"); |
| 8464 | PlaybackSession::open_project(&path).expect("the saved file opens"); |
| 8465 | } |
| 8466 | |
| 8467 | /// A video file whose sound is shorter than its picture (a 22.96 s picture under 20.67 s of |
| 8468 | /// sound): the timeline it opens to holds the grouped take to the sound's length, so an |
| 8469 | /// edit chain that splits, ripple-deletes and dissolves saves without a refusal and leaves |
| 8470 | /// no audio clip past the sound's end. |
| 8471 | #[test] |
| 8472 | fn a_picture_longer_than_its_sound_saves_after_edits() { |
| 8473 | let dir = crate::scratch::Scratch::dir("ve_short_sound_edits"); |
| 8474 | let media = dir.join("speech.mp4"); |
| 8475 | let made = std::process::Command::new("ffmpeg") |
| 8476 | .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=160x120:rate=25:duration=22.96", |
| 8477 | "-f", "lavfi", "-i", "sine=frequency=440:duration=20.67", "-c:v", "mpeg4", "-c:a", "aac"]) |
| 8478 | .arg(&media) |
| 8479 | .status() |
| 8480 | .map(|s| s.success() && media.exists()) |
| 8481 | .unwrap_or(false); |
| 8482 | if !made { |
| 8483 | eprintln!("no ffmpeg: a picture longer than its sound cannot be generated, skipping"); |
| 8484 | return; |
| 8485 | } |
| 8486 | let mut s = PlaybackSession::open(&media).expect("open the fixture"); |
| 8487 | s.set_gain(0.0); |
| 8488 | let sound_frames = 517; |
| 8489 | assert_eq!(s.lane_clips(Lane::A1)[0].out_frame, sound_frames, "the opened take is the sound's length"); |
| 8490 | assert_eq!(s.lane_clips(Lane::V1)[0].out_frame, sound_frames, "and so is its picture"); |
| 8491 | |
| 8492 | let path = dir.join("proj.edith"); |
| 8493 | assert!(s.cut_at(5.0)); |
| 8494 | assert!(s.cut_regions(&[(50, 100)], &[Lane::V1, Lane::A1]).is_ok()); |
| 8495 | assert!(s.set_transition_out(Lane::V1, 0, 10)); |
| 8496 | assert!(s.place_stream_at(0.0, &media, 0, None).expect("placeable")); |
| 8497 | let notes = s.save_project_noted(&path).expect("the edited take saves"); |
| 8498 | assert!(notes.is_empty(), "nothing needed shortening: {notes:?}"); |
| 8499 | for lane in [Lane::V1, Lane::A1] { |
| 8500 | for c in s.lane_clips(lane) { |
| 8501 | assert!(c.out_frame <= sound_frames, "{lane:?} clip ends at {} past the sound", c.out_frame); |
| 8502 | } |
| 8503 | } |
| 8504 | } |
| 8505 | |
| 8506 | /// A relink is one undo step on the session too: undo points the source back at the old file, |
| 8507 | /// which reads again (no longer offline), and redo points it at the new one. |
| 8508 | #[test] |
| 8509 | fn undoing_a_relink_reads_the_old_file_again() { |
| 8510 | let dir = crate::scratch::Scratch::dir("ve_relink_undo_session"); |
| 8511 | let media = dir.join("film.mp4"); |
| 8512 | std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture"); |
| 8513 | let session = PlaybackSession::open(&media).expect("open the fixture"); |
| 8514 | session.set_gain(0.0); |
| 8515 | let path = dir.join("proj.edith"); |
| 8516 | session.save_project(&path).expect("save"); |
| 8517 | let moved = dir.join("moved.mp4"); |
| 8518 | std::fs::rename(&media, &moved).expect("move the media"); |
| 8519 | |
| 8520 | let mut s = PlaybackSession::open_project(&path).expect("opens offline"); |
| 8521 | assert_eq!(s.offline_sources().len(), 1); |
| 8522 | s.relink_source(0, &moved).expect("relinks"); |
| 8523 | assert!(s.offline_sources().is_empty()); |
| 8524 | std::fs::copy(&moved, &media).expect("the old file is back beside it"); |
| 8525 | assert!(s.undo()); |
| 8526 | assert_eq!(s.sources()[0].path, std::fs::canonicalize(&media).expect("canonical")); |
| 8527 | assert!(s.offline_sources().is_empty(), "the old file reads again"); |
| 8528 | assert!(s.redo()); |
| 8529 | assert_eq!(s.sources()[0].path, std::fs::canonicalize(&moved).expect("canonical")); |
| 8530 | } |
| 8531 | |
| 8532 | /// A dead output is not the end of a session's sound. |
| 8533 | /// |
| 8534 | /// The stream is stopped the way a seek stops one and then flagged the way a |
| 8535 | /// failed write flags it ([`feed`]): nothing is feeding and nothing will. The |
| 8536 | /// session must say so -- a dead output used to hand the clock to wall time |
| 8537 | /// in silence, for the rest of the session's life, through every seek -- and |
| 8538 | /// the play (and the seek after it) must put the output back, which is read |
| 8539 | /// off the tap: the samples that actually reached the device. A session that |
| 8540 | /// only switched the clock leaves the tap empty. |
| 8541 | /// |
| 8542 | /// The tick below runs with the cooldown already spent (an attempt stamped |
| 8543 | /// just now), which is what makes the notice observable at all *and* what |
| 8544 | /// proves the one thing a frame-rate poll must not do: open a device that is |
| 8545 | /// gone for good sixty times a second. |
| 8546 | #[test] |
| 8547 | fn a_dead_output_is_rearmed_and_the_sound_comes_back() { |
| 8548 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); |
| 8549 | assert!( |
| 8550 | session.audio_tap().is_some(), |
| 8551 | "test_av.mp4 carries an audio track, which is what this drives" |
| 8552 | ); |
| 8553 | |
| 8554 | session.stop_audio(); |
| 8555 | let audio = session.audio.as_ref().expect("audio"); |
| 8556 | audio.died.store(true, Ordering::Release); |
| 8557 | *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now()); |
| 8558 | |
| 8559 | session.tick(); |
| 8560 | assert_eq!( |
| 8561 | session.audio_disabled_reason(), |
| 8562 | Some(AUDIO_LOST), |
| 8563 | "a dead output went to wall time without a word" |
| 8564 | ); |
| 8565 | assert!( |
| 8566 | session |
| 8567 | .audio |
| 8568 | .as_ref() |
| 8569 | .expect("audio") |
| 8570 | .died |
| 8571 | .load(Ordering::Acquire), |
| 8572 | "a tick opened the output again inside the cooldown" |
| 8573 | ); |
| 8574 | assert!( |
| 8575 | session.audio_tap().expect("audio").0.is_empty(), |
| 8576 | "something was still feeding the device" |
| 8577 | ); |
| 8578 | |
| 8579 | // Playing is the ask that is not throttled: the output is opened again, |
| 8580 | // the flag clears and a feeder fills the device -- asynchronously, so the |
| 8581 | // tap is waited on. |
| 8582 | session.play(); |
| 8583 | session.seek(1.0); |
| 8584 | let mut fed = Vec::new(); |
| 8585 | for _ in 0..200 { |
| 8586 | fed = session.audio_tap().expect("audio").0; |
| 8587 | if !fed.is_empty() { |
| 8588 | break; |
| 8589 | } |
| 8590 | std::thread::sleep(std::time::Duration::from_millis(5)); |
| 8591 | } |
| 8592 | assert!( |
| 8593 | !fed.is_empty(), |
| 8594 | "playing after a dead output fed nothing: the session cannot come back" |
| 8595 | ); |
| 8596 | assert!( |
| 8597 | !session |
| 8598 | .audio |
| 8599 | .as_ref() |
| 8600 | .expect("audio") |
| 8601 | .died |
| 8602 | .load(Ordering::Acquire), |
| 8603 | "the death flag stood after the output was replaced" |
| 8604 | ); |
| 8605 | assert_eq!( |
| 8606 | session.audio_disabled_reason(), |
| 8607 | None, |
| 8608 | "the notice was left standing over a session that is playing again" |
| 8609 | ); |
| 8610 | } |
| 8611 | |
| 8612 | /// A monitoring level is state, and a device replaced under the session is |
| 8613 | /// a new object that knows nothing about it: the re-armed stream came up |
| 8614 | /// at full volume, so a session playing muted while PipeWire restarted |
| 8615 | /// came back loud with the toolbar still reading "muted". The gain is |
| 8616 | /// therefore read back *from the device* ([`PlaybackSession::gain`]) and |
| 8617 | /// put back onto the replacement. |
| 8618 | /// |
| 8619 | /// The silent sink is what makes this a state round-trip rather than a |
| 8620 | /// claim about ears: it keeps the gain it was given, so the level after a |
| 8621 | /// re-arm is a number this process can read, and a plain open with no gain |
| 8622 | /// ever pushed is the control that says 1.0 is a real default rather than |
| 8623 | /// a leftover. |
| 8624 | #[test] |
| 8625 | fn a_rearmed_output_comes_back_at_the_level_the_session_was_running() { |
| 8626 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); |
| 8627 | // The control: a session nobody has pushed a level at is at full |
| 8628 | // volume, which is what a *fresh* device is expected to be. |
| 8629 | assert_eq!( |
| 8630 | session.gain(), |
| 8631 | Some(1.0), |
| 8632 | "a session that never had a gain pushed is not at full volume" |
| 8633 | ); |
| 8634 | assert!( |
| 8635 | session.set_gain(0.0), |
| 8636 | "a muted push was refused by the silent sink" |
| 8637 | ); |
| 8638 | assert_eq!( |
| 8639 | session.gain(), |
| 8640 | Some(0.0), |
| 8641 | "the push did not reach the device" |
| 8642 | ); |
| 8643 | |
| 8644 | // The device goes away the way a daemon restart takes it: the stream is |
| 8645 | // stopped and flagged dead, with the cooldown already spent. The |
| 8646 | // replacement is opened by the door the sibling re-arm witness drives |
| 8647 | // -- a play and the seek that follows, which is `start_audio`'s |
| 8648 | // unthrottled attempt -- and the death flag clearing is what says a new |
| 8649 | // device really was installed, rather than the read below passing over |
| 8650 | // the old one. |
| 8651 | session.stop_audio(); |
| 8652 | let audio = session.audio.as_ref().expect("audio"); |
| 8653 | audio.died.store(true, Ordering::Release); |
| 8654 | *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now()); |
| 8655 | session.play(); |
| 8656 | session.seek(1.0); |
| 8657 | assert!( |
| 8658 | !session |
| 8659 | .audio |
| 8660 | .as_ref() |
| 8661 | .expect("audio") |
| 8662 | .died |
| 8663 | .load(Ordering::Acquire), |
| 8664 | "the device was never replaced, so the level below says nothing about \ |
| 8665 | a re-armed stream" |
| 8666 | ); |
| 8667 | |
| 8668 | assert_eq!( |
| 8669 | session.gain(), |
| 8670 | Some(0.0), |
| 8671 | "the replacement device came up at full volume: a muted session \ |
| 8672 | that lost its output came back loud while the window still said muted" |
| 8673 | ); |
| 8674 | } |
| 8675 | |
| 8676 | /// The seat declares the canvas's own size; the painter masks the planes it |
| 8677 | /// returns to even dimensions, and a canvas the two disagree about used to |
| 8678 | /// take the picture down between them. On the revision before the seat masked |
| 8679 | /// what it declares, a 1920x1 canvas died *in the painter* -- `decode.rs` |
| 8680 | /// clamped the zero line of an h of 0: `max = -1`, `min > max` -- and a |
| 8681 | /// 321x181 one died in the conversion on the *canvas's* chroma plane, one row |
| 8682 | /// past the masked source's: `index out of bounds: the len is 14400 but the |
| 8683 | /// index is 14400`, a full plane and not an empty one. |
| 8684 | /// |
| 8685 | /// This drives the same path a front-end does (`set_resolution`, then frames |
| 8686 | /// out of the session). It is a guard against the shape coming back rather |
| 8687 | /// than a reproduction: a frame does still arrive on the parent revision |
| 8688 | /// (which is why the masking, not this test, is the fix). |
| 8689 | #[test] |
| 8690 | fn a_visualizer_seat_paints_a_canvas_it_cannot_evenly_divide() { |
| 8691 | for (w, h) in [(1920, 1), (1921, 1081), (320, 1), (321, 181)] { |
| 8692 | let mut session = |
| 8693 | PlaybackSession::open(asset("test_tone.mp3")).expect("open the audio fixture"); |
| 8694 | assert!( |
| 8695 | session.set_resolution(w, h), |
| 8696 | "{w}x{h} should be a resolution this session takes" |
| 8697 | ); |
| 8698 | let mut frame = None; |
| 8699 | for _ in 0..400 { |
| 8700 | if let Some(f) = session.try_frame() { |
| 8701 | frame = Some(f); |
| 8702 | break; |
| 8703 | } |
| 8704 | std::thread::sleep(std::time::Duration::from_millis(5)); |
| 8705 | } |
| 8706 | let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas")); |
| 8707 | assert_eq!( |
| 8708 | (frame.width, frame.height), |
| 8709 | (w, h), |
| 8710 | "a frame at the canvas's own size" |
| 8711 | ); |
| 8712 | } |
| 8713 | } |
| 8714 | |
| 8715 | /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is |
| 8716 | /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint. |
| 8717 | /// Straight alpha (255 in both) survives every weight, which is the one |
| 8718 | /// channel a wrong blend would otherwise fog. |
| 8719 | #[test] |
| 8720 | fn blend_bgra_interpolates_every_byte_including_alpha() { |
| 8721 | let a = [10u8, 20, 30, 255]; |
| 8722 | let b = [110u8, 120, 130, 255]; |
| 8723 | assert_eq!(blend_bgra(&a, &b, 0.0), a); |
| 8724 | assert_eq!(blend_bgra(&a, &b, 1.0), b); |
| 8725 | assert_eq!(blend_bgra(&a, &b, 0.5), [60, 70, 80, 255]); |
| 8726 | } |
| 8727 | |
| 8728 | /// A still wants the project's own pixels, not a view near them. |
| 8729 | /// [`PlaybackSession::set_view_size`] calls under 8 px no change at all (a |
| 8730 | /// window being dragged must not restart the picture every tick), so a |
| 8731 | /// caller that means "paint at the project's size" has to say it through |
| 8732 | /// [`PlaybackSession::set_view_size_exact`] -- and read its `false` as "the |
| 8733 | /// view is already there, the frame in hand is the one wanted", which is |
| 8734 | /// what stops it waiting for a picture nothing will reseek into existence. |
| 8735 | #[test] |
| 8736 | fn a_still_gets_the_exact_view_size_where_a_push_settles_for_near() { |
| 8737 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); |
| 8738 | assert!(session.set_resolution(1920, 1080)); |
| 8739 | let (w, h) = session.resolution(); |
| 8740 | assert_eq!((w, h), (1920, 1080)); |
| 8741 | // A preview-sized push, then the ask a still makes: two pixels short on |
| 8742 | // each axis, which the deadbanded push calls no change at all. |
| 8743 | assert!(session.set_view_size(1918, 1078)); |
| 8744 | assert!( |
| 8745 | std::ops::Not::not(session.set_view_size(w, h)), |
| 8746 | "the push's deadband is exactly what a still cannot use" |
| 8747 | ); |
| 8748 | assert_eq!( |
| 8749 | session.view_size(), |
| 8750 | (1918, 1078), |
| 8751 | "the push left the view near, not at, full -- so a still written now would be short" |
| 8752 | ); |
| 8753 | assert!( |
| 8754 | session.set_view_size_exact(w, h), |
| 8755 | "the exact setter must move a view the push called close enough" |
| 8756 | ); |
| 8757 | assert_eq!(session.view_size(), (w, h)); |
| 8758 | // ...and at the size already it says so rather than repainting: that |
| 8759 | // `false` is the caller's "write the frame you have". |
| 8760 | assert!(std::ops::Not::not(session.set_view_size_exact(w, h))); |
| 8761 | } |
| 8762 | |
| 8763 | /// The dissolve window's own edges, in the units [`PlaybackSession::start_span`] |
| 8764 | /// computes them in: a `tail_start` of `span.start + span.len - window` |
| 8765 | /// puts the very first output frame of the window at `idx_in_window == 0` |
| 8766 | /// and the very last at `window - 1`, clamped rather than overrun by a |
| 8767 | /// frame that lands exactly on the span's own end -- the same off-by-one |
| 8768 | /// a stray `%` or unclamped subtraction would have shown on screen as a |
| 8769 | /// blend that never quite reached full B. |
| 8770 | #[test] |
| 8771 | fn dissolve_window_edges_index_zero_to_window_minus_one() { |
| 8772 | let (span_start, span_len, window) = (100u32, 30u32, 10u32); |
| 8773 | let tail_start = span_start + span_len - window; |
| 8774 | assert_eq!(tail_start, 120); |
| 8775 | let idx_in_window = |frame: u32| (frame - tail_start).min(window - 1); |
| 8776 | assert_eq!(idx_in_window(120), 0, "first frame of the window"); |
| 8777 | assert_eq!(idx_in_window(129), 9, "last frame of the window"); |
| 8778 | assert_eq!( |
| 8779 | idx_in_window(130), |
| 8780 | 9, |
| 8781 | "one past the span's own end clamps rather than panics" |
| 8782 | ); |
| 8783 | } |
| 8784 | |
| 8785 | /// A picked project rate overrides the derived one, and its absence leaves |
| 8786 | /// the source's own -- the seam every explicit-sample-rate caller |
| 8787 | /// (playback rebuild, both export encoders) goes through |
| 8788 | /// ([`crate::AudioSession::open_multi_streams_speed_at`]). The per-segment |
| 8789 | /// conform chain resamples to whatever `meta` names, so the meta *is* the |
| 8790 | /// behaviour. |
| 8791 | #[test] |
| 8792 | fn a_picked_sample_rate_overrides_the_derived_one() { |
| 8793 | let file = asset("test_av.mp4"); |
| 8794 | let sources = [(file, 0)]; |
| 8795 | let segs = [(Some(0), 0., 1.)]; |
| 8796 | let derived = |
| 8797 | crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None) |
| 8798 | .expect("open the fixture") |
| 8799 | .expect("the fixture has sound") |
| 8800 | .0 |
| 8801 | .sample_rate; |
| 8802 | let picked = crate::AudioSession::open_multi_streams_speed_at( |
| 8803 | &sources, |
| 8804 | &segs, |
| 8805 | &[], |
| 8806 | &[], |
| 8807 | Some(32000), |
| 8808 | ) |
| 8809 | .expect("open the fixture") |
| 8810 | .expect("the fixture has sound") |
| 8811 | .0 |
| 8812 | .sample_rate; |
| 8813 | assert_ne!( |
| 8814 | derived, 32000, |
| 8815 | "a fixture at the picked rate proves nothing" |
| 8816 | ); |
| 8817 | assert_eq!(picked, 32000); |
| 8818 | } |
| 8819 | |
| 8820 | /// Which source the timeline's sound is opened on -- the one rule |
| 8821 | /// [`open_project`](PlaybackSession::open_project), the probe every import |
| 8822 | /// is held to and the audio worker all read through. A still at index 0 is |
| 8823 | /// a picture, not a silent timeline: opening the device on it is a project |
| 8824 | /// that plays silent although every clip on it has sound. |
| 8825 | #[test] |
| 8826 | fn the_audio_reference_is_never_a_still() { |
| 8827 | let (video, still) = (asset("test_av.mp4"), asset("test_still.png")); |
| 8828 | let sources = [Source::new(&still, 0), Source::new(&video, 3)]; |
| 8829 | assert_eq!( |
| 8830 | audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)), |
| 8831 | Some((&sources[1].path, 3)), |
| 8832 | "the first source that could have a track, with its own stream" |
| 8833 | ); |
| 8834 | assert!( |
| 8835 | audio_source_of(&sources[..1]).is_none(), |
| 8836 | "nothing but stills" |
| 8837 | ); |
| 8838 | assert!(audio_source_of(&[]).is_none(), "and no file at all"); |
| 8839 | } |
| 8840 | |
| 8841 | /// What a front end's "resolution/rate picked before any file is open" |
| 8842 | /// setting costs the engine: nothing new. `open` then `set_resolution`/ |
| 8843 | /// `set_frame_rate` right after construction -- the app's technique for |
| 8844 | /// applying a pre-import pick to the session it just made, mirroring |
| 8845 | /// [`PlaybackSession::open_project`]'s own `doc.resolution`/`doc.fps` |
| 8846 | /// override -- lands exactly where either setter lands it whenever it is |
| 8847 | /// called, and a later `import` of another file leaves both untouched: an |
| 8848 | /// import registers a source and its length, and never writes `meta.width`, |
| 8849 | /// `meta.height` or `meta.frame_rate`. |
| 8850 | #[test] |
| 8851 | fn a_pre_import_setting_survives_construction_and_a_later_import() { |
| 8852 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); |
| 8853 | let native = session.native_resolution(); |
| 8854 | let native_fps = session.native_frame_rate(); |
| 8855 | // The explicit picks a pre-import setting would apply, distinct from |
| 8856 | // the fixture's own so a no-op would be caught. |
| 8857 | let (picked_w, picked_h) = (1920, 1080); |
| 8858 | assert_ne!((picked_w, picked_h), native, "the test needs a real change"); |
| 8859 | let picked_fps = 24.0; |
| 8860 | assert_ne!(picked_fps, native_fps, "the test needs a real change"); |
| 8861 | assert!(session.set_resolution(picked_w, picked_h)); |
| 8862 | assert!(session.set_frame_rate(picked_fps)); |
| 8863 | assert_eq!(session.resolution(), (picked_w, picked_h)); |
| 8864 | assert_eq!(session.meta().frame_rate, picked_fps); |
| 8865 | |
| 8866 | // A second file joining the timeline is exactly the case the front end |
| 8867 | // worried a later import could silently override the explicit pick -- |
| 8868 | // it cannot, because `import` never touches the canvas. |
| 8869 | session |
| 8870 | .import(&asset("test_av2.mp4")) |
| 8871 | .expect("av2 matches the timeline it was set to"); |
| 8872 | assert_eq!( |
| 8873 | session.resolution(), |
| 8874 | (picked_w, picked_h), |
| 8875 | "an import must not move the project's own canvas size" |
| 8876 | ); |
| 8877 | assert_eq!( |
| 8878 | session.meta().frame_rate, |
| 8879 | picked_fps, |
| 8880 | "an import must not move the project's own rate" |
| 8881 | ); |
| 8882 | } |
| 8883 | |
| 8884 | #[test] |
| 8885 | fn an_audio_lane_walls_a_video_by_its_sound_and_a_video_lane_by_its_picture() { |
| 8886 | // A 2 s picture under 60 s of sound: the A1 half of a placed take can be |
| 8887 | // trimmed out to the sound's end, the V1 half only to the picture's. |
| 8888 | let path = asset("test_short_video_long_audio.mp4"); |
| 8889 | let mut session = PlaybackSession::open(&path).expect("open the fixture"); |
| 8890 | session.set_gain(0.0); |
| 8891 | let fps = session.meta().frame_rate; |
| 8892 | // Placed at the end, so nothing sits in front of it and the walls are the |
| 8893 | // source's own, not a neighbour's. |
| 8894 | let end = session.timeline_duration(); |
| 8895 | assert!( |
| 8896 | session |
| 8897 | .place_stream_at(end, &path, 0, Some(Lane::A1)) |
| 8898 | .expect("a file on this timeline is placeable") |
| 8899 | ); |
| 8900 | let a1 = session.lane_clips(Lane::A1).len() - 1; |
| 8901 | let v1 = session.lane_clips(Lane::V1).len() - 1; |
| 8902 | |
| 8903 | let audio = session.trim_walls(Lane::A1, a1, Edge::End).expect("A1 clip"); |
| 8904 | let picture = session.trim_walls(Lane::V1, v1, Edge::End).expect("V1 clip"); |
| 8905 | let placed = (end * fps).round(); |
| 8906 | assert!( |
| 8907 | audio.hi as f64 >= placed + 59.0 * fps, |
| 8908 | "the sound is 60 s: the A1 end may reach {} frames at {fps} fps", |
| 8909 | audio.hi |
| 8910 | ); |
| 8911 | assert!( |
| 8912 | (picture.hi as f64) < placed + 3.0 * fps, |
| 8913 | "the picture is 2 s: the V1 end stops at {} frames", |
| 8914 | picture.hi |
| 8915 | ); |
| 8916 | assert!( |
| 8917 | session.trim_clip(Lane::A1, a1, Edge::End, (placed + 40.0 * fps) as u32), |
| 8918 | "the A1 clip trims to 40 s" |
| 8919 | ); |
| 8920 | assert_eq!(session.lane_clips(Lane::A1)[a1].len(), (40.0 * fps) as u32); |
| 8921 | } |
| 8922 | |
| 8923 | /// The seam between the two lists a source index reaches: dropping a file |
| 8924 | /// from the library shortens `sources`, and `counts` -- the frame length |
| 8925 | /// per source, which is what a trim is walled by -- has to lose the same |
| 8926 | /// entry. Left behind, the dead file's length would wall the survivor. |
| 8927 | #[test] |
| 8928 | fn removing_a_source_takes_its_frame_count_with_it() { |
| 8929 | // Source 0 is 5 s, source 1 is 4 s: two different walls, so a stale |
| 8930 | // count cannot pass for the right one. |
| 8931 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); |
| 8932 | session.set_gain(0.0); |
| 8933 | // Imported, then dragged onto the end -- an import alone places nothing |
| 8934 | // ([`PlaybackSession::import`]), and this test needs both takes there. |
| 8935 | session.import(&asset("test_av2.mp4")).expect("av2 matches"); |
| 8936 | let end = session.timeline_duration(); |
| 8937 | assert!( |
| 8938 | session |
| 8939 | .place_stream_at(end, &asset("test_av2.mp4"), 0, None) |
| 8940 | .expect("a file just imported is on this timeline") |
| 8941 | ); |
| 8942 | let (long, short) = (session.counts[0], session.counts[1]); |
| 8943 | assert!(long > short, "{long} vs {short}"); |
| 8944 | |
| 8945 | // Clear source 0's take, then take the file itself out: av2's clip is |
| 8946 | // the only one left and it is source 0 now. |
| 8947 | assert!(session.delete_clip(Lane::V1, 0)); |
| 8948 | session |
| 8949 | .remove_source(&asset("test_av.mp4"), 0) |
| 8950 | .expect("nothing plays it any more"); |
| 8951 | assert_eq!(session.counts, vec![short], "the dead length went with it"); |
| 8952 | assert_eq!(session.sources().len(), session.counts.len()); |
| 8953 | |
| 8954 | // The wall is the surviving file's own length, not the gone one's: a |
| 8955 | // whole-file clip cannot be dragged out any further at all. |
| 8956 | let clip = session.lane_clips(Lane::V1)[0].clone(); |
| 8957 | assert_eq!(clip.len(), short, "av2's take, whole"); |
| 8958 | assert_eq!( |
| 8959 | session.trim_room(Lane::V1, 0, Edge::End), |
| 8960 | Some((clip.start + 1, clip.end())) |
| 8961 | ); |
| 8962 | assert!( |
| 8963 | !session.trim_clip(Lane::V1, 0, Edge::End, clip.end() + 30), |
| 8964 | "past the file's last frame is refused, by ITS length" |
| 8965 | ); |
| 8966 | |
| 8967 | // ...and the next import still lines the two lists up, which is the |
| 8968 | // alignment `note_frames` asserts on. |
| 8969 | session |
| 8970 | .import(&asset("test_av.mp4")) |
| 8971 | .expect("it may come back"); |
| 8972 | assert_eq!(session.counts, vec![short, long]); |
| 8973 | assert_eq!(session.sources().len(), session.counts.len()); |
| 8974 | } |
| 8975 | |
| 8976 | /// The two headers a place reads are read *once*: an mp4 dropped on a lane |
| 8977 | /// used to open its own container and the timeline's first source every |
| 8978 | /// time, both on the thread that draws, and a film whose pages have gone |
| 8979 | /// cold is 1.7 s of that. |
| 8980 | /// |
| 8981 | /// Proved by answering, not by timing: the memo is filled with a layout the |
| 8982 | /// file does not have, and the place is refused. Only a door that read the |
| 8983 | /// remembered header rather than the disk can refuse it. |
| 8984 | #[test] |
| 8985 | fn a_place_reads_each_audio_header_once() { |
| 8986 | let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); |
| 8987 | session.set_gain(0.0); |
| 8988 | session.import(&asset("test_av2.mp4")).expect("av2 matches"); |
| 8989 | let end = session.timeline_duration(); |
| 8990 | assert!( |
| 8991 | session |
| 8992 | .place_stream_at(end, &asset("test_av2.mp4"), 0, None) |
| 8993 | .expect("a file just imported is on this timeline") |
| 8994 | ); |
| 8995 | assert_eq!( |
| 8996 | session.probes.len(), |
| 8997 | 2, |
| 8998 | "the timeline's first source and the file placed, once each" |
| 8999 | ); |
| 9000 | |
| 9001 | // Now say av2 is 5.1. Nothing on disk changed, so a door that opens the |
| 9002 | // file still matches; one that trusts the memo refuses by layout. |
| 9003 | // Keyed exactly as a [`Source`] names a file -- canonical, symlinks |
| 9004 | // resolved -- which is the key the doors look up. |
| 9005 | let av2 = Source::new(asset("test_av2.mp4"), 0).path; |
| 9006 | session.probes.insert( |
| 9007 | (av2, 0), |
| 9008 | Some(crate::AudioProbe { |
| 9009 | sample_rate: 48_000, |
| 9010 | channels: 6, |
| 9011 | }), |
| 9012 | ); |
| 9013 | let refused = session |
| 9014 | .place_stream_at(end, &asset("test_av2.mp4"), 0, None) |
| 9015 | .expect_err("the remembered layout disagrees with the timeline's"); |
| 9016 | assert!( |
| 9017 | refused.to_string().contains("6 ch"), |
| 9018 | "refused in the layout's own words: {refused}" |
| 9019 | ); |
| 9020 | assert_eq!(session.probes.len(), 2, "and nothing was opened to say so"); |
| 9021 | } |
| 9022 | |
| 9023 | /// The door a library preview opens a chosen stream through: `test_multiaudio.mp4` |
| 9024 | /// has stream 0 stereo and stream 1 mono |
| 9025 | /// ([`crate::waveform::tests::each_stream_of_a_file_has_its_own_envelope`] |
| 9026 | /// names the same fixture), so a session that actually bound the stream it |
| 9027 | /// was asked for plays a different layout than one that did not -- and |
| 9028 | /// plain [`PlaybackSession::open`] still lands on stream 0, unchanged. |
| 9029 | #[test] |
| 9030 | fn open_with_audio_stream_binds_the_named_track() { |
| 9031 | let multi = asset("test_multiaudio.mp4"); |
| 9032 | let zero = PlaybackSession::open_with_audio_stream(&multi, 0).expect("stream 0 opens"); |
| 9033 | let one = PlaybackSession::open_with_audio_stream(&multi, 1).expect("stream 1 opens"); |
| 9034 | let default = PlaybackSession::open(&multi).expect("default open"); |
| 9035 | let (Some(a0), Some(a1), Some(ad)) = ( |
| 9036 | zero.audio.as_ref(), |
| 9037 | one.audio.as_ref(), |
| 9038 | default.audio.as_ref(), |
| 9039 | ) else { |
| 9040 | // No audio device on this machine: nothing further to check -- |
| 9041 | // the device is the machine's business, not this door's. |
| 9042 | return; |
| 9043 | }; |
| 9044 | assert_eq!(a0.channels, 2, "stream 0 is the stereo pair"); |
| 9045 | assert_eq!(a1.channels, 1, "stream 1 is the mono track"); |
| 9046 | assert_ne!(a0.channels, a1.channels, "the two streams must differ"); |
| 9047 | assert_eq!( |
| 9048 | ad.channels, a0.channels, |
| 9049 | "open() still defaults to stream 0" |
| 9050 | ); |
| 9051 | } |
| 9052 | |
| 9053 | /// The bug this regression pins: a preview paused (or scrubbed) to a |
| 9054 | /// frame inside a dissolve window used to show plain A forever, because |
| 9055 | /// B's decoder only opened on the tick that landed in the window and |
| 9056 | /// nothing polled `try_frame` again while the clock stood still |
| 9057 | /// (`Player::pump` only drains while playing or a seek is owed, and one |
| 9058 | /// delivered frame clears "owed"). Two clips of real fixtures, touching, |
| 9059 | /// with a dissolve set on the join -- seeking into the window and taking |
| 9060 | /// exactly one frame (no play, no second tick) must already show a blend: |
| 9061 | /// the same position with the dissolve turned off must differ from it. |
| 9062 | #[test] |
| 9063 | fn a_single_paused_tick_inside_the_dissolve_window_is_already_blended() { |
| 9064 | let window = 6u32; |
| 9065 | let build = |transition: u32| { |
| 9066 | let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open a"); |
| 9067 | s.set_gain(0.0); |
| 9068 | s.import(&asset("test_av2.mp4")).expect("av2 matches"); |
| 9069 | let end = s.timeline_duration(); |
| 9070 | assert!( |
| 9071 | s.place_stream_at(end, &asset("test_av2.mp4"), 0, None) |
| 9072 | .expect("av2, placed right after a") |
| 9073 | ); |
| 9074 | if transition > 0 { |
| 9075 | assert!(s.set_transition_out(Lane::V1, 0, transition)); |
| 9076 | } |
| 9077 | s |
| 9078 | }; |
| 9079 | let mut on = build(window); |
| 9080 | let mut off = build(0); |
| 9081 | |
| 9082 | let fps = on.meta().frame_rate; |
| 9083 | let clip0_len = on.lane_clips(Lane::V1)[0].len(); |
| 9084 | assert!( |
| 9085 | clip0_len > window, |
| 9086 | "the fixture needs to outlast the window" |
| 9087 | ); |
| 9088 | let mid_of_window = clip0_len - window / 2; |
| 9089 | let t = f64::from(mid_of_window) / fps; |
| 9090 | |
| 9091 | // One seek, then one frame -- exactly what a paused preview's single |
| 9092 | // repaint asks the engine for. Polled rather than taken on the first |
| 9093 | // call because the seek itself just restarted the decoder |
| 9094 | // (`start_span`) and its first picture is not synchronous; once |
| 9095 | // *a* frame lands this is the one tick under test. |
| 9096 | let frame_at = |s: &mut PlaybackSession| -> crate::decode::Frame { |
| 9097 | s.seek(t); |
| 9098 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); |
| 9099 | loop { |
| 9100 | if let Some(f) = s.try_frame() { |
| 9101 | return f; |
| 9102 | } |
| 9103 | assert!( |
| 9104 | std::time::Instant::now() < deadline, |
| 9105 | "no frame within 120s of the seek" |
| 9106 | ); |
| 9107 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 9108 | } |
| 9109 | }; |
| 9110 | |
| 9111 | let off_frame = frame_at(&mut off); |
| 9112 | let on_frame = frame_at(&mut on); |
| 9113 | assert_eq!(on_frame.index, off_frame.index, "same timeline position"); |
| 9114 | assert_ne!( |
| 9115 | on_frame.bgra, off_frame.bgra, |
| 9116 | "paused inside the window, the dissolve must already show B blended in" |
| 9117 | ); |
| 9118 | } |
| 9119 | |
| 9120 | #[test] |
| 9121 | fn boundary_seconds_round_trip_to_their_own_frame() { |
| 9122 | for f in 0u32..300 { |
| 9123 | let secs = f64::from(f) / 30.0; |
| 9124 | assert_eq!(secs_to_frame(secs, 30.0), f, "frame {f}"); |
| 9125 | } |
| 9126 | // Mid-frame positions still floor, and negatives clamp. |
| 9127 | assert_eq!(secs_to_frame(10.5 / 30.0, 30.0), 10); |
| 9128 | assert_eq!(secs_to_frame(-0.2, 30.0), 0); |
| 9129 | } |
| 9130 | |
| 9131 | /// A paused transform nudge -- `set_transform_live` at the position the |
| 9132 | /// picture already stands on -- never pays a full decoder restart: the |
| 9133 | /// worker is reused (`Worker::reseek`), never replaced |
| 9134 | /// (`PlaybackSession::retire`), so `restarts()` does not move. Guards the |
| 9135 | /// path a card's live edits go through against a future change routing |
| 9136 | /// them back through `seek`/a fresh worker, and a gap left between two |
| 9137 | /// edits (a person's think-time between nudges) longer than the *old* |
| 9138 | /// hardware-idle window still counts zero restarts -- a decoder worker |
| 9139 | /// outliving its span is not a "restart" this counter (or a caller) sees, |
| 9140 | /// whatever the hardware session inside it did. |
| 9141 | #[test] |
| 9142 | fn a_paused_transform_nudge_reuses_the_worker_not_a_restart() { |
| 9143 | let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); |
| 9144 | s.set_gain(0.0); |
| 9145 | let poll = |s: &mut PlaybackSession| -> crate::decode::Frame { |
| 9146 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); |
| 9147 | loop { |
| 9148 | if let Some(f) = s.try_frame() { |
| 9149 | return f; |
| 9150 | } |
| 9151 | assert!(std::time::Instant::now() < deadline, "no frame within 120s"); |
| 9152 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 9153 | } |
| 9154 | }; |
| 9155 | let first = poll(&mut s); |
| 9156 | let before = s.restarts(); |
| 9157 | |
| 9158 | // A gap past the pre-fix 2s hardware-idle window: the whole point of |
| 9159 | // widening it is that a nudge landing here still reuses the worker. |
| 9160 | std::thread::sleep(std::time::Duration::from_millis(2500)); |
| 9161 | |
| 9162 | let clip = s.video_clip_at(s.now()).expect("a clip under the playhead"); |
| 9163 | let params = TransformParams { |
| 9164 | scale: 1.2, |
| 9165 | ..Default::default() |
| 9166 | }; |
| 9167 | assert!( |
| 9168 | s.set_transform_live(clip.0, clip.1, Some(params)), |
| 9169 | "the edit took" |
| 9170 | ); |
| 9171 | let next = poll(&mut s); |
| 9172 | |
| 9173 | assert_eq!( |
| 9174 | before, |
| 9175 | s.restarts(), |
| 9176 | "a live transform edit must reuse the worker" |
| 9177 | ); |
| 9178 | assert_eq!( |
| 9179 | next.index, first.index, |
| 9180 | "paused: same timeline position before and after" |
| 9181 | ); |
| 9182 | } |
| 9183 | |
| 9184 | /// A rate undo lands the picture where the playhead is, in the rate that |
| 9185 | /// came *back*: the entry a pick takes carries the old numbering beside the |
| 9186 | /// old rate, so an undo restores both and the reseek has to be computed |
| 9187 | /// after the restore. Computed before it, the landing is the pre-undo |
| 9188 | /// rate's reading of the post-undo project -- `now` clamps to the pre-undo |
| 9189 | /// rate's idea of the timeline's end and the worker is handed the last |
| 9190 | /// frame of a five-second timeline for a playhead at three seconds. |
| 9191 | #[test] |
| 9192 | fn a_rate_undo_reseeks_at_the_rate_it_restored() { |
| 9193 | let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); |
| 9194 | s.set_gain(0.0); |
| 9195 | let poll = |s: &mut PlaybackSession| -> crate::decode::Frame { |
| 9196 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); |
| 9197 | loop { |
| 9198 | if let Some(f) = s.try_frame() { |
| 9199 | return f; |
| 9200 | } |
| 9201 | assert!(std::time::Instant::now() < deadline, "no frame within 120s"); |
| 9202 | std::thread::sleep(std::time::Duration::from_millis(10)); |
| 9203 | } |
| 9204 | }; |
| 9205 | let native = s.native_frame_rate(); |
| 9206 | s.seek(3.0); |
| 9207 | assert_eq!(s.now(), 3.0, "the fixture is five seconds long"); |
| 9208 | assert!(s.set_frame_rate(native * 2.0), "the rate pick"); |
| 9209 | assert!(s.undo(), "the pick is one step"); |
| 9210 | assert_eq!(s.meta().frame_rate, native, "the rate came back"); |
| 9211 | assert_eq!( |
| 9212 | s.now(), |
| 9213 | 3.0, |
| 9214 | "the playhead is the seconds it was, read at the rate that came back" |
| 9215 | ); |
| 9216 | // The worker's own landing, which is the half the clock alone cannot |
| 9217 | // show: a frame 149 of 150 is exactly the pre-undo rate's clamp. |
| 9218 | assert_eq!( |
| 9219 | s.span.expect("a span for the picture").start, |
| 9220 | secs_to_frame(3.0, native), |
| 9221 | "the picture was asked for the playhead's own frame" |
| 9222 | ); |
| 9223 | let frame = poll(&mut s); |
| 9224 | assert_eq!( |
| 9225 | frame.index, |
| 9226 | secs_to_frame(3.0, native), |
| 9227 | "and that is the frame that arrived" |
| 9228 | ); |
| 9229 | } |
| 9230 | |
| 9231 | /// The session's live look samples leave its history exactly where the |
| 9232 | /// press left it -- the colour-wheel drag's twin for the packed look, and |
| 9233 | /// what lets the app drive one from a pointer: `z` after a drag lands |
| 9234 | /// before the press, not one sample back down the drag. |
| 9235 | #[test] |
| 9236 | fn a_live_look_drag_is_one_step_of_the_sessions_history() { |
| 9237 | let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); |
| 9238 | let (lane, idx) = s.video_clip_at(s.now()).expect("a clip under the playhead"); |
| 9239 | let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue); |
| 9240 | assert!(s.set_viz_paint(lane, idx, look(1)), "the press"); |
| 9241 | for hue in 2..=6u8 { |
| 9242 | assert!(s.set_viz_paint_live(lane, idx, look(hue)), "a sample"); |
| 9243 | } |
| 9244 | assert_eq!(s.project.lane(lane)[idx].viz_paint, look(6)); |
| 9245 | assert!(s.undo(), "the drag's own step"); |
| 9246 | assert_eq!( |
| 9247 | s.project.lane(lane)[idx].viz_paint, |
| 9248 | 0, |
| 9249 | "one undo is the whole drag" |
| 9250 | ); |
| 9251 | } |
| 9252 | |
| 9253 | #[test] |
| 9254 | fn solo_keeps_only_the_soloed_audio_lanes_audible() { |
| 9255 | use super::soloed_gains; |
| 9256 | use crate::project::LaneKind; |
| 9257 | let a1 = Lane::new(LaneKind::Audio, 0); |
| 9258 | let a2 = Lane::new(LaneKind::Audio, 1); |
| 9259 | let a3 = Lane::new(LaneKind::Audio, 2); |
| 9260 | let v1 = Lane::new(LaneKind::Video, 0); |
| 9261 | let audio = [a1, a2, a3]; |
| 9262 | let gains = vec![1.0, 0.5, 0.0]; |
| 9263 | assert_eq!( |
| 9264 | soloed_gains(gains.clone(), &audio, &[a2]), |
| 9265 | vec![0.0, 0.5, 0.0], |
| 9266 | "the others go silent, the soloed one keeps its own gain" |
| 9267 | ); |
| 9268 | assert_eq!( |
| 9269 | soloed_gains(gains.clone(), &audio, &[]), |
| 9270 | vec![1.0, 0.5, 0.0], |
| 9271 | "no solo changes nothing" |
| 9272 | ); |
| 9273 | assert_eq!( |
| 9274 | soloed_gains(gains.clone(), &audio, &[v1]), |
| 9275 | vec![1.0, 0.5, 0.0], |
| 9276 | "a video lane is no audio solo" |
| 9277 | ); |
| 9278 | assert_eq!( |
| 9279 | soloed_gains(gains.clone(), &[a1, a3], &[a2]), |
| 9280 | vec![1.0, 0.5, 0.0], |
| 9281 | "a solo naming no audio lane any more is no solo" |
| 9282 | ); |
| 9283 | } |
| 9284 | } |