2021-10-18 06:42:42 +00:00
|
|
|
// Copyright (C) 2021 Sebastian Dröge <sebastian@centricular.com>
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public License, v2.0.
|
|
|
|
// If a copy of the MPL was not distributed with this file, You can obtain one at
|
|
|
|
// <https://mozilla.org/MPL/2.0/>.
|
|
|
|
//
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
|
|
|
// This creates a VoD DASH manifest based on the output of `cmafmux`. The media header
|
|
|
|
// ("initialization segment") is written into a separate file as the segments, and each segment is
|
|
|
|
// its own file too.
|
|
|
|
//
|
|
|
|
// All segments that are created are exactly 10s, expect for the last one which is only 3.333s.
|
|
|
|
|
|
|
|
use gst::prelude::*;
|
|
|
|
|
|
|
|
use std::path::PathBuf;
|
|
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
|
|
|
|
use anyhow::Error;
|
|
|
|
|
|
|
|
struct Segment {
|
|
|
|
start_time: gst::ClockTime,
|
|
|
|
duration: gst::ClockTime,
|
|
|
|
}
|
|
|
|
|
|
|
|
struct State {
|
|
|
|
start_time: Option<gst::ClockTime>,
|
|
|
|
end_time: Option<gst::ClockTime>,
|
|
|
|
segments: Vec<Segment>,
|
|
|
|
path: PathBuf,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() -> Result<(), Error> {
|
|
|
|
gst::init()?;
|
|
|
|
|
|
|
|
gstfmp4::plugin_register_static()?;
|
|
|
|
|
|
|
|
let state = Arc::new(Mutex::new(State {
|
|
|
|
start_time: None,
|
|
|
|
end_time: None,
|
|
|
|
segments: Vec::new(),
|
|
|
|
path: PathBuf::from("dash_stream"),
|
|
|
|
}));
|
|
|
|
|
2023-12-04 14:54:00 +00:00
|
|
|
let pipeline = gst::parse::launch("videotestsrc num-buffers=2500 ! timecodestamper ! video/x-raw,format=I420,width=1280,height=720,framerate=30/1 ! timeoverlay ! x264enc bframes=0 bitrate=2048 ! video/x-h264,profile=main ! cmafmux fragment-duration=10000000000 header-update-mode=update write-mehd=true ! appsink name=sink").unwrap().downcast::<gst::Pipeline>().unwrap();
|
2021-10-18 06:42:42 +00:00
|
|
|
|
|
|
|
let sink = pipeline
|
|
|
|
.by_name("sink")
|
|
|
|
.unwrap()
|
|
|
|
.dynamic_cast::<gst_app::AppSink>()
|
|
|
|
.unwrap();
|
|
|
|
sink.set_buffer_list(true);
|
|
|
|
|
|
|
|
let state_clone = state.clone();
|
|
|
|
sink.set_callbacks(
|
|
|
|
gst_app::AppSinkCallbacks::builder()
|
|
|
|
.new_sample(move |sink| {
|
|
|
|
let sample = sink.pull_sample().map_err(|_| gst::FlowError::Eos)?;
|
|
|
|
let mut state = state.lock().unwrap();
|
|
|
|
|
|
|
|
// The muxer only outputs non-empty buffer lists
|
|
|
|
let mut buffer_list = sample.buffer_list_owned().expect("no buffer list");
|
|
|
|
assert!(!buffer_list.is_empty());
|
|
|
|
|
|
|
|
let mut first = buffer_list.get(0).unwrap();
|
|
|
|
|
|
|
|
// Each list contains a full segment, i.e. does not start with a DELTA_UNIT
|
|
|
|
assert!(!first.flags().contains(gst::BufferFlags::DELTA_UNIT));
|
|
|
|
|
|
|
|
// If the buffer has the DISCONT and HEADER flag set then it contains the media
|
|
|
|
// header, i.e. the `ftyp`, `moov` and other media boxes.
|
|
|
|
//
|
|
|
|
// This might be the initial header or the updated header at the end of the stream.
|
2023-04-13 07:49:03 +00:00
|
|
|
if first
|
|
|
|
.flags()
|
|
|
|
.contains(gst::BufferFlags::DISCONT | gst::BufferFlags::HEADER)
|
|
|
|
{
|
2021-10-18 06:42:42 +00:00
|
|
|
let mut path = state.path.clone();
|
|
|
|
std::fs::create_dir_all(&path).expect("failed to create directory");
|
|
|
|
path.push("init.cmfi");
|
|
|
|
|
|
|
|
println!("writing header to {}", path.display());
|
|
|
|
let map = first.map_readable().unwrap();
|
|
|
|
std::fs::write(path, &map).expect("failed to write header");
|
|
|
|
drop(map);
|
|
|
|
|
|
|
|
// Remove the header from the buffer list
|
|
|
|
buffer_list.make_mut().remove(0, 1);
|
|
|
|
|
|
|
|
// If the list is now empty then it only contained the media header and nothing
|
|
|
|
// else.
|
|
|
|
if buffer_list.is_empty() {
|
|
|
|
return Ok(gst::FlowSuccess::Ok);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise get the next buffer and continue working with that.
|
|
|
|
first = buffer_list.get(0).unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the buffer only has the HEADER flag set then this is a segment header that is
|
|
|
|
// followed by one or more actual media buffers.
|
|
|
|
assert!(first.flags().contains(gst::BufferFlags::HEADER));
|
|
|
|
|
2023-04-13 07:49:03 +00:00
|
|
|
let segment = sample
|
|
|
|
.segment()
|
|
|
|
.expect("no segment")
|
|
|
|
.downcast_ref::<gst::ClockTime>()
|
|
|
|
.expect("no time segment");
|
2021-10-18 06:42:42 +00:00
|
|
|
|
|
|
|
// Initialize the start time with the first PTS we observed. This will be used
|
|
|
|
// later for calculating the duration of the whole media for the DASH manifest.
|
|
|
|
//
|
|
|
|
// The PTS of the segment header is equivalent to the earliest PTS of the whole
|
|
|
|
// segment.
|
2023-04-13 07:49:03 +00:00
|
|
|
let pts = segment
|
|
|
|
.to_running_time(first.pts().unwrap())
|
|
|
|
.expect("can't get running time");
|
2021-10-18 06:42:42 +00:00
|
|
|
if state.start_time.is_none() {
|
|
|
|
state.start_time = Some(pts);
|
|
|
|
}
|
|
|
|
|
|
|
|
// The metadata of the first media buffer is duplicated to the segment header.
|
|
|
|
// Based on this we can know the timecode of the first frame in this segment.
|
2023-04-13 07:49:03 +00:00
|
|
|
let meta = first
|
|
|
|
.meta::<gst_video::VideoTimeCodeMeta>()
|
|
|
|
.expect("no timecode meta");
|
2021-10-18 06:42:42 +00:00
|
|
|
|
|
|
|
let mut path = state.path.clone();
|
|
|
|
path.push(format!("segment_{}.cmfv", state.segments.len() + 1));
|
2023-04-13 07:49:03 +00:00
|
|
|
println!(
|
|
|
|
"writing segment with timecode {} to {}",
|
|
|
|
meta.tc(),
|
|
|
|
path.display()
|
|
|
|
);
|
2021-10-18 06:42:42 +00:00
|
|
|
|
|
|
|
// Calculate the end time at this point. The duration of the segment header is set
|
|
|
|
// to the whole duration of this segment.
|
|
|
|
let duration = first.duration().unwrap();
|
|
|
|
let end_time = first.pts().unwrap() + first.duration().unwrap();
|
2023-04-13 07:49:03 +00:00
|
|
|
state.end_time = Some(
|
|
|
|
segment
|
|
|
|
.to_running_time(end_time)
|
|
|
|
.expect("can't get running time"),
|
|
|
|
);
|
2021-10-18 06:42:42 +00:00
|
|
|
|
|
|
|
let mut file = std::fs::File::create(path).expect("failed to open fragment");
|
|
|
|
for buffer in &*buffer_list {
|
|
|
|
use std::io::prelude::*;
|
|
|
|
|
|
|
|
let map = buffer.map_readable().unwrap();
|
|
|
|
file.write_all(&map).expect("failed to write fragment");
|
|
|
|
}
|
|
|
|
|
|
|
|
state.segments.push(Segment {
|
|
|
|
start_time: pts,
|
|
|
|
duration,
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok(gst::FlowSuccess::Ok)
|
|
|
|
})
|
|
|
|
.eos(move |_sink| {
|
|
|
|
let state = state_clone.lock().unwrap();
|
|
|
|
|
|
|
|
// Now write the manifest
|
|
|
|
let mut path = state.path.clone();
|
|
|
|
path.push("manifest.mpd");
|
|
|
|
|
|
|
|
println!("writing manifest to {}", path.display());
|
|
|
|
|
2023-04-12 14:24:37 +00:00
|
|
|
let duration = state
|
|
|
|
.end_time
|
|
|
|
.opt_checked_sub(state.start_time)
|
|
|
|
.ok()
|
|
|
|
.flatten()
|
|
|
|
.unwrap()
|
|
|
|
.mseconds();
|
2021-10-18 06:42:42 +00:00
|
|
|
|
|
|
|
// Write the whole segment timeline out here, compressing multiple segments with
|
|
|
|
// the same duration to a repeated segment.
|
2023-04-12 14:24:37 +00:00
|
|
|
let mut segments = vec![];
|
2024-05-14 19:34:33 +00:00
|
|
|
let mut write_segment = |start: gst::ClockTime, duration: u64, repeat: usize| {
|
|
|
|
let mut s = dash_mpd::S {
|
|
|
|
t: Some(start.mseconds()),
|
|
|
|
d: duration,
|
|
|
|
..Default::default()
|
2023-04-12 14:24:37 +00:00
|
|
|
};
|
2024-05-14 19:34:33 +00:00
|
|
|
if repeat > 0 {
|
|
|
|
s.r = Some(repeat as i64);
|
|
|
|
}
|
|
|
|
|
|
|
|
segments.push(s);
|
|
|
|
};
|
2021-10-18 06:42:42 +00:00
|
|
|
|
|
|
|
let mut start = None;
|
|
|
|
let mut num_segments = 0;
|
|
|
|
let mut last_duration = None;
|
|
|
|
for segment in &state.segments {
|
|
|
|
if start.is_none() {
|
|
|
|
start = Some(segment.start_time);
|
|
|
|
}
|
|
|
|
if last_duration.is_none() {
|
2024-05-14 19:34:33 +00:00
|
|
|
last_duration = Some(segment.duration.mseconds());
|
2021-10-18 06:42:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// If the duration of this segment is different from the previous one then we
|
|
|
|
// have to write out the segment now.
|
2024-05-14 19:34:33 +00:00
|
|
|
if last_duration != Some(segment.duration.mseconds()) {
|
2021-10-18 06:42:42 +00:00
|
|
|
write_segment(start.unwrap(), last_duration.unwrap(), num_segments - 1);
|
|
|
|
start = Some(segment.start_time);
|
2024-05-14 19:34:33 +00:00
|
|
|
last_duration = Some(segment.duration.mseconds());
|
2021-10-18 06:42:42 +00:00
|
|
|
num_segments = 1;
|
|
|
|
} else {
|
|
|
|
num_segments += 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write the last segment if any
|
|
|
|
if num_segments > 0 {
|
|
|
|
write_segment(start.unwrap(), last_duration.unwrap(), num_segments - 1);
|
|
|
|
}
|
|
|
|
|
2023-04-12 14:24:37 +00:00
|
|
|
let segment_template = dash_mpd::SegmentTemplate {
|
|
|
|
timescale: Some(1000),
|
|
|
|
initialization: Some("init.cmfi".to_string()),
|
|
|
|
media: Some("segment_$Number$.cmfv".to_string()),
|
|
|
|
SegmentTimeline: Some(dash_mpd::SegmentTimeline { segments }),
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
|
|
|
|
let rep = dash_mpd::Representation {
|
|
|
|
id: Some("A".to_string()),
|
|
|
|
width: Some(1280),
|
|
|
|
height: Some(720),
|
|
|
|
bandwidth: Some(2048000),
|
|
|
|
SegmentTemplate: Some(segment_template),
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
|
|
|
|
let adapt = dash_mpd::AdaptationSet {
|
|
|
|
contentType: Some("video".to_string()),
|
|
|
|
mimeType: Some("video/mp4".to_string()),
|
|
|
|
codecs: Some("avc1.4d0228".to_string()),
|
|
|
|
frameRate: Some("30/1".to_string()),
|
|
|
|
segmentAlignment: Some(true),
|
|
|
|
subsegmentStartsWithSAP: Some(1),
|
|
|
|
representations: vec![rep],
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
|
|
|
|
let period = dash_mpd::Period {
|
|
|
|
adaptations: vec![adapt],
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
|
|
|
|
let mpd = dash_mpd::MPD {
|
|
|
|
mpdtype: Some("static".to_string()),
|
|
|
|
xmlns: Some("urn:mpeg:dash:schema:mpd:2011".to_string()),
|
|
|
|
schemaLocation: Some("urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd".to_string()),
|
|
|
|
profiles: Some("urn:mpeg:dash:profile:isoff-on-demand:2011".to_string()),
|
|
|
|
periods: vec![period],
|
|
|
|
mediaPresentationDuration: Some(std::time::Duration::from_millis(duration)),
|
2023-04-27 12:16:40 +00:00
|
|
|
minBufferTime: Some(std::time::Duration::from_secs(1)),
|
2023-04-12 14:24:37 +00:00
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
|
|
|
|
use serde::ser::Serialize;
|
|
|
|
|
|
|
|
let mut xml = String::new();
|
|
|
|
let mut ser = quick_xml::se::Serializer::new(&mut xml);
|
|
|
|
ser.indent(' ', 4);
|
|
|
|
mpd.serialize(ser).unwrap();
|
|
|
|
|
|
|
|
let manifest = format!(
|
|
|
|
r###"<?xml version="1.0" encoding="UTF-8"?>
|
|
|
|
{xml}
|
|
|
|
"###
|
|
|
|
);
|
2021-10-18 06:42:42 +00:00
|
|
|
|
2022-12-13 09:43:16 +00:00
|
|
|
std::fs::write(path, manifest).expect("failed to write manifest");
|
2021-10-18 06:42:42 +00:00
|
|
|
})
|
|
|
|
.build(),
|
|
|
|
);
|
|
|
|
|
|
|
|
pipeline.set_state(gst::State::Playing)?;
|
|
|
|
|
|
|
|
let bus = pipeline
|
|
|
|
.bus()
|
|
|
|
.expect("Pipeline without bus. Shouldn't happen!");
|
|
|
|
|
|
|
|
for msg in bus.iter_timed(gst::ClockTime::NONE) {
|
|
|
|
use gst::MessageView;
|
|
|
|
|
|
|
|
match msg.view() {
|
|
|
|
MessageView::Eos(..) => {
|
|
|
|
println!("EOS");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
MessageView::Error(err) => {
|
|
|
|
pipeline.set_state(gst::State::Null)?;
|
|
|
|
eprintln!(
|
|
|
|
"Got error from {}: {} ({})",
|
|
|
|
msg.src()
|
|
|
|
.map(|s| String::from(s.path_string()))
|
|
|
|
.unwrap_or_else(|| "None".into()),
|
2021-12-02 20:31:52 +00:00
|
|
|
err.error(),
|
2021-10-18 06:42:42 +00:00
|
|
|
err.debug().unwrap_or_else(|| "".into()),
|
|
|
|
);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pipeline.set_state(gst::State::Null)?;
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|