video2dvd

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 26 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

video2dvd

Go Reference Go Report Card CI codecov

複数の MP4/WebM から DVD-Video ディレクトリを作成するための Go ライブラリ API です。FFmpeg などの外部コマンドは起動しません。

現在の実装

Converter は入力ファイルの検証、クリップごとの変換処理、DVD オーサリング処理、出力の公開を管理します。中間ファイルは出力先と同じ親ディレクトリに一時作成し、処理がすべて成功した場合だけ VIDEO_TS ディレクトリを出力先へ移動します。

ProbeMedia はファイルから MP4/WebM を判別してトラック・コーデック・解像度・音声情報・再生時間を読み取ります。個別の ProbeMP4 と ProbeWebM も使えます。DemuxMP4 は非 fragmented MP4 の音声・映像サンプルを DTS/PTS とともに順に取り出します。H.264 の AVC 設定を取得でき、AVCToAnnexB と AVCConfigToAnnexB でNAL列とSPS/PPSを Annex B 形式に変換できます。AAC の AudioSpecificConfig も取得します。

DecodeMP4Video は progressive 8-bit 4:2:0 H.264 をYUVフレームに、DecodeMP4Audio は対応する AAC-LC/AC-3 を48 kHz stereo PCMにデコードします。DecodeWebMVideo は VP9 Profile 0/2、VP8、AV1 の映像を、DecodeWebMAudio は Opus 音声をDVD向けフレーム/PCMへデコードします。VP9 Profile 2 の10/12-bit映像は8-bitへ変換します。各デコーダーは純Go実装を使い、FFmpegなどの外部コマンドは起動しません。

組み込み変換器で扱える主な入力は MP4 H.264 + AAC-LC/AC-3 と WebM VP8/VP9 Profile 0/2/AV1 + Opus です。VP9 Profile 1/3、WebM Vorbis、AV1の高ビット深度、HDRのトーンマッピング、AVC以外のMP4映像コーデックは未対応です。VP9 Profile 2のビット深度変換は行いますが、BT.2020/PQ/HLGからDVD向けSDRへの色変換は行いません。

PrepareMP4VideoForDVD と PrepareWebMVideoForDVD は入力映像をDVDラスタへフィットし、NTSC 29.97 fps/PAL 25 fpsへ変換します。入力の表示アスペクト比は明示します。個別処理には FitVideoFrame と DVDFrameRateConverter を使えます。PrepareMP4AudioForDVD と PrepareWebMAudioForDVD は入力音声を48 kHz stereo LPCM音声データへ変換します。DVDLPCMPacketWriter はPCMチャンクをDVD LPCMヘッダー付きPESにまとめ、2048バイトのプログラムストリームセクターへ書きます。

NewInProcessEncoder は外部コマンドを使わず MP4/WebM からMPEG-2映像とLPCM音声を生成します。映像の上限ビットレートを7 Mbit/sに引き上げ、プログラムストリームの宣言レートも更新しています。MediaInput を使うと映像と音声を別ファイルから選び、コンテナ内のトラック番号を指定できます。音声の開始オフセットに応じて無音を挿入し、映像の再生時間に合わせて音声を切り詰めます。MPEG-2エンコーダーは閉じたGOPにI/Pフレームを出力し、Pフレームでは半画素精度の動き予測と量子化DCT残差を使います。各フレームの再構成画像を次の予測参照に使います。現段階では動き探索とレート制御が簡易的で、Bフレームも使わないため、画質と圧縮効率は専用エンコーダーに及びません。

MuxDVDTitleVOB は1タイトル分のMPEG-2映像とLPCM音声をPTS順に多重化し、Iフレームから始まるVOBUごとにPCI/DSI入りのNAVパックを置きます。MPEGProgramStreamWriter と DVDLPCMPacketWriter はその下位部品で、BuildDVDNAVPack はNAVパック単体を構築します。fragmented MP4、暗号化トラック、映像demux側でのedit list適用も現在の対象外です。

NewInProcessAuthorer はDVD規格上の最大99個の入力を入力順に別々のVTS/タイトルとしてオーサリングし、各入力動画を1タイトル・1チャプターとして登録します。自動生成タイトルメニューは動画ファイル名を VIDEO_TS.VOB に表示し、DVDリモコンの方向キーと決定ボタンで各タイトルへ移動できます。タイトル再生終了後はタイトルメニューへ戻り、メニューは再生終了後に先頭へループします。4:3メニューは2列、16:9メニューは1列で、最大36ボタン単位にページを自動生成します。Options.MenuTitle、MenuBackgroundLuma、MenuTextLuma でメニュー見出しと明るさを変更できます。英数字以外は ? として表示されます。字幕は未対応です。VMG/VTSのIFO・BUP、PTT/PGC/セル/VOBUテーブルと各タイトルのVOBも作成します。WriteDVDISO は VIDEO_TS をISO 9660とUDF 1.02の両方から読めるDVD-Videoイメージにまとめます。UDFの実ファイル配置に基づいてIFO内のセクタ参照を確定し、ISOメタデータを含めた容量も確認します。UDFの記述には純Goの go-sdk-winmediafoundry UDF package を使い、外部プロセスは起動しません。ディスクへの書き込みは未実装です。

