metadata

package
v1.10.9 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: Apache-2.0 Imports: 23 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

metadata

Format-agnostic metadata extraction registry. Handlers register themselves against a content-type regular expression and one or more namespaces (see AddHandler), and GetMetadata runs the handlers that match a given content type, optionally narrowed to specific namespaces via WithNamespace.

This document covers seven namespaces specifically: dc (Dublin Core), exif (and its tiff sibling), image, video, audio, tmdb - metadata looked up from The Movie Database for video files - and markdown, a document's content.

dc (Dublin Core) namespace

dc: entries come from five different kinds of source, so the set of keys isn't fixed:

  1. Container tags, mapped onto a small, fixed set of dc: keys by the video/audio/RAW handlers.
  2. A TMDB match (video files only), mirroring the title/overview/release-date of the movie found by the tmdb namespace handler - see tmdb namespace below.
  3. The most specific available EXIF capture date/time (JPEG, RAW, and HEIF/AVIF - see exif namespace below), mirrored as dc:date.
  4. A video file's creation-time container tag (see video/audio namespaces below), reformatted as RFC 3339 and mirrored as dc:date.
  5. Embedded XMP, where any Dublin Core element present in the file's XMP document is surfaced verbatim as dc:<element> - not limited to the fixed set below.
Key Value Source
dc:title Title Video title tag, audio title/tracktitle tag, or a TMDB match's title
dc:creator Artist/director Video director tag, audio artist/artists/album-artist tag, or a RAW file's own artist field
dc:description Description Video description tag (or synopsis if there's no description tag), a RAW file's own description field, or a TMDB match's overview
dc:date Release date, YYYY-MM-DD, or full RFC 3339 timestamp A TMDB match's release date, a JPEG/RAW/HEIF file's exif:DateTimeOriginal (preferred), exif:DateTimeDigitized, or tiff:DateTime, or a video file's creation-time tag

exif namespace (and its tiff sibling)

Unlike dc, image, and tmdb, exif:/tiff: keys aren't a fixed, enumerable set - they mirror whatever standard EXIF tag names a file's own EXIF data actually contains. The prefix follows the tag's IFD (Image File Directory), per (*exif.Tag).Key() in pkg/exif/tag.go: tiff:<Name> for IFD0/IFD1 tags, exif:<Name> for Exif/GPS/Interop IFD tags.

JPEG (metadata/image/exif.go), a RAW file's embedded thumbnail (metadata/image/raw.go), and HEIF/AVIF (metadata/image/heif.go) all feed their EXIF tags through the same shared exifTagsToMetadata helper, so a few tags are enriched identically across all three: date/time tags are merged with their UTC-offset tag and reformatted, and single-rational tags (GPS coordinates, FNumber, ExposureTime, FocalLength, ...) get a parsed numeric value via Any() alongside the unchanged human-readable string via Value().

All three also mirror the most specific available capture date/time as dc:date (mirrorDCDate in metadata/image/exif.go) - see dc namespace above.

Common keys

Real values from etc/test/PXL_20250102_172041079.MP.jpg (a JPEG, enriched):

Key Value()
tiff:Make Google
tiff:Model Pixel 8
tiff:Software HDR+ 1.0.702121622zd
tiff:DateTime 2025-01-02T18:20:41+01:00
exif:DateTimeOriginal 2025-01-02T18:20:41+01:00
exif:ISOSpeedRatings 410
exif:FNumber f/1.7
exif:ExposureTime 1/80 sec.
exif:FocalLength 6.9 mm
GPS keys

Value() for a GPS coordinate is always the raw degrees/minutes/seconds string - only Any() is parsed, uniformly as a signed float64 regardless of source (JPEG, RAW, or HEIF/AVIF). Real values from etc/test/photo.HEIC:

Key Value() Any()
exif:GPSLatitude 51, 32, 9.71 51.536030555555556 (float64, signed - negative south)
exif:GPSLongitude 0, 8, 39.53 -0.14431388888888888 (float64, signed - negative west)
exif:GPSAltitude 35.6820 35.68202589489718 (float64, negative if GPSAltitudeRef says below sea level)

So: to compute with a coordinate, use Any().(float64) - safe across all three producers. exif:GPSLatitudeRef/GPSLongitudeRef/GPSAltitudeRef (N/S, E/W, sea level or below) are consumed and dropped from the output once merged into the corresponding signed value.

RAW files also start from libraw's own curated tiff:/exif: fields (Make, Model, Software, ISOSpeedRatings, ExposureTime, FNumber, FocalLength, DateTimeOriginal - see pkg/raw/meta.go), overridden by the embedded thumbnail's enriched EXIF wherever the two overlap.

image namespace

image: entries describe the decoded image itself (dimensions and format). Exactly one of two producers runs per file, since they're matched by disjoint content-type patterns - the generic image handler's ^image/.*$ vs. the RAW handler's own raw.ContentTypes - so there's no ambiguity about which meaning of image:format applies to a given file.

Generic image handler (metadata/image/image.go)

Any image/* content type Go's stdlib image package can decode (plus the registered HEIF/AVIF, BMP, TIFF, and WebP decoders).

Key Value
image:format Decoder-reported format name: jpeg, png, gif, bmp, tiff, webp, heif, or avif
image:width Pixel width
image:height Pixel height
RAW camera handler (metadata/image/raw.go)
Key Value
image:format The camera manufacturer name, lowercased (e.g. olympus, canon) - not a file-format identifier like cr2/orf, since libraw doesn't expose one
image:width Processed pixel width, after crop/rotation
image:height Processed pixel height, after crop/rotation

video and audio namespaces

Like exif/tiff, video:/audio: keys aren't a fully fixed set: metadata/video/handler.go and metadata/audio/handler.go map a handful of container tag names onto canonical dc:/video: (or dc:/audio:) keys, drop a list of noisy/uninteresting tags, and pass everything else through as video:<tag>/audio:<tag> - so an unrecognized container tag still shows up, just without a canonical mapping. Sanitizing a tag name lowercases it and collapses any run of non-alphanumeric characters (including _) into a single -.

Both handlers are registered under "dc" as well as their own namespace, since dc:title/ dc:creator are two of the canonical mappings.

video: (metadata/video/handler.go)

Real values from etc/test/sample.mp4:

Key Value Source
video:duration 5.312 (seconds) Always present
dc:title Sample From Big Buck Bunny title tag
dc:creator - director tag
dc:description - description tag, or synopsis if there's no description tag (see below)
video:year - date/year tag
video:encoder Lavf53.24.2 Any other tag, sanitized and passed through
video:creation-time 1970-01-01T00:00:00.000000Z Any other tag, sanitized and passed through
dc:date 1970-01-01T00:00:00Z Mirrors quicktime:creationdate (see below), or else video:creation-time, reformatted as RFC 3339, when it parses as a timestamp

synopsis is never surfaced as its own video:synopsis key: it only becomes dc:description, and only when there's no dedicated description tag to prefer instead (buildVideoEntries in metadata/video/handler.go).

Dropped entirely (noisy/uninteresting): compatible-brands, major-brand, minor-version, comment, itunes-cddb-1, itunmovi, gapless-playback, itunextc. A tag which ffmpeg repeats with its language, such as model-eng for model, is dropped when its value is the same.

quicktime: (metadata/video/handler.go)

Apple's QuickTime tags, com.apple.quicktime.<name>, written by iPhones, iPads and Macs, are in their own namespace as quicktime:<name>, sanitized as other tags are. The video handler is registered under "quicktime" too. Real values from an iPhone's video:

Key Value
quicktime:make Apple
quicktime:model iPhone 12 mini
quicktime:software 16.1.1
quicktime:creationdate 2023-03-16T07:23:27+0100
quicktime:location-iso6709 +52.4158+013.5896+035.667/
quicktime:location-accuracy-horizontal 9.424789 (metres)
quicktime:latitude 52.4158, a float64, parsed from the ISO 6709 location
quicktime:longitude 13.5896, a float64
quicktime:altitude 35.667 (metres), a float64, when the location has one

quicktime:creationdate is when the video was recorded, in its own time zone, so it's mirrored as dc:date, as RFC 3339, rather than creation-time, which is in UTC and can be when the file was written.

audio: (metadata/audio/handler.go)

Real values from etc/test/sample.mp3 (an untagged file, hence just Duration) and sample_with_artwork.mp3:

Key Value Source
audio:duration 20.734717 (seconds) Always present
dc:title - title/tracktitle tag
dc:creator - artist/artists/album-artist tag
audio:album - album/albumtitle tag
audio:genre - genre/music-genre tag
audio:year - originalyear/year/date/originaldate/tdor tag
audio:track - track/tracknumber/itunes-cddb-tracknumber tag
audio:encoder Lavf62.12.102 Any other tag, sanitized and passed through

Dropped entirely (mostly ID3/iTunes-specific noise): comment, itunnorm, itunsmpb, itunextc, gapless-playback, tagging-time, accurateripdiscid, accurateripresult, id3v1-comment, id3v2-priv-averagelevel, id3v2-priv-google-originalclientid, id3v2-priv-www-amazon-com, itunes-cddb-1, itunes-cddb-ids, account-id, compatible-brands, major-brand, minor-version, eitunnorm.

musicbrainz: (metadata/audio/handler.go)

MusicBrainz's tags, as MusicBrainz Picard writes them, are in their own namespace, named for MusicBrainz's entities, so an identifier can be looked up with MusicBrainz's API. Each is spelled differently in each container, such as MUSICBRAINZ_ALBUMID in a FLAC file and MusicBrainz Album Id in an MP3 or MP4 file, and all spellings have the same key. The audio handler is registered under "musicbrainz" too. Real values from a FLAC file:

Key Value Tag
musicbrainz:release-id e1262988-757c-4861-9778-65e7d4ef5c55 Album Id
musicbrainz:release-group-id c7d1950a-5bda-4d8f-a939-7db8bca44647 Release Group Id
musicbrainz:recording-id 53bb54ac-1020-4cd4-83ce-362a58e1ec17 Track Id, or in an MP3, its ID3 tag's UFID frame owned by http://musicbrainz.org, which ffmpeg doesn't return as a tag
musicbrainz:track-id 2797c3c5-021c-329b-8885-4f10ed37260a Release Track Id
musicbrainz:artist-id 9fadfba9-ecae-4383-a4d8-47b043cea19a Artist Id
musicbrainz:album-artist-id 885f90ef-6bd9-409a-b2df-e165e553c68e Album Artist Id
musicbrainz:release-type album;compilation Album Type, or RELEASETYPE in FLAC
musicbrainz:release-status official Album Status, or RELEASESTATUS in FLAC
musicbrainz:release-country US Album Release Country, or RELEASECOUNTRY in FLAC

musicbrainz:work-id, disc-id, original-release-id and original-artist-id are mapped too, and another tag with MusicBrainz's prefix keeps its name, such as musicbrainz:<name>.

tmdb namespace

Unlike dc and the other content-derived namespaces (exif, tiff, image, artwork, ...), tmdb entries come from a network lookup: the input's filename is parsed into a search query (see tmdb.ExtractQuery in tmdb/httpclient/query.go) and used to search TMDB for a matching movie. The handler is a no-op unless both of the following are true:

  • A TMDB client was configured via metadata.WithTMDB(token) - without one, no lookup is attempted and no tmdb: entries are returned.
  • The input reader implements gomedia.NamedReader (i.e. it has a filename) and that filename parses to a non-empty title, or the movie or episode is given by its identifier (see below).

A filename with an S01E01-style marker is an episode of a TV show, whose show is searched for, and otherwise it's a movie.

When the caller already knows the match, such as from an earlier lookup, it can give it by its identifier: metadata.WithTMDBMovie(id) for a movie, or metadata.WithTMDBEpisode(show, season, episode) for an episode. The handler then gets it directly, without searching or matching, which is fewer requests and always the same match, whatever the filename. A movie or episode which TMDB doesn't have returns no metadata.

Key Value Always present?
tmdb:id The matched movie's TMDB ID (numeric string) Yes, when a match is found
tmdb:title The matched movie's official TMDB title Yes, when a match is found
tmdb:releasedate Release date, YYYY-MM-DD Only if TMDB returned one
tmdb:overview Synopsis/overview text Only if TMDB returned one

The same handler also mirrors tmdb:title, tmdb:overview, and tmdb:releasedate as dc:title, dc:description, and dc:date respectively (see dc namespace above), so it's registered under both the tmdb and dc namespaces.

If the search returns no results (or none of the above conditions are met), the handler returns no metadata and no error - a missing TMDB match isn't treated as a failure.

TMDB's search endpoint returns results ranked by relevance; the handler takes the top match without further disambiguation (e.g. by release year proximity).

markdown namespace

A document's content as Markdown, which a handler returns only when the namespace is requested with WithNamespace, as converting a document can be expensive. In go-media, metadata/subtitle returns SubRip (.srt) subtitles as a paragraph for each cue, which starts with its number, and its start and end times, such as **1 · 00:01:02 → 00:01:04** Hello there., without the cues' styling or repeated cues. A cue without a number has the previous cue's and one. Applications can register handlers for their own formats.

Key Value Present
markdown:body The Markdown, or the part of it in the range, as a string Always
markdown:offset The byte the part starts at, as a uint64 When the range has an offset
markdown:next The offset of the next part, as a uint64 When there's more

WithRange(offset, limit) sets the part to return, so a long document is read a part at a time, from each markdown:next. A handler writes the Markdown to a MarkdownWriter, which keeps the part, in whole characters, and returns an error from a write once it has it, so the handler stops rather than converting the rest. The handler returns w.Metadata(err):

w := metadata.NewMarkdownWriter(o)
for _, paragraph := range paragraphs {
    if _, err = w.WriteString(paragraph); err != nil {
        break
    }
}
return w.Metadata(err)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddHandler

func AddHandler(re *regexp.Regexp, name string, fn HandlerFunc, namespaces ...string)

Add a metadata handler for a given regular expression, along with a short name identifying it (e.g. "ffmpeg", "tmdb", "artwork" - used to name its span, "metadata.Handler.<name>", so it's distinguishable from other handlers in a trace) and the namespaces (e.g. "exif", "tiff") of metadata it can produce. A caller that requests specific namespaces via WithNamespace will only run handlers registered for one of those namespaces.

func AddTextExtensionType added in v1.10.7

func AddTextExtensionType(ext, contentType string) error

AddTextExtensionType registers the type of text with the extension, such as text/x-typescript for .ts, which refines content sniffed as plain text, as mime.AddExtensionType's does, but is never the type of content by its extension alone, so content which isn't text, such as an MPEG transport stream, has the type it otherwise has. The extension starts with a dot, and is matched without case.

func ContentType

func ContentType(r io.Reader) (string, map[string]string, error)

Type returns the MIME type of the given file, along with a map of any additional metadata that was extracted from the file. If the MIME type cannot be determined, an error is returned.

func ExtensionByType

func ExtensionByType(contentType string) string

ExtensionByType returns the preferred extension for contentType, falling back to the first registered extension if no preferred extension matches, or else the first extension of the type of text (see AddTextExtensionType).

func FilterMetadata

func FilterMetadata(entries map[string]gomedia.Metadata, o *Opts) []gomedia.Metadata

FilterMetadata returns the entries whose namespace was requested via o (see WithNamespace), or every entry if no namespace was requested. Keys are of the form "namespace:name" and matched case-insensitively. This is a helper for handlers that build up a map of "namespace:name"-keyed metadata and need to apply the namespace filter passed to their HandlerFunc.

func GetMetadata

func GetMetadata(parent context.Context, r io.Reader, contentType string, opts ...Option) (_ []gomedia.Metadata, err error)

GetMetadata runs every handler registered for contentType against r, concurrently, and returns the combined metadata from all of them. Metadata from handlers that succeed is always returned, even if other handlers for the same content type fail; a non-nil error is the joined errors from any failing handlers, and should be treated as a warning rather than a reason to discard the metadata that was returned alongside it. ctx is passed to every handler and checked before any work starts, but GetMetadata otherwise waits for all handlers to finish rather than returning early on cancellation.

Types

type HandlerFunc

type HandlerFunc func(context.Context, io.Reader, *Opts) ([]gomedia.Metadata, error)

HandlerFunc is a function that can be used to extract metadata from a given reader. The context can be used to cancel or time out long-running extraction. Opts carries the options passed to GetMetadata; in particular Opts.HasNamespace can be used to check whether a specific namespace (e.g. "artwork") was requested via WithNamespace, which handlers that do expensive work for a single namespace should use to opt in only when that namespace was explicitly requested. A handler that produces several namespaces can use FilterMetadata to return only the ones requested.

func GetHandlers

func GetHandlers(contentType string) []HandlerFunc

GetHandlers returns all handlers registered for a given content type, or nil if no handler is registered for that content type.

type MarkdownWriter added in v1.10.9

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

MarkdownWriter is written the content of a document as Markdown, by a handler of the "markdown" namespace, and keeps the part of it in the range set via WithRange. Once it has the part, a write returns an error, so the handler can stop, rather than converting the rest of the document. A handler returns the part with Metadata, which also takes the handler's error.

func NewMarkdownWriter added in v1.10.9

func NewMarkdownWriter(o *Opts) *MarkdownWriter

NewMarkdownWriter returns a writer which keeps the part of the Markdown in the range set via WithRange, or all of it

func (*MarkdownWriter) Metadata added in v1.10.9

func (w *MarkdownWriter) Metadata(err error) ([]gomedia.Metadata, error)

Metadata returns the part of the Markdown, and the handler's error, which is nil when it stopped as the writer had the part. The part is markdown:body; markdown:offset is the byte it starts at, when the range has an offset, which is moved forward to the start of a character; and markdown:next is the offset of the next part, when there's more. Returns an error when the offset is beyond the end of the Markdown.

func (*MarkdownWriter) Write added in v1.10.9

func (w *MarkdownWriter) Write(data []byte) (int, error)

Write keeps the part of the data in the range. It returns an error once it has the part, and there's more of the Markdown, so the handler can stop.

func (*MarkdownWriter) WriteString added in v1.10.9

func (w *MarkdownWriter) WriteString(s string) (int, error)

WriteString keeps the part of the string in the range, as Write does

type NamedStream

type NamedStream interface {
	// Name returns the name (path) of the stream, which can be used to
	// determine the MIME type.
	Name() string
}

type Option added in v1.9.3

type Option func(*Opts) error

func WithDuration added in v1.10.5

func WithDuration(d time.Duration) Option

WithDuration sets the duration of the stream, when the caller knows it, such as from the stream's own metadata. The TMDB handler then only matches a movie whose runtime is within 10% of it.

func WithNamespace added in v1.9.3

func WithNamespace(ns ...string) Option

Return only the metadata from the given namespaces.

func WithRange added in v1.10.9

func WithRange(offset, limit uint64) Option

WithRange sets the part of a document's Markdown which a handler of the markdown namespace returns: from the byte offset, and at most limit bytes, so a long document is read a part at a time. A limit of zero is all of it from the offset, and otherwise holds a whole character. See MarkdownWriter.

func WithTMDB added in v1.9.3

func WithTMDB(token string, clientopts ...client.ClientOpt) Option

Use The Movie Database (TMDB) client to fetch metadata from TMDB.

func WithTMDBEpisode added in v1.10.9

func WithTMDBEpisode(show, season, episode uint64) Option

WithTMDBEpisode sets the TMDB identifier of the stream's show, and its season and episode, when the caller knows them, such as from an earlier match. The TMDB handler then gets the episode by them, rather than searching for the show and matching the results. Season zero is a show's specials. It replaces a movie set via WithTMDBMovie.

func WithTMDBMovie added in v1.10.9

func WithTMDBMovie(id uint64) Option

WithTMDBMovie sets the TMDB identifier of the stream's movie, when the caller knows it, such as from an earlier match. The TMDB handler then gets the movie by it, rather than searching for the stream's name and matching the results, which is fewer requests, and is sure to be the same movie. It replaces an episode set via WithTMDBEpisode.

func WithTracer added in v1.9.3

func WithTracer(tracer trace.Tracer) Option

Set the otel tracer to use for metadata operations.

func WithYear added in v1.10.6

func WithYear(year int) Option

WithYear sets the year of the stream, such as its release year, when the caller knows it, such as from the stream's own metadata. The TMDB handler then matches a movie whose title is the stream's, and whose release year is the year, whatever its runtime. A year in the stream's name is used rather than it. Zero is no year.

type Opts added in v1.9.3

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

func (*Opts) Duration added in v1.10.5

func (o *Opts) Duration() time.Duration

Duration returns the duration of the stream set via WithDuration, or zero when it isn't known

func (*Opts) HasNamespace added in v1.9.3

func (o *Opts) HasNamespace(ns string) bool

HasNamespace reports whether ns was requested via WithNamespace, case-insensitively. Handlers that do expensive work for a single namespace (e.g. artwork extraction) use this to opt in only when that namespace was explicitly requested, rather than whenever no namespace filter was given at all.

func (*Opts) IsText added in v1.10.4

func (o *Opts) IsText() bool

IsText reports whether the stream is a text document with a type which isn't a text type, such as a playlist with an audio type. Media handlers, such as ffmpeg's, don't read it, as it isn't media.

func (*Opts) TMDB added in v1.9.3

func (o *Opts) TMDB() *tmdb.Client

TMDB returns the TMDB client set via WithTMDB, or nil if none was set. Handlers that need to query TMDB use this to opt out (return nil, nil) when no client is configured, rather than erroring.

func (*Opts) TMDBEpisode added in v1.10.9

func (o *Opts) TMDBEpisode() (show, season, episode uint64)

TMDBEpisode returns the TMDB identifier of the stream's show, and its season and episode, set via WithTMDBEpisode, or zeros

func (*Opts) TMDBMovie added in v1.10.9

func (o *Opts) TMDBMovie() uint64

TMDBMovie returns the TMDB identifier of the stream's movie set via WithTMDBMovie, or zero

func (*Opts) Year added in v1.10.6

func (o *Opts) Year() int

Year returns the year of the stream set via WithYear, or zero when it isn't known

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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