zenjpeg 0.8.1

Pure Rust JPEG encoder/decoder with perceptual optimizations
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
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
//! Streaming input encoder API.
//!
//! This module provides a streaming encoder that accepts rows incrementally,
//! reducing peak memory by not requiring the full input image in memory.
//!
//! # Memory Savings
//!
//! For a 4K (3840x2160) RGB image:
//! - Standard encoder: ~50 MB peak (input buffer + internal)
//! - Streaming encoder: ~26 MB peak (~50% reduction)
//!
//! # Example
//!
//! ```rust,ignore
//! use zenjpeg::{StreamingEncoder, Quality, Subsampling};
//!
//! let mut encoder = StreamingEncoder::new(1920, 1080)
//!     .quality(Quality::ApproxJpegli(85.0))
//!     .subsampling(Subsampling::S420)
//!     .start()?;
//!
//! // Push rows one at a time (e.g., from a decoder or generator)
//! for row in image_rows {
//!     encoder.push_row(row)?;
//! }
//!
//! // Or push chunks of rows
//! // encoder.push_rows(chunk, 4)?;
//!
//! let jpeg = encoder.finish()?;
//! ```

#![allow(dead_code)]

use crate::encode::config::ComputedConfig;
use crate::encode::encoder_types::HuffmanStrategy;
use crate::encode::strip::StripProcessor;
use crate::error::{Error, Result};
use crate::quant::{self, QuantTable, ZeroBiasParams};
use crate::types::{ColorSpace, JpegMode, Subsampling};
use enough::{Stop, Unstoppable};

pub(crate) use super::streaming_builder::StreamingEncoderBuilder;

/// State for streaming-through encoding mode.
///
/// When present, blocks are entropy-encoded immediately on each strip flush
/// rather than buffered for a later two-pass Huffman optimization.
struct StreamingOutputState {
    /// BitWriter accumulates encoded scan data across strip flushes.
    writer: crate::foundation::bitstream::BitWriter,
    /// Huffman tables used for encoding (boxed: ~5.7 KB, uncommon path).
    tables: Box<crate::huffman::optimize::HuffmanTableSet>,
    /// Entropy encoding state (DC prediction, restart markers).
    entropy_state: crate::entropy::StreamingEntropyState,
    /// Total MCUs in the full image (for restart marker logic).
    total_mcus: usize,
    /// JPEG header bytes (SOI through SOS), written at construction time.
    header: Vec<u8>,
}

/// Streaming input JPEG encoder.
///
/// Accepts rows incrementally and outputs JPEG at the end.
/// Uses strip-based processing internally for low peak memory usage.
///
/// Two encoding modes:
/// - **Buffered** (default with `HuffmanStrategy::Optimize`): buffers all blocks,
///   builds optimal Huffman tables at `finish()`.
/// - **Streaming-through** (with `HuffmanStrategy::Custom` or `Fixed`, sequential only):
///   writes JPEG header at construction, encodes blocks immediately on each
///   strip flush. At `finish()`, just appends EOI.
pub(crate) struct StreamingEncoder {
    /// Image width in pixels
    width: usize,
    /// Image height in pixels
    height: usize,
    /// Bytes per row of input data
    bytes_per_row: usize,
    /// Strip height (rows to buffer before processing)
    strip_height: usize,

    /// Row buffer (accumulates rows until strip is ready)
    row_buffer: Vec<u8>,
    /// Number of rows currently buffered
    rows_buffered: usize,
    /// Current Y position (rows processed so far)
    current_y: usize,

    /// Underlying strip processor
    processor: StripProcessor,

    /// Configuration for JPEG output generation
    config: ComputedConfig,

    /// Quantization tables (generated from quality)
    y_quant: QuantTable,
    cb_quant: QuantTable,
    cr_quant: QuantTable,

    /// Streaming-through state. None = buffered mode (default).
    streaming: Option<StreamingOutputState>,
}

impl StreamingEncoder {
    /// Creates a new streaming encoder builder with the given dimensions.
    ///
    /// Use the builder methods to configure quality, subsampling, etc.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use zenjpeg::{StreamingEncoder, Quality, Subsampling};
    ///
    /// let encoder = StreamingEncoder::new(1920, 1080)
    ///     .quality(Quality::ApproxJpegli(85.0))
    ///     .subsampling(Subsampling::S420)
    ///     .start()?;
    /// ```
    #[must_use]
    #[allow(clippy::new_ret_no_self)] // Builder pattern: new() returns builder
    pub(crate) fn new(width: u32, height: u32) -> StreamingEncoderBuilder {
        StreamingEncoderBuilder::new(width, height)
    }

