video2dvd

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 49 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 CI codecov

A Go library for creating DVD-Video directories and ISO images from multiple MP4 and WebM files. It does not launch external commands such as FFmpeg.

Current implementation

Converter validates input files and coordinates per-clip conversion, DVD authoring, and output publishing. Intermediate files are staged in a temporary directory beside the destination. The VIDEO_TS directory is moved to the destination only after all processing succeeds.

ProbeMedia detects MP4 and WebM files and reads their tracks, codecs, resolutions, audio information, and durations, and the language and name of each track. Subtitle tracks are reported as TrackKindSubtitle; a WebM file with subtitle tracks (or any other track outside the WebM audio and video codecs) is read like the same file without them. You can also use ProbeMP4 and ProbeWebM directly. DemuxMP4 reads audio and video samples from non-fragmented MP4 files in order, including their DTS and PTS values. The library can read H.264 AVC configuration and convert NAL units and SPS/PPS to Annex B using AVCToAnnexB and AVCConfigToAnnexB. It can also read AAC AudioSpecificConfig data.

DecodeMP4Video decodes progressive 8-bit 4:2:0 H.264 into YUV frames. DecodeMP4Audio decodes supported AAC-LC (mono or stereo) and AC-3 audio into 48 kHz stereo PCM on the movie timeline: a leading empty edit becomes silence, and the first media edit's start and length are applied rounded to whole samples, so edit lists written on a millisecond movie timescale are accepted. If the primary MP4 AAC decoder rejects an access unit because of non-zero byte-alignment padding (some encoders leave such bits set), a pure-Go AAC-LC fallback decodes the MP4 access units via ADTS framing instead. The switch also happens when the primary decoder has already delivered PCM: the fallback decodes the track from its start, applies the same edit-list timing and sample-rate conversion, and passes on only the audio after the last frame already delivered, so the PCM handler receives one contiguous stream with nothing repeated or missing. The fallback buffers its decoded PCM in a temporary file, which it removes when it returns. Any other decoding failure is returned as an error, and if the fallback fails too the error reports both decoders' failures. DecodeWebMVideo decodes VP9 Profile 0/2, VP8, and AV1 video; DecodeWebMAudio decodes Opus audio into DVD-ready frames and PCM. VP9 Profile 2 10/12-bit video is converted to 8-bit. VP9 Profiles 0 and 2 use github.com/aethiopicuschan/go-vp9, which maintains VP9 reference state and processes superframes. The decoders are implemented in pure Go and do not launch external commands such as FFmpeg.

The built-in converter supports MP4 with H.264 and AAC-LC/AC-3, and WebM with VP8, VP9 Profile 0/2, or AV1 video and Opus audio. VP9 Profiles 1/3, WebM Vorbis, high-bit-depth AV1, HDR tone mapping, and MP4 video codecs other than AVC are not supported. VP9 Profile 2 bit depth is converted, but BT.2020/PQ/HLG video is not converted to DVD-compatible SDR.

PrepareMP4VideoForDVD and PrepareWebMVideoForDVD fit input video to the DVD raster and convert it to NTSC 29.97 fps or PAL 25 fps. The input display aspect ratio must be provided explicitly. When an MP4 video 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, which keeps video aligned with the audio track's edits. Frames are resampled with a Lanczos-3 filter. Sources whose colour matrix is BT.709 (tagged in the container or bitstream, or untagged and larger than 1024x576) are converted to the BT.601 matrix that DVD players assume, and sources explicitly tagged full range are compressed to studio range; without this step greens and reds of HD sources are visibly off. WebM timestamps rounded to milliseconds are restored to an even cadence before frame-rate conversion, so 30 and 60 fps sources do not stutter. A 1080p or 4K source still looks softer on DVD than the original: 720x480 or 720x576 is the format's resolution, and the fair comparison is the source scaled to that size. These two functions always produce the video frame rate, so a 24 fps source comes out with every fourth frame repeated; the built-in encoder treats such sources as film instead (see Film sources). For lower-level processing, use FitVideoFrame (resampling only), FitVideoFrameForDVD (resampling and colour conversion, using DecodedVideoFrame.Color), DVDFrameRateConverter, and NewDVDFilmFrameRateConverter. PrepareMP4AudioForDVD and PrepareWebMAudioForDVD convert audio to 48 kHz stereo LPCM data. DVDLPCMPacketWriter wraps PCM chunks in DVD LPCM PES packets and writes them into 2048-byte program-stream sectors.

NewInProcessEncoder creates MPEG-2 video and LPCM or AC-3 audio from MP4 or WebM without external commands (see Audio tracks). Requested video bitrates above 7.5 Mbit/s, including the 8 Mbit/s default, are coded and declared at 7.5 Mbit/s so that video, LPCM audio, and pack overhead fit the 10.08 Mbit/s DVD multiplex rate. MediaInput lets you select separate video and audio files and choose tracks within each container. The title is exactly as long as the encoded video. Audio is shifted by inserting silence or trimming its start according to the requested offset, then padded with silence or trimmed to the video length. Decoded audio chunks are placed by their running sample count; container timestamps only reposition audio when they deviate by more than 20 ms, so nanosecond- or millisecond-rounded timestamps never drop or insert samples. When video and audio come from the same WebM file, the title starts at the first video frame and audio moves with it. Inputs whose audio tracks cannot be decoded (for example MP3 in MP4, or multichannel AAC) are rejected before video encoding starts; multichannel AC-3 and Opus are downmixed (see Audio tracks). The MPEG-2 encoder emits I/P frames in closed GOPs of up to 15 pictures (12 or 13 for film) and starts a new GOP at a scene cut. P frames use half-pixel motion prediction over a range of 32 pixels with quantized DCT residuals, code macroblocks without a usable prediction as intra, and use reconstructed frames as references. Rate control follows the VBV model and balances quality within a GOP. The stream is labelled SMPTE 170M (NTSC) or BT.470BG (PAL). The encoder does not use B frames or adaptive quantization, so its compression efficiency is below that of dedicated encoders.

MuxDVDTitleVOB multiplexes one title's MPEG-2 video and LPCM audio against a byte-driven system clock: SCR starts at zero and advances with the 10.08 Mbit/s multiplex rate, the first picture is decoded 0.3 s into the stream, and every access unit is delivered ahead of its DTS/PTS within the DVD decoder buffer sizes. Picture timestamps count display fields, two per picture or three where repeat_first_field is set, so soft-telecined film is timed correctly. A NAV pack with PCI/DSI, including the VOBU search tables and audio sync pointers, starts each VOBU at an I frame. The muxer reads the elementary streams twice (a planning pass, then the writing pass) and returns an error before writing anything if the video cannot be delivered in time. MPEGProgramStreamWriter and DVDLPCMPacketWriter are lower-level components, and BuildDVDNAVPack creates a standalone NAV pack. Fragmented MP4, encrypted tracks, MP4 edits after the first media edit, and MP4 rotation metadata are outside the current scope. DemuxMP4 and DecodeMP4Video report media timestamps without applying edit lists.

NewInProcessAuthorer authors up to 99 inputs as separate VTS/title sets in input order, registering each input as one title and one chapter. The generated title menu in VIDEO_TS.VOB lists each title by its input file name (EncodedTitle.Name); users can navigate to titles with the DVD remote's arrow and enter buttons, and the selected button is highlighted through a subpicture stream. 16:9 menus carry a second, letterboxed highlight for 4:3 displays. Playback returns to the title menu when a title ends, and the menu loops back to its first page after playback. The 4:3 menu uses two columns and the 16:9 menu uses one column. Menus are automatically split into pages of up to 36 buttons. Each page is half a second of video (15 pictures, 0.6 s on PAL) with silent LPCM audio of the same length, stored as a VOB of its own inside VIDEO_TS.VOB; the page is a still cell, so its picture stays on screen until a button is chosen. macOS DVD Player needs both the pictures and the audio: it shows only a black screen for the single-picture menu with 2 ms of audio that earlier versions wrote. Options.MenuTitle, MenuBackgroundLuma, and MenuTextLuma configure the menu heading and brightness; the heading and the title names may contain Japanese (see Menu text), and labels are truncated to the button width. Text subtitle tracks of the inputs can be recorded as DVD subtitles (see Subtitles). The authorer creates VMG/VTS IFO and BUP files, PTT/PGC/cell/VOBU tables, a VTS time map, and each title's VOB, split into VTS_nn_1.VOB through VTS_nn_9.VOB of at most 1 GiB each, so a title may be up to about 9 GiB. Title sets have no menu VOB of their own (VTS_nn_0.VOB is not written). WriteDVDISO packages VIDEO_TS into a DVD-Video image readable through both ISO 9660 and UDF 1.02. It lays each file set out contiguously (IFO, VOBs, BUP), sets the IFO sector references from that layout relative to the owning IFO, and checks capacity including ISO metadata. Converting to an ISO needs temporary space beside the destination for the elementary streams, the VIDEO_TS files, and the image, roughly three times the image size. UDF structures are written using the pure-Go go-sdk-winmediafoundry UDF package; no external processes are launched. Writing to physical discs is not implemented.

Film sources (soft telecine)

On NTSC discs the built-in encoder codes a source that runs at 23.976 (24000/1001) or 24 fps throughout as film, the way commercial film DVDs are made. Only the source frames are coded, 23.976 pictures per second, and each picture carries the top_field_first and repeat_first_field flags that tell the player how to fill the 59.94 fields per second of NTSC: the frames are shown for three and two fields in turn (3:2 pulldown). The stream itself stays a 29.97 fps DVD stream of progressive frame pictures.

  • An interlaced player or TV output shows the standard 3:2 cadence, 50 ms and 33 ms per frame alternately, instead of three frames of 33 ms and one of 67 ms.
  • Progressive-scan DVD players and software players such as VLC decode the 23.976 film frames themselves and pace them for their display.
  • A fifth fewer pictures are coded at the same bitrate, so each one gets about 25% more bits.

Whether a source is film is decided before encoding starts, from the timestamps of the whole video track; they are read from the MP4 sample tables or the WebM blocks without decoding, and millisecond-rounded WebM timestamps are recognised. A track is film when at least nine in ten of its frames follow the one before after one film period and frames never come faster than 24 a second. A frame that stays longer (a held first frame, a gap, a passage at a lower rate) does not change that; it is repeated on the film grid as it would be on the video grid. A track with a passage at a higher rate, such as 24 fps followed by 30 fps, is not film: coded as film it would lose every fifth frame of that passage, so it is converted at the video rate. Sources at 25, 29.97, 30, 50, 59.94, or 60 fps, such variable-frame-rate sources, and all PAL titles are converted exactly as before.

A 23.976 fps source maps frame for frame. A source at exactly 24 fps keeps its real duration, so audio stays in sync without being resampled: one frame in 1001 is left out, the first after 21 seconds and then one every 42 seconds. Each picture is the source frame nearest in time, so video is never more than half a film period (21 ms) early or late against the audio; on an interlaced display 3:2 pulldown itself shows every other frame another 8 ms late.

A film GOP holds 12 pictures, 30 fields, and starts with a top field on a frame of the 29.97 fps display raster. A scene change may start a GOP after 11 pictures (28 fields); the GOPs after it hold 13 (32 fields) until one ends on a scene change after 12, which keeps every GOP on the display raster. The title always ends on a whole display frame, with a bottom field: where the 3:2 cycle would stop after a top field, the last picture is shown for one field more or less. Soft-telecined titles have been checked with ffmpeg, VLC (libdvdnav and libdvdread), and lsdvd, not on a hardware player.

Set Options.DisableSoftTelecine (or Profile.DisableSoftTelecine when calling an encoder directly) to convert film sources like any other, with every fourth frame shown twice.

EncodedTitle.FrameRateNumerator/Denominator remain the display rate of the standard (30000/1001) for film titles. The multiplexer reads the flags of every picture and derives timestamps, VOBU times, and navigation data from the display fields, so MPEG-2 streams soft-telecined by another encoder work as well. A title declared as 24000/1001, or a stream whose sequence header says so, is rejected: that is not a DVD-Video frame rate. (Earlier versions accepted the declaration from an external encoder, but only together with such a stream, and timed it as 23.976 progressive pictures per second, which no DVD player is required to play.) The multiplexer does not alter a stream from another encoder, which may end on a single field. NewMPEG2SoftTelecineEncoder and NewDVDFilmFrameRateConverter expose the film path for custom pipelines; MPEG2VideoEncoder.DisplayFields gives the stream length once the encoder is closed.

Menu text

Without any configuration the title menu draws ASCII with a built-in 5x7 font and Japanese with an embedded bitmap font, the 16-dot gothic face of the public-domain Shinonome font family. The embedded font covers JIS X 0208 (hiragana, katakana, level 1 and 2 kanji, full-width letters, digits and symbols, Japanese punctuation) and half-width katakana; its table is 114 KB, and together with the font reader for MenuFont it adds about 0.4 MB to a program. It is drawn bold so that its strokes match the ASCII font and stay visible on a television. ASCII letters are shown in upper case; other characters are shown as written. File names that macOS reports in decomposed form (か followed by a combining voiced sound mark instead of が) are composed first. A character that no font has is shown as ?.

Labels and the heading are laid out by pixel width: an ASCII character takes 12 pixels, a full-width character 16, and a half-width katakana 8. A label that is wider than its button is cut after the last character that fits, without an ellipsis. A 16:9 menu shows about 35 full-width characters of a title name, and a two-column 4:3 menu about 15.

To draw the menu with another typeface, or in another language, pass a TrueType or OpenType font. Text is then anti-aliased, keeps its upper and lower case, and is scaled horizontally by the inverse of the pixel aspect ratio (10:11 and 40:33 for NTSC 4:3 and 16:9, 12:11 and 16:11 for PAL), so glyphs have their natural proportions on the television instead of being stretched. Characters missing from the font fall back to the built-in fonts one by one, so a Latin-only font still shows Japanese names.

data, err := os.ReadFile("/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc")
if err != nil {
	return err
}
menuFont, err := video2dvd.ParseMenuFont(data) // TTF, OTF, or the first font of a TTC/OTC
if err != nil {
	return err
}
err = converter.Convert(ctx, []string{"夏休みの思い出.mp4"}, "./disc", video2dvd.Options{
	MenuTitle: "家族ビデオ 2024年",
	MenuFont:  menuFont,
})

ParseMenuFontIndex selects another font of a collection. Rendering uses integer arithmetic only, so a menu picture is identical on every platform. Limits: the font size is fixed (a 16-line em) and the bitmap fonts are not scaled to the pixel aspect ratio, so they look about 21% wider on a 16:9 NTSC display and 9% narrower on a 4:3 one; text is drawn left to right, one glyph per character, without kerning, ligatures, shaping, or vertical forms, which rules out scripts such as Arabic or Devanagari; combining marks other than the kana sound marks are not composed; characters outside JIS X 0208 (emoji, rare kanji, Hangul, accented Latin letters) need a MenuFont that has them, except that ゔ, ヷ, ヸ, ヹ, and ヺ are spelled as the base kana followed by ゛; marks above capital letters, as in É, can lose their top lines to the button rectangle; hinting, bitmap or colour glyphs, and variable-font axes of a MenuFont are not used; and ParseMenuFont returns an error for fonts its reader (golang.org/x/image/font/sfnt) does not accept, which includes some system fonts.

Audio tracks

A title can have up to eight audio streams, which the viewer switches between with the player's audio button; players label each with its language. Set Options.IncludeAllAudio to record every audio track of an input that the built-in decoders read (tracks they cannot decode, such as multichannel AAC, are skipped; an input with AudioTrackIndex keeps its one track), or list the tracks of one input in MediaInput.AudioTracks (tracks of AudioPath, or of VideoPath when it is empty; it cannot be combined with AudioTrackIndex). The first stream is the one players start with: with IncludeAllAudio that is the track the file marks as default (see Default tracks), followed by the others in track order. Each stream is labelled with its track's language, mapped as DVDLanguageCode describes. Every stream is placed on the title timeline exactly as the single audio track always was (edit lists, AudioOffset, the first video frame of a WebM file) and padded with silence or cut to the length of the video, each on its own. Track lists with more than eight tracks, unknown or unsupported tracks, or repeated tracks are refused before anything is encoded.

err = converter.ConvertSources(ctx,
	[]video2dvd.MediaInput{{VideoPath: "dubbed.webm", AudioTracks: []int{2, 1}}}, // track 2 plays first
	"./disc",
	video2dvd.Options{},
)

Options.AudioFormat decides how the audio is coded. With the default, AudioFormatAuto, a title with one audio stream keeps LPCM, as before, and its output is unchanged byte for byte; a title with several gets AC-3 for all of them, because a second 1.536 Mbit/s LPCM stream does not fit the 10.08 Mbit/s multiplex beside the video, and LPCM and AC-3 are the only audio formats every NTSC player must play. AudioFormatAC3 also codes a single stream as AC-3. AC-3 is written by a pure-Go encoder at 48 kHz stereo; Options.AC3Bitrate selects 192 (the default), 224, 256, 320, 384 or 448 kbit/s. AudioFormatLPCM keeps several streams LPCM and lowers the video bitrate instead: video and audio together get 9.036 Mbit/s, the share of 7.5 Mbit/s video and one LPCM stream, so two LPCM streams leave the video 5.964 Mbit/s, three 4.428 and four 2.892; from five on the video would get less than 2 Mbit/s, and the conversion is refused before anything is encoded. AC-3 streams are accounted the same way, so many streams at a high AC-3 bitrate lower the video bitrate as well (eight at 448 kbit/s leave 5.452 Mbit/s).

The multiplexer puts LPCM streams on substreams 0xA0 and up and AC-3 streams on 0x80 and up, writes the audio sync pointers of every stream into the NAV packs, and keeps each AC-3 stream within a 4 KiB decoder buffer. The IFOs state each stream's coding, channel count and language, and the title PGC enables all of them. An Encoder of your own can return several streams in EncodedTitle.Audio (LPCM or AC-3 files with their languages); AudioPath and AudioCodec then describe the first one.

EstimateDVDBytes estimates the size of the ISO image for titles of given lengths and audio stream counts with given options, before anything is encoded, so that an application can tell whether its inputs fit a disc. It counts every stream at its full rate, which the video encoder never exceeds but undershoots on simple pictures, so it is an upper estimate: detailed video comes close to it, while a still or mostly black picture takes a fraction.

The AC-3 encoder is written in Go for this library (ATSC A/52: 512-sample MDCT with the KBD window, long blocks, rematrixing, adaptive exponent strategies, the standard parametric bit allocation with a per-frame SNR offset search, no coupling, 19.8 kHz bandwidth up to 256 kbit/s and 20.9 kHz above). Every stream starts with 256 samples of silence, which keeps the start of the audio free of the aliasing a decoder cannot cancel in the first block; the multiplexer presents AC-3 that much earlier, which also suits AC-3 from encoders such as ffmpeg's, which have the same delay. Its quality was measured by decoding its output with both ffmpeg and the pure-Go AC-3 decoder of go-264 and comparing it with the input sample by sample, from the first sample (the decoders agree within 0.3 dB; both CRCs of every frame verify, and ffmpeg reports no errors even with -err_detect crccheck+bitstream+buffer):

Signal 192 kbit/s 448 kbit/s
1 kHz sine at -6 dBFS 82.8 dB 86.2 dB
ten tones from 100 Hz to 15 kHz 39.6 dB 62.8 dB
music-like (band-limited noise and notes) 21.6 dB 27.3 dB

On the music-like signal ffmpeg's own AC-3 encoder reaches 22.1 and 27.1 dB; a perceptual coder places its noise under the masking threshold instead of minimizing it, so broadband signals score lower than tones. Discs with two AC-3 streams made from MP4 (AAC) and WebM (Opus) sources were checked with ffprobe, lsdvd, libdvdnav, VLC and macOS DVD Player; on a test signal of a flash and a beep every second, each stream kept the source's offset between picture and sound within 0.2 ms over 20 seconds. The encoder runs at about 240 times realtime. It writes long blocks only, so sharp transients can pre-echo slightly.

Audio with more than two channels is downmixed to stereo. Opus in WebM with 3 to 8 channels (channel mapping family 1, Vorbis order) is decoded with gopus's multistream decoder and mixed with the ITU-R BS.775 coefficients: Lo = L + 0.7071·C + 0.7071·Ls + 0.7071·Lb + 0.5·Cb and Ro = R + 0.7071·C + 0.7071·Rs + 0.7071·Rb + 0.5·Cb, with the LFE channel discarded; both outputs are then divided by their coefficient sum (1/(1 + 0.7071 + 0.7071) for 5.1, 1/3.1213 for 7.1), so the mix cannot clip. AC-3 in MP4 of any channel mode is downmixed by the go-264 decoder with the centre and surround mix levels coded in the stream, LFE discarded and normalized the same way; at the usual -3 dB levels this is the BS.775 downmix for the layouts with two surround channels, while a single surround channel (2/1, 3/1) is added to both outputs at the full surround level. Mono and stereo sources are unchanged. Multichannel AAC is still refused before encoding: the pure-Go AAC decoders this library uses (go-264 and aac-go) decode mono and stereo only, and the one pure-Go multichannel AAC decoder found is GPL-licensed. Opus ambisonics (mapping families 2 and 3) is refused as well.

Default tracks

TrackInfo.Default reports the container's mark of a default track: the enabled flag of an MP4 track header (ffprobe shows it as the default disposition) or a WebM track's FlagDefault. Matroska makes a track without a FlagDefault element a default track, so TrackInfo.Default is true for such tracks. The converter only follows such an implied mark when another track of the same kind has FlagDefault 0, which is how ffmpeg writes it; in files from tools that write no FlagDefault at all, which would have every track marked, the implied marks are ignored.

Unless MediaInput.AudioTrackIndex or AudioTracks says otherwise, the converter records the first supported audio track that carries a default mark, and the first supported audio track when none does. With IncludeSubtitles, the subtitle track that carries a default mark becomes subtitle stream 1 and the others follow in track order. These are changes from v1.1.0, which always took the first supported audio track and kept subtitle tracks in track order; files without marks, or whose first tracks are the marked ones, convert as before.

Subtitles

