trix-player 1.0.0

A beautiful, keyboard-driven terminal music player for Linux.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::{
    collections::VecDeque,
    fs::File,
    io::BufReader,
    path::{Path, PathBuf},
    time::Duration,
};

use anyhow::{anyhow, Context, Result};
use rodio::Source;
use symphonia::core::{
    audio::SampleBuffer,
    codecs::{Decoder, DecoderOptions},
    errors::Error as SymphoniaError,
    formats::{FormatOptions, FormatReader, SeekMode, SeekTo},
    io::MediaSourceStream,
    meta::MetadataOptions,
    probe::Hint,
    units::Time,
};

pub fn open_source(
    path: &Path,
    start_pos: Duration,
    loop_enabled: bool,
) -> Result<(Box<dyn Source<Item = f32> + Send>, Option<Duration>)> {
    // Prefer our own Symphonia source, because it allows us to disable strict
    // verification and to recover from decode errors.
    match SymphoniaSource::try_new(path.to_path_buf(), start_pos, loop_enabled) {
        Ok(src) => {
            let total = src.total_duration();
            return Ok((Box::new(src), total));
        }
        Err(primary) => {
            // Fallback to rodio's built-in decoder.
            // This can still succeed for formats Symphonia doesn't handle well
            // in our streaming wrapper.
            let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
            let reader = BufReader::new(file);
            let decoder = rodio::Decoder::new(reader)
                .with_context(|| format!("rodio decode failed: {primary:#}"))?;
            let total = decoder.total_duration();
            let source = decoder.skip_duration(start_pos).convert_samples();
            let source: Box<dyn Source<Item = f32> + Send> = if loop_enabled {
                Box::new(source.repeat_infinite())
            } else {
                Box::new(source)
            };
            Ok((source, total))
        }
    }
}

struct SymphoniaSource {
    path: PathBuf,
    loop_enabled: bool,

    // Decoder state.
    format: Box<dyn FormatReader>,
    decoder: Box<dyn Decoder>,
    track_id: u32,

    // Audio format.
    sample_rate: u32,
    channels: u16,

    // Playback.
    total: Option<Duration>,
    fifo: VecDeque<f32>,
    skip_samples: u64,

    // Error recovery.
    consecutive_decode_errors: u32,
}

impl SymphoniaSource {
    fn try_new(path: PathBuf, start_pos: Duration, loop_enabled: bool) -> Result<Self> {
        let (format, track_id) = open_format(&path)?;

        let track = format
            .tracks()
            .iter()
            .find(|t| t.id == track_id)
            .cloned()
            .ok_or_else(|| anyhow!("no default track"))?;

        let total = best_effort_duration(&track.codec_params);

        let decoder = symphonia::default::get_codecs()
            .make(
                &track.codec_params,
                &DecoderOptions {
                    // This is the key to being more tolerant of "almost valid" MP3s.
                    // Many players rely on ffmpeg-style error recovery; we emulate that
                    // by disabling strict verification and skipping bad frames.
                    verify: false,
                    ..Default::default()
                },
            )
            .context("create decoder")?;

        let mut source = Self {
            path,
            loop_enabled,
            format,
            decoder,
            track_id,
            sample_rate: track.codec_params.sample_rate.unwrap_or(48_000),
            channels: track
                .codec_params
                .channels
                .map(|c| c.count() as u16)
                .unwrap_or(2),
            total,
            fifo: VecDeque::with_capacity(48_000),
            skip_samples: 0,
            consecutive_decode_errors: 0,
        };

        // Seek to the desired position using Symphonia's container seeking when possible.
        // This avoids decoding from the start (which can starve the audio thread and
        // cause ALSA underruns when the user seeks rapidly).
        if start_pos > Duration::ZERO {
            if source.try_seek_to(start_pos).is_err() {
                // Fallback: decode-and-discard (slow, but done before playback starts).
                let start_frames = (start_pos.as_secs_f64() * source.sample_rate as f64)
                    .max(0.0)
                    .round() as u64;
                source.skip_samples = start_frames.saturating_mul(source.channels as u64);
            }
        }

        // Prime the decoder so we can fail early instead of hanging on a corrupt stream.
        source.prime_and_apply_initial_skip()?;
        Ok(source)
    }

