threers-codec 0.0.12

Pure-Rust media codecs: H.264/HEVC/VP9 encoders, H.264/HEVC/VP9/AV1 decoders, AAC/MP3/Opus/Vorbis/FLAC/WAV decoders, AAC-LC and MP3 encoders, MP4/WebM/Matroska/Ogg, GIF/APNG, captions, and VideoToolbox acceleration on macOS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
//! A from-scratch H.264 / AVC decoder.
//!
//! Baseline, Main and High profiles, frame, field and MBAFF coded —
//! CAVLC and CABAC, I/P/B slices, multiple slices, 8×8 transforms, scaling
//! matrices, weighted prediction (explicit and implicit), spatial and
//! temporal direct, long-term references and every memory management
//! operation, 4:2:0, 4:2:2 (High 4:2:2) or monochrome, 8 bits and up. Not
//! supported, and refused with an error rather than decoded wrongly:
//! 4:4:4, slice groups (FMO), data partitioning, SP/SI slices and lossless
//! transform bypass.
//!
//! Feed it NAL units with [`H264Decoder::decode_nal`]; each finished picture
//! comes out of [`H264Decoder::finish_picture`] (called for you when a new
//! picture starts) tagged with its picture order count.

#[cfg(feature = "decode")]
pub mod cabac_init;
#[cfg(feature = "decode")]
pub mod cavlc;
#[cfg(feature = "decode")]
pub mod deblock;
#[cfg(feature = "decode")]
pub mod inter;
#[cfg(feature = "decode")]
pub mod intra;
// Parameter sets parse without the decoder: the MP4 muxer reads them.
#[cfg_attr(not(feature = "decode"), allow(dead_code))]
pub mod params;
#[cfg(feature = "decode")]
pub mod parse_cabac;
#[cfg(feature = "decode")]
pub mod parse_cavlc;
#[cfg(feature = "decode")]
pub mod slice;
// Parameter sets parse without the decoder: the MP4 muxer reads them.
#[cfg_attr(not(feature = "decode"), allow(dead_code))]
pub mod tables;
#[cfg(feature = "decode")]
pub mod types;

#[cfg(feature = "decode")]
use std::collections::BTreeMap;
#[cfg(feature = "decode")]
use std::sync::{Arc, Mutex};

#[cfg(feature = "decode")]
use self::cavlc::CavlcTables;
#[cfg(feature = "decode")]
use self::params::{Mmco, Pps, SliceHeader, SliceType, Sps};
#[cfg(feature = "decode")]
use self::slice::{CurPic, SliceDeblock, SliceDec};
#[cfg(feature = "decode")]
use self::types::{MbInfo, RefData, RefEntry, RefPic};
#[cfg(feature = "decode")]
use super::bits::unescape;
#[cfg(feature = "decode")]
use super::jobs::{caught, Jobs, Slot};
#[cfg(feature = "decode")]
use super::picture::{ChromaFormat, ColorInfo, DecodedFrame, Plane};

/// Decoding errors are messages naming what was malformed or unsupported.
#[cfg(feature = "decode")]
pub type Result<T> = std::result::Result<T, String>;

#[cfg(feature = "decode")]
/// A decoded picture and where it goes in display order.
#[derive(Debug, Clone)]
pub struct H264Picture {
    /// The picture, cropped to its display size.
    pub frame: DecodedFrame,
    /// `PicOrderCnt`. Resets at every IDR picture (and memory management
    /// operation 5), so it orders pictures only within one such period.
    pub poc: i32,
    /// Whether this picture is an IDR picture, which starts a new POC
    /// period.
    pub idr: bool,
}

#[cfg(feature = "decode")]
/// The picture (frame or field) being decoded, with what marking needs
/// once it is done.
struct Current {
    pic: CurPic,
    sps: Sps,
    /// 1 top field, 2 bottom field, 3 frame.
    structure: u8,
    /// `MbaffFrameFlag`.
    mbaff: bool,
    /// Index of its frame store in the DPB.
    store: usize,
    /// Second field of a frame whose first field is in `store`.
    second_field: bool,
    idr: bool,
    nal_ref_idc: u32,
    frame_num: u32,
    long_term_reference: bool,
    mmcos: Option<Vec<Mmco>>,
    /// For detecting the first slice of the next picture.
    pps_id: u32,
    poc_lsb: u32,
    poc_msb: i32,
    frame_num_offset: i32,
    /// With threads, the slices for its job to reconstruct.
    work: Vec<SliceWork>,
}

/// A slice whose header is read and whose data is not.
#[cfg(feature = "decode")]
struct SliceWork {
    rbsp: Vec<u8>,
    hdr: SliceHeader,
    pps: Pps,
    refs: [Vec<RefEntry>; 2],
    slice_num: u32,
}

/// The state shared with picture jobs.
#[cfg(feature = "decode")]
struct Threads {
    jobs: Arc<Jobs>,
    /// Finished pictures in decode order; `None` for one that failed.
    finished: Arc<Mutex<BTreeMap<u64, Option<H264Picture>>>>,
    /// The first failure in decode order.
    error: Arc<Mutex<Option<(u64, String)>>>,
    next_take: u64,
    next_job: u64,
    /// Pictures still go to jobs. A field or MBAFF stream stops that: a
    /// second field reads the first from the store they share.
    active: bool,
}

/// A hardware back end for [`H264Decoder`].
///
/// The decoder keeps doing everything but reconstruction: it parses the
/// parameter sets and slice headers, numbers and marks references, builds
/// the reference lists and orders output. Each slice is handed over with all
/// of that, the accelerator reconstructs the picture, and when a frame is
/// complete the decoder asks it for the samples. This is the shape of VAAPI
/// and the other "the driver does not parse" APIs.
#[cfg(feature = "decode")]
pub trait H264Accel {
    /// Decode one slice of the current picture.
    fn slice(&mut self, s: &AccelSlice<'_>) -> Result<()>;
    /// The current picture (frame or field) has had all its slices.
    fn end_picture(&mut self) -> Result<()>;
    /// The samples of the frame in store `store_id`, cropped as `sps` says.
    fn frame(&mut self, store_id: u32, sps: &Sps) -> Result<DecodedFrame>;
}

/// Everything an [`H264Accel`] is told about one slice.
#[cfg(feature = "decode")]
pub struct AccelSlice<'a> {
    /// The NAL unit as coded: header byte included, emulation prevention in.
    pub nal: &'a [u8],
    /// The active sequence parameter set.
    pub sps: &'a Sps,
    /// The active picture parameter set.
    pub pps: &'a Pps,
    /// The parsed slice header (`data_bit_offset` is where slice data starts, in RBSP bits after the header byte).
    pub hdr: &'a SliceHeader,
    /// The first slice of a new picture.
    pub first: bool,
    /// The frame store the picture is decoded into (shared by both fields).
    pub store_id: u32,
    /// 1 top field, 2 bottom field, 3 frame.
    pub structure: u8,
    /// `TopFieldOrderCnt`, `BottomFieldOrderCnt` of the picture.
    pub field_poc: [i32; 2],
    /// The frame stores, with their reference marking.
    pub dpb: &'a [RefPic],
    /// `RefPicList0` and `RefPicList1`, entries indexing `dpb`.
    pub refs: &'a [Vec<RefEntry>; 2],
}

/// An H.264 decoder fed one NAL unit at a time ([`decode_nal`](Self::decode_nal)).
///
/// Most callers want [`NativeDecoder`](crate::decode::NativeDecoder), which
/// unpacks MP4 samples and orders the output; this is the layer below it.
#[cfg(feature = "decode")]
pub struct H264Decoder {
    spss: Vec<Option<Sps>>,
    ppss: Vec<Option<Pps>>,
    tables: Arc<CavlcTables>,
    cur: Option<Current>,
    /// Frame stores: references, plus the frame whose first field waits for
    /// its pair.
    dpb: Vec<RefPic>,
    next_id: u32,
    max_lt_idx: Option<u32>,
    prev_poc_msb: i32,
    prev_poc_lsb: i32,
    prev_frame_num_offset: i32,
    prev_frame_num: u32,
    prev_ref_frame_num: u32,
    prev_had_mmco5: bool,
    /// A decoded first field waiting for its pair: `(store id, structure,
    /// frame_num, reference)`.
    pending: Option<(u32, u8, u32, bool)>,
    /// Size of the last activated SPS, to notice a resolution change.
    active_size: Option<(u32, u32)>,
    done: Vec<H264Picture>,
    accel: Option<Box<dyn H264Accel>>,
    /// The first error an accelerator reported where nothing could return it.
    accel_error: Option<String>,
    /// The current picture has had a slice handed to the accelerator.
    accel_started: bool,
    threads: Option<Threads>,
}

#[cfg(feature = "decode")]
impl Default for H264Decoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "decode")]
fn empty_planes() -> [Plane; 3] {
    [
        Plane::new(0, 0, 0),
        Plane::new(0, 0, 0),
        Plane::new(0, 0, 0),
    ]
}

#[cfg(feature = "decode")]
impl H264Decoder {
    /// A decoder with no parameter sets yet.
    pub fn new() -> Self {
        H264Decoder {
            spss: vec![None; 32],
            ppss: vec![None; 256],
            tables: Arc::new(CavlcTables::new()),
            cur: None,
            dpb: Vec::new(),
            next_id: 1,
            max_lt_idx: None,
            prev_poc_msb: 0,
            prev_poc_lsb: 0,
            prev_frame_num_offset: 0,
            prev_frame_num: 0,
            prev_ref_frame_num: 0,
            prev_had_mmco5: false,
            pending: None,
            active_size: None,
            done: Vec::new(),
            accel: None,
            accel_error: None,
            accel_started: false,
            threads: None,
        }
    }

    /// Reconstruct up to `threads` frames at once, each as soon as its
    /// references are finished. Headers stay in order on the calling thread,
    /// so [`decode_nal`](Self::decode_nal) can block when too many are
    /// waiting, and must not be called from the thread pool itself: this does
    /// nothing there, with one thread, or with an accelerator. Field and MBAFF
    /// pictures decode in order on the calling thread.
    ///
    /// [`take_pictures`](Self::take_pictures) then gives pictures once they
    /// are finished, leaving out any that failed; decoding carries on past
    /// those, and [`take_thread_error`](Self::take_thread_error) has the first.
    pub fn set_threads(&mut self, threads: usize) {
        if threads > 1 && self.accel.is_none() && crate::pool_can_serve_caller() {
            self.threads = Some(Threads {
                jobs: Jobs::new(threads * 2),
                finished: Arc::default(),
                error: Arc::default(),
                next_take: 0,
                next_job: 0,
                active: true,
            });
        }
    }

    /// Wait for every picture job to finish.
    pub fn wait_for_pictures(&self) {
        if let Some(t) = &self.threads {
            t.jobs.wait();
        }
    }

    /// The first error from a picture job, in decode order, once
    /// [`wait_for_pictures`](Self::wait_for_pictures) has returned.
    pub fn take_thread_error(&mut self) -> Option<String> {
        let t = self.threads.as_ref()?;
        t.error.lock().unwrap().take().map(|e| e.1)
    }

    /// Whether [`set_threads`](Self::set_threads) took effect.
    pub(crate) fn threaded(&self) -> bool {
        self.threads.is_some()
    }

    /// The number the next finished picture will have.
    pub(crate) fn next_output_id(&self) -> u64 {
        self.threads.as_ref().map_or(0, |t| t.next_job)
    }

    /// With threads: pictures finished so far by number, in decode order,
    /// `None` for one that failed.
    pub(crate) fn take_finished(&mut self) -> Vec<(u64, Option<H264Picture>)> {
        let mut out = Vec::new();
        if let Some(t) = &mut self.threads {
            let mut finished = t.finished.lock().unwrap();
            while let Some(picture) = finished.remove(&t.next_take) {
                out.push((t.next_take, picture));
                t.next_take += 1;
            }
        }
        out
    }

    /// Back to reconstructing here: every job done, and the buffer holding
    /// real pictures again.
    fn stop_jobs(&mut self) {
        let Some(t) = &mut self.threads else {
            return;
        };
        t.jobs.wait();
        t.active = false;
        for p in &mut self.dpb {
            if let Some(data) = p.slot.take().and_then(|s| s.get()) {
                p.planes = data.planes.clone();
                p.mbs = data.mbs.clone();
            }
        }
    }

    /// Queue a picture for [`take_pictures`](Self::take_pictures).
    fn publish(&mut self, picture: H264Picture) {
        match &mut self.threads {
            Some(t) => {
                t.finished.lock().unwrap().insert(t.next_job, Some(picture));
                t.next_job += 1;
            }
            None => self.done.push(picture),
        }
    }

    fn jobs_active(&self) -> bool {
        self.threads.as_ref().is_some_and(|t| t.active)
    }

    /// Hand reconstruction to `accel` (see [`H264Accel`]).
    pub fn set_accel(&mut self, accel: Box<dyn H264Accel>) {
        self.accel = Some(accel);
    }

    /// The first error the accelerator reported from
    /// [`finish_picture`](Self::finish_picture), which cannot return one.
    pub fn take_accel_error(&mut self) -> Option<String> {
        self.accel_error.take()
    }

    /// Decode one NAL unit (without start code or length prefix).
    pub fn decode_nal(&mut self, nal: &[u8]) -> Result<()> {
        if nal.is_empty() {
            return Ok(());
        }
        let nal_ref_idc = ((nal[0] >> 5) & 3) as u32;
        let nal_type = (nal[0] & 31) as u32;
        match nal_type {
            1 | 5 => {
                let rbsp = unescape(&nal[1..]);
                self.decode_slice(nal, &rbsp, nal_type, nal_ref_idc)
            }
            2..=4 => Err("data-partitioned slices are not supported".into()),
            7 => {
                let rbsp = unescape(&nal[1..]);
                let sps = Sps::parse(&rbsp)?;
                let id = sps.id as usize;
                self.spss[id] = Some(sps);
                Ok(())
            }
            8 => {
                let rbsp = unescape(&nal[1..]);
                let pps = Pps::parse(&rbsp, &self.spss)?;
                let id = pps.id as usize;
                self.ppss[id] = Some(pps);
                Ok(())
            }
            9..=11 => {
                // Access unit delimiter / end of sequence / end of stream: the
                // current picture, if any, is complete.
                self.finish_picture();
                Ok(())
            }
            _ => Ok(()),
        }
    }

    /// Pictures finished so far, in decode order.
    pub fn take_pictures(&mut self) -> Vec<H264Picture> {
        let finished: Vec<_> = self
            .take_finished()
            .into_iter()
            .filter_map(|p| p.1)
            .collect();
        self.done.extend(finished);
        std::mem::take(&mut self.done)
    }

    fn decode_slice(
        &mut self,
        nal: &[u8],
        rbsp: &[u8],
        nal_type: u32,
        nal_ref_idc: u32,
    ) -> Result<()> {
        let hdr = SliceHeader::parse(rbsp, nal_type, nal_ref_idc, &self.spss, &self.ppss)?;
        if hdr.redundant_pic_cnt > 0 {
            return Ok(());
        }
        let structure = if !hdr.field_pic {
            3
        } else if hdr.bottom_field {
            2
        } else {
            1
        };
        let new_pic = match &self.cur {
            None => true,
            Some(c) => {
                hdr.first_mb == 0
                    || c.frame_num != hdr.frame_num
                    || c.pps_id != hdr.pps_id
                    || c.idr != hdr.idr
                    || (c.nal_ref_idc == 0) != (nal_ref_idc == 0)
                    || c.poc_lsb != hdr.poc_lsb
                    || c.structure != structure
            }
        };
        if new_pic {
            self.finish_picture();
            self.start_picture(&hdr)?;
        }
        let pps = self.ppss[hdr.pps_id as usize]
            .clone()
            .ok_or("missing PPS")?;
        let refs = self.build_lists(&hdr)?;
        if let Some(accel) = self.accel.as_mut() {
            let cur = self.cur.as_ref().unwrap();
            let sps = cur.sps.clone();
            let slice = AccelSlice {
                nal,
                sps: &sps,
                pps: &pps,
                hdr: &hdr,
                first: !self.accel_started,
                store_id: self.dpb[cur.store].id,
                structure,
                field_poc: cur.pic.field_poc,
                dpb: &self.dpb,
                refs: &refs,
            };
            self.accel_started = true;
            return accel.slice(&slice);
        }
        let frefs = if hdr.mbaff {
            self.field_lists(&refs)
        } else {
            Default::default()
        };
        let jobs = self.jobs_active();
        let cur = self.cur.as_mut().unwrap();
        let slice_num = cur.pic.slices.len() as u32;
        cur.pic.slices.push(SliceDeblock {
            disable: hdr.disable_deblocking,
            alpha: hdr.alpha_offset,
            beta: hdr.beta_offset,
        });
        if jobs {
            cur.work.push(SliceWork {
                rbsp: rbsp.to_vec(),
                hdr,
                pps,
                refs,
                slice_num,
            });
            return Ok(());
        }
        let mut dec = SliceDec::new(
            &cur.sps,
            &pps,
            &hdr,
            slice_num,
            &mut cur.pic,
            &self.dpb,
            &refs,
            &frefs,
            &self.tables,
        );
        dec.decode(rbsp)
    }

    /// MBAFF field macroblocks' lists (§8.4.2.1): each frame of `refs` as
    /// its two fields, the current macroblock's parity first; `[parity][list]`.
    fn field_lists(&mut self, refs: &[Vec<RefEntry>; 2]) -> [[Vec<RefEntry>; 2]; 2] {
        let mut out: [[Vec<RefEntry>; 2]; 2] = Default::default();
        for (par, lists) in out.iter_mut().enumerate() {
            for (l, list) in lists.iter_mut().enumerate() {
                for e in &refs[l] {
                    for k in 0..2 {
                        let fp = par ^ k;
                        let st = &mut self.dpb[e.dpb];
                        list.push(RefEntry {
                            dpb: e.dpb,
                            id: st.id * 4 + 1 + fp as u32,
                            poc: st.field_poc[fp],
                            long_term: e.long_term,
                            structure: 1 + fp as u8,
                            planes: st.field(fp),
                        });
                    }
                }
            }
        }
        out
    }

    /// Drop frame stores that are neither references nor the frame waiting
    /// for its second field (indices into `dpb` shift).
    fn prune(&mut self) {
        let keep = self.pending.map(|p| p.0);
        self.dpb.retain(|p| p.is_ref() || Some(p.id) == keep);
    }

    fn start_picture(&mut self, hdr: &SliceHeader) -> Result<()> {
        let pps = self.ppss[hdr.pps_id as usize]
            .as_ref()
            .ok_or("missing PPS")?;
        let sps = self.spss[pps.sps_id as usize]
            .clone()
            .ok_or("missing SPS")?;
        if sps.transform_bypass {
            return Err("lossless (transform bypass) coding is not supported".into());
        }
        if !sps.frame_mbs_only && self.jobs_active() {
            self.stop_jobs();
        }
        let structure: u8 = if !hdr.field_pic {
            3
        } else if hdr.bottom_field {
            2
        } else {
            1
        };
        // h264_field_start: pair with a waiting first field of the other
        // parity and the same frame_num; an unmatched one is dropped from
        // display (but stays a reference if marked).
        let mut second_store = None;
        if let Some((id, s, fnum, _)) = self.pending.take() {
            if structure != 3 && structure != s && fnum == hdr.frame_num {
                second_store = self.dpb.iter().position(|p| p.id == id);
            }
            if second_store.is_none() {
                self.prune();
            }
        }
        let second_field = second_store.is_some();
        let size = (sps.width_mbs, sps.height_mbs);
        if self.active_size != Some(size) {
            self.dpb.clear();
            self.active_size = Some(size);
        }
        let max_frame_num = 1u32 << sps.log2_max_frame_num;
        if hdr.idr && !second_field {
            self.dpb.clear();
            self.max_lt_idx = None;
        } else if !second_field {
            let expected = (self.prev_ref_frame_num + 1) % max_frame_num;
            if hdr.frame_num != self.prev_ref_frame_num && hdr.frame_num != expected {
                self.fill_frame_num_gap(&sps, hdr.frame_num);
            }
        }

        // Picture order count (§8.2.1); a field sets only its own.
        let mut poc_msb = 0;
        let mut frame_num_offset = 0;
        let (top, bottom) = match sps.poc_type {
            0 => {
                let (prev_msb, prev_lsb) = if hdr.idr {
                    (0, 0)
                } else {
                    (self.prev_poc_msb, self.prev_poc_lsb)
                };
                let max_lsb = 1i32 << sps.log2_max_poc_lsb;
                let lsb = hdr.poc_lsb as i32;
                poc_msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 {
                    prev_msb + max_lsb
                } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 {
                    prev_msb - max_lsb
                } else {
                    prev_msb
                };
                let top = poc_msb + lsb;
                (
                    top,
                    if structure == 3 {
                        top + hdr.delta_poc_bottom
                    } else {
                        top
                    },
                )
            }
            _ => {
                let prev_off = if self.prev_had_mmco5 {
                    0
                } else {
                    self.prev_frame_num_offset
                };
                frame_num_offset = if hdr.idr {
                    0
                } else if self.prev_frame_num > hdr.frame_num {
                    prev_off + max_frame_num as i32
                } else {
                    prev_off
                };
                if sps.poc_type == 1 {
                    let n = sps.offset_for_ref_frame.len() as i32;
                    let mut abs = if n != 0 {
                        frame_num_offset + hdr.frame_num as i32
                    } else {
                        0
                    };
                    if hdr.nal_ref_idc == 0 && abs > 0 {
                        abs -= 1;
                    }
                    let mut expected = 0;
                    if abs > 0 {
                        let cycle = (abs - 1) / n;
                        let in_cycle = (abs - 1) % n;
                        let delta: i32 = sps.offset_for_ref_frame.iter().sum();
                        expected = cycle * delta
                            + sps.offset_for_ref_frame[..=in_cycle as usize]
                                .iter()
                                .sum::<i32>();
                    }
                    if hdr.nal_ref_idc == 0 {
                        expected += sps.offset_for_non_ref_pic;
                    }
                    let top = expected + hdr.delta_poc[0];
                    let mut bottom = top + sps.offset_for_top_to_bottom_field;
                    if structure == 3 {
                        bottom += hdr.delta_poc[1];
                    }
                    (top, bottom)
                } else {
                    let t = if hdr.idr {
                        0
                    } else if hdr.nal_ref_idc == 0 {
                        2 * (frame_num_offset + hdr.frame_num as i32) - 1
                    } else {
                        2 * (frame_num_offset + hdr.frame_num as i32)
                    };
                    (t, t)
                }
            }
        };

        let (w_mbs, h_mbs) = (sps.width_mbs as usize, sps.height_mbs as usize);
        let fill_y = 1u16 << (sps.bit_depth_luma - 1);
        let fill_c = 1u16 << (sps.bit_depth_chroma - 1);
        let ch_rows = if sps.chroma_format_idc == 2 { 16 } else { 8 };
        // A field picture is half the frame's height.
        let pic_h_mbs = if structure == 3 { h_mbs } else { h_mbs / 2 };
        // Neither an accelerator nor a job needs the samples here.
        let accel = self.accel.is_some() || self.jobs_active();
        let make = |h: usize| {
            if accel {
                // The accelerator holds the samples.
                empty_planes()
            } else if sps.chroma_format_idc == 0 {
                [
                    Plane::new(w_mbs * 16, h * 16, fill_y),
                    Plane::new(0, 0, 0),
                    Plane::new(0, 0, 0),
                ]
            } else {
                [
                    Plane::new(w_mbs * 16, h * 16, fill_y),
                    Plane::new(w_mbs * 8, h * ch_rows, fill_c),
                    Plane::new(w_mbs * 8, h * ch_rows, fill_c),
                ]
            }
        };
        let store = match second_store {
            Some(i) => i,
            None => {
                let id = self.next_id;
                self.next_id += 1;
                self.dpb.push(RefPic {
                    id,
                    planes: Arc::new(make(h_mbs)),
                    field_planes: [None, None],
                    mbs: Arc::new(Vec::new()),
                    field_mbs: [None, None],
                    field_poc: [i32::MAX, i32::MAX],
                    poc: i32::MAX,
                    frame_num: hdr.frame_num,
                    frame_num_wrap: hdr.frame_num as i32,
                    short: 0,
                    long: 0,
                    lt_idx: 0,
                    slot: None,
                });
                self.dpb.len() - 1
            }
        };
        {
            let st = &mut self.dpb[store];
            if structure & 1 != 0 {
                st.field_poc[0] = top;
            }
            if structure & 2 != 0 {
                st.field_poc[1] = bottom;
            }
            st.poc = st.field_poc[0].min(st.field_poc[1]);
        }
        let poc = match structure {
            1 => top,
            2 => bottom,
            _ => top.min(bottom),
        };
        self.cur = Some(Current {
            pic: CurPic {
                planes: make(pic_h_mbs),
                mbs: if accel {
                    Vec::new()
                } else {
                    vec![MbInfo::default(); w_mbs * pic_h_mbs]
                },
                w_mbs,
                h_mbs: pic_h_mbs,
                poc,
                field_poc: [top, bottom],
                slices: Vec::new(),
                decoded: 0,
            },
            sps,
            structure,
            mbaff: hdr.mbaff,
            store,
            second_field,
            idr: hdr.idr,
            nal_ref_idc: hdr.nal_ref_idc,
            frame_num: hdr.frame_num,
            long_term_reference: hdr.long_term_reference,
            mmcos: hdr.mmcos.clone(),
            pps_id: hdr.pps_id,
            poc_lsb: hdr.poc_lsb,
            poc_msb,
            frame_num_offset,
            work: Vec::new(),
        });
        Ok(())
    }

