diff --git a/internal/decoder/decoder.go b/internal/decoder/decoder.go index a78200c..3285129 100644 --- a/internal/decoder/decoder.go +++ b/internal/decoder/decoder.go @@ -130,11 +130,17 @@ func (d *Decoder) finishPicture() []*frame.Picture { if d.grid != nil { pic.Motion = d.grid.motion() } - if d.buffer != nil && d.lastHdr != nil { - d.buffer.store(pic, d.lastHdr) + var out []*frame.Picture + if d.buffer != nil && d.lastHdr != nil && d.buffer.store(pic, d.lastHdr) { + // Memory management control operation 5 ends the coded video sequence + // as far as output is concerned, as an IDR picture does (Annex C.4.4): + // the pictures before it all come out first, and its own order count + // restarts at 0, below the ones they carried. + out = d.bump(true) + pic.POC = 0 } d.pending = append(d.pending, pic) - return d.bump(false) + return append(out, d.bump(false)...) } func (d *Decoder) handleUnit(ebsp []byte) ([]*frame.Picture, error) { @@ -234,6 +240,7 @@ func (d *Decoder) decodeSlice(u nal.Unit) ([]*frame.Picture, error) { if hdr.IDR { d.buffer.refs = d.buffer.refs[:0] } + d.buffer.fillGap(sps, hdr) d.sps = sps d.cur = frame.NewPicture(sps.PicWidthInMbs(), sps.FrameHeightInMbs()) d.cur.FrameNum = hdr.FrameNum diff --git a/internal/decoder/dpb.go b/internal/decoder/dpb.go index 4491943..60bf823 100644 --- a/internal/decoder/dpb.go +++ b/internal/decoder/dpb.go @@ -14,6 +14,11 @@ type refFrame struct { picNum int longTerm bool longTermIdx int + // nonExisting marks a frame inferred for a gap in frame_num (section + // 8.2.5.2). It holds a reference slot and a frame number but has no + // picture of its own: pic is borrowed from the nearest real reference so + // that a stream which wrongly refers to it still decodes. + nonExisting bool } type dpb struct { @@ -25,6 +30,16 @@ type dpb struct { prevPicOrderCntLsb int prevFrameNumOffset int prevFrameNum uint32 + + // prevRefFrameNum is PrevRefFrameNum of section 7.4.3: the frame_num of the + // previous reference picture, 0 after one with operation 5. It exists once + // a reference picture has been stored. + prevRefFrameNum uint32 + haveRef bool + + // curTop and curBottom are TopFieldOrderCnt and BottomFieldOrderCnt of the + // picture whose order count was derived last. + curTop, curBottom int } func newDPB(sps *syntax.SPS) *dpb { @@ -43,7 +58,25 @@ func (b *dpb) clear() { b.prevFrameNum = 0 } +// computePOC returns PicOrderCnt of the frame, Min(TopFieldOrderCnt, +// BottomFieldOrderCnt) (8-1), and keeps both counts for the picture so that +// operation 5 can rebase them (section 8.2.1, tempPicOrderCnt). func (b *dpb) computePOC(sps *syntax.SPS, hdr *syntax.SliceHeader) int { + top := b.topPOC(sps, hdr) + bottom := top + switch sps.PicOrderCntType { + case 0: // (8-5) for a frame + bottom = top + int(hdr.DeltaPicOrderCntBottom) + case 1: // (8-10) + bottom = top + int(sps.OffsetForTopToBottomField) + int(hdr.DeltaPicOrderCnt[1]) + } + b.curTop, b.curBottom = top, bottom + return min(top, bottom) +} + +// topPOC derives TopFieldOrderCnt (8.2.1.1 to 8.2.1.3) and advances the +// previous-picture state. +func (b *dpb) topPOC(sps *syntax.SPS, hdr *syntax.SliceHeader) int { switch sps.PicOrderCntType { case 0: maxLsb := int(sps.MaxPicOrderCntLsb()) @@ -308,30 +341,101 @@ func moveToIndex(list []*refFrame, target *refFrame, idx int) []*refFrame { return out } -func (b *dpb) store(pic *frame.Picture, hdr *syntax.SliceHeader) { +// store marks the decoded picture as a reference. It reports whether the +// picture carried memory_management_control_operation 5, after which the +// caller must treat everything decoded before it as outputtable and give the +// picture the picture order count 0 (H.264 section 8.2.1, "tempPicOrderCnt"). +func (b *dpb) store(pic *frame.Picture, hdr *syntax.SliceHeader) (mmco5 bool) { if hdr.NalRefIDC == 0 { - return + return false } + b.prevRefFrameNum, b.haveRef = hdr.FrameNum, true if hdr.IDR { b.refs = b.refs[:0] entry := &refFrame{pic: pic, frameNum: hdr.FrameNum, longTerm: hdr.LongTermReference} pic.LongTerm = hdr.LongTermReference b.refs = append(b.refs, entry) b.updatePicNums(hdr.FrameNum) - return + return false } if hdr.AdaptiveRefPicMarking { entry := &refFrame{pic: pic, frameNum: hdr.FrameNum} b.applyMMCO(hdr, entry) + if hasMMCO5(hdr) { + // Section 7.4.3: after operation 5 the picture is inferred to have + // had frame_num 0, and section 8.2.1 restarts the order count + // from it, so the next picture's FrameNumWrap, FrameNumOffset and + // PicOrderCntMsb are all taken against 0. + entry.frameNum = 0 + pic.FrameNum = 0 + b.prevRefFrameNum = 0 + // 8.2.1: tempPicOrderCnt = Min(top, bottom) is taken off both + // counts, and 8.2.1.1 then starts the next picture from + // PicOrderCntMsb 0 and the rebased TopFieldOrderCnt. + b.prevPicOrderCntMsb = 0 + b.prevPicOrderCntLsb = b.curTop - min(b.curTop, b.curBottom) + b.prevFrameNumOffset = 0 + b.prevFrameNum = 0 + mmco5 = true + } b.refs = append(b.refs, entry) - b.updatePicNums(hdr.FrameNum) + b.updatePicNums(entry.frameNum) b.enforceCapacity() - return + return mmco5 } b.refs = append(b.refs, &refFrame{pic: pic, frameNum: hdr.FrameNum}) b.updatePicNums(hdr.FrameNum) b.slidingWindow() b.enforceCapacity() + return false +} + +// fillGap runs the decoding process for gaps in frame_num (section 8.2.5.2). +// When the slice's frame_num is neither PrevRefFrameNum nor the value after it, +// frames were lost or, with gaps_in_frame_num_value_allowed_flag set, left out +// on purpose (temporal scalability, sub-sequences). Each missing frame number +// becomes a "non-existing" short-term reference frame, so that the sliding +// window moves as the encoder's did and the frame numbers the slice refers to +// still resolve to the right pictures. +// +// Only the last max_num_ref_frames of them can survive the sliding window, so +// a stream cannot make this allocate more than that however wide the gap. +func (b *dpb) fillGap(sps *syntax.SPS, hdr *syntax.SliceHeader) { + if hdr.IDR || !b.haveRef || !sps.GapsInFrameNumValueAllowed || len(b.refs) == 0 { + return + } + max := b.maxFrameNum + next := (b.prevRefFrameNum + 1) % max + if hdr.FrameNum == b.prevRefFrameNum || hdr.FrameNum == next { + return + } + gap := int((hdr.FrameNum + max - next) % max) + donor := b.refs[len(b.refs)-1].pic + for i, fn := 0, next; i < gap; i, fn = i+1, (fn+1)%max { + if sps.PicOrderCntType != 0 { + // The order count of the following picture is measured from the + // last frame number seen, including these. + if fn < b.prevFrameNum { + b.prevFrameNumOffset += int(max) + } + b.prevFrameNum = fn + } + if i >= gap-b.maxNumRefs { + b.refs = append(b.refs, &refFrame{pic: donor, frameNum: fn, nonExisting: true}) + b.updatePicNums(fn) + b.slidingWindow() + } + } + b.prevRefFrameNum = (hdr.FrameNum + max - 1) % max +} + +func hasMMCO5(hdr *syntax.SliceHeader) bool { + for _, m := range hdr.MMCOs { + if m.Op == 5 { + return true + } + } + return false } func (b *dpb) enforceCapacity() { @@ -362,7 +466,9 @@ func (b *dpb) applyMMCO(hdr *syntax.SliceHeader, current *refFrame) { if r := b.shortTermByPicNum(pn); r != nil { r.longTerm = true r.longTermIdx = int(m.LongTermFrameIdx) - r.pic.LongTerm = true + if !r.nonExisting { + r.pic.LongTerm = true + } } case 4: max := int(m.MaxLongTermFrameIdxPlus1) - 1 diff --git a/internal/decoder/dpb_test.go b/internal/decoder/dpb_test.go index d2d6c0f..05109e7 100644 --- a/internal/decoder/dpb_test.go +++ b/internal/decoder/dpb_test.go @@ -829,3 +829,212 @@ func TestSlidingWindowStillAppliesWithoutAdaptiveMarking(t *testing.T) { } } } + +func TestStoreMMCO5RestartsFrameNumAndOrderCount(t *testing.T) { + old := newRef(7, false, 0) + b := &dpb{ + maxNumRefs: 4, maxFrameNum: 16, refs: []*refFrame{old}, + prevPicOrderCntMsb: 32, prevPicOrderCntLsb: 5, prevFrameNumOffset: 16, prevFrameNum: 9, + } + pic := frame.NewPicture(1, 1) + hdr := &syntax.SliceHeader{ + NalRefIDC: 1, FrameNum: 9, AdaptiveRefPicMarking: true, + MMCOs: []syntax.MMCO{{Op: 5}}, + } + + if !b.store(pic, hdr) { + t.Fatal("store did not report operation 5") + } + + // Section 7.4.3: the picture is inferred to have had frame_num 0; the + // operation also emptied the buffer, so it is alone in it. + if len(b.refs) != 1 || b.refs[0].pic != pic || b.refs[0].frameNum != 0 || pic.FrameNum != 0 { + t.Fatalf("refs = %+v, want only the new picture with frame number 0", b.refs) + } + // Section 8.2.1: the next picture's order count and FrameNumOffset are + // measured from it. + if b.prevPicOrderCntMsb != 0 || b.prevPicOrderCntLsb != 0 || b.prevFrameNumOffset != 0 || b.prevFrameNum != 0 || b.prevRefFrameNum != 0 { + t.Fatalf("state after operation 5: %+v", b) + } +} + +func TestStoreWithoutMMCO5ReportsNothing(t *testing.T) { + b := &dpb{maxNumRefs: 4, maxFrameNum: 16} + for name, hdr := range map[string]*syntax.SliceHeader{ + "non-reference": {NalRefIDC: 0, FrameNum: 3}, + "idr": {NalRefIDC: 1, IDR: true}, + "sliding": {NalRefIDC: 1, FrameNum: 1}, + "adaptive": {NalRefIDC: 1, FrameNum: 2, AdaptiveRefPicMarking: true, MMCOs: []syntax.MMCO{{Op: 4, MaxLongTermFrameIdxPlus1: 1}}}, + } { + if b.store(frame.NewPicture(1, 1), hdr) { + t.Errorf("%s: reported operation 5", name) + } + } + if b.prevRefFrameNum != 2 || !b.haveRef { + t.Errorf("PrevRefFrameNum = %d (have %v), want 2: the non-reference picture must not move it", b.prevRefFrameNum, b.haveRef) + } +} + +func gapState(maxNumRefs int, maxFrameNum uint32, prevRef uint32, frameNums ...uint32) *dpb { + b := &dpb{maxNumRefs: maxNumRefs, maxFrameNum: maxFrameNum, prevRefFrameNum: prevRef, haveRef: true} + for _, fn := range frameNums { + b.refs = append(b.refs, newRef(fn, false, 0)) + } + return b +} + +func frameNums(b *dpb) []uint32 { + var out []uint32 + for _, r := range b.refs { + out = append(out, r.frameNum) + } + return out +} + +func equalFrameNums(a, b []uint32) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func TestFillGapInsertsNonExistingFrames(t *testing.T) { + sps := &syntax.SPS{GapsInFrameNumValueAllowed: true} + cases := []struct { + name string + b *dpb + sps *syntax.SPS + hdr *syntax.SliceHeader + want []uint32 + wantPrev uint32 + }{ + {"next frame number is no gap", gapState(3, 16, 5, 5), sps, &syntax.SliceHeader{FrameNum: 6}, []uint32{5}, 5}, + {"same frame number is no gap", gapState(3, 16, 5, 5), sps, &syntax.SliceHeader{FrameNum: 5}, []uint32{5}, 5}, + {"gap of three, window keeps the last three", gapState(3, 16, 5, 4, 5), sps, &syntax.SliceHeader{FrameNum: 9}, []uint32{6, 7, 8}, 8}, + {"gap of one", gapState(4, 16, 5, 5), sps, &syntax.SliceHeader{FrameNum: 7}, []uint32{5, 6}, 6}, + {"gap across the wrap", gapState(4, 16, 14, 14), sps, &syntax.SliceHeader{FrameNum: 2}, []uint32{14, 15, 0, 1}, 1}, + {"gaps not allowed", gapState(3, 16, 5, 5), &syntax.SPS{}, &syntax.SliceHeader{FrameNum: 9}, []uint32{5}, 5}, + {"idr", gapState(3, 16, 5, 5), sps, &syntax.SliceHeader{FrameNum: 9, IDR: true}, []uint32{5}, 5}, + {"no reference seen yet", &dpb{maxNumRefs: 3, maxFrameNum: 16}, sps, &syntax.SliceHeader{FrameNum: 9}, nil, 0}, + {"empty buffer", &dpb{maxNumRefs: 3, maxFrameNum: 16, haveRef: true}, sps, &syntax.SliceHeader{FrameNum: 9}, nil, 0}, + } + for _, c := range cases { + c.b.fillGap(c.sps, c.hdr) + if got := frameNums(c.b); !equalFrameNums(got, c.want) { + t.Errorf("%s: frame numbers %v, want %v", c.name, got, c.want) + } + if c.b.prevRefFrameNum != c.wantPrev { + t.Errorf("%s: PrevRefFrameNum %d, want %d", c.name, c.b.prevRefFrameNum, c.wantPrev) + } + } +} + +func TestFillGapMarksFramesNonExistingAndBoundsThem(t *testing.T) { + b := gapState(4, 65536, 10, 10) + b.fillGap(&syntax.SPS{GapsInFrameNumValueAllowed: true}, &syntax.SliceHeader{FrameNum: 60000}) + if len(b.refs) != 4 { + t.Fatalf("%d reference frames after a gap of 59989, want max_num_ref_frames (4)", len(b.refs)) + } + for _, r := range b.refs { + if !r.nonExisting { + t.Errorf("frame %d is not marked non-existing", r.frameNum) + } + } + // A non-existing frame converted to long term must not mark the real + // picture it borrows. + donor := b.refs[0].pic + b.applyMMCO(&syntax.SliceHeader{FrameNum: 60000, MMCOs: []syntax.MMCO{{Op: 3, DifferenceOfPicNumsMinus1: 0, LongTermFrameIdx: 1}}}, newCurrent()) + if donor.LongTerm { + t.Error("operation 3 on a non-existing frame marked the borrowed picture long term") + } +} + +func TestFillGapKeepsTheOrderCountCounters(t *testing.T) { + // Order count type 2 detects a wrap by frame_num going down; the gap's + // frame numbers have to count, or the wrap inside the gap is lost. + b := gapState(2, 16, 14, 14) + b.prevFrameNum = 14 + b.fillGap(&syntax.SPS{GapsInFrameNumValueAllowed: true, PicOrderCntType: 2}, &syntax.SliceHeader{FrameNum: 3}) + if b.prevFrameNumOffset != 16 || b.prevFrameNum != 2 { + t.Fatalf("offset %d prevFrameNum %d, want 16 and 2", b.prevFrameNumOffset, b.prevFrameNum) + } +} + +func TestFinishPictureWithMMCO5OutputsEarlierPicturesFirst(t *testing.T) { + d := New() + d.maxReorder = 8 + d.buffer = &dpb{maxNumRefs: 4, maxFrameNum: 16} + earlier := []*frame.Picture{frame.NewPicture(1, 1), frame.NewPicture(1, 1)} + earlier[0].POC, earlier[1].POC = 40, 38 + d.pending = append(d.pending, earlier...) + cur := frame.NewPicture(1, 1) + cur.POC = 44 + d.cur = cur + d.lastHdr = &syntax.SliceHeader{NalRefIDC: 1, FrameNum: 5, AdaptiveRefPicMarking: true, MMCOs: []syntax.MMCO{{Op: 5}}} + + out := d.finishPicture() + + if len(out) != 2 || out[0] != earlier[1] || out[1] != earlier[0] { + t.Fatalf("output %v, want the two earlier pictures in order count order", out) + } + if len(d.pending) != 1 || d.pending[0] != cur || cur.POC != 0 { + t.Fatalf("pending %v, picture order count %d: want the operation 5 picture alone, at 0", d.pending, cur.POC) + } +} + +func TestComputePOCIsTheMinimumOfTopAndBottom(t *testing.T) { + sps0 := &syntax.SPS{PicOrderCntType: 0, Log2MaxPicOrderCntLsbMinus4: 4} + sps1 := &syntax.SPS{PicOrderCntType: 1, OffsetForTopToBottomField: -4, OffsetForRefFrame: []int32{2}} + cases := []struct { + name string + sps *syntax.SPS + hdr *syntax.SliceHeader + want int + top, bottom int + }{ + {"type 0, bottom before top", sps0, &syntax.SliceHeader{NalRefIDC: 1, PicOrderCntLsb: 10, DeltaPicOrderCntBottom: -3}, 7, 10, 7}, + {"type 0, bottom after top", sps0, &syntax.SliceHeader{NalRefIDC: 1, PicOrderCntLsb: 10, DeltaPicOrderCntBottom: 2}, 10, 10, 12}, + {"type 1, offset_for_top_to_bottom_field", sps1, &syntax.SliceHeader{NalRefIDC: 1, FrameNum: 1, DeltaPicOrderCnt: [2]int32{1, -1}}, -2, 3, -2}, + } + for _, c := range cases { + b := &dpb{maxFrameNum: 16} + if got := b.computePOC(c.sps, c.hdr); got != c.want || b.curTop != c.top || b.curBottom != c.bottom { + t.Errorf("%s: POC %d top %d bottom %d, want %d %d %d", c.name, got, b.curTop, b.curBottom, c.want, c.top, c.bottom) + } + } +} + +// 8.2.1: after operation 5 both counts are rebased by Min(top, bottom), and +// 8.2.1.1 starts the next picture from PicOrderCntMsb 0 and the rebased +// TopFieldOrderCnt, which is not 0 when the bottom field comes first. +func TestMMCO5RebasesPrevPicOrderCntLsbWithNegativeBottomDelta(t *testing.T) { + sps := &syntax.SPS{PicOrderCntType: 0, Log2MaxPicOrderCntLsbMinus4: 4} + for _, c := range []struct { + delta int32 + wantLsb int + }{{-3, 3}, {0, 0}, {2, 0}} { + b := &dpb{maxNumRefs: 4, maxFrameNum: 16} + hdr := &syntax.SliceHeader{ + NalRefIDC: 1, FrameNum: 5, PicOrderCntLsb: 10, DeltaPicOrderCntBottom: c.delta, + AdaptiveRefPicMarking: true, MMCOs: []syntax.MMCO{{Op: 5}}, + } + pic := frame.NewPicture(1, 1) + pic.POC = b.computePOC(sps, hdr) + if !b.store(pic, hdr) { + t.Fatal("operation 5 not reported") + } + if b.prevPicOrderCntMsb != 0 || b.prevPicOrderCntLsb != c.wantLsb { + t.Errorf("delta %d: prevMsb %d prevLsb %d, want 0 and %d", c.delta, b.prevPicOrderCntMsb, b.prevPicOrderCntLsb, c.wantLsb) + } + // The next picture, lsb 4: measured from the rebased state. + next := &syntax.SliceHeader{NalRefIDC: 1, FrameNum: 1, PicOrderCntLsb: 4} + if got := b.computePOC(sps, next); got != 4 { + t.Errorf("delta %d: next picture POC %d, want 4", c.delta, got) + } + } +}