    /// Creates a streaming encoder from builder configuration.
    pub(crate) fn from_builder(builder: StreamingEncoderBuilder) -> Result<Self> {
        let width = builder.width as usize;
        let height = builder.height as usize;

        if width == 0 || height == 0 {
            return Err(Error::invalid_dimensions(
                builder.width,
                builder.height,
                "dimensions must be non-zero",
            ));
        }

        // Generate quantization tables and zero-bias params
        let is_420 = builder.subsampling == Subsampling::S420;
        let distance = builder.quality.to_distance();
        let color_space = if builder.use_xyb {
            ColorSpace::Xyb
        } else {
            ColorSpace::YCbCr
        };

        let allow_16bit = builder.allow_16bit_quant_tables;
        let ((y_quant, cb_quant, cr_quant), (y_zero_bias, cb_zero_bias, cr_zero_bias)) =
            if let Some(ref tables) = builder.encoding_tables {
                // Branch 1: Custom encoding tables provided explicitly
                let quant = tables.generate_quant_tables(distance, is_420);
                let zero_bias = tables.generate_zero_bias_all();
                // Apply allow_16bit clamping if needed
                let quant = if allow_16bit {
                    quant
                } else {
                    (
                        quant.0.clamp_to_baseline(),
                        quant.1.clamp_to_baseline(),
                        quant.2.clamp_to_baseline(),
                    )
                };
                (quant, zero_bias)
            } else if builder.quant_source == super::encoder_types::QuantTableSource::MozjpegDefault
            {
                // Branch 2: Mozjpeg Robidoux tables with quality scaling
                // Use for_mozjpeg_tables() to preserve the original mozjpeg quality.
                // to_internal() remaps for jpegli's distance system, producing wrong tables.
                let quality_u8 = builder.quality.for_mozjpeg_tables();
                let force_baseline = !allow_16bit;
                let tables = super::tables::robidoux::generate_mozjpeg_default_tables(
                    quality_u8,
                    force_baseline,
                );
                let quant = tables.generate_quant_tables(distance, is_420);
                let zero_bias = tables.generate_zero_bias_all();
                (quant, zero_bias)
            } else {
                // Branch 3: Jpegli perceptual defaults (original path)
                //
                // When separate_chroma_tables is false (2-table mode, jpeg_set_quality),
                // use the Cr base matrix for both Cb and Cr tables. This matches C++
                // jpegli behavior where the single chroma table uses the Cr matrix.
                let cb_component = if builder.separate_chroma_tables { 1 } else { 2 };

                let quant = (
                    quant::generate_quant_table_ex(
                        builder.quality,
                        0,
                        color_space,
                        builder.use_xyb,
                        is_420,
                        allow_16bit,
                    ),
                    quant::generate_quant_table_ex(
                        builder.quality,
                        cb_component,
                        color_space,
                        builder.use_xyb,
                        is_420,
                        allow_16bit,
                    ),
                    quant::generate_quant_table_ex(
                        builder.quality,
                        2,
                        color_space,
                        builder.use_xyb,
                        is_420,
                        allow_16bit,
                    ),
                );

                // Compute effective distance for quality-adaptive zero bias
                let effective_distance =
                    quant::quant_vals_to_distance(&quant.0, &quant.1, &quant.2);

                // Auto-select zero bias based on color mode
                let zero_bias = if builder.use_xyb {
                    (
                        ZeroBiasParams::for_xyb(effective_distance, 0),
                        ZeroBiasParams::for_xyb(effective_distance, 1),
                        ZeroBiasParams::for_xyb(effective_distance, 2),
                    )
                } else {
                    (
                        ZeroBiasParams::for_ycbcr(effective_distance, 0),
                        ZeroBiasParams::for_ycbcr(effective_distance, 1),
                        ZeroBiasParams::for_ycbcr(effective_distance, 2),
                    )
                };

                (quant, zero_bias)
            };

        // Build quantization context (all tables + SIMD variants)
        let quant_ctx = crate::encode::strip::QuantContext::new(
            y_quant.clone(),
            cb_quant.clone(),
            cr_quant.clone(),
            y_zero_bias,
            cb_zero_bias,
            cr_zero_bias,
        );

        // Determine if we can use streaming-through encoding early,
        // so StripProcessor can allocate minimal block storage.
        let enable_streaming = !matches!(builder.huffman, HuffmanStrategy::Optimize)
            && builder.mode != JpegMode::Progressive
            && !builder.use_xyb;

        // Create strip processor with quant tables provided at construction.
        // In streaming-through mode, only allocate one strip of block storage.
        let mut processor = if enable_streaming {
            StripProcessor::with_xyb_streaming(
                width,
                height,
                builder.subsampling,
                builder.pixel_format,
                builder.chroma_downsampling,
                builder.restart_interval,
                builder.use_xyb,
                quant_ctx,
                builder.aq_enabled,
            )?
        } else {
            StripProcessor::with_xyb(
                width,
                height,
                builder.subsampling,
                builder.pixel_format,
                builder.chroma_downsampling,
                builder.restart_interval,
                builder.use_xyb,
                quant_ctx,
                builder.aq_enabled,
            )?
        };

        // Set deringing (on by default in both builder and processor)
        processor.set_deringing(builder.deringing);

        // Enable trellis quantization if configured
        #[cfg(feature = "trellis")]
        {
            if let Some(ref trellis) = builder.trellis {
                processor.set_trellis(*trellis);
            } else if builder.hybrid_config.enabled {
                processor.set_hybrid(builder.hybrid_config);
            }
        }

        let strip_height = processor.strip_height();
        let bytes_per_row = width * builder.pixel_format.bytes_per_pixel();

        // Allocate row buffer for one strip
        let row_buffer = vec![0u8; bytes_per_row * strip_height];

        // Create config for final JPEG output
        let config = ComputedConfig {
            width: builder.width,
            height: builder.height,
            pixel_format: builder.pixel_format,
            quality: builder.quality,
            subsampling: builder.subsampling,
            mode: builder.mode,
            huffman: builder.huffman.clone(),
            chroma_downsampling: builder.chroma_downsampling,
            restart_interval: builder.restart_interval,
            use_xyb: builder.use_xyb,
            #[cfg(feature = "parallel")]
            parallel: builder.parallel,
            #[cfg(feature = "trellis")]
            hybrid_config: builder.hybrid_config,
            custom_aq_map: builder.custom_aq_map,
            #[cfg(feature = "trellis")]
            trellis: builder.trellis,
            encoding_tables: builder.encoding_tables,
            edge_padding: crate::types::EdgePaddingConfig::default(),
            original_width: None,
            original_height: None,
            allow_16bit_quant_tables: builder.allow_16bit_quant_tables,
            force_sof1: builder.force_sof1,
            separate_chroma_tables: builder.separate_chroma_tables,
            scan_strategy: builder.scan_strategy,
        };

        #[allow(unused_mut)]
        let mut config = config;

        // Enforce MCU row alignment for any nonzero restart interval.
        // Non-row-aligned restarts break the fused chroma upsample + color
        // conversion decode path, which processes complete MCU rows.
        if config.restart_interval > 0 {
            config.restart_interval = config.align_restart_to_row(config.restart_interval);
        }

        let streaming = if enable_streaming {
            // Get tables: custom if provided, otherwise standard JPEG tables
            let tables = match builder.huffman {
                HuffmanStrategy::Custom(tables) => tables,
                HuffmanStrategy::Fixed => Box::new(crate::huffman::builtin_tables::select_tables(
                    &builder.quality,
                    builder.use_xyb,
                    builder.subsampling,
                )),
                HuffmanStrategy::FixedAnnexK => {
                    // Annex K tables are well-defined constants, cannot fail
                    Box::new(
                        crate::huffman::optimize::HuffmanTableSet::annex_k()
                            .expect("JPEG Annex K tables are constant and valid"),
                    )
                }
                HuffmanStrategy::Optimize => unreachable!(),
            };

            // Write JPEG header (SOI through SOS) into buffer
            let mut header = Vec::new();
            config.write_header(&mut header)?;
            config.write_quant_tables(&mut header, &y_quant, &cb_quant, &cr_quant)?;
            let is_extended =
                y_quant.precision > 0 || cb_quant.precision > 0 || cr_quant.precision > 0;
            config.write_frame_header_ex(&mut header, is_extended)?;
            config.write_huffman_tables_optimized(&mut header, &tables)?;
            if config.restart_interval > 0 {
                config.write_restart_interval(&mut header)?;
            }
            config.write_scan_header(&mut header)?;

            Some(StreamingOutputState {
                writer: crate::foundation::bitstream::BitWriter::new(),
                tables,
                entropy_state: crate::entropy::StreamingEntropyState::new(),
                total_mcus: processor.layout.total_mcus,
                header,
            })
        } else {
            None
        };

        Ok(Self {
            width,
            height,
            bytes_per_row,
            strip_height,
            row_buffer,
            rows_buffered: 0,
            current_y: 0,
            processor,
            config,
            y_quant,
            cb_quant,
            cr_quant,
            streaming,
        })
    }

    /// Returns the number of rows pushed so far.
    #[must_use]
    pub(crate) fn rows_pushed(&self) -> usize {
        self.current_y + self.rows_buffered
    }

    /// Returns the expected number of bytes per row.
    #[must_use]
    pub(crate) fn bytes_per_row(&self) -> usize {
        self.bytes_per_row
    }

    /// Returns the total height of the image.
    #[must_use]
    pub(crate) fn height(&self) -> usize {
        self.height
    }

    /// Returns the strip height (internal processing unit).
    #[must_use]
    pub(crate) fn strip_height(&self) -> usize {
        self.strip_height
    }

    /// Returns allocation statistics from the strip processor.
    ///
    /// This tracks all major allocations made during encoding setup,
    /// including color plane buffers, DCT block storage, and AQ buffers.
    #[must_use]
    pub(crate) fn encode_stats(&self) -> &crate::foundation::alloc::EncodeStats {
        self.processor.encode_stats()
    }

    /// Returns whether this encoder is in streaming-through mode.
    ///
    /// In streaming mode, blocks are encoded immediately on each strip flush.
    /// In buffered mode (default), all blocks are buffered and encoded at `finish()`.
    #[must_use]
    pub(crate) fn is_streaming(&self) -> bool {
        self.streaming.is_some()
    }

    /// Pushes a single row of pixel data.
    ///
    /// The row must be exactly `bytes_per_row()` bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Row length doesn't match expected bytes per row
    /// - All rows have already been pushed
    /// - Internal processing fails
    pub(crate) fn push_row(&mut self, row: &[u8]) -> Result<()> {
        self.push_row_with_stop(row, Unstoppable)
    }

    /// Pushes a single row with cancellation support.
    ///
    /// The `stop` source is checked before processing each strip.
    /// Returns `Error::cancelled()` if cancellation is requested.
    pub(crate) fn push_row_with_stop(&mut self, row: &[u8], stop: impl Stop) -> Result<()> {
        // Check cancellation
        stop.check()?;

        // Validate row size
        if row.len() != self.bytes_per_row {
            return Err(Error::invalid_buffer_size(self.bytes_per_row, row.len()));
        }

        // Check if we've already received all rows
        if self.current_y + self.rows_buffered >= self.height {
            return Err(Error::io_error(format!(
                "already received all {} rows",
                self.height
            )));
        }

        // Copy row into buffer
        let offset = self.rows_buffered * self.bytes_per_row;
        self.row_buffer[offset..offset + self.bytes_per_row].copy_from_slice(row);
        self.rows_buffered += 1;

        // Check if we should flush the strip
        let remaining = self.height - self.current_y;
        if self.rows_buffered >= self.strip_height || self.rows_buffered >= remaining {
            self.flush_strip_with_stop(&stop)?;
        }

        Ok(())
    }

    /// Pushes multiple rows at once.
    ///
    /// The data must be exactly `num_rows * bytes_per_row()` bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Data length doesn't match expected size
    /// - Too many rows would be pushed
    /// - Internal processing fails
    pub(crate) fn push_rows(&mut self, data: &[u8], num_rows: usize) -> Result<()> {
        self.push_rows_with_stop(data, num_rows, Unstoppable)
    }

    /// Pushes multiple rows with cancellation support.
    ///
    /// This method is optimized to process complete strips directly from the input
    /// buffer without intermediate copies. Only partial strips at the beginning
    /// and end require buffering.
    pub(crate) fn push_rows_with_stop(
        &mut self,
        data: &[u8],
        num_rows: usize,
        stop: impl Stop,
    ) -> Result<()> {
        let expected_len = num_rows * self.bytes_per_row;
        if data.len() != expected_len {
            return Err(Error::invalid_buffer_size(expected_len, data.len()));
        }

        if num_rows == 0 {
            return Ok(());
        }

        // Check if we've already received all rows
        if self.current_y + self.rows_buffered >= self.height {
            return Err(Error::io_error(format!(
                "already received all {} rows",
                self.height
            )));
        }

        let mut data_offset = 0usize;
        let mut rows_remaining = num_rows;

        // Step 1: Complete any partial strip in buffer
        if self.rows_buffered > 0 {
            let rows_to_complete = (self.strip_height - self.rows_buffered).min(rows_remaining);
            let rows_to_complete =
                rows_to_complete.min(self.height - self.current_y - self.rows_buffered);

            // Copy rows to buffer to complete the strip
            let buf_offset = self.rows_buffered * self.bytes_per_row;
            let src_bytes = rows_to_complete * self.bytes_per_row;
            self.row_buffer[buf_offset..buf_offset + src_bytes]
                .copy_from_slice(&data[data_offset..data_offset + src_bytes]);

            self.rows_buffered += rows_to_complete;
            data_offset += src_bytes;
            rows_remaining -= rows_to_complete;

            // Flush if strip is complete
            let remaining_height = self.height - self.current_y;
            if self.rows_buffered >= self.strip_height || self.rows_buffered >= remaining_height {
                self.flush_strip_with_stop(&stop)?;
            }
        }

        // Step 2: Process complete strips directly from input (no copy!)
        while rows_remaining >= self.strip_height {
            stop.check()?;

            let remaining_height = self.height - self.current_y;
            let strip_rows = self.strip_height.min(remaining_height);

            if strip_rows == 0 {
                break;
            }

            let strip_bytes = strip_rows * self.bytes_per_row;
            let strip_data = &data[data_offset..data_offset + strip_bytes];

            // Process directly from input buffer
            self.processor.process_strip(strip_data, self.current_y)?;

            // In streaming mode, encode blocks immediately to avoid accumulation
            if self.streaming.is_some() {
                self.encode_new_blocks_streaming()?;
            }

            self.current_y += strip_rows;

            data_offset += strip_bytes;
            rows_remaining -= strip_rows;
        }

        // Step 3: Buffer any remaining partial rows
        if rows_remaining > 0 {
            let remaining_height = self.height - self.current_y;
            let rows_to_buffer = rows_remaining.min(remaining_height);

            if rows_to_buffer > 0 {
                let src_bytes = rows_to_buffer * self.bytes_per_row;
                self.row_buffer[..src_bytes]
                    .copy_from_slice(&data[data_offset..data_offset + src_bytes]);
                self.rows_buffered = rows_to_buffer;

                // Check if this is the final partial strip
                if rows_to_buffer >= remaining_height {
                    self.flush_strip_with_stop(&stop)?;
                }
            }
        }

        Ok(())
    }

    /// Pushes a strip of YCbCr f32 planar data.
    ///
    /// This bypasses RGB→YCbCr conversion, accepting YCbCr data directly.
    /// Values should be in centered range [-128, 127].
    ///
    /// # Arguments
    /// * `y` - Y plane data (width × num_rows floats)
    /// * `cb` - Cb plane data (width × num_rows floats, full resolution)
    /// * `cr` - Cr plane data (width × num_rows floats, full resolution)
    /// * `num_rows` - Number of rows in this strip
    ///
    /// # Note
    ///
    /// Unlike `push_row` which buffers internally, this method processes
    /// the strip immediately. For optimal performance, push `strip_height()`
    /// rows at a time.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - RGB rows are already buffered (can't mix RGB and YCbCr input)
    /// - Plane sizes don't match expected dimensions
    /// - XYB mode is enabled (requires RGB input)
    pub(crate) fn push_ycbcr_strip_f32(
        &mut self,
        y: &[f32],
        cb: &[f32],
        cr: &[f32],
        num_rows: usize,
    ) -> Result<()> {
        // Can't mix RGB and YCbCr input
        if self.rows_buffered > 0 {
            return Err(Error::internal(
                "cannot mix RGB and YCbCr input (RGB rows buffered)",
            ));
        }

        // Validate we haven't received all rows yet
        if self.current_y >= self.height {
            return Err(Error::io_error(format!(
                "already received all {} rows",
                self.height
            )));
        }

        // Clamp to remaining rows
        let actual_rows = num_rows.min(self.height - self.current_y);

        // Validate plane sizes
        let expected_size = self.width * actual_rows;
        if y.len() < expected_size {
            return Err(Error::invalid_buffer_size(expected_size, y.len()));
        }
        if cb.len() < expected_size || cr.len() < expected_size {
            return Err(Error::invalid_buffer_size(
                expected_size,
                cb.len().min(cr.len()),
            ));
        }

        // Process in chunks of strip_height rows
        let mut processed = 0;
        while processed < actual_rows {
            let remaining = self.height - self.current_y;
            let strip_rows = self
                .strip_height
                .min(actual_rows - processed)
                .min(remaining);

            let start = processed * self.width;
            let end = start + strip_rows * self.width;

            self.processor.process_strip_ycbcr_f32(
                &y[start..end],
                &cb[start..end],
                &cr[start..end],
                self.current_y,
            )?;

            self.current_y += strip_rows;
            processed += strip_rows;
        }

        Ok(())
    }

