h265

package module
v0.24.2 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: BSD-3-Clause Imports: 9 Imported by: 1 module, 1 package

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

h265

ci Go Reference

Part of go-avkit: documentation.

Pure-Go (CGO=0) reader for the H.265/HEVC bitstream: the NAL layer, the parameter sets, the slice segment header, and the boundaries between coded pictures.

units, err := h265.SplitAnnexB(data)
sps, err := h265.ParseSPS(spsUnit)
pps, err := h265.ParsePPS(ppsUnit)
pics, err := h265.SplitPictures(units, pps)   // without decoding any

What it is not

It is a decoder of our own, and it is slow (see Speed below). Decoder takes NAL units in decoding order and returns the pictures in output order:

d := h265.NewDecoder(h265.Options{VerifyHash: true})
for _, u := range units {
	pics, err := d.Decode(u) // err does not stop the decoder; the pictures are valid
}
pics, err := d.Flush()

Every hashed picture of the conformance suite that it decodes (intra and inter, 7178 of them) matches its decoded picture hash SEI, including the 7 streams that use cabac_bypass_alignment_enabled_flag (the alignment of 9.3.4.3.6). Limits (Limits) bound the picture size and the memory of the picture buffer; a fuzz target covers the whole decoder. Speed is below. CI pins these counts. The 9 MV-HEVC conformance streams (675 units of layers 1 to 5) decode their base layer to the md5 the suite ships, the other layers' units being skipped. The streams that carry no hash SEI are held to the md5 of their decoded output (output order, cropped, as a yuv file) that the suite ships: 45 of the 52 such streams it decodes match; the other 7 ship no md5 file, so nothing verifies them. What it has:

  • the CABAC engine and the full slice-data syntax (7.3.8): all 52271 slices of the conformance suite (v1 and RExt) walk to their last bit;
  • QP, scaling lists, dequantisation and inverse transforms (8.6);
  • intra prediction and picture construction (8.4, 8.6.7), with deblocking (8.7.2) and SAO (8.7.3);
  • motion vector derivation (merge, AMVP, temporal prediction, 8.5.3.2), fractional sample interpolation and weighted prediction (8.5.3.3), and the inter residual (8.5.4);
  • the decoded picture buffer: RPS marking, unavailable pictures, output and bumping (C.5.2), conformance-window cropping; all 10238 pictures of the suite run through it;
  • SEI parsing and the decoded picture hash (MD5, CRC, checksum).

decode v0.10.0 decodes HEVC with this decoder (h265 v0.21.0). Since v0.21.0 a caller can set Unit.Tag (a uint64); the picture whose first slice segment came from a tagged unit carries it in Output.Tag, whatever the output order, which carries a container timestamp through reordering, skipped RASL pictures and refused pictures.

New: picture reuse (Options.RecyclePictures, (*DecodedPicture).Release)

Additive, off by default: a caller that does not set the option sees no change, and every output picture keeps the lifetime stated at Output. Every picture is otherwise a fresh allocation that the operating system faults in (about 1400 page faults a frame at 1080p). With RecyclePictures a caller that is done with an output picture calls Release(); its planes go back to a pool once the decoder no longer needs the picture as a reference (a Release while it is still in the buffer defers the reuse), and the next picture is decoded into them. A picture that is not released is never reused, a second Release does nothing, a released picture is empty (At reads 0), and Release without the option, or on a Clone, does nothing at all. The caller must not read a plane slice it took before Release. The motion fields of pictures are reused too, whatever the caller releases. The output is unchanged: the md5 of all 196 conformance streams equals the plain decode's with the option on. h265.Decoder alone, Zen 4 (taskset -c 5, 15 interleaved rounds, an A/A control: the two option-off arms differ by 0.0 to 0.4 %), option off against on:

stream off, fps on, fps page faults per frame, off to on
alien-main 104.2 113.9 (+9 %) 1380 to 316
fade-main 93.3 101.2 (+8 %) 1540 to 422
alien-main10 89.2 100.3 (+12 %) 1882 to 357
alien8 121.3 124.9 (+3 %) 883 to 256
Speed

Behaviour change in v0.22.0: an 8-bit picture is decoded natively into bytes, and Plane.Pix is renamed Pix16, with no alias. An 8-bit picture carries Pix8 []uint8 instead; exactly one of Pix8 and Pix16 is non-nil, and Plane.Is8, Plane.At and Plane.Len read either. A caller that reads Pix must read Pix16, or Pix8 for an 8-bit stream. The output is unchanged: the md5 of the four streams equals v0.21.0's and ffmpeg's. h265.Decoder alone against v0.21.0, frames per second (Zen 4, pinned core; Apple M4 indicative, load 5 to 9):

stream v0.21.0, Zen 4 v0.22.0, Zen 4 v0.21.0, M4 v0.22.0, M4
alien-main 91.1 107.6 (+18 %) 98.4 99.0
fade-main (explicit weights) 82.2 95.3 (+16 %) 105.7 112.8
alien8 103.9 125.7 (+21 %) 112.1 120.8
alien-main10 91.8 91.3 (same) 91.3 93.3

The v0.20.0 table below, against the third-party decoder, predates this change.

Behaviour change in v0.19.0: the planes of a picture returned by Decoder.Output are read-only views of the decoder's own pictures, not copies, and Stride can be larger than Width. A picture you keep stays valid and unchanged, but writing into its planes corrupts the decoding of later pictures that reference it. A caller that modifies samples must call (*DecodedPicture).Clone() first, which returns an owned, writable copy.

