rsmediainfo 0.2.0

Rust wrapper for MediaInfo library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
//! Top-level [`MediaInfo`] type and the parse pipeline that builds it.
//!
//! This module exposes the entrypoints for parsing media files (paths,
//! readers, URLs, raw XML strings), the [`ParseOptions`] builder that
//! configures the parse, the [`MediaInfoSource`] trait that lets a single
//! call accept any of the supported input shapes, and the [`LibVersion`]
//! helper used for runtime feature detection.

use crate::error::{EncodingErrorMode, MediaInfoError, Result};
use crate::ffi::{MediaInfoHandle, MediaInfoLib};
use crate::platform;
use crate::track::Track;
use crate::xml;
use log::{debug, warn};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Read, Seek, SeekFrom, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock, RwLock};

/// Library version information.
///
/// Holds the parsed major / minor / patch components of the underlying media
/// library so callers can branch on the runtime version when deciding which
/// optional features (cover data, post-call reset, thread-safe handle reuse,
/// XML output naming) are available.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct LibVersion {
    /// Major version number, e.g. `20` in `20.09`.
    pub major: u32,
    /// Minor version number, e.g. `9` in `20.09`.
    pub minor: u32,
    /// Patch version number, or `0` when the library reports only
    /// `major.minor`.
    pub patch: u32,
}

impl LibVersion {
    /// Constructs a [`LibVersion`] from explicit `major`, `minor`, and
    /// `patch` components. Useful in tests and for hand-built sentinels.
    pub fn new(major: u32, minor: u32, patch: u32) -> Self {
        LibVersion {
            major,
            minor,
            patch,
        }
    }

    /// Parses a dotted version string into a [`LibVersion`].
    ///
    /// Accepts both `"major.minor"` and `"major.minor.patch"` shapes; a
    /// missing patch component defaults to `0`. Returns `None` only when
    /// the string is empty or the major component is not a valid integer.
    ///
    /// # Example
    ///
    /// ```
    /// use rsmediainfo::mediainfo::LibVersion;
    ///
    /// let v = LibVersion::parse("20.09").unwrap();
    /// assert_eq!(v.major, 20);
    /// assert_eq!(v.minor, 9);
    /// assert_eq!(v.patch, 0);
    /// ```
    pub fn parse(version_str: &str) -> Option<Self> {
        let parts: Vec<&str> = version_str.split('.').collect();
        if parts.is_empty() {
            return None;
        }

        let major = parts.first()?.parse().ok()?;
        let minor = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
        let patch = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);

        Some(LibVersion {
            major,
            minor,
            patch,
        })
    }

    /// Returns `true` when this version supports the `Cover_Data` option
    /// (library 18.3 and newer).
    ///
    /// Older builds always emit cover data when present and have no way
    /// to suppress it; newer builds only emit it when the option is set.
    pub fn supports_cover_data(&self) -> bool {
        *self >= LibVersion::new(18, 3, 0)
    }

    /// Returns `true` when this version supports the `Reset` option
    /// (library 19.9 and newer).
    ///
    /// The reset is used after a parse that set custom options, so the
    /// next parse starts from a clean slate.
    pub fn supports_reset(&self) -> bool {
        *self >= LibVersion::new(19, 9, 0)
    }

    /// Returns the option name to use when requesting XML output from
    /// this version.
    ///
    /// Library 17.10 and newer use `"OLDXML"`; earlier builds use the
    /// plain `"XML"` option name.
    pub fn xml_option_name(&self) -> &'static str {
        if *self >= LibVersion::new(17, 10, 0) {
            "OLDXML"
        } else {
            "XML"
        }
    }

    /// Returns `true` when this version's option-handling code path is
    /// thread-safe (library 20.3 and newer).
    #[allow(dead_code)]
    pub fn is_thread_safe(&self) -> bool {
        *self >= LibVersion::new(20, 3, 0)
    }
}

/// Configuration for a single parse call.
///
/// All fields have sensible defaults (see [`ParseOptions::default`]) and
/// the type uses a chainable builder pattern so callers can override only
/// the options they care about. Every parse entrypoint accepts a
/// `&ParseOptions`, so the same builder can be reused across calls.
///
/// Parse calls are serialized internally so concurrent callers see
/// consistent option state regardless of which thread set them; see the
/// crate-level "Thread safety" section for details.
#[derive(Debug, Clone)]
pub struct ParseOptions {
    /// Explicit path to the shared library. When set, library
    /// auto-detection is bypassed and only this path is tried.
    /// Defaults to `None`.
    pub library_file: Option<PathBuf>,

    /// Directory to search for a bundled shared library before falling
    /// back to system paths. When unset, the parser uses the directory
    /// containing the current executable as the default bundled search
    /// location, falling back to the current working directory if that
    /// is not usable. Defaults to `None`.
    pub library_search_dir: Option<PathBuf>,

    /// When `true`, the parser extracts embedded cover art as base64
    /// text on the general track. Requires library version 18.3 or
    /// newer; older builds always emit cover data when present and have
    /// no way to suppress it. Defaults to `false`.
    pub cover_data: bool,

    /// Parse-speed knob, where `0.0` favors throughput and `1.0` favors
    /// completeness. Values outside the typical `[0.0, 1.0]` range are
    /// forwarded to the library unchanged. Defaults to `0.5`.
    pub parse_speed: f32,

    /// When `true`, the parser emits the full set of details on every
    /// track (the equivalent of the `--Full` flag on the library's
    /// command line). Defaults to `true`.
    pub full: bool,

    /// When `true`, the parser uses the legacy per-stream display
    /// formatting that some integrations rely on. Defaults to `false`.
    pub legacy_stream_display: bool,

    /// Extra option key/value pairs forwarded verbatim to the underlying
    /// option setter. The crate issues a `Reset` after the parse on
    /// library version 19.9 and newer so the next call starts clean; on
    /// older builds it cannot, and a warning is logged through the
    /// `log` crate. Defaults to `None`.
    ///
    /// # Thread safety
    ///
    /// The `Reset` call used to restore the option store after a
    /// custom-options parse mutates process-global state. The parse
    /// pipeline serializes every call via an internal mutex, so
    /// concurrent parses with custom options are safe in the sense
    /// that they will not race against each other — but callers
    /// should still be aware that custom options temporarily take
    /// over the library's global option store for the duration of
    /// each parse. Unrelated FFI callers in the same process that
    /// bypass this crate's lock would observe the transient state.
    pub mediainfo_options: Option<HashMap<String, String>>,

    /// When `Some`, parse calls return a raw text payload in the
    /// requested format instead of building a structured [`MediaInfo`].
    /// Common values include `""` (or `"text"`), `"JSON"`, `"XML"`,
    /// `"OLDXML"`, and `%`-delimited templates such as
    /// `"General;%FileSize%"`. Defaults to `None`.
    pub output: Option<String>,

    /// Buffer size in bytes for the reader-driven parse path. `None`
    /// means "consume the reader in a single `read_to_end` call".
    /// Defaults to `Some(64 * 1024)`.
    pub buffer_size: Option<usize>,

    /// How invalid UTF-8 in the library's XML output is handled. See
    /// [`EncodingErrorMode`] for the available strategies. Defaults to
    /// [`EncodingErrorMode::Strict`].
    pub encoding_errors: EncodingErrorMode,
}

/// Marker trait for reader inputs accepted by the parse pipeline.
///
/// Anything that implements both [`Read`] and [`Seek`] is automatically a
/// [`ReadSeek`]. The trait exists so the parser can take a
/// `&mut dyn ReadSeek` trait object without exposing both bounds at every
/// call site.
pub trait ReadSeek: Read + Seek {}

impl<T: Read + Seek + ?Sized> ReadSeek for T {}

/// A unified input handed to the internal parse pipeline.
///
/// Most callers will go through [`MediaInfoSource`] instead of constructing
/// this enum by hand, but the variants are public so callers that already
/// have one of these shapes can pass them directly.
pub enum MediaInfoInput<'a> {
    /// A path to a media file on disk.
    Path(&'a Path),
    /// A URL the underlying library knows how to open.
    Url(&'a str),
    /// A `Read + Seek` source that the parser will consume through the
    /// buffer-protocol path.
    Reader(&'a mut dyn ReadSeek),
}

/// Conversion trait that lets a single parse call accept any of the
/// supported input shapes (path, URL, reader, or a pre-built
/// [`MediaInfoInput`]).
///
/// Implementations exist for `&Path`, `&PathBuf`, `&str`, `&String`,
/// `&mut R: Read + Seek`, `&mut dyn ReadSeek`, and `MediaInfoInput<'_>`.
/// String inputs are routed to [`MediaInfoInput::Url`] when they contain
/// `://` and to [`MediaInfoInput::Path`] otherwise.
pub trait MediaInfoSource<'a> {
    /// Converts the value into a [`MediaInfoInput`] the parse pipeline
    /// can consume.
    fn into_input(self) -> MediaInfoInput<'a>;
}

impl<'a> MediaInfoSource<'a> for MediaInfoInput<'a> {
    fn into_input(self) -> MediaInfoInput<'a> {
        self
    }
}

impl<'a> MediaInfoSource<'a> for &'a Path {
    fn into_input(self) -> MediaInfoInput<'a> {
        MediaInfoInput::Path(self)
    }
}

impl<'a> MediaInfoSource<'a> for &'a PathBuf {
    fn into_input(self) -> MediaInfoInput<'a> {
        MediaInfoInput::Path(self.as_path())
    }
}

impl<'a> MediaInfoSource<'a> for &'a str {
    fn into_input(self) -> MediaInfoInput<'a> {
        if self.contains("://") {
            MediaInfoInput::Url(self)
        } else {
            MediaInfoInput::Path(Path::new(self))
        }
    }
}

impl<'a> MediaInfoSource<'a> for &'a String {
    fn into_input(self) -> MediaInfoInput<'a> {
        self.as_str().into_input()
    }
}

impl<'a, R: ReadSeek> MediaInfoSource<'a> for &'a mut R {
    fn into_input(self) -> MediaInfoInput<'a> {
        MediaInfoInput::Reader(self)
    }
}

impl<'a> MediaInfoSource<'a> for &'a mut dyn ReadSeek {
    fn into_input(self) -> MediaInfoInput<'a> {
        MediaInfoInput::Reader(self)
    }
}

impl Default for ParseOptions {
    fn default() -> Self {
        ParseOptions {
            library_file: None,
            library_search_dir: None,
            cover_data: false,
            parse_speed: 0.5,
            full: true,
            legacy_stream_display: false,
            mediainfo_options: None,
            output: None,
            buffer_size: Some(64 * 1024),
            encoding_errors: EncodingErrorMode::default(),
        }
    }
}

impl ParseOptions {
    /// Constructs a new [`ParseOptions`] with all defaults.
    ///
    /// Equivalent to `ParseOptions::default()`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets [`Self::library_file`] to an explicit shared library path,
    /// bypassing the auto-detection search.
    pub fn library_file<P: Into<PathBuf>>(mut self, path: P) -> Self {
        self.library_file = Some(path.into());
        self
    }

    /// Sets [`Self::library_search_dir`] to a directory the loader
    /// should look in before falling back to system paths.
    pub fn library_search_dir<P: Into<PathBuf>>(mut self, path: P) -> Self {
        self.library_search_dir = Some(path.into());
        self
    }

    /// Sets [`Self::cover_data`].
    ///
    /// When `true`, embedded cover art is exposed as a base64 string on
    /// the general track. Requires library version 18.3 or newer.
    pub fn cover_data(mut self, cover_data: bool) -> Self {
        self.cover_data = cover_data;
        self
    }

    /// Sets [`Self::parse_speed`].
    ///
    /// Values outside the typical `[0.0, 1.0]` range are forwarded to
    /// the library unchanged.
    pub fn parse_speed(mut self, speed: f32) -> Self {
        self.parse_speed = speed;
        self
    }

    /// Sets [`Self::full`].
    ///
    /// When `true`, every track is rendered with the complete attribute
    /// set rather than the abbreviated default.
    pub fn full(mut self, full: bool) -> Self {
        self.full = full;
        self
    }

    /// Sets [`Self::legacy_stream_display`].
    pub fn legacy_stream_display(mut self, legacy: bool) -> Self {
        self.legacy_stream_display = legacy;
        self
    }

    /// Sets [`Self::mediainfo_options`] to a map of extra option
    /// key/value pairs that the parse call will forward to the
    /// underlying library.
    ///
    /// The crate issues a `Reset` after the parse on library 19.9 and
    /// newer; on older builds it cannot, and a warning is logged
    /// through the `log` crate to make the limitation visible.
    pub fn mediainfo_options(mut self, options: HashMap<String, String>) -> Self {
        self.mediainfo_options = Some(options);
        self
    }

    /// Sets [`Self::output`].
    ///
    /// When set, parse calls return raw text instead of structured data.
    /// See the field doc for the list of accepted format strings.
    pub fn output<S: Into<String>>(mut self, output: S) -> Self {
        self.output = Some(output.into());
        self
    }

    /// Sets [`Self::buffer_size`].
    ///
    /// `None` reads the entire input in a single `read_to_end` call;
    /// `Some(n)` reads in `n`-byte chunks through the buffer protocol.
    pub fn buffer_size(mut self, size: Option<usize>) -> Self {
        self.buffer_size = size;
        self
    }

    /// Sets [`Self::encoding_errors`].
    ///
    /// Controls how invalid UTF-8 in the library's XML output is
    /// handled. See [`EncodingErrorMode`] for the available strategies.
    ///
    /// # Example
    ///
    /// ```
    /// use rsmediainfo::{ParseOptions, EncodingErrorMode};
    ///
    /// let strict_opts = ParseOptions::new()
    ///     .encoding_errors(EncodingErrorMode::Strict);
    ///
    /// let replace_opts = ParseOptions::new()
    ///     .encoding_errors(EncodingErrorMode::Replace);
    /// ```
    pub fn encoding_errors(mut self, mode: EncodingErrorMode) -> Self {
        self.encoding_errors = mode;
        self
    }
}

/// A parsed media file: an ordered list of [`Track`] values plus the
/// associated track-shortcut accessors.
///
/// Build a [`MediaInfo`] by calling one of the parse entrypoints
/// ([`MediaInfo::parse`], [`MediaInfo::parse_media_info`],
/// [`MediaInfo::parse_path`], [`MediaInfo::parse_from_reader`]) or by
/// passing a pre-generated XML string to [`MediaInfo::from_xml`]. The
/// resulting value is `Send + Sync + Clone` and can be moved across
/// threads freely.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MediaInfo {
    /// Tracks in source order, exposed through [`MediaInfo::tracks`].
    tracks: Vec<Track>,
}

/// Acquires the process-wide parse lock.
///
/// The underlying media library exposes a single global option store: every
/// `MediaInfo_Option` call (parse speed, output format, completion level,
/// custom options, the post-parse `Reset`, and so on) mutates state that is
/// shared by every handle in the process. Two threads that call into the
/// library with different options simultaneously can therefore observe each
/// other's settings, which produces non-deterministic results — or, on older
/// library builds without thread-safe option handling, outright crashes.
///
/// This guard serializes the entire parse pipeline so callers always see the
/// options they configured. The lock has no effect on `MediaInfo::from_xml`
/// (pure XML parsing does not touch the FFI) and is held only for the
/// duration of a single parse call. The cost is one extra mutex acquire per
/// parse, which is negligible compared to the work the library performs.
fn parse_lock() -> std::sync::MutexGuard<'static, ()> {
    static PARSE_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    PARSE_LOCK
        .get_or_init(|| Mutex::new(()))
        .lock()
        .expect("parse lock poisoned")
}

/// Already-loaded MediaInfo library plus cached version metadata.
///
/// Passed into the `*_internal_unlocked` parse functions so they do not
/// have to reload the shared library on every call. The lifetime borrows
/// from either a [`MediaInfoContext`] or a transient load in the free
/// function fallback path; the struct itself is a cheap stack value.
struct LoadedLibrary<'a> {
    lib: &'a Arc<MediaInfoLib>,
    version: LibVersion,
    version_number: &'a str,
}

/// Process-wide lazy default [`MediaInfoContext`].
///
/// `OnceLock` gives the single-initialization guarantee, the inner
/// `RwLock<Option<...>>` lets [`MediaInfo::reset_default_context`] swap
/// the stored value back to `None` so the next parse call rebuilds it.
/// Reads on the happy path take a shared `RwLock::read` guard, which is
/// effectively free on an uncontended lock.
static DEFAULT_CONTEXT: OnceLock<RwLock<Option<Arc<MediaInfoContext>>>> = OnceLock::new();

/// Returns the process-wide default [`MediaInfoContext`], constructing
/// it on first call.
///
/// A load failure is returned to the caller directly rather than
/// cached: subsequent calls will retry, which keeps the error path
/// transparent for users who fix their environment mid-process.
/// [`MediaInfo::reset_default_context`] can be used to force a retry
/// after a successful context has been installed.
fn default_context() -> Result<Arc<MediaInfoContext>> {
    let lock = DEFAULT_CONTEXT.get_or_init(|| RwLock::new(None));

    {
        let guard = lock.read().expect("default context lock poisoned");
        if let Some(ctx) = guard.as_ref() {
            return Ok(Arc::clone(ctx));
        }
    }

    let mut guard = lock.write().expect("default context lock poisoned");
    if let Some(ctx) = guard.as_ref() {
        return Ok(Arc::clone(ctx));
    }

    let ctx = Arc::new(MediaInfoContext::new()?);
    *guard = Some(Arc::clone(&ctx));
    Ok(ctx)
}

/// Drops the cached default [`MediaInfoContext`] so the next free
/// function parse call rebuilds it from scratch.
///
/// This is the only way to recover from a library-load failure that
/// was observed earlier in the process without restarting, or to pick
/// up a new library copy that was installed after the first parse.
pub fn reset_default_context() {
    if let Some(lock) = DEFAULT_CONTEXT.get() {
        let mut guard = lock.write().expect("default context lock poisoned");
        *guard = None;
    }
}

