mediaframe 0.5.0

A common media-stream descriptor vocabulary (pixel-format, colour, and frame metadata for video — audio/subtitle to follow) for media processing pipelines.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
//! `buffa::Message` implementations for the mediaframe wire-relevant
//! types, behind the `buffa` feature. Used via `extern_path` from
//! buffa-generated crates so a `.proto`-defined message can embed a
//! mediaframe type without redefining it.
//!
//! These are hand-written inherent-trait impls — there is **no**
//! codegen and **no** `.proto` in this crate (mirrors the
//! `mediatime` design). The module needs no re-export: the impls are
//! `impl Trait for crate::Type`.
//!
//! # Wire format (clean redesign — no compatibility with any prior
//! encoding is required)
//!
//! ## Enums (each is a standalone message = one field)
//!
//! ```text
//! Matrix    { uint32 value = 1; }   // value = to_u32()
//! Primaries { string value = 1; }
//! Transfer  { string value = 1; }
//! DynamicRange     { string value = 1; }
//! ChromaLocation { string value = 1; }
//! DcpTargetGamut { string value = 1; }
//! Rotation       { string value = 1; }
//! FieldOrder     { string value = 1; }
//! StereoMode     { string value = 1; }
//! PixelFormat    { string value = 1; }
//! ```
//!
//! Each enum encodes its `as_str()` slug as a single `string` at
//! field #1, decoded via `FromStr` — the same shape the codec family
//! has always used. The slug is the spelling because `Other(SmolStr)`
//! is the crate's one extension idiom: a value this build does not
//! name still has a *name*, and a number would not carry it.
//!
//! **Default-elision (not proto3 zero-elision):** the field is
//! written iff `*self != <Ty>::default()`. The decoder seeds the
//! message from `Default` (= FFmpeg `UNSPECIFIED` for the colour
//! enums — code `2` for primaries/transfer/matrix, `0` for
//! range/chroma), so an absent field decodes back to `Default`. A
//! *present* field always carries the exact `to_u32()` code —
//! **including code `0`** (`Matrix::Rgb`, FFmpeg
//! `AVCOL_SPC_RGB`), which is *non-default* and therefore explicitly
//! encoded, so it is never conflated with an absent field. Plain
//! proto3 zero-elision would be **unsound** here (it would drop the
//! non-default code-`0` `Rgb`); default-elision is exact for every
//! value. Wrong wire type on field #1 →
//! `DecodeError::WireTypeMismatch`; unknown fields are skipped via
//! `skip_field_depth`.
//!
//! ## Structs
//!
//! ```text
//! Dimensions        { uint32 width = 1; uint32 height = 2; }
//! Rect              { uint32 x = 1; uint32 y = 2; uint32 width = 3; uint32 height = 4; }
//! SampleAspectRatio { int64  num = 1; int64  den = 2; }          // both ALWAYS encoded
//! Rational          { int64  num = 1; int64  den = 2; }          // both ALWAYS encoded
//! FrameRate         { Rational rate = 1;                         // rate ALWAYS encoded
//!                     bool     is_vfr = 2; }                     // proto3 zero-elision
//! DolbyVisionConfig { uint32 profile = 1; uint32 level = 2;      // proto3 zero-elision
//!                     bool rpu_present = 3; bool el_present = 4; //   (all-zero default)
//!                     uint32 bl_signal_compat_id = 5; }
//! Info         { Primaries primaries = 1;              // all five ALWAYS
//!                     Transfer  transfer  = 2;              //   encoded as the
//!                     Matrix    matrix    = 3;              //   bare uint32 id
//!                     DynamicRange     range     = 4;              //   (not nested msgs)
//!                     ChromaLocation chroma    = 5; }
//! ContentLightLevel { uint32 max_cll = 1; uint32 max_fall = 2; }
//! ChromaCoord       { uint32 x = 1; uint32 y = 2; }              // u16 widened to uint32
//! MasteringDisplay  { ChromaCoord primary_r   = 1;               // ALWAYS encoded
//!                     ChromaCoord primary_g   = 2;               // ALWAYS encoded
//!                     ChromaCoord primary_b   = 3;               // ALWAYS encoded
//!                     ChromaCoord white_point = 4;               // ALWAYS encoded
//!                     uint32 max_luminance = 5;
//!                     uint32 min_luminance = 6; }
//! HdrStaticMetadata { MasteringDisplay  mastering     = 1;       // absent when None
//!                     ContentLightLevel content_light = 2; }     // absent when None
//! ```
//!
//! Field numbers follow declaration order. proto3 zero-elision is
//! used **only** where the decoder seed (`DefaultInstance`, i.e.
//! `Default`/`new`) is the proto-zero for that field
//! (`Dimensions`, `Rect`, `ContentLightLevel`, `ChromaCoord`, the
//! `*_luminance` scalars). Where `Default` ≠ proto-zero the field is
//! **always encoded** (the `mediatime::Timebase` reasoning):
//!
//! - `SampleAspectRatio` — `Default` is `1:1`. `num`'s default is
//!   `1` (≠ 0) and `den` is `NonZeroI64` (never 0), so eliding a
//!   zero would mis-decode. Both fields are always written. On the
//!   way back in, both halves are clamped into the range
//!   `Rational::new` accepts, so decode stays total: a negative
//!   `num` becomes `0`, and a `den` that is zero *or negative*
//!   becomes `1`. Neither is producible by this encoder — a peer
//!   reaches them either directly or by writing a `uint64` above
//!   `i64::MAX`, which `decode_int64` reinterprets as negative.
//!   (Before `Rational` became signed, `den` was `NonZeroU32` and
//!   only the zero case existed.)
//! - `Rational` — same shape / reasoning as `SampleAspectRatio`
//!   (`Default` is `1/1`, `num` default `1`, `den` `NonZeroI64`):
//!   both fields always encoded, malformed `num`/`den` clamped the
//!   same way.
//! - `FrameRate` — `rate` is an always-encoded length-delimited
//!   `Rational` sub-message (its inner `Default` is `1/1` ≠
//!   proto-zero, so the nested-message-always-encoded
//!   `mediatime::Timebase` stance applies, like `MasteringDisplay`'s
//!   coords); `is_vfr` defaults to `false` == proto-zero so it uses
//!   proto3 zero-elision.
//! - `Info` — **all five enum fields are always encoded** as
//!   the bare FFmpeg-code `uint32` id (not a nested message); tags
//!   #1–#5 are single-byte. `Info`'s own seed is
//!   `Info::UNSPECIFIED` (every field FFmpeg `UNSPECIFIED`).
//!   Always-encoding keeps the round-trip exact regardless of which
//!   FFmpeg code a field holds — in particular `matrix ==
//!   Matrix::Rgb` (FFmpeg code `0`) survives because the id is
//!   written unconditionally, never elided — the same defensive
//!   `mediatime::Timebase` always-encode stance.
//! - `MasteringDisplay` — the three primaries and the white point
//!   are always-encoded length-delimited sub-messages so presence
//!   is unambiguous and `decode(encode(x)) == x` holds regardless of
//!   `ChromaCoord` content (nested-message presence, like
//!   `mediatime`'s always-encoded `Timebase`).
//! - `HdrStaticMetadata` — the two `Option` fields are
//!   presence-encoded length-delimited messages, omitted entirely
//!   when `None`.
//!
//! Every `merge_field` rejects a wrong wire type with
//! `DecodeError::WireTypeMismatch` and skips unknown fields with
//! `skip_field_depth`; `clear()` resets to `Default` / `new`.
//!
//! ## Audio + container types
//!
//! ```text
//! ChannelLayout        { string value = 1; }   // value = as_str()
//! BitRateMode          { uint32 value = 1; }   // value = to_u32() (Cbr=0)
//! SampleFormat          { uint32 value = 1; }   // value = to_u32() (FFmpeg AV_SAMPLE_FMT_* code, Other → u32::MAX)
//! ContainerFormat { string value = 1; }   // value = as_str()
//! Format      { string value = 1; }   // value = as_str()
//!
//! Loudness         { float integrated_lufs = 1; float range_lu = 2;
//!                    float true_peak_dbtp = 3; float sample_peak_dbfs = 4; }
//! ReplayGain       { float track_gain_db = 1; float track_peak = 2;
//!                    optional float album_gain_db = 3;
//!                    optional float album_peak = 4; }
//! Fingerprint { string algorithm = 1; bytes value = 2; }     // algorithm ALWAYS encoded
//! CoverArt    { string mime      = 1; bytes data  = 2; }     // both ALWAYS encoded
//! Tags        { string title        = 1; string artist        = 2;
//!                    string album_artist = 3; string album         = 4;
//!                    string composer     = 5; string genre         = 6;
//!                    string comment      = 7;
//!                    uint32 year         = 8; uint32 track_number  = 9;
//!                    uint32 track_total  = 10; uint32 disc_number   = 11;
//!                    uint32 disc_total   = 12; string language      = 13; }
//! ```
//!
//! - **String-bearing enums** (`ChannelLayout`, `ContainerFormat`,
//!   `Format`, `SampleFormat`) encode their `as_str()` slug. Default
//!   (where defined) elides; `Other(SmolStr)` round-trips losslessly.
//!   `BitRateMode` is strictly closed and encodes its `to_u32()` id.
//! - **`Loudness`** — all four `f32` fields use proto3 zero-elision
//!   (`Default` is all-zero == proto-zero for `f32`). Each present
//!   field is wire-type `Fixed32` (4 bytes LE).
//! - **`ReplayGain`** — `track_gain_db` / `track_peak` use proto3
//!   zero-elision (`Default` is all-zero == proto-zero for `f32`);
//!   `album_gain_db` / `album_peak` are `optional float` so a
//!   distribution-absent album-level number round-trips as `None`
//!   (the wire field is absent rather than zero). Each present field
//!   is wire-type `Fixed32` (4 bytes LE).
//! - **`Fingerprint`** — `algorithm` is ALWAYS encoded
//!   (`try_new` rejects empty, so a default-constructed wire-empty
//!   `algorithm` would not be a valid `Fingerprint` — encoding
//!   it explicitly preserves the invariant on the wire round-trip).
//!   `value` (bytes) uses proto3 zero-elision (an empty fingerprint
//!   is legal). The decoder seed is `try_new("default", []).unwrap()`
//!   so that an absent `algorithm` decodes to a synthetic non-empty
//!   placeholder rather than violating the type invariant.
//! - **`CoverArt`** — both `mime` and `data` are ALWAYS encoded
//!   (`try_new` rejects empty in either, so default-constructed
//!   wire-empty fields would violate the invariant). Same
//!   placeholder-seed strategy as `Fingerprint`.
//! - **`Tags`** — string fields use proto3 zero-elision (the
//!   empty string is the canonical "absent" value); numeric `u16`
//!   fields are widened to `uint32` and use proto3 zero-elision —
//!   `Some(0)` (legal value) and `None` (absent) **cannot be
//!   distinguished on the wire** in this codec; both round-trip to
//!   `None`. A future codec revision can switch to wrapper messages
//!   if the distinction becomes load-bearing. `language` is the
//!   placeholder BCP-47 SmolStr; the `TODO(lang)` comment on the
//!   Rust type tracks the swap to `Option<Language>`.
//!
//! ## Subtitle + disposition
//!
//! Three stream-vocab types from the `subtitle` + `disposition`
//! modules. All three are standalone one-field messages:
//!
//! ```text
//! Format      { string value = 1; }   // FFmpeg-style slug from `as_str()`
//! TrackOrigin { string value = 1; }   // value = as_str()
//! TrackDisposition    { uint32 bits  = 1; }   // bits = to_u32() (= raw bitflags bits)
//! ```
//!
//! - **`Format`** — a closed-ish enum with an `Other(SmolStr)`
//!   escape arm has no stable numeric id, so it encodes the
//!   FFmpeg-style slug (`"srt"` / `"webvtt"` / `"hdmv_pgs_subtitle"` /
//!   …) as a `string`. The decoder funnels through `FromStr` (total —
//!   unknown slugs land in `Other`). Default-elision: the default is
//!   not proto-zero (`Srt` is the inhabited representative — though
//!   the encoder treats *every* value as non-default and always
//!   encodes, to side-step the issue entirely). In practice we
//!   always-encode the slug so an empty string can never be conflated
//!   with `Srt`; on decode an empty string maps to `Other("")`,
//!   matching `FromStr`.
//! - **`TrackOrigin`** — an open enum since 0.5.0 (`Other(SmolStr)`),
//!   so its stable ids no longer span the value space and it encodes
//!   the slug as a `string`, like `Format` above. Always-encoded for
//!   the same reason: the empty string is `Other("")` on decode, a
//!   distinct legal value that eliding would conflate with an absent
//!   field. **Wire-incompatible with 0.4.x**, which wrote a varint id
//!   in this field.
//! - **`TrackDisposition`** — bitflags. Encoded as the raw `u32`
//!   bits at field #1, decoded via [`TrackDisposition::from_u32`]
//!   (`from_bits_retain` semantics — unknown bits round-trip
//!   losslessly). Default-elision is sound: the default is the
//!   empty flag set whose `bits()` is `0` (proto-zero).
//!
//! ## Capture + language
//!
//! Three alloc-gated types from the `capture` + `lang` modules:
//!
//! ```text
//! Device      { string make = 1; string model = 2; }     // proto3 zero-elision (empty == absent)
//! GeoLocation { double lat = 1; double lon = 2;          // lat/lon ALWAYS encoded
//!               float altitude = 3; }                     // altitude emitted iff Some
//! Language    { string value = 1; }                      // BCP-47 canonical tag; "und" elides
//! ```
//!
//! - **`Device`** — two empty strings == proto-zero, so proto3
//!   zero-elision is sound. Empty string is the in-rust sentinel
//!   for "absent" (matches the same convention used by `Tags`).
//! - **`GeoLocation`** — the `(0.0, 0.0)` "Null Island" default is a
//!   real, legal coordinate, so proto3 zero-elision on `lat`/`lon`
//!   would be **unsound** (it would lose the Null-Island record).
//!   Both fields are always encoded; the optional `altitude` field
//!   uses presence encoding (emitted iff `Some`, including for
//!   `Some(0.0)` so sea-level distinct from absent altitude). Same
//!   defensive stance as `SampleAspectRatio`.
//! - **`Language`** — encoded as the BCP-47 canonical tag via
//!   `to_bcp47()`. Default is `"und"` (ISO 639-3 undetermined),
//!   which is the in-rust sentinel for "no usable tag"; the wire
//!   uses default-elision (an absent field decodes to `und`). An
//!   invalid wire string silently coerces to `Language::default()`
//!   (`und`) — `buffa::DecodeError` in 0.6 has no general
//!   "invalid value" arm, and the type's sentinel is the right
//!   fallback.

