mini-film 4.2.0

Apply Lightroom-style film emulation profiles to RAW files with RawTherapee and HALD workflows.
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
//! Native Nikon "Connect to PC" ingest over PTP/IP.
//!
//! Nikon Wireless Transmitter Utility ultimately receives image-transfer traffic
//! over PTP/IP. This module implements the transport and object-download side
//! directly so daemon mode can use a camera as an inbox source without depending
//! on external camera-control helpers at runtime.

use std::{
    env, fs,
    io::{self, Read, Write},
    net::{TcpStream, ToSocketAddrs},
    path::{Path, PathBuf},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
        mpsc::{self, Receiver},
    },
    thread::{self, JoinHandle},
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use anyhow::{Context, Result, anyhow, bail};
use chrono::Utc;
use serde_json::{Value, json};
use sha1::{Digest, Sha1};

use crate::app::util::is_supported_raw_file;

const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
const DEFAULT_IO_TIMEOUT: Duration = Duration::from_secs(10);
const EVENT_READ_TIMEOUT: Duration = Duration::from_millis(750);
const RECONNECT_DELAY: Duration = Duration::from_secs(3);
const TRANSFER_POLL_INTERVAL: Duration = Duration::from_millis(900);

const PTPIP_INIT_COMMAND_REQUEST: u32 = 1;
const PTPIP_INIT_COMMAND_ACK: u32 = 2;
const PTPIP_INIT_EVENT_REQUEST: u32 = 3;
const PTPIP_INIT_EVENT_ACK: u32 = 4;
const PTPIP_INIT_FAIL: u32 = 5;
const PTPIP_CMD_REQUEST: u32 = 6;
const PTPIP_CMD_RESPONSE: u32 = 7;
const PTPIP_EVENT: u32 = 8;
const PTPIP_START_DATA_PACKET: u32 = 9;
const PTPIP_DATA_PACKET: u32 = 10;
const PTPIP_END_DATA_PACKET: u32 = 12;
const PTPIP_PING: u32 = 13;
const PTPIP_PONG: u32 = 14;

const PTP_RC_OK: u16 = 0x2001;
const PTP_OC_GET_DEVICE_INFO: u16 = 0x1001;
const PTP_OC_OPEN_SESSION: u16 = 0x1002;
const PTP_OC_CLOSE_SESSION: u16 = 0x1003;
const PTP_OC_GET_OBJECT_INFO: u16 = 0x1008;
const PTP_OC_GET_PARTIAL_OBJECT: u16 = 0x101b;
const PTP_OC_NIKON_GET_NEXT_TRANSFER_OBJECT: u16 = 0x9010;
const PTP_OC_NIKON_GET_DEVICE_PTPIP_INFO: u16 = 0x90e0;
const PTP_OC_NIKON_COMPLETE_PAIRING: u16 = 0x935a;
const PTP_OC_NIKON_GET_PAIRING_CODE: u16 = 0x952b;
const PTP_EC_OBJECT_ADDED: u16 = 0x4002;
const PTP_EC_DEVICE_PROP_CHANGED: u16 = 0x4006;
const PTP_EC_CAPTURE_COMPLETE: u16 = 0x400d;

const NIKON_PAIRING_AUTHENTICATED: u32 = 0x2002;
const NIKON_PAIRING_COMPLETE: u32 = 0x2001;
const PAIRING_FINALIZE_RETRIES: usize = 5;
const NIKON_TRANSFER_ACTIVE: u8 = 2;
const NIKON_TRANSFER_OK: u32 = PTP_RC_OK as u32;
const NIKON_TRANSFER_BLOCK_SIZE: u32 = 0x80_0000;
const NIKON_TRANSFER_DRAIN_LIMIT: usize = 32;

/// Result of probing the Nikon connection wizard.
///
/// Nikon splits pairing into an auth-code acceptance step and a final pairing
/// step. The first step usually closes the socket, so callers need to reconnect
/// and send the completion command on a fresh command channel.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PairingWizardState {
    NotActive,
    NeedsFinalReconnect,
}

/// Configuration for the background Nikon WTU receiver.
///
/// The receiver downloads camera-transfer objects into `output_dir`, which is
/// normally daemon mode's watched inbox. `camera` is the reachable camera host
/// or IP, while `computer_name` and `guid` define the stable PTP/IP initiator
/// identity Nikon stores during pairing.
#[derive(Clone, Debug)]
pub(crate) struct NikonWtuConfig {
    pub(crate) camera: String,
    pub(crate) port: u16,
    pub(crate) output_dir: PathBuf,
    pub(crate) computer_name: Option<String>,
    pub(crate) guid: Option<String>,
}

/// Long-lived Nikon WTU worker owned by daemon mode.
///
/// The worker reconnects in the background and sends status lines through a
/// channel so the daemon progress bar can print them without the receiver
/// writing directly to stdout.
pub(crate) struct NikonWtuReceiver {
    stop: Arc<AtomicBool>,
    logs: Receiver<String>,
    handle: Option<JoinHandle<()>>,
}

impl NikonWtuReceiver {
    /// Drain currently pending receiver log lines without blocking daemon work.
    pub(crate) fn drain_logs(&self) -> Vec<String> {
        let mut logs = Vec::new();
        while let Ok(log) = self.logs.try_recv() {
            logs.push(log);
        }
        logs
    }
}

impl Drop for NikonWtuReceiver {
    fn drop(&mut self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }
}

/// Start the native Nikon PTP/IP receiver thread.
///
/// The thread keeps trying to connect until dropped. Expected camera-offline
/// socket failures are silent because daemon mode may be left running while the
/// camera is powered off.
pub(crate) fn start_nikon_wtu_receiver(config: NikonWtuConfig) -> Result<NikonWtuReceiver> {
    fs::create_dir_all(&config.output_dir)
        .with_context(|| format!("creating Nikon WTU inbox {}", config.output_dir.display()))?;
    let guid = resolve_guid(config.guid.as_deref())?;
    let computer_name = config
        .computer_name
        .clone()
        .filter(|name| !name.trim().is_empty())
        .unwrap_or_else(default_computer_name);
    let (tx, logs) = mpsc::channel();
    let stop = Arc::new(AtomicBool::new(false));
    let thread_stop = Arc::clone(&stop);
    let handle = thread::spawn(move || {
        let mut announced_guid = false;
        while !thread_stop.load(Ordering::Relaxed) {
            if !announced_guid {
                let _ = tx.send(format!(
                    "nikon-wtu: using initiator '{}' guid {}",
                    computer_name,
                    format_guid(&guid)
                ));
                announced_guid = true;
            }
            let result = run_receiver_once(&config, &computer_name, guid, &thread_stop, &tx);
            if let Err(error) = result
                && !is_expected_camera_offline_error(&error)
            {
                // Pairing and protocol errors are useful; routine "camera off"
                // reconnect failures are filtered above to keep daemon quiet.
                let _ = tx.send(format!("nikon-wtu: {error:#}"));
            }
            sleep_until_stopped(&thread_stop, RECONNECT_DELAY);
        }
    });

    Ok(NikonWtuReceiver {
        stop,
        logs,
        handle: Some(handle),
    })
}

/// Run one complete connection lifecycle: connect, pair if needed, then transfer.
///
/// A cached pairing goes straight to transfer setup. If the camera rejects that
/// setup, we fall back to the pairing wizard because Nikon can invalidate a
/// remembered identity when the body is reset or paired from another machine.
fn run_receiver_once(
    config: &NikonWtuConfig,
    computer_name: &str,
    guid: [u8; 16],
    stop: &AtomicBool,
    logs: &mpsc::Sender<String>,
) -> Result<()> {
    let mut pairing_cache = PairingCache::load().context("loading Nikon WTU pairing cache")?;
    let mut session = PtpIpSession::connect(
        &config.camera,
        config.port,
        computer_name,
        guid,
        DEFAULT_CONNECT_TIMEOUT,
    )
    .with_context(|| format!("connecting to {}:{}", config.camera, config.port))?;

    logs.send(format!(
        "nikon-wtu: connected to {} ({})",
        session.camera_name, config.camera
    ))
    .ok();

    let known_pairing = pairing_cache.is_paired(
        &config.camera,
        config.port,
        &session.camera_name,
        computer_name,
        &guid,
    );
    if known_pairing {
        logs.send(format!(
            "nikon-wtu: using cached pairing for {} ({})",
            session.camera_name,
            pairing_cache.path.display()
        ))
        .ok();
        match prepare_transfer_session(&mut session, logs) {
            Ok(()) => return transfer_loop(&mut session, &config.output_dir, stop, logs),
            Err(error) => logs
                .send(format!(
                    "nikon-wtu: cached pairing did not start transfer; retrying wizard: {error:#}"
                ))
                .ok(),
        };
        drop(session);
        thread::sleep(Duration::from_millis(500));
        session = PtpIpSession::connect(
            &config.camera,
            config.port,
            computer_name,
            guid,
            DEFAULT_CONNECT_TIMEOUT,
        )
        .with_context(|| {
            format!(
                "reconnecting to {}:{} for pairing",
                config.camera, config.port
            )
        })?;
        logs.send(format!(
            "nikon-wtu: reconnected to {} ({}) for pairing",
            session.camera_name, config.camera
        ))
        .ok();
    } else {
        logs.send(format!(
            "nikon-wtu: no cached pairing for {}; checking wizard",
            session.camera_name
        ))
        .ok();
    }

    let paired = match try_complete_pairing_wizard(&mut session, logs)? {
        PairingWizardState::NotActive => false,
        PairingWizardState::NeedsFinalReconnect => {
            drop(session);
            // Nikon closes or destabilizes the auth session after the code is
            // accepted. Completing pairing on a fresh socket matches the camera
            // wizard behavior and avoids partial-buffer reads on the old one.
            finalize_pairing_after_auth(config, computer_name, guid, logs)?;
            session = PtpIpSession::connect(
                &config.camera,
                config.port,
                computer_name,
                guid,
                DEFAULT_CONNECT_TIMEOUT,
            )
            .with_context(|| {
                format!(
                    "reconnecting to {}:{} after pairing",
                    config.camera, config.port
                )
            })?;
            logs.send(format!(
                "nikon-wtu: reconnected to {} ({}) after pairing",
                session.camera_name, config.camera
            ))
            .ok();
            true
        }
    };
    if paired {
        pairing_cache.upsert(
            &config.camera,
            config.port,
            &session.camera_name,
            computer_name,
            &guid,
        )?;
        logs.send(format!(
            "nikon-wtu: pairing cached in {}",
            pairing_cache.path.display()
        ))
        .ok();
    }
    logs.send("nikon-wtu: reconnecting for image transfer".to_string())
        .ok();
    drop(session);
    thread::sleep(Duration::from_millis(500));
    let mut session = PtpIpSession::connect(
        &config.camera,
        config.port,
        computer_name,
        guid,
        DEFAULT_CONNECT_TIMEOUT,
    )
    .with_context(|| format!("reconnecting to {}:{}", config.camera, config.port))?;
    logs.send(format!(
        "nikon-wtu: reconnected to {} ({})",
        session.camera_name, config.camera
    ))
    .ok();

    prepare_transfer_session(&mut session, logs)?;
    transfer_loop(&mut session, &config.output_dir, stop, logs)
}

/// Open a standard PTP session and log the camera's capability table.
///
/// The optional Nikon GetDevicePTPIPInfo command is useful when present, but
/// some Z bodies do not advertise it even though transfer still works, so this
/// treats it as diagnostic rather than mandatory.
fn prepare_transfer_session(session: &mut PtpIpSession, logs: &mpsc::Sender<String>) -> Result<()> {
    logs.send("nikon-wtu: reading PTP device info".to_string())
        .ok();
    let device_info = DeviceInfo::parse(&session.command_with_data(PTP_OC_GET_DEVICE_INFO, &[])?)?;
    logs.send(format!(
        "nikon-wtu: device info vendor=0x{:08x} version=0x{:04x} manufacturer='{}' model='{}' ops={}",
        device_info.vendor_extension_id,
        device_info.vendor_extension_version,
        device_info.manufacturer,
        device_info.model,
        format_opcodes(&device_info.operations)
    ))
    .ok();
    logs.send("nikon-wtu: opening PTP session".to_string()).ok();
    session.command_no_data(PTP_OC_OPEN_SESSION, &[1])?;
    if device_info
        .operations
        .contains(&PTP_OC_NIKON_GET_DEVICE_PTPIP_INFO)
    {
        match session.command_with_data(PTP_OC_NIKON_GET_DEVICE_PTPIP_INFO, &[]) {
            Ok(info) => logs
                .send(format!(
                    "nikon-wtu: Nikon GetDevicePTPIPInfo returned {} bytes: {}",
                    info.len(),
                    hex_preview(&info, 96)
                ))
                .ok(),
            Err(error) => logs
                .send(format!(
                    "nikon-wtu: Nikon GetDevicePTPIPInfo failed: {error:#}"
                ))
                .ok(),
        };
    } else {
        logs.send("nikon-wtu: Nikon GetDevicePTPIPInfo is not listed by this camera".to_string())
            .ok();
    }
    logs.send("nikon-wtu: ready; waiting for uploaded RAW objects".to_string())
        .ok();
    Ok(())
}

/// Wait for camera events and opportunistically drain Nikon's transfer queue.
///
/// The event payloads are not reliable object handles for WTU transfer mode.
/// Instead, events are treated as wakeups and the actual object is requested
/// with Nikon opcode `0x9010`.
fn transfer_loop(
    session: &mut PtpIpSession,
    output_dir: &Path,
    stop: &AtomicBool,
    logs: &mpsc::Sender<String>,
) -> Result<()> {
    let mut state = TransferState::new();
    while !stop.load(Ordering::Relaxed) {
        match session.read_event(EVENT_READ_TIMEOUT)? {
            Some(event)
                if matches!(
                    event.code,
                    PTP_EC_OBJECT_ADDED | PTP_EC_DEVICE_PROP_CHANGED | PTP_EC_CAPTURE_COMPLETE
                ) =>
            {
                // DevicePropChanged can arrive in bursts while the camera is
                // busy. Throttle those wakeups, but force a queue poll for
                // object/capture events where a transfer may be ready now.
                let force = event.code != PTP_EC_DEVICE_PROP_CHANGED;
                poll_transfer_queue(session, &mut state, output_dir, logs, force)?;
            }
            Some(event) => {
                logs.send(format!(
                    "nikon-wtu: event 0x{:04x} params {:?}",
                    event.code, event.params
                ))
                .ok();
            }
            None => poll_transfer_queue(session, &mut state, output_dir, logs, false)?,
        }
    }

    let _ = session.command_no_data(PTP_OC_CLOSE_SESSION, &[]);
    Ok(())
}

/// Mutable state for Nikon's "next transfer object" command.
///
/// The camera expects the previous transfer job status as the parameter to
/// opcode `0x9010`; after a successful or deliberately consumed object we send
/// OK again.
#[derive(Debug)]
struct TransferState {
    last_job_status: u32,
    last_poll: Instant,
}

impl TransferState {
    fn new() -> Self {
        Self {
            last_job_status: NIKON_TRANSFER_OK,
            last_poll: Instant::now()
                .checked_sub(TRANSFER_POLL_INTERVAL)
                .unwrap_or_else(Instant::now),
        }
    }
}

/// Poll the transfer queue if enough time has passed or an event forced it.
fn poll_transfer_queue(
    session: &mut PtpIpSession,
    state: &mut TransferState,
    output_dir: &Path,
    logs: &mpsc::Sender<String>,
    force: bool,
) -> Result<()> {
    if !force && state.last_poll.elapsed() < TRANSFER_POLL_INTERVAL {
        return Ok(());
    }
    state.last_poll = Instant::now();
    drain_transfer_queue(session, state, output_dir, logs)
}