バックエンドの接続

encoder := video2dvd.NewInProcessEncoder()
authorer := video2dvd.NewInProcessAuthorer()

converter, err := video2dvd.New(encoder, authorer)
if err != nil {
	return err
}

err = converter.Convert(ctx,
	[]string{"part-1.mp4", "part-2.mp4"},
	"./disc",
	video2dvd.Options{
		Standard: video2dvd.VideoStandardNTSC,
		Aspect:   video2dvd.AspectRatio16x9,
	},
)

ISOイメージまで作成する場合は ConvertISO を使います。

err = converter.ConvertISO(ctx,
	[]string{"part-1.mp4", "part-2.mp4"},
	"./disc.iso",
	video2dvd.Options{Standard: video2dvd.VideoStandardNTSC},
)

YouTube ダウンローダーが映像と音声を別ファイルに保存した場合は ConvertSources を使います。トラック番号は ProbeMedia が返す TrackInfo.Index と同じゼロ始まりです。AudioOffset が正なら音声の前に無音を挿入し、負なら音声の先頭を切り詰めます。

err = converter.ConvertSources(ctx,
	[]video2dvd.MediaInput{{
		VideoPath:   "video-only.webm",
		AudioPath:   "audio-only.webm",
		AudioOffset: 250 * time.Millisecond,
	}},
	"./disc",
	video2dvd.Options{Standard: video2dvd.VideoStandardNTSC},
)

同じファイル内の映像・音声トラックを選ぶ場合も MediaInput の VideoTrackIndex と AudioTrackIndex を設定できます。未指定時は、デコーダーが対応する最初のトラックを選びます。

出力先は既存でないパスを指定します。Convert の成功時は disc/VIDEO_TS 以下に DVD-Video ファイルが作成されます。ConvertISO はISOイメージファイルを作ります。すでに作成したディレクトリは WriteDVDISO(ctx, "./disc/VIDEO_TS", "./disc.iso") でイメージ化できます。DiscCapacityBytes を省略するとDVD-5の4.7 GBを上限にし、ISO/UDFの管理領域も含めて判定します。Options.VideoBitrate は映像ビットレート(2〜8.5 Mbps)を指定でき、省略時は8 Mbpsです。エンコーダーの出力は MPEG-2 映像と AC-3、LPCM、または MPEG-1 Layer II 音声で、解像度とフレームレートは選択した DVD 規格に適合する必要があります。

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 a basic in-process Encoder; DVD directory generation still requires an Authorer.

Index

Constants

View Source
const (
	VideoCodecMPEG2       = "mpeg2video"
	AudioCodecAC3         = "ac3"
	AudioCodecLPCM        = "lpcm"
	AudioCodecMPEG1Layer2 = "mp2"
)
View Source
const DVD5CapacityBytes int64 = 4_700_000_000
View Source
const (
	DVDVOBSectorSize = 2048
)

Variables

View Source
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")
)
View Source
var ErrInvalidAVC = errors.New("video2dvd: invalid AVC sample or configuration")
View Source
var ErrInvalidMP4 = errors.New("video2dvd: invalid or unsupported MP4 container")

Functions

func AVCConfigToAnnexB

func AVCConfigToAnnexB(config []byte) ([]byte, error)

AVCConfigToAnnexB writes the SPS and PPS units from avcC in Annex-B form.

func AVCNALLengthSize

func AVCNALLengthSize(config []byte) (int, error)

AVCNALLengthSize returns the size of the NAL unit length field stored in an avcC decoder configuration record.

func AVCParameterSets

func AVCParameterSets(config []byte) ([][]byte, [][]byte, error)

AVCParameterSets returns the SPS and PPS NAL units in an avcC record.

func AVCToAnnexB

func AVCToAnnexB(sample []byte, nalLengthSize int) ([]byte, error)

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 DecodeMP4Audio

func DecodeMP4Audio(ctx context.Context, path string, trackIndex *int, handler func(PCMChunk) error) 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. Audio payloads and edit-list timing are validated by the decoder.

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) 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 a pure-Go VP9 decoder; VP8/AV1 use the bundled pure-Go media pipeline.

func MuxDVDTitleVOB

func MuxDVDTitleVOB(ctx context.Context, title EncodedTitle, workDir string, dst io.Writer) error

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.

func PrepareMP4AudioForDVD

func PrepareMP4AudioForDVD(ctx context.Context, path string, trackIndex *int, dst io.Writer) error

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.

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 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.