use core::num::NonZeroI64;

use ::buffa::{
  DecodeContext, DecodeError, DefaultInstance, EncodeSink, Message, SizeCache,
  bytes::Buf,
  encoding::{Tag, WireType, encode_varint, skip_field_depth, varint_len},
  types::{
    FIXED32_ENCODED_LEN, bytes_encoded_len, decode_bytes, decode_double, decode_float,
    decode_int64, decode_string, decode_uint32, encode_bytes, encode_double, encode_float,
    encode_int64, encode_string, encode_uint32, int64_encoded_len, string_encoded_len,
    uint32_encoded_len,
  },
};
use smol_str::SmolStr;

use crate::{
  audio::{
    BitRateMode, ChannelLayout, ContainerFormat, CoverArt, Fingerprint, Loudness, ReplayGain,
    SampleFormat, Tags,
  },
  capture::{Device, GeoLocation},
  color::{
    ChromaCoord, ChromaLocation, ContentLightLevel, DcpTargetGamut, DolbyVisionConfig,
    DynamicRange, HdrStaticMetadata, Info, MasteringDisplay, Matrix, Primaries, Transfer,
  },
  container::Format,
  disposition::TrackDisposition,
  frame::{
    DEN_ONE, Dimensions, FieldOrder, FrameRate, Rational, Rect, Rotation, SampleAspectRatio,
    StereoMode,
  },
  lang::Language,
  pixel_format::PixelFormat,
};

const VARINT: u8 = WireType::Varint as u8;
const LEN: u8 = WireType::LengthDelimited as u8;

// The colour / frame / pixel-format vocabularies carry names, not numbers:
// `Other(SmolStr)` is the escape, so the slug is the only spelling that
// survives a value this build has never heard of. They therefore ride the
// same one-field `{ string value = 1; }` shape as the codec family — see
// `impl_string_enum_message!` below. The declarations sit there, beside it.

// ----------------------------------------------------------------------------
// Dimensions — { uint32 width = 1; uint32 height = 2; }
// Default is (0, 0) == proto-zero, so zero-elision is sound.
// ----------------------------------------------------------------------------

impl DefaultInstance for Dimensions {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Dimensions> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Dimensions::default()))
  }
}

impl Message for Dimensions {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // proto3 zero-elision: sound — seed is Dimensions::default() = (0, 0).
    if self.width() != 0 {
      size += 1 + uint32_encoded_len(self.width()) as u32;
    }
    if self.height() != 0 {
      size += 1 + uint32_encoded_len(self.height()) as u32;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    // proto3 zero-elision: sound — see `compute_size`.
    if self.width() != 0 {
      Tag::new(1, WireType::Varint).encode(buf);
      encode_uint32(self.width(), buf);
    }
    if self.height() != 0 {
      Tag::new(2, WireType::Varint).encode(buf);
      encode_uint32(self.height(), buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let w = decode_uint32(buf)?;
        self.set_width(w);
      }
      2 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let h = decode_uint32(buf)?;
        self.set_height(h);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = Dimensions::default();
  }
}

// ----------------------------------------------------------------------------
// Rect — { uint32 x = 1; uint32 y = 2; uint32 width = 3; uint32 height = 4; }
// Default is all-zero == proto-zero, so zero-elision is sound.
// ----------------------------------------------------------------------------

impl DefaultInstance for Rect {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Rect> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Rect::default()))
  }
}