/// Loads the MediaInfo shared library and probes its version.
///
/// This is the one-time expensive work that used to run on every parse
/// call: resolving the candidate library paths, calling `dlopen` (or the
/// platform equivalent), binding every FFI symbol, creating a temporary
/// handle to query `Info_Version`, and parsing the resulting version
/// string into a [`LibVersion`]. The returned tuple lets the caller
/// build a [`LoadedLibrary`] once and reuse it across many parses.
///
/// The throwaway probe handle used to read `Info_Version` issues
/// `MediaInfo_New` and `MediaInfo_Delete` calls, which are not
/// thread-safe on every libmediainfo build. To avoid racing against an
/// in-flight parse on another thread, this function takes the global
/// parse lock for the duration of the probe. Callers **must not**
/// already hold the parse lock when calling this function, or the
/// second acquisition will deadlock.
fn load_library_full(
    library_file: Option<&Path>,
    library_search_dir: Option<&Path>,
) -> Result<(Arc<MediaInfoLib>, String, LibVersion)> {
    let search_dir = library_search_dir
        .map(PathBuf::from)
        .or_else(MediaInfo::default_library_search_dir);

    let paths = if let Some(path) = library_file {
        vec![path.to_path_buf()]
    } else {
        platform::get_library_paths(search_dir.as_deref())
    };

    let lib = Arc::new(MediaInfoLib::load_from_paths(&paths)?);

    // Serialize the probe with any concurrent parse. The probe handle
    // drops before the guard is released, so both `MediaInfo_New` and
    // `MediaInfo_Delete` happen inside the locked region.
    let _parse_guard = parse_lock();
    let probe_handle = MediaInfoHandle::new(lib.clone());
    let version_str = probe_handle.option("Info_Version", "");

    let version_number = MediaInfo::extract_version_number(&version_str)?;
    let version =
        LibVersion::parse(&version_number).ok_or(MediaInfoError::VersionDetectionFailed)?;

    Ok((lib, version_number, version))
}

/// Return value of the parse entrypoints that accept arbitrary
/// [`ParseOptions::output`] modes.
///
/// When the caller leaves `output` unset, parse calls return the
/// [`ParseOutput::MediaInfo`] variant carrying a structured value. When
/// the caller sets `output` (to `"JSON"`, `"text"`, a template string,
/// and so on), parse calls return [`ParseOutput::Output`] carrying the
/// raw text the underlying library produced.
///
/// Use [`MediaInfo::parse_media_info`] or
/// [`MediaInfo::parse_to_string`] when you know in advance which shape
/// you want and would rather not pattern-match on the result.
#[derive(Debug, Clone, PartialEq)]
pub enum ParseOutput {
    /// Structured parse result, returned when no `output` mode is set.
    MediaInfo(MediaInfo),
    /// Raw text payload, returned when an `output` mode is set.
    Output(String),
}

impl ParseOutput {
    /// Returns the inner [`MediaInfo`] by reference, or `None` when this
    /// is a raw-output result.
    pub fn as_media_info(&self) -> Option<&MediaInfo> {
        match self {
            ParseOutput::MediaInfo(mi) => Some(mi),
            ParseOutput::Output(_) => None,
        }
    }

    /// Returns the raw output text by reference, or `None` when this is
    /// a structured result.
    pub fn as_output(&self) -> Option<&str> {
        match self {
            ParseOutput::MediaInfo(_) => None,
            ParseOutput::Output(text) => Some(text.as_str()),
        }
    }

    /// Consumes the enum and yields the [`MediaInfo`] if present.
    pub fn into_media_info(self) -> Option<MediaInfo> {
        match self {
            ParseOutput::MediaInfo(mi) => Some(mi),
            ParseOutput::Output(_) => None,
        }
    }

    /// Consumes the enum and yields the raw output if present.
    pub fn into_output(self) -> Option<String> {
        match self {
            ParseOutput::MediaInfo(_) => None,
            ParseOutput::Output(text) => Some(text),
        }
    }
}

impl MediaInfo {
    /// Constructs a [`MediaInfo`] directly from an owned list of tracks.
    ///
    /// This is the lowest-level constructor and is mostly useful for
    /// tests and for callers that produce tracks through some path
    /// other than the parse entrypoints.
    pub fn new(tracks: Vec<Track>) -> Self {
        MediaInfo { tracks }
    }

    /// Constructs a [`MediaInfo`] from a pre-generated XML string using
    /// the default strict encoding mode.
    ///
    /// This entrypoint never touches the underlying media library, so it
    /// works in environments where the shared library is not available
    /// at runtime.
    ///
    /// # Errors
    ///
    /// Returns [`MediaInfoError::XmlParseError`] when the input is not
    /// well-formed XML or contains invalid UTF-8.
    ///
    /// # Example
    ///
    /// ```
    /// use rsmediainfo::MediaInfo;
    ///
    /// let xml = r#"<?xml version="1.0"?><File><track type="General"><Format>MKV</Format></track></File>"#;
    /// let mi = MediaInfo::from_xml(xml).unwrap();
    /// assert_eq!(mi.tracks().len(), 1);
    /// ```
    pub fn from_xml(xml: &str) -> Result<Self> {
        Self::from_xml_with_encoding(xml, EncodingErrorMode::Strict)
    }

    /// Constructs a [`MediaInfo`] from a pre-generated XML string with a
    /// caller-supplied [`EncodingErrorMode`].
    ///
    /// # Errors
    ///
    /// Returns [`MediaInfoError::XmlParseError`] when the input is not
    /// well-formed XML, or when invalid UTF-8 is encountered under
    /// [`EncodingErrorMode::Strict`].
    ///
    /// # Example
    ///
    /// ```
    /// use rsmediainfo::{MediaInfo, EncodingErrorMode};
    ///
    /// let xml = r#"<?xml version="1.0"?><File><track type="General"><Format>MKV</Format></track></File>"#;
    /// let mi = MediaInfo::from_xml_with_encoding(xml, EncodingErrorMode::Strict).unwrap();
    /// assert_eq!(mi.tracks().len(), 1);
    /// ```
    pub fn from_xml_with_encoding(xml: &str, encoding_mode: EncodingErrorMode) -> Result<Self> {
        let tracks = xml::parse_xml_with_encoding(xml, encoding_mode)?;
        Ok(MediaInfo { tracks })
    }

    /// Constructs a [`MediaInfo`] from a raw XML byte buffer with a
    /// caller-supplied [`EncodingErrorMode`].
    ///
    /// Use this when the source bytes may not be valid UTF-8 and the
    /// caller wants to control how invalid sequences are handled.
    ///
    /// # Errors
    ///
    /// Returns [`MediaInfoError::XmlParseError`] for malformed XML or
    /// for invalid UTF-8 under [`EncodingErrorMode::Strict`].
    pub fn from_xml_bytes_with_encoding(
        xml_bytes: &[u8],
        encoding_mode: EncodingErrorMode,
    ) -> Result<Self> {
        let tracks = xml::parse_xml_bytes_with_encoding(xml_bytes, encoding_mode)?;
        Ok(MediaInfo { tracks })
    }

    /// Constructs a [`MediaInfo`] from a raw XML byte buffer using the
    /// default strict encoding mode.
    ///
    /// # Errors
    ///
    /// Returns [`MediaInfoError::XmlParseError`] for malformed XML or
    /// for invalid UTF-8.
    pub fn from_xml_bytes(xml_bytes: &[u8]) -> Result<Self> {
        Self::from_xml_bytes_with_encoding(xml_bytes, EncodingErrorMode::Strict)
    }

    /// Returns `true` when the underlying media library can be loaded
    /// and a test handle can be created against it.
    ///
    /// This is the right way to probe whether parsing is possible at all
    /// before attempting a parse — it never panics and never returns an
    /// error, just `false` when the library is missing or unusable.
    ///
    /// When `library_file` is `Some`, only that path is tried; when it
    /// is `None`, the standard auto-detection search runs (see
    /// [`ParseOptions::library_search_dir`] for the resolution order).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsmediainfo::MediaInfo;
    /// use std::path::Path;
    ///
    /// if MediaInfo::can_parse(None) {
    ///     println!("library is available");
    /// }
    ///
    /// if MediaInfo::can_parse(Some(Path::new("/usr/lib/libmediainfo.so"))) {
    ///     println!("custom library is available");
    /// }
    /// ```
    pub fn can_parse(library_file: Option<&Path>) -> bool {
        load_library_full(library_file, None).is_ok()
    }

    /// Drops the cached process-wide default [`MediaInfoContext`].
    ///
    /// Free parse functions on [`MediaInfo`] route through a lazily
    /// initialized default context that stays alive for the process
    /// lifetime after the first successful parse. Calling this function
    /// releases the cached context so the next parse call rebuilds it
    /// from scratch. Useful when:
    ///
    /// - The shared library was missing at the first call but has
    ///   since been installed.
    /// - The process intentionally installed a new library copy and
    ///   wants new parses to pick it up.
    /// - A test wants to force a clean default-context state between
    ///   runs.
    ///
    /// This is a rare-path escape hatch. Most programs never need it.
    pub fn reset_default_context() {
        reset_default_context();
    }

    /// Loads the underlying library and returns its raw version string
    /// alongside the parsed [`LibVersion`].
    ///
    /// The raw string is whatever the library reports for the
    /// `Info_Version` option (typically `"20.09"`-shaped). The parsed
    /// [`LibVersion`] is the same value as a struct so callers can use
    /// the feature-detection helpers without re-parsing it.
    ///
    /// # Errors
    ///
    /// Returns [`MediaInfoError::LibraryNotFound`] when the library
    /// cannot be loaded, or [`MediaInfoError::VersionDetectionFailed`]
    /// when the loaded library reports a version string the crate
    /// cannot interpret.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rsmediainfo::MediaInfo;
    ///
    /// if MediaInfo::can_parse(None) {
    ///     let (version_str, version) = MediaInfo::library_version(None).unwrap();
    ///     println!("library version: {version_str}");
    ///     if version.supports_cover_data() {
    ///         println!("cover data extraction is available");
    ///     }
    /// }
    /// ```
    pub fn library_version(library_file: Option<&Path>) -> Result<(String, LibVersion)> {
        let (_lib, version_number, version) = load_library_full(library_file, None)?;
        Ok((version_number, version))
    }

    /// Parses any supported source (path, URL, or reader) using the
    /// default [`ParseOptions`].
    ///
    /// This is the primary entrypoint for the structured parse pipeline.
    /// The result is always [`ParseOutput::MediaInfo`] because the
    /// default options leave [`ParseOptions::output`] unset.
    ///
    /// # Errors
    ///
    /// Returns [`MediaInfoError::LibraryNotFound`] if the underlying
    /// library cannot be loaded, [`MediaInfoError::FileNotFound`] for a
    /// missing path, [`MediaInfoError::ParseError`] for an unparseable
    /// file or URL, [`MediaInfoError::IoError`] for reader I/O failures,
    /// and [`MediaInfoError::XmlParseError`] when the library produces
    /// XML output the crate cannot interpret.
    pub fn parse<'a, S>(source: S) -> Result<ParseOutput>
    where
        S: MediaInfoSource<'a>,
    {
        Self::parse_with_options(source, &ParseOptions::default())
    }

    /// Path-typed alias for [`MediaInfo::parse`] that accepts any
    /// `AsRef<Path>` value.
    ///
    /// Useful when the caller already has a `String`, `PathBuf`, or
    /// `&Path` and would rather not go through the [`MediaInfoSource`]
    /// generic dispatch.
    pub fn parse_path<P: AsRef<Path>>(path: P) -> Result<ParseOutput> {
        Self::parse(path.as_ref())
    }

    /// Parses any supported source and returns the result as a
    /// structured [`MediaInfo`] directly.
    ///
    /// This is the right entrypoint when the caller knows it does not
    /// want raw text output. Equivalent to calling [`MediaInfo::parse`]
    /// and pattern-matching for the [`ParseOutput::MediaInfo`] variant.
    ///
    /// # Errors
    ///
    /// Same as [`MediaInfo::parse`].
    pub fn parse_media_info<'a, S>(source: S) -> Result<Self>
    where
        S: MediaInfoSource<'a>,
    {
        Self::parse_media_info_with_options(source, &ParseOptions::default())
    }

