Skip to main content

radio_cli/
recorder.rs

1use crate::error::{DomainError, ErrorCode};
2use crate::{
3    USER_AGENT,
4    config::{Config, validate_url},
5    model::{Recording, Station},
6    process,
7    store::Store,
8};
9use anyhow::{Context, Result, bail};
10use serde_json::Value;
11use std::{
12    fs::{self, OpenOptions},
13    io::{BufRead, BufReader},
14    path::{Path, PathBuf},
15    process::{Child, Command, Stdio},
16    sync::{
17        Arc,
18        atomic::{AtomicBool, AtomicU64, Ordering},
19    },
20    thread,
21    time::{Duration, Instant},
22};
23
24pub struct Recorder {
25    pub space_estimated: bool,
26    child: Child,
27    pub record: Recording,
28    partial: PathBuf,
29    deadline: Option<Instant>,
30    target_duration: Option<Duration>,
31    ended_without_stop: bool,
32    timed_out: bool,
33    progress: Arc<AtomicU64>,
34    duration_ms: u64,
35    readers: Vec<thread::JoinHandle<()>>,
36    errors: Arc<std::sync::Mutex<String>>,
37    reconnects: Arc<AtomicU64>,
38    finished: bool,
39    stop_requested: bool,
40}
41
42pub struct RecordingMetadata<'a> {
43    pub station: &'a Station,
44    pub track: Option<&'a str>,
45}
46
47fn filename_component(text: &str, max_chars: usize, max_bytes: usize) -> String {
48    let mut result = String::new();
49    for c in text
50        .chars()
51        .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
52        .take(max_chars)
53    {
54        if result.len() + c.len_utf8() > max_bytes {
55            break;
56        }
57        result.push(c);
58    }
59    result
60}
61
62fn track_filename_component(text: &str, max_bytes: usize) -> String {
63    let words: Vec<_> = text
64        .split_whitespace()
65        .map(|word| filename_component(word, 40, max_bytes))
66        .filter(|word| !word.is_empty())
67        .collect();
68    filename_component(&words.join("_"), 40, max_bytes)
69}
70
71const ERROR_TAIL_BYTES: usize = 8192;
72
73fn recording_progress(line: &str) -> bool {
74    line.split_once('=').is_some_and(|(key, _)| {
75        matches!(
76            key,
77            "frame"
78                | "fps"
79                | "bitrate"
80                | "total_size"
81                | "out_time_us"
82                | "out_time_ms"
83                | "out_time"
84                | "dup_frames"
85                | "drop_frames"
86                | "speed"
87                | "progress"
88        )
89    })
90}
91
92fn append_error_tail(text: &mut String, line: &str) {
93    // Keep readable diagnostic lines without allowing terminal control codes.
94    text.extend(
95        line.chars()
96            .filter(|c| !c.is_control() || *c == '\n' || *c == '\t'),
97    );
98    let mut start = text.len().saturating_sub(ERROR_TAIL_BYTES);
99    while !text.is_char_boundary(start) {
100        start += 1;
101    }
102    if start > 0 {
103        text.drain(..start);
104    }
105}
106
107pub fn probe(config: &Config, url: &str, stop: &Arc<AtomicBool>) -> Result<Value> {
108    probe_with_timeout(
109        config,
110        url,
111        stop,
112        Duration::from_secs(config.settings.probe_timeout_secs),
113    )
114}
115
116fn probe_with_timeout(
117    config: &Config,
118    url: &str,
119    stop: &Arc<AtomicBool>,
120    timeout: Duration,
121) -> Result<Value> {
122    let data = process::output(
123        Command::new(&config.settings.ffprobe).args([
124            "-v",
125            "error",
126            "-rw_timeout",
127            "5000000",
128            "-analyzeduration",
129            "1000000",
130            "-probesize",
131            "262144",
132            "-user_agent",
133            USER_AGENT,
134            "-select_streams",
135            "a:0",
136            "-show_entries",
137            "stream=codec_name,bit_rate:format=duration,bit_rate",
138            "-of",
139            "json",
140            "-i",
141            url,
142        ]),
143        timeout,
144        stop,
145    )?;
146    Ok(serde_json::from_slice(&data)?)
147}
148
149pub fn format_for_codec(codec: &str) -> Result<(&'static str, &'static str)> {
150    match codec {
151        "mp3" => Ok(("mp3", "mp3")),
152        "aac" => Ok(("aac", "adts")),
153        "vorbis" => Ok(("ogg", "ogg")),
154        "opus" => Ok(("opus", "opus")),
155        _ => bail!(DomainError::new(ErrorCode::UnsupportedCodec).with("codec", codec)),
156    }
157}
158
159pub fn sidecar(record: &Recording) -> Result<()> {
160    let path = PathBuf::from(format!("{}.json", record.path));
161    crate::files::write_atomic(&path, &serde_json::to_vec_pretty(record)?, None)
162}
163
164fn complete_finalization(store: &Store, record: &mut Recording) -> Result<()> {
165    let partial = PathBuf::from(&record.path);
166    let final_path = PathBuf::from(
167        record
168            .final_path
169            .as_ref()
170            .context(DomainError::new(ErrorCode::FinalPathMissing))?,
171    );
172    if partial.exists() {
173        crate::files::publish_noclobber(&partial, &final_path).with_context(|| {
174            DomainError::new(ErrorCode::RecordingPublish)
175                .with("id", &record.id)
176                .with("path", partial.display())
177                .with("final_path", final_path.display())
178        })?;
179    }
180    let size = fs::metadata(&final_path)?.len();
181    if size != record.size_bytes || size == 0 {
182        bail!(DomainError::new(ErrorCode::RecordingSizeMismatch));
183    }
184    let mut complete = record.clone();
185    complete.path = final_path.to_string_lossy().into();
186    complete.status = "complete".into();
187    complete.error = None;
188    complete.recovery_pending = false;
189    // The DB remains finalizing until the final sidecar is safely written.
190    sidecar(&complete)?;
191    store.save_recording(&complete)?;
192    let _ = fs::remove_file(format!("{}.json", partial.display()));
193    *record = complete;
194    Ok(())
195}
196
197pub fn recover(store: &Store) -> Result<Vec<String>> {
198    let mut warnings = Vec::new();
199    for mut r in store.unfinished_recordings()? {
200        let result = (|| -> Result<()> {
201            if r.status == "finalizing" {
202                return complete_finalization(store, &mut r);
203            }
204            if r.status == "recording" {
205                r.status = "interrupted".into();
206                r.stopped_at = Some(crate::timestamp::now());
207                r.error = Some("上一个会话未正常结束;保留临时文件供恢复".into());
208                r.size_bytes = fs::metadata(&r.path).map(|m| m.len()).unwrap_or(0);
209                r.recovery_pending = true;
210                store.save_recording(&r)?;
211            }
212            let retry = r.recovery_pending;
213            if retry {
214                r.error = Some(
215                    if Path::new(&r.path).exists() {
216                        "上一个会话未正常结束;临时文件保留,元数据已恢复"
217                    } else {
218                        "上一个会话未正常结束;音频文件缺失,元数据已恢复"
219                    }
220                    .into(),
221                );
222            }
223            r.recovery_pending = false;
224            sidecar(&r)?;
225            if retry {
226                store.save_recording(&r)?;
227            }
228            Ok(())
229        })();
230        if let Err(error) = result {
231            let message = format!(
232                "恢复失败: 录音 {} ({}):{error:#};使用 recordings recover 重试",
233                r.id, r.path
234            );
235            r.error = Some(message.clone());
236            r.recovery_pending = true;
237            if let Err(db_error) = store.save_recording(&r) {
238                warnings.push(format!("{message};数据库: {db_error:#}"));
239            } else {
240                warnings.push(message);
241            }
242        }
243    }
244    Ok(warnings)
245}
246
247// An unbounded recording or unknown bitrate has no finite total estimate.
248// Preserve the reserve check and make that limitation visible to the caller.
249fn required_space(
250    reserve_mb: u64,
251    station_kbps: u32,
252    info: &Value,
253    duration: Option<Duration>,
254) -> (u64, bool) {
255    let positive = |v: &Value| {
256        v.as_str()
257            .and_then(|v| v.parse::<u64>().ok())
258            .or_else(|| v.as_u64())
259            .filter(|v| *v > 0)
260    };
261    let bitrate = positive(&info["streams"][0]["bit_rate"])
262        .or_else(|| positive(&info["format"]["bit_rate"]))
263        .or_else(|| (station_kbps > 0).then_some(u64::from(station_kbps) * 1000));
264    let reserve = reserve_mb.saturating_mul(1024 * 1024);
265    match (duration, bitrate) {
266        (Some(duration), Some(bitrate)) => {
267            let bytes = u128::from(bitrate).saturating_mul(duration.as_nanos());
268            let bytes = bytes.div_ceil(8_000_000_000).min(u128::from(u64::MAX)) as u64;
269            (reserve.saturating_add(bytes), true)
270        }
271        (None, _) | (_, None) => (reserve, false),
272    }
273}
274
275#[cfg(test)]
276pub(crate) mod test_hooks {
277    use super::*;
278    pub(crate) fn filename_component(text: &str, max_chars: usize, max_bytes: usize) -> String {
279        super::filename_component(text, max_chars, max_bytes)
280    }
281    pub(crate) fn track_filename_component(text: &str, max_bytes: usize) -> String {
282        super::track_filename_component(text, max_bytes)
283    }
284    pub(crate) fn required_space(
285        reserve_mb: u64,
286        station_kbps: u32,
287        info: &Value,
288        duration: Option<Duration>,
289    ) -> (u64, bool) {
290        super::required_space(reserve_mb, station_kbps, info, duration)
291    }
292    pub(crate) fn append_error_tail(text: &mut String, line: &str) {
293        super::append_error_tail(text, line);
294    }
295    pub(crate) fn recording_progress(line: &str) -> bool {
296        super::recording_progress(line)
297    }
298}
299
300impl Recorder {
301    pub fn start(
302        config: &Config,
303        store: &Store,
304        station: &Station,
305        url: &str,
306        dir: &Path,
307        duration: Option<Duration>,
308        stop: &Arc<AtomicBool>,
309    ) -> Result<Self> {
310        validate_url(url)?;
311        let info = probe(config, url, stop)?;
312        Self::start_with_info(config, store, station, url, dir, duration, info)
313    }
314
315    pub fn start_with_info(
316        config: &Config,
317        store: &Store,
318        station: &Station,
319        url: &str,
320        dir: &Path,
321        duration: Option<Duration>,
322        info: Value,
323    ) -> Result<Self> {
324        Self::start_with_metadata(
325            config,
326            store,
327            RecordingMetadata {
328                station,
329                track: None,
330            },
331            url,
332            dir,
333            duration,
334            info,
335        )
336    }
337
338    pub fn start_with_metadata(
339        config: &Config,
340        store: &Store,
341        metadata: RecordingMetadata<'_>,
342        url: &str,
343        dir: &Path,
344        duration: Option<Duration>,
345        info: Value,
346    ) -> Result<Self> {
347        let station = metadata.station;
348        let track = metadata
349            .track
350            .map(crate::clean_text)
351            .map(|title| title.trim().to_owned())
352            .filter(|title| !title.is_empty());
353        validate_url(url)?;
354        let codec = info["streams"][0]["codec_name"]
355            .as_str()
356            .context(DomainError::new(ErrorCode::NoAudio))?
357            .to_owned();
358        let (extension, muxer) = format_for_codec(&codec)?;
359        let dir = std::path::absolute(dir)?;
360        let (required, space_estimated) = required_space(
361            config.settings.recording_min_free_mb,
362            station.bitrate,
363            &info,
364            duration,
365        );
366        // A missing destination uses its nearest existing ancestor's filesystem.
367        // Check before creating it so a rejected recording leaves no directories.
368        let mut ancestor = dir.as_path();
369        loop {
370            match fs::metadata(ancestor) {
371                Ok(_) => break,
372                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
373                    ancestor = ancestor
374                        .parent()
375                        .context(DomainError::new(ErrorCode::FinalPathMissing))?;
376                }
377                Err(error) => return Err(error.into()),
378            }
379        }
380        let available = fs2::available_space(ancestor)?;
381        if available < required {
382            bail!(
383                DomainError::new(ErrorCode::InsufficientSpace)
384                    .with("available", available)
385                    .with("required", required)
386            );
387        }
388        fs::create_dir_all(&dir)?;
389        let dir = fs::canonicalize(dir)?;
390        let id = uuid::Uuid::new_v4().to_string();
391        // Leave byte room for timestamps, suffixes, .part and .json.tmp even
392        // when station and track names contain multibyte Unicode characters.
393        let name = filename_component(&station.name, 60, 180);
394        let track_name = track_filename_component(track.as_deref().unwrap_or(""), 200 - name.len());
395        let label = if track_name.is_empty() {
396            name
397        } else {
398            format!("{name}-{track_name}")
399        };
400        let base = format!(
401            "{}-{}-{}",
402            jiff::ZonedDateTime::now().strftime("%Y%m%d-%H%M%S"),
403            label,
404            &id[..8]
405        );
406        let final_path = dir.join(format!("{base}.{extension}"));
407        let partial = dir.join(format!("{base}.{extension}.part"));
408        let file = OpenOptions::new()
409            .write(true)
410            .create_new(true)
411            .open(&partial)?;
412        let mut command = Command::new(&config.settings.ffmpeg);
413        command.args([
414            "-hide_banner",
415            "-loglevel",
416            "warning",
417            "-nostats",
418            "-rw_timeout",
419            "12000000",
420            // Retry truncated HTTP/ICY streams, including non-seekable ones.
421            // Exponential backoff stops when the next delay exceeds 2s;
422            // these options also work with older FFmpeg versions. Do not use
423            // reconnect_at_eof: a finite resource must not loop to fill -t.
424            "-reconnect",
425            "1",
426            "-reconnect_streamed",
427            "1",
428            "-reconnect_delay_max",
429            "2",
430            "-analyzeduration",
431            "1000000",
432            "-probesize",
433            "262144",
434            "-user_agent",
435            USER_AGENT,
436            "-i",
437            url,
438            "-map",
439            "0:a:0",
440            "-c:a",
441            "copy",
442        ]);
443        if let Some(duration) = duration {
444            command.arg("-t").arg(duration.as_secs_f64().to_string());
445        }
446        command.args(["-progress", "pipe:2", "-f", muxer, "pipe:1"]);
447        // An exclusively created file is passed as stdout; no shell or unsafe FD setup.
448        command
449            .stdin(Stdio::piped())
450            .stdout(Stdio::from(file))
451            .stderr(Stdio::piped());
452        let child_result = process::spawn_owned(command);
453        let mut child = match child_result {
454            Ok(child) => child,
455            Err(e) => {
456                let _ = fs::remove_file(&partial);
457                return Err(e).context(
458                    DomainError::new(ErrorCode::MissingDependency).with("program", "ffmpeg"),
459                );
460            }
461        };
462        let progress = Arc::new(AtomicU64::new(0));
463        let latest = progress.clone();
464        let errors = Arc::new(std::sync::Mutex::new(String::new()));
465        let target = errors.clone();
466        let reconnects = Arc::new(AtomicU64::new(0));
467        let retry_count = reconnects.clone();
468        let stderr = child.stderr.take().unwrap();
469        let reader = thread::spawn(move || {
470            let mut input = BufReader::new(stderr);
471            let mut line = String::new();
472            loop {
473                line.clear();
474                match input.read_line(&mut line) {
475                    Ok(0) | Err(_) => break,
476                    _ => {}
477                }
478                if let Some(value) = line.trim().strip_prefix("out_time_us=") {
479                    if let Ok(value) = value.parse::<u64>() {
480                        latest.fetch_max(value / 1000, Ordering::Relaxed);
481                    }
482                } else if !recording_progress(line.trim()) {
483                    // Count before trimming the tail so later diagnostics cannot
484                    // erase evidence of an interrupted stream. HTTP/ICY inputs
485                    // report "Will reconnect at"; the HLS demuxer reports
486                    // "Failed to open segment" when a segment cannot be
487                    // re-fetched and is skipped.
488                    if line.contains("Will reconnect at") || line.contains("Failed to open segment")
489                    {
490                        retry_count.fetch_add(1, Ordering::Relaxed);
491                    }
492                    let mut text = target.lock().unwrap();
493                    append_error_tail(&mut text, &line);
494                }
495            }
496        });
497        let record = Recording {
498            id,
499            stationuuid: station.stationuuid.clone(),
500            station_name: station.name.clone(),
501            track,
502            source_url_resolved: url.into(),
503            started_at: crate::timestamp::now(),
504            stopped_at: None,
505            media_duration_ms: None,
506            codec,
507            container: muxer.into(),
508            path: partial.to_string_lossy().into(),
509            final_path: Some(final_path.to_string_lossy().into()),
510            size_bytes: 0,
511            status: "recording".into(),
512            error: None,
513            reconnects: 0,
514            recovery_pending: false,
515        };
516        let recorder = Self {
517            space_estimated,
518            child,
519            record,
520            partial,
521            deadline: duration.map(|d| {
522                Instant::now() + d + Duration::from_secs(config.settings.playback_timeout_secs)
523            }),
524            target_duration: duration,
525            ended_without_stop: false,
526            timed_out: false,
527            progress,
528            duration_ms: 0,
529            readers: vec![reader],
530            errors,
531            reconnects,
532            finished: false,
533            stop_requested: false,
534        };
535        store.save_recording(&recorder.record)?;
536        sidecar(&recorder.record)?;
537        Ok(recorder)
538    }
539
540    pub fn poll(&mut self) -> Result<bool> {
541        self.duration_ms = self.progress.load(Ordering::Relaxed);
542        self.ended_without_stop = self.child.try_wait()?.is_some();
543        self.timed_out =
544            !self.ended_without_stop && self.deadline.is_some_and(|d| Instant::now() >= d);
545        Ok(self.ended_without_stop || self.timed_out)
546    }
547
548    pub fn elapsed_ms(&self) -> u64 {
549        self.duration_ms
550    }
551
552    fn stop_child(&mut self) -> Result<std::process::ExitStatus> {
553        if let Some(status) = self.child.try_wait()? {
554            return Ok(status);
555        }
556        // FFmpeg only reads "q" from a terminal, never from a piped stdin;
557        // SIGINT is its supported graceful stop and still finalizes the file.
558        self.stop_requested = true;
559        unsafe { libc::kill(self.child.id() as libc::pid_t, libc::SIGINT) };
560        let deadline = Instant::now() + Duration::from_secs(3);
561        loop {
562            if let Some(status) = self.child.try_wait()? {
563                return Ok(status);
564            }
565            if Instant::now() >= deadline {
566                self.child.kill()?;
567                return Ok(self.child.wait()?);
568            }
569            thread::sleep(Duration::from_millis(30));
570        }
571    }
572
573    pub fn finish(self, config: &Config, store: &Store, reason: Option<&str>) -> Result<Recording> {
574        self.finish_cancellable(config, store, reason, &Arc::new(AtomicBool::new(false)))
575    }
576
577    pub fn finish_cancellable(
578        mut self,
579        config: &Config,
580        store: &Store,
581        reason: Option<&str>,
582        stop: &Arc<AtomicBool>,
583    ) -> Result<Recording> {
584        let status = self.stop_child()?;
585        for handle in self.readers.drain(..) {
586            let _ = handle.join();
587        }
588        self.duration_ms = self.progress.load(Ordering::Relaxed);
589        self.record.stopped_at = Some(crate::timestamp::now());
590        self.record.reconnects = self.reconnects.load(Ordering::Relaxed);
591        self.record.size_bytes = fs::metadata(&self.partial)?.len();
592        let verification = probe_with_timeout(
593            config,
594            &self.partial.to_string_lossy(),
595            stop,
596            Duration::from_secs(2),
597        );
598        if let Ok(info) = &verification {
599            self.record.media_duration_ms = info["format"]["duration"]
600                .as_str()
601                .and_then(|s| s.parse::<f64>().ok())
602                .filter(|d| d.is_finite() && *d >= 0.)
603                .map(|d| (d * 1000.) as u64);
604        }
605        let premature = self.ended_without_stop
606            && self.target_duration.is_none_or(|d| {
607                self.record
608                    .media_duration_ms
609                    .unwrap_or(self.duration_ms)
610                    .saturating_add(100)
611                    < d.as_millis() as u64
612            });
613        let reason = reason.or(if self.timed_out {
614            Some("录音未在时限内完成")
615        } else if premature && status.success() {
616            Some("直播源提前结束")
617        } else {
618            None
619        });
620        // FFmpeg exits 255 after finalizing on our SIGINT; a stop we asked for
621        // is not a failure as long as the output verifies below.
622        let graceful = status.success() || self.stop_requested;
623        self.record.status = if graceful && reason.is_none() && self.record.size_bytes > 0 {
624            "complete"
625        } else if reason.is_some() {
626            "interrupted"
627        } else {
628            "failed"
629        }
630        .into();
631        if self.record.status == "complete"
632            && verification
633                .as_ref()
634                .ok()
635                .and_then(|info| info["streams"][0]["codec_name"].as_str())
636                != Some(self.record.codec.as_str())
637        {
638            self.record.status = "failed".into();
639            self.record.error = Some("录音文件未通过音频轨道验证;保留临时文件".into());
640        }
641        // Progress remains useful when a native live container has no duration field.
642        if self.record.media_duration_ms.is_none() && self.duration_ms > 0 {
643            self.record.media_duration_ms = Some(self.duration_ms);
644        }
645        if self.record.status == "complete" {
646            // Persist intent before moving the only audio file. A failed DB
647            // write leaves the original recording and its .part file intact.
648            self.record.status = "finalizing".into();
649            store.save_recording(&self.record)?;
650            sidecar(&self.record)?;
651            if let Err(error) = complete_finalization(store, &mut self.record) {
652                self.record.recovery_pending = true;
653                self.record.error = Some(format!(
654                    "录音 {} ({}) 收尾待重试: {error:#}",
655                    self.record.id, self.record.path
656                ));
657                let _ = store.save_recording(&self.record);
658                let _ = sidecar(&self.record);
659                return Err(error).context(self.record.error.clone().unwrap());
660            }
661        } else {
662            let errors = self.errors.lock().unwrap();
663            let summary = self
664                .record
665                .error
666                .as_deref()
667                .or(reason)
668                .map(str::to_owned)
669                .unwrap_or_else(|| format!("FFmpeg: {status}"));
670            self.record.error = Some(if errors.trim().is_empty() {
671                summary
672            } else {
673                format!("{summary}\n{}", errors.trim())
674            });
675        }
676        if self.record.status != "complete" {
677            store.save_recording(&self.record)?;
678            sidecar(&self.record)?;
679        }
680        self.finished = true;
681        Ok(self.record.clone())
682    }
683}
684
685impl Drop for Recorder {
686    fn drop(&mut self) {
687        if !self.finished {
688            let _ = self.stop_child();
689        }
690        for handle in self.readers.drain(..) {
691            let _ = handle.join();
692        }
693    }
694}
695
696pub fn parse_duration(value: &str) -> Result<Duration> {
697    let split = value
698        .find(|c: char| !c.is_ascii_digit())
699        .unwrap_or(value.len());
700    let n = value[..split]
701        .parse::<u64>()
702        .context(DomainError::new(ErrorCode::InvalidDuration))?;
703    let factor = match &value[split..] {
704        "" | "s" => 1,
705        "m" => 60,
706        "h" => 3600,
707        _ => bail!(DomainError::new(ErrorCode::DurationUnit)),
708    };
709    let secs = n
710        .checked_mul(factor)
711        .context(DomainError::new(ErrorCode::DurationOverflow))?;
712    if secs == 0 || secs > 365 * 24 * 3600 {
713        bail!(DomainError::new(ErrorCode::DurationRange));
714    }
715    Ok(Duration::from_secs(secs))
716}
717
718#[cfg(test)]
719mod tests {
720    use super::*;
721
722    #[test]
723    fn recording_track_is_optional_for_older_metadata() {
724        let dir = tempfile::tempdir().unwrap();
725        let old = pending(dir.path());
726        let value = serde_json::to_value(&old).unwrap();
727        assert!(value.get("track").is_none());
728        let decoded: Recording = serde_json::from_value(value).unwrap();
729        assert!(decoded.track.is_none());
730    }
731
732    fn pending(dir: &Path) -> Recording {
733        let partial = dir.join("test.mp3.part");
734        fs::write(&partial, b"verified audio").unwrap();
735        Recording {
736            id: uuid::Uuid::new_v4().to_string(),
737            stationuuid: uuid::Uuid::new_v4().to_string(),
738            station_name: "test".into(),
739            track: None,
740            source_url_resolved: "https://example.com/audio".into(),
741            started_at: "2026-01-01T00:00:00Z".into(),
742            stopped_at: Some("2026-01-01T00:00:01Z".into()),
743            media_duration_ms: Some(1000),
744            codec: "mp3".into(),
745            container: "mp3".into(),
746            path: partial.to_string_lossy().into(),
747            final_path: Some(dir.join("test.mp3").to_string_lossy().into()),
748            size_bytes: 14,
749            status: "finalizing".into(),
750            error: None,
751            reconnects: 0,
752            recovery_pending: false,
753        }
754    }
755
756    #[test]
757    fn space_estimate_prefers_audio_bitrate_and_reports_unknown_totals() {
758        let reserve = 16 * 1024 * 1024;
759        let mut info =
760            serde_json::json!({"streams":[{"bit_rate":"128000"}], "format":{"bit_rate":"256000"}});
761        assert_eq!(
762            required_space(16, 320, &info, Some(Duration::from_millis(1500))),
763            (reserve + 24000, true)
764        );
765        assert_eq!(required_space(16, 320, &info, None), (reserve, false));
766        info["streams"][0]["bit_rate"] = "0".into();
767        assert_eq!(
768            required_space(16, 320, &info, Some(Duration::from_secs(1))),
769            (reserve + 32000, true)
770        );
771        assert_eq!(
772            required_space(16, 0, &Value::Null, Some(Duration::from_secs(1))),
773            (reserve, false)
774        );
775        assert_eq!(
776            required_space(16, 128, &Value::Null, Some(Duration::from_secs(1))),
777            (reserve + 16000, true)
778        );
779        let extreme = serde_json::json!({"streams":[{"bit_rate":u64::MAX.to_string()}]});
780        assert_eq!(
781            required_space(16, 0, &extreme, Some(Duration::from_secs(u64::MAX))),
782            (u64::MAX, true)
783        );
784    }
785
786    #[test]
787    fn recovery_repairs_each_publication_boundary_idempotently() {
788        for phase in 0..5 {
789            let dir = tempfile::tempdir().unwrap();
790            let store = Store::open(&dir.path().join("radio.db")).unwrap();
791            let mut r = pending(dir.path());
792            r.reconnects = 2;
793            store.save_recording(&r).unwrap();
794            sidecar(&r).unwrap();
795            if phase >= 1 {
796                fs::hard_link(&r.path, r.final_path.as_ref().unwrap()).unwrap();
797            }
798            if phase >= 2 {
799                crate::files::publish_noclobber(
800                    Path::new(&r.path),
801                    Path::new(r.final_path.as_ref().unwrap()),
802                )
803                .unwrap();
804            }
805            if phase >= 3 {
806                let mut complete = r.clone();
807                complete.path = complete.final_path.clone().unwrap();
808                complete.status = "complete".into();
809                sidecar(&complete).unwrap();
810            }
811            if phase == 4 {
812                // A blocked DB write after publication must leave recoverable intent.
813                let lock = rusqlite::Connection::open(dir.path().join("radio.db")).unwrap();
814                lock.execute_batch("BEGIN IMMEDIATE").unwrap();
815                assert!(complete_finalization(&store, &mut r).is_err());
816                lock.execute_batch("ROLLBACK").unwrap();
817            }
818            recover(&store).unwrap();
819            recover(&store).unwrap();
820            let saved = store.recordings(1).unwrap().remove(0);
821            assert_eq!(saved.status, "complete");
822            assert_eq!(saved.reconnects, 2);
823            assert_eq!(fs::read(&saved.path).unwrap(), b"verified audio");
824            assert_eq!(
825                serde_json::from_slice::<Recording>(
826                    &fs::read(format!("{}.json", saved.path)).unwrap()
827                )
828                .unwrap()
829                .id,
830                saved.id
831            );
832            assert!(!Path::new(&r.path).exists());
833        }
834    }
835
836    #[test]
837    fn successful_sidecar_retry_clears_recovery_pending_state() {
838        let dir = tempfile::tempdir().unwrap();
839        let store = Store::open(&dir.path().join("radio.db")).unwrap();
840        let mut r = pending(dir.path());
841        r.status = "recording".into();
842        r.path = dir.path().join("missing/old.part").to_string_lossy().into();
843        store.save_recording(&r).unwrap();
844        assert_eq!(recover(&store).unwrap().len(), 1);
845        assert_eq!(store.unfinished_recordings().unwrap().len(), 1);
846        let mut retry = store.recordings(1).unwrap().remove(0);
847        assert!(retry.recovery_pending);
848        retry.error = Some("diagnostic wording has changed".into());
849        store.save_recording(&retry).unwrap();
850        assert_eq!(store.unfinished_recordings().unwrap().len(), 1);
851        fs::create_dir(dir.path().join("missing")).unwrap();
852        assert!(recover(&store).unwrap().is_empty());
853        assert!(store.unfinished_recordings().unwrap().is_empty());
854        let saved = store.recordings(1).unwrap().remove(0);
855        assert_eq!(saved.status, "interrupted");
856        assert!(!saved.recovery_pending);
857        assert!(saved.error.as_deref().unwrap().contains("音频文件缺失"));
858        assert!(Path::new(&format!("{}.json", saved.path)).exists());
859        assert!(recover(&store).unwrap().is_empty());
860    }
861
862    #[test]
863    fn recovery_selection_uses_the_flag_instead_of_error_text() {
864        let dir = tempfile::tempdir().unwrap();
865        let store = Store::open(&dir.path().join("radio.db")).unwrap();
866        let mut record = pending(dir.path());
867        record.status = "interrupted".into();
868        record.error = Some("恢复失败: diagnostic text alone".into());
869        store.save_recording(&record).unwrap();
870        assert!(store.unfinished_recordings().unwrap().is_empty());
871        record.recovery_pending = true;
872        record.error = None;
873        store.save_recording(&record).unwrap();
874        assert_eq!(store.unfinished_recordings().unwrap().len(), 1);
875        assert!(recover(&store).unwrap().is_empty());
876        assert!(store.unfinished_recordings().unwrap().is_empty());
877    }
878
879    #[test]
880    fn version_one_database_migrates_legacy_recovery_state_once() {
881        let dir = tempfile::tempdir().unwrap();
882        let path = dir.path().join("legacy.db");
883        let mut record = pending(dir.path());
884        record.status = "interrupted".into();
885        record.error = Some("恢复失败: old-format sidecar failure".into());
886        let mut json = serde_json::to_value(&record).unwrap();
887        json.as_object_mut().unwrap().remove("recovery_pending");
888        let conn = rusqlite::Connection::open(&path).unwrap();
889        conn.execute_batch("CREATE TABLE recordings (id TEXT PRIMARY KEY,status TEXT NOT NULL,json TEXT NOT NULL);
890            CREATE TABLE stations (uuid TEXT PRIMARY KEY,name TEXT NOT NULL,search TEXT NOT NULL,
891                country TEXT NOT NULL,languages TEXT NOT NULL,tags TEXT NOT NULL,bitrate INTEGER NOT NULL,
892                popularity INTEGER NOT NULL,custom INTEGER NOT NULL,active INTEGER NOT NULL,json TEXT NOT NULL);
893            CREATE TABLE meta (key TEXT PRIMARY KEY,value TEXT NOT NULL);
894            CREATE TABLE favorites (uuid TEXT PRIMARY KEY REFERENCES stations(uuid),created_at TEXT NOT NULL);
895            CREATE TABLE history (id INTEGER PRIMARY KEY,uuid TEXT NOT NULL REFERENCES stations(uuid),played_at TEXT NOT NULL);
896            CREATE INDEX history_station ON history(uuid);
897            PRAGMA user_version=1;").unwrap();
898        conn.execute(
899            "INSERT INTO recordings VALUES (?1,?2,?3)",
900            rusqlite::params![record.id, record.status, json.to_string()],
901        )
902        .unwrap();
903        drop(conn);
904        let store = Store::open(&path).unwrap();
905        assert!(store.unfinished_recordings().unwrap()[0].recovery_pending);
906        assert!(recover(&store).unwrap().is_empty());
907        assert!(!store.recordings(1).unwrap()[0].recovery_pending);
908        drop(store);
909        let store = Store::open(&path).unwrap();
910        assert!(store.unfinished_recordings().unwrap().is_empty());
911        let conn = rusqlite::Connection::open(&path).unwrap();
912        assert_eq!(
913            conn.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))
914                .unwrap(),
915            11
916        );
917    }
918
919    #[test]
920    fn publication_never_overwrites_an_existing_file() {
921        let dir = tempfile::tempdir().unwrap();
922        let store = Store::open(&dir.path().join("radio.db")).unwrap();
923        let mut r = pending(dir.path());
924        store.save_recording(&r).unwrap();
925        fs::write(r.final_path.as_ref().unwrap(), b"other recording").unwrap();
926        assert!(complete_finalization(&store, &mut r).is_err());
927        assert_eq!(
928            fs::read(r.final_path.as_ref().unwrap()).unwrap(),
929            b"other recording"
930        );
931        assert_eq!(fs::read(&r.path).unwrap(), b"verified audio");
932        fs::remove_file(r.final_path.as_ref().unwrap()).unwrap();
933        recover(&store).unwrap();
934        assert_eq!(store.recordings(1).unwrap()[0].status, "complete");
935    }
936
937    #[test]
938    fn publication_rejects_matching_contents_and_symlink_destinations() {
939        use std::os::unix::fs::symlink;
940        for symlink_target in [false, true] {
941            let dir = tempfile::tempdir().unwrap();
942            let store = Store::open(&dir.path().join("radio.db")).unwrap();
943            let mut r = pending(dir.path());
944            let final_path = PathBuf::from(r.final_path.as_ref().unwrap());
945            if symlink_target {
946                symlink(&r.path, &final_path).unwrap();
947            } else {
948                fs::copy(&r.path, &final_path).unwrap();
949            }
950            assert!(complete_finalization(&store, &mut r).is_err());
951            assert_eq!(fs::read(&r.path).unwrap(), b"verified audio");
952            assert_eq!(fs::read(final_path).unwrap(), b"verified audio");
953            assert_eq!(r.status, "finalizing");
954        }
955    }
956}