impl Message for Rect {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // proto3 zero-elision: sound — seed is Rect::default() = all-zero.
    if self.x() != 0 {
      size += 1 + uint32_encoded_len(self.x()) as u32;
    }
    if self.y() != 0 {
      size += 1 + uint32_encoded_len(self.y()) as u32;
    }
    if self.width() != 0 {
      size += 1 + uint32_encoded_len(self.width()) as u32;
    }
    if self.height() != 0 {
      size += 1 + uint32_encoded_len(self.height()) as u32;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    // proto3 zero-elision: sound — see `compute_size`.
    if self.x() != 0 {
      Tag::new(1, WireType::Varint).encode(buf);
      encode_uint32(self.x(), buf);
    }
    if self.y() != 0 {
      Tag::new(2, WireType::Varint).encode(buf);
      encode_uint32(self.y(), buf);
    }
    if self.width() != 0 {
      Tag::new(3, WireType::Varint).encode(buf);
      encode_uint32(self.width(), buf);
    }
    if self.height() != 0 {
      Tag::new(4, WireType::Varint).encode(buf);
      encode_uint32(self.height(), buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_uint32(buf)?;
        self.set_x(v);
      }
      2 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_uint32(buf)?;
        self.set_y(v);
      }
      3 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 3,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_uint32(buf)?;
        self.set_width(v);
      }
      4 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 4,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_uint32(buf)?;
        self.set_height(v);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = Rect::default();
  }
}

// ----------------------------------------------------------------------------
// SampleAspectRatio — { int64 num = 1; int64 den = 2; }
//
// `num`/`den` are encoded UNCONDITIONALLY — no proto3 zero elision.
// The decoder seeds from `SampleAspectRatio::default()` (1:1), NOT
// proto-zero. Eliding `num == 0` would decode back as `num == 1`;
// `den` is `NonZeroI64` and can never legitimately be 0. (Exactly
// the `mediatime::Timebase` reasoning.) Both tags are single-byte.
//
// The fields were `uint32` before `Rational` became signed and 64-bit.
// Protobuf's `int64` and `uint32` are the same plain (non-ZigZag)
// varint over the values a `SampleAspectRatio` can hold — non-negative
// and, for anything a `uint32` peer wrote, at most `u32::MAX` — so the
// bytes are unchanged in both directions and previously-encoded
// payloads still decode. `sint64` would have been the silent break:
// ZigZag re-encodes every value. Note the widening is one-way at the
// edges: a value above `u32::MAX` is writable now and a `uint32`
// reader would truncate it.
// ----------------------------------------------------------------------------

impl DefaultInstance for SampleAspectRatio {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<SampleAspectRatio> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(SampleAspectRatio::default()))
  }
}

impl Message for SampleAspectRatio {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    2 + int64_encoded_len(self.num()) as u32 + int64_encoded_len(self.den().get()) as u32
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    Tag::new(1, WireType::Varint).encode(buf);
    encode_int64(self.num(), buf);
    Tag::new(2, WireType::Varint).encode(buf);
    encode_int64(self.den().get(), buf);
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        // `Rational::new` panics on a negative numerator, so decode
        // must not hand it one. Our own encoder never writes a
        // negative; a peer can, either directly or by writing a
        // `uint64` above `i64::MAX` that `decode_int64` reinterprets
        // into the negative half. Clamp to the smallest legal
        // numerator so decode stays total, as `den` does.
        let num = decode_int64(buf)?.max(0);
        self.set_num(num);
      }
      2 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        // `den` is NonZeroI64; a malformed den — zero, or negative by
        // the same route as `num` above — is clamped to 1. Since
        // `NonZeroI64::MIN` is `i64::MIN`, the clamp target is spelled
        // out as `DEN_ONE`. This is the same decode policy as
        // `mediatime::Timebase`'s in the published `mediatime` extern
        // that SAR mirrors, and upholds the codec family's
        // total-scalar-decode invariant (scalar values never raise
        // decode errors; only structural errors do). Codex
        // adversarial-review F6: resolved as a coordinated
        // mediatime/buffa policy, NOT a mediaframe-only divergence.
        let den = NonZeroI64::new(decode_int64(buf)?)
          .filter(|d| d.get() > 0)
          .unwrap_or(DEN_ONE);
        self.set_den(den);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = SampleAspectRatio::default();
  }
}

// ----------------------------------------------------------------------------
// Rational — { int64 num = 1; int64 den = 2; }
//
// Same shape and reasoning as `SampleAspectRatio`, including the
// `uint32` → `int64` widening being byte-compatible in both
// directions: `num`/`den` are encoded UNCONDITIONALLY (no proto3
// zero-elision). The decoder seeds from `Rational::default()` (1/1),
// NOT proto-zero; eliding `num == 0` would decode back as `num == 1`.
// `den` is `NonZeroI64` and can never legitimately be 0; a malformed
// wire `den` — zero or negative — is clamped to 1 to keep decode
// total, as is a negative `num`. Both tags are single-byte.
// ----------------------------------------------------------------------------

impl DefaultInstance for Rational {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Rational> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Rational::default()))
  }
}

impl Message for Rational {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    2 + int64_encoded_len(self.num()) as u32 + int64_encoded_len(self.den().get()) as u32
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    Tag::new(1, WireType::Varint).encode(buf);
    encode_int64(self.num(), buf);
    Tag::new(2, WireType::Varint).encode(buf);
    encode_int64(self.den().get(), buf);
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        // A negative numerator would trip `Rational::new`'s assert;
        // clamp as `SampleAspectRatio` does to keep decode total.
        let num = decode_int64(buf)?.max(0);
        self.set_num(num);
      }
      2 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        // `den` is NonZeroI64; a malformed 0 or negative on the wire
        // (never produced by our own encoder) is clamped to 1 —
        // identical to `SampleAspectRatio`'s decode, upholding the
        // codec family's total-scalar-decode invariant.
        let den = NonZeroI64::new(decode_int64(buf)?)
          .filter(|d| d.get() > 0)
          .unwrap_or(DEN_ONE);
        self.set_den(den);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = Rational::default();
  }
}

// ----------------------------------------------------------------------------
// FrameRate — { Rational rate = 1; bool is_vfr = 2; }
//
// `rate` is an always-encoded length-delimited `Rational`
// sub-message: its inner `Default` is `1/1` ≠ proto-zero, so the
// nested-message-always-encoded `mediatime::Timebase` stance applies
// (like `MasteringDisplay`'s coords) — presence is unambiguous and
// `decode(encode(x)) == x` holds regardless of the inner ratio.
// `is_vfr` defaults to `false` == proto-zero, so it uses sound proto3
// zero-elision (only `true` is written).
// ----------------------------------------------------------------------------

impl DefaultInstance for FrameRate {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<FrameRate> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(FrameRate::default()))
  }
}

impl Message for FrameRate {
  fn compute_size(&self, cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // rate (field 1) — always-encoded nested message.
    {
      let slot = cache.reserve();
      let inner = self.rate().compute_size(cache);
      cache.set(slot, inner);
      size += 1 + varint_len(inner as u64) as u32 + inner;
    }
    // proto3 zero-elision: sound — seed `is_vfr` is `false`.
    if self.is_vfr() {
      size += 1 + 1; // tag + single-byte bool varint
    }
    size
  }

  fn write_to(&self, cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    Tag::new(1, WireType::LengthDelimited).encode(buf);
    encode_varint(cache.consume_next() as u64, buf);
    self.rate().write_to(cache, buf);
    // proto3 zero-elision: sound — see `compute_size`.
    if self.is_vfr() {
      Tag::new(2, WireType::Varint).encode(buf);
      encode_varint(1, buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let mut rate = self.rate();
        buffa::Message::merge_length_delimited(&mut rate, buf, ctx)?;
        self.set_rate(rate);
      }
      2 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        self.update_is_vfr(decode_uint32(buf)? != 0);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = FrameRate::default();
  }
}

// ----------------------------------------------------------------------------
// DolbyVisionConfig — { uint32 profile = 1; uint32 level = 2;
//                       bool rpu_present = 3; bool el_present = 4;
//                       uint32 bl_signal_compat_id = 5; }
//
// `Default` is all-zero == proto-zero for every field, so proto3
// zero-elision is sound throughout. `u8` fields widen to the `uint32`
// wire scalar; bools are 0/1 varints.
// ----------------------------------------------------------------------------

impl DefaultInstance for DolbyVisionConfig {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<DolbyVisionConfig> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(DolbyVisionConfig::default()))
  }
}

