use mediacommon/pkg/mpegts in examples

This commit is contained in:
aler9
2023-07-28 22:06:12 +02:00
committed by Alessandro Ros
parent 0a8c761fba
commit 577d6f3a28
5 changed files with 117 additions and 192 deletions

View File

@@ -2,15 +2,18 @@ package main
import (
"bufio"
"context"
"log"
"os"
"time"
"github.com/asticode/go-astits"
"github.com/bluenviron/mediacommon/pkg/codecs/h264"
"github.com/bluenviron/mediacommon/pkg/formats/mpegts"
)
func durationGoToMPEGTS(v time.Duration) int64 {
return int64(v.Seconds() * 90000)
}
// mpegtsMuxer allows to save a H264 stream into a MPEG-TS file.
type mpegtsMuxer struct {
sps []byte
@@ -18,7 +21,8 @@ type mpegtsMuxer struct {
f *os.File
b *bufio.Writer
mux *astits.Muxer
w *mpegts.Writer
track *mpegts.Track
dtsExtractor *h264.DTSExtractor
firstIDRReceived bool
startDTS time.Duration
@@ -32,19 +36,20 @@ func newMPEGTSMuxer(sps []byte, pps []byte) (*mpegtsMuxer, error) {
}
b := bufio.NewWriter(f)
mux := astits.NewMuxer(context.Background(), b)
mux.AddElementaryStream(astits.PMTElementaryStream{
ElementaryPID: 256,
StreamType: astits.StreamTypeH264Video,
})
mux.SetPCRPID(256)
track := &mpegts.Track{
PID: 256,
Codec: &mpegts.CodecH264{},
}
w := mpegts.NewWriter(b, []*mpegts.Track{track})
return &mpegtsMuxer{
sps: sps,
pps: pps,
f: f,
b: b,
mux: mux,
sps: sps,
pps: pps,
f: f,
b: b,
w: w,
track: track,
}, nil
}
@@ -131,39 +136,8 @@ func (e *mpegtsMuxer) encode(au [][]byte, pts time.Duration) error {
pts -= e.startDTS
}
oh := &astits.PESOptionalHeader{
MarkerBits: 2,
}
if dts == pts {
oh.PTSDTSIndicator = astits.PTSDTSIndicatorOnlyPTS
oh.PTS = &astits.ClockReference{Base: int64(pts.Seconds() * 90000)}
} else {
oh.PTSDTSIndicator = astits.PTSDTSIndicatorBothPresent
oh.DTS = &astits.ClockReference{Base: int64(dts.Seconds() * 90000)}
oh.PTS = &astits.ClockReference{Base: int64(pts.Seconds() * 90000)}
}
// encode into Annex-B
annexb, err := h264.AnnexBMarshal(au)
if err != nil {
return err
}
// write TS packet
_, err = e.mux.WriteData(&astits.MuxerData{
PID: 256,
AdaptationField: &astits.PacketAdaptationField{
RandomAccessIndicator: idrPresent,
},
PES: &astits.PESData{
Header: &astits.PESHeader{
OptionalHeader: oh,
StreamID: 224, // video
},
Data: annexb,
},
})
// encode into MPEG-TS
err := e.w.WriteH26x(e.track, durationGoToMPEGTS(pts), durationGoToMPEGTS(dts), idrPresent, au)
if err != nil {
return err
}