    /// Path-typed alias for [`MediaInfo::parse_media_info`] that accepts
    /// any `AsRef<Path>` value.
    pub fn parse_media_info_path<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::parse_media_info(path.as_ref())
    }

    /// Parses any supported source with caller-supplied [`ParseOptions`]
    /// and returns the result as a structured [`MediaInfo`].
    ///
    /// # Errors
    ///
    /// In addition to the errors documented on [`MediaInfo::parse`],
    /// returns [`MediaInfoError::InvalidInput`] when `options.output`
    /// is set — that combination is rejected because the structured
    /// return type cannot represent raw text output.
    pub fn parse_media_info_with_options<'a, S>(source: S, options: &ParseOptions) -> Result<Self>
    where
        S: MediaInfoSource<'a>,
    {
        if options.output.is_some() {
            return Err(MediaInfoError::invalid_input(
                "output is only supported by parse or parse_with_options",
            ));
        }

        match Self::parse_with_options(source, options)? {
            ParseOutput::MediaInfo(mi) => Ok(mi),
            ParseOutput::Output(_) => Err(MediaInfoError::invalid_input(
                "output is only supported by parse or parse_with_options",
            )),
        }
    }

    /// Path-typed alias for [`MediaInfo::parse_media_info_with_options`].
    pub fn parse_media_info_path_with_options<P: AsRef<Path>>(
        path: P,
        options: &ParseOptions,
    ) -> Result<Self> {
        Self::parse_media_info_with_options(path.as_ref(), options)
    }

    /// Parses any supported source with caller-supplied [`ParseOptions`].
    ///
    /// The return type is [`ParseOutput`] because `options.output` may
    /// request raw text output, in which case the returned variant is
    /// [`ParseOutput::Output`]. When `options.output` is unset, the
    /// returned variant is always [`ParseOutput::MediaInfo`].
    ///
    /// # Errors
    ///
    /// Same as [`MediaInfo::parse`].
    pub fn parse_with_options<'a, S>(source: S, options: &ParseOptions) -> Result<ParseOutput>
    where
        S: MediaInfoSource<'a>,
    {
        let input = source.into_input();
        Self::parse_input_with_options(input, options)
    }

    /// Path-typed alias for [`MediaInfo::parse_with_options`].
    pub fn parse_path_with_options<P: AsRef<Path>>(
        path: P,
        options: &ParseOptions,
    ) -> Result<ParseOutput> {
        Self::parse_with_options(path.as_ref(), options)
    }

    /// Alias for [`MediaInfo::parse`]. Kept for symmetry with the
    /// `*_with_options` family.
    pub fn parse_source<'a, S>(source: S) -> Result<ParseOutput>
    where
        S: MediaInfoSource<'a>,
    {
        Self::parse(source)
    }

    /// Alias for [`MediaInfo::parse_with_options`]. Kept for symmetry.
    pub fn parse_source_with_options<'a, S>(
        source: S,
        options: &ParseOptions,
    ) -> Result<ParseOutput>
    where
        S: MediaInfoSource<'a>,
    {
        Self::parse_with_options(source, options)
    }

    /// Parses a media file from disk and returns the raw text output the
    /// underlying library produces in the requested format.
    ///
    /// `output_format` is forwarded as the library's `Inform` option and
    /// controls the shape of the returned string. Common values:
    ///
    /// - `""` — default human-readable text report
    /// - `"text"` — alias for the empty string
    /// - `"JSON"` — JSON document
    /// - `"XML"` / `"OLDXML"` — XML document
    /// - `%`-delimited templates such as `"General;%FileSize%"`
    ///
    /// # Errors
    ///
    /// Same as [`MediaInfo::parse`].
    pub fn parse_to_string<P: AsRef<Path>>(filename: P, output_format: &str) -> Result<String> {
        let options = ParseOptions::new().output(output_format.to_string());
        Self::parse_to_string_internal(filename, &options)
    }

    /// Parses a media file from disk with caller-supplied [`ParseOptions`]
    /// and returns the raw text output the library produces.
    ///
    /// Use this overload when you need to combine an explicit output
    /// format with other option overrides (parse speed, full mode, custom
    /// `mediainfo_options`, etc.). The `output_format` from the options
    /// value is the one that takes effect.
    ///
    /// # Errors
    ///
    /// Same as [`MediaInfo::parse`].
    pub fn parse_to_string_with_options<P: AsRef<Path>>(
        filename: P,
        options: &ParseOptions,
    ) -> Result<String> {
        Self::parse_to_string_internal(filename, options)
    }

    fn parse_to_string_internal<P: AsRef<Path>>(
        filename: P,
        options: &ParseOptions,
    ) -> Result<String> {
        // The library must be resolved BEFORE we acquire the parse
        // lock: `load_library_full` and `default_context` both take
        // the parse lock internally to serialize their probe handles,
        // so entering them while already holding it would deadlock.
        if options.library_file.is_some() || options.library_search_dir.is_some() {
            // Honor the v0.1.0 contract: when the caller pins the
            // library path or search directory, load a fresh library
            // for this call instead of reusing the cached default
            // context.
            let (lib, version_number, version) = load_library_full(
                options.library_file.as_deref(),
                options.library_search_dir.as_deref(),
            )?;
            let _parse_guard = parse_lock();
            let loaded = LoadedLibrary {
                lib: &lib,
                version,
                version_number: &version_number,
            };
            return Self::parse_to_string_internal_unlocked(&loaded, filename, options);
        }

        let ctx = default_context()?;
        let _parse_guard = parse_lock();
        let loaded = ctx.loaded();
        Self::parse_to_string_internal_unlocked(&loaded, filename, options)
    }

    fn parse_to_string_internal_unlocked<P: AsRef<Path>>(
        loaded: &LoadedLibrary<'_>,
        filename: P,
        options: &ParseOptions,
    ) -> Result<String> {
        let path = filename.as_ref();
        let path_str = path.to_string_lossy().to_string();

        // Strings that look like URLs are routed straight to the URL
        // entrypoint rather than being interpreted as filesystem paths.
        if path_str.contains("://") {
            return Self::parse_to_string_from_url_unlocked(loaded, &path_str, options);
        }

        let handle = MediaInfoHandle::new(loaded.lib.clone());

        Self::configure_parse_options(&handle, &loaded.version, loaded.version_number, options);
        Self::configure_output_options(&handle, &loaded.version, options);

        // Probe the filesystem first so missing-file errors surface as
        // FileNotFound rather than the more generic library parse error.
        if !path.exists() {
            return Err(MediaInfoError::file_not_found(path));
        }

        if handle.open(&path_str) == 0 {
            return Err(MediaInfoError::parse_error(&path_str));
        }

        let output = handle.inform();

        // Reset the global option store on library builds that support
        // it, so the next parse call starts from a clean slate.
        if options.mediainfo_options.is_some() && loaded.version.supports_reset() {
            handle.option("Reset", "");
        }

        Ok(output)
    }

    fn parse_to_string_from_url(url: &str, options: &ParseOptions) -> Result<String> {
        // Resolve the library before taking the parse lock so the
        // inner probe-handle serialization in `load_library_full` /
        // `default_context` does not re-enter the lock.
        if options.library_file.is_some() || options.library_search_dir.is_some() {
            let (lib, version_number, version) = load_library_full(
                options.library_file.as_deref(),
                options.library_search_dir.as_deref(),
            )?;
            let _parse_guard = parse_lock();
            let loaded = LoadedLibrary {
                lib: &lib,
                version,
                version_number: &version_number,
            };
            return Self::parse_to_string_from_url_unlocked(&loaded, url, options);
        }

        let ctx = default_context()?;
        let _parse_guard = parse_lock();
        let loaded = ctx.loaded();
        Self::parse_to_string_from_url_unlocked(&loaded, url, options)
    }

    fn parse_to_string_from_url_unlocked(
        loaded: &LoadedLibrary<'_>,
        url: &str,
        options: &ParseOptions,
    ) -> Result<String> {
        let handle = MediaInfoHandle::new(loaded.lib.clone());

        Self::configure_parse_options(&handle, &loaded.version, loaded.version_number, options);
        Self::configure_output_options(&handle, &loaded.version, options);

        if handle.open(url) == 0 {
            if options.mediainfo_options.is_some() && loaded.version.supports_reset() {
                handle.option("Reset", "");
            }

            // The native opener could not handle the URL. For plain HTTP we
            // try a built-in fetch fallback so the caller still gets results
            // when the underlying library was built without CURL support.
            if url.starts_with("http://") {
                debug!(
                    "native URL opener could not handle {}; falling back to built-in HTTP fetch",
                    url
                );
                return Self::parse_url_via_http(loaded, url, options);
            }

            return Err(MediaInfoError::parse_error(url));
        }

        let output = handle.inform();

        if options.mediainfo_options.is_some() && loaded.version.supports_reset() {
            handle.option("Reset", "");
        }

        Ok(output)
    }

    /// Parses any `Read + Seek` source through the buffer-protocol path.
    ///
    /// The reader is consumed in `buffer_size`-sized chunks (or in a
    /// single `read_to_end` call when `buffer_size` is `None`). Readers
    /// must produce raw bytes — text-mode readers are not supported by
    /// the type system and would not produce the right results anyway.
    ///
    /// # Errors
    ///
    /// Same as [`MediaInfo::parse`].
    pub fn parse_from_reader<R: ReadSeek>(reader: &mut R) -> Result<ParseOutput> {
        Self::parse_from_reader_with_options(reader, &ParseOptions::default())
    }

    /// Parses any `Read + Seek` source with caller-supplied
    /// [`ParseOptions`].
    ///
    /// When `options.output` is set, this returns
    /// [`ParseOutput::Output`] carrying the raw text payload; otherwise
    /// it returns [`ParseOutput::MediaInfo`] carrying a structured
    /// value built from the library's XML output.
    ///
    /// # Errors
    ///
    /// Same as [`MediaInfo::parse`].
    pub fn parse_from_reader_with_options<R: ReadSeek>(
        reader: &mut R,
        options: &ParseOptions,
    ) -> Result<ParseOutput> {
        if options.output.is_some() {
            let output = Self::parse_reader_to_string_internal(reader, options)?;
            return Ok(ParseOutput::Output(output));
        }

        let output = Self::parse_reader_to_string_internal(reader, options)?;
        let mi =
            MediaInfo::from_xml_bytes_with_encoding(output.as_bytes(), options.encoding_errors)?;
        Ok(ParseOutput::MediaInfo(mi))
    }

    /// Parses a [`MediaInfoInput`] using the default [`ParseOptions`].
    ///
    /// Use this when you have a pre-built [`MediaInfoInput`] (for
    /// example, after threading one through your own dispatch logic).
    /// Most callers should prefer the more ergonomic [`MediaInfo::parse`]
    /// or one of its specialized helpers.
    pub fn parse_input(input: MediaInfoInput<'_>) -> Result<ParseOutput> {
        Self::parse_input_with_options(input, &ParseOptions::default())
    }

    /// Parses a [`MediaInfoInput`] with caller-supplied [`ParseOptions`].
    ///
    /// Behaves like [`MediaInfo::parse_with_options`] but takes the
    /// already-converted [`MediaInfoInput`] enum.
    pub fn parse_input_with_options(
        input: MediaInfoInput<'_>,
        options: &ParseOptions,
    ) -> Result<ParseOutput> {
        if options.output.is_some() {
            let output = Self::parse_input_to_string_with_options(input, options)?;
            return Ok(ParseOutput::Output(output));
        }

        let output = Self::parse_input_to_string_with_options(input, options)?;
        let mi =
            MediaInfo::from_xml_bytes_with_encoding(output.as_bytes(), options.encoding_errors)?;
        Ok(ParseOutput::MediaInfo(mi))
    }

    /// Parses a [`MediaInfoInput`] in raw-output mode.
    ///
    /// `output_format` is forwarded as the library's `Inform` option;
    /// see [`MediaInfo::parse_to_string`] for the list of common values.
    pub fn parse_input_to_string(input: MediaInfoInput<'_>, output_format: &str) -> Result<String> {
        let options = ParseOptions::new().output(output_format.to_string());
        Self::parse_input_to_string_with_options(input, &options)
    }

    /// Parses a [`MediaInfoInput`] in raw-output mode with
    /// caller-supplied [`ParseOptions`].
    pub fn parse_input_to_string_with_options(
        input: MediaInfoInput<'_>,
        options: &ParseOptions,
    ) -> Result<String> {
        match input {
            MediaInfoInput::Path(path) => Self::parse_to_string_with_options(path, options),
            MediaInfoInput::Url(url) => Self::parse_to_string_from_url(url, options),
            MediaInfoInput::Reader(reader) => {
                Self::parse_reader_to_string_with_options(reader, options)
            }
        }
    }

    /// Parses any `Read + Seek` source and returns the raw text payload
    /// the library produces in the requested format.
    ///
    /// `output_format` is forwarded as the library's `Inform` option.
    /// See [`MediaInfo::parse_to_string`] for the list of common values.
    pub fn parse_reader_to_string<R: ReadSeek + ?Sized>(
        reader: &mut R,
        output_format: &str,
    ) -> Result<String> {
        let options = ParseOptions::new().output(output_format.to_string());
        Self::parse_reader_to_string_internal(reader, &options)
    }

    /// Parses any `Read + Seek` source with caller-supplied
    /// [`ParseOptions`] and returns the raw text payload.
    pub fn parse_reader_to_string_with_options<R: ReadSeek + ?Sized>(
        reader: &mut R,
        options: &ParseOptions,
    ) -> Result<String> {
        Self::parse_reader_to_string_internal(reader, options)
    }

    fn parse_reader_to_string_internal<R: ReadSeek + ?Sized>(
        reader: &mut R,
        options: &ParseOptions,
    ) -> Result<String> {
        // Resolve the library before taking the parse lock so the
        // inner probe-handle serialization in `load_library_full` /
        // `default_context` does not re-enter the lock.
        if options.library_file.is_some() || options.library_search_dir.is_some() {
            let (lib, version_number, version) = load_library_full(
                options.library_file.as_deref(),
                options.library_search_dir.as_deref(),
            )?;
            let _parse_guard = parse_lock();
            let loaded = LoadedLibrary {
                lib: &lib,
                version,
                version_number: &version_number,
            };
            return Self::parse_reader_to_string_internal_unlocked(&loaded, reader, options);
        }

        let ctx = default_context()?;
        let _parse_guard = parse_lock();
        let loaded = ctx.loaded();
        Self::parse_reader_to_string_internal_unlocked(&loaded, reader, options)
    }

    fn parse_reader_to_string_internal_unlocked<R: ReadSeek + ?Sized>(
        loaded: &LoadedLibrary<'_>,
        reader: &mut R,
        options: &ParseOptions,
    ) -> Result<String> {
        // Discover the total stream length up front so the buffer
        // protocol can give the library a meaningful file size hint, then
        // rewind to the start before the read loop kicks off.
        let file_size = reader.seek(SeekFrom::End(0))?;
        reader.seek(SeekFrom::Start(0))?;

        let handle = MediaInfoHandle::new(loaded.lib.clone());

        Self::configure_parse_options(&handle, &loaded.version, loaded.version_number, options);
        Self::configure_output_options(&handle, &loaded.version, options);

        handle.open_buffer_init(file_size, 0);

        if let Some(buffer_size) = options.buffer_size {
            let mut buffer = vec![0u8; buffer_size];

            loop {
                let bytes_read = reader.read(&mut buffer)?;
                if bytes_read == 0 {
                    break;
                }

                // Bit 3 (0x08) of the buffer-continue result is the
                // library's "I have everything I need" signal. When it
                // is set we stop reading even though there may be more
                // bytes left in the stream.
                let result = handle.open_buffer_continue(&buffer[..bytes_read]);
                if result & 0x08 != 0 {
                    break;
                }

                // The library may also ask us to seek to a specific
                // offset before delivering the next chunk; honor the
                // request and re-initialize the buffer protocol so the
                // file-position bookkeeping stays consistent.
                let seek_pos = handle.open_buffer_continue_goto_get();
                if seek_pos != u64::MAX {
                    reader.seek(SeekFrom::Start(seek_pos))?;
                    let current_pos = reader.stream_position()?;
                    handle.open_buffer_init(file_size, current_pos);
                }
            }
        } else {
            // Single-shot path: feed the entire stream to the library
            // in one call. The same finished/seek bits are still
            // honored so the loop terminates correctly even when the
            // library wants to seek around.
            let mut buffer = Vec::new();

            loop {
                buffer.clear();
                reader.read_to_end(&mut buffer)?;
                if buffer.is_empty() {
                    break;
                }

                let result = handle.open_buffer_continue(&buffer);
                if result & 0x08 != 0 {
                    break;
                }

                let seek_pos = handle.open_buffer_continue_goto_get();
                if seek_pos != u64::MAX {
                    reader.seek(SeekFrom::Start(seek_pos))?;
                    let current_pos = reader.stream_position()?;
                    handle.open_buffer_init(file_size, current_pos);
                } else {
                    break;
                }
            }
        }

        handle.open_buffer_finalize();

        let output = handle.inform();

        // Reset the global option store on library builds that support
        // it, so the next parse call starts from a clean slate.
        if options.mediainfo_options.is_some() && loaded.version.supports_reset() {
            handle.option("Reset", "");
        }

        Ok(output)
    }

    fn parse_url_via_http(
        loaded: &LoadedLibrary<'_>,
        url: &str,
        options: &ParseOptions,
    ) -> Result<String> {
        let bytes = Self::fetch_http_bytes(url).map_err(|_| MediaInfoError::parse_error(url))?;
        let mut cursor = std::io::Cursor::new(bytes);
        Self::parse_reader_to_string_internal_unlocked(loaded, &mut cursor, options)
    }

    fn fetch_http_bytes(url: &str) -> Result<Vec<u8>> {
        let (host, host_header, path, port) =
            Self::split_http_url(url).ok_or_else(|| MediaInfoError::parse_error(url))?;

        let mut stream = TcpStream::connect((host.as_str(), port))?;
        let request = format!(
            "GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n",
            path, host_header
        );
        stream.write_all(request.as_bytes())?;

        let mut response = Vec::new();
        stream.read_to_end(&mut response)?;

        let header_end = Self::find_http_header_end(&response)
            .ok_or_else(|| MediaInfoError::parse_error(url))?;
        let status_line = response
            .get(..header_end)
            .and_then(|header| header.split(|b| *b == b'\n').next())
            .and_then(|line| line.strip_suffix(b"\r"))
            .ok_or_else(|| MediaInfoError::parse_error(url))?;
        let status_str =
            std::str::from_utf8(status_line).map_err(|_| MediaInfoError::parse_error(url))?;
        let status_code = status_str
            .split_whitespace()
            .nth(1)
            .and_then(|code| code.parse::<u16>().ok())
            .ok_or_else(|| MediaInfoError::parse_error(url))?;
        if status_code != 200 && status_code != 206 {
            return Err(MediaInfoError::parse_error(url));
        }

        Ok(response[(header_end + 4)..].to_vec())
    }

    fn split_http_url(url: &str) -> Option<(String, String, String, u16)> {
        let without_scheme = url.strip_prefix("http://")?;
        let mut parts = without_scheme.splitn(2, '/');
        let host_port = parts.next().unwrap_or("");
        if host_port.is_empty() {
            return None;
        }

        let path = format!("/{}", parts.next().unwrap_or(""));
        let mut host = host_port;
        let mut port = 80u16;
        if let Some((left, right)) = host_port.rsplit_once(':')
            && right.chars().all(|c| c.is_ascii_digit())
        {
            host = left;
            port = right.parse().ok()?;
        }

        let host_header = if host_port.contains(':') {
            host_port
        } else {
            host
        };

        Some((host.to_string(), host_header.to_string(), path, port))
    }

    fn find_http_header_end(response: &[u8]) -> Option<usize> {
        response.windows(4).position(|window| window == b"\r\n\r\n")
    }

    /// Returns every parsed track in source order.
    pub fn tracks(&self) -> &[Track] {
        &self.tracks
    }

    /// Returns a mutable reference to the track list, so callers can
    /// reorder, filter, or otherwise mutate the parsed tracks in place.
    pub fn tracks_mut(&mut self) -> &mut Vec<Track> {
        &mut self.tracks
    }

    /// Consumes the [`MediaInfo`] and yields its owned track list.
    pub fn into_tracks(self) -> Vec<Track> {
        self.tracks
    }

    /// Returns the parsed tracks whose `track_type` is exactly `"General"`.
    ///
    /// Track type matching is byte-exact and case-sensitive: a track with
    /// type `"GENERAL"` would not be returned here.
    pub fn general_tracks(&self) -> Vec<&Track> {
        self.tracks
            .iter()
            .filter(|t| t.track_type() == "General")
            .collect()
    }

    /// Returns the parsed tracks whose `track_type` is exactly `"Video"`.
    pub fn video_tracks(&self) -> Vec<&Track> {
        self.tracks
            .iter()
            .filter(|t| t.track_type() == "Video")
            .collect()
    }

    /// Returns the parsed tracks whose `track_type` is exactly `"Audio"`.
    pub fn audio_tracks(&self) -> Vec<&Track> {
        self.tracks
            .iter()
            .filter(|t| t.track_type() == "Audio")
            .collect()
    }

    /// Returns the parsed tracks whose `track_type` is exactly `"Text"`.
    pub fn text_tracks(&self) -> Vec<&Track> {
        self.tracks
            .iter()
            .filter(|t| t.track_type() == "Text")
            .collect()
    }

    /// Returns the parsed tracks whose `track_type` is exactly `"Other"`.
    pub fn other_tracks(&self) -> Vec<&Track> {
        self.tracks
            .iter()
            .filter(|t| t.track_type() == "Other")
            .collect()
    }

    /// Returns the parsed tracks whose `track_type` is exactly `"Image"`.
    pub fn image_tracks(&self) -> Vec<&Track> {
        self.tracks
            .iter()
            .filter(|t| t.track_type() == "Image")
            .collect()
    }

    /// Returns the parsed tracks whose `track_type` is exactly `"Menu"`.
    pub fn menu_tracks(&self) -> Vec<&Track> {
        self.tracks
            .iter()
            .filter(|t| t.track_type() == "Menu")
            .collect()
    }

    /// Renders the [`MediaInfo`] as a flat JSON object.
    ///
    /// The returned [`serde_json::Map`] contains a single `tracks` key
    /// whose value is an ordered array of per-track dictionaries built
    /// by [`Track::to_data`]. Insertion order is preserved at both
    /// levels — the array follows source order, and each track map
    /// follows attribute encounter order.
    pub fn to_data(&self) -> serde_json::Map<String, serde_json::Value> {
        let tracks_data: Vec<serde_json::Value> = self
            .tracks
            .iter()
            .map(|t| serde_json::Value::Object(t.to_data()))
            .collect();

        let mut data = serde_json::Map::new();
        data.insert("tracks".to_string(), serde_json::Value::Array(tracks_data));
        data
    }

    /// Serializes [`MediaInfo::to_data`] to a JSON string.
    ///
    /// Keys are emitted in the same order they appear in the underlying
    /// maps, which is the order of attributes encountered during parse.
    ///
    /// # Errors
    ///
    /// Returns [`MediaInfoError::InvalidInput`] when `serde_json` cannot
    /// serialize the value (in practice this never happens because the
    /// values produced by [`MediaInfo::to_data`] are always
    /// JSON-representable).
    pub fn to_json(&self) -> Result<String> {
        serde_json::to_string(&self.to_data())
            .map_err(|e| MediaInfoError::invalid_input(e.to_string()))
    }

    fn default_library_search_dir() -> Option<PathBuf> {
        // Highest precedence: an explicit runtime override.
        if let Ok(dir) = std::env::var("RS_MEDIAINFO_LIBRARY_DIR")
            && !dir.trim().is_empty()
        {
            return Some(PathBuf::from(dir));
        }

        // Next: the directory the build script staged the bundled
        // library into, recorded at compile time.
        if let Some(dir) = option_env!("RS_MEDIAINFO_BUNDLED_DIR") {
            return Some(PathBuf::from(dir));
        }

        // Then: the directory containing the running executable, which
        // is the conventional place to ship a bundled library next to
        // the binary.
        if let Ok(exe) = std::env::current_exe()
            && let Some(parent) = exe.parent()
        {
            return Some(parent.to_path_buf());
        }

        // Last resort: the current working directory.
        std::env::current_dir().ok()
    }

    fn extract_version_number(version_str: &str) -> Result<String> {
        // The library reports the version as a leading prefix followed
        // by free-form text, e.g. `"MediaInfoLib - v20.09"` or
        // `"MediaInfoLib - v20.09 (build 123)"`. Both lowercase and
        // historical capital-V variants are accepted.
        let version_part = version_str
            .strip_prefix("MediaInfoLib - v")
            .or_else(|| version_str.strip_prefix("MediaInfoLib - V"))
            .ok_or(MediaInfoError::VersionDetectionFailed)?;

        let version_num = version_part
            .split_whitespace()
            .next()
            .ok_or(MediaInfoError::VersionDetectionFailed)?;

        Ok(version_num.to_string())
    }

    fn configure_parse_options(
        handle: &MediaInfoHandle,
        version: &LibVersion,
        version_number: &str,
        options: &ParseOptions,
    ) {
        // The Cover_Data option only exists on library 18.3 and newer;
        // older builds always emit cover data unconditionally.
        if version.supports_cover_data() {
            handle.option("Cover_Data", if options.cover_data { "base64" } else { "" });
        }

        handle.option("ParseSpeed", &options.parse_speed.to_string());

        if let Some(ref custom_options) = options.mediainfo_options {
            // On builds without a working Reset option there is no way
            // to undo whatever the caller's custom options changed, so
            // we surface a warning through the logger to make the
            // limitation visible to applications that watch logs.
            if !version.supports_reset() {
                let message = format!(
                    "This version of MediaInfo (v{}) does not support resetting all options to their default values, passing it custom options is not recommended and may result in unpredictable behavior, see https://github.com/MediaArea/MediaInfoLib/issues/1128",
                    version_number
                );
                Self::emit_warning(&message);
            }

            for (key, value) in custom_options {
                handle.option(key, value);
            }
        }
    }

    fn configure_output_options(
        handle: &MediaInfoHandle,
        version: &LibVersion,
        options: &ParseOptions,
    ) {
        handle.option("CharSet", "UTF-8");

        // The library has both an `Output` option and an `Inform`
        // option, and the two interact in surprising ways. Clearing
        // `Output` first guarantees that whatever we set on `Inform`
        // is the value that takes effect.
        handle.option("Output", "");

        let inform_value = if let Some(output) = options.output.as_deref() {
            Self::normalize_output_option(output)
        } else {
            version.xml_option_name()
        };
        handle.option("Inform", inform_value);

        handle.option("Complete", if options.full { "1" } else { "" });

        handle.option(
            "LegacyStreamDisplay",
            if options.legacy_stream_display {
                "1"
            } else {
                ""
            },
        );
    }

    fn normalize_output_option(value: &str) -> &str {
        // The friendly `"text"` alias maps to the empty string, which
        // is the value the library actually expects for plain text
        // output.
        if value.eq_ignore_ascii_case("text") {
            ""
        } else {
            value
        }
    }

    fn emit_warning(message: &str) {
        warn!("{}", message);
    }
}