impl Message for DolbyVisionConfig {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // proto3 zero-elision: sound — seed is all-zero default.
    if self.profile() != 0 {
      size += 1 + uint32_encoded_len(self.profile() as u32) as u32;
    }
    if self.level() != 0 {
      size += 1 + uint32_encoded_len(self.level() as u32) as u32;
    }
    if self.rpu_present() {
      size += 1 + 1;
    }
    if self.el_present() {
      size += 1 + 1;
    }
    if self.bl_signal_compat_id() != 0 {
      size += 1 + uint32_encoded_len(self.bl_signal_compat_id() as u32) as u32;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    // proto3 zero-elision: sound — see `compute_size`.
    if self.profile() != 0 {
      Tag::new(1, WireType::Varint).encode(buf);
      encode_uint32(self.profile() as u32, buf);
    }
    if self.level() != 0 {
      Tag::new(2, WireType::Varint).encode(buf);
      encode_uint32(self.level() as u32, buf);
    }
    if self.rpu_present() {
      Tag::new(3, WireType::Varint).encode(buf);
      encode_varint(1, buf);
    }
    if self.el_present() {
      Tag::new(4, WireType::Varint).encode(buf);
      encode_varint(1, buf);
    }
    if self.bl_signal_compat_id() != 0 {
      Tag::new(5, WireType::Varint).encode(buf);
      encode_uint32(self.bl_signal_compat_id() as u32, buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        self.set_profile(decode_uint32(buf)? as u8);
      }
      2 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        self.set_level(decode_uint32(buf)? as u8);
      }
      3 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 3,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        self.update_rpu_present(decode_uint32(buf)? != 0);
      }
      4 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 4,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        self.update_el_present(decode_uint32(buf)? != 0);
      }
      5 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 5,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        self.set_bl_signal_compat_id(decode_uint32(buf)? as u8);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = DolbyVisionConfig::default();
  }
}

// ----------------------------------------------------------------------------
// Info — five enum slugs, each a bare `string`, ALL always encoded.
// See the module doc: always-encoding (esp. `matrix`, whose semantic
// default is `Bt709`) decouples the wire round-trip from the field's own
// default — the `mediatime` always-encode-nontrivial-default stance.
// Tags #1–#5 single-byte. The slug is the spelling because the member
// enums' only escape is `Other(SmolStr)`.
// ----------------------------------------------------------------------------

impl DefaultInstance for Info {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Info> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Info::UNSPECIFIED))
  }
}

impl Message for Info {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    // All five are unconditionally encoded (presence-independent).
    5 + string_encoded_len(self.primaries().as_str()) as u32
      + string_encoded_len(self.transfer().as_str()) as u32
      + string_encoded_len(self.matrix().as_str()) as u32
      + string_encoded_len(self.range().as_str()) as u32
      + string_encoded_len(self.chroma_location().as_str()) as u32
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    Tag::new(1, WireType::LengthDelimited).encode(buf);
    encode_string(self.primaries().as_str(), buf);
    Tag::new(2, WireType::LengthDelimited).encode(buf);
    encode_string(self.transfer().as_str(), buf);
    Tag::new(3, WireType::LengthDelimited).encode(buf);
    encode_string(self.matrix().as_str(), buf);
    Tag::new(4, WireType::LengthDelimited).encode(buf);
    encode_string(self.range().as_str(), buf);
    Tag::new(5, WireType::LengthDelimited).encode(buf);
    encode_string(self.chroma_location().as_str(), buf);
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let s = decode_string(buf)?;
        self.set_primaries(s.parse().unwrap_or_else(|_| unreachable!()));
      }
      2 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let s = decode_string(buf)?;
        self.set_transfer(s.parse().unwrap_or_else(|_| unreachable!()));
      }
      3 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 3,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let s = decode_string(buf)?;
        self.set_matrix(s.parse().unwrap_or_else(|_| unreachable!()));
      }
      4 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 4,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let s = decode_string(buf)?;
        self.set_range(s.parse().unwrap_or_else(|_| unreachable!()));
      }
      5 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 5,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let s = decode_string(buf)?;
        self.set_chroma_location(s.parse().unwrap_or_else(|_| unreachable!()));
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = Info::UNSPECIFIED;
  }
}

// ----------------------------------------------------------------------------
// ContentLightLevel — { uint32 max_cll = 1; uint32 max_fall = 2; }
// Default is (0, 0) == proto-zero, so zero-elision is sound.
// ----------------------------------------------------------------------------

impl DefaultInstance for ContentLightLevel {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<ContentLightLevel> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(ContentLightLevel::default()))
  }
}

impl Message for ContentLightLevel {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // proto3 zero-elision: sound — seed is ContentLightLevel::default() = (0, 0).
    if self.max_cll() != 0 {
      size += 1 + uint32_encoded_len(self.max_cll()) as u32;
    }
    if self.max_fall() != 0 {
      size += 1 + uint32_encoded_len(self.max_fall()) as u32;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    // proto3 zero-elision: sound — see `compute_size`.
    if self.max_cll() != 0 {
      Tag::new(1, WireType::Varint).encode(buf);
      encode_uint32(self.max_cll(), buf);
    }
    if self.max_fall() != 0 {
      Tag::new(2, WireType::Varint).encode(buf);
      encode_uint32(self.max_fall(), buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_uint32(buf)?;
        self.set_max_cll(v);
      }
      2 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_uint32(buf)?;
        self.set_max_fall(v);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = ContentLightLevel::default();
  }
}

// ----------------------------------------------------------------------------
// ChromaCoord — { uint32 x = 1; uint32 y = 2; }
// `x`/`y` are `u32` storage == the wire scalar; every value (incl.
// out-of-range / future / corrupt) round-trips losslessly — no
// saturation (Codex adversarial-review F3).
// Default is (0, 0) == proto-zero, so zero-elision is sound.
// ----------------------------------------------------------------------------

impl DefaultInstance for ChromaCoord {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<ChromaCoord> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(ChromaCoord::default()))
  }
}

impl Message for ChromaCoord {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // proto3 zero-elision: sound — seed is ChromaCoord::default() = (0, 0).
    if self.x() != 0 {
      size += 1 + uint32_encoded_len(self.x()) as u32;
    }
    if self.y() != 0 {
      size += 1 + uint32_encoded_len(self.y()) as u32;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    // proto3 zero-elision: sound — see `compute_size`.
    if self.x() != 0 {
      Tag::new(1, WireType::Varint).encode(buf);
      encode_uint32(self.x(), buf);
    }
    if self.y() != 0 {
      Tag::new(2, WireType::Varint).encode(buf);
      encode_uint32(self.y(), buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        // u32 storage == wire scalar: preserved verbatim, no
        // saturation (Codex F3).
        self.set_x(decode_uint32(buf)?);
      }
      2 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        self.set_y(decode_uint32(buf)?);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = ChromaCoord::default();
  }
}

// ----------------------------------------------------------------------------
// MasteringDisplay — { ChromaCoord primary_r = 1; primary_g = 2;
//                      primary_b = 3; white_point = 4;
//                      uint32 max_luminance = 5; uint32 min_luminance = 6; }
//
// The four nested ChromaCoords are ALWAYS encoded (length-delimited)
// so presence is unambiguous and round-trip holds regardless of
// content (the `mediatime` always-encoded-nested-message stance).
// The two luminance scalars default to 0 == proto-zero so they use
// proto3 zero-elision.
// ----------------------------------------------------------------------------

impl DefaultInstance for MasteringDisplay {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<MasteringDisplay> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(MasteringDisplay::default()))
  }
}

impl Message for MasteringDisplay {
  fn compute_size(&self, cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    let primaries = self.display_primaries();
    // primary_r / g / b (fields 1..=3) — always encoded.
    for cc in &primaries {
      let slot = cache.reserve();
      let inner = cc.compute_size(cache);
      cache.set(slot, inner);
      size += 1 + varint_len(inner as u64) as u32 + inner;
    }
    // white_point (field 4) — always encoded.
    {
      let slot = cache.reserve();
      let inner = self.white_point().compute_size(cache);
      cache.set(slot, inner);
      size += 1 + varint_len(inner as u64) as u32 + inner;
    }
    // proto3 zero-elision: sound — seed is MasteringDisplay::default(),
    // whose luminances are 0.
    if self.max_luminance() != 0 {
      size += 1 + uint32_encoded_len(self.max_luminance()) as u32;
    }
    if self.min_luminance() != 0 {
      size += 1 + uint32_encoded_len(self.min_luminance()) as u32;
    }
    size
  }

  fn write_to(&self, cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    let primaries = self.display_primaries();
    for (i, cc) in primaries.iter().enumerate() {
      Tag::new(1 + i as u32, WireType::LengthDelimited).encode(buf);
      encode_varint(cache.consume_next() as u64, buf);
      cc.write_to(cache, buf);
    }
    Tag::new(4, WireType::LengthDelimited).encode(buf);
    encode_varint(cache.consume_next() as u64, buf);
    self.white_point().write_to(cache, buf);
    // proto3 zero-elision: sound — see `compute_size`.
    if self.max_luminance() != 0 {
      Tag::new(5, WireType::Varint).encode(buf);
      encode_uint32(self.max_luminance(), buf);
    }
    if self.min_luminance() != 0 {
      Tag::new(6, WireType::Varint).encode(buf);
      encode_uint32(self.min_luminance(), buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      n @ 1..=3 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: n,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let mut primaries = self.display_primaries();
        let mut cc = primaries[(n - 1) as usize];
        buffa::Message::merge_length_delimited(&mut cc, buf, ctx)?;
        primaries[(n - 1) as usize] = cc;
        self.set_display_primaries(primaries);
      }
      4 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 4,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let mut wp = self.white_point();
        buffa::Message::merge_length_delimited(&mut wp, buf, ctx)?;
        self.set_white_point(wp);
      }
      5 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 5,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_uint32(buf)?;
        self.set_max_luminance(v);
      }
      6 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 6,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_uint32(buf)?;
        self.set_min_luminance(v);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = MasteringDisplay::default();
  }
}

// ----------------------------------------------------------------------------
// HdrStaticMetadata — { MasteringDisplay mastering = 1;
//                       ContentLightLevel content_light = 2; }
//
// Both fields are `Option`: presence-encoded length-delimited
// sub-messages, omitted entirely when `None`. (A present-but-default
// inner message still round-trips because each inner type's own
// codec is round-trip-safe and presence is carried by the tag.)
// ----------------------------------------------------------------------------

impl DefaultInstance for HdrStaticMetadata {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<HdrStaticMetadata> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(HdrStaticMetadata::default()))
  }
}

impl Message for HdrStaticMetadata {
  fn compute_size(&self, cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    if let Some(md) = self.mastering() {
      let slot = cache.reserve();
      let inner = md.compute_size(cache);
      cache.set(slot, inner);
      size += 1 + varint_len(inner as u64) as u32 + inner;
    }
    if let Some(cll) = self.content_light() {
      let slot = cache.reserve();
      let inner = cll.compute_size(cache);
      cache.set(slot, inner);
      size += 1 + varint_len(inner as u64) as u32 + inner;
    }
    size
  }

  fn write_to(&self, cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    if let Some(md) = self.mastering() {
      Tag::new(1, WireType::LengthDelimited).encode(buf);
      encode_varint(cache.consume_next() as u64, buf);
      md.write_to(cache, buf);
    }
    if let Some(cll) = self.content_light() {
      Tag::new(2, WireType::LengthDelimited).encode(buf);
      encode_varint(cache.consume_next() as u64, buf);
      cll.write_to(cache, buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let mut md = self.mastering().unwrap_or_default();
        buffa::Message::merge_length_delimited(&mut md, buf, ctx)?;
        self.set_mastering(Some(md));
      }
      2 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let mut cll = self.content_light().unwrap_or_default();
        buffa::Message::merge_length_delimited(&mut cll, buf, ctx)?;
        self.set_content_light(Some(cll));
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = HdrStaticMetadata::default();
  }
}

// ============================================================================
// Audio + container types — see the `## Audio + container types`
// sub-section of the module doc block at the top of this file for
// the full wire layout.
// ============================================================================

// ----------------------------------------------------------------------------
// String-bearing enum codec helper.
//
// One-field message `{ string value = 1; }` where `value` is the
// `as_str()` slug — the crate's one wire shape for a name vocabulary.
// Default-elision: written iff `*self != $default_expr`. For enums with
// a `Default` that is a named variant, that default elides and an absent
// field decodes back to it; for enums without one, the "default" is the
// wire-zero state (empty string → `Other("")`).
// ----------------------------------------------------------------------------

macro_rules! impl_string_enum_message {
  ($ty:ty, $default_expr:expr) => {
    impl DefaultInstance for $ty {
      fn default_instance() -> &'static Self {
        static VALUE: buffa::__private::OnceBox<$ty> = buffa::__private::OnceBox::new();
        VALUE.get_or_init(|| buffa::alloc::boxed::Box::new($default_expr))
      }
    }

    impl Message for $ty {
      fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
        // Default-elision: the decoder seeds from the same default, so an
        // absent field decodes back to it exactly. Every other value —
        // including the empty slug where that is not the default —
        // writes its name.
        if *self != $default_expr {
          1 + string_encoded_len(self.as_str()) as u32
        } else {
          0
        }
      }

      fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
        if *self != $default_expr {
          Tag::new(1, WireType::LengthDelimited).encode(buf);
          encode_string(self.as_str(), buf);
        }
      }

      fn merge_field(
        &mut self,
        tag: Tag,
        buf: &mut impl Buf,
        ctx: DecodeContext<'_>,
      ) -> Result<(), DecodeError> {
        match tag.field_number() {
          1 => {
            if tag.wire_type() != WireType::LengthDelimited {
              return Err(DecodeError::WireTypeMismatch {
                field_number: 1,
                expected: LEN,
                actual: tag.wire_type() as u8,
              });
            }
            let s = decode_string(buf)?;
            // Every vocabulary routed through this macro parses totally at
            // the `buffa` tier (`buffa` implies `alloc`, which is exactly
            // where each one's `Other` arm lives), so `FromStr::Err` is
            // `Infallible` and this binding is irrefutable. That is the
            // point of spelling it this way: add a type here whose parse
            // can refuse and this line stops compiling (`E0005`) instead
            // of silently acquiring an `unreachable!()` that is only
            // unreachable by argument.
            let Ok(parsed) = <$ty as core::str::FromStr>::from_str(&s);
            *self = parsed;
          }
          _ => skip_field_depth(tag, buf, ctx.depth())?,
        }
        Ok(())
      }

      fn clear(&mut self) {
        *self = $default_expr;
      }
    }
  };
}

// Closed-vocabulary string-bearing enums. They don't have a
// `Default` impl, so the decoder seed is the wire-zero `Other("")`
// (round-trips losslessly through the slug codec).
impl_string_enum_message!(ChannelLayout, ChannelLayout::Other(SmolStr::new_inline("")));
impl_string_enum_message!(
  ContainerFormat,
  ContainerFormat::Other(SmolStr::new_inline(""))
);
impl_string_enum_message!(Format, Format::Other(SmolStr::new_inline("")));

// Name vocabularies with a real `Default`: the seed is that default, and
// every value writes its slug. `Unknown(u32)` is gone, so a number is no
// longer a spelling any of these has.
impl_string_enum_message!(Matrix, Matrix::default());
impl_string_enum_message!(Primaries, Primaries::default());
impl_string_enum_message!(Transfer, Transfer::default());
impl_string_enum_message!(DynamicRange, DynamicRange::default());
impl_string_enum_message!(ChromaLocation, ChromaLocation::default());
impl_string_enum_message!(DcpTargetGamut, DcpTargetGamut::default());
impl_string_enum_message!(Rotation, Rotation::default());
impl_string_enum_message!(FieldOrder, FieldOrder::default());
impl_string_enum_message!(StereoMode, StereoMode::default());
impl_string_enum_message!(PixelFormat, PixelFormat::default());
impl_string_enum_message!(SampleFormat, SampleFormat::default());

// ----------------------------------------------------------------------------
// BitRateMode — { uint32 value = 1; }
//
// `BitRateMode::default() == Cbr` whose `to_u32() == 0`, so proto3
// zero-elision is sound: an absent field decodes via
// `from_u32(0) == Cbr`.
// ----------------------------------------------------------------------------

impl DefaultInstance for BitRateMode {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<BitRateMode> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(BitRateMode::default()))
  }
}

impl Message for BitRateMode {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let v = self.to_u32();
    if v != 0 {
      1 + uint32_encoded_len(v) as u32
    } else {
      0
    }
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    let v = self.to_u32();
    if v != 0 {
      Tag::new(1, WireType::Varint).encode(buf);
      encode_uint32(v, buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        *self = BitRateMode::from_u32(decode_uint32(buf)?);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = BitRateMode::default();
  }
}

// ----------------------------------------------------------------------------
// Loudness — four `float` fields (Fixed32 wire). Default is
// all-zero, which is proto-zero for `f32`, so proto3 zero-elision is
// sound throughout.
// ----------------------------------------------------------------------------

const FIXED32: u8 = WireType::Fixed32 as u8;

impl DefaultInstance for Loudness {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Loudness> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Loudness::default()))
  }
}