    /// Insert "non-existing" frames for skipped `frame_num`s (§8.2.5.2), so
    /// the sliding window and list initialisation see what the encoder did.
    fn fill_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) {
        let max = 1u32 << sps.log2_max_frame_num;
        let mut f = (self.prev_ref_frame_num + 1) % max;
        let mut guard = 0;
        // Content of a non-existing frame is unspecified; reuse the newest
        // reference so a stream that does reference one degrades gracefully.
        let src = self
            .dpb
            .iter()
            .filter(|p| p.is_ref())
            .max_by_key(|p| p.id)
            .map(|p| (p.planes.clone(), p.slot.clone()));
        let Some((planes, slot)) = src else {
            self.prev_ref_frame_num = frame_num.wrapping_sub(1) % max;
            return;
        };
        while f != frame_num && guard < max {
            self.update_wraps(f, max);
            self.sliding_window(sps, false);
            let id = self.next_id;
            self.next_id += 1;
            let mbs = Arc::new(vec![
                MbInfo::default();
                (sps.width_mbs * sps.height_mbs) as usize
            ]);
            self.dpb.push(RefPic {
                id,
                planes: planes.clone(),
                field_planes: [None, None],
                mbs,
                field_mbs: [None, None],
                field_poc: [0, 0],
                poc: 0,
                frame_num: f,
                frame_num_wrap: 0,
                short: 3,
                long: 0,
                lt_idx: 0,
                slot: slot.clone(),
            });
            self.prev_ref_frame_num = f;
            self.prev_frame_num = f;
            f = (f + 1) % max;
            guard += 1;
        }
    }

    /// Recompute `FrameNumWrap` against the current `frame_num`.
    fn update_wraps(&mut self, frame_num: u32, max_frame_num: u32) {
        for p in &mut self.dpb {
            if p.short != 0 {
                p.frame_num_wrap = if p.frame_num > frame_num {
                    p.frame_num as i32 - max_frame_num as i32
                } else {
                    p.frame_num as i32
                };
            }
        }
    }

    fn build_lists(&mut self, hdr: &SliceHeader) -> Result<[Vec<RefEntry>; 2]> {
        let cur = self.cur.as_ref().unwrap();
        let max_frame_num = 1u32 << cur.sps.log2_max_frame_num;
        let structure = cur.structure;
        let field = structure != 3;
        let cur_par = (structure == 2) as usize;
        let cur_poc = cur.pic.poc;
        let cur_store_id = self.dpb[cur.store].id;
        self.update_wraps(hdr.frame_num, max_frame_num);
        let mut lists: [Vec<RefEntry>; 2] = [Vec::new(), Vec::new()];
        if hdr.slice_type == SliceType::I {
            return Ok(lists);
        }
        // Frames take only stores with both fields marked; fields take any.
        let full = |m: u8| if field { m != 0 } else { m == 3 };
        let mut short: Vec<usize> = (0..self.dpb.len())
            .filter(|&i| full(self.dpb[i].short))
            .collect();
        let mut long: Vec<usize> = (0..self.dpb.len())
            .filter(|&i| full(self.dpb[i].long))
            .collect();
        long.sort_by_key(|&i| self.dpb[i].lt_idx);
        // An ordered list of frame stores -> entries (§8.2.4.2.5 for fields:
        // alternate parities starting with the current one).
        let expand = |dpb: &mut Vec<RefPic>, order: &[usize], long_term: bool| -> Vec<RefEntry> {
            let mark = |p: &RefPic| if long_term { p.long } else { p.short };
            let mut out = Vec::new();
            if !field {
                for &i in order {
                    let p = &dpb[i];
                    out.push(RefEntry {
                        dpb: i,
                        id: p.id * 4 + 3,
                        poc: p.poc,
                        long_term,
                        structure: 3,
                        planes: p.planes.clone(),
                    });
                }
                return out;
            }
            let sel = [cur_par, 1 - cur_par];
            let mut idx = [0usize, 0usize];
            loop {
                let mut any = false;
                for (k, &par) in sel.iter().enumerate() {
                    while idx[k] < order.len() && mark(&dpb[order[idx[k]]]) & (1 << par) == 0 {
                        idx[k] += 1;
                    }
                    if idx[k] < order.len() {
                        let i = order[idx[k]];
                        idx[k] += 1;
                        any = true;
                        let planes = dpb[i].field(par);
                        let p = &dpb[i];
                        out.push(RefEntry {
                            dpb: i,
                            id: p.id * 4 + 1 + par as u32,
                            poc: p.field_poc[par],
                            long_term,
                            structure: 1 + par as u8,
                            planes,
                        });
                    }
                }
                if !any {
                    break;
                }
            }
            out
        };
        if hdr.slice_type == SliceType::P {
            short.sort_by_key(|&i| std::cmp::Reverse(self.dpb[i].frame_num_wrap));
            let mut l = expand(&mut self.dpb, &short, false);
            l.extend(expand(&mut self.dpb, &long, true));
            lists[0] = l;
        } else {
            // B: by the frame (or pair) POC around the current POC; equal
            // POCs go before (ffmpeg add_sorted).
            let mut before: Vec<usize> = short
                .iter()
                .copied()
                .filter(|&i| self.dpb[i].poc <= cur_poc)
                .collect();
            let mut after: Vec<usize> = short
                .iter()
                .copied()
                .filter(|&i| !before.contains(&i))
                .collect();
            before.sort_by_key(|&i| std::cmp::Reverse(self.dpb[i].poc));
            after.sort_by_key(|&i| self.dpb[i].poc);
            let o0: Vec<usize> = before.iter().chain(after.iter()).copied().collect();
            let o1: Vec<usize> = after.iter().chain(before.iter()).copied().collect();
            let mut l0 = expand(&mut self.dpb, &o0, false);
            let mut l1 = expand(&mut self.dpb, &o1, false);
            let lt = expand(&mut self.dpb, &long, true);
            l0.extend(lt.iter().cloned());
            l1.extend(lt);
            // Identical lists (compared by frame store, as ffmpeg does):
            // swap the first two of list 1.
            if l1.len() > 1
                && l0.len() == l1.len()
                && l0.iter().zip(&l1).all(|(a, b)| a.dpb == b.dpb)
            {
                l1.swap(0, 1);
            }
            lists = [l0, l1];
        }
        let _ = cur_store_id;
        let (curr_pic_num, max_pic_num) = if field {
            (2 * hdr.frame_num as i32 + 1, 2 * max_frame_num as i32)
        } else {
            (hdr.frame_num as i32, max_frame_num as i32)
        };
        for l in 0..2 {
            let n = hdr.num_ref_idx[l] as usize;
            lists[l].truncate(n);
            if hdr.list_mods[l].is_empty() {
                continue;
            }
            let mut pred = curr_pic_num;
            let mut idx = 0usize;
            for m in &hdr.list_mods[l] {
                // (store index, parity or None for a frame, long-term)
                let target: Option<(usize, Option<usize>, bool)> = if m.idc < 2 {
                    let abs = m.value as i32 + 1;
                    let mut no_wrap = if m.idc == 0 { pred - abs } else { pred + abs };
                    if no_wrap < 0 {
                        no_wrap += max_pic_num;
                    } else if no_wrap >= max_pic_num {
                        no_wrap -= max_pic_num;
                    }
                    pred = no_wrap;
                    let pic_num = if no_wrap > curr_pic_num {
                        no_wrap - max_pic_num
                    } else {
                        no_wrap
                    };
                    if field {
                        let par = if pic_num & 1 == 1 {
                            cur_par
                        } else {
                            1 - cur_par
                        };
                        let fnw = pic_num >> 1;
                        self.dpb
                            .iter()
                            .position(|p| p.short & (1 << par) != 0 && p.frame_num_wrap == fnw)
                            .map(|i| (i, Some(par), false))
                    } else {
                        self.dpb
                            .iter()
                            .position(|p| p.short == 3 && p.frame_num_wrap == pic_num)
                            .map(|i| (i, None, false))
                    }
                } else if field {
                    let par = if m.value & 1 == 1 {
                        cur_par
                    } else {
                        1 - cur_par
                    };
                    let lt = m.value >> 1;
                    self.dpb
                        .iter()
                        .position(|p| p.long & (1 << par) != 0 && p.lt_idx == lt)
                        .map(|i| (i, Some(par), true))
                } else {
                    self.dpb
                        .iter()
                        .position(|p| p.long == 3 && p.lt_idx == m.value)
                        .map(|i| (i, None, true))
                };
                let Some((i, par, long_term)) = target else {
                    return Err("ref_pic_list_modification names a missing picture".into());
                };
                let e = match par {
                    None => {
                        let p = &self.dpb[i];
                        RefEntry {
                            dpb: i,
                            id: p.id * 4 + 3,
                            poc: p.poc,
                            long_term,
                            structure: 3,
                            planes: p.planes.clone(),
                        }
                    }
                    Some(par) => {
                        let planes = self.dpb[i].field(par);
                        let p = &self.dpb[i];
                        RefEntry {
                            dpb: i,
                            id: p.id * 4 + 1 + par as u32,
                            poc: p.field_poc[par],
                            long_term,
                            structure: 1 + par as u8,
                            planes,
                        }
                    }
                };
                if idx > lists[l].len() {
                    idx = lists[l].len();
                }
                let eid = e.id;
                lists[l].insert(idx, e);
                idx += 1;
                let mut k = idx;
                while k < lists[l].len() {
                    if lists[l][k].id == eid {
                        lists[l].remove(k);
                    } else {
                        k += 1;
                    }
                }
            }
            lists[l].truncate(n);
        }
        Ok(lists)
    }

    /// §8.2.5.3: when the DPB is full, unmark the short-term frame (or pair,
    /// or field) with the smallest `FrameNumWrap`. `exclude` is the current
    /// frame store (its first field does not count).
    fn sliding_window(&mut self, sps: &Sps, _exclude: bool) {
        let max = sps.max_num_ref_frames.max(1) as usize;
        let n_ref = self.dpb.iter().filter(|p| p.is_ref()).count();
        let n_short = self.dpb.iter().filter(|p| p.short != 0).count();
        if n_ref >= max
            && n_short > 0
            && let Some(i) = (0..self.dpb.len())
                .filter(|&i| self.dpb[i].short != 0)
                .min_by_key(|&i| self.dpb[i].frame_num_wrap)
        {
            self.dpb[i].short = 0;
        }
    }

    /// Reference marking (§8.2.5) for the finished picture `cur`; returns
    /// whether it carried memory_management_control_operation 5.
    fn mark(&mut self, cur: &Current) -> bool {
        let max_frame_num = 1u32 << cur.sps.log2_max_frame_num;
        let structure = cur.structure;
        let field = structure != 3;
        let cur_par = (structure == 2) as usize;
        let cur_bits: u8 = if field { 1 << cur_par } else { 3 };
        let cur_id = self.dpb[cur.store].id;
        self.update_wraps(cur.frame_num, max_frame_num);
        let mut long_term = false;
        let mut lt_idx = 0;
        let mut had_mmco5 = false;
        // Unmark the given fields of store `i`.
        fn unmark(p: &mut RefPic, bits: u8, long: bool) {
            if long {
                p.long &= !bits;
            } else {
                p.short &= !bits;
            }
        }
        // (store, field bits) of a short-term picNumX / long-term pic num.
        let (curr_pic_num, _) = if field {
            (2 * cur.frame_num as i32 + 1, 0)
        } else {
            (cur.frame_num as i32, 0)
        };
        let find_short = |dpb: &[RefPic], pic_num: i32| -> Option<(usize, u8)> {
            if field {
                let par = if pic_num & 1 == 1 {
                    cur_par
                } else {
                    1 - cur_par
                };
                let fnw = pic_num >> 1;
                dpb.iter()
                    .position(|p| p.short & (1 << par) != 0 && p.frame_num_wrap == fnw)
                    .map(|i| (i, 1u8 << par))
            } else {
                dpb.iter()
                    .position(|p| p.short == 3 && p.frame_num_wrap == pic_num)
                    .map(|i| (i, 3))
            }
        };
        let find_long = |dpb: &[RefPic], num: u32| -> Option<(usize, u8)> {
            if field {
                let par = if num & 1 == 1 { cur_par } else { 1 - cur_par };
                dpb.iter()
                    .position(|p| p.long & (1 << par) != 0 && p.lt_idx == num >> 1)
                    .map(|i| (i, 1u8 << par))
            } else {
                dpb.iter()
                    .position(|p| p.long == 3 && p.lt_idx == num)
                    .map(|i| (i, 3))
            }
        };
        if cur.idr && !cur.second_field {
            if cur.long_term_reference {
                long_term = true;
                self.max_lt_idx = Some(0);
            } else {
                self.max_lt_idx = None;
            }
        } else if cur.second_field
            && (self.dpb[cur.store].short != 0 || self.dpb[cur.store].long != 0)
            && cur.mmcos.is_none()
        {
            // The first field already holds the frame's marking: the second
            // takes the same (no sliding window, §8.2.5.3).
            long_term = self.dpb[cur.store].long != 0;
            lt_idx = self.dpb[cur.store].lt_idx;
        } else if let Some(ops) = &cur.mmcos {
            for m in ops {
                let pic_num_x = curr_pic_num - (m.diff_pic_nums_minus1 as i32 + 1);
                match m.op {
                    1 => {
                        if let Some((i, b)) = find_short(&self.dpb, pic_num_x) {
                            unmark(&mut self.dpb[i], b, false);
                        }
                    }
                    2 => {
                        if let Some((i, b)) = find_long(&self.dpb, m.long_term_pic_num) {
                            unmark(&mut self.dpb[i], b, true);
                        }
                    }
                    3 => {
                        let idx = m.long_term_frame_idx;
                        if let Some((i, b)) = find_short(&self.dpb, pic_num_x) {
                            let id = self.dpb[i].id;
                            // Free the index unless it holds this field's sibling.
                            for p in self.dpb.iter_mut() {
                                if p.long != 0 && p.lt_idx == idx && (p.id != id || !field) {
                                    p.long = 0;
                                }
                            }
                            let p = &mut self.dpb[i];
                            p.short &= !b;
                            p.long |= b;
                            p.lt_idx = idx;
                        }
                    }
                    4 => {
                        let max = m.max_long_term_frame_idx_plus1;
                        self.max_lt_idx = max.checked_sub(1);
                        for p in self.dpb.iter_mut() {
                            if p.long != 0 && p.lt_idx >= max {
                                p.long = 0;
                            }
                        }
                    }
                    5 => {
                        for p in self.dpb.iter_mut() {
                            p.short = 0;
                            p.long = 0;
                        }
                        self.max_lt_idx = None;
                        had_mmco5 = true;
                    }
                    6 => {
                        let idx = m.long_term_frame_idx;
                        for p in self.dpb.iter_mut() {
                            if p.long != 0 && p.lt_idx == idx && p.id != cur_id {
                                p.long = 0;
                            }
                        }
                        long_term = true;
                        lt_idx = idx;
                    }
                    _ => {}
                }
            }
            if !long_term {
                // A stream that overfills the DPB with adaptive marking
                // is broken; slide rather than grow without bound.
                let max = cur.sps.max_num_ref_frames.max(1) as usize;
                let others = self
                    .dpb
                    .iter()
                    .filter(|p| p.is_ref() && p.id != cur_id)
                    .count();
                if others >= max {
                    self.sliding_window(&cur.sps, true);
                }
            }
        } else {
            self.sliding_window(&cur.sps, true);
        }
        let st = &mut self.dpb[cur.store];
        if long_term {
            st.long |= cur_bits;
            st.short &= !cur_bits;
            st.lt_idx = lt_idx;
        } else {
            st.short |= cur_bits;
        }
        had_mmco5
    }

    /// Finish the picture in progress, if any: deblock, mark references, and
    /// queue a completed frame for output.
    pub fn finish_picture(&mut self) {
        let Some(mut cur) = self.cur.take() else {
            return;
        };
        let sps = cur.sps.clone();
        let accel = self.accel.is_some();
        // Marking below drops entries; the slices' indices are into this.
        let jobs = self.jobs_active();
        let snapshot = jobs.then(|| self.dpb.clone());
        let slot = jobs.then(Slot::new);
        if jobs {
            self.dpb[cur.store].slot = slot.clone();
        } else if accel {
            if std::mem::take(&mut self.accel_started)
                && let Err(e) = self.accel.as_mut().unwrap().end_picture()
            {
                self.accel_error.get_or_insert(e);
            }
        } else if cur.mbaff {
            deblock::deblock_mbaff(
                &mut cur.pic,
                sps.bit_depth_luma,
                sps.bit_depth_chroma,
                sps.chroma_format_idc,
            );
        } else {
            deblock::deblock_picture(
                &mut cur.pic,
                sps.bit_depth_luma,
                sps.bit_depth_chroma,
                sps.chroma_format_idc,
                cur.structure != 3,
            );
        }
        // Move the samples and motion into the frame store.
        let structure = cur.structure;
        if !accel && !jobs {
            let planes = std::mem::replace(&mut cur.pic.planes, empty_planes());
            let mbs = Arc::new(std::mem::take(&mut cur.pic.mbs));
            let st = &mut self.dpb[cur.store];
            st.field_planes = [None, None];
            if structure == 3 {
                st.planes = Arc::new(planes);
                st.mbs = mbs;
            } else {
                let par = (structure == 2) as usize;
                let dst = Arc::make_mut(&mut st.planes);
                for c in 0..3 {
                    let (fp, d) = (&planes[c], &mut dst[c]);
                    for y in 0..fp.height {
                        let o = (2 * y + par) * d.width;
                        d.data[o..o + d.width]
                            .copy_from_slice(&fp.data[y * fp.width..(y + 1) * fp.width]);
                    }
                }
                st.field_mbs[par] = Some(mbs);
            }
        }
        let mut had_mmco5 = false;
        if cur.nal_ref_idc != 0 {
            had_mmco5 = self.mark(&cur);
            let st = &mut self.dpb[cur.store];
            if had_mmco5 {
                // The picture now counts as frame_num 0 with its POC rebased.
                let temp = match structure {
                    1 => st.field_poc[0],
                    2 => st.field_poc[1],
                    _ => st.field_poc[0].min(st.field_poc[1]),
                };
                if structure & 1 != 0 {
                    st.field_poc[0] -= temp;
                }
                if structure & 2 != 0 {
                    st.field_poc[1] -= temp;
                }
                st.poc = st.field_poc[0].min(st.field_poc[1]);
                st.frame_num = 0;
            }
            st.frame_num_wrap = st.frame_num as i32;
            let frame_num = st.frame_num;
            self.prev_ref_frame_num = frame_num;
            if had_mmco5 {
                self.prev_poc_msb = 0;
                self.prev_poc_lsb = if structure == 2 { 0 } else { st.field_poc[0] };
            } else {
                self.prev_poc_msb = cur.poc_msb;
                self.prev_poc_lsb = cur.poc_lsb as i32;
            }
        }
        self.prev_had_mmco5 = had_mmco5;
        self.prev_frame_num = if had_mmco5 { 0 } else { cur.frame_num };
        self.prev_frame_num_offset = if had_mmco5 { 0 } else { cur.frame_num_offset };
        let complete = structure == 3 || cur.second_field;
        let st_id = self.dpb[cur.store].id;
        if !complete {
            self.pending = Some((st_id, structure, cur.frame_num, cur.nal_ref_idc != 0));
        }
        if let (Some(snapshot), Some(slot)) = (snapshot, slot) {
            let poc = self.dpb[cur.store].poc;
            let idr = cur.idr || had_mmco5;
            self.submit_picture(cur, snapshot, slot, poc, idr);
            self.prune();
            return;
        }
        if complete {
            let st = &self.dpb[cur.store];
            let (chroma, crop, color) = output_format(&sps);
            let frame = match self.accel.as_mut() {
                Some(a) => match a.frame(st.id, &sps) {
                    Ok(f) => f,
                    Err(e) => {
                        self.accel_error.get_or_insert(e);
                        self.prune();
                        return;
                    }
                },
                None => DecodedFrame::from_planes(
                    &st.planes,
                    chroma,
                    sps.bit_depth_luma as u8,
                    crop,
                    color,
                ),
            };
            let picture = H264Picture {
                frame,
                poc: st.poc,
                idr: cur.idr || had_mmco5,
            };
            self.publish(picture);
        }
        self.prune();
    }

    /// Hand a picture, its marking done, to a job.
    fn submit_picture(
        &mut self,
        cur: Current,
        dpb: Vec<RefPic>,
        slot: Arc<Slot<RefData>>,
        poc: i32,
        idr: bool,
    ) {
        let mut deps: Vec<Arc<Slot<RefData>>> = Vec::new();
        for entry in cur.work.iter().flat_map(|w| w.refs.iter().flatten()) {
            if let Some(dep) = dpb.get(entry.dpb).and_then(|p| p.slot.clone())
                && !Arc::ptr_eq(&dep, &slot)
                && !deps.iter().any(|d| Arc::ptr_eq(d, &dep))
            {
                deps.push(dep);
            }
        }
        let t = self.threads.as_mut().unwrap();
        let order = t.next_job;
        t.next_job += 1;
        let (finished, error) = (t.finished.clone(), t.error.clone());
        let tables = self.tables.clone();
        let sps = cur.sps.clone();
        t.jobs.clone().submit(&deps, move || {
            let (data, frame) = match caught(|| reconstruct(cur, dpb, &tables)) {
                Ok((data, frame)) => (data, Some(frame)),
                Err(e) => {
                    let mut first = error.lock().unwrap();
                    if first.as_ref().is_none_or(|f| order < f.0) {
                        *first = Some((order, e));
                    }
                    (grey_frame(&sps), None)
                }
            };
            let picture = frame.map(|frame| H264Picture { frame, poc, idr });
            finished.lock().unwrap().insert(order, picture);
            slot.finish(data);
        });
    }
}