func PrepareWebMAudioForDVD

func PrepareWebMAudioForDVD(ctx context.Context, path string, trackIndex *int, dst io.Writer) error

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 and frame rate. High-bit-depth VP9 is reduced to 8-bit for DVD.

func WriteDVDISO

func WriteDVDISO(ctx context.Context, videoTSDir, outputISO string) error

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

func WriteDVDLPCM(dst io.Writer, chunk PCMChunk) error

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.

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 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

func New(encoder Encoder, authorer Authorer) (*Converter, error)

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.

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

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 DVDNAVPackInfo

type DVDNAVPackInfo struct {
	SCRBase                   uint64
	LogicalBlockNumber        uint32
	VOBUEndAddress            uint32
	FirstReferenceEndAddress  uint32
	SecondReferenceEndAddress uint32
	ThirdReferenceEndAddress  uint32
	VOBID                     uint16
	CellID                    uint8
	StartPTM                  uint32
	EndPTM                    uint32
	CellElapsedTime           [4]byte
	Buttons                   []DVDNAVButton
}

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
}

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.

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. The output uses bilinear scaling and even chroma-aligned edges.

For FitLetterbox, unused pixels are set to studio-range black. For FitCrop, the source is center-cropped. The input frame is not modified.

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
}

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.

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.

const (
	// FitLetterbox preserves the entire picture and fills any unused area with
	// black. This is the zero value and avoids cropping source content.
	FitLetterbox FitMode = iota
	// FitCrop fills the DVD raster and crops any excess source image.
	FitCrop
)

type InProcessAuthorer

type InProcessAuthorer struct{}

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.

type InProcessEncoder

type InProcessEncoder struct{}

InProcessEncoder is a built-in Encoder that uses only Go code. Its current MPEG-2 video coder uses I pictures and P-picture macroblock skips with a simple intra quantizer and no motion estimation; use it as an experimental backend rather than a quality transcoder. It converts MP4 AAC-LC/AC-3 and WebM Opus audio to LPCM and creates silent LPCM when the input has no audio track.

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

type MP4Info struct {
	Duration time.Duration
	Tracks   []TrackInfo
}

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 from a non-fragmented MP4 in track order. It does not decode samples or convert H.264 length prefixes to Annex B.

func ProbeMP4

func ProbeMP4(path string) (MP4Info, error)

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

func ProbeMP4Reader(r io.ReaderAt, size int64) (MP4Info, error)

ProbeMP4Reader is the ReaderAt form of ProbeMP4. size is the total length of the file. The reader is not closed or retained.

func ProbeMedia

func ProbeMedia(path string) (MP4Info, error)

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.

func ProbeWebM

func ProbeWebM(path string) (MP4Info, error)

ProbeWebM reads metadata from a WebM file without decoding its streams.

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 and quantized DCT residuals.

The writer does not close dst. Call Close after the final frame to write the MPEG sequence-end code.

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.

func (*MPEG2VideoEncoder) Close

func (e *MPEG2VideoEncoder) Close() error

Close finishes the elementary stream. It does not close the destination.

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.15 MB/s declared program mux rate. PES packets must be submitted in nondecreasing PTS order.

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.

func (*MPEGProgramStreamWriter) WritePES

func (w *MPEGProgramStreamWriter) WritePES(streamID byte, pts time.Duration, payload []byte) error

WritePES writes a PES payload using a video, audio, or private_stream_1 stream id. The first PES fragment carries PTS; continuation fragments do not. Each fragment is placed in its own fixed-size pack sector with padding.

type MediaInput

type MediaInput struct {
	VideoPath       string
	AudioPath       string
	VideoTrackIndex *int
	AudioTrackIndex *int
	AudioOffset     time.Duration
}

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.

type Options

type Options struct {
	Standard           VideoStandard
	Aspect             AspectRatio
	DiscCapacityBytes  int64
	MenuTitle          string
	MenuBackgroundLuma uint8
	MenuTextLuma       uint8
	VideoBitrate       int
}

Options controls conversion and DVD authoring. The zero value selects NTSC, 16:9, and the full-resolution DVD raster for that standard.

type PCMChunk

type PCMChunk struct {
	Start      time.Duration
	SampleRate int
	Channels   int
	Samples    []int16
}

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
	VideoBitrate       int
}

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 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
}

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.

type TrackKind

type TrackKind string

TrackKind identifies the media carried by an MP4 track.

const (
	TrackKindVideo TrackKind = "video"
	TrackKindAudio TrackKind = "audio"
	TrackKindOther TrackKind = "other"
)

type VideoStandard

type VideoStandard uint8

VideoStandard selects the DVD video raster and frame-rate family.

const (
	VideoStandardNTSC VideoStandard = iota + 1
	VideoStandardPAL
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL