mp4

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DataTypeReserved = 0  // Reserved, should not be used
	DataTypeUTF8     = 1  // UTF-8 text (most common)
	DataTypeUTF16BE  = 2  // UTF-16 big-endian text
	DataTypeJPEG     = 13 // JPEG image data
	DataTypePNG      = 14 // PNG image data
	DataTypeGenre    = 18 // Genre (special text format - the problematic type)
	DataTypeInteger  = 21 // Signed big-endian integer (1, 2, 3, 4, or 8 bytes)
	DataTypeBMP      = 27 // BMP image data
)

MP4 data types used in iTunes metadata atoms.

Variables

View Source
var (
	// Standard iTunes metadata atoms.
	AtomTitle     = [4]byte{0xA9, 'n', 'a', 'm'} // ©nam - Title
	AtomArtist    = [4]byte{0xA9, 'A', 'R', 'T'} // ©ART - Artist (author)
	AtomAlbum     = [4]byte{0xA9, 'a', 'l', 'b'} // ©alb - Album
	AtomComposer  = [4]byte{0xA9, 'c', 'm', 'p'} // ©cmp - Composer (narrator for audiobooks)
	AtomNarrator  = [4]byte{0xA9, 'n', 'r', 't'} // ©nrt - Narrator (dedicated audiobook narrator atom)
	AtomGenre     = [4]byte{0xA9, 'g', 'e', 'n'} // ©gen - Genre (custom text)
	AtomWriter    = [4]byte{0xA9, 'w', 'r', 't'} // ©wrt - Writer
	AtomComment   = [4]byte{0xA9, 'c', 'm', 't'} // ©cmt - Comment
	AtomYear      = [4]byte{0xA9, 'd', 'a', 'y'} // ©day - Year/Date
	AtomGrouping  = [4]byte{0xA9, 'g', 'r', 'p'} // ©grp - Grouping
	AtomCopyright = [4]byte{0xA9, 'c', 'p', 'y'} // ©cpy - Copyright
	AtomEncoder   = [4]byte{0xA9, 't', 'o', 'o'} // ©too - Encoder/Encoding tool
	AtomPublisher = [4]byte{0xA9, 'p', 'u', 'b'} // ©pub - Publisher

	// Non-copyright atoms (standard ASCII).
	AtomReleaseDate = [4]byte{'r', 'l', 'd', 't'} // rldt - Release date (Audible)
	AtomCover       = [4]byte{'c', 'o', 'v', 'r'} // covr - Cover artwork
	AtomGenreID     = [4]byte{'g', 'n', 'r', 'e'} // gnre - Genre ID (ID3v1 index)
	AtomMediaType   = [4]byte{'s', 't', 'i', 'k'} // stik - Media type (2 = audiobook)
	AtomDescription = [4]byte{'d', 'e', 's', 'c'} // desc - Description
	AtomFreeform    = [4]byte{'-', '-', '-', '-'} // ---- - Freeform/custom atom
)

iTunes atom type names (4-byte codes). Note: © symbol is encoded as 0xA9 in MacRoman.

View Source
var (
	BoxTypeMoov = gomp4.BoxTypeMoov()        // moov - Movie box
	BoxTypeUdta = gomp4.BoxTypeUdta()        // udta - User data box
	BoxTypeMeta = gomp4.BoxTypeMeta()        // meta - Metadata box
	BoxTypeIlst = gomp4.BoxTypeIlst()        // ilst - Item list box
	BoxTypeData = gomp4.BoxTypeData()        // data - Data box
	BoxTypeMvhd = gomp4.BoxTypeMvhd()        // mvhd - Movie header
	BoxTypeTrak = gomp4.BoxTypeTrak()        // trak - Track box
	BoxTypeHdlr = gomp4.BoxTypeHdlr()        // hdlr - Handler box
	BoxTypeMdia = gomp4.BoxTypeMdia()        // mdia - Media box
	BoxTypeMinf = gomp4.BoxTypeMinf()        // minf - Media information box
	BoxTypeStbl = gomp4.BoxTypeStbl()        // stbl - Sample table box
	BoxTypeStsd = gomp4.BoxTypeStsd()        // stsd - Sample description box
	BoxTypeMp4a = gomp4.BoxTypeMp4a()        // mp4a - MPEG-4 audio
	BoxTypeEsds = gomp4.BoxTypeEsds()        // esds - Elementary stream descriptor
	BoxTypeEc3  = gomp4.StrToBoxType("ec-3") // ec-3 - E-AC-3 (Dolby Digital Plus)
	BoxTypeDec3 = gomp4.StrToBoxType("dec3") // dec3 - E-AC-3 specific box
	BoxTypeAc3  = gomp4.StrToBoxType("ac-3") // ac-3 - AC-3 (Dolby Digital)
	BoxTypeDac3 = gomp4.StrToBoxType("dac3") // dac3 - AC-3 specific box
	BoxTypeAlac = gomp4.StrToBoxType("alac") // alac - Apple Lossless
	BoxTypeChpl = gomp4.StrToBoxType("chpl") // chpl - Chapter list (Nero)
	BoxTypeTref = gomp4.StrToBoxType("tref") // tref - Track reference
	BoxTypeChap = gomp4.StrToBoxType("chap") // chap - Chapter reference
)

Box types for navigation.

View Source
var (
	// ErrNotMP4 is returned when the file is not a valid MP4/M4B file.
	ErrNotMP4 = errors.New("not a valid MP4/M4B file")

	// ErrNoMetadata is returned when the file has no metadata.
	ErrNoMetadata = errors.New("no metadata found")

	// ErrInvalidBox is returned when a box structure is invalid.
	ErrInvalidBox = errors.New("invalid box structure")
)

Errors returned by the mp4 package.

Functions

func Parse

func Parse(path string) (*mediafile.ParsedMetadata, error)

Parse reads metadata from an M4B/MP4 file and returns it in the mediafile.ParsedMetadata format for compatibility with the existing scanner.

func Write

func Write(path string, metadata *Metadata, opts WriteOptions) error

Write updates the metadata in an M4B/MP4 file. This modifies the file in place. Use CreateBackup option to create a backup first.

func WriteToFile

func WriteToFile(srcPath, destPath string, metadata *Metadata) error

WriteToFile writes modified metadata to a new file using a bounded-memory, atomic rewrite. Unchanged top-level boxes are copied incrementally.

func WriteToFileContext added in v0.0.50

func WriteToFileContext(ctx context.Context, srcPath, destPath string, metadata *Metadata) error

WriteToFileContext is WriteToFile with cancellation support. Cancellation interrupts incremental copying and removes the temporary destination. The destination is created requesting 0644, like other generated files.

Types

type Chapter

type Chapter struct {
	Title string
	Start time.Duration
	End   time.Duration
}

Chapter represents a chapter in the audiobook.

type Metadata

type Metadata struct {
	Title           string
	Subtitle        string                       // from ----:com.apple.iTunes:SUBTITLE or ----:com.pilabor.tone:SUBTITLE
	Authors         []mediafile.ParsedAuthor     // from ©ART (artist)
	Narrators       []string                     // from ©nrt (narrator) or ©cmp (composer)
	Album           string                       // from ©alb
	Series          string                       // parsed from com.apple.iTunes:SERIES freeform or ©grp
	SeriesNumber    *float64                     // range start parsed from com.apple.iTunes:SERIES-PART freeform or ©grp
	SeriesNumberEnd *float64                     // optional range end parsed from com.apple.iTunes:SERIES-PART freeform or ©grp
	Genre           string                       // from ©gen or gnre (original, may be comma-separated)
	Genres          []string                     // parsed from ©gen (comma-separated)
	Tags            []string                     // from ----:com.shisho:tags freeform atom
	Description     string                       // from desc
	Publisher       string                       // from ©pub
	URL             string                       // from com.shisho:url freeform
	ReleaseDate     *time.Time                   // parsed from rldt or ©day
	Comment         string                       // from ©cmt
	Year            string                       // from ©day
	Copyright       string                       // from ©cpy
	Encoder         string                       // from ©too
	CoverData       []byte                       // cover artwork
	CoverMimeType   string                       // "image/jpeg" or "image/png"
	Duration        time.Duration                // from mvhd
	Bitrate         int                          // bps from esds
	Codec           string                       // audio codec with profile (e.g., "AAC-LC", "xHE-AAC")
	Chapters        []Chapter                    // chapter list (Phase 3)
	MediaType       int                          // from stik (2 = audiobook)
	Freeform        map[string]string            // freeform (----) atoms like com.apple.iTunes:ASIN
	Identifiers     []mediafile.ParsedIdentifier // parsed identifiers from freeform atoms
	Language        *string                      // from com.pilabor.tone:LANGUAGE or com.apple.iTunes:LANGUAGE freeform atom
	Abridged        *bool                        // from com.pilabor.tone:ABRIDGED freeform atom
	UnknownAtoms    []RawAtom                    // preserved unrecognized atoms from source
}

Metadata represents extracted M4B audiobook metadata.

func ParseFull

func ParseFull(path string) (*Metadata, error)

ParseFull reads complete metadata from an M4B/MP4 file including duration, chapters, and other extended information.

func ParseFullContext added in v0.0.50

func ParseFullContext(ctx context.Context, path string) (*Metadata, error)

ParseFullContext is ParseFull with cancellation support.

func ParseFullReaderContext added in v0.2.0

func ParseFullReaderContext(ctx context.Context, r io.ReaderAt, size int64) (*Metadata, error)

ParseFullReaderContext is ParseFullContext for the first size bytes of r. It reads the boxes it needs and skips over the audio.

type RawAtom

type RawAtom struct {
	Type [4]byte // 4-byte atom type code
	Data []byte  // complete atom data including header
}

RawAtom represents an MP4 atom preserved in its raw form.

type Rewrite added in v0.2.0

type Rewrite struct {
	// contains filtered or unexported fields
}

Rewrite is an M4B rewrite planned from the source's box layout and moov, ready to be written front to back. Its size is known before the first byte, so a download can send it as Content-Length.

func PrepareRewrite added in v0.2.0

func PrepareRewrite(ctx context.Context, src io.ReaderAt, sourceSize int64, metadata *Metadata) (*Rewrite, error)

PrepareRewrite plans writing src with metadata. It reads only the box headers and moov, rebuilding moov with the metadata, cover, and chapter track, and computing every offset the output needs, so all of the work that can fail on a malformed file happens before any byte is written.

Only moov and the chapter samples are held in memory; WriteTo copies every unchanged box, above all the audio mdat, through a fixed buffer. Peak memory must scale with the modified structures, never the audiobook size; writer_streaming_test.go enforces a bound.

func (*Rewrite) Size added in v0.2.0

func (r *Rewrite) Size() int64

Size returns the exact number of bytes WriteTo writes.

func (*Rewrite) WriteTo added in v0.2.0

func (r *Rewrite) WriteTo(ctx context.Context, dest io.Writer) error

WriteTo writes the rewritten file to dest front to back, copying every unchanged box from the source.

type WriteOptions

type WriteOptions struct {
	// CreateBackup creates a .bak file before modifying
	CreateBackup bool
}

WriteOptions configures the write operation.

Jump to

Keyboard shortcuts

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