    /// Pushes a strip of pre-downsampled YCbCr f32 planar data.
    ///
    /// This accepts chroma data that is already downsampled according to the
    /// subsampling mode. Skips the internal chroma downsampling step.
    ///
    /// # Arguments
    /// * `y` - Y plane data (width × num_rows floats)
    /// * `cb` - Cb plane data (chroma_width × chroma_rows floats)
    /// * `cr` - Cr plane data (chroma_width × chroma_rows floats)
    /// * `num_rows` - Number of Y rows in this strip
    ///
    /// # Chroma Dimensions
    /// - 4:4:4: cb/cr at full width × full height
    /// - 4:2:2: cb/cr at width/2 × full height
    /// - 4:2:0: cb/cr at width/2 × height/2
    pub(crate) fn push_ycbcr_strip_f32_subsampled(
        &mut self,
        y: &[f32],
        cb: &[f32],
        cr: &[f32],
        num_rows: usize,
    ) -> Result<()> {
        // Can't mix RGB and YCbCr input
        if self.rows_buffered > 0 {
            return Err(Error::internal(
                "cannot mix RGB and YCbCr input (RGB rows buffered)",
            ));
        }

        // Validate we haven't received all rows yet
        if self.current_y >= self.height {
            return Err(Error::io_error(format!(
                "already received all {} rows",
                self.height
            )));
        }

        // Clamp to remaining rows
        let actual_rows = num_rows.min(self.height - self.current_y);

        // Validate Y plane size
        let expected_y_size = self.width * actual_rows;
        if y.len() < expected_y_size {
            return Err(Error::invalid_buffer_size(expected_y_size, y.len()));
        }

        // Get subsampling info for chroma slicing
        let subsampling = self.processor.subsampling();
        let chroma_width = match subsampling {
            Subsampling::S444 | Subsampling::S440 => self.width,
            Subsampling::S422 | Subsampling::S420 => (self.width + 1) / 2,
        };
        let chroma_h_factor = match subsampling {
            Subsampling::S444 | Subsampling::S422 => 1,
            Subsampling::S420 | Subsampling::S440 => 2,
        };

        // Process in chunks of strip_height rows
        let mut y_processed = 0;
        let mut chroma_processed = 0;
        while y_processed < actual_rows {
            let remaining = self.height - self.current_y;
            let strip_rows = self
                .strip_height
                .min(actual_rows - y_processed)
                .min(remaining);

            let y_start = y_processed * self.width;
            let y_end = y_start + strip_rows * self.width;

            // Calculate chroma rows for this strip
            let chroma_rows = (strip_rows + chroma_h_factor - 1) / chroma_h_factor;
            let c_start = chroma_processed * chroma_width;
            let c_end = c_start + chroma_rows * chroma_width;

            self.processor.process_strip_ycbcr_f32_subsampled(
                &y[y_start..y_end],
                &cb[c_start..c_end.min(cb.len())],
                &cr[c_start..c_end.min(cr.len())],
                self.current_y,
            )?;

            self.current_y += strip_rows;
            y_processed += strip_rows;
            chroma_processed += chroma_rows;
        }

        Ok(())
    }

    /// Flushes the current strip buffer to the processor.
    fn flush_strip_with_stop(&mut self, stop: &impl Stop) -> Result<()> {
        stop.check()?;

        if self.rows_buffered == 0 {
            return Ok(());
        }

        let strip_data = &self.row_buffer[..self.rows_buffered * self.bytes_per_row];
        self.processor.process_strip(strip_data, self.current_y)?;

        // In streaming mode, encode the new blocks immediately and free them
        if self.streaming.is_some() {
            self.encode_new_blocks_streaming()?;
        }

        self.current_y += self.rows_buffered;
        self.rows_buffered = 0;

        Ok(())
    }

    /// Encodes newly-produced blocks in streaming mode.
    ///
    /// Borrows blocks from the strip processor, encodes them to the
    /// BitWriter, then clears them (keeping allocation for reuse).
    fn encode_new_blocks_streaming(&mut self) -> Result<()> {
        let is_color = !self.config.pixel_format.is_grayscale();
        let width = self.width;
        let subsampling = self.config.subsampling;
        let restart_interval = self.config.restart_interval;

        let state = self.streaming.as_mut().unwrap();
        crate::entropy::encode_blocks_mcu_order(
            self.processor.y_blocks(),
            self.processor.cb_blocks(),
            self.processor.cr_blocks(),
            &state.tables,
            &mut state.writer,
            is_color,
            &mut state.entropy_state,
            subsampling,
            width,
            restart_interval,
            state.total_mcus,
        )?;

        self.processor.clear_blocks();

        Ok(())
    }

    /// Finishes encoding and returns the JPEG data.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Not all rows have been pushed
    /// - JPEG generation fails
    pub(crate) fn finish(self) -> Result<Vec<u8>> {
        self.finish_with_stop(Unstoppable)
    }

    /// Finishes encoding and returns both the JPEG and the frequency counts.
    ///
    /// For sequential mode with `HuffmanStrategy::Optimize`, the counts come from
    /// the optimization pass at no extra cost. For progressive mode, the blocks
    /// are counted separately (same quantized blocks, same symbol distribution).
    ///
    /// Returns `None` for counts if:
    /// - Streaming-through mode was used (no buffered blocks to count)
    pub(crate) fn finish_with_huffman_frequencies(
        self,
    ) -> Result<(
        Vec<u8>,
        Option<Box<super::blocks::HuffmanSymbolFrequencies>>,
    )> {
        let mut output = Vec::new();
        let counts = self.finish_into_with_huffman_frequencies(&mut output, Unstoppable)?;
        Ok((output, counts))
    }

    /// Finishes encoding with cancellation support.
    pub(crate) fn finish_with_stop(self, stop: impl Stop) -> Result<Vec<u8>> {
        let mut output = Vec::new();
        self.finish_into_with_stop(&mut output, stop)?;
        Ok(output)
    }

    /// Finishes encoding, writing directly to the provided buffer.
    ///
    /// This avoids an extra allocation compared to `finish()`. The buffer
    /// is cleared before writing.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Not all rows have been pushed
    /// - JPEG generation fails
    /// - Memory allocation fails
    pub(crate) fn finish_into(self, output: &mut Vec<u8>) -> Result<()> {
        self.finish_into_with_stop(output, Unstoppable)
    }

    /// Finishes encoding into provided buffer with cancellation support.
    pub(crate) fn finish_into_with_stop(
        mut self,
        output: &mut Vec<u8>,
        stop: impl Stop,
    ) -> Result<()> {
        stop.check()?;

        // Calculate total rows received
        let total_rows = self.current_y + self.rows_buffered;

        // Validate all rows were pushed before trying to process
        if total_rows < self.height {
            return Err(Error::io_error(format!(
                "only {} of {} rows were pushed",
                total_rows, self.height
            )));
        }

        // Flush any remaining rows (in streaming mode, this also encodes them)
        if self.rows_buffered > 0 {
            self.flush_strip_with_stop(&stop)?;
        }

        if let Some(mut streaming) = self.streaming.take() {
            // Streaming mode: finalize the strip processor to flush the last
            // pending iMCU (AQ delays blocks by one strip), then encode them
            let is_color = !self.config.pixel_format.is_grayscale();
            let width = self.width;
            let subsampling = self.config.subsampling;
            let restart_interval = self.config.restart_interval;

            let final_output = self.processor.finalize()?;
            if !final_output.y_blocks.is_empty() {
                crate::entropy::encode_blocks_mcu_order(
                    &final_output.y_blocks,
                    &final_output.cb_blocks,
                    &final_output.cr_blocks,
                    &streaming.tables,
                    &mut streaming.writer,
                    is_color,
                    &mut streaming.entropy_state,
                    subsampling,
                    width,
                    restart_interval,
                    streaming.total_mcus,
                )?;
            }

            // header + scan data + EOI
            Self::finish_streaming_static(streaming, output)
        } else {
            // Buffered mode: build complete JPEG from all blocks
            let config = self.config;
            let y_quant = self.y_quant;
            let cb_quant = self.cb_quant;
            let cr_quant = self.cr_quant;
            let width = self.width;
            let height = self.height;

            let strip_output = self.processor.finalize()?;

            Self::build_jpeg_from_blocks_into(
                &config,
                &y_quant,
                &cb_quant,
                &cr_quant,
                width,
                height,
                strip_output,
                output,
                stop,
            )
        }
    }