/// Drain all currently available camera transfer objects.
///
/// Nikon's WTU mode does not expose new files by directly using event params as
/// object handles. We repeatedly ask the body for the next transfer job, then
/// download or consume it before reporting OK back to the queue.
fn drain_transfer_queue(
    session: &mut PtpIpSession,
    state: &mut TransferState,
    output_dir: &Path,
    logs: &mpsc::Sender<String>,
) -> Result<()> {
    for _ in 0..NIKON_TRANSFER_DRAIN_LIMIT {
        let Some(object) = query_next_transfer_object(session, state.last_job_status)? else {
            return Ok(());
        };
        if object.transfer_job != NIKON_TRANSFER_ACTIVE || object.object_handle == 0 {
            return Ok(());
        }
        match download_transfer_object(session, &object, output_dir) {
            Ok(TransferDownload::Downloaded { filename, bytes }) => {
                logs.send(format!(
                    "nikon-wtu: downloaded {filename} ({bytes} bytes, object 0x{:08x})",
                    object.object_handle
                ))
                .ok();
            }
            Ok(TransferDownload::SkippedExisting(filename)) => {
                logs.send(format!("nikon-wtu: skipped existing {filename}"))
                    .ok();
            }
            Ok(TransferDownload::SkippedUnsupported) => {}
            Err(error) if is_connection_closed_error(&error) => return Err(error),
            Err(error) => {
                logs.send(format!(
                    "nikon-wtu: failed transfer object 0x{:08x}: {error:#}",
                    object.object_handle
                ))
                .ok();
            }
        }
        // The next `0x9010` call uses this status to tell the body that the
        // previous transfer slot was handled, including unsupported JPEGs that
        // were read and discarded.
        state.last_job_status = NIKON_TRANSFER_OK;
    }
    Ok(())
}

/// Ask Nikon firmware for the next queued transfer object.
///
/// Empty data means no object is ready. A non-active job status is also treated
/// as an empty queue because it represents camera-side state, not a file to
/// download.
fn query_next_transfer_object(
    session: &mut PtpIpSession,
    last_job_status: u32,
) -> Result<Option<TransferObject>> {
    let data = session
        .command_with_data(PTP_OC_NIKON_GET_NEXT_TRANSFER_OBJECT, &[last_job_status])
        .context("querying Nikon transfer queue")?;
    if data.is_empty() {
        return Ok(None);
    }
    let object = TransferObject::parse(&data)?;
    if object.transfer_job == NIKON_TRANSFER_ACTIVE && object.object_handle != 0 {
        Ok(Some(object))
    } else {
        Ok(None)
    }
}

/// Probe and accept an active Nikon pairing wizard.
///
/// This command sequence is only attempted when no cached pairing is known, or
/// when a cached pairing failed to open transfer mode.
fn try_complete_pairing_wizard(
    session: &mut PtpIpSession,
    logs: &mpsc::Sender<String>,
) -> Result<PairingWizardState> {
    logs.send("nikon-wtu: checking Nikon pairing wizard".to_string())
        .ok();
    if let Err(error) = session.command_no_data(PTP_OC_OPEN_SESSION, &[1]) {
        logs.send(format!(
            "nikon-wtu: pairing wizard not ready; OpenSession failed: {error:#}"
        ))
        .ok();
        return Ok(PairingWizardState::NotActive);
    }

    let pairing_code_data = match session.command_with_data(PTP_OC_NIKON_GET_PAIRING_CODE, &[]) {
        Ok(data) => data,
        Err(error) => {
            logs.send(format!(
                "nikon-wtu: no active pairing wizard detected: {error:#}"
            ))
            .ok();
            let _ = session.command_no_data(PTP_OC_CLOSE_SESSION, &[]);
            return Ok(PairingWizardState::NotActive);
        }
    };
    let pairing_code = parse_pairing_code(&pairing_code_data)?;
    logs.send(format!(
        "nikon-wtu: camera pairing code {pairing_code}; accepting wizard"
    ))
    .ok();

    match session.command_no_data(
        PTP_OC_NIKON_COMPLETE_PAIRING,
        &[NIKON_PAIRING_AUTHENTICATED],
    ) {
        Ok(_) => {
            logs.send(
                "nikon-wtu: auth step accepted; closing session before final pairing".to_string(),
            )
            .ok();
            let _ = session.command_no_data(PTP_OC_CLOSE_SESSION, &[]);
        }
        Err(error) if is_connection_closed_error(&error) => {
            logs.send(format!(
                "nikon-wtu: auth step closed the command socket; continuing with final pairing: {error:#}"
            ))
            .ok();
        }
        Err(error) => return Err(error).context("sending Nikon pairing auth step"),
    }
    Ok(PairingWizardState::NeedsFinalReconnect)
}

/// Complete Nikon pairing after the wizard auth code was accepted.
///
/// Bodies can close the command socket as part of successful pairing, so socket
/// closure is accepted here if it happens after sending the final command.
fn finalize_pairing_after_auth(
    config: &NikonWtuConfig,
    computer_name: &str,
    guid: [u8; 16],
    logs: &mpsc::Sender<String>,
) -> Result<()> {
    for attempt in 1..=PAIRING_FINALIZE_RETRIES {
        thread::sleep(Duration::from_millis(400));
        logs.send(format!(
            "nikon-wtu: final pairing attempt {attempt}/{PAIRING_FINALIZE_RETRIES}"
        ))
        .ok();
        let result = (|| -> Result<()> {
            let mut session = PtpIpSession::connect(
                &config.camera,
                config.port,
                computer_name,
                guid,
                DEFAULT_CONNECT_TIMEOUT,
            )
            .with_context(|| {
                format!(
                    "connecting to {}:{} for final pairing",
                    config.camera, config.port
                )
            })?;
            session.command_no_data(PTP_OC_OPEN_SESSION, &[1])?;
            match session.command_no_data(PTP_OC_NIKON_COMPLETE_PAIRING, &[NIKON_PAIRING_COMPLETE])
            {
                Ok(_) => {
                    logs.send("nikon-wtu: final pairing command accepted".to_string())
                        .ok();
                    let _ = session.command_no_data(PTP_OC_CLOSE_SESSION, &[]);
                    Ok(())
                }
                Err(error) if is_connection_closed_error(&error) => {
                    logs.send(format!(
                        "nikon-wtu: final pairing closed the command socket; treating as accepted: {error:#}"
                    ))
                    .ok();
                    Ok(())
                }
                Err(error) => Err(error).context("sending Nikon final pairing command"),
            }
        })();
        match result {
            Ok(()) => return Ok(()),
            Err(error) => {
                logs.send(format!(
                    "nikon-wtu: final pairing attempt {attempt} failed: {error:#}"
                ))
                .ok();
            }
        }
    }
    bail!("Nikon final pairing did not complete after {PAIRING_FINALIZE_RETRIES} attempts")
}

/// Decode Nikon's pairing-code payload into the digits shown by the camera.
fn parse_pairing_code(data: &[u8]) -> Result<String> {
    let len = read_u32(data, 0)? as usize;
    if len == 0 || len > 16 {
        bail!("invalid Nikon pairing code length {len}");
    }
    let digits = data
        .get(4..4 + len)
        .ok_or_else(|| anyhow!("short Nikon pairing code response"))?;
    let mut code = String::with_capacity(len);
    for digit in digits {
        match *digit {
            0..=9 => code.push(char::from(b'0' + *digit)),
            b'0'..=b'9' => code.push(char::from(*digit)),
            value => bail!("invalid Nikon pairing code digit 0x{value:02x}"),
        }
    }
    Ok(code)
}

/// On-disk pairing identity cache.
///
/// Nikon pairing is tied to the initiator GUID, the computer name, the PTP/IP
/// port, and either the current host/IP or the camera name reported by the body.
struct PairingCache {
    path: PathBuf,
    records: Vec<Value>,
}

impl PairingCache {
    /// Load the JSON pairing cache, treating missing or malformed files as empty.
    fn load() -> Result<Self> {
        let path = default_pairing_cache_path()?;
        let records = match fs::read_to_string(&path) {
            Ok(text) => serde_json::from_str::<Value>(&text)
                .ok()
                .and_then(|value| value.get("pairings").and_then(Value::as_array).cloned())
                .unwrap_or_default(),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Vec::new(),
            Err(error) => return Err(error).with_context(|| format!("reading {}", path.display())),
        };
        Ok(Self { path, records })
    }

    /// Return true when the cached initiator identity matches this camera.
    fn is_paired(
        &self,
        camera: &str,
        port: u16,
        camera_name: &str,
        computer_name: &str,
        guid: &[u8; 16],
    ) -> bool {
        let guid = format_guid(guid);
        self.records.iter().any(|record| {
            value_str(record, "guid") == Some(guid.as_str())
                && value_str(record, "computer_name") == Some(computer_name)
                && value_u64(record, "port") == Some(u64::from(port))
                && (value_str(record, "camera") == Some(camera)
                    || value_str(record, "camera_name") == Some(camera_name))
        })
    }

    /// Store a successful camera pairing, replacing an older matching record.
    fn upsert(
        &mut self,
        camera: &str,
        port: u16,
        camera_name: &str,
        computer_name: &str,
        guid: &[u8; 16],
    ) -> Result<()> {
        let guid_text = format_guid(guid);
        self.records.retain(|existing| {
            !(value_str(existing, "guid") == Some(guid_text.as_str())
                && value_str(existing, "computer_name") == Some(computer_name)
                && value_u64(existing, "port") == Some(u64::from(port))
                && (value_str(existing, "camera") == Some(camera)
                    || value_str(existing, "camera_name") == Some(camera_name)))
        });
        let record = json!({
            "camera": camera,
            "port": port,
            "camera_name": camera_name,
            "computer_name": computer_name,
            "guid": guid_text,
            "paired_at": Utc::now().to_rfc3339(),
        });
        self.records.push(record);
        if let Some(parent) = self.path.parent() {
            fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
        }
        let text = serde_json::to_string_pretty(&json!({
            "version": 1,
            "pairings": &self.records,
        }))?;
        fs::write(&self.path, text).with_context(|| format!("writing {}", self.path.display()))?;
        Ok(())
    }
}

fn value_str<'a>(record: &'a Value, key: &str) -> Option<&'a str> {
    record.get(key).and_then(Value::as_str)
}

fn value_u64(record: &Value, key: &str) -> Option<u64> {
    record.get(key).and_then(Value::as_u64)
}

/// Result of handling one Nikon transfer object.
///
/// Existing and unsupported objects are still read from the camera so they are
/// removed from the Nikon transfer queue.
enum TransferDownload {
    Downloaded { filename: String, bytes: u64 },
    SkippedExisting(String),
    SkippedUnsupported,
}

/// Nikon WTU transfer-queue entry returned by opcode `0x9010`.
///
/// The payload is not a standard PTP object-info block. It contains a transfer
/// job marker, object handle, UTF-16 path, size, and optional date strings.
#[derive(Debug)]
struct TransferObject {
    transfer_job: u8,
    object_handle: u32,
    object_path: String,
    object_size: u32,
}

impl TransferObject {
    /// Parse Nikon's compact transfer-object payload.
    ///
    /// Inactive records can be as short as a single status byte. Active records
    /// are expected to carry at least a handle and path length.
    fn parse(data: &[u8]) -> Result<Self> {
        let transfer_job = *data
            .first()
            .ok_or_else(|| anyhow!("empty Nikon transfer-object response"))?;
        if data.len() < 6 {
            if transfer_job == NIKON_TRANSFER_ACTIVE {
                bail!("short active Nikon transfer-object response");
            }
            return Ok(Self {
                transfer_job,
                object_handle: 0,
                object_path: String::new(),
                object_size: 0,
            });
        }

        let object_handle = read_u32(data, 1)?;
        let path_units = usize::from(data[5]);
        let (object_path, mut offset) = read_utf16_units_at(data, 6, path_units)?;
        let object_size = if offset + 4 <= data.len() {
            let size = read_u32(data, offset)?;
            offset += 4;
            size
        } else {
            0
        };

        for _ in 0..2 {
            // Official Nikon transfer records include capture and modification
            // date strings after the object size. We do not need them for file
            // ingest, but walking past them validates the record shape.
            let Some(units) = data.get(offset).copied().map(usize::from) else {
                break;
            };
            offset += 1;
            let (_, next) = read_utf16_units_at(data, offset, units)?;
            offset = next;
        }

        Ok(Self {
            transfer_job,
            object_handle,
            object_path,
            object_size,
        })
    }
}

/// Fetch metadata for one queued object and either download or consume it.
///
/// Non-RAW objects are silently consumed because the camera may offer JPEG/RAW
/// pairs; leaving JPEGs unread can cause the body to keep advertising the same
/// unsupported queue item.
fn download_transfer_object(
    session: &mut PtpIpSession,
    object: &TransferObject,
    output_dir: &Path,
) -> Result<TransferDownload> {
    let info_data = session
        .command_with_data(PTP_OC_GET_OBJECT_INFO, &[object.object_handle])
        .with_context(|| format!("reading object info for 0x{:08x}", object.object_handle))?;
    let info = ObjectInfo::parse(&info_data).unwrap_or_else(|_| ObjectInfo {
        filename: filename_from_transfer_path(&object.object_path)
            .unwrap_or_else(|| format!("nikon-object-{:08x}", object.object_handle)),
        size: object.object_size,
    });
    let filename = if info.filename.trim().is_empty() {
        filename_from_transfer_path(&object.object_path)
            .unwrap_or_else(|| format!("nikon-object-{:08x}", object.object_handle))
    } else {
        info.filename.clone()
    };
    if !is_supported_raw_file(Path::new(&filename)) {
        // Read-and-discard tells the body the transfer slot is done while
        // preserving mini-film's RAW-only inbox behavior.
        consume_transfer_object(session, object, &info)
            .with_context(|| format!("discarding unsupported transfer object {filename}"))?;
        return Ok(TransferDownload::SkippedUnsupported);
    }

    let safe_filename = sanitize_filename::sanitize(&filename);
    let output = output_dir.join(safe_filename.as_ref());
    if output.exists() {
        // Existing files can happen after reconnects; consume the object anyway
        // so it does not block later RAWs in the camera queue.
        consume_transfer_object(session, object, &info)
            .with_context(|| format!("discarding already-downloaded transfer object {filename}"))?;
        return Ok(TransferDownload::SkippedExisting(filename));
    }
    let tmp = output.with_file_name(format!("{safe_filename}.mini-film-part"));
    let result = download_transfer_object_to_file(session, object, &info, &tmp).and_then(|bytes| {
        fs::rename(&tmp, &output)
            .with_context(|| format!("moving {} to {}", tmp.display(), output.display()))?;
        Ok(bytes)
    });

    match result {
        Ok(bytes) => Ok(TransferDownload::Downloaded { filename, bytes }),
        Err(error) => {
            let _ = fs::remove_file(&tmp);
            Err(error)
        }
    }
}

/// Download a supported RAW transfer object into a temporary file.
fn download_transfer_object_to_file(
    session: &mut PtpIpSession,
    object: &TransferObject,
    info: &ObjectInfo,
    tmp: &Path,
) -> Result<u64> {
    let expected_size = u64::from(info.size.max(object.object_size));
    let mut file = fs::File::create(tmp).with_context(|| format!("creating {}", tmp.display()))?;
    let bytes = read_transfer_object_chunks(session, object, info, |chunk| {
        file.write_all(chunk)
            .with_context(|| format!("writing {}", tmp.display()))
    })?;

    file.flush()
        .with_context(|| format!("flushing {}", tmp.display()))?;
    drop(file);
    if expected_size > 0 && bytes != expected_size {
        // Some Nikon bodies report object size accurately before transfer.
        // Preserve the old strictness here because RAW processors tend to fail
        // later with less useful errors when a partial file slips through.
        bail!(
            "object {} expected {} bytes, received {} bytes",
            info.filename,
            expected_size,
            bytes
        );
    }
    Ok(bytes)
}

/// Read and discard an object so Nikon advances its transfer queue.
fn consume_transfer_object(
    session: &mut PtpIpSession,
    object: &TransferObject,
    info: &ObjectInfo,
) -> Result<u64> {
    read_transfer_object_chunks(session, object, info, |_| Ok(()))
}

/// Read a Nikon object through repeated `GetPartialObject` requests.
///
/// PTP/IP packet sizes are bounded and Nikon WTU uses partial reads for large
/// objects. The callback lets callers either write chunks to disk or discard
/// them while sharing the same queue-consuming behavior.
fn read_transfer_object_chunks(
    session: &mut PtpIpSession,
    object: &TransferObject,
    info: &ObjectInfo,
    mut on_chunk: impl FnMut(&[u8]) -> Result<()>,
) -> Result<u64> {
    let expected_size = u64::from(info.size.max(object.object_size));
    let mut offset = 0u64;
    loop {
        if expected_size > 0 && offset >= expected_size {
            break;
        }
        let remaining = expected_size.saturating_sub(offset);
        let request_size = if expected_size == 0 {
            NIKON_TRANSFER_BLOCK_SIZE
        } else {
            u32::try_from(remaining.min(u64::from(NIKON_TRANSFER_BLOCK_SIZE)))
                .unwrap_or(NIKON_TRANSFER_BLOCK_SIZE)
        };
        let (chunk, _) = session.command_with_data_response(
            PTP_OC_GET_PARTIAL_OBJECT,
            &[
                object.object_handle,
                // Nikon's GetPartialObject variant takes a 32-bit byte offset.
                // Bail above 4 GiB rather than wrapping and corrupting output.
                u32::try_from(offset).context("Nikon transfer object exceeds 4 GiB")?,
                request_size,
            ],
        )?;
        if chunk.is_empty() {
            if expected_size == 0 {
                break;
            }
            bail!(
                "object {} ended at {} of {} bytes",
                info.filename,
                offset,
                expected_size
            );
        }
        on_chunk(&chunk)?;
        offset = offset
            .checked_add(chunk.len() as u64)
            .ok_or_else(|| anyhow!("Nikon transfer byte count overflow"))?;
        if expected_size == 0 && chunk.len() < request_size as usize {
            break;
        }
    }
    Ok(offset)
}

/// Extract a filename from Nikon's slash- or backslash-separated object path.
fn filename_from_transfer_path(path: &str) -> Option<String> {
    let normalized = path.replace('\\', "/");
    Path::new(&normalized)
        .file_name()
        .and_then(|name| name.to_str())
        .filter(|name| !name.trim().is_empty())
        .map(str::to_string)
}

/// Sleep in short increments so receiver shutdown does not wait the full delay.
fn sleep_until_stopped(stop: &AtomicBool, duration: Duration) {
    let mut remaining = duration;
    while !stop.load(Ordering::Relaxed) && !remaining.is_zero() {
        let step = remaining.min(Duration::from_millis(100));
        thread::sleep(step);
        remaining = remaining.saturating_sub(step);
    }
}

/// PTP/IP command and event channel pair.
///
/// PTP/IP opens two TCP connections: the command channel carries requests and
/// data, while the event channel carries camera-side notifications and pings.
struct PtpIpSession {
    command: TcpStream,
    event: TcpStream,
    transaction_id: u32,
    camera_name: String,
}

impl PtpIpSession {
    /// Establish command and event channels using Nikon's PTP/IP init handshake.
    fn connect(
        host: &str,
        port: u16,
        computer_name: &str,
        guid: [u8; 16],
        timeout: Duration,
    ) -> Result<Self> {
        let mut command = connect_tcp(host, port, timeout)?;
        command.set_read_timeout(Some(DEFAULT_IO_TIMEOUT))?;
        command.set_write_timeout(Some(DEFAULT_IO_TIMEOUT))?;
        send_packet(
            &mut command,
            PTPIP_INIT_COMMAND_REQUEST,
            &init_command_payload(guid, computer_name),
        )?;
        let packet = read_packet(&mut command)?;
        if packet.kind == PTPIP_INIT_FAIL {
            bail!(
                "camera rejected PTP/IP init; first-time Nikon pairing/auth is probably required"
            );
        }
        if packet.kind != PTPIP_INIT_COMMAND_ACK {
            bail!("expected InitCommandAck, got packet type {}", packet.kind);
        }
        let connection_id = read_u32(&packet.payload, 0)?;
        let camera_name = utf16z_to_string(packet.payload.get(20..).unwrap_or_default());

        // The event connection is explicitly linked to the command connection
        // ID returned by InitCommandAck.
        let mut event = connect_tcp(host, port, timeout)?;
        event.set_read_timeout(Some(EVENT_READ_TIMEOUT))?;
        event.set_write_timeout(Some(DEFAULT_IO_TIMEOUT))?;
        let mut payload = Vec::with_capacity(4);
        push_u32(&mut payload, connection_id);
        send_packet(&mut event, PTPIP_INIT_EVENT_REQUEST, &payload)?;
        let packet = read_packet(&mut event)?;
        if packet.kind != PTPIP_INIT_EVENT_ACK {
            bail!("expected InitEventAck, got packet type {}", packet.kind);
        }

        Ok(Self {
            command,
            event,
            transaction_id: 1,
            camera_name: if camera_name.is_empty() {
                "Nikon camera".to_string()
            } else {
                camera_name
            },
        })
    }

    /// Send a PTP command that should return only a response packet.
    fn command_no_data(&mut self, opcode: u16, params: &[u32]) -> Result<PtpResponse> {
        self.send_command(opcode, params)?;
        let response = self.read_response()?;
        response.ensure_ok(opcode)?;
        Ok(response)
    }

    /// Send a PTP command and return only its data payload.
    fn command_with_data(&mut self, opcode: u16, params: &[u32]) -> Result<Vec<u8>> {
        Ok(self.command_with_data_response(opcode, params)?.0)
    }

    /// Send a PTP command and return both data and final response.
    ///
    /// Some Nikon commands return an immediate response when no data is
    /// available, so this method handles both `StartDataPacket` and
    /// `CmdResponse` as valid first packets.
    fn command_with_data_response(
        &mut self,
        opcode: u16,
        params: &[u32],
    ) -> Result<(Vec<u8>, PtpResponse)> {
        self.send_command(opcode, params)?;
        match self.read_data_or_response()? {
            DataRead::Data(data) => {
                let response = self.read_response()?;
                response.ensure_ok(opcode)?;
                Ok((data, response))
            }
            DataRead::Response(response) => {
                response.ensure_ok(opcode)?;
                Ok((Vec::new(), response))
            }
        }
    }

    /// Serialize and send a PTP command request packet.
    fn send_command(&mut self, opcode: u16, params: &[u32]) -> Result<u32> {
        if params.len() > 5 {
            bail!("PTP/IP supports at most 5 command parameters");
        }
        let transaction_id = self.transaction_id;
        self.transaction_id = self.transaction_id.wrapping_add(1).max(1);
        let mut payload = Vec::with_capacity(10 + params.len() * 4);
        push_u32(&mut payload, 1);
        push_u16(&mut payload, opcode);
        push_u32(&mut payload, transaction_id);
        for param in params {
            push_u32(&mut payload, *param);
        }
        send_packet(&mut self.command, PTPIP_CMD_REQUEST, &payload)?;
        Ok(transaction_id)
    }

    /// Read either a complete data phase or an immediate response.
    fn read_data_or_response(&mut self) -> Result<DataRead> {
        let first = read_packet(&mut self.command)?;
        if first.kind == PTPIP_CMD_RESPONSE {
            return Ok(DataRead::Response(PtpResponse::parse(&first.payload)?));
        }
        if first.kind != PTPIP_START_DATA_PACKET {
            bail!("expected StartDataPacket, got packet type {}", first.kind);
        }
        let total = usize::try_from(read_u64(&first.payload, 4)?)
            .context("PTP/IP data packet length exceeds usize")?;
        let mut data = Vec::with_capacity(total);
        while data.len() < total {
            let packet = read_packet(&mut self.command)?;
            match packet.kind {
                PTPIP_DATA_PACKET | PTPIP_END_DATA_PACKET => {
                    if packet.payload.len() < 4 {
                        bail!("short data packet");
                    }
                    data.extend_from_slice(&packet.payload[4..]);
                    if packet.kind == PTPIP_END_DATA_PACKET {
                        // Nikon can end the data phase before the advertised
                        // byte count has been reached on zero/unknown length
                        // responses; truncate/checking happens at the caller.
                        break;
                    }
                }
                kind => bail!("unexpected packet type {kind} while reading data"),
            }
        }
        data.truncate(total);
        Ok(DataRead::Data(data))
    }