    fn next_track_packet(&mut self) -> Result<symphonia::core::formats::Packet> {
        loop {
            let packet = match self.format.next_packet() {
                Ok(p) => p,
                Err(SymphoniaError::IoError(_)) => return Err(anyhow!("eof")),
                Err(SymphoniaError::ResetRequired) => {
                    self.decoder.reset();
                    continue;
                }
                Err(e) => return Err(anyhow!(e)),
            };

            if packet.track_id() != self.track_id {
                continue;
            }

            return Ok(packet);
        }
    }

    fn try_seek_to(&mut self, pos: Duration) -> Result<()> {
        let time: Time = pos.as_secs_f64().into();
        let seek_res = self
            .format
            .seek(
                SeekMode::Accurate,
                SeekTo::Time {
                    time,
                    track_id: Some(self.track_id),
                },
            )
            .context("symphonia seek")?;

        // After seeking, refine within the next packet so playback starts close to
        // the requested time.
        self.decoder.reset();
        self.fifo.clear();

        // `SeekedTo` is expressed in the track's timebase (typically frames). We now need
        // to skip `required_ts - actual_ts` frames into the first decoded packet.
        let mut frames_to_pass = seek_res.required_ts.saturating_sub(seek_res.actual_ts);

        // Find the first packet that overlaps the desired position.
        let packet = loop {
            let candidate = self.next_track_packet()?;
            if candidate.dur() > frames_to_pass {
                break candidate;
            }
            frames_to_pass = frames_to_pass.saturating_sub(candidate.dur());
        };

        // Decode with a couple retries to tolerate bad frames.
        const MAX_DECODE_RETRIES: usize = 3;
        let mut decoded = self.decoder.decode(&packet);
        for _ in 0..MAX_DECODE_RETRIES {
            if decoded.is_ok() {
                break;
            }
            let retry_packet = self.next_track_packet()?;
            decoded = self.decoder.decode(&retry_packet);
        }

        let audio = decoded.context("decode after seek")?;
        let spec = *audio.spec();
        let mut sample_buf = SampleBuffer::<f32>::new(audio.frames() as u64, spec);
        sample_buf.copy_interleaved_ref(audio);

        // Track observed format (best-effort).
        self.sample_rate = self.sample_rate.max(spec.rate).max(1);
        self.channels = self.channels.max(spec.channels.count() as u16).max(1);

        let ch = spec.channels.count().max(1);
        let offset = (frames_to_pass as usize).saturating_mul(ch);
        if offset < sample_buf.samples().len() {
            self.fifo.extend(sample_buf.samples()[offset..].iter().copied());
        }

        // Seeking is now handled; no additional skip budget required.
        self.skip_samples = 0;
        Ok(())
    }

    fn prime_and_apply_initial_skip(&mut self) -> Result<()> {
        // Ensure we have samples and, if we couldn't seek, apply an initial skip budget
        // up-front (so the audio thread doesn't have to decode-and-discard).
        let mut packets_seen = 0u32;
        while packets_seen < 1_000 {
            packets_seen += 1;

            if self.fifo.is_empty() {
                let _ = self.decode_more();
            }

            while self.skip_samples > 0 {
                if self.fifo.pop_front().is_some() {
                    self.skip_samples -= 1;
                } else {
                    break;
                }
            }

            if self.skip_samples == 0 && !self.fifo.is_empty() {
                return Ok(());
            }
        }

        Err(anyhow!(
            "no decodable audio frames (stream may be badly corrupted, unsupported, or unseekable)"
        ))
    }

    fn reopen_for_loop(&mut self) -> Result<()> {
        let (format, track_id) = open_format(&self.path)?;
        self.format = format;
        self.track_id = track_id;

        let track = self
            .format
            .tracks()
            .iter()
            .find(|t| t.id == track_id)
            .ok_or_else(|| anyhow!("no default track"))?;

        self.decoder = symphonia::default::get_codecs().make(
            &track.codec_params,
            &DecoderOptions {
                verify: false,
                ..Default::default()
            },
        )?;

        self.fifo.clear();
        self.skip_samples = 0;
        self.consecutive_decode_errors = 0;
        Ok(())
    }