impl Message for Loudness {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // proto3 zero-elision: sound — every field defaults to 0.0
    // (proto-zero for `f32`).
    if self.integrated_lufs() != 0.0 {
      size += 1 + FIXED32_ENCODED_LEN as u32;
    }
    if self.range_lu() != 0.0 {
      size += 1 + FIXED32_ENCODED_LEN as u32;
    }
    if self.true_peak_dbtp() != 0.0 {
      size += 1 + FIXED32_ENCODED_LEN as u32;
    }
    if self.sample_peak_dbfs() != 0.0 {
      size += 1 + FIXED32_ENCODED_LEN as u32;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    if self.integrated_lufs() != 0.0 {
      Tag::new(1, WireType::Fixed32).encode(buf);
      encode_float(self.integrated_lufs(), buf);
    }
    if self.range_lu() != 0.0 {
      Tag::new(2, WireType::Fixed32).encode(buf);
      encode_float(self.range_lu(), buf);
    }
    if self.true_peak_dbtp() != 0.0 {
      Tag::new(3, WireType::Fixed32).encode(buf);
      encode_float(self.true_peak_dbtp(), buf);
    }
    if self.sample_peak_dbfs() != 0.0 {
      Tag::new(4, WireType::Fixed32).encode(buf);
      encode_float(self.sample_peak_dbfs(), buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      n @ 1..=4 => {
        if tag.wire_type() != WireType::Fixed32 {
          return Err(DecodeError::WireTypeMismatch {
            field_number: n,
            expected: FIXED32,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_float(buf)?;
        match n {
          1 => {
            self.set_integrated_lufs(v);
          }
          2 => {
            self.set_range_lu(v);
          }
          3 => {
            self.set_true_peak_dbtp(v);
          }
          4 => {
            self.set_sample_peak_dbfs(v);
          }
          _ => unreachable!(),
        }
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = Loudness::default();
  }
}

// ----------------------------------------------------------------------------
// ReplayGain — `track_gain_db` / `track_peak` are `float` with proto3
// zero-elision (Default is all-zero == proto-zero for f32). The two
// album-level scalars are `optional float` so a distribution-absent
// album-level number round-trips as `None` (wire field absent rather
// than zero). All four are wire-type `Fixed32` (4 bytes LE).
// ----------------------------------------------------------------------------

impl DefaultInstance for ReplayGain {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<ReplayGain> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(ReplayGain::default()))
  }
}

impl Message for ReplayGain {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // proto3 zero-elision on the two `float` fields.
    if self.track_gain_db() != 0.0 {
      size += 1 + FIXED32_ENCODED_LEN as u32;
    }
    if self.track_peak() != 0.0 {
      size += 1 + FIXED32_ENCODED_LEN as u32;
    }
    // `optional float` — present iff `Some` (independent of value).
    if self.album_gain_db().is_some() {
      size += 1 + FIXED32_ENCODED_LEN as u32;
    }
    if self.album_peak().is_some() {
      size += 1 + FIXED32_ENCODED_LEN as u32;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    if self.track_gain_db() != 0.0 {
      Tag::new(1, WireType::Fixed32).encode(buf);
      encode_float(self.track_gain_db(), buf);
    }
    if self.track_peak() != 0.0 {
      Tag::new(2, WireType::Fixed32).encode(buf);
      encode_float(self.track_peak(), buf);
    }
    if let Some(v) = self.album_gain_db() {
      Tag::new(3, WireType::Fixed32).encode(buf);
      encode_float(v, buf);
    }
    if let Some(v) = self.album_peak() {
      Tag::new(4, WireType::Fixed32).encode(buf);
      encode_float(v, buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      n @ 1..=4 => {
        if tag.wire_type() != WireType::Fixed32 {
          return Err(DecodeError::WireTypeMismatch {
            field_number: n,
            expected: FIXED32,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_float(buf)?;
        match n {
          1 => {
            self.set_track_gain_db(v);
          }
          2 => {
            self.set_track_peak(v);
          }
          3 => {
            self.set_album_gain_db(Some(v));
          }
          4 => {
            self.set_album_peak(Some(v));
          }
          _ => unreachable!(),
        }
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = ReplayGain::default();
  }
}

// ----------------------------------------------------------------------------
// Fingerprint — { string algorithm = 1; bytes value = 2; }
//
// `try_new` rejects empty `algorithm`, so the type has no
// natural-zero `Default`. The decoder seed is a synthetic
// `Fingerprint { algorithm: "default", value: [] }` (the
// always-encoded `algorithm` overwrites it on decode). `algorithm`
// is encoded UNCONDITIONALLY; `value` (bytes) uses proto3
// zero-elision (empty fingerprint is a legal value).
// ----------------------------------------------------------------------------

fn audio_fingerprint_seed() -> Fingerprint {
  // Safety: the literal is non-empty so `try_new` cannot fail.
  Fingerprint::try_new(SmolStr::new_inline("default"), std::vec::Vec::new())
    .unwrap_or_else(|_| unreachable!())
}

impl DefaultInstance for Fingerprint {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Fingerprint> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(audio_fingerprint_seed()))
  }
}

impl Message for Fingerprint {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let mut size = 1 + string_encoded_len(self.algorithm()) as u32;
    if !self.value().is_empty() {
      size += 1 + bytes_encoded_len(self.value()) as u32;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    Tag::new(1, WireType::LengthDelimited).encode(buf);
    encode_string(self.algorithm(), buf);
    if !self.value().is_empty() {
      Tag::new(2, WireType::LengthDelimited).encode(buf);
      encode_bytes(self.value(), buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let algo = decode_string(buf)?;
        // Empty algorithm on the wire is malformed (the type
        // invariant forbids it); clamp to the seed's `"default"`
        // sentinel to keep decode total.
        let algo = if algo.is_empty() {
          SmolStr::new_inline("default")
        } else {
          SmolStr::new(&algo)
        };
        // Preserve existing `value`, swap `algorithm`. `try_new`
        // moves the bytes back in unchanged.
        let value = self.value().to_vec();
        *self = Fingerprint::try_new(algo, value).unwrap_or_else(|_| audio_fingerprint_seed());
      }
      2 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let bytes = decode_bytes(buf)?;
        // Preserve `algorithm`, replace `value`.
        let algo = SmolStr::from(self.algorithm());
        *self = Fingerprint::try_new(algo, bytes).unwrap_or_else(|_| audio_fingerprint_seed());
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = audio_fingerprint_seed();
  }
}

// ----------------------------------------------------------------------------
// CoverArt — { string mime = 1; bytes data = 2; }
//
// `try_new` rejects empty mime / empty data, so the type has no
// natural-zero `Default`. Decoder seed is a synthetic
// `CoverArt { mime: "application/octet-stream", data: [0u8] }`
// (sentinel that gets overwritten on decode; both fields are
// ALWAYS encoded on the write path).
// ----------------------------------------------------------------------------

fn audio_cover_art_seed() -> CoverArt {
  CoverArt::try_new(
    SmolStr::new_static("application/octet-stream"),
    std::vec![0u8],
  )
  .unwrap_or_else(|_| unreachable!())
}

impl DefaultInstance for CoverArt {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<CoverArt> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(audio_cover_art_seed()))
  }
}

impl Message for CoverArt {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    2 + string_encoded_len(self.mime()) as u32 + bytes_encoded_len(self.data()) as u32
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    Tag::new(1, WireType::LengthDelimited).encode(buf);
    encode_string(self.mime(), buf);
    Tag::new(2, WireType::LengthDelimited).encode(buf);
    encode_bytes(self.data(), buf);
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let mime = decode_string(buf)?;
        // Empty mime on the wire violates the invariant; clamp to
        // the sentinel to keep decode total.
        let mime = if mime.is_empty() {
          SmolStr::new_static("application/octet-stream")
        } else {
          SmolStr::new(&mime)
        };
        let data = self.data().to_vec();
        let data = if data.is_empty() {
          std::vec![0u8]
        } else {
          data
        };
        *self = CoverArt::try_new(mime, data).unwrap_or_else(|_| audio_cover_art_seed());
      }
      2 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let data = decode_bytes(buf)?;
        // Empty data on the wire violates the invariant; clamp to
        // the single-byte sentinel.
        let data = if data.is_empty() {
          std::vec![0u8]
        } else {
          data
        };
        let mime = SmolStr::from(self.mime());
        *self = CoverArt::try_new(mime, data).unwrap_or_else(|_| audio_cover_art_seed());
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = audio_cover_art_seed();
  }
}

// ----------------------------------------------------------------------------
// Tags — every string field uses proto3 zero-elision ("" ==
// "absent" by the type's own convention); every numeric Option<u16>
// is widened to uint32 and uses proto3 zero-elision. `Some(0)`
// (theoretically legal) and `None` (absent) round-trip identically
// to `None` — documented limitation.
// ----------------------------------------------------------------------------

impl DefaultInstance for Tags {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Tags> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Tags::default()))
  }
}

impl Message for Tags {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    if !self.title().is_empty() {
      size += 1 + string_encoded_len(self.title()) as u32;
    }
    if !self.artist().is_empty() {
      size += 1 + string_encoded_len(self.artist()) as u32;
    }
    if !self.album_artist().is_empty() {
      size += 1 + string_encoded_len(self.album_artist()) as u32;
    }
    if !self.album().is_empty() {
      size += 1 + string_encoded_len(self.album()) as u32;
    }
    if !self.composer().is_empty() {
      size += 1 + string_encoded_len(self.composer()) as u32;
    }
    if !self.genre().is_empty() {
      size += 1 + string_encoded_len(self.genre()) as u32;
    }
    if !self.comment().is_empty() {
      size += 1 + string_encoded_len(self.comment()) as u32;
    }
    // Numeric fields are bare `u16` with `0` = absent — proto3 zero-elision
    // applies directly (no `Option` to unwrap).
    if self.year() != 0 {
      size += 1 + uint32_encoded_len(self.year() as u32) as u32;
    }
    if self.track_number() != 0 {
      size += 1 + uint32_encoded_len(self.track_number() as u32) as u32;
    }
    if self.track_total() != 0 {
      size += 1 + uint32_encoded_len(self.track_total() as u32) as u32;
    }
    if self.disc_number() != 0 {
      size += 1 + uint32_encoded_len(self.disc_number() as u32) as u32;
    }
    if self.disc_total() != 0 {
      size += 1 + uint32_encoded_len(self.disc_total() as u32) as u32;
    }
    if let Some(lang) = self.language() {
      size += 1 + string_encoded_len(&lang.to_bcp47()) as u32;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    if !self.title().is_empty() {
      Tag::new(1, WireType::LengthDelimited).encode(buf);
      encode_string(self.title(), buf);
    }
    if !self.artist().is_empty() {
      Tag::new(2, WireType::LengthDelimited).encode(buf);
      encode_string(self.artist(), buf);
    }
    if !self.album_artist().is_empty() {
      Tag::new(3, WireType::LengthDelimited).encode(buf);
      encode_string(self.album_artist(), buf);
    }
    if !self.album().is_empty() {
      Tag::new(4, WireType::LengthDelimited).encode(buf);
      encode_string(self.album(), buf);
    }
    if !self.composer().is_empty() {
      Tag::new(5, WireType::LengthDelimited).encode(buf);
      encode_string(self.composer(), buf);
    }
    if !self.genre().is_empty() {
      Tag::new(6, WireType::LengthDelimited).encode(buf);
      encode_string(self.genre(), buf);
    }
    if !self.comment().is_empty() {
      Tag::new(7, WireType::LengthDelimited).encode(buf);
      encode_string(self.comment(), buf);
    }
    if self.year() != 0 {
      Tag::new(8, WireType::Varint).encode(buf);
      encode_uint32(self.year() as u32, buf);
    }
    if self.track_number() != 0 {
      Tag::new(9, WireType::Varint).encode(buf);
      encode_uint32(self.track_number() as u32, buf);
    }
    if self.track_total() != 0 {
      Tag::new(10, WireType::Varint).encode(buf);
      encode_uint32(self.track_total() as u32, buf);
    }
    if self.disc_number() != 0 {
      Tag::new(11, WireType::Varint).encode(buf);
      encode_uint32(self.disc_number() as u32, buf);
    }
    if self.disc_total() != 0 {
      Tag::new(12, WireType::Varint).encode(buf);
      encode_uint32(self.disc_total() as u32, buf);
    }
    if let Some(lang) = self.language() {
      Tag::new(13, WireType::LengthDelimited).encode(buf);
      encode_string(&lang.to_bcp47(), buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    let n = tag.field_number();
    match n {
      1..=7 | 13 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: n,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let s = decode_string(buf)?;
        let s = SmolStr::new(&s);
        match n {
          1 => {
            self.set_title(s);
          }
          2 => {
            self.set_artist(s);
          }
          3 => {
            self.set_album_artist(s);
          }
          4 => {
            self.set_album(s);
          }
          5 => {
            self.set_composer(s);
          }
          6 => {
            self.set_genre(s);
          }
          7 => {
            self.set_comment(s);
          }
          13 => {
            // An empty field-13 string means "no language tag" (`None`);
            // a non-empty value parses as BCP-47, coercing an unparseable
            // tag to `Language::default()` (`und`) — the same lenient
            // semantics the standalone `Language` codec uses (buffa 0.6's
            // `DecodeError` has no general "invalid value" arm).
            self.update_language(if s.is_empty() {
              None
            } else {
              Some(Language::from_bcp47(&s).unwrap_or_default())
            });
          }
          _ => unreachable!(),
        }
      }
      8..=12 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: n,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        // Numeric fields are bare `u16` with `0` = absent — a decoded `0`
        // (or an elided, never-written field) is simply `0`.
        let v = decode_uint32(buf)? as u16;
        match n {
          8 => {
            self.set_year(v);
          }
          9 => {
            self.set_track_number(v);
          }
          10 => {
            self.set_track_total(v);
          }
          11 => {
            self.set_disc_number(v);
          }
          12 => {
            self.set_disc_total(v);
          }
          _ => unreachable!(),
        }
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = Tags::default();
  }
}

// ----------------------------------------------------------------------------
// TrackDisposition — { uint32 bits = 1; }
// Default is the empty flag set (`bits() == 0`), so proto3 zero-elision is
// sound: an absent field decodes back to `TrackDisposition::empty()`. The
// `from_u32` (= `from_bits_retain`) decoder preserves every bit, so unknown
// bits introduced in a future FFmpeg release round-trip losslessly.
// ----------------------------------------------------------------------------

impl DefaultInstance for TrackDisposition {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<TrackDisposition> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(TrackDisposition::default()))
  }
}

impl Message for TrackDisposition {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    // proto3 zero-elision: sound — default is the empty flag set
    // (`bits() == 0`).
    if self.to_u32() != 0 {
      1 + uint32_encoded_len(self.to_u32()) as u32
    } else {
      0
    }
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    if self.to_u32() != 0 {
      Tag::new(1, WireType::Varint).encode(buf);
      encode_uint32(self.to_u32(), buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Varint {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: VARINT,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_uint32(buf)?;
        *self = TrackDisposition::from_u32(v);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = TrackDisposition::default();
  }
}

// ----------------------------------------------------------------------------
// TrackOrigin + Format live in `crate::subtitle`, which is
// `cfg`-gated on the `alloc` feature (the `Other(SmolStr)` escape on
// `Format`). Mirror that gate on the wire impls so a
// `--no-default-features --features buffa` build (no `alloc`) still compiles.
// ----------------------------------------------------------------------------

#[cfg(any(feature = "std", feature = "alloc"))]
mod subtitle_impls {
  use super::*;
  use ::buffa::types::{decode_string, encode_string, string_encoded_len};
  use core::str::FromStr;

  use crate::subtitle::{Format, TrackOrigin};

  // ----------------------------------------------------------------------------
  // TrackOrigin — { string value = 1; }
  // Open since 0.5.0 (`Other(SmolStr)`), so there is no total numeric id;
  // encodes the slug from `as_str()`, exactly like `Format` below.
  // Always-encoded (NOT default-elision): the empty string decodes to
  // `Other("")`, a distinct legal value, so eliding would conflate it with
  // an absent field.
  // ----------------------------------------------------------------------------

  impl DefaultInstance for TrackOrigin {
    fn default_instance() -> &'static Self {
      static VALUE: buffa::__private::OnceBox<TrackOrigin> = buffa::__private::OnceBox::new();
      VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(TrackOrigin::default()))
    }
  }

  impl Message for TrackOrigin {
    fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
      // Always-encode the slug — see the wire-format note above.
      1 + string_encoded_len(self.as_str()) as u32
    }

    fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
      Tag::new(1, WireType::LengthDelimited).encode(buf);
      encode_string(self.as_str(), buf);
    }

    fn merge_field(
      &mut self,
      tag: Tag,
      buf: &mut impl Buf,
      ctx: DecodeContext<'_>,
    ) -> Result<(), DecodeError> {
      match tag.field_number() {
        1 => {
          if tag.wire_type() != WireType::LengthDelimited {
            return Err(DecodeError::WireTypeMismatch {
              field_number: 1,
              expected: LEN,
              actual: tag.wire_type() as u8,
            });
          }
          let s = decode_string(buf)?;
          // `FromStr for TrackOrigin` is `Infallible` (total — every
          // string decodes either to a named variant or to `Other(_)`),
          // so there is no failure branch to write.
          let Ok(parsed) = TrackOrigin::from_str(&s);
          *self = parsed;
        }
        _ => skip_field_depth(tag, buf, ctx.depth())?,
      }
      Ok(())
    }

    fn clear(&mut self) {
      *self = TrackOrigin::default();
    }
  }