/// How `sps` says a picture leaves the decoder.
#[cfg(feature = "decode")]
fn output_format(sps: &Sps) -> (ChromaFormat, [usize; 4], ColorInfo) {
    let chroma = match sps.chroma_format_idc {
        0 => ChromaFormat::Monochrome,
        2 => ChromaFormat::Yuv422,
        _ => ChromaFormat::Yuv420,
    };
    let color = ColorInfo::from_vui(
        sps.matrix_coefficients,
        sps.full_range,
        sps.height_mbs * 16 - sps.crop[2] - sps.crop[3],
    );
    (chroma, sps.crop.map(|v| v as usize), color)
}

/// What a failed picture leaves for the ones that reference it.
#[cfg(feature = "decode")]
fn grey_frame(sps: &Sps) -> RefData {
    let (w, h) = (sps.width_mbs as usize * 16, sps.height_mbs as usize * 16);
    let (cw, ch) = match sps.chroma_format_idc {
        0 => (0, 0),
        2 => (w / 2, h),
        _ => (w / 2, h / 2),
    };
    let planes = [
        Plane::new(w, h, 1 << (sps.bit_depth_luma - 1)),
        Plane::new(cw, ch, 1 << (sps.bit_depth_chroma - 1)),
        Plane::new(cw, ch, 1 << (sps.bit_depth_chroma - 1)),
    ];
    RefData {
        planes: Arc::new(planes),
        mbs: Arc::new(vec![
            MbInfo::default();
            (sps.width_mbs * sps.height_mbs) as usize
        ]),
    }
}