    fn decode_more(&mut self) -> Result<()> {
        loop {
            let packet = self.next_track_packet()?;

            match self.decoder.decode(&packet) {
                Ok(audio) => {
                    self.consecutive_decode_errors = 0;

                    // Convert to interleaved f32 *immediately* so we don't keep
                    // a borrow from the decoder alive.
                    let spec = *audio.spec();
                    let mut sample_buf =
                        SampleBuffer::<f32>::new(audio.frames() as u64, spec);
                    sample_buf.copy_interleaved_ref(audio);

                    // Track observed format (best-effort). If it changes mid-stream,
                    // keep the original. Rodio expects these to stay stable.
                    if self.sample_rate == 0 {
                        self.sample_rate = spec.rate;
                    }
                    if self.channels == 0 {
                        self.channels = spec.channels.count() as u16;
                    }

                    self.fifo.extend(sample_buf.samples());
                    return Ok(());
                }
                Err(SymphoniaError::DecodeError(_)) => {
                    // Bad frame: skip and continue.
                    self.consecutive_decode_errors = self.consecutive_decode_errors.saturating_add(1);
                    if self.consecutive_decode_errors > 1_000 {
                        return Err(anyhow!("too many consecutive decode errors"));
                    }
                    continue;
                }
                Err(SymphoniaError::ResetRequired) => {
                    self.decoder.reset();
                    continue;
                }
                Err(e) => return Err(anyhow!(e)),
            }
        }
    }
}

impl Iterator for SymphoniaSource {
    type Item = f32;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // Ensure we have data.
            if self.fifo.is_empty() {
                match self.decode_more() {
                    Ok(()) => {}
                    Err(_) => {
                        if self.loop_enabled {
                            if self.reopen_for_loop().is_ok() {
                                continue;
                            }
                        }
                        return None;
                    }
                }
            }

            // Apply initial skip.
            while self.skip_samples > 0 {
                if self.fifo.pop_front().is_some() {
                    self.skip_samples -= 1;
                } else {
                    break;
                }
            }

            if self.skip_samples > 0 {
                continue;
            }

            if let Some(s) = self.fifo.pop_front() {
                return Some(s);
            }
        }
    }
}

impl Source for SymphoniaSource {
    fn current_frame_len(&self) -> Option<usize> {
        None
    }

    fn channels(&self) -> u16 {
        self.channels.max(1)
    }

    fn sample_rate(&self) -> u32 {
        self.sample_rate.max(1)
    }

    fn total_duration(&self) -> Option<Duration> {
        self.total
    }
}

fn open_format(path: &Path) -> Result<(Box<dyn FormatReader>, u32)> {
    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
    let mss = MediaSourceStream::new(Box::new(file), Default::default());

    let mut hint = Hint::new();
    if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
        hint.with_extension(ext);
    }

    let probed = symphonia::default::get_probe().format(
        &hint,
        mss,
        &FormatOptions::default(),
        &MetadataOptions::default(),
    )?;

    let track_id = probed
        .format
        .default_track()
        .or_else(|| probed.format.tracks().first())
        .ok_or_else(|| anyhow!("no tracks in container"))?
        .id;

    Ok((probed.format, track_id))
}

fn best_effort_duration(params: &symphonia::core::codecs::CodecParameters) -> Option<Duration> {
    if let (Some(time_base), Some(n_frames)) = (params.time_base, params.n_frames) {
        let Time { seconds, frac, .. } = time_base.calc_time(n_frames);
        return Some(Duration::from_secs(seconds) + Duration::from_secs_f64(frac));
    }

    if let (Some(sample_rate), Some(n_frames)) = (params.sample_rate, params.n_frames) {
        let secs = n_frames as f64 / sample_rate as f64;
        if secs.is_finite() && secs > 0.0 {
            return Some(Duration::from_secs_f64(secs));
        }
    }

    None
}