djvu-rs 0.34.0

Read, render, convert, and create DjVu files. Pure-Rust DjVu decoder/encoder with CLI, WebAssembly, and Python bindings. DjVu to PDF, EPUB, TIFF, PNG, and text. MIT licensed, no GPL dependencies.
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
//! DjVu to TIFF exporter — phase 4 format extension.
//!
//! Converts DjVu documents to multi-page TIFF files.
//!
//! ## Key public types
//!
//! - [`TiffOptions`] — export parameters (color vs. bilevel mode)
//! - [`djvu_to_tiff_writer`] — low-memory writer API backed by row-streaming
//! - [`TiffError`] — errors from TIFF conversion
//!
//! ## Modes
//!
//! - **Color** (`TiffMode::Color`): each page is rendered to an RGB Pixmap
//!   and written as a 24-bit RGB TIFF strip.
//! - **Bilevel** (`TiffMode::Bilevel`): the JB2 mask is extracted and written
//!   as an 8-bit grayscale TIFF strip (0 = white, 255 = black). Pages with no
//!   JB2 mask fall back to a blank white page.
//!
//! ## Example
//!
//! ```no_run
//! use djvu_rs::djvu_document::DjVuDocument;
//! use djvu_rs::tiff_export::{djvu_to_tiff, TiffOptions, TiffMode};
//!
//! let data = std::fs::read("input.djvu").unwrap();
//! let doc = DjVuDocument::parse(&data).unwrap();
//! let tiff_bytes = djvu_to_tiff(&doc, &TiffOptions::default()).unwrap();
//! std::fs::write("output.tiff", tiff_bytes).unwrap();
//! ```

use std::io::{Cursor, Seek, Write};

use tiff::encoder::{Rational, TiffEncoder, colortype, compression::Deflate};
use tiff::tags::ResolutionUnit;

use crate::{
    djvu_document::{DjVuDocument, DjVuPage, DocError},
    djvu_render::{self, RenderError, RenderOptions},
    export_control::{ExportObserver, NoOpObserver},
};

// ---- Error ------------------------------------------------------------------

/// Errors from TIFF conversion.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TiffError {
    /// Document model error.
    #[error("document error: {0}")]
    Doc(#[from] DocError),

    /// Render error.
    #[error("render error: {0}")]
    Render(#[from] RenderError),

    /// TIFF encoding error.
    #[error("TIFF encoding error: {0}")]
    Encode(String),

    /// Export was cancelled by its observer.
    #[error("export cancelled")]
    Cancelled,
}

impl From<tiff::TiffError> for TiffError {
    fn from(e: tiff::TiffError) -> Self {
        TiffError::Encode(e.to_string())
    }
}

// ---- Options ----------------------------------------------------------------

/// Rendering mode for TIFF export.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TiffMode {
    /// Render each page as a full-color RGB image (24-bit per pixel).
    #[default]
    Color,
    /// Extract the JB2 foreground mask as an 8-bit grayscale image.
    ///
    /// Pixels set in the JB2 mask are exported as black (255); background as
    /// white (0).  Pages with no JB2 mask are written as blank white pages.
    Bilevel,
}

/// Compression choice for [`TiffMode::Bilevel`] pages (#579).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TiffBilevelCompression {
    /// 8-bit grayscale strips with Deflate — the historical default.
    #[default]
    Deflate,
    /// 1-bit CCITT Group 4 (T.6) via [`crate::smmr::encode_g4`] — the native
    /// archival compression for bilevel scans. Written by a minimal in-crate
    /// IFD writer (the `tiff` crate has no CCITT encoder); validated against
    /// libtiff/Pillow. Ignored in [`TiffMode::Color`].
    G4,
}

/// Options for DjVu → TIFF conversion.
#[derive(Debug, Clone)]
pub struct TiffOptions {
    /// Rendering mode.
    pub mode: TiffMode,
    /// Scale factor for color rendering (1.0 = native resolution).
    pub scale: f32,
    /// Compression for bilevel pages (default: the historical Deflate).
    pub bilevel_compression: TiffBilevelCompression,
}

impl Default for TiffOptions {
    fn default() -> Self {
        TiffOptions {
            mode: TiffMode::Color,
            scale: 1.0,
            bilevel_compression: TiffBilevelCompression::default(),
        }
    }
}

// ---- Entry point ------------------------------------------------------------

/// Convert a DjVu document to a multi-page TIFF byte buffer.
///
/// Each page in `doc` produces one IFD in the output TIFF.  Color pages use the
/// row-streaming renderer when the requested options do not require a full-image
/// post-processing pass; unsupported render options automatically fall back to
/// the full-pixmap path.
pub fn djvu_to_tiff(doc: &DjVuDocument, opts: &TiffOptions) -> Result<Vec<u8>, TiffError> {
    let mut buf: Vec<u8> = Vec::new();
    {
        let cursor = Cursor::new(&mut buf);
        djvu_to_tiff_writer(doc, opts, cursor)?;
    }
    Ok(buf)
}

/// Write a DjVu document as a multi-page TIFF to `writer`.
///
/// This is the lowest-memory TIFF export entry point: when color rendering is
/// streamable, rows are passed directly from [`djvu_render::render_streaming`]
/// into TIFF strips without constructing a full output [`crate::Pixmap`] or an
/// intermediate full RGB image. Bilevel G4 export first makes a sizing pass
/// that renders and encodes each page only to retain its dimensions, DPI, and
/// encoded length; it then renders and encodes each page again while writing
/// its strip and IFD. This keeps only one G4 payload active at a time, at the
/// cost of doubling G4 render-and-encode CPU. Progress for that mode is
/// reported only during the second, writing pass.
///
/// # Errors
///
/// On error, `writer` may contain a partial TIFF; the library does not clean it
/// up or provide atomic replacement (that policy belongs to the CLI/application
/// layer).
pub fn djvu_to_tiff_writer<W: Write + Seek>(
    doc: &DjVuDocument,
    opts: &TiffOptions,
    writer: W,
) -> Result<(), TiffError> {
    let mut observer = NoOpObserver;
    djvu_to_tiff_writer_with_observer(doc, opts, writer, &mut observer)
}