    /// Read the final command response packet, skipping redundant EndData packets.
    fn read_response(&mut self) -> Result<PtpResponse> {
        loop {
            let packet = read_packet(&mut self.command)?;
            match packet.kind {
                PTPIP_CMD_RESPONSE => return PtpResponse::parse(&packet.payload),
                PTPIP_END_DATA_PACKET => continue,
                kind => bail!("expected CmdResponse, got packet type {kind}"),
            }
        }
    }

    /// Read one event-channel packet, answering PTP/IP pings automatically.
    fn read_event(&mut self, timeout: Duration) -> Result<Option<PtpEvent>> {
        self.event.set_read_timeout(Some(timeout))?;
        match read_packet(&mut self.event) {
            Ok(packet) if packet.kind == PTPIP_EVENT => Ok(Some(PtpEvent::parse(&packet.payload)?)),
            Ok(packet) if packet.kind == PTPIP_PING => {
                send_packet(&mut self.event, PTPIP_PONG, &[])?;
                Ok(None)
            }
            Ok(packet) => bail!("unexpected event-channel packet type {}", packet.kind),
            Err(error) if is_timeout_error(error.downcast_ref::<io::Error>()) => Ok(None),
            Err(error) => Err(error),
        }
    }
}

/// Result of the first command-channel packet after a command request.
///
/// Standard data commands start with `StartDataPacket`; Nikon queue probes can
/// instead answer immediately with `CmdResponse` when there is nothing to send.
enum DataRead {
    Data(Vec<u8>),
    Response(PtpResponse),
}

/// Parsed PTP command response.
struct PtpResponse {
    code: u16,
    transaction_id: u32,
    params: Vec<u32>,
}

impl PtpResponse {
    /// Parse a PTP response payload from a PTP/IP `CmdResponse` packet.
    fn parse(payload: &[u8]) -> Result<Self> {
        let code = read_u16(payload, 0)?;
        let transaction_id = read_u32(payload, 2)?;
        let mut params = Vec::new();
        let mut offset = 6;
        while offset + 4 <= payload.len() && params.len() < 5 {
            params.push(read_u32(payload, offset)?);
            offset += 4;
        }
        Ok(Self {
            code,
            transaction_id,
            params,
        })
    }

    /// Fail unless the response is OK, preserving opcode and transaction data.
    fn ensure_ok(&self, opcode: u16) -> Result<()> {
        if self.code == PTP_RC_OK {
            return Ok(());
        }
        bail!(
            "PTP command 0x{opcode:04x} failed with response 0x{:04x}, transaction {}, params {:?}",
            self.code,
            self.transaction_id,
            self.params
        )
    }
}

/// Parsed PTP event-channel notification.
struct PtpEvent {
    code: u16,
    params: Vec<u32>,
}

impl PtpEvent {
    /// Parse a PTP event payload from a PTP/IP `Event` packet.
    fn parse(payload: &[u8]) -> Result<Self> {
        let code = read_u16(payload, 0)?;
        let mut params = Vec::new();
        let mut offset = 6;
        while offset + 4 <= payload.len() && params.len() < 3 {
            params.push(read_u32(payload, offset)?);
            offset += 4;
        }
        Ok(Self { code, params })
    }
}

/// Minimal standard PTP object-info fields needed for inbox writes.
struct ObjectInfo {
    filename: String,
    size: u32,
}

impl ObjectInfo {
    /// Parse standard PTP ObjectInfo, using only filename and compressed size.
    fn parse(data: &[u8]) -> Result<Self> {
        let size = read_u32(data, 8).unwrap_or(0);
        let filename = read_ptp_string(data, 52)
            .ok_or_else(|| anyhow!("object info did not include a filename"))?;
        Ok(Self { filename, size })
    }
}

/// Minimal standard PTP device-info fields used for logging and feature checks.
struct DeviceInfo {
    vendor_extension_id: u32,
    vendor_extension_version: u16,
    operations: Vec<u16>,
    manufacturer: String,
    model: String,
}

impl DeviceInfo {
    /// Parse standard PTP DeviceInfo including supported operation codes.
    fn parse(data: &[u8]) -> Result<Self> {
        let vendor_extension_id = read_u32(data, 2)?;
        let vendor_extension_version = read_u16(data, 6)?;
        let (_, mut offset) = read_ptp_string_at(data, 8)
            .ok_or_else(|| anyhow!("device info did not include vendor extension description"))?;
        offset = offset
            .checked_add(2)
            .ok_or_else(|| anyhow!("device info offset overflow"))?;
        let (operations, next) = read_u16_array_at(data, offset)?;
        let (_, next) = read_u16_array_at(data, next)?;
        let (_, next) = read_u16_array_at(data, next)?;
        let (_, next) = read_u16_array_at(data, next)?;
        let (_, next) = read_u16_array_at(data, next)?;
        let (manufacturer, next) = read_ptp_string_at(data, next)
            .ok_or_else(|| anyhow!("device info did not include manufacturer"))?;
        let (model, _) = read_ptp_string_at(data, next)
            .ok_or_else(|| anyhow!("device info did not include model"))?;
        Ok(Self {
            vendor_extension_id,
            vendor_extension_version,
            operations,
            manufacturer,
            model,
        })
    }
}

/// Raw PTP/IP packet after the length/type header is removed.
struct Packet {
    kind: u32,
    payload: Vec<u8>,
}

/// Connect to the first resolved TCP address within the configured timeout.
fn connect_tcp(host: &str, port: u16, timeout: Duration) -> Result<TcpStream> {
    let mut last_error = None;
    for address in (host, port).to_socket_addrs()? {
        match TcpStream::connect_timeout(&address, timeout) {
            Ok(stream) => return Ok(stream),
            Err(error) => last_error = Some(error),
        }
    }
    Err(last_error
        .map(anyhow::Error::from)
        .unwrap_or_else(|| anyhow!("no socket addresses resolved for {host}:{port}")))
}

/// Build a complete little-endian PTP/IP packet.
fn build_packet(kind: u32, payload: &[u8]) -> Result<Vec<u8>> {
    let len = 8usize
        .checked_add(payload.len())
        .ok_or_else(|| anyhow!("PTP/IP packet too large"))?;
    let len = u32::try_from(len).context("PTP/IP packet length exceeds u32")?;
    let mut buffer = Vec::with_capacity(len as usize);
    push_u32(&mut buffer, len);
    push_u32(&mut buffer, kind);
    buffer.extend_from_slice(payload);
    Ok(buffer)
}

/// Write one PTP/IP packet to a TCP stream.
fn send_packet(stream: &mut TcpStream, kind: u32, payload: &[u8]) -> Result<()> {
    let buffer = build_packet(kind, payload)?;
    stream.write_all(&buffer)?;
    Ok(())
}

/// Read one complete PTP/IP packet from a TCP stream.
fn read_packet(stream: &mut TcpStream) -> Result<Packet> {
    let mut header = [0u8; 8];
    stream.read_exact(&mut header)?;
    let len = read_u32(&header, 0)? as usize;
    let kind = read_u32(&header, 4)?;
    if len < 8 {
        bail!("invalid PTP/IP packet length {len}");
    }
    let mut payload = vec![0u8; len - 8];
    stream.read_exact(&mut payload)?;
    Ok(Packet { kind, payload })
}

/// Build the initiator payload used by `InitCommandRequest`.
fn init_command_payload(guid: [u8; 16], computer_name: &str) -> Vec<u8> {
    let mut payload = Vec::new();
    payload.extend_from_slice(&guid);
    push_utf16z(&mut payload, computer_name);
    push_u16(&mut payload, 0);
    push_u16(&mut payload, 1);
    payload
}

fn push_utf16z(out: &mut Vec<u8>, value: &str) {
    for unit in value.encode_utf16() {
        push_u16(out, unit);
    }
    push_u16(out, 0);
}

fn utf16z_to_string(bytes: &[u8]) -> String {
    let mut units = Vec::new();
    for chunk in bytes.chunks_exact(2) {
        let unit = u16::from_le_bytes([chunk[0], chunk[1]]);
        if unit == 0 {
            break;
        }
        units.push(unit);
    }
    String::from_utf16_lossy(&units)
}

fn read_ptp_string(data: &[u8], offset: usize) -> Option<String> {
    read_ptp_string_at(data, offset).map(|(value, _)| value)
}

