Documentation
¶
Overview ¶
Package video2dvd provides APIs for preparing DVD-compatible media and orchestrating DVD-Video directory creation from MP4 and WebM media.
The package itself does not start external processes. It includes in-process encoder and authorer implementations for creating menu-less DVD-Video output.
Index ¶
- Constants
- Variables
- func AVCConfigToAnnexB(config []byte) ([]byte, error)
- func AVCNALLengthSize(config []byte) (int, error)
- func AVCParameterSets(config []byte) ([][]byte, [][]byte, error)
- func AVCToAnnexB(sample []byte, nalLengthSize int) ([]byte, error)
- func BuildDVDNAVPack(info DVDNAVPackInfo) ([]byte, error)
- func DVDLanguageCode(language string) string
- func DecodeMP4Audio(ctx context.Context, path string, trackIndex *int, ...) (err error)
- func DecodeMP4Video(ctx context.Context, path string, trackIndex *int, ...) error
- func DecodeWebMAudio(ctx context.Context, path string, trackIndex *int, ...) error
- func DecodeWebMVideo(ctx context.Context, path string, trackIndex *int, ...) (err error)
- func MuxDVDTitleVOB(ctx context.Context, title EncodedTitle, workDir string, dst io.Writer) error
- func PrepareMP4AudioForDVD(ctx context.Context, path string, trackIndex *int, dst io.Writer) error
- func PrepareMP4VideoForDVD(ctx context.Context, path string, trackIndex *int, profile Profile, ...) error
- func PrepareWebMAudioForDVD(ctx context.Context, path string, trackIndex *int, dst io.Writer) error
- func PrepareWebMVideoForDVD(ctx context.Context, path string, trackIndex *int, profile Profile, ...) error
- func SupportedSubtitleCodec(codec string) bool
- func WriteDVDISO(ctx context.Context, videoTSDir, outputISO string) error
- func WriteDVDISOWithOptions(ctx context.Context, videoTSDir, outputISO string, options DVDImageOptions) error
- func WriteDVDLPCM(dst io.Writer, chunk PCMChunk) error
- func WriteDVDNAVPack(dst io.Writer, info DVDNAVPackInfo) error
- func WriteDVDSubtitleStream(w io.Writer, cues []SubtitleCue, duration time.Duration, profile Profile) error
- type AspectRatio
- type Authorer
- type ColorMatrix
- type Converter
- func (c *Converter) Convert(ctx context.Context, inputs []string, outputDir string, options Options) error
- func (c *Converter) ConvertISO(ctx context.Context, inputs []string, outputISO string, options Options) error
- func (c *Converter) ConvertSources(ctx context.Context, inputs []MediaInput, outputDir string, options Options) error
- func (c *Converter) ConvertSourcesISO(ctx context.Context, inputs []MediaInput, outputISO string, options Options) error
- type DVDFrameRateConverter
- type DVDImageOptions
- type DVDLPCMPacketWriter
- type DVDNAVButton
- type DVDNAVButtonGroup
- type DVDNAVPackInfo
- type DecodedVideoFrame
- type EncodedSubtitle
- type EncodedTitle
- type Encoder
- type FitMode
- type InProcessAuthorer
- type InProcessEncoder
- type MP4Info
- type MPEG2VideoEncoder
- type MPEG2VideoInfo
- type MPEGProgramStreamWriter
- type MediaInput
- type MenuFont
- type Options
- type PCMChunk
- type Profile
- type SampleHandler
- type SampleInfo
- type StreamEncoder
- type SubtitleCue
- type TrackInfo
- type TrackKind
- type VideoColor
- type VideoStandard
Constants ¶
const ( // SubtitleCodecTX3G is MP4 timed text (3GPP TS 26.245, MPEG-4 Part 17), // which ffmpeg calls mov_text. SubtitleCodecTX3G = "tx3g" // SubtitleCodecWebMVTT is WebVTT stored as the WebM project defines it: // each block holds the cue identifier, the cue settings and the cue // text, separated by line feeds. SubtitleCodecWebMVTT = "D_WEBVTT/SUBTITLES" // SubtitleCodecMatroskaVTT is WebVTT as the Matroska specification // stores it: each block holds the cue text only. SubtitleCodecMatroskaVTT = "S_TEXT/WEBVTT" // SubtitleCodecMatroskaSRT is plain UTF-8 text, the SubRip format. SubtitleCodecMatroskaSRT = "S_TEXT/UTF8" )
Codecs of the text subtitle tracks the converter reads, as TrackInfo reports them.
const ( VideoCodecMPEG2 = "mpeg2video" AudioCodecAC3 = "ac3" AudioCodecLPCM = "lpcm" AudioCodecMPEG1Layer2 = "mp2" )
const DVD5CapacityBytes int64 = 4_700_000_000
const DVDNAVAudioSyncNone uint16 = 0x3fff
DVDNAVAudioSyncNone is the A_SYNCA value of an audio stream that has no pack for the VOBU.
const DVDNAVSRIEndOfCell uint32 = 0x3fffffff
DVDNAVSRIEndOfCell marks the boundary of a DVD cell in a VOBU search pointer. It is used for a VOBU with no next or previous VOBU in its cell.
const DVDNAVSubpictureSyncCurrent uint32 = 0x7fffffff
DVDNAVSubpictureSyncCurrent is the SP_SYNCA value of a subpicture stream whose unit for the VOBU is stored in the VOBU itself.
const (
DVDVOBSectorSize = 2048
)
Variables ¶
var ( ErrNoInputs = errors.New("video2dvd: at least one input file is required") ErrOutputExists = errors.New("video2dvd: output path already exists") ErrInvalidProfile = errors.New("video2dvd: invalid DVD profile") ErrDiscCapacity = errors.New("video2dvd: authored DVD exceeds configured capacity") )
var ErrInvalidAVC = errors.New("video2dvd: invalid AVC sample or configuration")
var ErrInvalidMP4 = errors.New("video2dvd: invalid or unsupported MP4 container")
Functions ¶
func AVCConfigToAnnexB ¶
AVCConfigToAnnexB writes the SPS and PPS units from avcC in Annex-B form.
func AVCNALLengthSize ¶
AVCNALLengthSize returns the size of the NAL unit length field stored in an avcC decoder configuration record.
func AVCParameterSets ¶
AVCParameterSets returns the SPS and PPS NAL units in an avcC record.
func AVCToAnnexB ¶
AVCToAnnexB converts one length-prefixed AVC access unit from MP4 into Annex-B NAL units. nalLengthSize must come from the track's avcC record.
func BuildDVDNAVPack ¶
func BuildDVDNAVPack(info DVDNAVPackInfo) ([]byte, error)
BuildDVDNAVPack builds one 2048-byte DVD navigation pack containing the MPEG-2 pack and system headers, followed by PCI and DSI private-stream-2 packets. It is a pack primitive; callers still need to arrange VOBUs and generate the corresponding IFO navigation tables.
func DVDLanguageCode ¶ added in v1.1.0
DVDLanguageCode returns the two-letter ISO 639-1 code that DVD-Video stores for a language, given a BCP 47 tag ("ja", "pt-BR", "zh-Hant"), an ISO 639-2 code of either form ("jpn", "ger", "deu") or an ISO 639-1 code. It returns "" for an undetermined language ("und", "mul", "zxx") and for a language that ISO 639-1 has no code for.
func DecodeMP4Audio ¶
func DecodeMP4Audio(ctx context.Context, path string, trackIndex *int, handler func(PCMChunk) error) (err error)
DecodeMP4Audio decodes an AAC-LC or AC-3 MP4 audio track to 48 kHz stereo S16 PCM. trackIndex selects the zero-based trak; nil selects a supported track. Chunks are contiguous and start at movie time zero: a leading empty edit becomes silence and the first media edit's start and length are applied rounded to whole samples. Later edits are not applied.
If the primary decoder rejects an AAC access unit because of non-zero byte-alignment padding, the AAC-LC fallback decoder finishes the track. When that happens after chunks were already delivered, the fallback's output is placed on the same timeline and only the part after the last delivered frame is passed on, so the handler sees one contiguous stream without repeated or missing audio and never has to discard what it received.
func DecodeMP4Video ¶
func DecodeMP4Video(ctx context.Context, path string, trackIndex *int, handler func(DecodedVideoFrame) error) error
DecodeMP4Video decodes one progressive 8-bit 4:2:0 H.264 track. trackIndex is a zero-based trak index; nil selects the first H.264 video track. Frames are delivered in presentation order and own their pixel buffers.
func DecodeWebMAudio ¶
func DecodeWebMAudio(ctx context.Context, path string, trackIndex *int, handler func(PCMChunk) error) error
DecodeWebMAudio sends 48 kHz stereo Opus PCM chunks from a WebM file. The selected stream index is zero-based in the container track list.
func DecodeWebMVideo ¶
func DecodeWebMVideo(ctx context.Context, path string, trackIndex *int, handler func(DecodedVideoFrame) error) (err error)
DecodeWebMVideo sends owned 8-bit YUV 4:2:0 frames from a WebM video track to handler. VP9 Profile 0 and Profile 2 use the stateful go-vp9 decoder so reference frames, hidden frames, superframes, and resolution changes are processed consistently. VP8/AV1 use the bundled pure-Go media pipeline.
func MuxDVDTitleVOB ¶
MuxDVDTitleVOB combines one MPEG-2 elementary stream and one raw DVD LPCM stream into VOBUs with NAV packs and fixed-size MPEG program-stream sectors. The result does not include IFO/BUP files or complete DVD navigation tables.
The output is one continuous sector stream whose NAV addresses are relative to its first sector; it is not split at the 1 GiB DVD file size limit.
func PrepareMP4AudioForDVD ¶
PrepareMP4AudioForDVD decodes the selected AAC-LC or AC-3 track to 48 kHz stereo and writes big-endian 16-bit DVD LPCM audio essence. The destination is not a VOB audio PES stream; an authorer still needs to packetize it and add the DVD LPCM private-stream headers.
dst is written sequentially and never rewound: when the AAC fallback decoder takes over from the primary decoder (see DecodeMP4Audio), it continues after the last frame already written. On an error, dst holds the valid start of the stream up to the point of failure.
func PrepareMP4VideoForDVD ¶
func PrepareMP4VideoForDVD( ctx context.Context, path string, trackIndex *int, profile Profile, sourceAspectNumerator, sourceAspectDenominator int, mode FitMode, handler func(DecodedVideoFrame) error, ) error
PrepareMP4VideoForDVD decodes an MP4 H.264 track, fits frames to the DVD raster and its BT.601 studio-range colour encoding (see FitVideoFrameForDVD), and converts the presentation timestamps to the selected DVD frame rate. Source display aspect ratio must be supplied by the caller because some MP4 files use non-square pixels or rotation metadata not represented by the decoded frame dimensions. The handler receives owned DVD-raster frames. When the track has an edit list, output starts at movie time zero: frames before the first media edit are skipped and a leading empty edit holds the first frame.
func PrepareWebMAudioForDVD ¶
PrepareWebMAudioForDVD decodes an Opus track to 48 kHz stereo and writes DVD LPCM audio essence. AV1/Opus decoding and WebM demuxing use pure-Go packages.
func PrepareWebMVideoForDVD ¶
func PrepareWebMVideoForDVD( ctx context.Context, path string, trackIndex *int, profile Profile, sourceAspectNumerator, sourceAspectDenominator int, mode FitMode, handler func(DecodedVideoFrame) error, ) error
PrepareWebMVideoForDVD decodes WebM VP9 (including 10/12-bit VP9 Profile 2), VP8, or AV1 video, converts frames to 8-bit YUV 4:2:0, and prepares the DVD raster, colour encoding (see FitVideoFrameForDVD) and frame rate. High-bit-depth VP9 is reduced to 8-bit for DVD. Timestamps of constant-frame-rate video, which WebM stores rounded to its millisecond tick, are put back on their exact frame times before frame-rate conversion; the first frame's timestamp is kept.
func SupportedSubtitleCodec ¶ added in v1.1.0
SupportedSubtitleCodec reports whether the converter reads subtitle tracks of a codec, as reported by TrackInfo.Codec.
func WriteDVDISO ¶
WriteDVDISO writes an authored VIDEO_TS directory as a DVD-Video UDF bridge image. It creates an ISO 9660 view and a UDF 1.02 view over the same file extents, and publishes outputISO only after the image has been completed.
func WriteDVDISOWithOptions ¶
func WriteDVDISOWithOptions(ctx context.Context, videoTSDir, outputISO string, options DVDImageOptions) error
WriteDVDISOWithOptions is WriteDVDISO with a volume identifier and capacity limit. The image is assembled in-process and does not invoke external tools.
func WriteDVDLPCM ¶
WriteDVDLPCM writes the audio essence for a DVD 48 kHz, 16-bit, two-channel LPCM stream. Samples are signed PCM values interleaved left/right and are written big-endian as required by DVD LPCM. A DVD muxer must still wrap this essence in private_stream_1 PES packets and add each packet's LPCM headers.
func WriteDVDNAVPack ¶
func WriteDVDNAVPack(dst io.Writer, info DVDNAVPackInfo) error
WriteDVDNAVPack writes one fixed-size navigation pack without closing dst.
func WriteDVDSubtitleStream ¶ added in v1.1.0
func WriteDVDSubtitleStream(w io.Writer, cues []SubtitleCue, duration time.Duration, profile Profile) error
WriteDVDSubtitleStream draws subtitle cues for a title as a DVD subtitle stream file, the form EncodedSubtitle.Path refers to. Cue times are on the title timeline, which starts when the first picture of the title is shown, and the cues are cut to the title's duration. Cues may overlap: while several are shown together, their texts are shown one below the other.
The text is drawn with profile.MenuFont, or with the built-in fonts when it is nil, as on the title menu: without a MenuFont, ASCII letters are shown in upper case. It is drawn in white with a black outline, centred at the bottom of the title-safe area, in lines broken to fit 80% of the frame width; Japanese text may break between any two characters except before closing punctuation and small kana.
The file is a sequence of subpicture units in presentation order, each preceded by its presentation time as a big-endian 64-bit count of 90 kHz ticks from the start of the title. Every unit shows its picture at that time and hides it before the next unit is presented.
Types ¶
type AspectRatio ¶
type AspectRatio uint8
AspectRatio is the display aspect ratio signaled in the MPEG-2 stream.
const ( AspectRatio4x3 AspectRatio = iota + 1 AspectRatio16x9 )
type Authorer ¶
type Authorer interface {
Author(ctx context.Context, titles []EncodedTitle, outputDir string, profile Profile) error
}
Authorer creates a DVD-Video directory (including VIDEO_TS.IFO/BUP and VOB files) from the encoded titles. outputDir is an empty directory. Implementors should honor context cancellation. Converter passes absolute elementary-stream paths in titles.
type ColorMatrix ¶ added in v0.8.0
type ColorMatrix uint8
ColorMatrix identifies the Y'CbCr matrix a video was encoded with.
const ( // ColorMatrixUnspecified means the source carries no usable tag. Like // players do, the conversion then assumes BT.709 for pictures taller than // 576 lines or wider than 1024 samples and BT.601 for smaller ones. ColorMatrixUnspecified ColorMatrix = iota // ColorMatrixBT601 covers BT.601, BT.470BG, SMPTE 170M and FCC. ColorMatrixBT601 // ColorMatrixBT709 is the HD matrix. ColorMatrixBT709 // ColorMatrixOther is any tagged encoding the library does not convert, // such as BT.2020, SMPTE 240M, YCgCo or RGB. Samples pass through as they // are. ColorMatrixOther )
type Converter ¶
type Converter struct {
// contains filtered or unexported fields
}
Converter coordinates encoding and DVD authoring. It stages all files beside the destination and publishes the result with a directory rename only after authoring succeeds.
func New ¶
New constructs a Converter with the supplied encoding and authoring backends. It does not select defaults or invoke external commands.
func (*Converter) Convert ¶
func (c *Converter) Convert(ctx context.Context, inputs []string, outputDir string, options Options) error
Convert turns inputs into a DVD-Video directory at outputDir. outputDir must not already exist; it will contain a VIDEO_TS subdirectory on success.
func (*Converter) ConvertISO ¶
func (c *Converter) ConvertISO(ctx context.Context, inputs []string, outputISO string, options Options) error
ConvertISO converts inputs into a DVD-Video UDF bridge ISO image. The image contains both ISO 9660 and UDF 1.02 directory views over the same VIDEO_TS file extents and is published only after authoring and image creation succeed.
func (*Converter) ConvertSources ¶
func (c *Converter) ConvertSources(ctx context.Context, inputs []MediaInput, outputDir string, options Options) error
ConvertSources creates a DVD-Video directory from video sources and optional independent audio sources. Each MediaInput becomes one DVD title.
func (*Converter) ConvertSourcesISO ¶
func (c *Converter) ConvertSourcesISO(ctx context.Context, inputs []MediaInput, outputISO string, options Options) error
ConvertSourcesISO creates a DVD-Video UDF bridge image from media sources.
type DVDFrameRateConverter ¶
type DVDFrameRateConverter struct {
// contains filtered or unexported fields
}
DVDFrameRateConverter maps timestamped decoded frames to the standard DVD output rate: 30000/1001 fps for NTSC and 25 fps for PAL. It holds the most recent source frame and repeats or drops frames as needed. Input PTS values must be in presentation order and each frame must carry a positive Duration.
A converter made by NewDVDFilmFrameRateConverter has the film rate of 24000/1001 fps as its output rate instead.
func NewDVDFilmFrameRateConverter ¶ added in v0.8.0
func NewDVDFilmFrameRateConverter(profile Profile, handler func(DecodedVideoFrame) error) (*DVDFrameRateConverter, error)
NewDVDFilmFrameRateConverter creates a streaming converter to the film rate of an NTSC DVD, 24000/1001 fps, whose output NewMPEG2SoftTelecineEncoder codes. A source at that rate passes through frame for frame. One at exactly 24 fps keeps its timing too, so that audio stays in sync without being resampled: about every 1001st frame (41.7 s) is dropped instead, the first after 21 s, which keeps the picture within half a film period (21 ms) of its time. Any other cadence is followed by showing, at each output timestamp, the source frame nearest to it.
func NewDVDFrameRateConverter ¶
func NewDVDFrameRateConverter(profile Profile, handler func(DecodedVideoFrame) error) (*DVDFrameRateConverter, error)
NewDVDFrameRateConverter creates a streaming DVD frame-rate converter.
func (*DVDFrameRateConverter) Finish ¶
func (c *DVDFrameRateConverter) Finish() error
Finish emits output timestamps covered by the final input frame and closes the converter. It may be called only once.
func (*DVDFrameRateConverter) Push ¶
func (c *DVDFrameRateConverter) Push(frame DecodedVideoFrame) error
Push adds one decoded frame. Output is emitted as soon as the next input frame establishes that no earlier source frame can be selected for that output timestamp.
type DVDImageOptions ¶
type DVDImageOptions struct {
// VolumeID is the ISO 9660 volume identifier. Empty selects VIDEO2DVD.
VolumeID string
// DiscCapacityBytes is the maximum image size. Zero selects DVD5 capacity.
DiscCapacityBytes int64
}
DVDImageOptions configures a UDF 1.02 / ISO 9660 DVD-Video image.
type DVDLPCMPacketWriter ¶
type DVDLPCMPacketWriter struct {
// contains filtered or unexported fields
}
DVDLPCMPacketWriter packetizes 48 kHz, 16-bit stereo PCM into DVD LPCM private_stream_1 PES packets and writes them as 2048-byte program-stream sectors. It does not add NAV packs or DVD navigation files.
func NewDVDLPCMPacketWriter ¶
func NewDVDLPCMPacketWriter(dst io.Writer, streamNumber uint8) (*DVDLPCMPacketWriter, error)
NewDVDLPCMPacketWriter creates a writer for LPCM audio stream 0 through 7.
func (*DVDLPCMPacketWriter) Close ¶
func (w *DVDLPCMPacketWriter) Close() error
Close pads a final partial 80-sample LPCM frame with silence and flushes it. It does not close the destination writer.
func (*DVDLPCMPacketWriter) WriteChunk ¶
func (w *DVDLPCMPacketWriter) WriteChunk(chunk PCMChunk) error
WriteChunk adds contiguous interleaved stereo samples. Chunk timestamps must continue the same 48 kHz sample timeline.
type DVDNAVButton ¶
type DVDNAVButton struct {
XStart, YStart int
XEnd, YEnd int
Up, Down uint8
Left, Right uint8
Command [8]byte
}
DVDNAVButton describes one rectangular menu button. Coordinates use the DVD 720x480/576 display raster and commands are eight-byte DVD VM words.
type DVDNAVButtonGroup ¶ added in v0.7.0
type DVDNAVButtonGroup struct {
DisplayType uint8
Buttons []DVDNAVButton
}
DVDNAVButtonGroup is the button layout for one display mode. DisplayType has the meaning of DVDNAVPackInfo.ButtonDisplayType.
type DVDNAVPackInfo ¶
type DVDNAVPackInfo struct {
SCRBase uint64
// SCRExtension is the 27 MHz remainder (0-299) of the pack's system clock
// reference.
SCRExtension uint16
LogicalBlockNumber uint32
VOBUEndAddress uint32
// NextVOBU and PreviousVOBU are raw DSI VOBU_SRI pointers. Valid
// pointers contain the relative sector offset and bit 31; use
// DVDNAVSRIEndOfCell at a cell boundary. Zero defaults to end-of-cell.
NextVOBU uint32
PreviousVOBU uint32
// ForwardVOBUs and BackwardVOBUs are the raw FWDA and BWDA scan pointers
// in DSI order: ForwardVOBUs runs from +120 s down to +0.5 s and
// BackwardVOBUs from -0.5 s to -120 s. Zero entries default to
// DVDNAVSRIEndOfCell.
ForwardVOBUs [19]uint32
BackwardVOBUs [19]uint32
// AudioSync holds A_SYNCA for audio streams 0-7: the sector offset from
// this NAV pack to the audio pack presented at StartPTM, with bit 15 set
// for a pack that precedes the NAV pack. Zero marks an absent stream.
AudioSync [8]uint16
// SubpictureSync holds SP_SYNCA for subpicture streams 0-31: the sector
// offset to the VOBU that holds the subpicture unit shown during this
// VOBU, with bit 31 set for an earlier VOBU, or
// DVDNAVSubpictureSyncCurrent for this VOBU. Zero marks an absent stream.
SubpictureSync [32]uint32
FirstReferenceEndAddress uint32
SecondReferenceEndAddress uint32
ThirdReferenceEndAddress uint32
VOBID uint16
CellID uint8
StartPTM uint32
EndPTM uint32
// SequenceEndPTM is the end presentation time of the video when the VOBU
// ends with a sequence_end_code and zero otherwise.
SequenceEndPTM uint32
// VOBStartPTM and VOBEndPTM are the presentation times of the first and
// the end of the last video frame of the whole VOB.
VOBStartPTM uint32
VOBEndPTM uint32
CellElapsedTime [4]byte
// ButtonDisplayType tells which display mode the first button group,
// Buttons, is laid out for. It is 0 for 4:3 video. For 16:9 video it is
// 1 for a widescreen display, 2 for a letterboxed and 4 for a
// pan-and-scan presentation on a 4:3 display; a group that serves more
// than one of these modes has the sum of their values.
ButtonDisplayType uint8
// Buttons is the first button group. The highlight is valid from
// StartPTM without an end time, as for a still menu, and recolours
// subpicture pattern pixels: palette entry 1 marks the selected button
// and palette entry 2 the activated one.
Buttons []DVDNAVButton
// ExtraButtonGroups holds up to two more layouts of the same buttons
// for other display modes. Every group needs as many buttons as the
// first one, and with n groups each may hold 36/n buttons.
ExtraButtonGroups []DVDNAVButtonGroup
}
DVDNAVPackInfo contains the navigation fields associated with one VOBU. Sector addresses are relative to the beginning of the VOB file. Reference end addresses are relative to the NAV pack, as required by DSI_GI.
type DecodedVideoFrame ¶
type DecodedVideoFrame struct {
PTS time.Duration
Duration time.Duration
Width int
Height int
Y []byte
U []byte
V []byte
Color VideoColor
}
DecodedVideoFrame is an owned, planar 8-bit YUV 4:2:0 frame. Chroma planes have half the luma width and height. PTS and Duration use the MP4 media timeline; edit-list offsets are not applied. Color is the encoding the decoders found in the container or bitstream; samples are delivered as decoded, without colour conversion.
func FitVideoFrame ¶
func FitVideoFrame(frame DecodedVideoFrame, profile Profile, sourceAspectNumerator, sourceAspectDenominator int, mode FitMode) (DecodedVideoFrame, error)
FitVideoFrame converts an owned planar YUV 4:2:0 frame to the raster and display aspect ratio described by profile. sourceAspectNumerator and sourceAspectDenominator describe the source's displayed aspect ratio, such as 16 and 9. Enlargement and reduction both use a Lanczos-3 filter whose support grows with the reduction ratio. Chroma is treated as horizontally co-sited with even luma columns (the MPEG-2, H.264 and VP9 default) and vertically centred, and picture edges are chroma-aligned.
For FitLetterbox, unused pixels are set to studio-range black. For FitCrop, the source is center-cropped. The input frame is not modified. Samples are only resampled: no colour-matrix or range conversion is applied and Color is copied from the source. FitVideoFrameForDVD adds that conversion.
func FitVideoFrameForDVD ¶ added in v0.8.0
func FitVideoFrameForDVD(frame DecodedVideoFrame, profile Profile, sourceAspectNumerator, sourceAspectDenominator int, mode FitMode) (DecodedVideoFrame, error)
FitVideoFrameForDVD is FitVideoFrame followed by conversion of the picture area to the colour encoding DVD players assume, BT.601 Y'CbCr in studio range. frame.Color selects the conversion; see VideoColor. The preparation functions and the built-in encoder use this function.
type EncodedSubtitle ¶ added in v1.1.0
type EncodedSubtitle struct {
// Path is a subtitle stream file as WriteDVDSubtitleStream writes it.
// A relative path is resolved from the work directory, and the file
// must be inside it.
Path string
// Language is the ISO 639-1 code of the subtitles, such as "ja", which
// players show and choose streams by (see DVDLanguageCode); empty marks
// the language as unspecified.
Language string
}
EncodedSubtitle is one DVD subtitle stream of an EncodedTitle.
type EncodedTitle ¶
type EncodedTitle struct {
VideoPath string
AudioPath string
VideoCodec string
AudioCodec string
Aspect AspectRatio
Width int
Height int
FrameRateNumerator int
FrameRateDenominator int
Duration time.Duration
// Name is an optional label for the title in the disc menu. The
// Converter sets it to the base name of the input video file without
// its extension unless the encoder provided one; without a name the
// menu falls back to the base name of VideoPath.
Name string
// Subtitles are the subtitle streams of the title, at most 32, in DVD
// stream order. Their files may be empty; a stream without units has no
// subtitles to show.
Subtitles []EncodedSubtitle
}
EncodedTitle describes DVD-compatible elementary streams produced for one input. Relative paths are resolved from the work directory passed to Encoder.Encode. Both streams must be non-empty files inside that directory. Video is MPEG-2; audio must be AC-3, LPCM, or MPEG-1 Layer II. The authorer may use the duration and frame rate to build navigation data.
The frame rate is that of the MPEG-2 sequence header, which on a DVD is the display rate of the standard: 30000/1001 or 25. Film on an NTSC disc is such a 30000/1001 stream as well, with repeat_first_field set on the pictures that are shown for three fields (soft telecine); the multiplexer times every picture by its own flags. 24000/1001 is not accepted.
type Encoder ¶
type Encoder interface {
Encode(ctx context.Context, inputPath, workDir string, profile Profile) (EncodedTitle, error)
}
Encoder decodes and encodes one input file into DVD-compatible elementary streams. Implementations should honor context cancellation and keep generated files inside workDir. It is called once for each input, in input order.
type FitMode ¶
type FitMode uint8
FitMode controls how FitVideoFrame places source pixels in the DVD raster.
type InProcessAuthorer ¶
type InProcessAuthorer struct {
// contains filtered or unexported fields
}
InProcessAuthorer writes a DVD-Video title set with an automatically generated title menu. Each encoded title is one DVD title and one chapter.
func NewInProcessAuthorer ¶
func NewInProcessAuthorer() *InProcessAuthorer
NewInProcessAuthorer returns the built-in IFO/BUP and VOB authorer.
func (*InProcessAuthorer) Author ¶
func (a *InProcessAuthorer) Author(ctx context.Context, titles []EncodedTitle, outputDir string, profile Profile) error
Author writes a title set for every encoded title. The output directory must be empty. VTS numbers and title order match the input order. A title larger than one VOB file continues in VTS_nn_2.VOB and following files.
type InProcessEncoder ¶
type InProcessEncoder struct{}
InProcessEncoder is a built-in Encoder that uses only Go code. Its MPEG-2 video coder emits closed GOPs of I and P pictures with half-sample motion compensation and VBV rate control, without B pictures, so it needs more bits than a dedicated encoder for the same quality. Pictures are fitted to the DVD raster with FitVideoFrameForDVD, so BT.709 and full-range sources are converted to the BT.601 studio-range encoding players assume. It converts MP4 AAC-LC/AC-3 and WebM Opus audio to LPCM, padded or trimmed to the encoded video length, and creates silent LPCM when the input has no audio track.
An NTSC title whose video track runs at 24000/1001 or 24 frames per second throughout is coded as film with 3:2 pulldown flags (soft telecine, see NewMPEG2SoftTelecineEncoder) unless Profile.DisableSoftTelecine is set.
The text subtitle tracks that MediaInput.SubtitleTracks selects are read before any video is encoded and written as subtitle streams with WriteDVDSubtitleStream, on the title timeline: a cue keeps its distance from the first video frame of its file.
func NewInProcessEncoder ¶
func NewInProcessEncoder() *InProcessEncoder
NewInProcessEncoder returns the built-in Encoder implementation.
func (*InProcessEncoder) Encode ¶
func (e *InProcessEncoder) Encode(ctx context.Context, inputPath, workDir string, profile Profile) (EncodedTitle, error)
Encode turns one MP4 or WebM into DVD-compatible elementary streams in workDir.
func (*InProcessEncoder) EncodeStreams ¶
func (e *InProcessEncoder) EncodeStreams(ctx context.Context, input MediaInput, workDir string, profile Profile) (EncodedTitle, error)
EncodeStreams encodes one DVD title from independent video/audio files or selected tracks in a shared file.
type MP4Info ¶
MP4Info contains basic movie and track metadata read from the MP4 box tables.
func DemuxMP4 ¶
func DemuxMP4(path string, handler SampleHandler) (MP4Info, error)
DemuxMP4 reports every compressed sample of the video and audio tracks of a non-fragmented MP4 in track order. It does not decode samples or convert H.264 length prefixes to Annex B.
func ProbeMP4 ¶
ProbeMP4 reads container metadata without decoding the media. It supports regular, non-fragmented MP4 files with a moov box and returns the first sample description for each track.
func ProbeMP4Reader ¶
ProbeMP4Reader is the ReaderAt form of ProbeMP4. size is the total length of the file. The reader is not closed or retained.
func ProbeMedia ¶
ProbeMedia selects the built-in MP4 or WebM metadata reader from the file signature and extension. WebM VP9, AV1, and Opus inputs can then use the corresponding DVD preparation functions.
type MPEG2VideoEncoder ¶
type MPEG2VideoEncoder struct {
// contains filtered or unexported fields
}
MPEG2VideoEncoder writes a DVD-raster MPEG-2 elementary stream from planar YUV 4:2:0 frames. It emits closed GOPs containing I pictures and P pictures. P pictures use half-sample forward motion vectors of up to 32 samples and quantized DCT residuals, and code macroblocks that have no usable prediction as intra macroblocks. A GOP holds at most 15 pictures; a scene change may end it earlier, but not before it lasts 0.4 s.
An encoder made by NewMPEG2SoftTelecineEncoder codes film: see there.
The writer does not close dst. Call Close after the final frame to write the MPEG sequence-end code.
func NewMPEG2SoftTelecineEncoder ¶ added in v0.8.0
func NewMPEG2SoftTelecineEncoder(dst io.Writer, profile Profile) (*MPEG2VideoEncoder, error)
NewMPEG2SoftTelecineEncoder prepares an encoder for film on an NTSC DVD. Every frame written is one film frame, 24000/1001 of them per second. The stream is still a 30000/1001 one of frame pictures, as DVD-Video requires; top_field_first and repeat_first_field of each picture tell the player to show the frames for three and two fields in turn (3:2 pulldown), which a progressive-scan player undoes to show the film frames themselves. The field parity runs on across GOPs. A GOP holds 12 pictures, which are shown for 30 fields; a scene change may end it after 11, and the GOPs after that hold 13 until one ends on a scene change after 12. Every GOP starts with a top field on a frame of the display raster.
The stream always ends on a whole frame, with a bottom field: where the pulldown cycle would end on a top field, Close gives the last picture one field more or less. Each picture is therefore written to dst when the next one arrives or the encoder is closed.
The profile must be an NTSC one. Use DisplayFields for the length of the stream.
func NewMPEG2VideoEncoder ¶
func NewMPEG2VideoEncoder(dst io.Writer, profile Profile) (*MPEG2VideoEncoder, error)
NewMPEG2VideoEncoder prepares an encoder for NTSC or PAL full-raster DVD frames. It writes the sequence header with the first GOP. Bitrates above 7.5 Mbit/s are coded at 7.5 Mbit/s so that the stream still fits the DVD multiplex next to LPCM audio.
func (*MPEG2VideoEncoder) Close ¶
func (e *MPEG2VideoEncoder) Close() error
Close finishes the elementary stream. It does not close the destination.
func (*MPEG2VideoEncoder) DisplayFields ¶ added in v0.8.0
func (e *MPEG2VideoEncoder) DisplayFields() int64
DisplayFields returns the number of fields the frames written so far are displayed for: two per frame, or five per two frames of a soft-telecined stream. A field lasts 1001/60000 s on an NTSC disc and 1/50 s on a PAL one. Closing a soft-telecined stream may add a field to the last picture or take one from it, so the length of the stream is to be read after Close.
func (*MPEG2VideoEncoder) WriteFrame ¶
func (e *MPEG2VideoEncoder) WriteFrame(frame DecodedVideoFrame) error
WriteFrame encodes one full-resolution planar YUV 4:2:0 frame. Frames must already be fitted and timestamp-resampled to the selected DVD profile.
type MPEG2VideoInfo ¶
type MPEG2VideoInfo struct {
Width int
Height int
Aspect AspectRatio
FrameRateNumerator int
FrameRateDenominator int
Profile string
Level string
}
MPEG2VideoInfo describes the first MPEG-2 sequence in an elementary stream.
func ProbeMPEG2Video ¶
func ProbeMPEG2Video(path string) (MPEG2VideoInfo, error)
ProbeMPEG2Video parses sequence and sequence-extension headers without decoding picture data. It accepts Main Profile at Main Level streams used by DVD-Video and rejects MPEG-1 streams.
type MPEGProgramStreamWriter ¶
type MPEGProgramStreamWriter struct {
// contains filtered or unexported fields
}
MPEGProgramStreamWriter packetizes PES data into 2048-byte MPEG-2 program stream sectors. It is a muxing primitive, not a complete DVD-Video authorer: DVD NAV packs, system/navigation tables, LPCM substream headers, and IFO/BUP files must be supplied by a higher layer.
func NewMPEGProgramStreamWriter ¶
func NewMPEGProgramStreamWriter(dst io.Writer) (*MPEGProgramStreamWriter, error)
NewMPEGProgramStreamWriter creates a sector writer with a 1.26 MB/s declared program mux rate. PES packets must be submitted in nondecreasing PTS order.
The system clock reference starts at zero and advances with the bytes written, pausing only so that a packet is not delivered more than 0.3 s before its PTS. The writer never moves a timestamp: callers that need a decoder start-up delay must add it to the timestamps they pass in.
func (*MPEGProgramStreamWriter) Close ¶
func (w *MPEGProgramStreamWriter) Close() error
Close writes the MPEG program_end_code in its own fixed-size pack. It does not close the destination writer.
type MediaInput ¶
type MediaInput struct {
VideoPath string
AudioPath string
VideoTrackIndex *int
AudioTrackIndex *int
AudioOffset time.Duration
SubtitleTracks []int
}
MediaInput identifies the video and optional audio source for one DVD title. When AudioPath is empty, audio is read from VideoPath. Track indexes are zero-based container track indexes; nil selects the first supported track. AudioOffset shifts decoded audio on the video timeline. Positive values add silence before the audio; negative values trim audio that starts before the video.
SubtitleTracks lists the indexes of the text subtitle tracks of VideoPath to record as the title's subtitle streams, in stream order: the first is subtitle stream 1 of the title. Each must be a track ReadSubtitleCues can read, and a title has at most 32 streams. Nil leaves the choice to Options.IncludeSubtitles; an empty, non-nil list records no subtitles. Subtitles follow the video: they keep their place on the timeline of VideoPath, whatever AudioOffset is.
type MenuFont ¶ added in v0.7.0
type MenuFont struct {
// contains filtered or unexported fields
}
MenuFont is an outline font for the text of the generated title menu. Set Options.MenuFont to draw the menu heading and the title names with it instead of the built-in bitmap fonts.
A MenuFont is immutable and may be shared by concurrent conversions.
func ParseMenuFont ¶ added in v0.7.0
ParseMenuFont parses a TrueType or OpenType font (TTF or OTF data) for Options.MenuFont. Given a font collection (TTC or OTC) it selects the first font; use ParseMenuFontIndex for another one.
The font keeps referring to data, which must not be modified afterwards. Fonts are read with golang.org/x/image/font/sfnt, which does not accept every font file; an error is returned for those.
type Options ¶
type Options struct {
Standard VideoStandard
Aspect AspectRatio
DiscCapacityBytes int64
// MenuTitle is the heading of the generated title menu; empty selects
// VIDEO2DVD. It and the title names may contain Japanese text.
MenuTitle string
MenuBackgroundLuma uint8
MenuTextLuma uint8
// MenuFont is an optional TrueType or OpenType font, made by
// ParseMenuFont, for the text of the title menu. Text is drawn
// anti-aliased, in the case it was written in, and with the proportions
// of the font on the display. Characters the font lacks are drawn with
// the built-in fonts. With a nil MenuFont all text uses the built-in
// fonts: ASCII in upper case, and Japanese in an embedded 16-pixel
// bitmap font. Subtitles (IncludeSubtitles) are drawn with the same
// fonts, at twice the size.
MenuFont *MenuFont
VideoBitrate int
// VolumeID is the volume name of an ISO image, as shown when the disc is
// mounted. It may contain up to 32 ASCII letters, digits, underscores,
// and spaces; letters are stored in upper case. Empty selects VIDEO2DVD.
// It has no effect on directory output.
VolumeID string
// DisableSoftTelecine turns off the film mode of NTSC titles. By default
// the built-in encoder codes a source whose whole video track runs at
// 24000/1001 or 24 frames per second as film: only the source frames are coded, and
// flags in the stream have the player show them for three and two fields
// in turn (3:2 pulldown) or, on a progressive-scan player, as they are.
// With this set such a source is converted like any other, by showing
// every fourth frame twice. It has no effect on PAL titles and on
// sources at other frame rates.
DisableSoftTelecine bool
// IncludeSubtitles records the text subtitle tracks of the inputs as
// DVD subtitles, which the viewer turns on and off and chooses between
// with the player's subtitle button. For each input whose
// MediaInput.SubtitleTracks is nil, every track of its video file that
// ReadSubtitleCues can read becomes a subtitle stream, in track order and
// up to the 32 streams of a title; other subtitle tracks are skipped. An
// input without such tracks gets no subtitles. Subtitles are drawn as
// WriteDVDSubtitleStream describes, with MenuFont when it is set.
IncludeSubtitles bool
// ShowSubtitles turns the first subtitle stream of a title on when the
// title starts playing. By default a title with subtitles starts with
// them hidden. It has no effect on titles without subtitles.
ShowSubtitles bool
}
Options controls conversion and DVD authoring. The zero value selects NTSC, 16:9, and the full-resolution DVD raster for that standard.
type PCMChunk ¶
PCMChunk contains interleaved signed 16-bit PCM in DVD's 48 kHz rate. The decoder outputs stereo by default, suitable for later LPCM multiplexing.
type Profile ¶
type Profile struct {
Standard VideoStandard
Aspect AspectRatio
FrameWidth int
FrameHeight int
DiscCapacityBytes int64
// MenuTitle and menu luma values customize the generated title menu.
MenuTitle string
MenuBackgroundLuma uint8
MenuTextLuma uint8
// MenuFont, if not nil, draws the menu text and the subtitles; see
// Options.MenuFont.
MenuFont *MenuFont
VideoBitrate int
// DisableSoftTelecine is Options.DisableSoftTelecine.
DisableSoftTelecine bool
// ShowSubtitles is Options.ShowSubtitles.
ShowSubtitles bool
}
Profile describes the DVD-compatible video target requested from Encoder.
type SampleHandler ¶
type SampleHandler func(track TrackInfo, sample SampleInfo, data io.Reader) error
SampleHandler receives compressed samples in track order. The Reader is limited to the current sample and becomes invalid after the callback returns.
type SampleInfo ¶
type SampleInfo struct {
SampleNumber int
Offset int64
Size uint32
DTS int64
PTS int64
Duration uint32
KeyFrame bool
DescriptionIndex uint32
}
SampleInfo describes one compressed MP4 sample. DTS, PTS, and Duration are expressed in the track's TimeScale. SampleNumber is one-based.
type StreamEncoder ¶
type StreamEncoder interface {
EncodeStreams(ctx context.Context, input MediaInput, workDir string, profile Profile) (EncodedTitle, error)
}
StreamEncoder optionally accepts independent video and audio sources. Converter uses it when available; legacy Encoder implementations continue to work for single-file inputs without explicit track selection or offsets.
type SubtitleCue ¶ added in v1.1.0
SubtitleCue is a text shown from Start until End. Text is plain text: the markup of the source format is removed, character references are resolved, and lines are separated by "\n".
func ReadSubtitleCues ¶ added in v1.1.0
func ReadSubtitleCues(path string, trackIndex int) ([]SubtitleCue, error)
ReadSubtitleCues reads the cues of a text subtitle track (see SupportedSubtitleCodec) of an MP4 or WebM file. trackIndex is the zero-based track index of TrackInfo.Index. Cues are returned in file order on the timeline of the file: the WebM block timestamps, or for MP4 the movie timeline the track's edit list maps its samples to. A cue whose duration is not stated lasts until the next cue starts, at most five seconds. Cues may overlap; cues without text are left out.
type TrackInfo ¶
type TrackInfo struct {
Index int
Kind TrackKind
Codec string
CodecConfig []byte
NALLengthSize int
Width int
Height int
PixelAspectHorizontal uint32
PixelAspectVertical uint32
SampleRate int
Channels int
Duration time.Duration
DefaultDuration time.Duration
TimeScale uint32
Color VideoColor
Language string
Name string
// contains filtered or unexported fields
}
TrackInfo contains container-level metadata. Codec is the MP4 sample-entry code or the WebM codec name. CodecConfig contains codec-specific setup data. PixelAspectHorizontal and PixelAspectVertical describe the displayed pixel shape; zero means square pixels or no pixel aspect metadata was present. Color is the colour encoding a video track is tagged with: for MP4 the H.264 VUI of the first SPS or else the colr box, for WebM the Colour element. Untagged tracks report ColorMatrixUnspecified.
Language is the language the container states for the track: the BCP 47 tag of an MP4 elng box or of a WebM LanguageBCP47 element if there is one, else the ISO 639-2 code of the MP4 media header or of the WebM Language element ("und" when it is undetermined). Name is the MP4 handler name or the WebM track name; it may be empty.
type TrackKind ¶
type TrackKind string
TrackKind identifies the media carried by an MP4 or WebM track.
const ( TrackKindVideo TrackKind = "video" TrackKindAudio TrackKind = "audio" // TrackKindSubtitle is a subtitle track: an MP4 track with a subtitle or // timed-text handler ("sbtl", "subt", "text") that no other track uses // for its chapter names, or a WebM subtitle track. Codec tells whether // the converter can read it; see SupportedSubtitleCodec. TrackKindSubtitle TrackKind = "subtitle" TrackKindOther TrackKind = "other" )
type VideoColor ¶ added in v0.8.0
type VideoColor struct {
Matrix ColorMatrix
// FullRange is set only when the source explicitly signals full-range
// (0..255) samples instead of studio range (16..235 luma, 16..240
// chroma).
FullRange bool
}
VideoColor describes how the samples of a DecodedVideoFrame are encoded. The zero value means untagged studio-range video.
DVD-Video has no colour signalling that players honour: they decode every disc as BT.601 in studio range. FitVideoFrameForDVD therefore rewrites the samples of BT.709 pictures with the BT.709 to BT.601 matrix, and compresses full-range pictures (BT.601 or BT.709) to studio range. Primaries and transfer characteristics are left alone. ColorMatrixOther sources are not converted in any way.
type VideoStandard ¶
type VideoStandard uint8
VideoStandard selects the DVD video raster and frame-rate family.
const ( VideoStandardNTSC VideoStandard = iota + 1 VideoStandardPAL )
Source Files
¶
- aac_config.go
- aac_fallback.go
- avc.go
- builtin_encoder.go
- decode.go
- demux.go
- dvd_author.go
- dvd_image.go
- dvd_lpcm.go
- dvd_lpcm_packet.go
- dvd_menu.go
- dvd_menu_font.go
- dvd_menu_text.go
- dvd_nav.go
- dvd_subtitle.go
- dvd_title_mux.go
- frame_rate.go
- frame_times.go
- language_code.go
- menu_font.go
- mp4_edit.go
- mpeg2_encode.go
- mpeg2_probe.go
- mpeg2_vlc.go
- pcm_window.go
- prepare_audio.go
- prepare_video.go
- probe.go
- program_stream.go
- subtitle_read.go
- video2dvd.go
- video_colour.go
- video_fit.go
- webm.go
- webm_tracks.go