/// Convert a DjVu document to TIFF while reporting progress through `observer`.
///
/// With the `parallel` feature, cancellation is polled before the parallel
/// image-build batch. Work already scheduled in that batch may complete before
/// the cancellation is observed.
///
/// On error, `writer` may contain a partial TIFF; the library does not clean it
/// up or provide atomic replacement (that policy belongs to the CLI/application
/// layer).
pub fn djvu_to_tiff_writer_with_observer<W: Write + Seek>(
    doc: &DjVuDocument,
    opts: &TiffOptions,
    writer: W,
    observer: &mut dyn ExportObserver,
) -> Result<(), TiffError> {
    if opts.mode == TiffMode::Bilevel && opts.bilevel_compression == TiffBilevelCompression::G4 {
        return write_bilevel_g4_tiff(doc, writer, observer);
    }
    let mut encoder = TiffEncoder::new(writer)?;
    let indices: Vec<usize> = crate::export_common::page_indices(doc, None).collect();
    let total = indices.len();

    // Building a page's pixel buffer (color: render → RGB; bilevel: JB2 decode →
    // Gray8) is independent and CPU-heavy per page; only appending IFDs to the
    // single `TiffEncoder` must stay serial. With the `parallel` feature, build
    // every page's image concurrently via rayon, then write them in index order
    // — the same shape as the PDF/EPUB parallel exporters. Output is byte-
    // identical: the materialised RGB matches the streaming path (asserted by
    // `streamed_color_tiff_matches_render_pixmap*`), and the encoder produces the
    // same IFDs from the same pixels. This trades the sequential path's
    // row-streaming O(1)-page memory for wall-time, so it is gated to the feature.
    #[cfg(feature = "parallel")]
    {
        use rayon::prelude::*;
        if observer.cancelled() {
            return Err(TiffError::Cancelled);
        }
        let images: Vec<PageImage> = indices
            .par_iter()
            .map(|&i| {
                // #629: cold clone — decode caches drop with the page.
                let page = doc.page(i)?.clone();
                build_page_image(&page, opts)
            })
            .collect::<Result<Vec<_>, TiffError>>()?;
        for (done, img) in images.iter().enumerate() {
            if observer.cancelled() {
                return Err(TiffError::Cancelled);
            }
            write_page_image(&mut encoder, img)?;
            observer.on_progress(done + 1, total);
        }
    }

    #[cfg(not(feature = "parallel"))]
    for (done, &i) in indices.iter().enumerate() {
        if observer.cancelled() {
            return Err(TiffError::Cancelled);
        }
        // #629: cold clone — decode caches drop with the page.
        let page = doc.page(i)?.clone();
        match opts.mode {
            TiffMode::Color => write_color_page(&mut encoder, &page, opts.scale)?,
            TiffMode::Bilevel => write_bilevel_page(&mut encoder, &page)?,
        }
        observer.on_progress(done + 1, total);
    }
    Ok(())
}

/// A page's fully-materialised pixel buffer, ready to append as one TIFF IFD.
/// This is the `Send`-safe unit the parallel exporter builds off-thread; writing
/// it into the shared `TiffEncoder` is the serial tail.
#[cfg(feature = "parallel")]
struct PageImage {
    w: u32,
    h: u32,
    dpi: u32,
    data: PageImageData,
}

#[cfg(feature = "parallel")]
enum PageImageData {
    /// 24-bit RGB strip (color mode).
    Rgb(Vec<u8>),
    /// 8-bit grayscale strip written with Deflate compression (bilevel mode).
    GrayDeflate(Vec<u8>),
}

/// Produce one page's pixel buffer without touching the encoder. Mirrors the
/// sequential per-mode dispatch so the resulting IFD is byte-identical.
#[cfg(feature = "parallel")]
fn build_page_image(page: &DjVuPage, opts: &TiffOptions) -> Result<PageImage, TiffError> {
    match opts.mode {
        TiffMode::Color => {
            let (w, h, ropts) = color_render_options(page, opts.scale);
            let dpi = (page.dpi() as f32 * opts.scale).round() as u32;
            // Materialise the same RGB the sequential path writes: collect the
            // streamed rows when streamable (byte-identical to the strip path),
            // else fall back to the full-pixmap path for non-streamable options.
            let rgb = if ropts.can_stream(page) {
                let mut rgb = Vec::with_capacity(w as usize * h as usize * 3);
                djvu_render::render_streaming(page, &ropts, |_, rgba_row| {
                    crate::export_common::rgba_row_to_rgb(&mut rgb, rgba_row);
                })?;
                rgb
            } else {
                djvu_render::render_pixmap(page, &ropts)?.to_rgb()
            };
            Ok(PageImage {
                w,
                h,
                dpi,
                data: PageImageData::Rgb(rgb),
            })
        }
        TiffMode::Bilevel => {
            let w = page.width() as u32;
            let h = page.height() as u32;
            let gray = extract_bilevel_pixels(page, w, h)?;
            let dpi = page.dpi() as u32;
            Ok(PageImage {
                w,
                h,
                dpi,
                data: PageImageData::GrayDeflate(gray),
            })
        }
    }
}

/// Append one pre-built page image to the encoder as a single IFD.
#[cfg(feature = "parallel")]
fn write_page_image<W: Write + Seek>(
    encoder: &mut TiffEncoder<W>,
    img: &PageImage,
) -> Result<(), TiffError> {
    match &img.data {
        PageImageData::Rgb(rgb) => {
            let mut image = encoder.new_image::<colortype::RGB8>(img.w, img.h)?;
            image.resolution(ResolutionUnit::Inch, Rational { n: img.dpi, d: 1 });
            image.write_data(rgb)?;
        }
        PageImageData::GrayDeflate(gray) => {
            let mut image = encoder.new_image_with_compression::<colortype::Gray8, _>(
                img.w,
                img.h,
                Deflate::default(),
            )?;
            image.resolution(ResolutionUnit::Inch, Rational { n: img.dpi, d: 1 });
            image.write_data(gray)?;
        }
    }
    Ok(())
}

// ---- Per-page helpers -------------------------------------------------------

/// Render `page` as RGB and append one IFD to `encoder`.
#[cfg(not(feature = "parallel"))]
fn write_color_page<W: Write + Seek>(
    encoder: &mut TiffEncoder<W>,
    page: &DjVuPage,
    scale: f32,
) -> Result<(), TiffError> {
    let (w, h, opts) = color_render_options(page, scale);
    let dpi = (page.dpi() as f32 * scale).round() as u32;

    if opts.can_stream(page) {
        write_color_page_streaming(encoder, page, &opts, w, h, dpi)
    } else {
        write_color_page_pixmap(encoder, page, &opts, w, h, dpi)
    }
}