fn read_ptp_string_at(data: &[u8], offset: usize) -> Option<(String, usize)> {
    let len = *data.get(offset)? as usize;
    if len == 0 {
        return Some((String::new(), offset + 1));
    }
    let start = offset + 1;
    let byte_len = len.checked_mul(2)?;
    let bytes = data.get(start..start + byte_len)?;
    Some((utf16z_to_string(bytes), start + byte_len))
}

fn read_utf16_units_at(data: &[u8], offset: usize, units: usize) -> Result<(String, usize)> {
    let byte_len = units
        .checked_mul(2)
        .ok_or_else(|| anyhow!("UTF-16 string length overflow"))?;
    let end = offset
        .checked_add(byte_len)
        .ok_or_else(|| anyhow!("UTF-16 string end offset overflow"))?;
    let bytes = data
        .get(offset..end)
        .ok_or_else(|| anyhow!("short UTF-16 string at {offset} with {units} units"))?;
    Ok((utf16z_to_string(bytes), end))
}

fn read_u16(data: &[u8], offset: usize) -> Result<u16> {
    let bytes = data
        .get(offset..offset + 2)
        .ok_or_else(|| anyhow!("short PTP/IP payload reading u16 at {offset}"))?;
    Ok(u16::from_le_bytes([bytes[0], bytes[1]]))
}

fn read_u32(data: &[u8], offset: usize) -> Result<u32> {
    let bytes = data
        .get(offset..offset + 4)
        .ok_or_else(|| anyhow!("short PTP/IP payload reading u32 at {offset}"))?;
    Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
}

fn read_u64(data: &[u8], offset: usize) -> Result<u64> {
    let bytes = data
        .get(offset..offset + 8)
        .ok_or_else(|| anyhow!("short PTP/IP payload reading u64 at {offset}"))?;
    Ok(u64::from_le_bytes([
        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
    ]))
}

fn push_u16(out: &mut Vec<u8>, value: u16) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn push_u32(out: &mut Vec<u8>, value: u32) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn read_u16_array_at(data: &[u8], offset: usize) -> Result<(Vec<u16>, usize)> {
    let count = read_u32(data, offset)? as usize;
    let mut next = offset
        .checked_add(4)
        .ok_or_else(|| anyhow!("PTP array offset overflow"))?;
    let byte_len = count
        .checked_mul(2)
        .ok_or_else(|| anyhow!("PTP array length overflow"))?;
    let end = next
        .checked_add(byte_len)
        .ok_or_else(|| anyhow!("PTP array end offset overflow"))?;
    data.get(next..end)
        .ok_or_else(|| anyhow!("short PTP array at {offset} with {count} entries"))?;
    let mut values = Vec::with_capacity(count);
    while next < end {
        values.push(read_u16(data, next)?);
        next += 2;
    }
    Ok((values, next))
}

/// Return true for event-channel read timeouts.
fn is_timeout_error(error: Option<&io::Error>) -> bool {
    matches!(
        error.map(io::Error::kind),
        Some(io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock)
    )
}

/// Return true when Nikon intentionally closed the socket mid-pairing/transfer.
fn is_connection_closed_error(error: &anyhow::Error) -> bool {
    error.chain().any(|cause| {
        cause.downcast_ref::<io::Error>().is_some_and(|io_error| {
            matches!(
                io_error.kind(),
                io::ErrorKind::UnexpectedEof
                    | io::ErrorKind::ConnectionAborted
                    | io::ErrorKind::ConnectionReset
                    | io::ErrorKind::BrokenPipe
            )
        })
    })
}

/// Return true for expected offline-camera connect errors.
///
/// Daemon mode can run for hours with the camera powered off. These errors only
/// mean "try again later", not a condition worth printing every reconnect.
fn is_expected_camera_offline_error(error: &anyhow::Error) -> bool {
    error.chain().any(|cause| {
        cause.downcast_ref::<io::Error>().is_some_and(|io_error| {
            matches!(
                io_error.kind(),
                io::ErrorKind::ConnectionRefused
                    | io::ErrorKind::TimedOut
                    | io::ErrorKind::AddrNotAvailable
                    | io::ErrorKind::NotConnected
            ) || matches!(
                io_error.raw_os_error(),
                // Linux, macOS/BSD, and Windows route/refuse/timeout errors.
                Some(101 | 110 | 111 | 113 | 51 | 60 | 61 | 65 | 10051 | 10060 | 10061 | 10065)
            )
        })
    })
}

/// Resolve the configured or cached Nikon initiator GUID.
///
/// A stable GUID matters because Nikon pairings are tied to this identity; a
/// new random GUID would force the user through the camera wizard again.
fn resolve_guid(explicit: Option<&str>) -> Result<[u8; 16]> {
    if let Some(value) = explicit {
        return parse_guid(value);
    }
    let path = default_guid_path()?;
    if let Ok(text) = fs::read_to_string(&path)
        && let Ok(guid) = parse_guid(text.trim())
    {
        return Ok(guid);
    }
    let guid = generated_guid();
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).ok();
    }
    fs::write(&path, format_guid(&guid)).ok();
    Ok(guid)
}

/// Path where mini-film persists the default WTU initiator GUID.
fn default_guid_path() -> Result<PathBuf> {
    Ok(default_cache_dir()?.join("nikon-wtu-guid"))
}

/// Path where mini-film remembers successful Nikon WTU pairings.
fn default_pairing_cache_path() -> Result<PathBuf> {
    Ok(default_cache_dir()?.join("nikon-wtu-pairings.json"))
}

/// mini-film cache directory under the user's home directory.
fn default_cache_dir() -> Result<PathBuf> {
    let home = env::var_os("HOME").ok_or_else(|| anyhow!("HOME is not set"))?;
    Ok(PathBuf::from(home).join(".cache").join("mini-film"))
}

/// Generate a stable-ish first-run GUID seed from local identity and time.
fn generated_guid() -> [u8; 16] {
    let mut hasher = Sha1::new();
    hasher.update(default_computer_name().as_bytes());
    if let Some(home) = env::var_os("HOME") {
        hasher.update(home.to_string_lossy().as_bytes());
    }
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    hasher.update(now.to_le_bytes());
    let digest = hasher.finalize();
    let mut guid = [0u8; 16];
    guid.copy_from_slice(&digest[..16]);
    guid
}

/// Parse plain or colon-separated 16-byte GUID text.
fn parse_guid(value: &str) -> Result<[u8; 16]> {
    let hex = value
        .chars()
        .filter(|ch| ch.is_ascii_hexdigit())
        .collect::<String>();
    if hex.len() != 32 {
        bail!("Nikon WTU GUID must contain exactly 16 hex bytes");
    }
    let mut guid = [0u8; 16];
    for index in 0..16 {
        guid[index] = u8::from_str_radix(&hex[index * 2..index * 2 + 2], 16)?;
    }
    Ok(guid)
}

/// Format a GUID as colon-separated lowercase hex for logs and cache files.
fn format_guid(guid: &[u8; 16]) -> String {
    guid.iter()
        .map(|byte| format!("{byte:02x}"))
        .collect::<Vec<_>>()
        .join(":")
}

/// Default PTP/IP initiator display name.
fn default_computer_name() -> String {
    env::var("HOSTNAME")
        .ok()
        .filter(|name| !name.trim().is_empty())
        .unwrap_or_else(|| "mini-film".to_string())
}

/// Format supported PTP operation codes for diagnostic logs.
fn format_opcodes(opcodes: &[u16]) -> String {
    opcodes
        .iter()
        .map(|opcode| format!("0x{opcode:04x}"))
        .collect::<Vec<_>>()
        .join(",")
}