  // ----------------------------------------------------------------------------
  // Format — { string value = 1; }
  // No stable numeric id; encodes the FFmpeg-style slug from `as_str()`.
  // Always-encoded (NOT proto3 zero-elision and NOT default-elision): the
  // empty string is `Other("")` on decode (per the total `FromStr`), which
  // is a distinct, legal value — eliding the field would conflate it with
  // an absent field. Writing the slug unconditionally side-steps the
  // ambiguity; on decode an absent field stays at the encoder's seed
  // (`Default::default()` = `Other("")`, defined ungated in
  // `crate::subtitle::format` — available regardless of the `buffa`
  // feature).
  // ----------------------------------------------------------------------------

  impl DefaultInstance for Format {
    fn default_instance() -> &'static Self {
      static VALUE: buffa::__private::OnceBox<Format> = buffa::__private::OnceBox::new();
      VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Format::default()))
    }
  }

  impl Message for Format {
    fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
      // Always-encode the slug — see the module-level wire-format note
      // for the rationale (empty slug is `Other("")` ≠ absent).
      let slug = self.as_str();
      1 + string_encoded_len(slug) as u32
    }

    fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
      let slug = self.as_str();
      Tag::new(1, WireType::LengthDelimited).encode(buf);
      encode_string(slug, buf);
    }

    fn merge_field(
      &mut self,
      tag: Tag,
      buf: &mut impl Buf,
      ctx: DecodeContext<'_>,
    ) -> Result<(), DecodeError> {
      match tag.field_number() {
        1 => {
          if tag.wire_type() != WireType::LengthDelimited {
            return Err(DecodeError::WireTypeMismatch {
              field_number: 1,
              expected: LEN,
              actual: tag.wire_type() as u8,
            });
          }
          let s = decode_string(buf)?;
          // `FromStr for Format` is `Infallible` (total — every
          // string decodes either to a named variant or to `Other(_)`).
          let Ok(parsed) = Format::from_str(&s);
          *self = parsed;
        }
        _ => skip_field_depth(tag, buf, ctx.depth())?,
      }
      Ok(())
    }

    fn clear(&mut self) {
      *self = Format::default();
    }
  }
}