    /// Like `finish_into_with_stop`, but also returns frequency counts from
    /// the Huffman optimization pass when in buffered + `HuffmanStrategy::Optimize` mode.
    pub(crate) fn finish_into_with_huffman_frequencies(
        mut self,
        output: &mut Vec<u8>,
        stop: impl Stop,
    ) -> Result<Option<Box<super::blocks::HuffmanSymbolFrequencies>>> {
        stop.check()?;

        let total_rows = self.current_y + self.rows_buffered;
        if total_rows < self.height {
            return Err(Error::io_error(format!(
                "only {} of {} rows were pushed",
                total_rows, self.height
            )));
        }

        if self.rows_buffered > 0 {
            self.flush_strip_with_stop(&stop)?;
        }

        if let Some(mut streaming) = self.streaming.take() {
            // Streaming mode - no buffered blocks, no counts available
            let is_color = !self.config.pixel_format.is_grayscale();
            let width = self.width;
            let subsampling = self.config.subsampling;
            let restart_interval = self.config.restart_interval;

            let final_output = self.processor.finalize()?;
            if !final_output.y_blocks.is_empty() {
                crate::entropy::encode_blocks_mcu_order(
                    &final_output.y_blocks,
                    &final_output.cb_blocks,
                    &final_output.cr_blocks,
                    &streaming.tables,
                    &mut streaming.writer,
                    is_color,
                    &mut streaming.entropy_state,
                    subsampling,
                    width,
                    restart_interval,
                    streaming.total_mcus,
                )?;
            }
            Self::finish_streaming_static(streaming, output)?;
            Ok(None)
        } else {
            // Buffered mode: extract frequency counts from the optimize pass
            let config = self.config;
            let y_quant = self.y_quant;
            let cb_quant = self.cb_quant;
            let cr_quant = self.cr_quant;
            let strip_output = self.processor.finalize()?;

            match config.mode {
                JpegMode::Progressive => {
                    if !matches!(config.huffman, HuffmanStrategy::Optimize) {
                        return Err(Error::unsupported_feature(
                            "Progressive mode requires optimized Huffman tables",
                        ));
                    }

                    // Count frequencies from the buffered blocks. The symbol
                    // distribution is the same regardless of scan structure,
                    // so single-scan counts are useful for general-purpose table training.
                    let is_color = !config.pixel_format.is_grayscale();
                    let counts = Box::new(config.count_block_frequencies(
                        &strip_output.y_blocks,
                        &strip_output.cb_blocks,
                        &strip_output.cr_blocks,
                        is_color,
                    ));

                    config.encode_progressive_from_blocks_into(
                        &strip_output.y_blocks,
                        &strip_output.cb_blocks,
                        &strip_output.cr_blocks,
                        &y_quant,
                        &cb_quant,
                        &cr_quant,
                        output,
                    )?;
                    Ok(Some(counts))
                }
                _ => {
                    // Sequential: collect_frequencies=true gets the counts
                    // from the optimize pass at no extra cost.
                    Self::build_jpeg_sequential_into(
                        &config,
                        &y_quant,
                        &cb_quant,
                        &cr_quant,
                        strip_output,
                        output,
                        true,
                    )
                }
            }
        }
    }

    /// Finishes streaming-through encoding.
    ///
    /// Combines the pre-written header with the scan data from the BitWriter
    /// and appends the EOI marker.
    fn finish_streaming_static(
        streaming: StreamingOutputState,
        output: &mut Vec<u8>,
    ) -> Result<()> {
        // Flush the BitWriter's remaining bits and scan data
        let scan_data = streaming.writer.into_bytes();

        // Assemble: header + scan data + EOI
        let total_size = streaming.header.len() + scan_data.len() + 2;
        output.clear();
        output
            .try_reserve(total_size)
            .map_err(|_| Error::allocation_failed(total_size, "streaming finish output"))?;

        output.extend_from_slice(&streaming.header);
        output.extend_from_slice(&scan_data);
        output.push(0xFF);
        output.push(crate::foundation::consts::MARKER_EOI);

        Ok(())
    }

    /// Builds JPEG output from processed blocks.
    fn build_jpeg_from_blocks(
        config: &ComputedConfig,
        y_quant: &QuantTable,
        cb_quant: &QuantTable,
        cr_quant: &QuantTable,
        width: usize,
        height: usize,
        strip_output: crate::encode::strip::StripProcessorOutput,
        stop: impl Stop,
    ) -> Result<Vec<u8>> {
        let mut output = Vec::new();
        Self::build_jpeg_from_blocks_into(
            config,
            y_quant,
            cb_quant,
            cr_quant,
            width,
            height,
            strip_output,
            &mut output,
            stop,
        )?;
        Ok(output)
    }

    /// Builds JPEG output from processed blocks into provided buffer.
    fn build_jpeg_from_blocks_into(
        config: &ComputedConfig,
        y_quant: &QuantTable,
        cb_quant: &QuantTable,
        cr_quant: &QuantTable,
        _width: usize,
        _height: usize,
        strip_output: crate::encode::strip::StripProcessorOutput,
        output: &mut Vec<u8>,
        stop: impl Stop,
    ) -> Result<()> {
        stop.check()?;

        // Branch based on encoding mode (mirrors encode_strip_based in encode/mod.rs)
        match config.mode {
            JpegMode::Progressive => {
                // Progressive mode requires optimized Huffman tables
                if !matches!(config.huffman, HuffmanStrategy::Optimize) {
                    return Err(Error::unsupported_feature(
                        "Progressive mode requires optimized Huffman tables",
                    ));
                }
                // Use progressive encoding path
                config.encode_progressive_from_blocks_into(
                    &strip_output.y_blocks,
                    &strip_output.cb_blocks,
                    &strip_output.cr_blocks,
                    y_quant,
                    cb_quant,
                    cr_quant,
                    output,
                )
            }
            _ => {
                // Sequential encoding
                Self::build_jpeg_sequential_into(
                    config,
                    y_quant,
                    cb_quant,
                    cr_quant,
                    strip_output,
                    output,
                    false,
                )?;
                Ok(())
            }
        }
    }

    /// Builds sequential JPEG output from processed blocks.
    fn build_jpeg_sequential(
        config: &ComputedConfig,
        y_quant: &QuantTable,
        cb_quant: &QuantTable,
        cr_quant: &QuantTable,
        strip_output: crate::encode::strip::StripProcessorOutput,
    ) -> Result<Vec<u8>> {
        let mut output = Vec::new();
        Self::build_jpeg_sequential_into(
            config,
            y_quant,
            cb_quant,
            cr_quant,
            strip_output,
            &mut output,
            false,
        )?;
        Ok(output)
    }

    /// Builds sequential JPEG output from processed blocks into provided buffer.
    ///
    /// When `collect_frequencies` is true, the YCbCr optimized Huffman path
    /// returns the symbol frequencies used to build the tables (at no extra
    /// cost—they are produced during the normal optimization pass).
    fn build_jpeg_sequential_into(
        config: &ComputedConfig,
        y_quant: &QuantTable,
        cb_quant: &QuantTable,
        cr_quant: &QuantTable,
        strip_output: crate::encode::strip::StripProcessorOutput,
        output: &mut Vec<u8>,
        collect_frequencies: bool,
    ) -> Result<Option<Box<super::blocks::HuffmanSymbolFrequencies>>> {
        let width = config.width as usize;
        let height = config.height as usize;

        output.clear();
        output
            .try_reserve(width * height / 4)
            .map_err(|_| Error::allocation_failed(width * height / 4, "sequential jpeg output"))?;

        let (scan_data, frequencies) = if config.use_xyb {
            Self::encode_sequential_xyb(
                config,
                y_quant,
                cb_quant,
                cr_quant,
                &strip_output,
                output,
                collect_frequencies,
            )?
        } else {
            Self::encode_sequential_ycbcr(
                config,
                y_quant,
                cb_quant,
                cr_quant,
                &strip_output,
                output,
                collect_frequencies,
            )?
        };

        output.extend_from_slice(&scan_data);

        // Write EOI marker
        output.push(0xFF);
        output.push(crate::foundation::consts::MARKER_EOI);

        Ok(frequencies)
    }