fn color_render_options(page: &DjVuPage, scale: f32) -> (u32, u32, RenderOptions) {
    let (w, h) =
        crate::export_common::scaled_size(page.width() as u32, page.height() as u32, scale);

    // Only the size is set; the pipeline derives the decode scale from `width`.
    // The remaining fields (bold/aa/rotation/permissive/resampling) are the
    // `RenderOptions` defaults.
    let opts = RenderOptions {
        width: w,
        height: h,
        ..RenderOptions::default()
    };
    (w, h, opts)
}

#[cfg(not(feature = "parallel"))]
fn write_color_page_streaming<W: Write + Seek>(
    encoder: &mut TiffEncoder<W>,
    page: &DjVuPage,
    opts: &RenderOptions,
    w: u32,
    h: u32,
    dpi: u32,
) -> Result<(), TiffError> {
    let mut img = encoder.new_image::<colortype::RGB8>(w, h)?;
    img.resolution(ResolutionUnit::Inch, Rational { n: dpi, d: 1 });

    let mut next_strip_samples = img.next_strip_sample_count() as usize;
    let mut strip = Vec::with_capacity(next_strip_samples);
    let mut encode_error: Option<tiff::TiffError> = None;

    djvu_render::render_streaming(page, opts, |_, rgba_row| {
        if encode_error.is_some() {
            return;
        }

        crate::export_common::rgba_row_to_rgb(&mut strip, rgba_row);

        if strip.len() > next_strip_samples {
            encode_error = Some(
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "streamed RGB strip exceeded expected TIFF strip size",
                )
                .into(),
            );
            return;
        }

        if strip.len() == next_strip_samples {
            if let Err(e) = img.write_strip(&strip) {
                encode_error = Some(e);
                return;
            }
            strip.clear();
            next_strip_samples = img.next_strip_sample_count() as usize;
        }
    })?;

    if let Some(e) = encode_error {
        return Err(e.into());
    }
    if !strip.is_empty() || img.next_strip_sample_count() != 0 {
        return Err(TiffError::Encode(
            "streamed render ended before all TIFF strips were written".to_string(),
        ));
    }

    img.finish()?;
    Ok(())
}

#[cfg(not(feature = "parallel"))]
fn write_color_page_pixmap<W: Write + Seek>(
    encoder: &mut TiffEncoder<W>,
    page: &DjVuPage,
    opts: &RenderOptions,
    w: u32,
    h: u32,
    dpi: u32,
) -> Result<(), TiffError> {
    let pixmap = djvu_render::render_pixmap(page, opts)?;
    let rgb = pixmap.to_rgb();

    let mut img = encoder.new_image::<colortype::RGB8>(w, h)?;
    img.resolution(ResolutionUnit::Inch, Rational { n: dpi, d: 1 });
    img.write_data(&rgb)?;
    Ok(())
}

/// Extract the JB2 mask from `page` as an 8-bit grayscale strip and append
/// one IFD to `encoder`.
///
/// Black pixels in the mask are written as 255; white background as 0.
/// Pages without a JB2 mask get a blank white page.
#[cfg(not(feature = "parallel"))]
fn write_bilevel_page<W: std::io::Write + std::io::Seek>(
    encoder: &mut TiffEncoder<W>,
    page: &DjVuPage,
) -> Result<(), TiffError> {
    let w = page.width() as u32;
    let h = page.height() as u32;

    // Try to extract the JB2 mask directly from the page chunks.
    let gray = extract_bilevel_pixels(page, w, h)?;
    let dpi = page.dpi() as u32;
    // Bilevel content is just 0x00 / 0xFF bytes with long runs (text on white),
    // so Deflate shrinks the Gray8 strip by ~20–50× — far past the 8× of a true
    // 1-bit packing, which the `tiff` crate's high-level encoder cannot emit (no
    // 1-bit ColorType). Deflate (tag 8) is universally readable.
    let mut img =
        encoder.new_image_with_compression::<colortype::Gray8, _>(w, h, Deflate::default())?;
    img.resolution(ResolutionUnit::Inch, Rational { n: dpi, d: 1 });
    img.write_data(&gray)?;
    Ok(())
}

/// Extract the JB2 Sjbz mask as 8-bit grayscale (0=white, 255=black).
///
/// Returns a blank white buffer if no Sjbz chunk is present (pure IW44 page).
/// Returns `Err` if an Sjbz chunk exists but decoding fails.
// ---- Bilevel G4 writer (#579) ------------------------------------------------
//
// The `tiff` crate (0.9) has no CCITT encoder, so the G4 path hand-rolls the
// minimal multi-page bilevel TIFF: little-endian header, one IFD per page with
// the 11 tags libtiff expects for a G4 fax image, strip data = the raw
// `smmr::encode_g4` T.6 payload (1 strip per page). Photometric is
// min-is-white (0), matching T.6's white-first run convention and our mask's
// 1 = black. To keep the writer memory-bounded, the first pass retains only
// per-page layout metadata; the second pass re-encodes and emits one strip at
// a time. The two passes intentionally trade G4 CPU for O(1)-page memory.
#[derive(Clone, Copy)]
struct G4PagePlan {
    width: u32,
    height: u32,
    dpi: u32,
    encoded_len: u32,
}

#[derive(Clone, Copy)]
struct G4PageLayout {
    strip_offset: u32,
    rational_offset: u32,
    ifd_offset: u32,
}

/// Render the page's bilevel mask and encode it as a G4 strip.
///
/// The returned metadata is sufficient to plan the TIFF layout. Callers doing
/// size discovery must drop the payload and retain only the metadata.
fn encode_bilevel_g4_page(
    doc: &DjVuDocument,
    page_index: usize,
) -> Result<(G4PagePlan, Vec<u8>), TiffError> {
    // #629: cold clone — the mask decode cache drops with the page.
    let page = doc.page(page_index)?.clone();
    let width = page.width() as u32;
    let height = page.height() as u32;
    let dpi = page.dpi().max(1) as u32;
    let mask = page
        .extract_mask()
        .map_err(TiffError::Doc)?
        .filter(|m| m.width >= width && m.height >= height)
        .unwrap_or_else(|| crate::bitmap::Bitmap::new(width, height));
    let encoded = crate::smmr::encode_g4(&mask);
    let plan = G4PagePlan {
        width,
        height,
        dpi,
        encoded_len: encoded.len() as u32,
    };
    Ok((plan, encoded))
}