/// A picture job: its slices, deblocking and what comes out. `dpb` is the
/// buffer as this frame saw it, its references all finished by now.
#[cfg(feature = "decode")]
fn reconstruct(
    mut cur: Current,
    mut dpb: Vec<RefPic>,
    tables: &CavlcTables,
) -> Result<(RefData, DecodedFrame)> {
    for p in &mut dpb {
        if let Some(data) = p.slot.as_ref().and_then(|s| s.get()) {
            p.planes = data.planes.clone();
            p.mbs = data.mbs.clone();
        }
    }
    let sps = cur.sps.clone();
    // The buffers come here rather than in the header walk, which they would
    // otherwise hold up.
    let blank = grey_frame(&sps);
    cur.pic.mbs = (*blank.mbs).clone();
    cur.pic.planes = Arc::try_unwrap(blank.planes).unwrap_or_else(|p| (*p).clone());
    for mut w in std::mem::take(&mut cur.work) {
        // The lists were built before these samples existed.
        for entry in w.refs.iter_mut().flatten() {
            entry.planes = dpb
                .get(entry.dpb)
                .ok_or("reference out of range")?
                .planes
                .clone();
        }
        let frefs = Default::default();
        let mut dec = SliceDec::new(
            &sps,
            &w.pps,
            &w.hdr,
            w.slice_num,
            &mut cur.pic,
            &dpb,
            &w.refs,
            &frefs,
            tables,
        );
        dec.decode(&w.rbsp)?;
    }
    deblock::deblock_picture(
        &mut cur.pic,
        sps.bit_depth_luma,
        sps.bit_depth_chroma,
        sps.chroma_format_idc,
        false,
    );
    let planes = std::mem::replace(&mut cur.pic.planes, empty_planes());
    let (chroma, crop, color) = output_format(&sps);
    let frame = DecodedFrame::from_planes(&planes, chroma, sps.bit_depth_luma as u8, crop, color);
    let mbs = Arc::new(std::mem::take(&mut cur.pic.mbs));
    Ok((
        RefData {
            planes: Arc::new(planes),
            mbs,
        },
        frame,
    ))
}