    /// Encodes sequential JPEG in XYB color mode.
    ///
    /// Writes XYB-specific headers (Adobe APP14, XYB ICC profile, XYB frame/scan
    /// headers) and encodes using XYB-specific table building and entropy coding.
    /// XYB mode never collects frequency tables.
    fn encode_sequential_xyb(
        config: &ComputedConfig,
        y_quant: &QuantTable,
        cb_quant: &QuantTable,
        cr_quant: &QuantTable,
        strip_output: &crate::encode::strip::StripProcessorOutput,
        output: &mut Vec<u8>,
        collect_frequencies: bool,
    ) -> Result<(
        Vec<u8>,
        Option<Box<super::blocks::HuffmanSymbolFrequencies>>,
    )> {
        config.write_header_xyb(output)?;
        config.write_app14_adobe(output, 0)?;
        config.write_icc_profile(output, &crate::foundation::consts::XYB_ICC_PROFILE)?;
        config.write_quant_tables_xyb(output, y_quant, cb_quant, cr_quant)?;

        // Use SOF1 if any quant table needs 16-bit precision, or if forced (XYB DC categories)
        let is_extended = config.force_sof1
            || y_quant.precision > 0
            || cb_quant.precision > 0
            || cr_quant.precision > 0;
        config.write_frame_header_xyb_ex(output, is_extended)?;

        if matches!(config.huffman, HuffmanStrategy::Optimize) {
            let (dc_table, ac_table, frequencies) = if collect_frequencies {
                let (dc, ac, f) = config.build_optimized_tables_xyb_raster_with_counts(
                    &strip_output.y_blocks,
                    &strip_output.cb_blocks,
                    &strip_output.cr_blocks,
                )?;
                (dc, ac, Some(f))
            } else {
                let (dc, ac) = config.build_optimized_tables_xyb_raster(
                    &strip_output.y_blocks,
                    &strip_output.cb_blocks,
                    &strip_output.cr_blocks,
                )?;
                (dc, ac, None)
            };

            config.write_huffman_tables_xyb_optimized(output, &dc_table, &ac_table);

            if config.restart_interval > 0 {
                config.write_restart_interval(output)?;
            }
            config.write_scan_header_xyb(output)?;

            let scan_data = config.encode_with_tables_xyb_raster(
                &strip_output.y_blocks,
                &strip_output.cb_blocks,
                &strip_output.cr_blocks,
                &dc_table,
                &ac_table,
            )?;
            Ok((scan_data, frequencies))
        } else if let HuffmanStrategy::Custom(ref tables) = config.huffman {
            // Custom tables: XYB uses dc_luma/ac_luma as the shared pair.
            config.write_huffman_tables_xyb_optimized(output, &tables.dc_luma, &tables.ac_luma);

            if config.restart_interval > 0 {
                config.write_restart_interval(output)?;
            }
            config.write_scan_header_xyb(output)?;

            let scan_data = config.encode_with_tables_xyb_raster(
                &strip_output.y_blocks,
                &strip_output.cb_blocks,
                &strip_output.cr_blocks,
                &tables.dc_luma,
                &tables.ac_luma,
            )?;
            Ok((scan_data, None))
        } else {
            // Fixed: use general-purpose trained tables for XYB
            let tables = crate::huffman::builtin_tables::select_tables(
                &config.quality,
                true,
                config.subsampling,
            );
            config.write_huffman_tables_xyb_optimized(output, &tables.dc_luma, &tables.ac_luma);

            if config.restart_interval > 0 {
                config.write_restart_interval(output)?;
            }
            config.write_scan_header_xyb(output)?;

            let scan_data = config.encode_with_tables_xyb_raster(
                &strip_output.y_blocks,
                &strip_output.cb_blocks,
                &strip_output.cr_blocks,
                &tables.dc_luma,
                &tables.ac_luma,
            )?;
            Ok((scan_data, None))
        }
    }