fn write_bilevel_g4_tiff<W: Write + Seek>(
    doc: &DjVuDocument,
    mut w: W,
    observer: &mut dyn ExportObserver,
) -> Result<(), TiffError> {
    let indices: Vec<usize> = crate::export_common::page_indices(doc, None).collect();

    // Pass 1: discover the exact G4 strip sizes needed to resolve the complete
    // IFD chain. The encoded payload is dropped after each page, leaving only
    // small per-page metadata records in memory.
    let mut plans = Vec::with_capacity(indices.len());
    for &page_index in &indices {
        if observer.cancelled() {
            return Err(TiffError::Cancelled);
        }
        let (plan, encoded) = encode_bilevel_g4_page(doc, page_index)?;
        drop(encoded);
        plans.push(plan);
    }

    let io = |e: std::io::Error| TiffError::Encode(e.to_string());

    // Layout: header (8) → per page [strip data, then 8-byte-aligned IFD].
    const NTAGS: u16 = 11;
    let ifd_size = 2 + NTAGS as u32 * 12 + 4; // count + entries + next-IFD ptr
    let mut offset: u32 = 8;
    let mut layout = Vec::with_capacity(plans.len());
    for plan in &plans {
        let strip_offset = offset;
        // XResolution/YResolution rationals (2×8 bytes) live after the strip.
        let rational_offset = (strip_offset + plan.encoded_len).div_ceil(2) * 2;
        let ifd_offset = (rational_offset + 16).div_ceil(2) * 2;
        layout.push(G4PageLayout {
            strip_offset,
            rational_offset,
            ifd_offset,
        });
        offset = ifd_offset + ifd_size;
    }

    // Header: little-endian, magic 42, first IFD offset.
    w.write_all(b"II\x2a\x00").map_err(io)?;
    w.write_all(&layout[0].ifd_offset.to_le_bytes())
        .map_err(io)?;

    let entry = |tag: u16, typ: u16, count: u32, value: u32| -> [u8; 12] {
        let mut e = [0u8; 12];
        e[0..2].copy_from_slice(&tag.to_le_bytes());
        e[2..4].copy_from_slice(&typ.to_le_bytes());
        e[4..8].copy_from_slice(&count.to_le_bytes());
        e[8..12].copy_from_slice(&value.to_le_bytes());
        e
    };

    // Pass 2: re-encode and emit one page at a time. We use pass-1 metadata
    // for the IFD so the output layout remains byte-for-byte unchanged.
    let mut pos: u32 = 8;
    for (idx, ((&page_index, plan), page_layout)) in
        indices.iter().zip(&plans).zip(&layout).enumerate()
    {
        if observer.cancelled() {
            return Err(TiffError::Cancelled);
        }
        let (emitted_plan, encoded) = encode_bilevel_g4_page(doc, page_index)?;
        debug_assert_eq!(plan.encoded_len, emitted_plan.encoded_len);
        if plan.encoded_len != emitted_plan.encoded_len {
            return Err(TiffError::Encode(format!(
                "G4 encoded length diverged between sizing and emission passes for page {}",
                idx + 1
            )));
        }

        debug_assert_eq!(pos, page_layout.strip_offset);
        w.write_all(&encoded).map_err(io)?;
        pos += emitted_plan.encoded_len;
        while pos < page_layout.rational_offset {
            w.write_all(&[0]).map_err(io)?;
            pos += 1;
        }
        // X/Y resolution rationals (dpi / 1).
        for _ in 0..2 {
            w.write_all(&plan.dpi.to_le_bytes()).map_err(io)?;
            w.write_all(&1u32.to_le_bytes()).map_err(io)?;
        }
        pos += 16;
        while pos < page_layout.ifd_offset {
            w.write_all(&[0]).map_err(io)?;
            pos += 1;
        }

        w.write_all(&NTAGS.to_le_bytes()).map_err(io)?;
        // Types: 3 = SHORT, 4 = LONG, 5 = RATIONAL.
        w.write_all(&entry(256, 4, 1, plan.width)).map_err(io)?; // ImageWidth
        w.write_all(&entry(257, 4, 1, plan.height)).map_err(io)?; // ImageLength
        w.write_all(&entry(258, 3, 1, 1)).map_err(io)?; // BitsPerSample
        w.write_all(&entry(259, 3, 1, 4)).map_err(io)?; // Compression = CCITT G4
        w.write_all(&entry(262, 3, 1, 0)).map_err(io)?; // Photometric = WhiteIsZero
        w.write_all(&entry(273, 4, 1, page_layout.strip_offset))
            .map_err(io)?; // StripOffsets
        w.write_all(&entry(277, 3, 1, 1)).map_err(io)?; // SamplesPerPixel
        w.write_all(&entry(278, 4, 1, plan.height)).map_err(io)?; // RowsPerStrip
        w.write_all(&entry(279, 4, 1, plan.encoded_len))
            .map_err(io)?; // StripByteCounts
        w.write_all(&entry(282, 5, 1, page_layout.rational_offset))
            .map_err(io)?; // XResolution
        w.write_all(&entry(283, 5, 1, page_layout.rational_offset + 8))
            .map_err(io)?; // YResolution
        let next = if idx + 1 < layout.len() {
            layout[idx + 1].ifd_offset
        } else {
            0
        };
        w.write_all(&next.to_le_bytes()).map_err(io)?;
        pos = page_layout.ifd_offset + ifd_size;
        observer.on_progress(idx + 1, plans.len());
    }
    w.flush().map_err(io)?;
    Ok(())
}

fn extract_bilevel_pixels(page: &DjVuPage, w: u32, h: u32) -> Result<Vec<u8>, TiffError> {
    let sjbz = match page.find_chunk(b"Sjbz") {
        Some(d) => d,
        None => return Ok(vec![0u8; (w * h) as usize]),
    };

    let dict = page
        .find_chunk(b"Djbz")
        .and_then(|djbz| crate::jb2::decode_dict(djbz, None).ok());

    let bm = crate::jb2::decode(sjbz, dict.as_ref())
        .map_err(|e| TiffError::Encode(format!("JB2 decode failed: {e}")))?;

    let wq = w as usize;
    let mut pixels = vec![0u8; wq * h as usize];

    // LUT byte-expansion: when the decoded mask covers the page, expand each
    // packed mask byte to 8 Gray8 pixels via a 256-entry table instead of one
    // `bm.get()` (stride mult + bit-extract) per pixel. MSB-first packing: pixel
    // x is bit (7 - x%8) of byte x/8, matching `BILEVEL_GRAY8`.
    if bm.width >= w && bm.height >= h {
        let stride = bm.row_stride();
        let nb_full = wq / 8;
        let rem = wq % 8;
        for y in 0..h as usize {
            let row = &bm.data[y * stride..];
            let out = &mut pixels[y * wq..(y + 1) * wq];
            for bi in 0..nb_full {
                out[bi * 8..bi * 8 + 8].copy_from_slice(&BILEVEL_GRAY8[row[bi] as usize]);
            }
            if rem > 0 {
                let src = &BILEVEL_GRAY8[row[nb_full] as usize];
                out[nb_full * 8..nb_full * 8 + rem].copy_from_slice(&src[..rem]);
            }
        }
        return Ok(pixels);
    }

    // Fallback for the unexpected case where the mask is smaller than the page.
    // Bitmap pixels: true = black foreground, false = white background.
    for y in 0..h {
        for x in 0..w {
            pixels[(y * w + x) as usize] = if bm.get(x, y) { 255u8 } else { 0u8 };
        }
    }
    Ok(pixels)
}

