2022-06-29 16:17:02 +00:00
|
|
|
package warp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"encoding/binary"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/fs"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/abema/go-mp4"
|
|
|
|
"github.com/kixelated/invoker"
|
|
|
|
"github.com/zencoder/go-dash/v3/mpd"
|
|
|
|
)
|
|
|
|
|
|
|
|
// This is a demo; you should actually fetch media from a live backend.
|
|
|
|
// It's just much easier to read from disk and "fake" being live.
|
|
|
|
type Media struct {
|
|
|
|
base fs.FS
|
2022-11-18 23:13:35 +00:00
|
|
|
inits map[string]*MediaInit
|
|
|
|
video []*mpd.Representation
|
|
|
|
audio []*mpd.Representation
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewMedia(playlistPath string) (m *Media, err error) {
|
|
|
|
m = new(Media)
|
|
|
|
|
|
|
|
// Create a fs.FS out of the folder holding the playlist
|
|
|
|
m.base = os.DirFS(filepath.Dir(playlistPath))
|
|
|
|
|
|
|
|
// Read the playlist file
|
|
|
|
playlist, err := mpd.ReadFromFile(playlistPath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to open playlist: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(playlist.Periods) > 1 {
|
|
|
|
return nil, fmt.Errorf("multiple periods not supported")
|
|
|
|
}
|
|
|
|
|
|
|
|
period := playlist.Periods[0]
|
|
|
|
|
|
|
|
for _, adaption := range period.AdaptationSets {
|
|
|
|
representation := adaption.Representations[0]
|
|
|
|
|
|
|
|
if representation.MimeType == nil {
|
|
|
|
return nil, fmt.Errorf("missing representation mime type")
|
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
if representation.Bandwidth == nil {
|
|
|
|
return nil, fmt.Errorf("missing representation bandwidth")
|
|
|
|
}
|
|
|
|
|
2022-06-29 16:17:02 +00:00
|
|
|
switch *representation.MimeType {
|
|
|
|
case "video/mp4":
|
2022-11-18 23:13:35 +00:00
|
|
|
m.video = append(m.video, representation)
|
2022-06-29 16:17:02 +00:00
|
|
|
case "audio/mp4":
|
2022-11-18 23:13:35 +00:00
|
|
|
m.audio = append(m.audio, representation)
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
if len(m.video) == 0 {
|
2022-06-29 16:17:02 +00:00
|
|
|
return nil, fmt.Errorf("no video representation found")
|
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
if len(m.audio) == 0 {
|
2022-06-29 16:17:02 +00:00
|
|
|
return nil, fmt.Errorf("no audio representation found")
|
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
m.inits = make(map[string]*MediaInit)
|
|
|
|
|
|
|
|
var reps []*mpd.Representation
|
|
|
|
reps = append(reps, m.audio...)
|
|
|
|
reps = append(reps, m.video...)
|
|
|
|
|
|
|
|
for _, rep := range reps {
|
|
|
|
path := *rep.SegmentTemplate.Initialization
|
|
|
|
|
|
|
|
// TODO Support the full template engine
|
|
|
|
path = strings.ReplaceAll(path, "$RepresentationID$", *rep.ID)
|
|
|
|
|
|
|
|
f, err := fs.ReadFile(m.base, path)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to read init file: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
init, err := newMediaInit(*rep.ID, f)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to create init segment: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
m.inits[*rep.ID] = init
|
|
|
|
}
|
|
|
|
|
2022-06-29 16:17:02 +00:00
|
|
|
return m, nil
|
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
func (m *Media) Start(bitrate func() uint64) (inits map[string]*MediaInit, audio *MediaStream, video *MediaStream, err error) {
|
2022-06-29 16:17:02 +00:00
|
|
|
start := time.Now()
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
audio, err = newMediaStream(m, m.audio, start, bitrate)
|
2022-06-29 16:17:02 +00:00
|
|
|
if err != nil {
|
2022-11-18 23:13:35 +00:00
|
|
|
return nil, nil, nil, err
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
video, err = newMediaStream(m, m.video, start, bitrate)
|
2022-06-29 16:17:02 +00:00
|
|
|
if err != nil {
|
2022-11-18 23:13:35 +00:00
|
|
|
return nil, nil, nil, err
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
return m.inits, audio, video, nil
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type MediaStream struct {
|
2022-11-18 23:13:35 +00:00
|
|
|
Media *Media
|
2022-06-29 16:17:02 +00:00
|
|
|
|
|
|
|
start time.Time
|
2022-11-18 23:13:35 +00:00
|
|
|
reps []*mpd.Representation
|
2022-06-29 16:17:02 +00:00
|
|
|
sequence int
|
2022-11-18 23:13:35 +00:00
|
|
|
bitrate func() uint64 // returns the current estimated bitrate
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
func newMediaStream(m *Media, reps []*mpd.Representation, start time.Time, bitrate func() uint64) (ms *MediaStream, err error) {
|
2022-06-29 16:17:02 +00:00
|
|
|
ms = new(MediaStream)
|
2022-11-18 23:13:35 +00:00
|
|
|
ms.Media = m
|
|
|
|
ms.reps = reps
|
2022-06-29 16:17:02 +00:00
|
|
|
ms.start = start
|
2022-11-18 23:13:35 +00:00
|
|
|
ms.bitrate = bitrate
|
2022-06-29 16:17:02 +00:00
|
|
|
return ms, nil
|
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
func (ms *MediaStream) chooseRepresentation() (choice *mpd.Representation) {
|
|
|
|
bitrate := ms.bitrate()
|
2022-06-29 16:17:02 +00:00
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
// Loop over the renditions and pick the highest bitrate we can support
|
|
|
|
for _, r := range ms.reps {
|
|
|
|
if uint64(*r.Bandwidth) <= bitrate && (choice == nil || *r.Bandwidth > *choice.Bandwidth) {
|
|
|
|
choice = r
|
|
|
|
}
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
if choice != nil {
|
|
|
|
return choice
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
// We can't support any of the bitrates, so find the lowest one.
|
|
|
|
for _, r := range ms.reps {
|
|
|
|
if choice == nil || *r.Bandwidth < *choice.Bandwidth {
|
|
|
|
choice = r
|
|
|
|
}
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
return choice
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Returns the next segment in the stream
|
2022-11-18 23:13:35 +00:00
|
|
|
func (ms *MediaStream) Next(ctx context.Context) (segment *MediaSegment, err error) {
|
|
|
|
rep := ms.chooseRepresentation()
|
|
|
|
|
|
|
|
if rep.SegmentTemplate == nil {
|
|
|
|
return nil, fmt.Errorf("missing segment template")
|
|
|
|
}
|
|
|
|
|
|
|
|
if rep.SegmentTemplate.Media == nil {
|
2022-06-29 16:17:02 +00:00
|
|
|
return nil, fmt.Errorf("no media template")
|
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
if rep.SegmentTemplate.StartNumber == nil {
|
|
|
|
return nil, fmt.Errorf("missing start number")
|
|
|
|
}
|
|
|
|
|
|
|
|
path := *rep.SegmentTemplate.Media
|
|
|
|
sequence := ms.sequence + int(*rep.SegmentTemplate.StartNumber)
|
2022-06-29 16:17:02 +00:00
|
|
|
|
|
|
|
// TODO Support the full template engine
|
2022-11-18 23:13:35 +00:00
|
|
|
path = strings.ReplaceAll(path, "$RepresentationID$", *rep.ID)
|
|
|
|
path = strings.ReplaceAll(path, "$Number%05d$", fmt.Sprintf("%05d", sequence)) // TODO TODO
|
2022-06-29 16:17:02 +00:00
|
|
|
|
|
|
|
// Try openning the file
|
2022-11-18 23:13:35 +00:00
|
|
|
f, err := ms.Media.base.Open(path)
|
|
|
|
if errors.Is(err, os.ErrNotExist) && ms.sequence != 0 {
|
2022-06-29 16:17:02 +00:00
|
|
|
// Return EOF if the next file is missing
|
|
|
|
return nil, nil
|
|
|
|
} else if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to open segment file: %w", err)
|
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
duration := time.Duration(*rep.SegmentTemplate.Duration) / time.Nanosecond
|
|
|
|
timestamp := time.Duration(ms.sequence) * duration
|
2022-06-29 16:17:02 +00:00
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
init := ms.Media.inits[*rep.ID]
|
2022-06-29 16:17:02 +00:00
|
|
|
|
|
|
|
segment, err = newMediaSegment(ms, init, f, timestamp)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to create segment: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
ms.sequence += 1
|
|
|
|
|
|
|
|
return segment, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type MediaInit struct {
|
2022-11-18 23:13:35 +00:00
|
|
|
ID string
|
2022-06-29 16:17:02 +00:00
|
|
|
Raw []byte
|
|
|
|
Timescale int
|
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
func newMediaInit(id string, raw []byte) (mi *MediaInit, err error) {
|
2022-06-29 16:17:02 +00:00
|
|
|
mi = new(MediaInit)
|
2022-11-18 23:13:35 +00:00
|
|
|
mi.ID = id
|
2022-06-29 16:17:02 +00:00
|
|
|
mi.Raw = raw
|
|
|
|
|
|
|
|
err = mi.parse()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse init segment: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return mi, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse through the init segment, literally just to populate the timescale
|
|
|
|
func (mi *MediaInit) parse() (err error) {
|
|
|
|
r := bytes.NewReader(mi.Raw)
|
|
|
|
|
|
|
|
_, err = mp4.ReadBoxStructure(r, func(h *mp4.ReadHandle) (interface{}, error) {
|
|
|
|
if !h.BoxInfo.IsSupportedType() {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
payload, _, err := h.ReadPayload()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
switch box := payload.(type) {
|
|
|
|
case *mp4.Mdhd: // Media Header; moov -> trak -> mdia > mdhd
|
|
|
|
if mi.Timescale != 0 {
|
|
|
|
// verify only one track
|
|
|
|
return nil, fmt.Errorf("multiple mdhd atoms")
|
|
|
|
}
|
|
|
|
|
|
|
|
mi.Timescale = int(box.Timescale)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Expands children
|
|
|
|
return h.Expand()
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to parse MP4 file: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type MediaSegment struct {
|
2022-11-18 23:13:35 +00:00
|
|
|
Stream *MediaStream
|
|
|
|
Init *MediaInit
|
|
|
|
|
2022-06-29 16:17:02 +00:00
|
|
|
file fs.File
|
|
|
|
timestamp time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
func newMediaSegment(s *MediaStream, init *MediaInit, file fs.File, timestamp time.Duration) (ms *MediaSegment, err error) {
|
|
|
|
ms = new(MediaSegment)
|
2022-11-18 23:13:35 +00:00
|
|
|
ms.Stream = s
|
|
|
|
ms.Init = init
|
|
|
|
|
2022-06-29 16:17:02 +00:00
|
|
|
ms.file = file
|
|
|
|
ms.timestamp = timestamp
|
2022-11-18 23:13:35 +00:00
|
|
|
|
2022-06-29 16:17:02 +00:00
|
|
|
return ms, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Return the next atom, sleeping based on the PTS to simulate a live stream
|
|
|
|
func (ms *MediaSegment) Read(ctx context.Context) (chunk []byte, err error) {
|
|
|
|
// Read the next top-level box
|
|
|
|
var header [8]byte
|
|
|
|
|
|
|
|
_, err = io.ReadFull(ms.file, header[:])
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to read header: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
size := int(binary.BigEndian.Uint32(header[0:4]))
|
|
|
|
if size < 8 {
|
|
|
|
return nil, fmt.Errorf("box is too small")
|
|
|
|
}
|
|
|
|
|
|
|
|
buf := make([]byte, size)
|
|
|
|
n := copy(buf, header[:])
|
|
|
|
|
|
|
|
_, err = io.ReadFull(ms.file, buf[n:])
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to read atom: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
sample, err := ms.parseAtom(ctx, buf)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse atom: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if sample != nil {
|
|
|
|
// Simulate a live stream by sleeping before we write this sample.
|
|
|
|
// Figure out how much time has elapsed since the start
|
2022-11-18 23:13:35 +00:00
|
|
|
elapsed := time.Since(ms.Stream.start)
|
2022-06-29 16:17:02 +00:00
|
|
|
delay := sample.Timestamp - elapsed
|
|
|
|
|
|
|
|
if delay > 0 {
|
|
|
|
// Sleep until we're supposed to see these samples
|
|
|
|
err = invoker.Sleep(delay)(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return buf, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse through the MP4 atom, returning infomation about the next fragmented sample
|
|
|
|
func (ms *MediaSegment) parseAtom(ctx context.Context, buf []byte) (sample *mediaSample, err error) {
|
|
|
|
r := bytes.NewReader(buf)
|
|
|
|
|
|
|
|
_, err = mp4.ReadBoxStructure(r, func(h *mp4.ReadHandle) (interface{}, error) {
|
|
|
|
if !h.BoxInfo.IsSupportedType() {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
payload, _, err := h.ReadPayload()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
switch box := payload.(type) {
|
|
|
|
case *mp4.Moof:
|
|
|
|
sample = new(mediaSample)
|
|
|
|
case *mp4.Tfdt: // Track Fragment Decode Timestamp; moof -> traf -> tfdt
|
|
|
|
// TODO This box isn't required
|
|
|
|
// TODO we want the last PTS if there are multiple samples
|
|
|
|
var dts time.Duration
|
|
|
|
if box.FullBox.Version == 0 {
|
|
|
|
dts = time.Duration(box.BaseMediaDecodeTimeV0)
|
|
|
|
} else {
|
|
|
|
dts = time.Duration(box.BaseMediaDecodeTimeV1)
|
|
|
|
}
|
|
|
|
|
2022-11-18 23:13:35 +00:00
|
|
|
if ms.Init.Timescale == 0 {
|
2022-06-29 16:17:02 +00:00
|
|
|
return nil, fmt.Errorf("missing timescale")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Convert to seconds
|
|
|
|
// TODO What about PTS?
|
2022-11-18 23:13:35 +00:00
|
|
|
sample.Timestamp = dts * time.Second / time.Duration(ms.Init.Timescale)
|
2022-06-29 16:17:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Expands children
|
|
|
|
return h.Expand()
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to parse MP4 file: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return sample, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ms *MediaSegment) Close() (err error) {
|
|
|
|
return ms.file.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
type mediaSample struct {
|
|
|
|
Timestamp time.Duration // The timestamp of the first sample
|
|
|
|
}
|