Set Options.IncludeSubtitles to record the text subtitle tracks of the inputs as DVD subtitles (subpicture streams), which the viewer turns on and off and switches between with the player's subtitle button. The converter reads MP4 timed text (tx3g, which ffmpeg calls mov_text) and WebM WebVTT (D_WEBVTT/SUBTITLES, as well as S_TEXT/WEBVTT) and SubRip (S_TEXT/UTF8) tracks. Every such track of an input's video file becomes a stream of its title, the one marked as default first (see Default tracks) and the others in track order, up to the 32 streams a title can have; other subtitle tracks, such as bitmap subtitles, are skipped. MediaInput.SubtitleTracks chooses the tracks of one input and their order instead (an empty list records none). ReadSubtitleCues returns the cues of a track, DVDLanguageCode the language code that is recorded for it.

err = converter.ConvertSources(ctx,
	[]video2dvd.MediaInput{{VideoPath: "talk.webm", SubtitleTracks: []int{3, 2}}}, // track 3 becomes stream 1
	"./disc",
	video2dvd.Options{IncludeSubtitles: true, ShowSubtitles: true},
)

A title with subtitles starts with its first stream selected and hidden; with Options.ShowSubtitles it is shown. Options.ShowDefaultSubtitles shows it instead when the track it comes from carries a default mark (see Default tracks) and hides it otherwise, and MediaInput.ShowSubtitles decides for one input. The first that is set wins, in this order: MediaInput.ShowSubtitles, Options.ShowDefaultSubtitles, Options.ShowSubtitles. Each stream is labelled with the language of its track (the BCP 47 tag, or else the ISO 639-2 code, mapped to the two-letter code DVD-Video stores), so players list it as Japanese or English; an undetermined language is recorded as unspecified. Cues keep their place relative to the first video frame of their file, as the audio of the same file does. Markup is removed: WebVTT tags and ruby text, SubRip <i>/<b>/<font> tags and {\an8}-style overrides, and the style boxes of timed text; WebVTT character references are resolved. While cues overlap, their texts are shown together, one below the other, the same text once. A subtitle longer than about 12 minutes is shown by several subpicture units, and cues are cut to the title.

Subtitles are drawn with the menu fonts at twice their size (32 lines for a line of Japanese), or with Options.MenuFont at twice its menu size, in white with a two-pixel black outline on a transparent background, centred at the bottom of the title-safe area. Lines are broken to fit 80% of the frame width: at spaces, and between the characters of Japanese, Chinese or Korean text except before closing punctuation and small kana, preferring a break after punctuation; the lines of a cue are made about equally long. Text that needs more than four lines is drawn at the menu size, and lines beyond eight are left out. The limits of the menu text apply: without a MenuFont, ASCII letters are shown in upper case, and characters outside the fonts are shown as ?. The same picture serves 4:3 and 16:9 displays, so on a 4:3 display a letterboxed 16:9 title shows its subtitles at the bottom of the frame and narrower than on a widescreen one.

Subtitles go through the rest of the pipeline as stream files that WriteDVDSubtitleStream writes from cues (EncodedTitle.Subtitles), so a custom Encoder can supply them as well. They count towards the disc capacity checks. Subtitled discs made from MP4 and WebM inputs have been checked with ffmpeg, lsdvd, libdvdnav, VLC, and macOS DVD Player (showing, switching, and turning off subtitles), not on a hardware player.

Connecting the backends

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

Use ConvertISO to create an ISO image as well:

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

Use ConvertSources when a downloader saves video and audio to separate files. Track indexes are zero-based, matching TrackInfo.Index returned by ProbeMedia. A positive AudioOffset inserts silence before the audio; a negative value trims the beginning of the audio.

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

To select video and audio tracks from the same file, set VideoTrackIndex and AudioTrackIndex on MediaInput. If omitted, the decoder selects the first supported track.

The output path must not already exist. On success, Convert creates DVD-Video files under disc/VIDEO_TS; ConvertISO creates an ISO image. You can create an image from an existing directory with WriteDVDISO(ctx, "./disc/VIDEO_TS", "./disc.iso"). If DiscCapacityBytes is omitted, the DVD-5 capacity of 4.7 GB is used, including ISO/UDF metadata. Options.VolumeID sets the ISO volume name (up to 32 ASCII letters, digits, underscores, and spaces, stored in upper case; default VIDEO2DVD). Options.VideoBitrate accepts 2 to 8.5 Mbps and defaults to 8 Mbps; the built-in encoder codes anything above 7.5 Mbps at 7.5 Mbps. The encoder outputs MPEG-2 video and AC-3, LPCM, or MPEG-1 Layer II audio; the resolution and frame rate must match the selected DVD standard.

Third-party license notices for dependencies used by the built-in decoder and for the menu fonts are in third_party_licenses.

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

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