/// Maps each packed mask byte (MSB-first) to its 8 expanded Gray8 pixels —
/// bit set (black) → 255, bit clear (white) → 0.
const BILEVEL_GRAY8: [[u8; 8]; 256] = {
    let mut lut = [[0u8; 8]; 256];
    let mut mb = 0usize;
    while mb < 256 {
        let mut j = 0usize;
        while j < 8 {
            lut[mb][j] = if (mb >> (7 - j)) & 1 != 0 { 255u8 } else { 0u8 };
            j += 1;
        }
        mb += 1;
    }
    lut
};

// ---- Tests ------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;

    use crate::djvu_render;

    fn assets_path() -> std::path::PathBuf {
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("references/djvujs/library/assets")
    }

    fn load_doc(filename: &str) -> DjVuDocument {
        let data = std::fs::read(assets_path().join(filename))
            .unwrap_or_else(|_| panic!("{filename} must exist"));
        DjVuDocument::parse(&data).unwrap_or_else(|e| panic!("parse failed: {e}"))
    }

    #[derive(Default)]
    struct RecordingObserver {
        progress: Vec<(usize, usize)>,
        cancel_after: Option<usize>,
    }

    impl ExportObserver for RecordingObserver {
        fn on_progress(&mut self, done: usize, total: usize) {
            self.progress.push((done, total));
        }

        fn cancelled(&self) -> bool {
            self.cancel_after
                .is_some_and(|after| self.progress.len() >= after)
        }
    }

    /// Cancels on a specific call to `cancelled`, allowing the tests to target
    /// either the G4 sizing pass or its subsequent emission pass.
    struct CancelOnPollObserver {
        cancel_on_poll: usize,
        polls: Cell<usize>,
        progress: Vec<(usize, usize)>,
    }

    impl ExportObserver for CancelOnPollObserver {
        fn on_progress(&mut self, done: usize, total: usize) {
            self.progress.push((done, total));
        }

        fn cancelled(&self) -> bool {
            let polls = self.polls.get() + 1;
            self.polls.set(polls);
            polls >= self.cancel_on_poll
        }
    }

    fn load_fixture_doc(filename: &str) -> DjVuDocument {
        let data = std::fs::read(
            std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures")
                .join(filename),
        )
        .unwrap();
        DjVuDocument::parse(&data).unwrap_or_else(|e| panic!("parse failed: {e}"))
    }

    fn g4_options() -> TiffOptions {
        TiffOptions {
            mode: TiffMode::Bilevel,
            bilevel_compression: TiffBilevelCompression::G4,
            ..Default::default()
        }
    }

    fn load_multipage_g4_doc() -> DjVuDocument {
        let data = std::fs::read(
            std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/corpus/cable_1973_100133.djvu"),
        )
        .unwrap();
        DjVuDocument::parse(&data).unwrap()
    }

    /// Exact pre-#690 G4 writer, retained only to lock the two-pass writer's
    /// byte layout to the former all-in-memory implementation.
    fn legacy_all_in_memory_g4_tiff(doc: &DjVuDocument) -> Result<Vec<u8>, TiffError> {
        let indices: Vec<usize> = crate::export_common::page_indices(doc, None).collect();
        let mut pages = Vec::with_capacity(indices.len());
        for page_index in indices {
            pages.push(encode_bilevel_g4_page(doc, page_index)?);
        }

        let io = |e: std::io::Error| TiffError::Encode(e.to_string());
        const NTAGS: u16 = 11;
        let ifd_size = 2 + NTAGS as u32 * 12 + 4;
        let mut offset: u32 = 8;
        let mut layout = Vec::with_capacity(pages.len());
        for (plan, g4) in &pages {
            let strip_off = offset;
            let rat_off = (strip_off + g4.len() as u32).div_ceil(2) * 2;
            let ifd_off = (rat_off + 16).div_ceil(2) * 2;
            layout.push((strip_off, rat_off, ifd_off));
            offset = ifd_off + ifd_size;
            assert_eq!(plan.encoded_len, g4.len() as u32);
        }

        let mut w = std::io::Cursor::new(Vec::new());
        w.write_all(b"II\x2a\x00").map_err(io)?;
        w.write_all(&layout[0].2.to_le_bytes()).map_err(io)?;

        let entry = |tag: u16, typ: u16, count: u32, value: u32| -> [u8; 12] {
            let mut e = [0u8; 12];
            e[0..2].copy_from_slice(&tag.to_le_bytes());
            e[2..4].copy_from_slice(&typ.to_le_bytes());
            e[4..8].copy_from_slice(&count.to_le_bytes());
            e[8..12].copy_from_slice(&value.to_le_bytes());
            e
        };

        let mut pos: u32 = 8;
        for (idx, ((plan, g4), &(strip_off, rat_off, ifd_off))) in
            pages.iter().zip(&layout).enumerate()
        {
            debug_assert_eq!(pos, strip_off);
            w.write_all(g4).map_err(io)?;
            pos += g4.len() as u32;
            while pos < rat_off {
                w.write_all(&[0]).map_err(io)?;
                pos += 1;
            }
            for _ in 0..2 {
                w.write_all(&plan.dpi.to_le_bytes()).map_err(io)?;
                w.write_all(&1u32.to_le_bytes()).map_err(io)?;
            }
            pos += 16;
            while pos < ifd_off {
                w.write_all(&[0]).map_err(io)?;
                pos += 1;
            }

            w.write_all(&NTAGS.to_le_bytes()).map_err(io)?;
            w.write_all(&entry(256, 4, 1, plan.width)).map_err(io)?;
            w.write_all(&entry(257, 4, 1, plan.height)).map_err(io)?;
            w.write_all(&entry(258, 3, 1, 1)).map_err(io)?;
            w.write_all(&entry(259, 3, 1, 4)).map_err(io)?;
            w.write_all(&entry(262, 3, 1, 0)).map_err(io)?;
            w.write_all(&entry(273, 4, 1, strip_off)).map_err(io)?;
            w.write_all(&entry(277, 3, 1, 1)).map_err(io)?;
            w.write_all(&entry(278, 4, 1, plan.height)).map_err(io)?;
            w.write_all(&entry(279, 4, 1, g4.len() as u32))
                .map_err(io)?;
            w.write_all(&entry(282, 5, 1, rat_off)).map_err(io)?;
            w.write_all(&entry(283, 5, 1, rat_off + 8)).map_err(io)?;
            let next = if idx + 1 < layout.len() {
                layout[idx + 1].2
            } else {
                0
            };
            w.write_all(&next.to_le_bytes()).map_err(io)?;
            pos = ifd_off + ifd_size;
        }
        w.flush().map_err(io)?;
        Ok(w.into_inner())
    }

    #[test]
    fn tiff_writer_observer_reports_each_page_in_order() {
        let doc = load_fixture_doc("vega.djvu");
        let total = doc.page_count();
        let mut observer = RecordingObserver::default();

        djvu_to_tiff_writer_with_observer(
            &doc,
            &TiffOptions::default(),
            std::io::Cursor::new(Vec::new()),
            &mut observer,
        )
        .expect("observer export must succeed");

        assert_eq!(
            observer.progress,
            (1..=total).map(|done| (done, total)).collect::<Vec<_>>()
        );
    }

    #[test]
    fn tiff_writer_cancellation_stops_after_completed_page() {
        let doc = load_fixture_doc("vega.djvu");
        assert!(doc.page_count() > 1, "fixture must contain multiple pages");
        let mut observer = RecordingObserver {
            cancel_after: Some(1),
            ..RecordingObserver::default()
        };

        let error = djvu_to_tiff_writer_with_observer(
            &doc,
            &TiffOptions::default(),
            std::io::Cursor::new(Vec::new()),
            &mut observer,
        )
        .expect_err("observer must cancel the export");

        assert!(matches!(error, TiffError::Cancelled));
        assert_eq!(observer.progress.len(), 1);
    }

    #[test]
    fn tiff_default_writer_delegates_to_noop_observer() {
        let doc = load_fixture_doc("vega.djvu");
        let opts = TiffOptions::default();

        let mut default_cursor = std::io::Cursor::new(Vec::new());
        djvu_to_tiff_writer(&doc, &opts, &mut default_cursor).unwrap();

        let mut observed_cursor = std::io::Cursor::new(Vec::new());
        let mut observer = NoOpObserver;
        djvu_to_tiff_writer_with_observer(&doc, &opts, &mut observed_cursor, &mut observer)
            .unwrap();

        assert_eq!(observed_cursor.into_inner(), default_cursor.into_inner());
    }

    #[test]
    fn tiff_writer_failing_sink_returns_io_error() {
        let doc = load_fixture_doc("chicken.djvu");
        let error = djvu_to_tiff_writer(
            &doc,
            &TiffOptions::default(),
            crate::export_test_support::FailingWriter::after(2),
        )
        .expect_err("injected sink failure must be returned");

        assert!(
            matches!(error, TiffError::Encode(message) if message.contains("injected sink failure"))
        );
    }

    fn decode_first_tiff_rgb(tiff_bytes: &[u8]) -> (u32, u32, Vec<u8>) {
        let cursor = std::io::Cursor::new(tiff_bytes);
        let mut decoder = tiff::decoder::Decoder::new(cursor).expect("tiff must be decodable");
        let (w, h) = decoder.dimensions().expect("must have dimensions");
        let img = decoder.read_image().expect("image must decode");
        let tiff::decoder::DecodingResult::U8(pixels) = img else {
            panic!("expected RGB8 TIFF pixels");
        };
        (w, h, pixels)
    }

    fn assert_streamed_color_tiff_matches_render_pixmap(filename: &str) {
        let doc = load_doc(filename);
        let page = doc.page(0).unwrap();
        let (_, _, render_opts) = color_render_options(page, 1.0);
        assert!(
            render_opts.can_stream(page),
            "fixture should use the streaming TIFF color path"
        );

        let mut cursor = std::io::Cursor::new(Vec::new());
        djvu_to_tiff_writer(&doc, &TiffOptions::default(), &mut cursor)
            .expect("streamed TIFF writer must succeed");
        let tiff_bytes = cursor.into_inner();
        let (w, h, pixels) = decode_first_tiff_rgb(&tiff_bytes);

        assert_eq!((w, h), (render_opts.width, render_opts.height));
        let expected = djvu_render::render_pixmap(page, &render_opts)
            .expect("render_pixmap must succeed")
            .to_rgb();
        assert_eq!(pixels, expected);
    }

    // ── TDD tests ─────────────────────────────────────────────────────────────

    /// `djvu_to_tiff` produces non-empty bytes for a color document.
    #[test]
    fn color_export_produces_bytes() {
        let doc = load_doc("chicken.djvu");
        let tiff = djvu_to_tiff(&doc, &TiffOptions::default()).expect("color export must succeed");
        assert!(!tiff.is_empty(), "TIFF output must not be empty");
    }

    /// TIFF output starts with the standard TIFF magic bytes (little-endian II or big-endian MM).
    #[test]
    fn output_starts_with_tiff_magic() {
        let doc = load_doc("chicken.djvu");
        let tiff = djvu_to_tiff(&doc, &TiffOptions::default()).unwrap();
        let magic = &tiff[..4];
        assert!(
            magic == b"II\x2A\x00" || magic == b"MM\x00\x2A",
            "must start with TIFF magic, got: {magic:?}"
        );
    }

    /// Bilevel export produces non-empty bytes.
    #[test]
    fn bilevel_export_produces_bytes() {
        let doc = load_doc("boy_jb2.djvu");
        let opts = TiffOptions {
            mode: TiffMode::Bilevel,
            ..Default::default()
        };
        let tiff = djvu_to_tiff(&doc, &opts).expect("bilevel export must succeed");
        assert!(!tiff.is_empty());
    }

    /// Bilevel export also starts with TIFF magic.
    #[test]
    fn bilevel_output_starts_with_tiff_magic() {
        let doc = load_doc("boy_jb2.djvu");
        let opts = TiffOptions {
            mode: TiffMode::Bilevel,
            ..Default::default()
        };
        let tiff = djvu_to_tiff(&doc, &opts).unwrap();
        let magic = &tiff[..4];
        assert!(magic == b"II\x2A\x00" || magic == b"MM\x00\x2A");
    }

    /// Multi-page export: two pages produce more output than one page.
    #[test]
    fn multipage_larger_than_single_page() {
        // Build a two-page DjVu document by concatenating two single-page exports
        // as separate DjVuDocument instances and comparing their individual outputs.
        let doc_a = load_doc("chicken.djvu");
        let doc_b = load_doc("boy.djvu");
        let opts = TiffOptions::default();

        let tiff_a = djvu_to_tiff(&doc_a, &opts).expect("page A export must succeed");
        let tiff_b = djvu_to_tiff(&doc_b, &opts).expect("page B export must succeed");

        // Both single-page TIFFs must be non-trivially sized
        assert!(tiff_a.len() > 100, "page A TIFF must be non-trivial");
        assert!(tiff_b.len() > 100, "page B TIFF must be non-trivial");
    }

    /// Two different single-page documents produce differently-sized TIFFs.
    #[test]
    fn different_pages_produce_different_sizes() {
        let doc_a = load_doc("chicken.djvu");
        let doc_b = load_doc("boy.djvu");
        let opts = TiffOptions::default();

        let tiff_a = djvu_to_tiff(&doc_a, &opts).unwrap();
        let tiff_b = djvu_to_tiff(&doc_b, &opts).unwrap();
        // Different pages have different content, so their TIFFs should differ
        assert_ne!(
            tiff_a.len(),
            tiff_b.len(),
            "different pages must produce different TIFF sizes"
        );
    }

    /// Color export at 0.5 scale produces a smaller file than at 1.0 scale.
    #[test]
    fn scale_factor_reduces_file_size() {
        let doc = load_doc("chicken.djvu");
        let full = djvu_to_tiff(&doc, &TiffOptions::default()).unwrap();
        let half = djvu_to_tiff(
            &doc,
            &TiffOptions {
                scale: 0.5,
                ..Default::default()
            },
        )
        .unwrap();
        assert!(
            half.len() < full.len(),
            "half-scale TIFF must be smaller: half={} full={}",
            half.len(),
            full.len()
        );
    }

    /// Round-trip: exported TIFF can be re-decoded by the `tiff` crate.
    #[test]
    fn color_tiff_round_trips_via_tiff_decoder() {
        let doc = load_doc("chicken.djvu");
        let tiff_bytes = djvu_to_tiff(&doc, &TiffOptions::default()).unwrap();

        let cursor = std::io::Cursor::new(&tiff_bytes);
        let mut decoder = tiff::decoder::Decoder::new(cursor).expect("tiff must be decodable");
        // The first IFD must decode without error and have reasonable dimensions.
        let (w, h) = decoder.dimensions().expect("must have dimensions");
        let page = doc.page(0).unwrap();
        assert_eq!(w, page.width() as u32);
        assert_eq!(h, page.height() as u32);
    }

    /// Streamed color TIFF export matches the existing full-pixmap render path on a color page.
    #[test]
    fn streamed_color_tiff_matches_render_pixmap_color_page() {
        assert_streamed_color_tiff_matches_render_pixmap("chicken.djvu");
    }

    /// Streamed color TIFF export also matches the full-pixmap path on a bilevel page.
    #[test]
    fn streamed_color_tiff_matches_render_pixmap_bilevel_page() {
        assert_streamed_color_tiff_matches_render_pixmap("boy_jb2.djvu");
    }

    /// Bilevel pages with JB2 mask have non-uniform pixel values (some black pixels).
    #[test]
    fn bilevel_jb2_page_has_black_pixels() {
        let doc = load_doc("boy_jb2.djvu");
        let opts = TiffOptions {
            mode: TiffMode::Bilevel,
            ..Default::default()
        };
        let tiff_bytes = djvu_to_tiff(&doc, &opts).unwrap();

        let cursor = std::io::Cursor::new(&tiff_bytes);
        let mut decoder = tiff::decoder::Decoder::new(cursor).unwrap();
        let img = decoder.read_image().unwrap();
        if let tiff::decoder::DecodingResult::U8(pixels) = img {
            let has_black = pixels.contains(&255);
            assert!(
                has_black,
                "bilevel JB2 page must have at least one black pixel"
            );
        }
    }

    /// Bilevel export on a page without JB2 mask returns a blank (all-white) page.
    #[test]
    fn bilevel_blank_when_no_jb2_mask() {
        // chicken.djvu is a color-only document with no JB2 mask
        let doc = load_doc("chicken.djvu");
        let page = doc.page(0).unwrap();
        let w = page.width() as u32;
        let h = page.height() as u32;

        let pixels = extract_bilevel_pixels(page, w, h).unwrap();
        assert!(
            pixels.iter().all(|&p| p == 0),
            "page without JB2 must be all-white (0)"
        );
    }

    /// Color export on a rotated page forces the pixmap path (can_stream returns
    /// false when page.rotation() != None), exercising write_color_page_pixmap.
    #[test]
    fn color_export_rotated_page_uses_pixmap_path() {
        let doc = load_doc("boy_jb2_rotate90.djvu");
        let page = doc.page(0).unwrap();
        // Confirm rotation is set so can_stream returns false
        assert_ne!(
            page.rotation(),
            crate::info::Rotation::None,
            "fixture must have rotation set"
        );
        let tiff =
            djvu_to_tiff(&doc, &TiffOptions::default()).expect("rotated color export must succeed");
        assert!(!tiff.is_empty());
        let magic = &tiff[..4];
        assert!(magic == b"II\x2A\x00" || magic == b"MM\x00\x2A");
    }

    /// `TiffOptions::default()` selects color mode at 1.0 scale.
    #[test]
    fn tiff_options_default() {
        let opts = TiffOptions::default();
        assert_eq!(opts.mode, TiffMode::Color);
        assert!((opts.scale - 1.0).abs() < 1e-6);
    }

    /// `From<tiff::TiffError> for TiffError` wraps the error message.
    #[test]
    fn from_tiff_error_wraps_message() {
        let io_err = std::io::Error::other("test tiff failure");
        let tiff_err: tiff::TiffError = io_err.into();
        let djvu_tiff_err: TiffError = tiff_err.into();
        let s = djvu_tiff_err.to_string();
        assert!(
            s.contains("TIFF encoding error"),
            "must mention TIFF encoding error: {s}"
        );
    }

    /// `TiffError::Encode` display includes the inner message.
    #[test]
    fn tiff_error_display() {
        let e = TiffError::Encode("something went wrong".to_string());
        assert!(e.to_string().contains("something went wrong"));
    }

    /// #579: the G4 bilevel TIFF is structurally sound (LE header, one IFD per
    /// page, CCITT G4 compression tag) and its strip round-trips through our
    /// own T.6 decoder to the exact page mask.
    #[test]
    fn bilevel_g4_tiff_round_trips_through_own_decoder() {
        let data = std::fs::read(
            std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/boy_jb2.djvu"),
        )
        .unwrap();
        let doc = DjVuDocument::parse(&data).unwrap();
        let tiff = djvu_to_tiff(
            &doc,
            &TiffOptions {
                mode: TiffMode::Bilevel,
                bilevel_compression: TiffBilevelCompression::G4,
                ..Default::default()
            },
        )
        .unwrap();

        assert_eq!(&tiff[0..4], b"II\x2a\x00", "little-endian TIFF header");
        let rd32 = |o: usize| u32::from_le_bytes(tiff[o..o + 4].try_into().unwrap());
        let rd16 = |o: usize| u16::from_le_bytes(tiff[o..o + 2].try_into().unwrap());
        let ifd = rd32(4) as usize;
        let ntags = rd16(ifd) as usize;
        let mut tags = std::collections::BTreeMap::new();
        for i in 0..ntags {
            let e = ifd + 2 + i * 12;
            tags.insert(rd16(e), rd32(e + 8));
        }
        assert_eq!(tags[&259], 4, "Compression must be CCITT G4");
        assert_eq!(tags[&258], 1, "BitsPerSample must be 1");
        assert_eq!(tags[&262], 0, "Photometric must be min-is-white");
        assert_eq!(rd32(ifd + 2 + ntags * 12), 0, "single page: next IFD = 0");

        let (w, h) = (tags[&256], tags[&257]);
        let off = tags[&273] as usize;
        let len = tags[&279] as usize;
        let mut chunk = Vec::with_capacity(4 + len);
        chunk.extend_from_slice(&(w as u16).to_be_bytes());
        chunk.extend_from_slice(&(h as u16).to_be_bytes());
        chunk.extend_from_slice(&tiff[off..off + len]);
        let decoded = crate::smmr::decode_smmr(&chunk).expect("G4 strip must decode");

        let mask = doc.page(0).unwrap().extract_mask().unwrap().unwrap();
        assert_eq!((decoded.width, decoded.height), (w, h));
        for y in 0..h {
            for x in 0..w {
                assert_eq!(decoded.get(x, y), mask.get(x, y), "pixel ({x},{y})");
            }
        }
    }

    /// #579: multi-page G4 TIFF chains IFDs for every page.
    #[test]
    fn bilevel_g4_tiff_multipage_chains_ifds() {
        let data = std::fs::read(
            std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/corpus/cable_1973_100133.djvu"),
        )
        .unwrap();
        let doc = DjVuDocument::parse(&data).unwrap();
        let tiff = djvu_to_tiff(
            &doc,
            &TiffOptions {
                mode: TiffMode::Bilevel,
                bilevel_compression: TiffBilevelCompression::G4,
                ..Default::default()
            },
        )
        .unwrap();
        let rd32 = |o: usize| u32::from_le_bytes(tiff[o..o + 4].try_into().unwrap());
        let rd16 = |o: usize| u16::from_le_bytes(tiff[o..o + 2].try_into().unwrap());
        let mut ifd = rd32(4) as usize;
        let mut pages = 0;
        while ifd != 0 {
            let ntags = rd16(ifd) as usize;
            pages += 1;
            ifd = rd32(ifd + 2 + ntags * 12) as usize;
        }
        assert_eq!(pages, doc.page_count(), "one IFD per page");
    }

    /// #690: the bounded-memory writer preserves the original strip/IFD byte
    /// layout of the pre-refactor all-in-memory G4 writer.
    #[test]
    fn bilevel_g4_two_pass_matches_legacy_all_in_memory_bytes() {
        let doc = load_multipage_g4_doc();
        let expected = legacy_all_in_memory_g4_tiff(&doc).unwrap();
        let actual = djvu_to_tiff(&doc, &g4_options()).unwrap();

        assert_eq!(actual, expected);
    }

    /// #690: G4 reports progress only for pages fully written in pass 2.
    #[test]
    fn bilevel_g4_two_pass_reports_each_written_page_in_order() {
        let doc = load_multipage_g4_doc();
        let total = doc.page_count();
        let mut observer = RecordingObserver::default();

        djvu_to_tiff_writer_with_observer(
            &doc,
            &g4_options(),
            std::io::Cursor::new(Vec::new()),
            &mut observer,
        )
        .expect("G4 export must succeed");

        assert_eq!(
            observer.progress,
            (1..=total).map(|done| (done, total)).collect::<Vec<_>>()
        );
    }

    /// #690: cancellation before a later page in the sizing pass returns
    /// `Cancelled` before any page is reported as written.
    #[test]
    fn bilevel_g4_two_pass_cancels_during_sizing_pass() {
        let doc = load_multipage_g4_doc();
        assert!(doc.page_count() > 1, "fixture must contain multiple pages");
        let mut observer = CancelOnPollObserver {
            cancel_on_poll: 2,
            polls: Cell::new(0),
            progress: Vec::new(),
        };

        let error = djvu_to_tiff_writer_with_observer(
            &doc,
            &g4_options(),
            std::io::Cursor::new(Vec::new()),
            &mut observer,
        )
        .expect_err("G4 sizing pass must observe cancellation");

        assert!(matches!(error, TiffError::Cancelled));
        assert_eq!(observer.polls.get(), 2);
        assert!(observer.progress.is_empty());
    }

    /// #690: cancellation before a later page in the emission pass preserves
    /// progress for only the already-written pages.
    #[test]
    fn bilevel_g4_two_pass_cancels_during_emission_pass() {
        let doc = load_multipage_g4_doc();
        let total = doc.page_count();
        assert!(total > 1, "fixture must contain multiple pages");
        let mut observer = CancelOnPollObserver {
            // `total` sizing polls, then one written page, then cancellation
            // immediately before the second emission page.
            cancel_on_poll: total + 2,
            polls: Cell::new(0),
            progress: Vec::new(),
        };

        let error = djvu_to_tiff_writer_with_observer(
            &doc,
            &g4_options(),
            std::io::Cursor::new(Vec::new()),
            &mut observer,
        )
        .expect_err("G4 emission pass must observe cancellation");

        assert!(matches!(error, TiffError::Cancelled));
        assert_eq!(observer.polls.get(), total + 2);
        assert_eq!(observer.progress, vec![(1, total)]);
    }
}