looping segment generation

This commit is contained in:
Muaz Ahmad 2023-10-25 13:24:04 +05:00
parent 8849808c1e
commit 0e48e03f17

View file

@ -4,6 +4,7 @@ use std::time;
use std::thread;
use std::fs;
use std::cmp::max;
use std::io::Write;
use crate::util;
use crate::muxer::hls::mp4;
@ -15,6 +16,7 @@ pub struct HLSHandler {
args: util::HLSArgs,
curr_segment_idx: usize,
curr_segments: Vec<String>,
curr_media_seq_idx: usize,
}
impl HLSHandler {
@ -25,7 +27,7 @@ impl HLSHandler {
None => (),
Some(segment) => {
let del_list = self.new_segment(segment);
delete_files(del_list);
self.delete_files(del_list);
self.dump_playlist();
self.curr_segment_idx += 1;
}
@ -34,27 +36,44 @@ impl HLSHandler {
}
}
fn new_segment(&mut self, segment: segments::Segment) -> std::vec::Drain<String> {
fn new_segment(&mut self, segment: segments::Segment) -> Vec<String> {
segment.dump();
self.curr_segments.push(segment.filename);
self.curr_segments.drain(..max(self.curr_segments.len() - self.args.max_segments, 0))
let to_drain = if self.curr_segments.len() > self.args.max_segments {self.curr_segments.len() - self.args.max_segments} else {0};
self.curr_segments.drain(..to_drain).collect()
}
fn delete_files(&mut self, mut del_list: Vec<String>) {
for filename in &del_list {
_ = fs::remove_file(filename);
self.curr_media_seq_idx += 1;
}
}
fn dump_playlist(&self) {
todo!();
let mut segment_listing = String::new();
for segment_filename in &self.curr_segments {
segment_listing += format!("\
#EXTINF:{},\n\
{}\n\
", self.args.segment_time, (self.args.segment_prepend.clone() + segment_filename)).as_str();
}
let playlist_string = format!("\
#EXTM3U\n\
#EXT-X-VERSION:7\n\
#EXT-X-MEDIA-SEQUENCE:{}\n\
#EXT-X-MAP:URI=\"{}init.mp4\"\n\
{}\
#EXT-X-ENDLIST\
", self.curr_media_seq_idx, self.args.segment_prepend.clone(), segment_listing);
let mut f = fs::File::create("stream.m3u8").unwrap();
f.write_all(&playlist_string.as_bytes());
}
}
pub fn spawn(v: mpsc::Receiver<util::NALUPacket>, a: mpsc::Receiver<util::NALUPacket>, err_in: mpsc::Sender<Box<dyn Error + Send + Sync>>, metadata: Arc<util::Metadata>, args: util::HLSArgs) -> Result<HLSHandler, Box<dyn Error>> {
Ok(HLSHandler {muxer: mp4::new_muxer(v, a, metadata, err_in.clone())?, err_in: err_in, args: args, curr_segment_idx: 0, curr_segments: Vec::new()})
Ok(HLSHandler {muxer: mp4::new_muxer(v, a, metadata, err_in.clone())?, err_in: err_in, args: args, curr_segment_idx: 0, curr_segments: Vec::new(), curr_media_seq_idx: 0})
}
fn delete_files(mut del_list: std::vec::Drain<String>) {
loop {
match del_list.next() {
Some(filename) => fs::remove_file(filename),
None => return
};
}
}