/// Reusable parse context that loads the MediaInfo shared library once
/// and reuses it across many parse calls.
///
/// Constructing a [`MediaInfoContext`] pays the one-time library load
/// cost up front: candidate path resolution, `dlopen` (or the platform
/// equivalent), FFI symbol binding, and version probing. Every parse
/// call made through the context skips that work and only creates a
/// fresh per-call handle, which is dramatically cheaper for batch
/// workloads such as scanning a directory of media files.
///
/// A context is `Send + Sync` and `Clone` (the clone is cheap — the
/// underlying library is shared via [`Arc`]). One context per process is
/// the expected usage pattern; wrap it in an [`Arc`] and share it across
/// a worker pool. Parse calls are still serialized internally by the
/// global parse lock so the underlying library's process-wide option
/// store stays deterministic even under heavy concurrency.
///
/// # Example
///
/// ```no_run
/// use rsmediainfo::MediaInfoContext;
///
/// let ctx = MediaInfoContext::new()?;
/// for path in &["a.mp4", "b.mkv", "c.mov"] {
///     let info = ctx.parse_media_info_path(path)?;
///     println!("{}: {} tracks", path, info.tracks().len());
/// }
/// # Ok::<(), rsmediainfo::MediaInfoError>(())
/// ```
#[derive(Clone)]
pub struct MediaInfoContext {
    lib: Arc<MediaInfoLib>,
    version_number: String,
    version: LibVersion,
    library_file: Option<PathBuf>,
}

impl MediaInfoContext {
    /// Constructs a new context using the default library search order.
    ///
    /// The resolver walks the following locations in order: the
    /// `RS_MEDIAINFO_LIBRARY_DIR` environment variable, the
    /// compile-time `RS_MEDIAINFO_BUNDLED_DIR` directory, the directory
    /// containing the running executable, and finally the current
    /// working directory. The first location that yields a loadable
    /// library is used.
    ///
    /// # Errors
    ///
    /// Returns [`MediaInfoError::LibraryNotFound`] when no candidate
    /// path can be opened, or [`MediaInfoError::VersionDetectionFailed`]
    /// when the loaded library reports a version string the crate
    /// cannot interpret.
    pub fn new() -> Result<Self> {
        Self::build(None, None)
    }

    /// Constructs a new context that loads the library from an explicit
    /// path, bypassing the default search order entirely.
    ///
    /// # Errors
    ///
    /// Same as [`MediaInfoContext::new`].
    pub fn with_library_file<P: Into<PathBuf>>(path: P) -> Result<Self> {
        let path = path.into();
        Self::build(Some(path.as_path()), None)
    }

    /// Constructs a new context that searches a caller-supplied
    /// directory for a bundled copy of the library before falling back
    /// to the platform library search path.
    ///
    /// # Errors
    ///
    /// Same as [`MediaInfoContext::new`].
    pub fn with_library_search_dir<P: Into<PathBuf>>(dir: P) -> Result<Self> {
        let dir = dir.into();
        Self::build(None, Some(dir.as_path()))
    }

    fn build(library_file: Option<&Path>, library_search_dir: Option<&Path>) -> Result<Self> {
        let (lib, version_number, version) = load_library_full(library_file, library_search_dir)?;
        Ok(Self {
            lib,
            version_number,
            version,
            library_file: library_file.map(PathBuf::from),
        })
    }

    /// Returns the parsed [`LibVersion`] of the loaded library.
    pub fn library_version(&self) -> LibVersion {
        self.version
    }

    /// Returns the raw version string reported by the loaded library
    /// (typically something like `"25.10"`).
    pub fn library_version_string(&self) -> &str {
        &self.version_number
    }

    /// Returns the explicit library path the context was built with, or
    /// `None` when the library was resolved through the default search
    /// order.
    pub fn library_file(&self) -> Option<&Path> {
        self.library_file.as_deref()
    }

    /// Returns `true` because a context can only be constructed once
    /// the library has successfully loaded.
    pub fn can_parse(&self) -> bool {
        true
    }

    fn loaded(&self) -> LoadedLibrary<'_> {
        LoadedLibrary {
            lib: &self.lib,
            version: self.version,
            version_number: &self.version_number,
        }
    }

    /// Parses any supported source (path, URL, or reader) using the
    /// default [`ParseOptions`].
    ///
    /// See [`MediaInfo::parse`] for the full behavior; this is the
    /// context-bound equivalent.
    pub fn parse<'a, S>(&self, source: S) -> Result<ParseOutput>
    where
        S: MediaInfoSource<'a>,
    {
        self.parse_with_options(source, &ParseOptions::default())
    }

    /// Parses any supported source with caller-supplied
    /// [`ParseOptions`]. See [`MediaInfo::parse_with_options`] for the
    /// full behavior.
    pub fn parse_with_options<'a, S>(
        &self,
        source: S,
        options: &ParseOptions,
    ) -> Result<ParseOutput>
    where
        S: MediaInfoSource<'a>,
    {
        self.check_library_overrides(options)?;
        let input = source.into_input();
        self.parse_input_with_options(input, options)
    }

    /// Parses any supported source and returns the result as a
    /// structured [`MediaInfo`] directly.
    pub fn parse_media_info<'a, S>(&self, source: S) -> Result<MediaInfo>
    where
        S: MediaInfoSource<'a>,
    {
        self.parse_media_info_with_options(source, &ParseOptions::default())
    }

    /// Parses any supported source with caller-supplied
    /// [`ParseOptions`] and returns the result as a structured
    /// [`MediaInfo`] directly.
    pub fn parse_media_info_with_options<'a, S>(
        &self,
        source: S,
        options: &ParseOptions,
    ) -> Result<MediaInfo>
    where
        S: MediaInfoSource<'a>,
    {
        if options.output.is_some() {
            return Err(MediaInfoError::invalid_input(
                "output is only supported by parse or parse_with_options",
            ));
        }

        match self.parse_with_options(source, options)? {
            ParseOutput::MediaInfo(mi) => Ok(mi),
            ParseOutput::Output(_) => Err(MediaInfoError::invalid_input(
                "output is only supported by parse or parse_with_options",
            )),
        }
    }

    /// Path-typed convenience wrapper around [`MediaInfoContext::parse`].
    pub fn parse_path<P: AsRef<Path>>(&self, path: P) -> Result<ParseOutput> {
        self.parse(path.as_ref())
    }

    /// Path-typed convenience wrapper around
    /// [`MediaInfoContext::parse_with_options`].
    pub fn parse_path_with_options<P: AsRef<Path>>(
        &self,
        path: P,
        options: &ParseOptions,
    ) -> Result<ParseOutput> {
        self.parse_with_options(path.as_ref(), options)
    }

    /// Path-typed convenience wrapper around
    /// [`MediaInfoContext::parse_media_info`].
    pub fn parse_media_info_path<P: AsRef<Path>>(&self, path: P) -> Result<MediaInfo> {
        self.parse_media_info(path.as_ref())
    }

    /// Path-typed convenience wrapper around
    /// [`MediaInfoContext::parse_media_info_with_options`].
    pub fn parse_media_info_path_with_options<P: AsRef<Path>>(
        &self,
        path: P,
        options: &ParseOptions,
    ) -> Result<MediaInfo> {
        self.parse_media_info_with_options(path.as_ref(), options)
    }

    /// Parses any `Read + Seek` source using the default [`ParseOptions`].
    pub fn parse_from_reader<R: ReadSeek + ?Sized>(&self, reader: &mut R) -> Result<ParseOutput> {
        self.parse_from_reader_with_options(reader, &ParseOptions::default())
    }

    /// Parses any `Read + Seek` source with caller-supplied
    /// [`ParseOptions`].
    pub fn parse_from_reader_with_options<R: ReadSeek + ?Sized>(
        &self,
        reader: &mut R,
        options: &ParseOptions,
    ) -> Result<ParseOutput> {
        self.check_library_overrides(options)?;
        let _parse_guard = parse_lock();
        let loaded = self.loaded();

        if options.output.is_some() {
            let output =
                MediaInfo::parse_reader_to_string_internal_unlocked(&loaded, reader, options)?;
            return Ok(ParseOutput::Output(output));
        }

        let output = MediaInfo::parse_reader_to_string_internal_unlocked(&loaded, reader, options)?;
        let mi =
            MediaInfo::from_xml_bytes_with_encoding(output.as_bytes(), options.encoding_errors)?;
        Ok(ParseOutput::MediaInfo(mi))
    }

    /// Parses a path and returns the raw text output produced by the
    /// underlying library.
    pub fn parse_to_string<P: AsRef<Path>>(&self, path: P, output_format: &str) -> Result<String> {
        let options = ParseOptions::new().output(output_format.to_string());
        self.parse_to_string_with_options(path, &options)
    }

    /// Parses a path with caller-supplied [`ParseOptions`] and returns
    /// the raw text output produced by the underlying library.
    pub fn parse_to_string_with_options<P: AsRef<Path>>(
        &self,
        path: P,
        options: &ParseOptions,
    ) -> Result<String> {
        self.check_library_overrides(options)?;
        let _parse_guard = parse_lock();
        let loaded = self.loaded();
        MediaInfo::parse_to_string_internal_unlocked(&loaded, path.as_ref(), options)
    }

    /// Parses a reader and returns the raw text output produced by the
    /// underlying library.
    pub fn parse_reader_to_string<R: ReadSeek + ?Sized>(
        &self,
        reader: &mut R,
        output_format: &str,
    ) -> Result<String> {
        let options = ParseOptions::new().output(output_format.to_string());
        self.parse_reader_to_string_with_options(reader, &options)
    }

    /// Parses a reader with caller-supplied [`ParseOptions`] and
    /// returns the raw text output produced by the underlying library.
    pub fn parse_reader_to_string_with_options<R: ReadSeek + ?Sized>(
        &self,
        reader: &mut R,
        options: &ParseOptions,
    ) -> Result<String> {
        self.check_library_overrides(options)?;
        let _parse_guard = parse_lock();
        let loaded = self.loaded();
        MediaInfo::parse_reader_to_string_internal_unlocked(&loaded, reader, options)
    }

    /// Parses a pre-built [`MediaInfoInput`] using the default
    /// [`ParseOptions`].
    pub fn parse_input(&self, input: MediaInfoInput<'_>) -> Result<ParseOutput> {
        self.parse_input_with_options(input, &ParseOptions::default())
    }

    /// Parses a pre-built [`MediaInfoInput`] with caller-supplied
    /// [`ParseOptions`].
    pub fn parse_input_with_options(
        &self,
        input: MediaInfoInput<'_>,
        options: &ParseOptions,
    ) -> Result<ParseOutput> {
        self.check_library_overrides(options)?;

        if options.output.is_some() {
            let output = self.parse_input_to_string_with_options(input, options)?;
            return Ok(ParseOutput::Output(output));
        }

        let output = self.parse_input_to_string_with_options(input, options)?;
        let mi =
            MediaInfo::from_xml_bytes_with_encoding(output.as_bytes(), options.encoding_errors)?;
        Ok(ParseOutput::MediaInfo(mi))
    }

    fn parse_input_to_string_with_options(
        &self,
        input: MediaInfoInput<'_>,
        options: &ParseOptions,
    ) -> Result<String> {
        let _parse_guard = parse_lock();
        let loaded = self.loaded();
        match input {
            MediaInfoInput::Path(path) => {
                MediaInfo::parse_to_string_internal_unlocked(&loaded, path, options)
            }
            MediaInfoInput::Url(url) => {
                MediaInfo::parse_to_string_from_url_unlocked(&loaded, url, options)
            }
            MediaInfoInput::Reader(reader) => {
                MediaInfo::parse_reader_to_string_internal_unlocked(&loaded, reader, options)
            }
        }
    }

    /// Rejects parse calls that would require a different shared
    /// library than the one the context already loaded.
    ///
    /// The match is path-literal and does not canonicalise (the two
    /// sides may differ by symlink resolution or relative-vs-absolute
    /// spelling). Callers that need a different library should build a
    /// separate context rather than trying to override through
    /// [`ParseOptions`].
    fn check_library_overrides(&self, options: &ParseOptions) -> Result<()> {
        if let Some(requested) = options.library_file.as_deref()
            && self.library_file.as_deref() != Some(requested)
        {
            return Err(MediaInfoError::library_mismatch(
                self.library_file.clone().unwrap_or_default(),
                requested,
            ));
        }

        if let Some(requested_dir) = options.library_search_dir.as_deref() {
            return Err(MediaInfoError::library_mismatch(
                self.library_file.clone().unwrap_or_default(),
                requested_dir,
            ));
        }

        Ok(())
    }
}

impl std::str::FromStr for MediaInfo {
    type Err = MediaInfoError;

    /// Parses a pre-generated XML string by delegating to
    /// [`MediaInfo::from_xml`].
    fn from_str(s: &str) -> Result<Self> {
        MediaInfo::from_xml(s)
    }
}

impl TryFrom<&str> for MediaInfo {
    type Error = MediaInfoError;

    /// Parses a pre-generated XML string by delegating to
    /// [`MediaInfo::from_xml`].
    fn try_from(value: &str) -> Result<Self> {
        MediaInfo::from_xml(value)
    }
}

impl std::fmt::Display for MediaInfo {
    /// Renders the value in a stable, debuggable single-line form:
    /// `<MediaInfo N tracks>`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "<MediaInfo {} tracks>", self.tracks.len())
    }
}

#[cfg(test)]
mod tests {
    //! Unit tests for items that intentionally remain private to this module.
    //!
    //! Tests that exercise the public API live alongside the rest of the
    //! integration suite under `tests/`.

    use super::*;

    #[test]
    fn test_default_library_search_dir_env_override() {
        let key = "RS_MEDIAINFO_LIBRARY_DIR";
        let original = std::env::var(key).ok();

        unsafe {
            std::env::set_var(key, "/tmp/rsmediainfo-test");
        }
        let resolved = MediaInfo::default_library_search_dir();
        assert_eq!(resolved, Some(PathBuf::from("/tmp/rsmediainfo-test")));

        unsafe {
            if let Some(value) = original {
                std::env::set_var(key, value);
            } else {
                std::env::remove_var(key);
            }
        }
    }

    #[test]
    fn test_normalize_output_option_text_alias() {
        assert_eq!(MediaInfo::normalize_output_option("text"), "");
        assert_eq!(MediaInfo::normalize_output_option("TEXT"), "");
        assert_eq!(MediaInfo::normalize_output_option("JSON"), "JSON");
    }
}