// ============================================================================
// Capture + language — `alloc`-gated wire impls. See the
// "## Capture + language" section in the module-level doc for the
// wire-format spec.
// ============================================================================

// ----------------------------------------------------------------------------
// Device — { string make = 1; string model = 2; }
// Default is two empty strings == proto-zero, so proto3 zero-elision
// is sound. Empty string is the in-rust sentinel for "absent".
// ----------------------------------------------------------------------------

#[cfg(any(feature = "std", feature = "alloc"))]
impl DefaultInstance for Device {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Device> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Device::default()))
  }
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl Message for Device {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let mut size = 0u32;
    // proto3 zero-elision: sound — seed is two empty strings.
    if !self.make().is_empty() {
      size += 1 + string_encoded_len(self.make()) as u32;
    }
    if !self.model().is_empty() {
      size += 1 + string_encoded_len(self.model()) as u32;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    // proto3 zero-elision: sound — see `compute_size`.
    if !self.make().is_empty() {
      Tag::new(1, WireType::LengthDelimited).encode(buf);
      encode_string(self.make(), buf);
    }
    if !self.model().is_empty() {
      Tag::new(2, WireType::LengthDelimited).encode(buf);
      encode_string(self.model(), buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let s = decode_string(buf)?;
        self.set_make(s.as_str());
      }
      2 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let s = decode_string(buf)?;
        self.set_model(s.as_str());
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = Device::default();
  }
}

// ----------------------------------------------------------------------------
// GeoLocation — { double lat = 1; double lon = 2; float altitude = 3; }
//
// `lat` and `lon` are always encoded: the default `(0.0, 0.0)` is
// "Null Island" — a real, legal coordinate. Proto3 zero-elision would
// conflate it with an absent field, which is unsound (same defensive
// `mediatime::Timebase` stance as `SampleAspectRatio`).
//
// `altitude` is presence-encoded: field #3 is written iff
// `Some(_)`, including for an explicit `Some(0.0)` (sea level); an
// absent field #3 on the wire decodes back to `None`. No companion
// presence bit is needed because the encoder is the sole writer.
// ----------------------------------------------------------------------------

#[cfg(any(feature = "std", feature = "alloc"))]
impl DefaultInstance for GeoLocation {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<GeoLocation> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| {
      buffa::alloc::boxed::Box::new(GeoLocation::try_new(0.0, 0.0, None).expect("0,0 is valid"))
    })
  }
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl Message for GeoLocation {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    // lat (Fixed64) + lon (Fixed64), always encoded: 1-byte tag + 8 bytes each.
    let mut size = (1 + 8) + (1 + 8);
    if self.altitude().is_some() {
      // altitude (Fixed32): 1-byte tag + 4 bytes.
      size += 1 + 4;
    }
    size
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    Tag::new(1, WireType::Fixed64).encode(buf);
    encode_double(self.lat(), buf);
    Tag::new(2, WireType::Fixed64).encode(buf);
    encode_double(self.lon(), buf);
    if let Some(alt) = self.altitude() {
      Tag::new(3, WireType::Fixed32).encode(buf);
      encode_float(alt, buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::Fixed64 {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: WireType::Fixed64 as u8,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_double(buf)?;
        let prev = *self;
        // Range-clamp at the boundary: a malformed wire value
        // outside [-90, 90] is replaced with the closest valid
        // extreme so decode is total (mirrors the
        // `SampleAspectRatio` `den == 0` → `1` defensive clamp).
        let lat = if v.is_finite() {
          v.clamp(-90.0, 90.0)
        } else {
          0.0
        };
        *self =
          GeoLocation::try_new(lat, prev.lon(), prev.altitude()).expect("clamped lat is in range");
      }
      2 => {
        if tag.wire_type() != WireType::Fixed64 {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 2,
            expected: WireType::Fixed64 as u8,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_double(buf)?;
        let prev = *self;
        let lon = if v.is_finite() {
          v.clamp(-180.0, 180.0)
        } else {
          0.0
        };
        *self =
          GeoLocation::try_new(prev.lat(), lon, prev.altitude()).expect("clamped lon is in range");
      }
      3 => {
        if tag.wire_type() != WireType::Fixed32 {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 3,
            expected: WireType::Fixed32 as u8,
            actual: tag.wire_type() as u8,
          });
        }
        let v = decode_float(buf)?;
        self.set_altitude(v);
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = GeoLocation::try_new(0.0, 0.0, None).expect("0,0 is valid");
  }
}

// ----------------------------------------------------------------------------
// Language — { string value = 1; }
//
// Encodes the canonical BCP-47 string at field #1. proto3
// zero-elision applies to the empty string; since `Language::default()`
// is the BCP-47 `"und"` tag (non-empty), the encoder always writes
// it. On decode, an absent field (empty buffer / unknown-field skip)
// seeds back to `Default` = `"und"`. A wire value that fails BCP-47
// parsing is rejected as `DecodeError::Other`.
// ----------------------------------------------------------------------------

#[cfg(any(feature = "std", feature = "alloc"))]
impl DefaultInstance for Language {
  fn default_instance() -> &'static Self {
    static VALUE: buffa::__private::OnceBox<Language> = buffa::__private::OnceBox::new();
    VALUE.get_or_init(|| buffa::alloc::boxed::Box::new(Language::default()))
  }
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl Message for Language {
  fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
    let tag = self.to_bcp47();
    if tag.is_empty() {
      0
    } else {
      1 + string_encoded_len(&tag) as u32
    }
  }

  fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
    let tag = self.to_bcp47();
    if !tag.is_empty() {
      Tag::new(1, WireType::LengthDelimited).encode(buf);
      encode_string(&tag, buf);
    }
  }

  fn merge_field(
    &mut self,
    tag: Tag,
    buf: &mut impl Buf,
    ctx: DecodeContext<'_>,
  ) -> Result<(), DecodeError> {
    match tag.field_number() {
      1 => {
        if tag.wire_type() != WireType::LengthDelimited {
          return Err(DecodeError::WireTypeMismatch {
            field_number: 1,
            expected: LEN,
            actual: tag.wire_type() as u8,
          });
        }
        let s = decode_string(buf)?;
        // A wire value that doesn't parse as BCP-47 is mapped to
        // `Language::default()` (the ISO 639-3 `"und"`
        // "undetermined" sentinel) rather than failing the decode —
        // that is the same semantics the type uses in-rust for
        // "no usable language tag", and keeps the decoder total.
        // The `DecodeError` enum in buffa 0.6 has no general
        // "invalid value" arm, so silent coercion to the
        // already-existing sentinel is the least-bad choice.
        *self = Language::from_bcp47(&s).unwrap_or_default();
      }
      _ => skip_field_depth(tag, buf, ctx.depth())?,
    }
    Ok(())
  }

  fn clear(&mut self) {
    *self = Language::default();
  }
}

#[cfg(test)]
mod tests;