    /// Encodes sequential JPEG in YCbCr color mode.
    ///
    /// Writes standard JPEG headers and encodes using standard table building
    /// and entropy coding. When `collect_frequencies` is true, returns the
    /// symbol frequencies from the Huffman optimization pass at no extra cost.
    fn encode_sequential_ycbcr(
        config: &ComputedConfig,
        y_quant: &QuantTable,
        cb_quant: &QuantTable,
        cr_quant: &QuantTable,
        strip_output: &crate::encode::strip::StripProcessorOutput,
        output: &mut Vec<u8>,
        collect_frequencies: bool,
    ) -> Result<(
        Vec<u8>,
        Option<Box<super::blocks::HuffmanSymbolFrequencies>>,
    )> {
        let is_color = !config.pixel_format.is_grayscale();

        config.write_header(output)?;
        config.write_quant_tables(output, y_quant, cb_quant, cr_quant)?;

        // Use SOF1 if any quant table needs 16-bit precision, or if forced (XYB DC categories)
        let is_extended = config.force_sof1
            || y_quant.precision > 0
            || cb_quant.precision > 0
            || cr_quant.precision > 0;
        config.write_frame_header_ex(output, is_extended)?;

        if matches!(config.huffman, HuffmanStrategy::Optimize) {
            let (tables, frequencies) = if collect_frequencies {
                let (t, f) = config.build_optimized_tables_with_counts(
                    &strip_output.y_blocks,
                    &strip_output.cb_blocks,
                    &strip_output.cr_blocks,
                    is_color,
                )?;
                (t, Some(f))
            } else {
                let t = config.build_optimized_tables(
                    &strip_output.y_blocks,
                    &strip_output.cb_blocks,
                    &strip_output.cr_blocks,
                    is_color,
                )?;
                (t, None)
            };

            config.write_huffman_tables_optimized(output, &tables)?;

            if config.restart_interval > 0 {
                config.write_restart_interval(output)?;
            }
            config.write_scan_header(output)?;

            let scan_data = config.encode_with_tables(
                &strip_output.y_blocks,
                &strip_output.cb_blocks,
                &strip_output.cr_blocks,
                is_color,
                Some(&tables),
            )?;
            Ok((scan_data, frequencies))
        } else if let HuffmanStrategy::Custom(ref tables) = config.huffman {
            config.write_huffman_tables_optimized(output, tables)?;

            if config.restart_interval > 0 {
                config.write_restart_interval(output)?;
            }
            config.write_scan_header(output)?;

            let scan_data = config.encode_with_tables(
                &strip_output.y_blocks,
                &strip_output.cb_blocks,
                &strip_output.cr_blocks,
                is_color,
                Some(tables),
            )?;
            Ok((scan_data, None))
        } else {
            // Fixed: use general-purpose trained tables
            let tables = crate::huffman::builtin_tables::select_tables(
                &config.quality,
                false,
                config.subsampling,
            );
            config.write_huffman_tables_optimized(output, &tables)?;

            if config.restart_interval > 0 {
                config.write_restart_interval(output)?;
            }
            config.write_scan_header(output)?;

            let scan_data = config.encode_with_tables(
                &strip_output.y_blocks,
                &strip_output.cb_blocks,
                &strip_output.cr_blocks,
                is_color,
                Some(&tables),
            )?;
            Ok((scan_data, None))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encode::encoder_types::Quality;

    #[test]
    fn test_streaming_encoder_creation() {
        let encoder = StreamingEncoder::new(640, 480).start();
        assert!(encoder.is_ok());
        let encoder = encoder.unwrap();
        assert_eq!(encoder.height(), 480);
        assert_eq!(encoder.bytes_per_row(), 640 * 3); // RGB default
    }

    #[test]
    fn test_streaming_encoder_420_strip_height() {
        let encoder = StreamingEncoder::new(640, 480)
            .subsampling(Subsampling::S420)
            .start()
            .unwrap();
        assert_eq!(encoder.strip_height(), 16);
    }

    #[test]
    fn test_streaming_encoder_444_strip_height() {
        let encoder = StreamingEncoder::new(640, 480)
            .subsampling(Subsampling::S444)
            .start()
            .unwrap();
        assert_eq!(encoder.strip_height(), 8);
    }

    #[test]
    fn test_streaming_encoder_wrong_row_size() {
        let mut encoder = StreamingEncoder::new(640, 480).start().unwrap();
        let wrong_row = vec![0u8; 100]; // Wrong size
        let result = encoder.push_row(&wrong_row);
        assert!(result.is_err());
    }

    #[test]
    fn test_streaming_encoder_too_many_rows() {
        let mut encoder = StreamingEncoder::new(4, 2).start().unwrap();
        let row = vec![128u8; 4 * 3]; // 4 pixels * 3 channels

        // Push first 2 rows (all of them)
        encoder.push_row(&row).unwrap();
        encoder.push_row(&row).unwrap();

        // Third row should fail
        let result = encoder.push_row(&row);
        assert!(result.is_err());
    }

    #[test]
    fn test_streaming_encoder_incomplete() {
        let mut encoder = StreamingEncoder::new(4, 4).start().unwrap();
        let row = vec![128u8; 4 * 3];

        // Push only 2 of 4 rows
        encoder.push_row(&row).unwrap();
        encoder.push_row(&row).unwrap();

        // finish() should fail
        let result = encoder.finish();
        assert!(result.is_err());
    }

    #[test]
    fn test_memory_estimate() {
        let estimate = StreamingEncoder::new(3840, 2160)
            .subsampling(Subsampling::S420)
            .estimate_memory_usage();

        // 4K with 4:2:0: ~28 MB (blocks + entropy output + working buffers)
        // Heaptrack measured ~28 MB for encoder alone (excluding input pixels)
        assert!(estimate > 25_000_000, "estimate {} too low", estimate);
        assert!(estimate < 40_000_000, "estimate {} too high", estimate);
    }

    #[test]
    fn test_streaming_matches_oneshot() {
        use archmage::testing::{CompileTimePolicy, for_each_token_permutation};

        // Create a small test image
        let width = 32u32;
        let height = 32u32;
        let pixels: Vec<u8> = (0..width * height * 3)
            .map(|i| ((i * 17) % 256) as u8)
            .collect();

        let _ = for_each_token_permutation(CompileTimePolicy::Warn, |perm| {
            // Encode with one-shot method
            let oneshot_result = StreamingEncoder::new(width, height)
                .quality(Quality::ApproxJpegli(85.0))
                .subsampling(Subsampling::S444)
                .encode(&pixels)
                .unwrap();

            // Encode with streaming encoder (row by row)
            let mut streaming = StreamingEncoder::new(width, height)
                .quality(Quality::ApproxJpegli(85.0))
                .subsampling(Subsampling::S444)
                .start()
                .unwrap();

            let row_size = width as usize * 3;
            for y in 0..height as usize {
                let start = y * row_size;
                let end = start + row_size;
                streaming.push_row(&pixels[start..end]).unwrap();
            }
            let streaming_result = streaming.finish().unwrap();

            // Results should be identical
            assert_eq!(
                oneshot_result.len(),
                streaming_result.len(),
                "output lengths differ at {perm}"
            );
            assert_eq!(oneshot_result, streaming_result, "outputs differ at {perm}");
        });
    }

    // === Streaming-through tests ===

    fn make_test_image(width: usize, height: usize) -> Vec<u8> {
        let mut data = vec![0u8; width * height * 3];
        for y in 0..height {
            for x in 0..width {
                let i = (y * width + x) * 3;
                data[i] = (x * 255 / width.max(1)) as u8; // R gradient
                data[i + 1] = (y * 255 / height.max(1)) as u8; // G gradient
                data[i + 2] = 128; // B constant
            }
        }
        data
    }

    #[test]
    fn test_custom_tables_enables_streaming() {
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();
        let encoder = StreamingEncoder::new(64, 64)
            .custom_huffman_tables(tables)
            .start()
            .unwrap();
        assert!(encoder.is_streaming());
    }

    #[test]
    fn test_fixed_tables_enables_streaming() {
        let encoder = StreamingEncoder::new(64, 64)
            .optimize_huffman(false)
            .start()
            .unwrap();
        assert!(encoder.is_streaming());
    }

    #[test]
    fn test_progressive_does_not_stream() {
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();
        let encoder = StreamingEncoder::new(64, 64)
            .custom_huffman_tables(tables)
            .progressive(true)
            .start()
            .unwrap();
        assert!(!encoder.is_streaming());
    }

    #[test]
    fn test_default_is_buffered() {
        let encoder = StreamingEncoder::new(64, 64).start().unwrap();
        assert!(!encoder.is_streaming());
    }

    #[test]
    fn test_custom_tables_produces_valid_jpeg() {
        let width = 64;
        let height = 64;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .encode(&data)
            .unwrap();

        // Valid JPEG starts with FFD8 and ends with FFD9
        assert!(jpeg.len() > 4, "JPEG too small: {} bytes", jpeg.len());
        assert_eq!(jpeg[0], 0xFF);
        assert_eq!(jpeg[1], 0xD8);
        assert_eq!(jpeg[jpeg.len() - 2], 0xFF);
        assert_eq!(jpeg[jpeg.len() - 1], 0xD9);
    }

    #[test]
    fn test_fixed_tables_produces_valid_jpeg() {
        let width = 64;
        let height = 64;
        let data = make_test_image(width, height);

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .optimize_huffman(false)
            .encode(&data)
            .unwrap();

        assert!(jpeg.len() > 4, "JPEG too small: {} bytes", jpeg.len());
        assert_eq!(jpeg[0], 0xFF);
        assert_eq!(jpeg[1], 0xD8);
        assert_eq!(jpeg[jpeg.len() - 2], 0xFF);
        assert_eq!(jpeg[jpeg.len() - 1], 0xD9);
    }

    #[test]
    fn test_streaming_vs_buffered_both_valid() {
        let width = 128;
        let height = 128;
        let data = make_test_image(width, height);

        // Streaming path (fixed tables)
        let streaming_jpeg = StreamingEncoder::new(width as u32, height as u32)
            .optimize_huffman(false)
            .encode(&data)
            .unwrap();

        // Buffered path (optimized tables)
        let buffered_jpeg = StreamingEncoder::new(width as u32, height as u32)
            .optimize_huffman(true)
            .encode(&data)
            .unwrap();

        // Both should be valid JPEGs
        for (name, jpeg) in [("streaming", &streaming_jpeg), ("buffered", &buffered_jpeg)] {
            assert!(
                jpeg.len() > 4,
                "{name} JPEG too small: {} bytes",
                jpeg.len()
            );
            assert_eq!(jpeg[0], 0xFF, "{name} missing SOI");
            assert_eq!(jpeg[1], 0xD8, "{name} missing SOI");
            assert_eq!(jpeg[jpeg.len() - 2], 0xFF, "{name} missing EOI");
            assert_eq!(jpeg[jpeg.len() - 1], 0xD9, "{name} missing EOI");
        }

        // Standard tables produce larger output than optimized tables.
        // The difference shouldn't be extreme for natural-ish content.
        let ratio = streaming_jpeg.len() as f64 / buffered_jpeg.len() as f64;
        assert!(
            ratio < 1.7,
            "streaming is too much larger than buffered: {ratio:.2}x ({} vs {} bytes)",
            streaming_jpeg.len(),
            buffered_jpeg.len(),
        );
    }

    #[test]
    fn test_streaming_420_produces_valid_jpeg() {
        let width = 128;
        let height = 128;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .subsampling(Subsampling::S420)
            .encode(&data)
            .unwrap();

        assert!(jpeg.len() > 4);
        assert_eq!(jpeg[0], 0xFF);
        assert_eq!(jpeg[1], 0xD8);
        assert_eq!(jpeg[jpeg.len() - 2], 0xFF);
        assert_eq!(jpeg[jpeg.len() - 1], 0xD9);
    }

    #[test]
    fn test_streaming_non_mcu_aligned_dimensions() {
        // Non-8-aligned dimensions to test edge handling
        let width = 67;
        let height = 53;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .encode(&data)
            .unwrap();

        assert!(jpeg.len() > 4);
        assert_eq!(jpeg[0], 0xFF);
        assert_eq!(jpeg[1], 0xD8);
        assert_eq!(jpeg[jpeg.len() - 2], 0xFF);
        assert_eq!(jpeg[jpeg.len() - 1], 0xD9);
    }

    #[test]
    fn test_streaming_422_produces_valid_jpeg() {
        let width = 128;
        let height = 128;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .subsampling(Subsampling::S422)
            .encode(&data)
            .unwrap();

        assert_valid_jpeg(&jpeg, "422");
    }

    #[test]
    fn test_streaming_440_produces_valid_jpeg() {
        let width = 128;
        let height = 128;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .subsampling(Subsampling::S440)
            .encode(&data)
            .unwrap();

        assert_valid_jpeg(&jpeg, "440");
    }

    #[test]
    fn test_streaming_with_restart_markers() {
        let width = 128;
        let height = 128;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        // Use row-aligned interval: 16 MCU cols for 128px 4:4:4
        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .restart_interval(16)
            .encode(&data)
            .unwrap();

        assert_valid_jpeg(&jpeg, "restart");

        // Verify restart markers are present in the scan data
        // Restart markers are FFD0-FFD7
        let mut restart_count = 0;
        for i in 0..jpeg.len() - 1 {
            if jpeg[i] == 0xFF && (0xD0..=0xD7).contains(&jpeg[i + 1]) {
                restart_count += 1;
            }
        }
        assert!(
            restart_count > 0,
            "Expected restart markers in output, found none"
        );
    }

    #[test]
    fn test_streaming_420_non_aligned() {
        // Non-16-aligned height with 4:2:0 (strip height = 16)
        let width = 100;
        let height = 75;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .subsampling(Subsampling::S420)
            .encode(&data)
            .unwrap();

        assert_valid_jpeg(&jpeg, "420-non-aligned");
    }

    #[test]
    fn test_streaming_larger_image() {
        // 512×512 exercises multiple strip flushes and DC prediction across strips
        let width = 512;
        let height = 512;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .encode(&data)
            .unwrap();

        assert_valid_jpeg(&jpeg, "512x512");
        // Sanity: compressed size should be smaller than raw RGB
        assert!(
            jpeg.len() < data.len(),
            "JPEG ({}) should be smaller than raw ({})",
            jpeg.len(),
            data.len()
        );
    }

    #[test]
    fn test_streaming_row_by_row() {
        // Verify row-by-row push works in streaming mode
        let width = 64;
        let height = 64;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let mut encoder = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .start()
            .unwrap();

        assert!(encoder.is_streaming());

        let row_bytes = width * 3;
        for y in 0..height {
            encoder
                .push_row(&data[y * row_bytes..(y + 1) * row_bytes])
                .unwrap();
        }

        let jpeg = encoder.finish().unwrap();
        assert_valid_jpeg(&jpeg, "row-by-row");
    }

    #[test]
    fn test_streaming_finish_into() {
        // Verify finish_into writes to caller's buffer
        let width = 64;
        let height = 64;
        let data = make_test_image(width, height);

        let mut encoder = StreamingEncoder::new(width as u32, height as u32)
            .optimize_huffman(false)
            .start()
            .unwrap();

        let row_bytes = width * 3;
        for y in 0..height {
            encoder
                .push_row(&data[y * row_bytes..(y + 1) * row_bytes])
                .unwrap();
        }

        let mut output = Vec::new();
        encoder.finish_into(&mut output).unwrap();

        assert_valid_jpeg(&output, "finish_into");
    }

    #[test]
    fn test_streaming_row_by_row_matches_encode() {
        use archmage::testing::{CompileTimePolicy, for_each_token_permutation};

        // Row-by-row and encode() convenience should produce identical output
        let width = 64;
        let height = 64;
        let data = make_test_image(width, height);

        let _ = for_each_token_permutation(CompileTimePolicy::Warn, |perm| {
            let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

            // Path 1: encode() convenience
            let jpeg_oneshot = StreamingEncoder::new(width as u32, height as u32)
                .custom_huffman_tables(tables.clone())
                .encode(&data)
                .unwrap();

            // Path 2: row-by-row
            let mut encoder = StreamingEncoder::new(width as u32, height as u32)
                .custom_huffman_tables(tables)
                .start()
                .unwrap();
            let row_bytes = width * 3;
            for y in 0..height {
                encoder
                    .push_row(&data[y * row_bytes..(y + 1) * row_bytes])
                    .unwrap();
            }
            let jpeg_manual = encoder.finish().unwrap();

            assert_eq!(
                jpeg_oneshot, jpeg_manual,
                "encode() and row-by-row should produce identical output at {perm}"
            );
        });
    }

    #[test]
    fn test_streaming_multiple_qualities() {
        // Verify streaming works across a range of quality levels
        let width = 64;
        let height = 64;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let mut prev_size = usize::MAX;
        for &q in &[95, 80, 50, 20] {
            let jpeg = StreamingEncoder::new(width as u32, height as u32)
                .custom_huffman_tables(tables.clone())
                .quality(Quality::from(q))
                .encode(&data)
                .unwrap();

            assert_valid_jpeg(&jpeg, &format!("q{q}"));

            // Lower quality should generally produce smaller files
            // (not strictly monotonic for all content, but true for gradients)
            if q < 95 {
                assert!(
                    jpeg.len() < prev_size,
                    "q{q} ({} bytes) should be smaller than previous ({} bytes)",
                    jpeg.len(),
                    prev_size,
                );
            }
            prev_size = jpeg.len();
        }
    }

    /// Decode streaming output and verify dimensions and pixel count.
    #[test]
    #[cfg(feature = "decoder")]
    fn test_streaming_round_trip_decode() {
        let width = 128;
        let height = 128;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .encode(&data)
            .unwrap();

        #[allow(deprecated)]
        let decoded = crate::decode::Decoder::new()
            .decode(&jpeg, enough::Unstoppable)
            .unwrap();
        assert_eq!(decoded.width, width as u32);
        assert_eq!(decoded.height, height as u32);
        assert_eq!(decoded.pixels_u8().unwrap().len(), width * height * 3);
    }

    /// Decode 4:2:0 streaming output and verify dimensions.
    #[test]
    #[cfg(feature = "decoder")]
    fn test_streaming_420_round_trip_decode() {
        let width = 128;
        let height = 128;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .subsampling(Subsampling::S420)
            .encode(&data)
            .unwrap();

        #[allow(deprecated)]
        let decoded = crate::decode::Decoder::new()
            .decode(&jpeg, enough::Unstoppable)
            .unwrap();
        assert_eq!(decoded.width, width as u32);
        assert_eq!(decoded.height, height as u32);
    }

    /// Decode streaming output with restart markers and verify it decodes correctly.
    #[test]
    #[cfg(feature = "decoder")]
    fn test_streaming_restart_round_trip_decode() {
        let width = 128;
        let height = 128;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .restart_interval(5)
            .encode(&data)
            .unwrap();

        #[allow(deprecated)]
        let decoded = crate::decode::Decoder::new()
            .decode(&jpeg, enough::Unstoppable)
            .unwrap();
        assert_eq!(decoded.width, width as u32);
        assert_eq!(decoded.height, height as u32);
        assert_eq!(decoded.pixels_u8().unwrap().len(), width * height * 3);
    }

    /// Decode non-aligned streaming output with 4:2:0.
    #[test]
    #[cfg(feature = "decoder")]
    fn test_streaming_non_aligned_420_round_trip() {
        let width = 100;
        let height = 75;
        let data = make_test_image(width, height);
        let tables = crate::huffman::optimize::HuffmanTableSet::from_standard().unwrap();

        let jpeg = StreamingEncoder::new(width as u32, height as u32)
            .custom_huffman_tables(tables)
            .subsampling(Subsampling::S420)
            .encode(&data)
            .unwrap();

        #[allow(deprecated)]
        let decoded = crate::decode::Decoder::new()
            .decode(&jpeg, enough::Unstoppable)
            .unwrap();
        assert_eq!(decoded.width, width as u32);
        assert_eq!(decoded.height, height as u32);
    }

    fn assert_valid_jpeg(jpeg: &[u8], label: &str) {
        assert!(
            jpeg.len() > 4,
            "{label}: JPEG too small: {} bytes",
            jpeg.len()
        );
        assert_eq!(jpeg[0], 0xFF, "{label}: missing SOI");
        assert_eq!(jpeg[1], 0xD8, "{label}: missing SOI");
        assert_eq!(jpeg[jpeg.len() - 2], 0xFF, "{label}: missing EOI");
        assert_eq!(jpeg[jpeg.len() - 1], 0xD9, "{label}: missing EOI");
    }
}