View Source
const (
	VideoCodecMPEG2       = "mpeg2video"
	AudioCodecAC3         = "ac3"
	AudioCodecLPCM        = "lpcm"
	AudioCodecMPEG1Layer2 = "mp2"
)
View Source
const DVD5CapacityBytes int64 = 4_700_000_000
View Source
const DVDNAVAudioSyncNone uint16 = 0x3fff

DVDNAVAudioSyncNone is the A_SYNCA value of an audio stream that has no pack for the VOBU.

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

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

View Source
const (
	DVDVOBSectorSize = 2048
)
View Source
const DefaultAC3Bitrate = 192_000

DefaultAC3Bitrate is the AC-3 bitrate used when Options.AC3Bitrate is zero, in bit/s.

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 DVDLanguageCode added in v1.1.0

func DVDLanguageCode(language string) string

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.

AAC must be mono or stereo. AC-3 with more channels is downmixed by the go-264 decoder with the stream's own centre and surround mix levels (cmixlev, surmixlev), LFE discarded, scaled down by the larger output's coefficient sum so that it cannot clip. At the -3 dB levels this is the ITU-R BS.775 downmix for the modes with two surround channels (2/2, 3/2); a single surround channel (2/1, 3/1) is added to both outputs at the full surround level rather than split between them at -3 dB.

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. Tracks with three to eight channels in channel mapping family 1 (Vorbis order) are downmixed to stereo with the ITU-R BS.775 coefficients: centre and surrounds at 0.7071, LFE discarded, normalised so the mix cannot clip.

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 EstimateDVDBytes added in v1.2.0

func EstimateDVDBytes(titles []TitleEstimate, options Options) (int64, error)

EstimateDVDBytes estimates the size in bytes of the ISO image that ConvertSourcesISO writes for titles with options, before anything is encoded, so that an application can tell whether its inputs fit a disc. It assumes the rates the built-in encoder codes at: the video at its bitrate (Options.VideoBitrate, at most 7.5 Mbit/s, lowered for several audio streams as Options.AudioFormat describes), every audio stream at 1.536 Mbit/s for LPCM or Options.AC3Bitrate for AC-3, about 3% for the multiplex, and a few megabytes for menus and the file system. The video encoder never exceeds its bitrate but spends less on simple pictures, so this is an upper estimate: close for detailed video, far above the result for a still or mostly black picture. Subtitles, which take little room, are not included. It returns an error for invalid options or durations and for audio streams that leave the video too little room.

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.

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

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.

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

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

func SupportedSubtitleCodec(codec string) bool

SupportedSubtitleCodec reports whether the converter reads subtitle tracks of a codec, as reported by TrackInfo.Codec.

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.

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 AudioFormat added in v1.2.0

type AudioFormat uint8

AudioFormat selects how the built-in encoder codes the audio streams of a title.

const (
	// AudioFormatAuto codes a title with one audio stream as LPCM and a
	// title with several as AC-3: two LPCM streams beside full-rate video
	// exceed the DVD multiplex rate.
	AudioFormatAuto AudioFormat = iota
	// AudioFormatLPCM codes every stream as 16-bit 48 kHz stereo LPCM. With
	// several streams the video bitrate is lowered so that video and audio
	// fit the multiplex rate; see Options.AudioFormat.
	AudioFormatLPCM
	// AudioFormatAC3 codes every stream as 48 kHz stereo AC-3 at
	// Options.AC3Bitrate.
	AudioFormatAC3
)

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

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.

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

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 EncodedAudio added in v1.2.0

type EncodedAudio struct {
	// Path is the stream: big-endian 16-bit 48 kHz stereo samples for
	// LPCM, as WriteDVDLPCM writes them, or AC-3 syncframes at 48 kHz.
	// Relative paths are resolved from the work directory.
	Path string
	// Codec is AudioCodecLPCM or AudioCodecAC3.
	Codec string
	// Language is the ISO 639-1 code of the stream, such as "ja", which
	// players show when switching audio (see DVDLanguageCode); empty marks
	// it as unspecified.
	Language string
}

EncodedAudio is one audio stream of an EncodedTitle.

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
	// ShowSubtitles, if not nil, decides for this title whether its first
	// subtitle stream is shown when it starts, instead of
	// Profile.ShowSubtitles. The Converter sets it from
	// MediaInput.ShowSubtitles and Options.ShowDefaultSubtitles unless the
	// encoder did.
	ShowSubtitles *bool
	// Audio lists the audio streams of the title, at most 8, in DVD stream
	// order; the first is the one players start with. When it is empty the
	// title has the one stream of AudioPath and AudioCodec. When it is set,
	// AudioPath and AudioCodec are those of its first stream (the Converter
	// fills them in when they are empty). The built-in authorer multiplexes
	// LPCM and AC-3 streams.
	Audio []EncodedAudio
}

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.

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

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

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

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
	SubtitleTracks  []int
	ShowSubtitles   *bool
	AudioTracks     []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. ShowSubtitles, if not nil, decides whether the title's first subtitle stream is shown when it starts, over Options.ShowDefaultSubtitles and Options.ShowSubtitles.