/// Return a bounded hex preview for diagnostic binary payload logging.
fn hex_preview(bytes: &[u8], max_len: usize) -> String {
    let mut out = bytes
        .iter()
        .take(max_len)
        .map(|byte| format!("{byte:02x}"))
        .collect::<Vec<_>>()
        .join(" ");
    if bytes.len() > max_len {
        out.push_str(" ...");
    }
    out
}

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

    #[test]
    fn init_payload_contains_guid_name_and_ptpip_version() {
        let guid = [0x11; 16];
        let payload = init_command_payload(guid, "mini");
        assert_eq!(&payload[..16], &[0x11; 16]);
        assert_eq!(&payload[16..26], b"m\0i\0n\0i\0\0\0");
        assert_eq!(&payload[26..30], &[0, 0, 1, 0]);
    }

    #[test]
    fn guid_parser_accepts_colon_and_plain_hex() {
        let expected = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
        assert_eq!(
            parse_guid("00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f").unwrap(),
            expected
        );
        assert_eq!(
            parse_guid("000102030405060708090a0b0c0d0e0f").unwrap(),
            expected
        );
    }

    #[test]
    fn object_info_parser_reads_filename_and_size() {
        let mut data = vec![0u8; 52];
        data[8..12].copy_from_slice(&1234u32.to_le_bytes());
        let filename = "DSC_0001.NEF";
        data.push((filename.encode_utf16().count() + 1) as u8);
        for unit in filename.encode_utf16().chain(std::iter::once(0)) {
            data.extend_from_slice(&unit.to_le_bytes());
        }
        let info = ObjectInfo::parse(&data).unwrap();
        assert_eq!(info.filename, filename);
        assert_eq!(info.size, 1234);
    }

    #[test]
    fn transfer_object_parser_reads_nikon_queue_record() {
        let mut data = Vec::new();
        data.push(NIKON_TRANSFER_ACTIVE);
        push_u32(&mut data, 0x0102_0304);
        push_sized_utf16(&mut data, "NIKON/DSC_0042.NEF");
        push_u32(&mut data, 42_000_000);
        push_sized_utf16(&mut data, "20260609T120000");
        push_sized_utf16(&mut data, "20260609T120001");

        let object = TransferObject::parse(&data).unwrap();
        assert_eq!(object.transfer_job, NIKON_TRANSFER_ACTIVE);
        assert_eq!(object.object_handle, 0x0102_0304);
        assert_eq!(object.object_path, "NIKON/DSC_0042.NEF");
        assert_eq!(object.object_size, 42_000_000);
    }

    #[test]
    fn transfer_object_parser_accepts_inactive_short_record() {
        let object = TransferObject::parse(&[0]).unwrap();
        assert_eq!(object.transfer_job, 0);
        assert_eq!(object.object_handle, 0);
    }

    #[test]
    fn transfer_filename_uses_last_path_component() {
        assert_eq!(
            filename_from_transfer_path("NIKON\\Z7\\DSC_0042.NEF").as_deref(),
            Some("DSC_0042.NEF")
        );
        assert_eq!(
            filename_from_transfer_path("/store/DCIM/100NIKON/DSC_0043.NEF").as_deref(),
            Some("DSC_0043.NEF")
        );
    }

    #[test]
    fn packet_round_trip_uses_little_endian_header() {
        let bytes = build_packet(PTPIP_CMD_REQUEST, &[1, 2, 3]).unwrap();
        assert_eq!(&bytes[..8], &[11, 0, 0, 0, 6, 0, 0, 0]);
    }

    #[test]
    fn start_data_lengths_are_read_as_64_bit_values() {
        let mut payload = Vec::new();
        push_u32(&mut payload, 7);
        payload.extend_from_slice(&0x1_0000_0001u64.to_le_bytes());
        assert_eq!(read_u64(&payload, 4).unwrap(), 0x1_0000_0001);
    }

    #[test]
    fn device_info_parser_reads_supported_operations_and_names() {
        let mut data = Vec::new();
        push_u16(&mut data, 100);
        push_u32(&mut data, 0x0000_000a);
        push_u16(&mut data, 0x0100);
        push_ptp_string(&mut data, "Nikon");
        push_u16(&mut data, 0);
        push_u16_array(
            &mut data,
            &[PTP_OC_GET_DEVICE_INFO, PTP_OC_NIKON_GET_DEVICE_PTPIP_INFO],
        );
        push_u16_array(&mut data, &[PTP_EC_OBJECT_ADDED]);
        push_u16_array(&mut data, &[]);
        push_u16_array(&mut data, &[]);
        push_u16_array(&mut data, &[]);
        push_ptp_string(&mut data, "NIKON CORPORATION");
        push_ptp_string(&mut data, "Z 7II");
        push_ptp_string(&mut data, "1.00");
        push_ptp_string(&mut data, "123");

        let info = DeviceInfo::parse(&data).unwrap();
        assert_eq!(info.vendor_extension_id, 0x0000_000a);
        assert_eq!(info.vendor_extension_version, 0x0100);
        assert_eq!(info.manufacturer, "NIKON CORPORATION");
        assert_eq!(info.model, "Z 7II");
        assert!(
            info.operations
                .contains(&PTP_OC_NIKON_GET_DEVICE_PTPIP_INFO)
        );
    }

    #[test]
    fn pairing_code_parser_reads_nikon_digit_response() {
        let mut data = Vec::new();
        push_u32(&mut data, 6);
        data.extend_from_slice(&[1, 2, 3, 4, 5, 6]);
        assert_eq!(parse_pairing_code(&data).unwrap(), "123456");
    }

    #[test]
    fn pairing_code_parser_accepts_ascii_digits() {
        let mut data = Vec::new();
        push_u32(&mut data, 4);
        data.extend_from_slice(b"7091");
        assert_eq!(parse_pairing_code(&data).unwrap(), "7091");
    }

    #[test]
    fn pairing_code_parser_rejects_invalid_digits() {
        let mut data = Vec::new();
        push_u32(&mut data, 3);
        data.extend_from_slice(&[1, 42, 3]);
        assert!(parse_pairing_code(&data).is_err());
    }

    #[test]
    fn pairing_socket_close_detection_matches_unexpected_eof() {
        let error = anyhow::Error::from(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "failed to fill whole buffer",
        ));
        assert!(is_connection_closed_error(&error));
        let error = anyhow::Error::from(io::Error::new(io::ErrorKind::InvalidData, "bad packet"));
        assert!(!is_connection_closed_error(&error));
    }

    #[test]
    fn camera_offline_errors_are_silent_reconnect_cases() {
        let no_route = anyhow::Error::from(io::Error::from_raw_os_error(113));
        assert!(is_expected_camera_offline_error(&no_route));

        let refused =
            anyhow::Error::from(io::Error::new(io::ErrorKind::ConnectionRefused, "refused"));
        assert!(is_expected_camera_offline_error(&refused));

        let timeout = anyhow::Error::from(io::Error::new(io::ErrorKind::TimedOut, "timeout"));
        assert!(is_expected_camera_offline_error(&timeout));

        let bad_packet =
            anyhow::Error::from(io::Error::new(io::ErrorKind::InvalidData, "bad packet"));
        assert!(!is_expected_camera_offline_error(&bad_packet));
    }

    #[test]
    fn pairing_cache_matches_same_identity_by_camera_name_or_host() {
        let dir = tempfile::tempdir().unwrap();
        let mut cache = PairingCache {
            path: dir.path().join("pairings.json"),
            records: Vec::new(),
        };
        let guid = [0x2a; 16];

        cache
            .upsert("192.168.0.201", 15740, "Z_7_2_6011974", "mini-film", &guid)
            .unwrap();

        assert!(cache.is_paired("192.168.0.99", 15740, "Z_7_2_6011974", "mini-film", &guid));
        assert!(cache.is_paired("192.168.0.201", 15740, "different-name", "mini-film", &guid));
        assert!(!cache.is_paired("192.168.0.99", 15740, "different-name", "mini-film", &guid));
        assert!(!cache.is_paired("192.168.0.201", 15740, "Z_7_2_6011974", "other-host", &guid));
    }

    fn push_ptp_string(out: &mut Vec<u8>, value: &str) {
        out.push((value.encode_utf16().count() + 1) as u8);
        for unit in value.encode_utf16().chain(std::iter::once(0)) {
            push_u16(out, unit);
        }
    }

    fn push_sized_utf16(out: &mut Vec<u8>, value: &str) {
        out.push((value.encode_utf16().count() + 1) as u8);
        for unit in value.encode_utf16().chain(std::iter::once(0)) {
            push_u16(out, unit);
        }
    }

    fn push_u16_array(out: &mut Vec<u8>, values: &[u16]) {
        push_u32(out, values.len() as u32);
        for value in values {
            push_u16(out, *value);
        }
    }
}