v0.20.0 runs the SAO edge offset on the kernel over the whole CTB, tightens plain-Go loops and uses widening kernels from go-videodsp/kernels v0.17.0, with the output unchanged bit for bit (every conformance gate is the same; the md5 of four 1080p outputs equals ffmpeg's). Frames per second by CPU time, one core (AMD Ryzen 9 7950X, taskset -c 5, ABBA of five rounds each, load 0.44 to 1.21, 2026-11-16). "Third-party" is gen2brain/h265, the decoder decode v0.9.0 used for HEVC, measured through DecodeTrack; ffmpeg is 6.1.1 with -threads 1.

stream (1080p) v0.19.0 v0.20.0 third-party ffmpeg v0.20.0 / third-party v0.20.0 / ffmpeg
alien, Main 75.9 91.2 87.2 392.6 1.05 0.23
fade, Main 68.7 82.6 79.9 428.2 1.03 0.19
alien, Main 10 79.1 92.0 30.0 303.2 3.07 0.30
alien8 85.6 104.0 95.2 431.0 1.09 0.24

On this x86 host the decoder alone is faster than the third-party decoder on all four streams (1.03 to 1.09 times on 8-bit, 3.07 on Main 10) and still 0.19 to 0.30 of ffmpeg's speed, an open defect. Through decode the 8-bit streams are slower on x86 (see the decode README, go-avkit/decode#101). Not measured: arm64 against the third-party decoder. No parity is claimed.

Security fix in v0.24.1: found by an independent security review of go-images/heif. (1) A sequence or picture parameter set that arrived between the slice segments of one picture, under the ids the picture was begun with, was read by the segments after it while the picture's buffers had the old geometry: Decode could panic with an index out of range. The decoder now decodes every segment of a picture against the sets the picture began with (7.4.2.4.2); the new sets apply from the next picture. (2) A slice segment that started at or before the end of the one before it decoded the same coding tree blocks again, so a few kilobytes of segments at address 0 cost seconds of CPU and gigabytes of allocation; such a segment is now refused with ErrSliceData and the picture is reported ErrCorruptPicture (slice segments come in increasing address order, 7.4.7.1). Upgrade if you call the decoder on untrusted input.

Security fix in v0.16.0: on a hostile SPS (a picture width or height that is not a multiple of the minimum coding block size) v0.14.0 and v0.15.0 could panic in intra reconstruction, found by FuzzDecoder; ParseSPS now refuses such a size, as 7.4.3.2.1 requires. Upgrade if you call them on untrusted input.

Behaviour change in v0.14.0: Unit.TemporalID is now TemporalId (0 for the base layer, as 7.4.2.2 defines it); every version up to v0.13.2 returned TemporalId + 2. A unit stating nuh_temporal_id_plus1 = 0 is refused with ErrTemporalIDPlus1. POCCounter used the wrong value too, so its picture order counts were wrong after the first picture on real streams.

The design of the decoder: docs/design/hevc.md (profile of the decoder it would replace, stages, kernels, conformance, target).

What is in it

SplitAnnexB, SplitLengthPrefixed, Unit, UnitType the NAL layer, both framings
ParseSPS, ParsePPS the parameter sets
ParseSliceSegmentHeader, SliceSegmentHeader, SliceType the slice segment header
SplitPictures, Picture coded pictures, from first_slice_segment_in_pic_flag
NewDecoder, Decoder, Options, Limits, Output the decoder: units in, cropped pictures out in output order (read-only views of the decoder's pictures, each its own allocation that stays valid and unchanged for as long as it is kept; see Output; Picture.Clone gives a writable copy; a Unit.Tag comes back as the Output.Tag of the picture whose first slice segment carried it; Output.Corrupt flags a picture that could not be decoded to its end), with bounds on picture size and buffer memory, an optional reuse of released pictures (Options.RecyclePictures, Picture.Release) and an optional check of each picture against its hash SEI
POCCounter, POC picture order counts, clause 8.3.1
ShortTermRPS, RefPic, LongTermRefPic the reference picture sets a sequence carries
ReferencesOf, PictureRefs, LongTermRef what one coded picture says it still needs
Derive, RefPicSet, LtPicture the pictures a decoder must keep for it, clause 8.3.2
Lists, RefListEntry the two lists a slice predicts from, clause 8.3.4, in the order the slice asked for
PredWeights, RefWeight how a slice weighs each picture, 7.3.6.3
ShortHeaderError a unit that ended inside the syntax, said as such

⛔ HEVC's slice types are not H.264's. Here B is 0, P is 1 and I is 2 — the reverse of H.264, where P is 0 and B is 1. A reader that shares a constant between the two formats reads every B slice as a P slice and every P slice as a B one, and the stream still parses.

The order a viewer sees

A stream sends only the LOW bits of each picture's order count, so the count has to be carried across pictures rather than read from one. POCCounter does that.

⛔ The picture the high bits come from is not simply the previous one. It is the previous picture of sub-layer zero that is neither a leading picture nor a sub-layer non-reference — which is exactly the set a thinned stream may have dropped. A counter that carried from every picture would make the order of what remains depend on what was thrown away.

An IDR states no count at all and is zero by definition; a BLA restarts the high bits, because a broken link is a splice.

The derivation is held against a second implementation: FFmpeg's ff_hevc_compute_poc2, transcribed into the test, over 263 168 carry-and-low -bit pairs at two widths. The one place the two part company is a negative carry — FFmpeg reconstructs the previous low bits as a remainder, which is negative there, and 84 of 1024 negative cases disagree. 8.3.1 keeps the low and high parts apart and the low part is what the slice header stated, so that is what this keeps.

The pictures a picture may still need

A sequence parameter set carries the short-term reference picture sets its slices may name. SPS.ShortTermRefPicSets holds them in order, each as the pictures already seen (Before) and those still to come (After), nearest first.

⛔ A set may be written as a DIFFERENCE from an earlier one, and the difference cannot even have its bits counted without the set it is a difference from — so the sets are read in order and every one is kept. The smallest difference the syntax can state is one: abs_delta_rps_minus1 has no way to say "the same set", so a predicted set always moves every entry, and an entry that crosses zero changes which half it belongs to.

⛔ Everything between the order-count width and the sets is conditional and of variable length — sub-layer buffering, block and transform geometry, the scaling lists, the PCM fields. A reader that walked any of them wrongly would read the sets from the wrong bits, and nothing in a set would show it. Each shape has a test that reads a known set back out of it.

The scaling lists are skipped with the reader the picture parameter set already had: a second copy of that walk would be a second thing to drift.

ReferencesOf reads what one picture states. A slice usually names one of the sequence's sets rather than restating it — which is why a sequence carries them — and may instead state one of its own, itself possibly a difference from one of the sequence's.

⛔ The index into those sets is as wide as the number of them needs, and one set means no index at all. A reader that always read bits would take the next field as the index and misread everything after it.

Long-term pictures come from two places at once and are counted as one run: some named out of the sequence's list, some stated by the slice. Each is named by the LOW bits of its order count, and states the high bits only when the low ones would be ambiguous.

An IDR says nothing, and that is not an error: it begins a coded video sequence, so nothing before it is available and nothing after it may reach back.

Derive turns that into the five lists 8.3.2 names, given the picture's own order count. The short-term entries are relative and become absolute here.

⛔ Curr and Foll are not the same thing. A picture in Curr may be predicted from by this picture. One in Foll may not — it is listed because a LATER picture will want it, and a decoder that dropped it would break that one instead. Both must be kept; only one may be used.

⛔ A long-term picture's count is exact only when the slice stated its high bits; otherwise it is the low bits, and the picture meant is whichever held matches them. LtPicture.Exact says which, because handing a decoder low bits as though they were a count is a wrong answer that looks like a right one.

The high bits are stated as a number of wraps that accumulates across the entries — each counted from the one before, not from zero — and the count starts afresh for the slice's own entries after the sequence's. Two entries each stating one wrap are 256 and 512 back, not 256 twice.

The two lists a slice predicts from

Lists builds RefPicList0 and RefPicList1 out of a derived set, clause 8.3.4. They hold the SAME pictures; the order is what distinguishes them.

refs, err := h265.ReferencesOf(first, sps, pps)
set := h265.Derive(refs, poc, sps)
l0, l1, err := h265.Lists(set, refs)

refs carries how many entries each list has and, where the slice stated one, the order they are taken in -- so the caller passes neither.

⛔ The two lists are not interchangeable. List 0 opens with the pictures BEFORE this one in output order, list 1 with those after. A caller that fed a B slice the same list twice, or swapped them, would predict from the wrong side and get an image that is wrong without being malformed.

A list is as long as the slice says, which has nothing to do with how many pictures are available. Shorter and it simply stops. Longer and the candidates are repeated, from the start, as many times as it takes — that is legal, and a list built to stop once would come out short.

An I slice gets no lists. A P slice gets list 0 only.

The order the slice asked for

A slice may state, for each position of each list, which picture goes there -- ref_pic_lists_modification(), 7.3.6.2. ReferencesOf reads it into ListEntryL0 and ListEntryL1, and Lists applies it.

⛔ An entry indexes the TEMPORARY list, which is as long as the greater of the list's own length and the pictures available. A slice may name a picture beyond the end of its own list, and a reader that cut the list to length first would refuse a legal stream.

⛔ nil is not an empty list. A slice that stated no modification leaves the default order standing; a list of no entries is a different thing, and the two must not be spelt the same way.

An entry is Ceil(Log2(NumPicTotalCurr)) bits wide, which holds values past the last picture — three pictures are named in two bits — so an index out of range is reachable from a field of conformant width.

⛔ An entry is bounded by the PICTURES, not by the temporary list it indexes (7.4.7.2). The temporary list is longer whenever the list has more entries than there are pictures, and bounding on it lets an index past the last picture through. FFmpeg bounds on the temporary list; GStreamer enforces the clause and cites it. Nothing is lost by refusing them: the temporary list past NumPicTotalCurr only repeats the candidates.

How a slice weighs what it predicts from

pred_weight_table(), 7.3.6.3, comes back as PictureRefs.Weights -- nil where the picture parameter set does not weight this kind of slice.

⛔ The weights are VALUES, not the differences the syntax carries. A weight is stated as a difference from the neutral 1 << denominator, and a chroma offset as a difference that still has the weight folded into it. Handed the raw numbers, a decoder scales by something close to nothing.

ChromaOffset = Clip(delta - ((128 * ChromaWeight) >> denom) + 128, -128, 127)

⛔ Every luma flag comes first, as one field of n bits, then every chroma flag, and only then the values. H.264 interleaves a flag with its own values; HEVC does not. A reader carrying the sibling's shape over takes the first entry's weight out of the second entry's flag -- a wrong number, not an error.

An entry that states nothing still comes back with the neutral weight and a zero offset, so a caller never has to ask whether a field was present.

The chroma fields follow ChromaArrayType, as the SAO flag does.

TemporalMVP, CollocatedFromL0 and CollocatedRefIdx say which picture the slice takes its motion from, and MaxMergeCand how many merge candidates it uses. The index is stated only where the list has more than one entry.

⛔ The offsets are bounded by the format, and two readers disagree on how much. 7.4.7.3 allows a luma offset in -128..127 and a chroma offset difference in -512..511 — four times the half range. FFmpeg checks neither: it bounds the chroma difference at ±2¹⁷, which guards its own arithmetic rather than stating the format's range, and does not check the luma offset at all. libde265 enforces both. This package follows the tighter pair, and the boundaries are pinned on both sides.

Not here: slice_qp_delta and the fields after it. ReferencesOf stops once it has everything about the pictures.

⛔ No sequence range extension. WpOffsetHalfRange is 1 << 7 unless high_precision_offsets_enabled_flag is set, and that flag lives in a sequence extension this package does not read — it sits past everything ParseSPS consumes. A stream that sets it states its offsets over a wider range and would be refused here, and nothing in this package can tell.

A picture may be carried by several slice segments, and only the one with first_slice_segment_in_pic_flag set begins a new picture. That is what SplitPictures counts, which is how a stream's pictures are counted without decoding any of them.

A ceiling on the sum, not on each half

⛔ 7.4.8 bounds num_negative_pics by sps_max_dec_pic_buffering_minus1 and num_positive_pics by what is LEFT of it, so the ceiling is on the sum. A bound on each half allows twice what any conforming stream may state: eight before and eight after is well inside sixteen each way and outside the format.

The ceiling is fifteen — sps_max_dec_pic_buffering_minus1 is at most MaxDpbSize - 1, and A.4.2 puts MaxDpbSize at sixteen whatever the level. GStreamer bounds NumDeltaPocs the same way.

A width is read before it is narrowed

⛔ log2_max_pic_order_cnt_lsb_minus4 is a BIT COUNT — a slice header reads its order count with it, so a reader given a wrong one is misaligned from that field onwards.

It was bounded, and the bound did not hold: the value was narrowed to uint8 before the check, and that conversion wraps. 1048576 becomes 0, so the width came out as 4 — the smallest legal one — and a value a million past the range read as conformant. The two bit depths were narrowed the same way and not bounded at all.

Every one of them is now read as a full uint32, checked against 7.4.3.2.1's range, and narrowed afterwards. Both boundaries are pinned.

Sibling

go-avkit/h264 is the same layer for H.264/AVC. Its clause 8.2 derivations have HEVC counterparts here — order counts, the reference set, the reference lists — with two exceptions: h264 also reads the prediction weights and applies the list reordering, and this package does neither yet.

Windows, macOS, Linux; six 64-bit architectures. 100% statement coverage, gated in CI.

Licence

BSD-3-Clause.

Documentation

Overview

Package h265 reads an H.265/HEVC bitstream in pure Go, with no libavcodec linkage and no external binaries.

The framing and the bit reading are go-avkit/bitstream's, shared with H.264: the two formats separate their units identically and differ in how the header bytes of a unit are read -- H.264 spends one and this spends two -- and in what the parameter sets hold. This package is that difference.

Index

Examples

Constants

View Source
const (
	HashMD5 = iota
	HashCRC
	HashChecksum
)

The hash_type values of Table D.10.

View Source
const MaxRefIdxActive = 15

MaxRefIdxActive is the most entries a reference picture list may have, 7.4.3.3. It bounds what a parameter set may state and what Lists will build.

View Source
const SEIPayloadDecodedPictureHash = 132

SEIPayloadDecodedPictureHash is payloadType of the decoded picture hash SEI message (D.2.1, D.2.20).

Variables

View Source
var (
	// ErrPictureTooLarge: a sequence parameter set describes a picture of more luma
	// samples than Limits.MaxPixels.
	ErrPictureTooLarge = errors.New("h265: the picture is larger than the decoder's limit")
	// ErrDPBTooLarge: the decoded picture buffer the stream needs would hold more than
	// Limits.MaxDPBBytes.
	ErrDPBTooLarge = errors.New("h265: the decoded picture buffer would exceed the decoder's memory limit")
	// ErrMissingParameterSet: a slice names a parameter set that was not received.
	ErrMissingParameterSet = errors.New("h265: a slice names a parameter set that was not received")
	// ErrCorruptPicture: a picture could not be decoded to its end; the picture is still
	// kept for reference and output, as far as it was decoded.
	ErrCorruptPicture = errors.New("h265: a picture could not be decoded")
	// ErrHashMismatch: a decoded picture differs from its decoded picture hash SEI message.
	ErrHashMismatch = errors.New("h265: a decoded picture does not match its picture hash")
)

Errors of the Decoder. The errors of the parsers it calls (ErrUnsupportedSPS, ErrSliceHeader, ErrSliceData ...) are returned as they are, wrapped.

View Source
var (
	// ErrNotPPS means the unit handed over is not a picture parameter set.
	ErrNotPPS = errors.New("h265: unit is not a picture parameter set")
	// ErrUnsupportedPPS means the set does not end where a set must end, so
	// something in it was read wrongly.
	ErrUnsupportedPPS = errors.New("h265: picture parameter set was not consumed exactly")
	// ErrRefIdxRange means the set states more reference indices than a list
	// can hold. 7.4.3.3 puts num_ref_idx_lX_default_active_minus1 in 0..14; a
	// larger value is not a big stream, it is a few bytes asking a reader to
	// size a list from an attacker's number.
	ErrRefIdxRange = errors.New("h265: num_ref_idx_lX_default_active_minus1 out of range")
)

Errors a picture parameter set can be refused with.

View Source
var (
	// ErrNotSlice means the unit handed over does not carry a slice segment.
	ErrNotSlice = errors.New("h265: unit does not carry a slice segment")
	// ErrSliceHeader means a segment states something this reader does not follow.
	ErrSliceHeader = errors.New("h265: unsupported slice segment header")
)

Errors a slice segment header can be refused with.

View Source
var (
	// ErrNotSPS means the unit handed over is not a sequence parameter set.
	ErrNotSPS = errors.New("h265: unit is not a sequence parameter set")
	// ErrUnsupportedSPS means the set states something this reader does not
	// follow.
	ErrUnsupportedSPS = errors.New("h265: unsupported sequence parameter set")
)

Errors a sequence parameter set can be refused with.

View Source
var ErrMissingReference = errors.New("h265: a reference picture is not in the decoded picture buffer")

ErrMissingReference means the reference picture set of a picture names a picture it may predict from that the buffer does not hold.

View Source
var ErrNoOrder = errors.New("h265: the unit carries no picture order count")

ErrNoOrder means the unit states no order of its own.

View Source
var ErrNotReconstructed = errors.New("h265: the coding unit needs a process that is not implemented")

ErrNotReconstructed means a coding unit needs what the reconstruction was not given: an inter coding unit without the reference lists of its slice (Reconstructor.Inter).

View Source
var ErrPOCRange = errors.New("h265: order count out of range")

ErrPOCRange means a slice names a picture whose order count 8.3.1 forbids: one outside the 32-bit range, or more than 2^15 from the current picture's.

View Source
var ErrRefLists = errors.New("h265: reference list cannot be built")

ErrRefLists means a slice asked for a reference list that cannot be built.

View Source
var ErrResidual = errors.New("h265: residual_coding is not valid")

ErrResidual means the residual coding of a transform block is not one the syntax allows: a coefficient outside CoeffMin..CoeffMax, or a bin string the binarisation does not have.

View Source
var ErrSEI = errors.New("h265: SEI message is not valid")

ErrSEI means an SEI RBSP is not what 7.3.2.4 and 7.3.5 allow: a message runs past the end of the unit, or a payload is not the size its syntax needs.

View Source
var ErrScalingList = errors.New("h265: scaling list data is not valid")

ErrScalingList means scaling_list_data( ) states what 7.4.5 forbids.

View Source
var ErrSliceData = errors.New("h265: slice segment data is not valid")

ErrSliceData means slice segment data is not what 7.3.8 allows: it does not end where its last coding tree unit says, a substream does not start where the entry points say, or a flag that must be 1 is 0.

View Source
var ErrTemporalIDPlus1 = errors.New("h265: nuh_temporal_id_plus1 is 0")

ErrTemporalIDPlus1 means a unit states nuh_temporal_id_plus1 equal to 0, which 7.4.2.2 forbids.

Functions

func ChromaQPTable added in v0.14.0

func ChromaQPTable(qPi int) int

ChromaQPTable is Table 8-10: QpC as a function of qPi for ChromaArrayType 1.

func CrossComponent added in v0.14.0

func CrossComponent(r, rY []int32, resScaleVal int32, bitDepthY, bitDepthC int)

CrossComponent is the residual modification of 8.6.6: r += ( resScaleVal * ( ( rY << BitDepthC ) >> BitDepthY ) ) >> 3 for each sample.

func DecodeResidual added in v0.14.0

func DecodeResidual(d *cabac.Decoder, m *cabac.Model, t *ResidualTools, in ResidualInput, out *ResidualBlock) error

DecodeResidual is residual_coding( x0, y0, log2TrafoSize, cIdx ), 7.3.8.11, with the context selection of 9.3.4.2.3 to 9.3.4.2.7, from the arithmetic decoder d and the context variables m. out.Levels must hold 1 << (2*Log2Size) entries; it is zeroed here.

func DecodeSliceData added in v0.14.0

func DecodeSliceData(ps *PictureState, u Unit, hdr SliceHeader, pps PPS, cu CodingUnitFunc) error

DecodeSliceData is slice_segment_data( ) (7.3.8.1): the coding tree units of the slice segment u, whose header is hdr, with the initialisation and the synchronisation of the context variables of 9.3.2 for tiles, wavefronts and dependent segments. cu decodes each coding unit. It succeeds only if the data ends exactly where end_of_slice_segment_flag says, each substream starts where the entry points say, and every end_of_subset_one_bit is 1.

func PredictIntra added in v0.14.0

func PredictIntra(refs []int32, p IntraParams, out []int32)

PredictIntra is 8.4.4.2.1 from the substituted reference samples: the filtering of the neighbouring samples (8.4.4.2.3) and the planar, DC or angular prediction (8.4.4.2.4 to 8.4.4.2.6). refs is not modified; out is n * n samples, y * n + x.

func RDPCM added in v0.14.0

func RDPCM(r []int32, n, mDir int)

RDPCM is the residual modification of 8.6.5 for blocks using a transform bypass: mDir 0 accumulates along rows, 1 down columns. r is indexed y * n + x.

func Residual added in v0.14.0

func Residual(levels []int32, p BlockParams, out []int32) error

Residual is the scaling and transformation process of 8.6.2: from the levels of a block (TransCoeffLevel, index y * nTbS + x) to its residual samples r. out must hold nTbS * nTbS entries.

func ScanIdx added in v0.14.0

func ScanIdx(in ResidualInput, chromaArrayType int) int

ScanIdx is 7.4.9.11: the scan order index of a transform block.

func SubstituteReferences added in v0.14.0

func SubstituteReferences(refs []int32, avail []bool, bitDepth int)

SubstituteReferences is 8.4.4.2.2: the samples of refs that are not available take the value of the one before them in the search order, the first taking that of the first available one, or 1 << ( bitDepth - 1 ) when none is.

Types

type BlockParams added in v0.14.0

type BlockParams struct {
	Log2Size int // log2( nTbS ), 2 to 5
	CIdx     int
	// QP is qP of 8.6.2: Qp'Y, Qp'Cb or Qp'Cr.
	QP       int
	BitDepth int // of the component
	// ExtendedPrecision is extended_precision_processing_flag.
	ExtendedPrecision bool
	// Factor is ScalingFactor[ sizeId ][ matrixId ] of the block (nTbS x nTbS, index
	// y * nTbS + x); nil for the flat 16 of scaling_list_enabled_flag equal to 0.
	Factor []uint8
	// TransquantBypass, TransformSkip and Intra are cu_transquant_bypass_flag,
	// transform_skip_flag and CuPredMode == MODE_INTRA; RotateEnabled is
	// transform_skip_rotation_enabled_flag.
	TransquantBypass, TransformSkip, Intra, RotateEnabled bool
}

BlockParams is what the scaling and transformation process of one transform block takes besides its levels.

type CodingUnit added in v0.14.0

type CodingUnit struct {
	X, Y, Log2Size   int
	TransquantBypass bool
	Mode             PredMode
	Part             PartMode
	// PCM says the samples are in PcmLuma and PcmChroma (Cb then Cr), as stated,
	// PcmBitDepth bits each.
	PCM                bool
	PcmLuma, PcmChroma []uint16
	// PU holds the NumPU prediction blocks of an inter coding unit.
	NumPU int
	PU    [4]PredictionUnit
	// The intra modes of the one or four prediction blocks, as stated: the
	// derivation of IntraPredModeY (8.4.2) and of the chroma mode (8.4.3) is not
	// made here. IntraChromaPredMode is 0..4, one per block in 4:4:4 and otherwise
	// the first.
	PrevIntraLumaPred    [4]bool
	MpmIdx               [4]uint8
	RemIntraLumaPredMode [4]uint8
	IntraChromaPredMode  [4]uint8
	// IntraPredModeY and IntraPredModeC are the derived modes (8.4.2, 8.4.3) of
	// each prediction block; without chroma partitions all four IntraPredModeC are
	// the first.
	IntraPredModeY, IntraPredModeC [4]uint8
	// RqtRootCbf is rqt_root_cbf (1 when absent); IntraSplit is IntraSplitFlag and
	// MaxTrafoDepth the depth the transform tree may reach.
	RqtRootCbf    bool
	IntraSplit    bool
	MaxTrafoDepth int
}

CodingUnit is coding_unit( ) (7.3.8.5) as it was read: the syntax elements, not the prediction they lead to.

type CodingUnitFunc added in v0.14.0

type CodingUnitFunc func(w *SliceWalker, x0, y0, log2CbSize int) error

CodingUnitFunc decodes coding_unit( x0, y0, log2CbSize ) with the walker w.

func CodingUnitDecoder added in v0.14.0

func CodingUnitDecoder(tree TransformTreeFunc, cu func(*CodingUnit)) CodingUnitFunc

CodingUnitDecoder is coding_unit( ) with tree for its transform tree, as the CodingUnitFunc that DecodeSliceData takes. When cu is not nil it receives each coding unit once its syntax has been read, before the transform tree.

type CtbLayout added in v0.14.0

type CtbLayout struct {
	// WidthCtbs and HeightCtbs are PicWidthInCtbsY and PicHeightInCtbsY.
	WidthCtbs, HeightCtbs int
	// ColBd and RowBd are colBd and rowBd (6-5, 6-6): the tile boundaries in
	// coding tree blocks, one more than there are tiles each way.
	ColBd, RowBd []int
	// RsToTs is CtbAddrRsToTs (6-7), TsToRs CtbAddrTsToRs (6-8) and TileID the
	// TileId of each address in TILE scan (6-9).
	RsToTs, TsToRs []int32
	TileID         []int32
	// contains filtered or unexported fields
}

CtbLayout is the CTB raster and tile scanning conversion of clause 6.5.1 for one picture: the order in which the coding tree blocks of the picture are coded, and which tile each belongs to.

func NewCtbLayout added in v0.14.0

func NewCtbLayout(sps SPS, pps PPS) (*CtbLayout, error)

NewCtbLayout derives the layout from the SPS and the PPS that names it. It validates the pair first (PPS.Validate), so the tile grid fits the picture.

func (*CtbLayout) MinTbAddrZs added in v0.14.0

func (l *CtbLayout) MinTbAddrZs(x, y int) int

MinTbAddrZs is the minimum block address in z-scan order of the minimum transform block at ( x, y ), in units of minimum transform blocks (6-10). It is computed where the specification stores it in an array: the array would hold up to 256 entries per coding tree block.

type DPB added in v0.14.0

type DPB struct {
	Output func(*DPBPicture)
	// Drop, when set, is called with each picture as the buffer lets go of it (its buffer
	// is emptied): the decoder recycles the planes of a picture the caller has released.
	Drop func(*DPBPicture)
	// contains filtered or unexported fields
}

DPB is the decoded picture buffer. Output is called with each picture as C.5.2.4 outputs it, in output order; the picture's frame is the uncropped decoded picture.

func (*DPB) Begin added in v0.14.0

func (d *DPB) Begin(in PictureInfo) (RefPics, error)

Begin is what happens between the slice header of the first slice of a picture and its decoding: the decoding process for the reference picture set (8.3.2), the output and removal of pictures of C.5.2.2, and the generation of unavailable reference pictures (8.3.3). It returns the pictures of the five lists, or ErrMissingReference when a picture the current one may predict from is not held.

func (*DPB) Finish added in v0.14.0

func (d *DPB) Finish(cur *DPBPicture, picOutput bool)

Finish stores the decoded current picture (C.3.4, 8.1.3) and does the additional bumping of C.5.2.3. cur's POC, Frame, State and SPS are the caller's.

func (*DPB) Flush added in v0.14.0

func (d *DPB) Flush()

Flush outputs every picture still needed for output, in order, and empties the buffer: the end of the bitstream.

func (*DPB) Pictures added in v0.14.0

func (d *DPB) Pictures() []*DPBPicture

Pictures returns the pictures held, in the order they entered.

type DPBPicture added in v0.14.0

type DPBPicture struct {
	POC   int32
	Frame *DecodedPicture
	// State is what the walk of the picture recorded, which later pictures read
	// (the motion data for temporal prediction); nil for a generated picture.
	State *PictureState
	SPS   SPS
	Mark  RefMark
	// NeededForOutput and LatencyCount are the output state of C.5.2; Generated says
	// the picture came from 8.3.3.
	NeededForOutput bool
	LatencyCount    int
	Generated       bool
	TemporalID      uint8
	// Tag is the Tag of the first slice segment of the picture (Unit.Tag).
	Tag uint64
	// Corrupt says the picture could not be decoded to its end (Stats.Failed counts it).
	Corrupt bool
}

DPBPicture is one picture storage buffer: a decoded picture, its marking, and what output needs of it.

type DecodedPicture added in v0.14.0

type DecodedPicture struct {
	Components int
	BitDepth   [3]int
	Planes     [3]Plane
	// contains filtered or unexported fields
}

DecodedPicture is a decoded picture: Components planes, each with its bit depth.

func NewDecodedPicture added in v0.14.0

func NewDecodedPicture(sps SPS) *DecodedPicture

NewDecodedPicture allocates the picture the sequence parameter set describes, a coded picture of pic_width_in_luma_samples by pic_height_in_luma_samples.

func (*DecodedPicture) Clone added in v0.19.0

func (p *DecodedPicture) Clone() *DecodedPicture

Clone returns a copy of the picture that the caller owns: every plane is its own allocation, Stride equal to Width, so it can be written to without touching the decoder's pictures. The planes of an Output picture are read-only views (see Output); Clone it first to modify it.

func (*DecodedPicture) Crop added in v0.14.0

func (p *DecodedPicture) Crop(sps SPS) *DecodedPicture

Crop returns the picture cut to the conformance window of sps (C.5.2.4). It is a view: each plane of the result is the window of the plane of p, the same memory with p's stride, so nothing is copied. See Output for what that means for the caller.

func (*DecodedPicture) Hash added in v0.14.0

func (p *DecodedPicture) Hash(kind uint8) PictureHash

Hash computes the decoded picture hash of kind (HashMD5, HashCRC, HashChecksum) as D.3.20 arranges and hashes the samples.

func (*DecodedPicture) Is8 added in v0.22.0

func (p *DecodedPicture) Is8() bool

Is8 reports whether the picture is made of byte planes: every component has a bit depth of 8.

func (*DecodedPicture) Release added in v0.24.0

func (p *DecodedPicture) Release()

Release says the caller is done with a picture the decoder output, so that the decoder may reuse its planes (Options.RecyclePictures). The planes are reused once the decoded picture buffer no longer needs the picture as a reference or for output: Release on a picture that is still in the buffer only defers the reuse until it has left. The picture is emptied (no planes), so reading it after Release gives nothing and cannot show another picture's samples; a second Release does nothing. Without Options.RecyclePictures, or on a picture that is not one the decoder output (a Clone, say), Release does nothing at all and the picture stays valid.

A caller that keeps a plane slice taken from the picture before Release must not use it after: the slice is the decoder's memory, which will hold another picture. A picture that is not released is never reused.

type Decoder added in v0.16.0

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

Decoder decodes the base layer of an HEVC bitstream. It is not safe for concurrent use.

func NewDecoder added in v0.16.0

func NewDecoder(opt Options) *Decoder

NewDecoder starts a decoder; zero limits stand for DefaultLimits.

func (*Decoder) Decode added in v0.16.0

func (d *Decoder) Decode(u Unit) ([]Output, error)

Decode takes the next NAL unit of the stream, in decoding order, and returns the pictures that became ready for output because of it. A picture is complete when the first slice segment of the next one, an end of sequence unit, or Flush arrives, so the pictures returned are usually those of earlier units. Units the decoder does not use (VPS, AUD, prefix SEI, layers above the base) are ignored. An error does not stop the decoder: the stream can go on, and the pictures returned alongside it are valid.

func (*Decoder) Flush added in v0.16.0

func (d *Decoder) Flush() ([]Output, error)

Flush ends the stream: the last picture is completed and every picture still waiting is output, in order. The decoder can then be used for another stream.

func (*Decoder) Stats added in v0.16.0

func (d *Decoder) Stats() DecoderStats

Stats returns the counts so far.

type DecoderStats added in v0.16.0

type DecoderStats struct {
	// Pictures decoded (including the ones that failed), SkippedRASL the RASL pictures
	// not decoded (8.1.3), Failed those that could not be decoded to their end.
	Pictures, SkippedRASL, Failed int
	// Verified, Mismatched and Unhashed count the decoded pictures with a hash that
	// matched, with one that did not, and without one (VerifyHash only).
	Verified, Mismatched, Unhashed int
	// VerifiedInter is the part of Verified with a P or B slice.
	VerifiedInter int
}

DecoderStats counts what a decoder has done.

type InterPredIdc added in v0.14.0

type InterPredIdc uint8

InterPredIdc is inter_pred_idc (Table 7-11).

const (
	PredL0 InterPredIdc = iota
	PredL1
	PredBi
)

The reference lists a prediction block uses.

type InterSlice added in v0.15.0

type InterSlice struct {
	Type SliceType
	POC  int32
	List [2][]RefEntry
	// TemporalMVP is slice_temporal_mvp_enabled_flag; Col is ColPic and
	// NoBackwardPred NoBackwardPredFlag (8.3.5); ColFromL0 is collocated_from_l0_flag.
	TemporalMVP    bool
	Col            *DPBPicture
	ColFromL0      bool
	NoBackwardPred bool
	MaxMergeCand   int
	// Log2ParMrgLevel is Log2ParMrgLevel (7-37).
	Log2ParMrgLevel int
	// Weights is pred_weight_table when the slice weighs its prediction explicitly
	// (weightedPredFlag of 8.5.3.3.4.1 is 1), nil otherwise.
	Weights *PredWeights
}

InterSlice is what the motion derivation of a P or B slice takes from the slice: its type and order count, the two reference picture lists, and the variables of 8.3.5.

func NewInterSlice added in v0.15.0

func NewInterSlice(hdr SliceHeader, pps PPS, poc int32, l0, l1 []RefEntry) (*InterSlice, error)

NewInterSlice derives ColPic and NoBackwardPredFlag (8.3.5) for a slice whose lists are l0 and l1.

type IntraParams added in v0.14.0

type IntraParams struct {
	Log2Size int
	CIdx     int
	Mode     int // predModeIntra, 0 to 34
	BitDepth int
	// FilterRefs is intra_smoothing_disabled_flag equal to 0 and cIdx equal to 0 or
	// ChromaArrayType equal to 3 (8.4.4.2.1, step 1).
	FilterRefs bool
	// Strong is strong_intra_smoothing_enabled_flag.
	Strong bool
	// NoBoundaryFilter is disableIntraBoundaryFilter of 8.4.4.2.6: implicit RDPCM
	// with transquant bypass.
	NoBoundaryFilter bool
}

IntraParams are the variables of 8.4.4.2.1 to 8.4.4.2.6 that are not samples.

type Limits added in v0.16.0

type Limits struct {
	// MaxPixels is the largest picture, in luma samples (default 8192 x 4320, the
	// largest of level 6.2).
	MaxPixels int64
	// MaxDPBBytes bounds the decoded picture buffer, estimated as the samples of its
	// pictures plus the data kept for prediction (default 2 GiB).
	MaxDPBBytes int64
}

Limits bound what a stream can make the decoder allocate.

func DefaultLimits added in v0.16.0

func DefaultLimits() Limits

DefaultLimits are the limits a zero Limits stands for.

type LongTermRef added in v0.5.0

type LongTermRef struct {
	POCLSB uint32
	Used   bool
	// MSBPresent says DeltaMSBCycle was stated. Without it the picture is the
	// one whose low bits match; with it, the one that many wraps further back.
	MSBPresent    bool
	DeltaMSBCycle uint32
	// FromSPS says the entry was named out of the sequence's own list rather
	// than stated by the slice.
	FromSPS bool
}

LongTermRef is one long-term picture a slice names.

A long-term picture is named by the LOW bits of its order count, which is enough while no two candidates share them. When two would, the slice states the high bits as well, which is what MSBPresent says.

type LongTermRefPic added in v0.4.0

type LongTermRefPic struct {
	POCLSB uint32
	Used   bool
}

LongTermRefPic is one long-term picture a sequence offers to its slices.

type LtPicture added in v0.7.0

type LtPicture struct {
	POC   int32
	Exact bool
}

LtPicture is one long-term picture a set names.

⛔ POC is a full order count only when Exact is set. Otherwise it is the LOW bits of one, and the picture meant is whichever held in the decoded picture buffer matches them -- which is enough while no two candidates share them, and is why the format lets a slice state the high bits when two would.

type Motion added in v0.14.0

type Motion struct {
	Pred [2]bool
	// Ref is the order count of the reference picture of each list used, which names
	// the picture; RefIdx its index in the slice's list and LongTerm whether it was a
	// long-term reference picture, which motion derivation reads (-1 for a list not used).
	Ref      [2]int32
	MV       [2][2]int16
	RefIdx   [2]int8
	LongTerm [2]bool
}

Motion is the motion of a prediction block as the boundary strength compares it (8.7.2.4): which lists it predicts from, the picture each list's reference is (an identifier of the picture, not an index into a list) and the vectors in quarter luma samples.

type Options added in v0.16.0

type Options struct {
	Limits Limits
	// VerifyHash compares each decoded picture with its decoded picture hash SEI message
	// when it has one (ErrHashMismatch on a difference).
	VerifyHash bool
	// RecyclePictures lets the decoder reuse the planes of pictures the caller has given
	// back with DecodedPicture.Release, instead of allocating every picture afresh (which at
	// 1080p costs about 1500 page faults a frame). Off by default: without it nothing changes
	// and an Output picture stays valid for as long as it is referenced (see Output). With it,
	// a picture that is not released is still never reused; a released one is, once the
	// decoder no longer needs it as a reference, so the caller must not read it after Release.
	RecyclePictures bool
}

Options configure a Decoder.

type Output added in v0.16.0

type Output struct {
	Picture *DecodedPicture
	POC     int32
	// Tag is the Tag of the first slice segment of the picture (Unit.Tag).
	Tag uint64
	// Corrupt says the picture could not be decoded to its end: a slice was lost or failed, or
	// it is predicted from a reference the stream never delivered (an error came back with it
	// and Stats.Failed counts it). The picture is still output, as far as it was decoded.
	Corrupt bool
}

Output is a picture the decoder outputs: cut to the conformance window, in output order (C.5.2.4).

Lifetime. Every decoded picture is its own allocation, which the decoder never recycles and never writes again once it is decoded, so Picture stays valid and unchanged for as long as the caller keeps it (the garbage collector frees it with the last reference). Its planes are views of the decoder's picture (cut to the conformance window, so a plane's Stride can be larger than its Width, and a plane's Pix runs to its last sample): the same memory the decoder reads as a reference picture for later ones. The caller must therefore treat the planes as read-only: writing to them changes the pictures predicted from this one. Call Picture.Clone first to get a copy that can be modified.

That is the default. With Options.RecyclePictures a caller may give a picture back with Picture.Release, after which its planes are the decoder's again (reused once the decoder no longer needs the picture as a reference) and Picture is empty; a picture that is not released keeps the lifetime above.

Behaviour change (the release that made planes views): output planes used to be copies the caller could write to; callers that modify them must Clone the picture first.

type POC added in v0.3.0

type POC struct {
	// Value is the count itself.
	Value int32
	// LSB is what the slice header stated, before the high bits were carried in.
	LSB uint32
	// Carried says this picture is the one later pictures count from. Only a
	// picture of sub-layer zero that is neither leading nor sub-layer
	// non-reference does that, and a counter that carried from every picture
	// would place everything after the first dropped one wrongly.
	Carried bool
}

POC is a picture's order count: where it belongs in the order a viewer sees, which is not the order it was coded in.

type POCCounter added in v0.3.0

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

POCCounter derives picture order counts across a coded video sequence.

⛔ It has to be a counter rather than a function because the format sends only the LOW bits of the count. The high bits are carried forward from an earlier picture, and the one they come from is not simply the previous picture: it is the previous one of sub-layer zero that is neither a leading picture nor a sub-layer non-reference. Those are exactly the pictures a thinned stream may have dropped, so counting from them would make the order depend on what was thrown away.

Feed it every coded picture of the sequence, in decode order, one slice per picture: the first slice segment of each. A picture carried by several segments is one picture here.

func (*POCCounter) Next added in v0.3.0

func (c *POCCounter) Next(u Unit, sps SPS, pps PPS) (POC, error)

Next gives the order count of one coded picture and remembers what the pictures after it will need.

The unit is wanted whole, not just its payload: the count depends on the unit TYPE, which says whether the high bits restart, and on the temporal identifier, which says whether this picture is one later ones count from.

func (*POCCounter) Reset added in v0.3.0

func (c *POCCounter) Reset()

Reset forgets every picture counted so far. It is what a seek is: the pictures before the new position are not the ones the counts should follow from.

type PPS

type PPS struct {
	ID                     uint32
	SPSID                  uint32
	DependentSlicesEnabled bool
	OutputFlagPresent      bool
	ExtraSliceHeaderBits   uint8
	SignDataHiding         bool
	CABACInitPresent       bool
	NumRefIdxL0            uint32
	NumRefIdxL1            uint32
	InitQP                 int32 // already un-biased
	ConstrainedIntraPred   bool
	TransformSkip          bool
	CUQPDeltaEnabled       bool
	CbQPOffset             int32
	CrQPOffset             int32
	SliceChromaQPOffsets   bool
	WeightedPred           bool
	WeightedBipred         bool
	TransquantBypass       bool
	TilesEnabled           bool
	EntropySyncEnabled     bool
	TileColumns            uint32
	TileRows               uint32
	UniformTileSpacing     bool
	DeblockingControl      bool // deblocking_filter_control_present_flag
	DeblockingOverride     bool
	DeblockingDisabled     bool
	BetaOffsetDiv2         int32
	TCOffsetDiv2           int32
	ListsModification      bool
	SliceHeaderExtension   bool

	// DiffCuQPDeltaDepth is diff_cu_qp_delta_depth: Log2MinCuQpDeltaSize is the
	// SPS's CtbLog2SizeY less it (7-36). Zero when cu_qp_delta is not enabled.
	DiffCuQPDeltaDepth uint8
	// ColumnWidthMinus1 and RowHeightMinus1 are the stated tile sizes, in
	// coding tree blocks, one fewer than the tile count when spacing is not
	// uniform; the last column and row are what is left.
	ColumnWidthMinus1, RowHeightMinus1 []uint32
	LoopFilterAcrossTiles              bool
	LoopFilterAcrossSlices             bool
	ScalingListPresent                 bool
	// ScalingList is pps_scaling_list_data( ), nil without it.
	ScalingList *ScalingLists
	// Log2ParMrgLevel is Log2ParMrgLevel (7-37): log2_parallel_merge_level_minus2 + 2.
	Log2ParMrgLevel uint8
	// Range is pps_range_extension; its zero value is what an absent one infers.
	Range PPSRangeExtension
}

PPS is what a picture parameter set says about the slices that refer to it.

Two of these fields are what a slice segment header cannot be read without: whether a segment may depend on the one before it, and how many bits of the header the stream reserves before the slice type. A reader without them is misaligned from the first field that matters.

func ParsePPS

func ParsePPS(u Unit) (PPS, error)

ParsePPS reads a picture parameter set.

⛔ Unlike H.264's, this needs no other set to be consumed exactly: HEVC states the number of scaling lists by the size class rather than by the chroma format, so the variable parts here depend only on fields the set itself carries.

func (PPS) Validate added in v0.14.0

func (p PPS) Validate(s SPS) error

Validate checks what a picture parameter set states against the sequence parameter set it names, which ParsePPS cannot know: the ids agree, the tile grid fits the picture in coding tree blocks (7.4.3.3: at most PicWidthInCtbsY columns and PicHeightInCtbsY rows, and explicit widths and heights that leave at least one block for the last column and row), and the depths, the QP and the range extension's fields are within what the sequence's block sizes and bit depths allow. Sums are made in 64 bits: a thousand 32-bit widths overflow 32.

type PPSRangeExtension added in v0.14.0

type PPSRangeExtension struct {
	// Log2MaxTransformSkipSize is log2_max_transform_skip_block_size_minus2 + 2;
	// 2 when absent.
	Log2MaxTransformSkipSize       uint8
	CrossComponentPrediction       bool
	ChromaQPOffsetListEnabled      bool
	DiffCuChromaQPOffsetDepth      uint8
	CbQPOffsetList, CrQPOffsetList []int32
	Log2SAOOffsetScaleLuma         uint8
	Log2SAOOffsetScaleChroma       uint8
}

PPSRangeExtension is pps_range_extension (7.3.2.3.2).

type PartMode added in v0.14.0

type PartMode uint8

PartMode is PartMode (Table 7-10): how a coding unit divides into prediction blocks.

const (
	Part2Nx2N PartMode = iota
	Part2NxN
	PartNx2N
	PartNxN
	Part2NxnU
	Part2NxnD
	PartnLx2N
	PartnRx2N
)

The partitionings, in the order of part_mode's values.

type Picture

type Picture struct {
	Units []Unit
	Type  SliceType
	// TypeKnown is false when no segment of this picture stated a type, which
	// happens when a stream is joined part way through a picture.
	TypeKnown bool
	Sync      bool
	Bytes     int
}

Picture is one coded picture: the units that carry it, and what it is.

Units are in the order they arrived, parameter sets and all, so a caller writing a sample table has the bytes of a sample and nothing else to gather.

func SplitPictures

func SplitPictures(units []Unit, pps PPS) ([]Picture, error)

SplitPictures groups a stream's units into the pictures they carry.

⛔ Where H.264 needs several fields compared between neighbouring slices to find a boundary, HEVC states it outright: one flag per segment says whether it begins a picture. That is the whole rule here, and it is worth saying that the simpler format is simpler rather than carrying the other one's machinery over.

Parameter sets and delimiters that arrive before a picture's first segment belong to that picture: a decoder must hold them before the segment that uses them.

type PictureHash added in v0.14.0

type PictureHash struct {
	Type       uint8
	Components int
	MD5        [3][16]byte
	CRC        [3]uint16
	Checksum   [3]uint32
}

PictureHash is decoded_picture_hash( ) (D.2.20) of one decoded picture: the hash of each of its Components colour components, in the field its Type says.

func ParsePictureHash added in v0.14.0

func ParsePictureHash(payload []byte, chromaFormatIdc int) (h PictureHash, ok bool, err error)

ParsePictureHash reads a decoded picture hash payload of a picture whose chroma_format_idc is given (it decides how many components are hashed). A reserved hash_type is not an error but is to be ignored (D.3.20): ok is false.

func (PictureHash) Verify added in v0.14.0

func (h PictureHash) Verify(p *DecodedPicture) error

Verify reports the first component of p whose hash is not the stated one.

type PictureInfo added in v0.14.0

type PictureInfo struct {
	Type       UnitType
	TemporalID uint8
	POC        int32
	// Set is the reference picture set the slice header states, absolute (Derive).
	Set RefPicSet
	SPS SPS
	// NoOutputOfPriorPics is no_output_of_prior_pics_flag, and PicOutput
	// PicOutputFlag (8.1.3). NoRaslOutput is NoRaslOutputFlag of an IRAP picture, and
	// First says it is picture 0 of the bitstream.
	NoOutputOfPriorPics bool
	PicOutput           bool
	NoRaslOutput        bool
	First               bool
}

PictureInfo is what the buffer needs to know about the picture being started.

type PictureRefs added in v0.5.0

type PictureRefs struct {
	ShortTerm ShortTermRPS
	LongTerm  []LongTermRef
	// NamedSet says the short-term set was NAMED out of the sequence's sets
	// rather than stated by the slice, and SetIndex says which.
	NamedSet bool
	SetIndex int

	// Type is how the slice is coded. An I slice predicts from nothing, so the
	// fields below are not stated for one.
	Type SliceType
	// NumRefIdxL0Active and NumRefIdxL1Active are how many entries each
	// reference list has. They start at the picture parameter set's and a
	// slice may override them.
	NumRefIdxL0Active uint32
	NumRefIdxL1Active uint32
	// ListEntryL0 and ListEntryL1 are ref_pic_lists_modification, 7.3.6.2: the
	// position in the temporary list that each entry of the final list is
	// taken from. nil means the slice stated no modification for that list and
	// the default order stands -- which is NOT the same as an empty slice.
	ListEntryL0 []uint32
	ListEntryL1 []uint32

	// TemporalMVP says the slice predicts motion from another picture, which
	// is what the two fields below name.
	TemporalMVP bool
	// CollocatedFromL0 says which list the picture is taken from, and
	// CollocatedRefIdx its position in that list. Both are only meaningful
	// while TemporalMVP is set.
	CollocatedFromL0 bool
	CollocatedRefIdx uint32
	// Weights is pred_weight_table, nil where the picture parameter set does
	// not weight this kind of slice.
	Weights *PredWeights
	// MaxMergeCand is 5 - five_minus_max_num_merge_cand, in 1..5.
	MaxMergeCand uint8

	// SAOLuma and SAOChroma are slice_sao_luma_flag and slice_sao_chroma_flag;
	// MvdL1Zero is mvd_l1_zero_flag and CabacInit is cabac_init_flag.
	SAOLuma, SAOChroma   bool
	MvdL1Zero, CabacInit bool
}

PictureRefs is what one coded picture states about the pictures it may still need: a short-term set, and the long-term pictures it names.

func ReferencesOf added in v0.5.0

func ReferencesOf(u Unit, sps SPS, pps PPS) (PictureRefs, error)

ReferencesOf reads what a coded picture says it still needs.

An IDR says nothing: it begins a coded video sequence, so nothing before it is available and nothing after it may reach back. That is not an error and comes back as an empty set.

Pass the FIRST slice segment of the picture. A later segment states no set of its own -- the set belongs to the picture -- and its address, which this package cannot yet work out, sits in the way.

type PictureState added in v0.14.0

type PictureState struct {
	SPS    SPS
	Layout *CtbLayout
	// SliceAddr is SliceAddrRs of each coding tree block in raster scan, -1 for
	// one not yet decoded in this picture.
	SliceAddr []int32
	// Sao holds the parameters of each coding tree block, raster scan.
	Sao []SaoParams
	// CtDepth is CtDepth at the granularity of the minimum coding block, raster
	// scan of a grid MinCbWidth wide.
	CtDepth    []uint8
	MinCbWidth int
	// CuSkip is cu_skip_flag on the same grid as CtDepth.
	CuSkip []bool
	// IntraMode is IntraPredModeY per 4x4 luma block, raster scan of a grid
	// IntraWidth wide; INTRA_DC (1) for blocks of coding units that are not
	// intra or are PCM, which is what 8.4.2 takes a neighbour's mode to be.
	IntraMode  []uint8
	IntraWidth int
	// CuMode is CuPredMode (a PredMode) on the same grid.
	CuMode []uint8
	// The maps of the deblocking filter (deblock.go): the edges found, vertical and
	// horizontal, and whether a luma transform block holds coefficients, on the 4x4
	// grid Edge4W wide; the coding units whose samples the filters leave alone; the
	// slice's beta and tc offsets per CTB; and the motion of each 4x4 block, nil
	// until inter prediction fills it.
	Edge4W       int
	EdgeV, EdgeH []uint8
	Cbf4         []bool
	NoFilter     []bool
	DbBeta, DbTc []int8
	// DbAcross is slice_loop_filter_across_slices_enabled_flag per CTB.
	DbAcross []bool
	Motion   []Motion
	// Inter is the reference picture lists and variables of the slice being decoded; nil
	// when the motion of prediction units is not derived.
	Inter *InterSlice
	// QpY is QpY of each coding unit on the grid of CtDepth; lastQpY is the QpY of
	// the last coding unit decoded, which a dependent slice segment continues from.
	QpY []int8
	// contains filtered or unexported fields
}

PictureState is what the slices of one picture share while their data is decoded: the layout, which slice each coding tree block belongs to (for the availability of 6.4.1), the parameters read so far, and the context variables stored for the synchronisation of 9.3.2.4 and 9.3.2.5.

func NewPictureState added in v0.14.0

func NewPictureState(sps SPS, l *CtbLayout) *PictureState

NewPictureState starts the decoding of a picture.

func (*PictureState) Deblock added in v0.14.0

func (ps *PictureState) Deblock(frame *DecodedPicture, sps SPS, pps PPS)

Deblock applies the deblocking filter to the reconstructed picture (8.7.2): the vertical edges of every coding unit, then the horizontal ones.

func (*PictureState) SAO added in v0.14.0

func (ps *PictureState) SAO(frame *DecodedPicture, sps SPS, pps PPS)

SAO applies sample adaptive offset to the deblocked picture frame (8.7.3.1) with the parameters the walk read for each coding tree block.

type Plane added in v0.14.0

type Plane struct {
	Width, Height, Stride int
	Pix8                  []uint8
	Pix16                 []uint16
}

Plane is one colour component of a decoded picture: Width x Height samples, rows Stride samples apart (Stride is at least Width; sample (x, y) is at index y*Stride+x).

The samples are in Pix8 when the component has a bit depth of 8, and in Pix16 for every other depth: exactly one of the two is non-nil (a plane with no samples has neither). Use Is8 to tell, and At to read a sample of either without caring.

func (*Plane) At added in v0.22.0

func (p *Plane) At(x, y int) uint16

At returns the sample at column x, row y, of a plane of either kind. It is for tests and tools: a decoder's loops work on the slice. A plane with no samples (the planes of a picture after Release) reads as 0.

func (*Plane) Is8 added in v0.22.0

func (p *Plane) Is8() bool

Is8 reports whether the plane holds its samples as bytes (a bit depth of 8).

func (*Plane) Len added in v0.22.0

func (p *Plane) Len() int

Len is the number of samples of the slice that holds them, whichever it is.

type PredMode added in v0.14.0

type PredMode uint8

PredMode is CuPredMode (7.4.9.5).

const (
	ModeInter PredMode = iota
	ModeIntra
	ModeSkip
)

The prediction modes of a coding unit.

type PredWeights added in v0.9.0

type PredWeights struct {
	LumaLog2Denom   uint8
	ChromaLog2Denom uint8
	// L0 and L1 are as long as the lists they weigh.
	L0 []RefWeight
	L1 []RefWeight
	// contains filtered or unexported fields
}

PredWeights is pred_weight_table, 7.3.6.3: how a slice weighs each picture it predicts from.

⛔ The weights here are VALUES, not the deltas the syntax carries. The format states each as a difference from the neutral weight, and the offsets of the chroma components as a difference that has to be folded with the weight before it means anything. A caller handed the raw deltas would scale by something close to zero.

type PredictionUnit added in v0.14.0

type PredictionUnit struct {
	X, Y, W, H int
	Merge      bool
	MergeIdx   uint8
	Idc        InterPredIdc
	RefIdx     [2]uint8
	// Mvd is MvdL0 and MvdL1 ( horizontal, vertical ); MvpFlag mvp_l0_flag and
	// mvp_l1_flag.
	Mvd     [2][2]int32
	MvpFlag [2]uint8
	// Motion is the motion derived from the above (8.5.3.2) when the slice's reference
	// picture lists are known to the walker (PictureState.Inter).
	Motion Motion
}

PredictionUnit is prediction_unit( ) (7.3.8.6) of one prediction block, in luma samples. A merged or skipped block states only its merge index.

type RangeExtension added in v0.14.0

type RangeExtension struct {
	TransformSkipRotation       bool
	TransformSkipContext        bool
	ImplicitRDPCM               bool
	ExplicitRDPCM               bool
	ExtendedPrecisionProcessing bool
	IntraSmoothingDisabled      bool
	HighPrecisionOffsets        bool
	PersistentRiceAdaptation    bool
	// CabacBypassAlignment is cabac_bypass_alignment_enabled_flag: the
	// alignment of 9.3.4.3.6 precedes the bypass bins of a sub-block with escape
	// data (residual coding).
	CabacBypassAlignment bool
}

RangeExtension is sps_range_extension (7.3.2.2.2), all false when the set does not carry one.

type Reconstructor added in v0.14.0

type Reconstructor struct {
	Frame *DecodedPicture

	// Inter is the slice being decoded when it is a P or B slice: the lists the inter
	// prediction reads, the same value as PictureState.Inter.
	Inter *InterSlice
	// contains filtered or unexported fields
}

Reconstructor builds a picture, before the in-loop filters, from the coding units and transform units a slice walk reports (8.4 and 8.6.7).

func NewReconstructor added in v0.14.0

func NewReconstructor(frame *DecodedPicture, sps SPS, pps PPS) *Reconstructor

NewReconstructor starts the reconstruction of a picture into frame; the picture parameter set is the one its slices use.

func (*Reconstructor) CodingUnit added in v0.14.0

func (r *Reconstructor) CodingUnit(cu *CodingUnit)

CodingUnit is called with each coding unit once its syntax is read: a PCM block is the reconstruction itself (8-12, 8-15, 8-16).

func (*Reconstructor) Decoder added in v0.14.0

func (r *Reconstructor) Decoder() CodingUnitFunc

Decoder is the coding unit decoder of a slice that reconstructs what it reads.

func (*Reconstructor) Err added in v0.15.0

func (r *Reconstructor) Err() error

Err is the first error the prediction of an inter coding unit met. Such a unit is predicted when it is reported, which has no way to return one, so the caller checks it after the slice.

func (*Reconstructor) Unit added in v0.14.0

func (r *Reconstructor) Unit(w *SliceWalker, cu *CodingUnit, tu *TransformUnit) error

Unit reconstructs the blocks of a transform unit: of an intra coding unit per block the intra prediction, the residual, and their sum (8.4.4.1); of an inter one the residual (8.5.4) added to the prediction CodingUnit already wrote.

type RefEntry added in v0.15.0

type RefEntry struct {
	POC      int32
	LongTerm bool
	Pic      *DPBPicture
}

RefEntry is one entry of a reference picture list as the derivation needs it: the picture's order count, whether it is a long-term reference picture, and the picture itself (whose stored motion temporal prediction reads).

type RefListEntry added in v0.7.0

type RefListEntry struct {
	POC int32
	// LongTerm says the entry came from the long-term pictures, which a decoder
	// treats differently: a long-term reference is not scaled by distance the
	// way a short-term one is.
	LongTerm bool
	// Exact says POC is a full order count. A long-term entry whose slice did
	// not state its high bits carries only the low ones. See LtPicture.
	Exact bool
}

RefListEntry is one entry of a reference picture list.

func Lists added in v0.7.0

func Lists(set RefPicSet, refs PictureRefs) (l0, l1 []RefListEntry, err error)

Lists builds the reference picture lists a slice predicts from, clause 8.3.4.

⛔ The two lists hold the SAME pictures in a different order, and the order is the point: list 0 starts with what came before this picture, list 1 with what comes after. A decoder handed them the same way round predicts a B slice from the wrong side.

refs carries how many entries each list has and, where the slice stated one, the order its entries are taken in. A list SHORTER than the pictures available simply stops; a list LONGER repeats them, which is legal and is why the candidates are cycled rather than laid down once.

An I slice predicts from nothing and gets no lists. A P slice gets list 0.

Example

ExampleLists is the snippet the README shows, compiled. A documented call that does not build is a claim, not a capability.

package main

import (
	"fmt"

	"github.com/go-avkit/h265"
)

// ExampleLists is the snippet the README shows, compiled. A documented call
// that does not build is a claim, not a capability.
func main() {
	var sps h265.SPS
	// What ReferencesOf reads out of the slice segment header. A B slice that
	// names, for each of its three list 0 entries, the picture it wants there.
	refs := h265.PictureRefs{
		Type:              h265.SliceB,
		NumRefIdxL0Active: 3,
		NumRefIdxL1Active: 2,
		ShortTerm: h265.ShortTermRPS{
			Before: []h265.RefPic{{DeltaPOC: -8, Used: true}, {DeltaPOC: -4, Used: true}},
			After:  []h265.RefPic{{DeltaPOC: 4, Used: true}},
		},
		ListEntryL0: []uint32{2, 0, 1},
	}

	set, err := h265.Derive(refs, 16, sps)
	if err != nil {
		fmt.Println(err)
		return
	}
	l0, l1, err := h265.Lists(set, refs)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("list 0:", order(l0))
	fmt.Println("list 1:", order(l1))
}

func order(l []h265.RefListEntry) []int32 {
	out := make([]int32, len(l))
	for i, e := range l {
		out[i] = e.POC
	}
	return out
}
Output:
list 0: [20 8 12]
list 1: [20 8]

type RefMark added in v0.14.0

type RefMark uint8

RefMark is how a picture is marked for reference (8.3.2).

const (
	UnusedForReference RefMark = iota
	ShortTermReference
	LongTermReference
)

The three markings, of which a picture has exactly one.

type RefPic added in v0.4.0

type RefPic struct {
	// DeltaPOC is the entry's order count minus the current picture's, so it is
	// negative for a picture already seen and positive for one still to come.
	DeltaPOC int32
	Used     bool
}

RefPic is one entry of a short-term reference picture set: where the picture sits relative to the current one, and whether the current one may use it.

A set lists pictures the DECODER must keep, which is not the same as the pictures this one predicts from. An entry that is not Used is kept because a LATER picture will want it, and dropping it would break that one instead.

type RefPicSet added in v0.7.0

type RefPicSet struct {
	// StCurrBefore are pictures already decoded that this one may use, nearest
	// first; StCurrAfter are those that follow it in output order and precede
	// it in the stream.
	StCurrBefore []int32
	StCurrAfter  []int32
	// StFoll are short-term pictures to keep and not use.
	StFoll []int32
	// LtCurr and LtFoll are the long-term pictures, likewise split.
	LtCurr []LtPicture
	LtFoll []LtPicture
}

RefPicSet is what one coded picture needs kept, derived from what its slice stated: five lists, and the difference between them is the whole point.

⛔ Curr and Foll are NOT the same thing. A picture in Curr may be predicted from by this picture. A picture in Foll may not -- it is listed because a LATER picture will want it, and a decoder that dropped it would break that one instead. Both must be kept; only one may be used.

func Derive added in v0.7.0

func Derive(refs PictureRefs, poc int32, sps SPS) (RefPicSet, error)

Derive turns what a slice stated into the pictures a decoder must keep, given the order count of the picture that stated it.

The short-term entries are relative and become absolute here; the long-term ones are already counts, or the low bits of counts.

An order count that 8.3.1 forbids is refused with ErrPOCRange, never wrapped or clamped (a clamped 2^31-1 could be a real picture's count): PicOrderCntVal of every named picture is in -2^31 to 2^31-1, and DiffPicOrderCnt( current, picture ) in -2^15 to 2^15-1 (8-4).

func (RefPicSet) Count added in v0.7.0

func (s RefPicSet) Count() int

Count is how many pictures the set names in all, which is what a decoded picture buffer must hold for this picture.

type RefPics added in v0.14.0

type RefPics struct {
	StCurrBefore, StCurrAfter, StFoll []*DPBPicture
	LtCurr, LtFoll                    []*DPBPicture
}

RefPics are the pictures of the RPS lists that were found (or generated), in the order of the lists; an entry the buffer did not hold is nil.

type RefWeight added in v0.9.0

type RefWeight struct {
	LumaStated   bool
	LumaWeight   int32
	LumaOffset   int32
	ChromaStated bool
	// ChromaWeight and ChromaOffset are Cb then Cr.
	ChromaWeight [2]int32
	ChromaOffset [2]int32
}

RefWeight is how one reference picture is weighted, 7.4.7.3.

Stated says the slice gave a weight for that component. Where it did not, the weight is the neutral one -- 1 << the denominator -- and the offset is zero, which this fills in so that a caller never has to ask whether a field was present before using it.

type ResidualBlock added in v0.14.0

type ResidualBlock struct {
	Log2Size int
	CIdx     int
	// TransformSkip, ExplicitRDPCM and ExplicitRDPCMDir are the flags of the
	// block, 0 when absent.
	TransformSkip, ExplicitRDPCM, ExplicitRDPCMDir bool
	// Levels is TransCoeffLevel[ yC * size + xC ]: size = 1 << Log2Size.
	Levels []int32
}

ResidualBlock is one transform block of residual_coding( ): the syntax it states and TransCoeffLevel, the levels, in raster order within the block.

type ResidualInput added in v0.14.0

type ResidualInput struct {
	Log2Size int
	CIdx     int
	// Intra is CuPredMode == MODE_INTRA; PredModeIntra is IntraPredModeY for
	// luma and IntraPredModeC for chroma (used when Intra).
	Intra         bool
	PredModeIntra int
	// CuTransquantBypass is cu_transquant_bypass_flag.
	CuTransquantBypass bool
}

ResidualInput is what the coding unit tells residual_coding( ).

type ResidualTools added in v0.14.0

type ResidualTools struct {
	ChromaArrayType int
	// SignDataHiding is sign_data_hiding_enabled_flag; TransformSkip is
	// transform_skip_enabled_flag with Log2MaxTransformSkipSize.
	SignDataHiding           bool
	TransformSkip            bool
	Log2MaxTransformSkipSize int
	// The range extension's switches (7.3.2.2.2).
	TransformSkipContext     bool
	ImplicitRDPCM            bool
	ExplicitRDPCM            bool
	PersistentRiceAdaptation bool
	ExtendedPrecision        bool
	// BypassAlignment is cabac_bypass_alignment_enabled_flag.
	BypassAlignment bool
	// BitDepthY and BitDepthC give CoeffMinY, CoeffMaxY and the C pair
	// (7-27 to 7-30): 15 bits, or Max( 15, BitDepth + 6 ) when
	// extended_precision_processing_flag is set.
	BitDepthY, BitDepthC int
}

ResidualTools are the switches of the SPS and PPS that residual_coding( ) reads.

type SEIMessage added in v0.14.0

type SEIMessage struct {
	Type    uint32
	Payload []byte
}

SEIMessage is one sei_message( ) (7.3.5): its payloadType and the payloadSize bytes of its payload, unescaped.

func ParseSEI added in v0.14.0

func ParseSEI(u Unit) ([]SEIMessage, error)

ParseSEI reads the messages of a prefix or suffix SEI unit: sei_rbsp( ) of 7.3.2.4.

type SPS

type SPS struct {
	VPSID        uint8
	MaxSubLayers uint8
	// MaxDecPicBufferingMinus1, MaxNumReorderPics and MaxLatencyIncreasePlus1 are the
	// sps_max_dec_pic_buffering_minus1, sps_max_num_reorder_pics and
	// sps_max_latency_increase_plus1 of the highest sub-layer.
	MaxDecPicBufferingMinus1, MaxNumReorderPics, MaxLatencyIncreasePlus1 uint32
	ProfileSpace                                                         uint8
	Tier                                                                 uint8
	ProfileIDC                                                           uint8
	LevelIDC                                                             uint8
	ID                                                                   uint32
	ChromaFormat                                                         uint8
	SeparatePlanes                                                       bool
	CodedWidth                                                           uint32
	CodedHeight                                                          uint32
	WinLeft                                                              uint32
	WinRight                                                             uint32
	WinTop                                                               uint32
	WinBottom                                                            uint32
	Width                                                                uint32
	Height                                                               uint32
	BitDepthLuma                                                         uint8
	BitDepthChroma                                                       uint8
	Log2MaxPOCLSB                                                        uint8
	// ShortTermRefPicSets are the sets a slice may name instead of stating one
	// of its own, in the order the sequence lists them. A set may be written as
	// a difference from an earlier one, so the order is load-bearing.
	// SAOEnabled and TemporalMVPEnabled are not used here, but a slice header
	// cannot be read without them: both decide whether a field is present,
	// and a reader without them is misaligned from that point on.
	SAOEnabled         bool
	TemporalMVPEnabled bool

	// The block geometry, as the base-2 logarithms of sizes in luma samples
	// (7.4.3.2.1): MinCbLog2SizeY, CtbLog2SizeY, MinTbLog2SizeY, MaxTbLog2SizeY.
	Log2MinCbSize, Log2CtbSize   uint8
	Log2MinTbSize, Log2MaxTbSize uint8
	// MaxTransformHierarchyDepthInter and ...Intra are the depths of the
	// transform tree below a coding unit.
	MaxTransformHierarchyDepthInter, MaxTransformHierarchyDepthIntra uint8
	ScalingListEnabled                                               bool
	// ScalingList is sps_scaling_list_data( ), nil when the SPS states none (the
	// default lists then apply if ScalingListEnabled).
	ScalingList          *ScalingLists
	AMPEnabled           bool
	StrongIntraSmoothing bool
	// PCM is the pcm_enabled_flag group; its sample bit depths are in bits.
	PCM struct {
		Enabled                      bool
		BitDepthLuma, BitDepthChroma uint8
		Log2MinCbSize, Log2MaxCbSize uint8
		LoopFilterDisabled           bool
	}
	// Range is sps_range_extension; all false without one.
	Range RangeExtension

	ShortTermRefPicSets []ShortTermRPS
	// LongTermRefPics are the long-term pictures the sequence offers, named by
	// the low bits of their order count.
	LongTermRefPics []LongTermRefPic
	// LongTermRefPicsPresent says the sequence allows long-term pictures at
	// all. It is not the same as offering any: a sequence may allow them and
	// list none, and then a slice states its own.
	LongTermRefPicsPresent bool
}

SPS is what a sequence parameter set says about the pictures that follow.

Width and Height are what a player shows and what a container states: the coded size less the conformance window. Unlike H.264 the coded size is stated in luma samples directly rather than in macroblocks, so there is no multiply -- but the window still has to be taken off, and its offsets are in CHROMA units.

func ParseSPS

func ParseSPS(u Unit) (SPS, error)

ParseSPS reads a sequence parameter set.

type SaoParams added in v0.14.0

type SaoParams struct {
	// Type is SaoTypeIdx (0 none, 1 band, 2 edge), BandPos sao_band_position and
	// EoClass SaoEoClass.
	Type, BandPos, EoClass [3]uint8
	// Offset is SaoOffsetVal[ 1..4 ] (7-72): signed and scaled by log2OffsetScale.
	Offset [3][4]int32
}

SaoParams is the sample adaptive offset of one coding tree block, as 7.4.9.3 derives it (merged or stated), for the colour components 0 to 2.

type ScalingFactors added in v0.14.0

type ScalingFactors [4][6][]uint8

ScalingFactors is ScalingFactor[ sizeId ][ matrixId ] (7-44 to 7-51): the nTbS x nTbS matrix m[ x ][ y ] of 8.6.3 at index y * nTbS + x.

func ScalingFactorsOf added in v0.14.0

func ScalingFactorsOf(sps SPS, pps PPS) *ScalingFactors

ScalingFactorsOf is the scaling factors a picture uses: nil for the flat 16 of scaling_list_enabled_flag equal to 0, the PPS's lists when it states them, the SPS's, or the default lists (7.4.3.3.1).

type ScalingLists added in v0.14.0

type ScalingLists struct {
	List [4][6][64]uint8
	// DC is scaling_list_dc_coef_minus8 + 8 of [ sizeId - 2 ][ matrixId ].
	DC [2][6]uint8
}

ScalingLists is scaling_list_data( ) (7.3.4) with the inference of 7.4.5 done: ScalingList[ sizeId ][ matrixId ][ i ] and the DC coefficients of the 16x16 and 32x32 lists. Entries of sizeId 3 are filled for matrixId 0 and 3 only, as stated; Factors derives the chroma ones.

func DefaultScalingLists added in v0.14.0

func DefaultScalingLists() *ScalingLists

DefaultScalingLists is what scaling_list_enabled_flag means with no scaling_list_data( ).

func (*ScalingLists) Factors added in v0.14.0

func (s *ScalingLists) Factors() *ScalingFactors

Factors derives the scaling factors of the lists. The 32x32 chroma matrices (matrixId 1, 2, 4, 5) come from the 16x16 lists (7-50, 7-51).

type Scan added in v0.14.0

type Scan [][2]uint8

Scan is a scan order: Scan[i] is the ( x, y ) of the i-th position.

func DiagScan added in v0.14.0

func DiagScan(blkSize int) Scan

DiagScan is the up-right diagonal scan order of blkSize (6.5.3, 6-11).

func HorScan added in v0.14.0

func HorScan(blkSize int) Scan

HorScan is the horizontal scan order (6.5.4, 6-12).

func VerScan added in v0.14.0

func VerScan(blkSize int) Scan

VerScan is the vertical scan order (6.5.5, 6-13).

type Sequence added in v0.14.0

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

Sequence tracks what 8.1.3 needs across pictures: whether a picture is the first of the bitstream or follows an end of sequence unit, and so what NoRaslOutputFlag is, and whether the RASL pictures that follow an IRAP picture are to be skipped.

func (*Sequence) EndOfSequence added in v0.14.0

func (s *Sequence) EndOfSequence()

EndOfSequence is called with an end of sequence NAL unit.

func (*Sequence) Next added in v0.14.0

func (s *Sequence) Next(t UnitType) (first, noRaslOutput, skip bool)

Next classifies the first slice segment of a picture: whether it is the first picture of the bitstream, its NoRaslOutputFlag (meaningful for IRAP pictures), and whether it is a RASL picture associated with an IRAP picture that has NoRaslOutputFlag 1, which is not decoded and not output (8.1.3).

type ShortHeaderError

type ShortHeaderError struct {
	Unit  int
	Bytes int
}

ShortHeaderError means a unit is too short to hold the two bytes of header this format spends.

func (*ShortHeaderError) Error

func (e *ShortHeaderError) Error() string

type ShortTermRPS added in v0.4.0

type ShortTermRPS struct {
	Before []RefPic // negative deltas, nearest first: -1, -2, ...
	After  []RefPic // positive deltas, nearest first: 1, 2, ...
}

ShortTermRPS is a short-term reference picture set: the pictures a coded picture may still need, stated relative to its own order count.

The two halves are kept apart because the format states them apart and because they mean different things: Before holds pictures already decoded, After holds pictures that follow in order but precede this one in the stream. Both are ordered by distance, nearest first.

func (ShortTermRPS) Count added in v0.4.0

func (s ShortTermRPS) Count() int

Count is how many pictures the set names, which is the NumDeltaPocs the next set may predict from.

type SliceHeader added in v0.14.0

type SliceHeader struct {
	FirstSliceSegmentInPic bool
	NoOutputOfPriorPics    bool
	PPSID                  uint32
	Dependent              bool
	// SegmentAddress is slice_segment_address, in CTBs in raster scan; 0 for the
	// first segment of a picture.
	SegmentAddress uint32
	// SliceAddrRs is the address of the first coding tree block of the SLICE the
	// segment belongs to: its own for an independent segment, the one before's
	// for a dependent one (7.4.7.1). 6.4.1 compares it to tell slices apart.
	SliceAddrRs uint32

	// Type is slice_type. PicOutput is pic_output_flag (1 when absent) and
	// ColourPlaneID colour_plane_id.
	Type          SliceType
	PicOutput     bool
	ColourPlaneID uint8
	// POCLSB is slice_pic_order_cnt_lsb, 0 for an IDR picture.
	POCLSB uint32
	// Refs is what the slice says about the pictures it predicts from: the
	// short-term and long-term sets, list sizes and modification, collocated
	// picture, weights, merge candidates, and the SAO, mvd_l1_zero and
	// cabac_init flags.
	Refs PictureRefs

	// QPDelta is slice_qp_delta and SliceQP is SliceQpY (7-54).
	QPDelta int32
	SliceQP int32
	// CbQPOffset and CrQPOffset are slice_cb_qp_offset and slice_cr_qp_offset (0
	// when absent); CuChromaQPOffsetEnabled is cu_chroma_qp_offset_enabled_flag.
	CbQPOffset, CrQPOffset  int32
	CuChromaQPOffsetEnabled bool
	// The deblocking and loop filter fields, with the PPS's values where the
	// slice states none.
	DeblockingDisabled     bool
	BetaOffsetDiv2         int32
	TCOffsetDiv2           int32
	LoopFilterAcrossSlices bool

	// EntryPoints are entry_point_offset_minus1 + 1: byte counts of the subsets
	// of the slice segment data, COUNTING emulation prevention bytes (7.4.7.1).
	EntryPoints []uint32

	// HeaderBits is how many bits of Unit.Unescape()'s output the syntax elements
	// take, before byte_alignment( ) (the unit's two header bytes are not part
	// of the payload).
	HeaderBits int
	// HeaderElements is how many syntax elements the header holds before
	// byte_alignment( ), as HM's trace counts them.
	HeaderElements int
	// DataOffset is the offset of the slice segment data in Unit.Unescape()'s
	// output: the first byte after byte_alignment( ).
	DataOffset int
}

SliceHeader is slice_segment_header( ) (7.3.6.1) read in full, with the inferences of 7.4.7.1 applied, and where the slice segment data begins.

func ParseSliceSegmentHeaderFull added in v0.14.0

func ParseSliceSegmentHeaderFull(u Unit, sps SPS, pps PPS, prev *SliceHeader) (SliceHeader, error)

ParseSliceSegmentHeaderFull reads a slice segment header against the sequence and picture parameter sets it activates. prev is the header of the previous independent slice segment of the same picture, which a dependent segment takes everything from but its address, entry points and data offset (nil otherwise).

The activation is where PPS.Validate is called: a picture parameter set that does not fit its sequence is refused here, before any slice data is read.

type SliceSegmentHeader

type SliceSegmentHeader struct {
	First        bool // first_slice_segment_in_pic_flag
	Dependent    bool // only meaningful when First is false
	PPSID        uint32
	Type         SliceType
	TypeRead     bool
	RandomAccess bool // the unit type says this picture can stand alone
	// NoOutputOfPriorPics is stated only by a random access picture.
	NoOutputOfPriorPics bool
}

SliceSegmentHeader is the beginning of a slice segment: which picture it belongs to, whether it starts one, and -- when it starts one -- how that picture is coded.

⛔ Type is read only for a segment that BEGINS a picture, and TypeRead says so. Reaching the type of a later segment means first reading its address, whose width comes from the coding tree block size in the sequence set -- a field this package does not read yet. Reporting a type it had not read would be worse than saying it did not: a picture's type would then come from whichever segment was looked at.

func ParseSliceSegmentHeader

func ParseSliceSegmentHeader(u Unit, pps PPS) (SliceSegmentHeader, error)

ParseSliceSegmentHeader reads the beginning of a slice segment.

It needs the picture parameter set, which states whether a segment may depend on the one before it and how many bits the stream reserves before the slice type. Both change where the type sits, so a reader without them is misaligned from the first field that matters.

type SliceType

type SliceType uint8

SliceType is how a slice is coded. HEVC numbers them the other way round from H.264, and naming them here rather than reusing a number is the point.

const (
	SliceB SliceType = 0
	SliceP SliceType = 1
	SliceI SliceType = 2
)

The slice types.

func (SliceType) String

func (t SliceType) String() string

String names a slice type the way tools report picture types.

type SliceWalker added in v0.14.0

type SliceWalker struct {
	Pic *PictureState
	SPS SPS
	PPS PPS
	Hdr SliceHeader
	D   cabac.Decoder
	M   cabac.Model

	// IsCuQpDeltaCoded, CuQpDeltaVal and IsCuChromaQpOffsetCoded of 7.3.8.4.
	IsCuQpDeltaCoded, IsCuChromaQpOffsetCoded bool
	CuQpDeltaVal                              int32

	// CuQpOffsetCb and CuQpOffsetCr are set by chroma_qp_offset( ) (7.4.9.15); they
	// start at 0 for each slice segment (7.4.7.1).
	CuQpOffsetCb, CuQpOffsetCr int32
	// contains filtered or unexported fields
}

SliceWalker is the state of slice_segment_data( ): the engine, the context variables, and the picture and slice it decodes.

func (*SliceWalker) Available added in v0.14.0

func (w *SliceWalker) Available(xCurr, yCurr, xN, yN int) bool

Available is the derivation of 6.4.1: whether the block covering ( xN, yN ) is available to the block at ( xCurr, yCurr ).

type TUBlock added in v0.14.0

type TUBlock struct {
	X, Y  int
	Block ResidualBlock
}

TUBlock is one residual_coding( ) call of a transform unit: the location the syntax gives it and the levels read. Levels belong to the walker and are valid until the callback of the transform unit returns.

type TransformTreeFunc added in v0.14.0

type TransformTreeFunc func(w *SliceWalker, cu *CodingUnit) error

TransformTreeFunc decodes transform_tree( ) of a coding unit whose rqt_root_cbf is 1.

func TransformTreeDecoder added in v0.14.0

func TransformTreeDecoder(tu TransformUnitFunc) TransformTreeFunc

TransformTreeDecoder is transform_tree( ) (7.3.8.8) with transform_unit( ), delta_qp( ), chroma_qp_offset( ) and cross_comp_pred( ), as the TransformTreeFunc that CodingUnitDecoder takes. tu may be nil.

type TransformUnit added in v0.14.0

type TransformUnit struct {
	X0, Y0, XBase, YBase int
	Log2Size, Depth      int
	BlkIdx               int
	// CbfLuma is cbf_luma; CbfCb and CbfCr are the chroma flags this unit
	// uses ([ 1 ] is the second block of 4:2:2), the parent's for a 4x4 luma
	// block of 4:2:0 and 4:2:2.
	CbfLuma      bool
	CbfCb, CbfCr [2]bool
	// QpDelta is CuQpDeltaVal and CuQpOffsetCb and CuQpOffsetCr the chroma
	// offsets in force when the unit was read.
	QpDelta                    int32
	CuQpOffsetCb, CuQpOffsetCr int32
	// QpY is QpY of the coding unit (8.6.1) and QpPrime Qp'Y, Qp'Cb and Qp'Cr, the
	// qP the scaling of the unit's blocks uses; the chroma ones are 0 without chroma.
	QpY     int32
	QpPrime [3]int32
	// ResScaleVal is ResScaleVal[ 1 ] and [ 2 ] of cross-component prediction
	// (7-79, 7-80), 0 when absent.
	ResScaleVal [2]int32
	// Blocks are the residual blocks in the order they were read.
	Blocks []TUBlock
}

TransformUnit is transform_unit( ) (7.3.8.10) as it was read.

type TransformUnitFunc added in v0.14.0

type TransformUnitFunc func(w *SliceWalker, cu *CodingUnit, tu *TransformUnit) error

TransformUnitFunc receives each transform unit once it has been read.

type Unit

type Unit struct {
	Type UnitType
	// LayerID is which layer of a scalable stream this belongs to. A plain
	// stream states zero throughout, and a decoder that ignored it would mix the
	// layers of one that does not.
	LayerID uint8
	// TemporalID is TemporalId, the sub-layer: nuh_temporal_id_plus1 minus 1, so 0
	// for the base layer. A stream can be thinned by dropping the higher ones,
	// which is what it is for.
	TemporalID uint8
	Payload    []byte
	// Tag is the caller's: a decoder carries the Tag of the first slice segment of a picture
	// to that picture's Output (which is how a container's timestamp finds the picture it
	// belongs to, however the pictures are reordered). Nothing else reads it.
	Tag uint64
}

Unit is one NAL unit: its two header bytes read, and its payload still escaped.

Payload is a window into the caller's bytes and is not copied.

func SplitAnnexB

func SplitAnnexB(data []byte) ([]Unit, error)

SplitAnnexB finds the NAL units of a byte stream and reads each one's header.

func SplitLengthPrefixed

func SplitLengthPrefixed(data []byte, lengthSize int) ([]Unit, error)

SplitLengthPrefixed finds the units of the form an MP4 sample carries, where each is preceded by its length in lengthSize bytes, and reads each one's header.

lengthSize comes from the hvcC record.

func (Unit) Unescape

func (u Unit) Unescape() []byte

Unescape undoes the escaping inside this unit's payload.

type UnitType

type UnitType uint8

UnitType is what a NAL unit holds. Only the ones this package acts on are named; the rest travel as their number.

const (
	UnitTrailN    UnitType = 0
	UnitTrailR    UnitType = 1
	UnitTSAN      UnitType = 2
	UnitTSAR      UnitType = 3
	UnitSTSAN     UnitType = 4
	UnitSTSAR     UnitType = 5
	UnitRADLN     UnitType = 6
	UnitRADLR     UnitType = 7
	UnitRASLN     UnitType = 8
	UnitRASLR     UnitType = 9
	UnitBLAWLP    UnitType = 16
	UnitBLAWRADL  UnitType = 17
	UnitBLANLP    UnitType = 18
	UnitIDRWRADL  UnitType = 19
	UnitIDRNLP    UnitType = 20
	UnitCRA       UnitType = 21
	UnitVPS       UnitType = 32
	UnitSPS       UnitType = 33
	UnitPPS       UnitType = 34
	UnitAUD       UnitType = 35
	UnitEOS       UnitType = 36
	UnitEOB       UnitType = 37
	UnitFD        UnitType = 38
	UnitPrefixSEI UnitType = 39
	UnitSuffixSEI UnitType = 40
)

The unit types a reader has to tell apart.

⛔ A picture's type is not one flag here as it is in H.264. HEVC names sixteen kinds of slice segment, and which of them can be decoded without anything before it is what a sample table needs: the ones from BLA_W_LP to CRA are exactly that set, and IsRandomAccess is where the boundary is written down rather than scattered.

func (UnitType) IsBLA added in v0.3.0

func (t UnitType) IsBLA() bool

IsBLA says the stream was spliced here. A broken link picture is decoded as a random access point whose leading pictures may refer to material that is not there, and its order count restarts: the high bits are taken as zero however far the count had got.

func (UnitType) IsIDR added in v0.3.0

func (t UnitType) IsIDR() bool

IsIDR says the picture starts a new coded video sequence and states no order of its own: an IDR carries no slice_pic_order_cnt_lsb at all, and its count is zero by definition.

func (UnitType) IsLeading added in v0.3.0

func (t UnitType) IsLeading() bool

IsLeading says the picture precedes its random access point in output order while following it in decode order -- RADL if it can be decoded, RASL if it refers to material before the access point and so may not be.

func (UnitType) IsRandomAccess

func (t UnitType) IsRandomAccess() bool

IsRandomAccess says whether a picture of this type can be decoded with nothing before it, which is what a sample table calls a sync sample.

func (UnitType) IsSliceSegment

func (t UnitType) IsSliceSegment() bool

IsSliceSegment says whether a unit carries coded picture data.

func (UnitType) IsSubLayerNonReference added in v0.3.0

func (t UnitType) IsSubLayerNonReference() bool

IsSubLayerNonReference says no picture of the same sub-layer uses this one for prediction, which is what makes a stream thinnable: these can be dropped without disturbing anything left. The even types below 15 are the ones.

Directories

Path Synopsis
internal
cabac
Package cabac is the arithmetic decoding engine of clause 9.3 of ITU-T H.265 (V11) (01/2026): initialisation of the engine (9.3.2.6), of the context variables (9.3.2.2), the decoding of a decision (9.3.4.3.2), of a bypass bin (9.3.4.3.4) and before termination (9.3.4.3.5), and the binarisations the slice data needs first (9.3.3).
Package cabac is the arithmetic decoding engine of clause 9.3 of ITU-T H.265 (V11) (01/2026): initialisation of the engine (9.3.2.6), of the context variables (9.3.2.2), the decoding of a decision (9.3.4.3.2), of a bypass bin (9.3.4.3.4) and before termination (9.3.4.3.5), and the binarisations the slice data needs first (9.3.3).
cabac/cabactest
Package cabactest is the arithmetic encoder of clause 9.3.5 (informative), for tests that need a bitstream the decoder did not produce: a syntax writer drives it with the same bins and contexts the decoder will ask for, and the decoder must read the bins back.
Package cabactest is the arithmetic encoder of clause 9.3.5 (informative), for tests that need a bitstream the decoder did not produce: a syntax writer drives it with the same bins and contexts the decoder will ask for, and the decoder must read the bins back.
tools
bench module

Jump to

Keyboard shortcuts

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