AudioTracks lists the audio tracks to record as the title's audio streams, in stream order: the first is audio stream 1, which players start with. They are tracks of AudioPath, or of VideoPath when AudioPath is empty, at most 8, each of a codec the built-in decoders read; all are placed on the timeline like a single audio track, including AudioOffset. It cannot be combined with AudioTrackIndex. Nil leaves the choice to Options.IncludeAllAudio and otherwise records one track: AudioTrackIndex, or the first supported track that carries a default mark (TrackInfo.Default), or the first supported track.

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

func ParseMenuFont(data []byte) (*MenuFont, error)

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.

func ParseMenuFontIndex added in v0.7.0

func ParseMenuFontIndex(data []byte, index int) (menuFont *MenuFont, err error)

ParseMenuFontIndex is like ParseMenuFont but selects the font with the given zero-based index of a font collection. A single font is a collection of one.

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, up to the 32
	// streams of a title: the one that carries a default mark (see
	// TrackInfo.Default) first and the others in track order; 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, and
	// ShowDefaultSubtitles and MediaInput.ShowSubtitles take precedence.
	ShowSubtitles bool
	// ShowDefaultSubtitles starts a title with its first subtitle stream
	// shown when the track it comes from carries the container's default
	// mark (TrackInfo.Default; for WebM a track without a FlagDefault element
	// counts only when another subtitle track has FlagDefault 0, as ffmpeg
	// writes it), and hidden otherwise, instead of following
	// ShowSubtitles. MediaInput.ShowSubtitles takes precedence over it.
	ShowDefaultSubtitles bool
	// IncludeAllAudio records every audio track of an input that the
	// built-in decoders read, up to the 8 audio streams of a title, for
	// each input whose MediaInput.AudioTracks and AudioTrackIndex are nil;
	// tracks they cannot decode, such as multichannel AAC, are skipped. The track that
	// carries a default mark (or else the first) becomes audio stream 1,
	// which players start with; the others follow in track order. Each
	// stream is labelled with its track's language (see DVDLanguageCode).
	IncludeAllAudio bool
	// AudioFormat selects LPCM or AC-3 for the audio; the zero value,
	// AudioFormatAuto, keeps a single stream LPCM and codes several as AC-3.
	// With AudioFormatLPCM and several streams the video bitrate is lowered
	// to make room: LPCM takes 1.536 Mbit/s per stream, and video and audio
	// together may take 9.036 Mbit/s, the share of a 7.5 Mbit/s video and
	// one LPCM stream. A title whose video would get less than 2 Mbit/s that
	// way, which is the case from five LPCM streams on, is refused before
	// anything is encoded. AC-3 streams take their bitrate from that share
	// as well, so eight streams at 448 kbit/s leave 5.45 Mbit/s to video.
	AudioFormat AudioFormat
	// AC3Bitrate is the bitrate of every AC-3 stream in bit/s: 192000,
	// 224000, 256000, 320000, 384000 or 448000. Zero selects
	// DefaultAC3Bitrate.
	AC3Bitrate 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
	// 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
	// AudioFormat and AC3Bitrate are Options.AudioFormat and
	// Options.AC3Bitrate; zero values select the defaults.
	AudioFormat AudioFormat
	AC3Bitrate  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 SubtitleCue added in v1.1.0

type SubtitleCue struct {
	Start time.Duration
	End   time.Duration
	Text  string
}

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 TitleEstimate added in v1.2.0

type TitleEstimate struct {
	// Duration is the length of the title's video.
	Duration time.Duration
	// AudioStreams is the number of audio streams; zero counts as one, the
	// stream of silence a title without audio gets.
	AudioStreams int
}

TitleEstimate describes a title for EstimateDVDBytes.

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
	Default               bool
	// 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.

Default is the container's mark of a track to be played by default: the track_enabled flag of an MP4 track header, or a WebM track's FlagDefault. Matroska makes a track without a FlagDefault element a default track, so a WebM file that writes no such element reports every track as Default. The converter only follows such an implied mark when another track of the same kind has FlagDefault 0, as ffmpeg writes it (see hasDefaultMark).

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
)

Jump to

Keyboard shortcuts

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