-
Notifications
You must be signed in to change notification settings - Fork 127
/
main.rs
750 lines (640 loc) · 26.4 KB
/
main.rs
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
// Symphonia
// Copyright (c) 2019-2022 The Project Symphonia Developers.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
#![warn(rust_2018_idioms)]
#![forbid(unsafe_code)]
// Justification: Fields on DecoderOptions and FormatOptions may change at any time, but
// symphonia-play doesn't want to be updated every time those fields change, therefore always fill
// in the remaining fields with default values.
#![allow(clippy::needless_update)]
use std::fs::File;
use std::io::Write;
use std::path::Path;
use lazy_static::lazy_static;
use symphonia::core::codecs::{DecoderOptions, FinalizeResult, CODEC_TYPE_NULL};
use symphonia::core::errors::{Error, Result};
use symphonia::core::formats::{Cue, FormatOptions, FormatReader, SeekMode, SeekTo, Track};
use symphonia::core::io::{MediaSource, MediaSourceStream, ReadOnlySource};
use symphonia::core::meta::{ColorMode, MetadataOptions, MetadataRevision, Tag, Value, Visual};
use symphonia::core::probe::{Hint, ProbeResult};
use symphonia::core::units::{Time, TimeBase};
use clap::{Arg, ArgMatches};
use log::{error, info, warn};
mod output;
#[cfg(not(target_os = "linux"))]
mod resampler;
fn main() {
pretty_env_logger::init();
let args = clap::Command::new("Symphonia Play")
.version("1.0")
.author("Philip Deljanov <philip.deljanov@gmail.com>")
.about("Play audio with Symphonia")
.arg(
Arg::new("seek")
.long("seek")
.short('s')
.value_name("TIME")
.help("Seek to the given time in seconds")
.conflicts_with_all(&["verify", "decode-only", "verify-only", "probe-only"]),
)
.arg(
Arg::new("track").long("track").short('t').value_name("TRACK").help("The track to use"),
)
.arg(
Arg::new("decode-only")
.long("decode-only")
.help("Decode, but do not play the audio")
.conflicts_with_all(&["probe-only", "verify-only", "verify"]),
)
.arg(
Arg::new("probe-only")
.long("probe-only")
.help("Only probe the input for metadata")
.conflicts_with_all(&["decode-only", "verify-only"]),
)
.arg(
Arg::new("verify-only")
.long("verify-only")
.help("Verify the decoded audio is valid, but do not play the audio")
.conflicts_with_all(&["verify"]),
)
.arg(
Arg::new("verify")
.long("verify")
.short('v')
.help("Verify the decoded audio is valid during playback"),
)
.arg(Arg::new("no-progress").long("no-progress").help("Do not display playback progress"))
.arg(
Arg::new("no-gapless").long("no-gapless").help("Disable gapless decoding and playback"),
)
.arg(
Arg::new("INPUT")
.help("The input file path, or - to use standard input")
.required(true)
.index(1),
)
.get_matches();
// For any error, return an exit code -1. Otherwise return the exit code provided.
let code = match run(&args) {
Ok(code) => code,
Err(err) => {
error!("{}", err.to_string().to_lowercase());
-1
}
};
std::process::exit(code)
}
fn run(args: &ArgMatches) -> Result<i32> {
let path_str = args.value_of("INPUT").unwrap();
// Create a hint to help the format registry guess what format reader is appropriate.
let mut hint = Hint::new();
// If the path string is '-' then read from standard input.
let source = if path_str == "-" {
Box::new(ReadOnlySource::new(std::io::stdin())) as Box<dyn MediaSource>
}
else {
// Othwerise, get a Path from the path string.
let path = Path::new(path_str);
// Provide the file extension as a hint.
if let Some(extension) = path.extension() {
if let Some(extension_str) = extension.to_str() {
hint.with_extension(extension_str);
}
}
Box::new(File::open(path)?)
};
// Create the media source stream using the boxed media source from above.
let mss = MediaSourceStream::new(source, Default::default());
// Use the default options for format readers other than for gapless playback.
let format_opts =
FormatOptions { enable_gapless: !args.is_present("no-gapless"), ..Default::default() };
// Use the default options for metadata readers.
let metadata_opts: MetadataOptions = Default::default();
// Get the value of the track option, if provided.
let track = match args.value_of("track") {
Some(track_str) => track_str.parse::<usize>().ok(),
_ => None,
};
let no_progress = args.is_present("no-progress");
// Probe the media source stream for metadata and get the format reader.
match symphonia::default::get_probe().format(&hint, mss, &format_opts, &metadata_opts) {
Ok(mut probed) => {
if args.is_present("verify-only") {
// Verify-only mode decodes and verifies the audio, but does not play it.
decode_only(probed.format, &DecoderOptions { verify: true, ..Default::default() })
}
else if args.is_present("decode-only") {
// Decode-only mode decodes the audio, but does not play or verify it.
decode_only(probed.format, &DecoderOptions { verify: false, ..Default::default() })
}
else if args.is_present("probe-only") {
// Probe-only mode only prints information about the format, tracks, metadata, etc.
print_format(path_str, &mut probed);
Ok(0)
}
else {
// Playback mode.
print_format(path_str, &mut probed);
// If present, parse the seek argument.
let seek_time = args.value_of("seek").map(|p| p.parse::<f64>().unwrap_or(0.0));
// Set the decoder options.
let decode_opts =
DecoderOptions { verify: args.is_present("verify"), ..Default::default() };
// Play it!
play(probed.format, track, seek_time, &decode_opts, no_progress)
}
}
Err(err) => {
// The input was not supported by any format reader.
info!("the input is not supported");
Err(err)
}
}
}
fn decode_only(mut reader: Box<dyn FormatReader>, decode_opts: &DecoderOptions) -> Result<i32> {
// Get the default track.
// TODO: Allow track selection.
let track = reader.default_track().unwrap();
let track_id = track.id;
// Create a decoder for the track.
let mut decoder = symphonia::default::get_codecs().make(&track.codec_params, decode_opts)?;
// Decode all packets, ignoring all decode errors.
let result = loop {
let packet = match reader.next_packet() {
Ok(packet) => packet,
Err(err) => break Err(err),
};
// If the packet does not belong to the selected track, skip over it.
if packet.track_id() != track_id {
continue;
}
// Decode the packet into audio samples.
match decoder.decode(&packet) {
Ok(_decoded) => continue,
Err(Error::DecodeError(err)) => warn!("decode error: {}", err),
Err(err) => break Err(err),
}
};
// Return if a fatal error occured.
ignore_end_of_stream_error(result)?;
// Finalize the decoder and return the verification result if it's been enabled.
do_verification(decoder.finalize())
}
#[derive(Copy, Clone)]
struct PlayTrackOptions {
track_id: u32,
seek_ts: u64,
}
fn play(
mut reader: Box<dyn FormatReader>,
track_num: Option<usize>,
seek_time: Option<f64>,
decode_opts: &DecoderOptions,
no_progress: bool,
) -> Result<i32> {
// If the user provided a track number, select that track if it exists, otherwise, select the
// first track with a known codec.
let track = track_num
.and_then(|t| reader.tracks().get(t))
.or_else(|| first_supported_track(reader.tracks()));
let mut track_id = match track {
Some(track) => track.id,
_ => return Ok(0),
};
// If there is a seek time, seek the reader to the time specified and get the timestamp of the
// seeked position. All packets with a timestamp < the seeked position will not be played.
//
// Note: This is a half-baked approach to seeking! After seeking the reader, packets should be
// decoded and *samples* discarded up-to the exact *sample* indicated by required_ts. The
// current approach will discard excess samples if seeking to a sample within a packet.
let seek_ts = if let Some(time) = seek_time {
let seek_to = SeekTo::Time { time: Time::from(time), track_id: Some(track_id) };
// Attempt the seek. If the seek fails, ignore the error and return a seek timestamp of 0 so
// that no samples are trimmed.
match reader.seek(SeekMode::Accurate, seek_to) {
Ok(seeked_to) => seeked_to.required_ts,
Err(Error::ResetRequired) => {
print_tracks(reader.tracks());
track_id = first_supported_track(reader.tracks()).unwrap().id;
0
}
Err(err) => {
// Don't give-up on a seek error.
warn!("seek error: {}", err);
0
}
}
}
else {
// If not seeking, the seek timestamp is 0.
0
};
// The audio output device.
let mut audio_output = None;
let mut track_info = PlayTrackOptions { track_id, seek_ts };
let result = loop {
match play_track(&mut reader, &mut audio_output, track_info, decode_opts, no_progress) {
Err(Error::ResetRequired) => {
// The demuxer indicated that a reset is required. This is sometimes seen with
// streaming OGG (e.g., Icecast) wherein the entire contents of the container change
// (new tracks, codecs, metadata, etc.). Therefore, we must select a new track and
// recreate the decoder.
print_tracks(reader.tracks());
// Select the first supported track since the user's selected track number might no
// longer be valid or make sense.
let track_id = first_supported_track(reader.tracks()).unwrap().id;
track_info = PlayTrackOptions { track_id, seek_ts: 0 };
}
res => break res,
}
};
// Flush the audio output to finish playing back any leftover samples.
if let Some(audio_output) = audio_output.as_mut() {
audio_output.flush()
}
result
}
fn play_track(
reader: &mut Box<dyn FormatReader>,
audio_output: &mut Option<Box<dyn output::AudioOutput>>,
play_opts: PlayTrackOptions,
decode_opts: &DecoderOptions,
no_progress: bool,
) -> Result<i32> {
// Get the selected track using the track ID.
let track = match reader.tracks().iter().find(|track| track.id == play_opts.track_id) {
Some(track) => track,
_ => return Ok(0),
};
// Create a decoder for the track.
let mut decoder = symphonia::default::get_codecs().make(&track.codec_params, decode_opts)?;
// Get the selected track's timebase and duration.
let tb = track.codec_params.time_base;
let dur = track.codec_params.n_frames.map(|frames| track.codec_params.start_ts + frames);
// Decode and play the packets belonging to the selected track.
let result = loop {
// Get the next packet from the format reader.
let packet = match reader.next_packet() {
Ok(packet) => packet,
Err(err) => break Err(err),
};
// If the packet does not belong to the selected track, skip it.
if packet.track_id() != play_opts.track_id {
continue;
}
//Print out new metadata.
while !reader.metadata().is_latest() {
reader.metadata().pop();
if let Some(rev) = reader.metadata().current() {
print_update(rev);
}
}
// Decode the packet into audio samples.
match decoder.decode(&packet) {
Ok(decoded) => {
// If the audio output is not open, try to open it.
if audio_output.is_none() {
// Get the audio buffer specification. This is a description of the decoded
// audio buffer's sample format and sample rate.
let spec = *decoded.spec();
// Get the capacity of the decoded buffer. Note that this is capacity, not
// length! The capacity of the decoded buffer is constant for the life of the
// decoder, but the length is not.
let duration = decoded.capacity() as u64;
// Try to open the audio output.
audio_output.replace(output::try_open(spec, duration).unwrap());
}
else {
// TODO: Check the audio spec. and duration hasn't changed.
}
// Write the decoded audio samples to the audio output if the presentation timestamp
// for the packet is >= the seeked position (0 if not seeking).
if packet.ts() >= play_opts.seek_ts {
if !no_progress {
print_progress(packet.ts(), dur, tb);
}
if let Some(audio_output) = audio_output {
audio_output.write(decoded).unwrap()
}
}
}
Err(Error::DecodeError(err)) => {
// Decode errors are not fatal. Print the error message and try to decode the next
// packet as usual.
warn!("decode error: {}", err);
}
Err(err) => break Err(err),
}
};
if !no_progress {
println!();
}
// Return if a fatal error occured.
ignore_end_of_stream_error(result)?;
// Finalize the decoder and return the verification result if it's been enabled.
do_verification(decoder.finalize())
}
fn first_supported_track(tracks: &[Track]) -> Option<&Track> {
tracks.iter().find(|t| t.codec_params.codec != CODEC_TYPE_NULL)
}
fn ignore_end_of_stream_error(result: Result<()>) -> Result<()> {
match result {
Err(Error::IoError(err))
if err.kind() == std::io::ErrorKind::UnexpectedEof
&& err.to_string() == "end of stream" =>
{
// Do not treat "end of stream" as a fatal error. It's the currently only way a
// format reader can indicate the media is complete.
Ok(())
}
_ => result,
}
}
fn do_verification(finalization: FinalizeResult) -> Result<i32> {
match finalization.verify_ok {
Some(is_ok) => {
// Got a verification result.
println!("verification: {}", if is_ok { "passed" } else { "failed" });
Ok(i32::from(!is_ok))
}
// Verification not enabled by user, or unsupported by the codec.
_ => Ok(0),
}
}
fn print_format(path: &str, probed: &mut ProbeResult) {
println!("+ {}", path);
print_tracks(probed.format.tracks());
// Prefer metadata that's provided in the container format, over other tags found during the
// probe operation.
if let Some(metadata_rev) = probed.format.metadata().current() {
print_tags(metadata_rev.tags());
print_visuals(metadata_rev.visuals());
// Warn that certain tags are preferred.
if probed.metadata.get().as_ref().is_some() {
info!("tags that are part of the container format are preferentially printed.");
info!("not printing additional tags that were found while probing.");
}
}
else if let Some(metadata_rev) = probed.metadata.get().as_ref().and_then(|m| m.current()) {
print_tags(metadata_rev.tags());
print_visuals(metadata_rev.visuals());
}
print_cues(probed.format.cues());
println!(":");
println!();
}
fn print_update(rev: &MetadataRevision) {
print_tags(rev.tags());
print_visuals(rev.visuals());
println!(":");
println!();
}
fn print_tracks(tracks: &[Track]) {
if !tracks.is_empty() {
println!("|");
println!("| // Tracks //");
for (idx, track) in tracks.iter().enumerate() {
let params = &track.codec_params;
print!("| [{:0>2}] Codec: ", idx + 1);
if let Some(codec) = symphonia::default::get_codecs().get_codec(params.codec) {
println!("{} ({})", codec.long_name, codec.short_name);
}
else {
println!("Unknown (#{})", params.codec);
}
if let Some(sample_rate) = params.sample_rate {
println!("| Sample Rate: {}", sample_rate);
}
if params.start_ts > 0 {
if let Some(tb) = params.time_base {
println!(
"| Start Time: {} ({})",
fmt_time(params.start_ts, tb),
params.start_ts
);
}
else {
println!("| Start Time: {}", params.start_ts);
}
}
if let Some(n_frames) = params.n_frames {
if let Some(tb) = params.time_base {
println!(
"| Duration: {} ({})",
fmt_time(n_frames, tb),
n_frames
);
}
else {
println!("| Frames: {}", n_frames);
}
}
if let Some(tb) = params.time_base {
println!("| Time Base: {}", tb);
}
if let Some(padding) = params.delay {
println!("| Encoder Delay: {}", padding);
}
if let Some(padding) = params.padding {
println!("| Encoder Padding: {}", padding);
}
if let Some(sample_format) = params.sample_format {
println!("| Sample Format: {:?}", sample_format);
}
if let Some(bits_per_sample) = params.bits_per_sample {
println!("| Bits per Sample: {}", bits_per_sample);
}
if let Some(channels) = params.channels {
println!("| Channel(s): {}", channels.count());
println!("| Channel Map: {}", channels);
}
if let Some(channel_layout) = params.channel_layout {
println!("| Channel Layout: {:?}", channel_layout);
}
if let Some(language) = &track.language {
println!("| Language: {}", language);
}
}
}
}
fn print_cues(cues: &[Cue]) {
if !cues.is_empty() {
println!("|");
println!("| // Cues //");
for (idx, cue) in cues.iter().enumerate() {
println!("| [{:0>2}] Track: {}", idx + 1, cue.index);
println!("| Timestamp: {}", cue.start_ts);
// Print tags associated with the Cue.
if !cue.tags.is_empty() {
println!("| Tags:");
for (tidx, tag) in cue.tags.iter().enumerate() {
if let Some(std_key) = tag.std_key {
println!(
"{}",
print_tag_item(tidx + 1, &format!("{:?}", std_key), &tag.value, 21)
);
}
else {
println!("{}", print_tag_item(tidx + 1, &tag.key, &tag.value, 21));
}
}
}
// Print any sub-cues.
if !cue.points.is_empty() {
println!("| Sub-Cues:");
for (ptidx, pt) in cue.points.iter().enumerate() {
println!(
"| [{:0>2}] Offset: {:?}",
ptidx + 1,
pt.start_offset_ts
);
// Start the number of sub-cue tags, but don't print them.
if !pt.tags.is_empty() {
println!(
"| Sub-Tags: {} (not listed)",
pt.tags.len()
);
}
}
}
}
}
}
fn print_tags(tags: &[Tag]) {
if !tags.is_empty() {
println!("|");
println!("| // Tags //");
let mut idx = 1;
// Print tags with a standard tag key first, these are the most common tags.
for tag in tags.iter().filter(|tag| tag.is_known()) {
if let Some(std_key) = tag.std_key {
println!("{}", print_tag_item(idx, &format!("{:?}", std_key), &tag.value, 4));
}
idx += 1;
}
// Print the remaining tags with keys truncated to 26 characters.
for tag in tags.iter().filter(|tag| !tag.is_known()) {
println!("{}", print_tag_item(idx, &tag.key, &tag.value, 4));
idx += 1;
}
}
}
fn print_visuals(visuals: &[Visual]) {
if !visuals.is_empty() {
println!("|");
println!("| // Visuals //");
for (idx, visual) in visuals.iter().enumerate() {
if let Some(usage) = visual.usage {
println!("| [{:0>2}] Usage: {:?}", idx + 1, usage);
println!("| Media Type: {}", visual.media_type);
}
else {
println!("| [{:0>2}] Media Type: {}", idx + 1, visual.media_type);
}
if let Some(dimensions) = visual.dimensions {
println!(
"| Dimensions: {} px x {} px",
dimensions.width, dimensions.height
);
}
if let Some(bpp) = visual.bits_per_pixel {
println!("| Bits/Pixel: {}", bpp);
}
if let Some(ColorMode::Indexed(colors)) = visual.color_mode {
println!("| Palette: {} colors", colors);
}
println!("| Size: {} bytes", visual.data.len());
// Print out tags similar to how regular tags are printed.
if !visual.tags.is_empty() {
println!("| Tags:");
}
for (tidx, tag) in visual.tags.iter().enumerate() {
if let Some(std_key) = tag.std_key {
println!(
"{}",
print_tag_item(tidx + 1, &format!("{:?}", std_key), &tag.value, 21)
);
}
else {
println!("{}", print_tag_item(tidx + 1, &tag.key, &tag.value, 21));
}
}
}
}
}
fn print_tag_item(idx: usize, key: &str, value: &Value, indent: usize) -> String {
let key_str = match key.len() {
0..=28 => format!("| {:w$}[{:0>2}] {:<28} : ", "", idx, key, w = indent),
_ => format!("| {:w$}[{:0>2}] {:.<28} : ", "", idx, key.split_at(26).0, w = indent),
};
let line_prefix = format!("\n| {:w$} : ", "", w = indent + 4 + 28 + 1);
let line_wrap_prefix = format!("\n| {:w$} ", "", w = indent + 4 + 28 + 1);
let mut out = String::new();
out.push_str(&key_str);
for (wrapped, line) in value.to_string().lines().enumerate() {
if wrapped > 0 {
out.push_str(&line_prefix);
}
let mut chars = line.chars();
let split = (0..)
.map(|_| chars.by_ref().take(72).collect::<String>())
.take_while(|s| !s.is_empty())
.collect::<Vec<_>>();
out.push_str(&split.join(&line_wrap_prefix));
}
out
}
fn fmt_time(ts: u64, tb: TimeBase) -> String {
let time = tb.calc_time(ts);
let hours = time.seconds / (60 * 60);
let mins = (time.seconds % (60 * 60)) / 60;
let secs = f64::from((time.seconds % 60) as u32) + time.frac;
format!("{}:{:0>2}:{:0>6.3}", hours, mins, secs)
}
fn print_progress(ts: u64, dur: Option<u64>, tb: Option<TimeBase>) {
// Get a string slice containing a progress bar.
fn progress_bar(ts: u64, dur: u64) -> &'static str {
const NUM_STEPS: usize = 60;
lazy_static! {
static ref PROGRESS_BAR: Vec<String> = {
(0..NUM_STEPS + 1).map(|i| format!("[{:<60}]", str::repeat("■", i))).collect()
};
}
let i = (NUM_STEPS as u64)
.saturating_mul(ts)
.checked_div(dur)
.unwrap_or(0)
.clamp(0, NUM_STEPS as u64);
&PROGRESS_BAR[i as usize]
}
// Multiple print! calls would need to be made to print the progress, so instead, only lock
// stdout once and use write! rather then print!.
let stdout = std::io::stdout();
let mut output = stdout.lock();
if let Some(tb) = tb {
let t = tb.calc_time(ts);
let hours = t.seconds / (60 * 60);
let mins = (t.seconds % (60 * 60)) / 60;
let secs = f64::from((t.seconds % 60) as u32) + t.frac;
write!(output, "\r\u{25b6}\u{fe0f} {}:{:0>2}:{:0>4.1}", hours, mins, secs).unwrap();
if let Some(dur) = dur {
let d = tb.calc_time(dur.saturating_sub(ts));
let hours = d.seconds / (60 * 60);
let mins = (d.seconds % (60 * 60)) / 60;
let secs = f64::from((d.seconds % 60) as u32) + d.frac;
write!(output, " {} -{}:{:0>2}:{:0>4.1}", progress_bar(ts, dur), hours, mins, secs)
.unwrap();
}
}
else {
write!(output, "\r\u{25b6}\u{fe0f} {}", ts).unwrap();
}
// This extra space is a workaround for Konsole to correctly erase the previous line.
write!(output, " ").unwrap();
// Flush immediately since stdout is buffered.
output.flush().unwrap();
}