llama-cpp-native 0.31.0

llama.cpp built from its sources with CMake, the native library llama-cpp-bindings-sys links against
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
#include "mtmd.h"
#include "mtmd-helper.h"
#include "mtmd-helper-common.h"
#include "llama.h"
#include "../src/llama-ext.h"

#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstring>
#include <functional>
#include <memory>
#include <random>
#include <string>
#include <unordered_map>
#include <vector>

#ifdef MTMD_INTERNAL_HEADER
#error "mtmd-helper is a public library outside of mtmd. it must not include internal headers"
#endif

//
// Audio generation helpers
//

// --tts-lang codes -> language names used by the codec_language special tokens
static const std::unordered_map<std::string, std::string> tts_lang_codes = {
    { "zh", "chinese"    },
    { "en", "english"    },
    { "de", "german"     },
    { "it", "italian"    },
    { "pt", "portuguese" },
    { "es", "spanish"    },
    { "ja", "japanese"   },
    { "ko", "korean"     },
    { "fr", "french"     },
    { "ru", "russian"    },
};

static std::string tts_resolve_lang(const std::string & lang) {
    auto it = tts_lang_codes.find(lang);
    return it != tts_lang_codes.end() ? it->second : lang;
}

static llama_token find_special_token(const llama_vocab * vocab, const std::string & piece) {
    const int32_t n = llama_vocab_n_tokens(vocab);
    for (llama_token t = 0; t < n; t++) {
        if (piece == llama_vocab_get_text(vocab, t)) {
            return t;
        }
    }
    return LLAMA_TOKEN_NULL;
}

static void put_bytes(std::vector<char> & buf, const void * p, size_t n) {
    const char * c = (const char *) p;
    buf.insert(buf.end(), c, c + n);
}

// data_sz == UINT32_MAX writes the "unknown length" sentinel (streaming), same as ffmpeg does on a pipe
static void write_wav16_header(std::vector<char> & buf, uint32_t data_sz, int32_t rate) {
    const uint32_t riff_sz   = data_sz == UINT32_MAX ? UINT32_MAX : 36 + data_sz;
    const uint32_t fmt_sz    = 16, byte_rate = (uint32_t) rate * 2;
    const uint16_t fmt = 1, ch = 1, align = 2, bits = 16;
    const uint32_t rate32    = (uint32_t) rate;
    put_bytes(buf, "RIFF", 4); put_bytes(buf, &riff_sz, 4); put_bytes(buf, "WAVE", 4);
    put_bytes(buf, "fmt ", 4); put_bytes(buf, &fmt_sz, 4);
    put_bytes(buf, &fmt, 2); put_bytes(buf, &ch, 2); put_bytes(buf, &rate32, 4);
    put_bytes(buf, &byte_rate, 4); put_bytes(buf, &align, 2); put_bytes(buf, &bits, 2);
    put_bytes(buf, "data", 4); put_bytes(buf, &data_sz, 4);
}

static void append_wav16_pcm(std::vector<char> & buf, const float * pcm, size_t n) {
    for (size_t i = 0; i < n; i++) {
        int16_t s = (int16_t) std::lround(std::max(-1.0f, std::min(1.0f, pcm[i])) * 32767.0f);
        put_bytes(buf, &s, 2);
    }
}

static bool write_wav16(std::vector<char> & buf, const std::vector<float> & pcm, int32_t rate) {
    // RIFF chunk sizes are 32-bit; refuse to emit a file with a truncated header
    if (pcm.size() > ((size_t) UINT32_MAX - 36) / 2) {
        return false;
    }
    write_wav16_header(buf, (uint32_t) (pcm.size() * 2), rate);
    append_wav16_pcm(buf, pcm.data(), pcm.size());
    return true;
}

class mtmd_gen_audio_pipeline {
public:
    mtmd_gen_audio_pipeline(llama_context * lctx, mtmd_context * mctx)
        : lctx(lctx), mctx(mctx), model(llama_get_model(lctx)), vocab(llama_model_get_vocab(model)),
          n_embd(llama_model_n_embd(model)), info(mtmd_gen_audio_get_info(mctx)) {}
    virtual ~mtmd_gen_audio_pipeline() = default;

    virtual void reset() = 0;
    virtual int32_t set_input(const mtmd_helper_gen_audio_inp * inp) = 0;
    // decodes at most n_batch prompt tokens; returns remaining count (0 = done), <0 on error
    virtual int32_t step_prompt(int32_t n_batch) = 0;
    // sampled can be LLAMA_TOKEN_NULL for pipelines with no discrete backbone token,
    // those read what they need from h_state_in instead
    // set out_stop on end-of-speech, h_state_out must be null if no frame is generated
    virtual int32_t step_gen(llama_token sampled, const float * h_state_in, const float ** h_state_out, bool * out_stop) = 0;
    virtual int32_t get_output(int32_t * out_sample_rate, const char ** out_data, size_t * out_data_len, int64_t * out_n_samples) = 0;
    // forces any buffered codes through code2wav now, regardless of window_frames
    virtual int32_t flush() = 0;
    // continuing a sequence (inp->n_past > 0) with the model's own text/audio switching
    virtual bool supports_continue() const { return false; }
    virtual bool next_is_text() const { return false; }

    std::vector<llama_logit_bias> logit_bias; // see mtmd_helper_gen_audio_get_logit_bias()

protected:
    // one state per generation, so a fixed seed always gives the same output
    bool init_gen_state(uint32_t seed) {
        mtmd_gen_state_params params = mtmd_gen_state_params_default();
        params.seed = seed;
        gen_state.reset(mtmd_gen_state_init(mctx, params));
        if (!gen_state) {
            LOG_ERR("mtmd_helper_gen_audio: failed to create the gen state\n");
            return false;
        }
        return true;
    }

    // encodes a speaker clip or a voice, out receives the encoder embeddings
    bool encode_speaker(mtmd_bitmap * bitmap, std::vector<float> & out) {
        if (!mtmd_bitmap_is_voice(bitmap) && !mtmd_support_audio(mctx)) {
            LOG_ERR("mtmd_helper_gen_audio: mmproj has no speaker/audio encoder\n");
            return false;
        }
        const std::string  marker = mtmd_get_marker(mctx);
        mtmd_input_text     text{ marker.c_str(), marker.size(), false, true };
        mtmd_input_chunks * chunks = mtmd_input_chunks_init();
        const mtmd_bitmap * bptr = bitmap;
        bool ok = mtmd_tokenize(mctx, chunks, &text, &bptr, 1) == 0;
        if (ok) {
            ok = false;
            for (size_t i = 0; i < mtmd_input_chunks_size(chunks); i++) {
                const mtmd_input_chunk * chunk = mtmd_input_chunks_get(chunks, i);
                if (mtmd_input_chunk_get_type(chunk) != MTMD_INPUT_CHUNK_TYPE_AUDIO) {
                    continue;
                }
                if (mtmd_encode_chunk(mctx, chunk) != 0) {
                    LOG_ERR("mtmd_helper_gen_audio: speaker encode failed\n");
                    break;
                }
                const float * embd = mtmd_get_output_embd(mctx);
                const size_t  n = (size_t) llama_model_n_embd_inp(model) * mtmd_input_chunk_get_n_tokens(chunk);
                out.assign(embd, embd + n);
                ok = true;
                break;
            }
        }
        mtmd_input_chunks_free(chunks);
        return ok;
    }

    llama_context * lctx;
    mtmd_context  * mctx;
    const llama_model * model;
    const llama_vocab  * vocab;
    int n_embd;
    mtmd_gen_audio_info info;
    mtmd::gen_state_ptr gen_state;
};

// Qwen3-TTS: backbone samples codec_0, code_predictor gives the other 15 codebooks,
// then code2wav decodes them to PCM
class qwen3tts_gen_audio_pipeline : public mtmd_gen_audio_pipeline {
public:
    using mtmd_gen_audio_pipeline::mtmd_gen_audio_pipeline;

    void reset() override {
        seq_id = 0;
        pos = 0;
        codes_buf.clear();
        gen_state.reset();
        audio_pcm.clear();
        overlay.clear();
        h_state_buf.clear();
        out_buf.clear();
        prompt_embd_buf.clear();
        prompt_batch.reset();
        n_prompt = 0;
        prompt_pos = 0;
        stream = false;
        pcm_sent = 0;
        wav_header_sent = false;
    }

    int32_t set_input(const mtmd_helper_gen_audio_inp * inp) override {
        reset();
        seq_id = inp->seq_id;

        if (!ensure_cache()) {
            return 1;
        }

        const std::string lang   = tts_resolve_lang((inp->lang && inp->lang[0]) ? inp->lang : "english");
        const llama_token c_lang = find_special_token(vocab, ("<|codec_language_" + lang + "|>").c_str());
        if (c_lang == LLAMA_TOKEN_NULL) {
            LOG_ERR("mtmd_helper_gen_audio: unknown language '%s'\n", lang.c_str());
            return 1;
        }

        std::vector<float> speaker_embd;
        if (inp->speaker_ref) {
            if (!encode_speaker(inp->speaker_ref, speaker_embd)) {
                return 1;
            }
        }

        const int n_e = n_embd;
        auto row = [&](llama_token t) {
            return std::vector<float>(tok_embd.begin() + (size_t) t * n_e,
                                       tok_embd.begin() + (size_t) (t + 1) * n_e);
        };
        auto sum_row = [&](llama_token a, llama_token b) {
            std::vector<float> va = row(a), vb = row(b);
            for (int i = 0; i < n_e; i++) va[(size_t) i] += vb[(size_t) i];
            return va;
        };
        auto sum_vec = [&](llama_token a, const std::vector<float> & vb) {
            std::vector<float> va = row(a);
            for (int i = 0; i < n_e; i++) va[(size_t) i] += vb[(size_t) i];
            return va;
        };

        // upstream chat wrap, then slices: [0:3] role, [3:-5] utterance body
        const std::string full = "<|im_start|>assistant\n" + std::string(inp->prompt, inp->prompt_len) +
                                  "<|im_end|>\n<|im_start|>assistant\n";
        std::vector<llama_token> ids(full.size() + 16);
        int n_ids = llama_tokenize(vocab, full.c_str(), (int32_t) full.size(), ids.data(), (int32_t) ids.size(),
                                   false, true);
        if (n_ids < 8) {
            LOG_ERR("mtmd_helper_gen_audio: tokenization failed\n");
            return 1;
        }
        ids.resize((size_t) n_ids);

        std::vector<std::vector<float>> prompt;
        for (int i = 0; i < 3; i++) prompt.push_back(row(ids[(size_t) i]));
        prompt.push_back(sum_row(tts_pad, c_think));
        prompt.push_back(sum_row(tts_pad, c_think_b));
        prompt.push_back(sum_row(tts_pad, c_lang));
        prompt.push_back(sum_row(tts_pad, c_think_e));
        if (!speaker_embd.empty()) prompt.push_back(sum_vec(tts_pad, speaker_embd));
        prompt.push_back(sum_row(tts_bos, codec_pad));
        for (int i = 3; i < n_ids - 5; i++) prompt.push_back(sum_row(ids[(size_t) i], codec_pad));
        prompt.push_back(sum_row(tts_eos, codec_pad));
        prompt.push_back(sum_row(tts_pad, codec_bos));

        n_prompt = (int) prompt.size();

        // the talker uses the qwen3vl interleaved mrope, all sections are equal for a text/codec stream
        mrope = llama_model_rope_type(model) == LLAMA_ROPE_TYPE_MROPE ||
                llama_model_rope_type(model) == LLAMA_ROPE_TYPE_IMROPE;
        const int n_pos_per_embd = mrope ? 4 : 1;

        prompt_embd_buf.resize((size_t) n_prompt * (size_t) n_e);
        for (int i = 0; i < n_prompt; i++) {
            memcpy(prompt_embd_buf.data() + (size_t) i * n_e, prompt[(size_t) i].data(), (size_t) n_e * sizeof(float));
        }

        prompt_batch.reset(new decode_embd_batch(prompt_embd_buf.data(), n_prompt, n_pos_per_embd, n_e));
        if (mrope) prompt_batch->set_position_mrope_1d(0, seq_id);
        else       prompt_batch->set_position_normal  (0, seq_id);
        prompt_pos = 0;

        pos = 0;
        const mtmd_gen_inp def = mtmd_gen_inp_default(mctx);
        top_k = inp->top_k > 0 ? inp->top_k : def.top_k;
        top_p = inp->top_p > 0 ? inp->top_p : def.top_p;
        out_type = inp->out_type;
        stream = inp->stream;
        if (!init_gen_state(inp->seed)) {
            return 1;
        }

        // the prompt above holds the whole text stream up to tts_eos, so every generated
        // frame adds tts_pad on top of the codes embedding
        overlay = row(tts_pad);

        return 0;
    }

    int32_t step_prompt(int32_t n_batch) override {
        GGML_ASSERT(n_batch > 0);
        if (prompt_pos >= n_prompt) {
            return 0;
        }
        const int32_t n_tokens_batch = std::min(n_batch, n_prompt - prompt_pos);

        const bool is_last_batch = (prompt_pos + n_tokens_batch) == n_prompt;
        if (is_last_batch) {
            prompt_batch->logits[prompt_pos + n_tokens_batch - 1] = 1;
        }

        if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, prompt_batch->render(lctx, prompt_pos, n_tokens_batch)) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: prompt decode failed\n");
            return -1;
        }

        pos        += n_tokens_batch;
        prompt_pos += n_tokens_batch;

        if (prompt_pos >= n_prompt) {
            // prompt fully processed, its embedding buffer is no longer needed
            prompt_batch.reset();
            prompt_embd_buf.clear();
            return 0;
        }
        return n_prompt - prompt_pos;
    }

    int32_t step_gen(llama_token sampled, const float * h_state_in, const float ** h_state_out, bool * out_stop) override {
        if (sampled == LLAMA_TOKEN_NULL) {
            LOG_ERR("mtmd_helper_gen_audio: qwen3tts requires a token sampled from the backbone\n");
            return 1;
        }

        // backbone signals end-of-speech with a token, no frame for this step
        if (sampled == codec_eos || llama_vocab_is_eog(vocab, sampled)) {
            *out_stop    = true;
            *h_state_out = nullptr;
            return 0;
        }

        mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
        inp.type  = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
        inp.code0 = sampled - codec_0;
        inp.embd  = const_cast<float *>(h_state_in);
        inp.top_k = top_k;
        inp.top_p = top_p;
        mtmd_gen_out out{};
        if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: gen_code process failed\n");
            return 1;
        }

        codes_buf.insert(codes_buf.end(), out.codes, out.codes + out.n_codes);
        if (out.n_codes > 0 && codes_buf.size() / out.n_codes >= window_frames) {
            if (!flush_gen_wav()) {
                return 1;
            }
        }

        std::vector<float> fb(out.embd, out.embd + n_embd);
        for (int i = 0; i < n_embd; i++) fb[(size_t) i] += overlay[(size_t) i];

        const int n_pos_per_embd = mrope ? 4 : 1;
        decode_embd_batch batch_embd(fb.data(), 1, n_pos_per_embd, n_embd);
        if (mrope) batch_embd.set_position_mrope_1d(pos, seq_id);
        else       batch_embd.set_position_normal  (pos, seq_id);
        batch_embd.logits[0] = 1;
        pos++;

        if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch_embd.render(lctx, 0, 1)) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: decode failed\n");
            return 1;
        }

        const float * he = llama_get_embeddings_ith(lctx, -1);
        h_state_buf.assign(he, he + n_embd);
        *h_state_out = h_state_buf.data();

        return 0;
    }

    int32_t get_output(int32_t * out_sample_rate, const char ** out_data, size_t * out_data_len, int64_t * out_n_samples) override {
        *out_sample_rate = info.sample_rate;

        if (!stream) {
            // one-shot call: force out whatever's left, regardless of window_frames
            if (!flush_gen_wav()) {
                return 1;
            }
            if (out_n_samples) {
                *out_n_samples = (int64_t) audio_pcm.size();
            }
            if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
                *out_data     = (const char *) audio_pcm.data();
                *out_data_len = audio_pcm.size() * sizeof(float);
                return 0;
            }
            out_buf.clear();
            if (!write_wav16(out_buf, audio_pcm, info.sample_rate)) {
                LOG_ERR("mtmd_helper_gen_audio: output too large for WAV\n");
                return 1;
            }
            *out_data     = out_buf.data();
            *out_data_len = out_buf.size();
            return 0;
        }

        // streaming: only return audio produced since the previous call
        const size_t n_new = audio_pcm.size() - pcm_sent;
        if (out_n_samples) {
            *out_n_samples = (int64_t) n_new;
        }

        if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
            *out_data     = (const char *) (audio_pcm.data() + pcm_sent);
            *out_data_len = n_new * sizeof(float);
            pcm_sent = audio_pcm.size();
            return 0;
        }

        out_buf.clear();
        if (!wav_header_sent) {
            write_wav16_header(out_buf, UINT32_MAX, info.sample_rate);
            wav_header_sent = true;
        }
        append_wav16_pcm(out_buf, audio_pcm.data() + pcm_sent, n_new);
        pcm_sent = audio_pcm.size();
        *out_data     = out_buf.data();
        *out_data_len = out_buf.size();
        return 0;
    }

    int32_t flush() override {
        return flush_gen_wav() ? 0 : 1;
    }

private:
    bool ensure_cache() {
        if (specials_ok) {
            return true;
        }
        codec_0   = find_special_token(vocab, "<|codec_0|>");
        codec_bos = find_special_token(vocab, "<|codec_bos|>");
        codec_eos = find_special_token(vocab, "<|codec_eos_token|>");
        codec_pad = find_special_token(vocab, "<|codec_pad|>");
        c_think   = find_special_token(vocab, "<|codec_think|>");
        c_think_b = find_special_token(vocab, "<|codec_think_bos|>");
        c_think_e = find_special_token(vocab, "<|codec_think_eos|>");
        tts_pad   = find_special_token(vocab, "<tts_pad>");
        tts_bos   = find_special_token(vocab, "<tts_text_bos>");
        tts_eos   = find_special_token(vocab, "<tts_text_eod>");
        for (llama_token t : { codec_0, codec_bos, codec_eos, codec_pad,
                               c_think, c_think_b, c_think_e,
                               tts_pad, tts_bos, tts_eos }) {
            if (t == LLAMA_TOKEN_NULL) {
                LOG_ERR("mtmd_helper_gen_audio: missing a required special token in vocab\n");
                return false;
            }
        }
        const uint32_t n_tok_embd = llama_model_get_tok_embd(model, nullptr);
        if (n_tok_embd == 0) {
            LOG_ERR("mtmd_helper_gen_audio: model has no token embeddings\n");
            return false;
        }
        tok_embd.resize(n_tok_embd);
        if (llama_model_get_tok_embd(model, tok_embd.data()) != n_tok_embd) {
            LOG_ERR("mtmd_helper_gen_audio: token embedding copy failed\n");
            return false;
        }
        specials_ok = true;
        return true;
    }

    // one GEN_WAV process() call over the buffered codes, state is carried across batches
    bool flush_gen_wav() {
        if (codes_buf.empty()) {
            return true;
        }
        mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
        inp.type       = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
        inp.codes      = codes_buf.data();
        inp.n_codes    = codes_buf.size();
        mtmd_gen_out out{};
        if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: gen_wav process failed\n");
            return false;
        }
        audio_pcm.insert(audio_pcm.end(), out.audio, out.audio + out.n_samples);
        codes_buf.clear();
        return true;
    }

    // vocab specials fixed across the whole session, looked up once
    bool specials_ok = false;
    llama_token codec_0    = LLAMA_TOKEN_NULL;
    llama_token codec_bos  = LLAMA_TOKEN_NULL;
    llama_token codec_eos  = LLAMA_TOKEN_NULL;
    llama_token codec_pad  = LLAMA_TOKEN_NULL;
    llama_token c_think    = LLAMA_TOKEN_NULL;
    llama_token c_think_b  = LLAMA_TOKEN_NULL;
    llama_token c_think_e  = LLAMA_TOKEN_NULL;
    llama_token tts_pad    = LLAMA_TOKEN_NULL;
    llama_token tts_bos    = LLAMA_TOKEN_NULL;
    llama_token tts_eos    = LLAMA_TOKEN_NULL;
    std::vector<float> tok_embd; // whole token embedding matrix, n_vocab * n_embd

    // must match hparams.wav_tfm_swa hardcoded in mtmd-model.cpp
    size_t window_frames = 72;

    // per-generation state, cleared by reset()
    llama_seq_id seq_id = 0;
    bool mrope = false;
    int pos = 0;
    // prompt decode state, consumed batch-by-batch by step_prompt()
    std::vector<float> prompt_embd_buf;
    std::unique_ptr<decode_embd_batch> prompt_batch;
    int n_prompt = 0;
    int prompt_pos = 0;
    int32_t  top_k = 50;
    float    top_p = 1.0f;
    std::vector<int32_t> codes_buf;
    std::vector<float>   audio_pcm;
    std::vector<float> overlay;
    std::vector<float> h_state_buf;
    mtmd_helper_gen_audio_outtype out_type = MTMD_HELPER_GEN_AUDIO_OUTTYPE_WAV;
    std::vector<char> out_buf;
    bool   stream          = false;
    size_t pcm_sent        = 0; // samples already returned by get_output()
    bool   wav_header_sent = false;
};

// settings that only live in the reference's per-pack yaml, not in the checkpoint
// the english packs share the same shapes and tokenizer, but disagree on these
// both are 0 / false when the pack does not tune them, the model default is then used
struct pockettts_pack_settings {
    int  frames_after_eos = 0;
    bool pad_short_text   = false;
};

static pockettts_pack_settings pockettts_pack(const char * variant) {
    static const std::unordered_map<std::string, pockettts_pack_settings> packs = {
        { "english",         { 0, false } },
        { "english_2026-01", { 0, true  } },
        { "english_2026-04", { 0, false } },
        { "french_24l",      { 8, false } },
        { "italian",         { 0, false } },
    };
    auto it = packs.find(variant ? variant : "");
    if (it == packs.end()) {
        LOG_WRN("mtmd_helper_gen_audio: no tuned settings for pocket-tts variant \"%s\"\n",
                variant ? variant : "");
        return {};
    }
    return it->second;
}

// pocket-tts: the backbone emits no token, the flow net turns each hidden state into a latent
// the end-of-speech head also lives in the mmproj
class pockettts_gen_audio_pipeline : public mtmd_gen_audio_pipeline {
public:
    using mtmd_gen_audio_pipeline::mtmd_gen_audio_pipeline;

    void reset() override {
        seq_id = 0;
        pos = 0;
        feats_buf.clear();
        gen_state.reset();
        audio_pcm.clear();
        h_state_buf.clear();
        out_buf.clear();
        prompt_embd_buf.clear();
        prompt_batch.reset();
        n_prompt = 0;
        prompt_pos = 0;
        step_idx = 0;
        eos_step = -1;
        chunks.clear();
        chunk_idx = 0;
        n_voice_pos = 0;
        chunk_budget = 0;
        stream = false;
        pcm_sent = 0;
        wav_header_sent = false;
    }

    int32_t set_input(const mtmd_helper_gen_audio_inp * inp) override {
        reset();
        seq_id = inp->seq_id;

        if (!ensure_cache()) {
            return 1;
        }

        std::vector<float> voice;
        if (inp->speaker_ref) {
            if (!encode_speaker(inp->speaker_ref, voice)) {
                return 1;
            }
        }

        pack = pockettts_pack(info.model_variant);

        const std::string text = prepare_text(std::string(inp->prompt, inp->prompt_len),
                                              pack.pad_short_text);
        if (text.empty()) {
            LOG_ERR("mtmd_helper_gen_audio: empty prompt\n");
            return 1;
        }

        std::vector<llama_token> ids(text.size() + 16);
        int n_ids = llama_tokenize(vocab, text.c_str(), (int32_t) text.size(), ids.data(),
                                   (int32_t) ids.size(), false, false);
        if (n_ids <= 0) {
            LOG_ERR("mtmd_helper_gen_audio: tokenization failed\n");
            return 1;
        }
        ids.resize((size_t) n_ids);

        // long inputs degrade badly, so each chunk restarts from the voice conditioning
        // see split_into_best_sentences() in the reference
        chunks = split_chunks(ids);
        chunk_idx = 0;
        if (chunks.size() > 1) {
            LOG_INF("mtmd_helper_gen_audio: %d tokens split into %zu chunks\n", n_ids, chunks.size());
        }

        const int n_e = n_embd;

        // sequence order is voice, then text, then the audio BOS that starts generation
        if (!voice.empty()) {
            GGML_ASSERT(voice.size() % (size_t) n_e == 0);
            if (bos_before_voice != LLAMA_TOKEN_NULL) {
                push_embd_row(prompt_embd_buf, bos_before_voice);
            }
            prompt_embd_buf.insert(prompt_embd_buf.end(), voice.begin(), voice.end());
        }
        // every later chunk rewinds to here and re-prompts, so the voice stays primed
        n_voice_pos = (int) (prompt_embd_buf.size() / (size_t) n_e);

        for (llama_token t : chunks[0]) {
            push_embd_row(prompt_embd_buf, t);
        }
        push_embd_row(prompt_embd_buf, audio_bos);
        arm_chunk_budget(0);

        n_prompt = (int) (prompt_embd_buf.size() / (size_t) n_e);
        prompt_batch.reset(new decode_embd_batch(prompt_embd_buf.data(), n_prompt, 1, n_e));
        prompt_batch->set_position_normal(0, seq_id);
        prompt_pos = 0;

        temp     = inp->temp;
        out_type = inp->out_type;
        stream   = inp->stream;
        if (!init_gen_state(inp->seed)) {
            return 1;
        }

        return 0;
    }

    int32_t step_prompt(int32_t n_batch) override {
        GGML_ASSERT(n_batch > 0);
        if (prompt_pos >= n_prompt) {
            return 0;
        }
        const int32_t n_tokens_batch = std::min(n_batch, n_prompt - prompt_pos);

        if ((prompt_pos + n_tokens_batch) == n_prompt) {
            prompt_batch->logits[prompt_pos + n_tokens_batch - 1] = 1;
        }

        if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, prompt_batch->render(lctx, prompt_pos, n_tokens_batch)) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: prompt decode failed\n");
            return -1;
        }

        pos        += n_tokens_batch;
        prompt_pos += n_tokens_batch;

        if (prompt_pos >= n_prompt) {
            prompt_batch.reset();
            prompt_embd_buf.clear();
            return 0;
        }
        return n_prompt - prompt_pos;
    }

    int32_t step_gen(llama_token sampled, const float * h_state_in, const float ** h_state_out, bool * out_stop) override {
        (void) sampled; // the backbone output is continuous, there is no token to consume

        mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
        inp.type = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
        inp.embd = const_cast<float *>(h_state_in);
        if (temp >= 0.0f) {
            inp.temp = temp;
        }
        mtmd_gen_out out{};
        if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: flow decode failed\n");
            return 1;
        }
        if (out.is_eos && eos_step < 0) {
            eos_step = step_idx;
        }
        // the frame of the stopping step is discarded, matching _autoregressive_generation().
        // the budget is the reference's fallback for a chunk whose eos head never fires
        const bool chunk_done = (eos_step >= 0 && step_idx >= eos_step + frames_after_eos) ||
                                step_idx >= chunk_budget;
        if (chunk_done) {
            if (eos_step < 0) {
                LOG_WRN("mtmd_helper_gen_audio: chunk %zu hit its budget without end-of-speech\n", chunk_idx);
            }
            return finish_chunk(h_state_out, out_stop);
        }

        feats_buf.insert(feats_buf.end(), out.feats, out.feats + out.n_feats);
        step_idx++;
        if (out.n_feats > 0 && feats_buf.size() / out.n_feats >= window_frames) {
            if (!flush_gen_wav()) {
                return 1;
            }
        }

        decode_embd_batch batch_embd(out.embd, 1, 1, n_embd);
        batch_embd.set_position_normal(pos, seq_id);
        batch_embd.logits[0] = 1;
        pos++;

        if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch_embd.render(lctx, 0, 1)) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: decode failed\n");
            return 1;
        }

        const float * he = llama_get_embeddings_ith(lctx, -1);
        h_state_buf.assign(he, he + n_embd);
        *h_state_out = h_state_buf.data();

        return 0;
    }

    int32_t get_output(int32_t * out_sample_rate, const char ** out_data, size_t * out_data_len, int64_t * out_n_samples) override {
        *out_sample_rate = info.sample_rate;

        if (!stream) {
            // one-shot call: force out whatever's left, regardless of window_frames
            if (!flush_gen_wav()) {
                return 1;
            }
            if (out_n_samples) {
                *out_n_samples = (int64_t) audio_pcm.size();
            }
            if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
                *out_data     = (const char *) audio_pcm.data();
                *out_data_len = audio_pcm.size() * sizeof(float);
                return 0;
            }
            out_buf.clear();
            if (!write_wav16(out_buf, audio_pcm, info.sample_rate)) {
                LOG_ERR("mtmd_helper_gen_audio: output too large for WAV\n");
                return 1;
            }
            *out_data     = out_buf.data();
            *out_data_len = out_buf.size();
            return 0;
        }

        // streaming: only return audio produced since the previous call
        const size_t n_new = audio_pcm.size() - pcm_sent;
        if (out_n_samples) {
            *out_n_samples = (int64_t) n_new;
        }

        if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
            *out_data     = (const char *) (audio_pcm.data() + pcm_sent);
            *out_data_len = n_new * sizeof(float);
            pcm_sent = audio_pcm.size();
            return 0;
        }

        out_buf.clear();
        if (!wav_header_sent) {
            write_wav16_header(out_buf, UINT32_MAX, info.sample_rate);
            wav_header_sent = true;
        }
        append_wav16_pcm(out_buf, audio_pcm.data() + pcm_sent, n_new);
        pcm_sent = audio_pcm.size();
        *out_data     = out_buf.data();
        *out_data_len = out_buf.size();
        return 0;
    }

    int32_t flush() override {
        return flush_gen_wav() ? 0 : 1;
    }

private:
    bool ensure_cache() {
        if (specials_ok) {
            return true;
        }
        // bos_before_voice is optional, some packs do not insert it
        bos_before_voice = find_special_token(vocab, "<|bos_before_voice|>");
        audio_bos        = find_special_token(vocab, "<|audio_bos|>");
        if (audio_bos == LLAMA_TOKEN_NULL) {
            LOG_ERR("mtmd_helper_gen_audio: missing <|audio_bos|> in vocab\n");
            return false;
        }
        const uint32_t n_tok_embd = llama_model_get_tok_embd(model, nullptr);
        if (n_tok_embd == 0) {
            LOG_ERR("mtmd_helper_gen_audio: model has no token embeddings\n");
            return false;
        }
        tok_embd.resize(n_tok_embd);
        if (llama_model_get_tok_embd(model, tok_embd.data()) != n_tok_embd) {
            LOG_ERR("mtmd_helper_gen_audio: token embedding copy failed\n");
            return false;
        }
        GGML_ASSERT(n_embd > 0 && n_tok_embd % (uint32_t) n_embd == 0);
        specials_ok = true;
        return true;
    }

    // the table can be shorter than the vocab, so bound the row lookup
    void push_embd_row(std::vector<float> & dst, llama_token t) const {
        const size_t n_rows = tok_embd.size() / (size_t) n_embd;
        GGML_ASSERT(t >= 0 && (size_t) t < n_rows);
        dst.insert(dst.end(),
                   tok_embd.begin() + (size_t) t * n_embd,
                   tok_embd.begin() + (size_t) (t + 1) * n_embd);
    }

    // token ids of the pieces the reference splits on, see split_into_best_sentences().
    // the leading token is dropped, it is the tokenizer's dummy prefix
    std::vector<llama_token> punct_ids(const char * s) const {
        std::vector<llama_token> ids(16);
        const int n = llama_tokenize(vocab, s, (int32_t) strlen(s), ids.data(), (int32_t) ids.size(), false, false);
        if (n <= 1) {
            return {};
        }
        return std::vector<llama_token>(ids.begin() + 1, ids.begin() + n);
    }

    // cut after runs of boundary tokens, so punctuation stays with the sentence it ends
    static std::vector<std::vector<llama_token>> split_on(const std::vector<llama_token> & ids,
                                                          const std::vector<llama_token> & boundary) {
        std::vector<std::vector<llama_token>> out;
        size_t start = 0;
        bool prev_was_boundary = false;
        for (size_t i = 0; i < ids.size(); i++) {
            const bool is_boundary = std::find(boundary.begin(), boundary.end(), ids[i]) != boundary.end();
            if (!is_boundary && prev_was_boundary) {
                out.emplace_back(ids.begin() + start, ids.begin() + i);
                start = i;
            }
            prev_was_boundary = is_boundary;
        }
        out.emplace_back(ids.begin() + start, ids.end());
        return out;
    }

    std::vector<std::vector<llama_token>> split_chunks(const std::vector<llama_token> & ids) const {
        if ((int) ids.size() <= max_chunk_tokens) {
            return { ids };
        }
        const std::vector<llama_token> eos_punct = punct_ids(".!...?");
        const std::vector<llama_token> mid_punct = punct_ids(",;:");

        // oversized sentences are split again on weaker punctuation, else words get skipped
        std::vector<std::vector<llama_token>> segments;
        for (auto & seg : split_on(ids, eos_punct)) {
            if ((int) seg.size() <= max_chunk_tokens) {
                segments.push_back(std::move(seg));
                continue;
            }
            auto sub = split_on(seg, mid_punct);
            if (sub.size() > 1) {
                for (auto & s : sub) {
                    segments.push_back(std::move(s));
                }
            } else {
                segments.push_back(std::move(seg));
            }
        }

        std::vector<std::vector<llama_token>> out;
        for (auto & seg : segments) {
            if (seg.empty()) {
                continue;
            }
            if (!out.empty() && (int) (out.back().size() + seg.size()) <= max_chunk_tokens) {
                out.back().insert(out.back().end(), seg.begin(), seg.end());
            } else {
                out.push_back(std::move(seg));
            }
        }
        if (out.empty()) {
            out.push_back(ids);
        }
        for (const auto & c : out) {
            if ((int) c.size() > max_chunk_tokens) {
                LOG_WRN("mtmd_helper_gen_audio: chunk of %zu tokens exceeds the %d token budget, "
                        "generation may skip words\n", c.size(), max_chunk_tokens);
            }
        }
        return out;
    }

    // _estimate_max_gen_len() plus the per-chunk tail guess, both in frames
    void arm_chunk_budget(size_t idx) {
        const int n_tok = (int) chunks[idx].size();
        chunk_budget = (int) std::ceil((n_tok / 3.0 + 2.0) * frame_rate);
        // the pack may pin the tail, else the reference guesses it from the word count
        frames_after_eos = pack.frames_after_eos > 0 ? pack.frames_after_eos : (n_tok <= 6 ? 5 : 3);
        step_idx = 0;
        eos_step = -1;
    }

    // ends the current chunk and, if there is another, re-prompts it on top of the voice
    int32_t finish_chunk(const float ** h_state_out, bool * out_stop) {
        if (!flush_gen_wav()) {
            return 1;
        }
        // the decoder restarts too, the next chunk's audio is not continuous with this one
        mtmd_gen_state_reset(gen_state.get());

        if (chunk_idx + 1 >= chunks.size()) {
            *out_stop    = true;
            *h_state_out = nullptr;
            return 0;
        }
        chunk_idx++;

        // drop this chunk's text and audio, keep the voice conditioning
        llama_memory_seq_rm(llama_get_memory(lctx), seq_id, n_voice_pos, -1);
        pos = n_voice_pos;

        const int n_e = n_embd;
        prompt_embd_buf.clear();
        for (llama_token t : chunks[chunk_idx]) {
            push_embd_row(prompt_embd_buf, t);
        }
        push_embd_row(prompt_embd_buf, audio_bos);
        arm_chunk_budget(chunk_idx);

        const int n_rows = (int) (prompt_embd_buf.size() / (size_t) n_e);
        GGML_ASSERT(n_rows > 0);
        decode_embd_batch batch(prompt_embd_buf.data(), n_rows, 1, n_e);
        batch.set_position_normal(pos, seq_id);
        batch.logits[n_rows - 1] = 1;
        if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch.render(lctx, 0, n_rows)) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: chunk prompt decode failed\n");
            return 1;
        }
        pos += n_rows;
        prompt_embd_buf.clear();

        const float * he = llama_get_embeddings_ith(lctx, -1);
        h_state_buf.assign(he, he + n_embd);
        *h_state_out = h_state_buf.data();
        *out_stop    = false;
        return 0;
    }

    // same normalization as prepare_text_prompt() in the reference, it affects quality
    static std::string prepare_text(const std::string & in, bool pad_short) {
        std::string s;
        s.reserve(in.size() + 1);
        for (char c : in) {
            if (c == '\n' || c == '\r') {
                s += ' ';
            } else if (c == ';') {
                s += ',';
            } else {
                s += c;
            }
        }
        const size_t b = s.find_first_not_of(' ');
        const size_t e = s.find_last_not_of(' ');
        if (b == std::string::npos) {
            return "";
        }
        s = s.substr(b, e - b + 1);
        if (s[0] >= 'a' && s[0] <= 'z') {
            s[0] = (char) (s[0] - 'a' + 'A');
        }
        const unsigned char last = (unsigned char) s.back();
        if (std::isalnum(last)) {
            s += '.';
        }
        if (pad_short && count_words(s) < 5) {
            s = std::string(8, ' ') + s;
        }
        return s;
    }

    static int count_words(const std::string & s) {
        int n = 0;
        bool in_word = false;
        for (char c : s) {
            if (c == ' ') {
                in_word = false;
            } else if (!in_word) {
                in_word = true;
                n++;
            }
        }
        return n;
    }

    // decodes the buffered latents, the mimi decoder state carries over between calls
    bool flush_gen_wav() {
        if (feats_buf.empty()) {
            return true;
        }
        mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
        inp.type       = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
        inp.feats      = feats_buf.data();
        inp.n_feats    = feats_buf.size();
        mtmd_gen_out out{};
        if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: mimi decode failed\n");
            return false;
        }
        audio_pcm.insert(audio_pcm.end(), out.audio, out.audio + out.n_samples);
        feats_buf.clear();
        return true;
    }

    pockettts_pack_settings pack;
    float temp = -1.0f; // the caller's flow noise scale, < 0 for the model default
    bool specials_ok = false;
    llama_token bos_before_voice = LLAMA_TOKEN_NULL;
    llama_token audio_bos        = LLAMA_TOKEN_NULL;
    std::vector<float> tok_embd;

    llama_seq_id seq_id = 0;
    int pos = 0;
    std::vector<float> prompt_embd_buf;
    std::unique_ptr<decode_embd_batch> prompt_batch;
    int n_prompt = 0;
    int prompt_pos = 0;
    // end-of-speech is latched, then a few more frames are generated as tail padding
    int step_idx = 0;
    int eos_step = -1;
    int frames_after_eos = 3;
    static constexpr int max_chunk_tokens = 50;  // MAX_TOKEN_PER_CHUNK in the reference
    static constexpr double frame_rate    = 12.5;
    std::vector<std::vector<llama_token>> chunks;
    size_t chunk_idx   = 0;
    int    n_voice_pos = 0; // KV positions held by the voice conditioning
    int    chunk_budget = 0;

    // latents are decoded a window at a time, the decoder state bridges the windows
    size_t window_frames = 8;
    std::vector<float>   feats_buf;
    std::vector<float>   audio_pcm;
    std::vector<float>   h_state_buf;
    mtmd_helper_gen_audio_outtype out_type = MTMD_HELPER_GEN_AUDIO_OUTTYPE_WAV;
    std::vector<char> out_buf;
    bool   stream          = false;
    size_t pcm_sent        = 0; // samples already returned by get_output()
    bool   wav_header_sent = false;
};

// Soprano uses the hidden state that predicts each non-EOS token, including the prompt's last state.
class soprano_gen_audio_pipeline : public mtmd_gen_audio_pipeline {
public:
    using mtmd_gen_audio_pipeline::mtmd_gen_audio_pipeline;

    void reset() override {
        prompt.clear();
        features.clear();
        h_next.clear();
        audio.clear();
        wav.clear();
        pos = 0;
        prompt_pos = 0;
        decoded = false;
        sent = false;
    }

    int32_t set_input(const mtmd_helper_gen_audio_inp * inp) override {
        reset();
        if (inp->speaker_ref || !inp->prompt || inp->prompt_len == 0 || inp->prompt_len > INT32_MAX ||
            inp->seq_id < 0 || (uint32_t) inp->seq_id >= llama_n_seq_max(lctx)) {
            LOG_ERR("mtmd_helper_gen_audio: soprano requires text, without a speaker reference\n");
            return 1;
        }
        seq_id = inp->seq_id;
        out_type = inp->out_type;
        stream = inp->stream;
        const llama_token text = find_special_token(vocab, "[TEXT]");
        const llama_token start = find_special_token(vocab, "[START]");
        const llama_token stop = find_special_token(vocab, "[STOP]");
        if (text == LLAMA_TOKEN_NULL || start == LLAMA_TOKEN_NULL || stop == LLAMA_TOKEN_NULL) {
            LOG_ERR("mtmd_helper_gen_audio: incompatible soprano vocabulary\n");
            return 1;
        }
        const int required = llama_tokenize(vocab, inp->prompt, inp->prompt_len, nullptr, 0, false, false);
        if (required >= 0 || (uint32_t) (-required + 3) >= llama_n_ctx_seq(lctx)) {
            LOG_ERR("mtmd_helper_gen_audio: soprano prompt does not fit in the context\n");
            return 1;
        }
        const int n = -required;
        prompt.resize(n + 3);
        prompt[0] = stop;
        prompt[1] = text;
        if (llama_tokenize(vocab, inp->prompt, inp->prompt_len, prompt.data() + 2, n, false, false) != n) {
            return 1;
        }
        prompt.back() = start;
        if (!llama_memory_seq_rm(llama_get_memory(lctx), seq_id, 0, -1)) {
            LOG_ERR("mtmd_helper_gen_audio: cannot reset soprano sequence\n");
            return 1;
        }
        if (!init_gen_state(inp->seed)) {
            return 1;
        }
        return 0;
    }

    int32_t step_prompt(int32_t n_batch) override {
        if (n_batch <= 0 || prompt.empty()) {
            return -1;
        }
        const int n = std::min(n_batch, (int) prompt.size() - prompt_pos);
        if (n == 0) {
            return 0;
        }
        if (!decode(prompt.data() + prompt_pos, n)) {
            return -1;
        }
        prompt_pos += n;
        return (int) prompt.size() - prompt_pos;
    }

    int32_t step_gen(llama_token sampled, const float * h_state_in, const float ** h_state_out, bool * out_stop) override {
        *h_state_out = nullptr;
        *out_stop = false;
        if (sampled < 0 || sampled >= llama_vocab_n_tokens(vocab) || !h_state_in || prompt_pos != (int) prompt.size() || prompt.empty()) {
            return 1;
        }
        if (llama_vocab_is_eog(vocab, sampled) || (uint32_t) pos >= llama_n_ctx_seq(lctx)) {
            *out_stop = true;
            return 0;
        }
        features.insert(features.end(), h_state_in, h_state_in + n_embd);
        if (!decode(&sampled, 1)) {
            features.resize(features.size() - n_embd);
            return 1;
        }
        const float * h = llama_get_embeddings_ith(lctx, -1);
        if (!h) {
            return 1;
        }
        h_next.assign(h, h + n_embd);
        *h_state_out = h_next.data();
        return 0;
    }

    int32_t get_output(int32_t * sample_rate, const char ** data, size_t * data_len, int64_t * n_samples) override {
        *sample_rate = info.sample_rate;
        *data_len = 0;
        if (n_samples) { *n_samples = 0; }
        if (stream) {
            // the decoder needs the whole utterance, so the audio comes out in one chunk after flush()
            if (!decoded || sent) {
                return 0;
            }
            sent = true;
        } else if (!decode_audio()) {
            return 1;
        }
        if (n_samples) { *n_samples = audio.size(); }
        if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
            *data = (const char *) audio.data();
            *data_len = audio.size() * sizeof(float);
        } else {
            wav.clear();
            if (!write_wav16(wav, audio, info.sample_rate)) {
                return 1;
            }
            *data = wav.data();
            *data_len = wav.size();
        }
        return 0;
    }

    // the whole utterance is decoded at once
    int32_t flush() override {
        return decode_audio() ? 0 : 1;
    }

private:
    bool decode_audio() {
        if (decoded) {
            return true;
        }
        if (features.size() < 2 * (size_t) n_embd) {
            LOG_ERR("mtmd_helper_gen_audio: soprano needs at least two generated frames\n");
            return false;
        }
        mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
        inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
        inp.feats = features.data();
        inp.n_feats = features.size();
        mtmd_gen_out out{};
        if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) {
            return false;
        }
        audio.assign(out.audio, out.audio + out.n_samples);
        decoded = true;
        return true;
    }

    bool decode(llama_token * tokens, int n) {
        llama_batch batch = llama_batch_init(n, 0, 1);
        batch.n_tokens = n;
        for (int i = 0; i < n; ++i) {
            batch.token[i] = tokens[i];
            batch.pos[i] = pos + i;
            batch.n_seq_id[i] = 1;
            batch.seq_id[i][0] = seq_id;
            batch.logits[i] = i == n - 1;
        }
        const int ret = llama_decode(lctx, batch);
        llama_batch_free(batch);
        if (ret != 0) {
            LOG_ERR("mtmd_helper_gen_audio: soprano backbone decode failed\n");
            return false;
        }
        pos += n;
        return true;
    }

    llama_seq_id seq_id = 0;
    llama_pos pos = 0;
    int prompt_pos = 0;
    std::vector<llama_token> prompt;
    std::vector<float> features;
    std::vector<float> h_next;
    std::vector<float> audio;
    std::vector<char> wav;
    mtmd_helper_gen_audio_outtype out_type = MTMD_HELPER_GEN_AUDIO_OUTTYPE_WAV;
    bool stream  = false;
    bool decoded = false;
    bool sent    = false;
};

// LFM3-Audio TTS, see generate() in the reference: each step samples a frame of codes by MaskGIT
// and feeds its embedding back, the end-of-audio code stops
class lfm3a_gen_audio_pipeline : public mtmd_gen_audio_pipeline {
public:
    using mtmd_gen_audio_pipeline::mtmd_gen_audio_pipeline;

    void reset() override {
        seq_id = 0;
        pos = 0;
        continuing = false;
        mode = MODE_AUDIO;
        slots_left = 0;
        speaking = false;
        text_done = false;
        prompt_tokens.clear();
        prompt_pos = 0;
        hist.clear();
        gen_state.reset();
        pending_tail = false;
        pcm_sent = 0;
        wav_header_sent = false;
        audio_pcm.clear();
        h_state_buf.clear();
        out_buf.clear();
    }

    int32_t set_input(const mtmd_helper_gen_audio_inp * inp) override {
        reset();
        seq_id = inp->seq_id;

        // a voice is named in the prompt instead
        if (inp->speaker_ref && !mtmd_bitmap_is_voice(inp->speaker_ref)) {
            LOG_WRN("mtmd_helper_gen_audio: the model has no voice conditioning, the speaker file is ignored\n");
        }

        // the prompt is rendered by the caller: the "tts" chat template of the model, or the next turn of a conversation
        continuing = inp->n_past > 0;
        pos        = continuing ? inp->n_past : 0;
        const std::string full(inp->prompt, inp->prompt_len);
        prompt_tokens.resize(full.size() + 16);
        const int n_ids = llama_tokenize(vocab, full.c_str(), (int32_t) full.size(), prompt_tokens.data(),
                                         (int32_t) prompt_tokens.size(), false, true);
        if (n_ids <= 0) {
            LOG_ERR("mtmd_helper_gen_audio: tokenization failed\n");
            return 1;
        }
        prompt_tokens.resize((size_t) n_ids);

        if (!find_tokens()) {
            return 1;
        }
        // a continued response opens with the token of the asked mode, a text-only one cannot switch to audio
        if (continuing) {
            switch (inp->out_mode) {
                case MTMD_HELPER_GEN_AUDIO_OUT_AUDIO: prompt_tokens.push_back(tok_audio_start); break;
                case MTMD_HELPER_GEN_AUDIO_OUT_MIXED: prompt_tokens.push_back(tok_mixed_start); break;
                case MTMD_HELPER_GEN_AUDIO_OUT_TEXT:
                    logit_bias = { { tok_audio_start, -INFINITY }, { tok_mixed_start, -INFINITY } };
                    break;
                default: break;
            }
        }
        // the last prompt token picks the mode, see generate() of the reference
        const llama_token last = prompt_tokens.back();
        mode = last == tok_audio_start ? MODE_AUDIO : last == tok_mixed_start ? MODE_MIXED : MODE_TEXT;
        slots_left = n_text_block;
        if (!continuing && mode != MODE_AUDIO) {
            LOG_ERR("mtmd_helper_gen_audio: the prompt must come from the \"tts\" chat template of the model\n");
            return 1;
        }

        // the sampling defaults of the model, the caller can only override the temperature
        const mtmd_gen_inp def = mtmd_gen_inp_default(mctx);
        temp        = inp->temp >= 0.0f ? inp->temp : def.temp;
        top_k       = def.top_k;
        rep_penalty = def.penalty_repeat;
        rep_window  = def.penalty_last_n;

        out_type = inp->out_type;
        stream   = inp->stream;
        rng.seed(inp->seed == UINT32_MAX ? std::random_device{}() : inp->seed);
        return init_gen_state(inp->seed) ? 0 : 1;
    }

    int32_t step_prompt(int32_t n_batch) override {
        GGML_ASSERT(n_batch > 0);
        const int n_prompt = (int) prompt_tokens.size();
        if (prompt_pos >= n_prompt) {
            return 0;
        }
        const int n = std::min(n_batch, n_prompt - prompt_pos);
        llama_batch batch = llama_batch_init(n, 0, 1);
        for (int i = 0; i < n; i++) {
            batch.token   [i]    = prompt_tokens[(size_t) (prompt_pos + i)];
            batch.pos     [i]    = pos + i;
            batch.n_seq_id[i]    = 1;
            batch.seq_id  [i][0] = seq_id;
            batch.logits  [i]    = prompt_pos + i == n_prompt - 1;
        }
        batch.n_tokens = n;
        const int ret = llama_decode(lctx, batch);
        llama_batch_free(batch);
        if (ret != 0) {
            LOG_ERR("mtmd_helper_gen_audio: prompt decode failed\n");
            return -1;
        }
        pos        += n;
        prompt_pos += n;
        return n_prompt - prompt_pos;
    }

    bool supports_continue() const override {
        return true;
    }

    bool next_is_text() const override {
        return mode == MODE_TEXT || (mode == MODE_MIXED && !speaking);
    }

    // one generate() step: a text token from the caller or an audio frame from the hidden state
    int32_t step_gen(llama_token sampled, const float * h_state_in, const float ** h_state_out, bool * out_stop) override {
        const bool interleaving = mode == MODE_MIXED;
        if (next_is_text()) {
            // <|im_end|> ends the response in any text slot, <|text_end|> outside an interleaved block too
            if (sampled == tok_im_end || (!interleaving && sampled == tok_text_end)) {
                *out_stop    = true;
                *h_state_out = nullptr;
                return 0;
            }
            // the switching tokens are fed back like any text token
            if (!interleaving) {
                if (sampled == tok_audio_start) {
                    mode = MODE_AUDIO;
                } else if (sampled == tok_mixed_start) {
                    mode       = MODE_MIXED;
                    slots_left = n_text_block;
                    speaking   = false;
                    text_done  = false;
                }
            } else if (sampled == tok_text_end) {
                text_done = true;
                speaking  = true;
            }
            llama_batch batch = llama_batch_get_one(&sampled, 1);
            if (!decode(batch)) {
                return 1;
            }
        } else {
            std::vector<int32_t> codes;
            const float * fb = nullptr;
            bool is_eos = false;
            if (!sample_frame(h_state_in, codes, &fb, &is_eos)) {
                return 1;
            }
            if (is_eos) {
                if (!continuing) {
                    // TTS: the end of audio ends the generation
                    *out_stop    = true;
                    *h_state_out = nullptr;
                    return 0;
                }
                // the segment ends, the codec tail goes out and the response continues in text
                if (flush() != 0) {
                    return 1;
                }
                mode = MODE_TEXT;
            } else {
                hist.insert(hist.end(), codes.begin(), codes.end());
                if (!decode_wav(codes.data(), codes.size())) {
                    return 1;
                }
            }
            decode_embd_batch batch_embd(const_cast<float *>(fb), 1, 1, n_embd);
            batch_embd.set_position_normal(pos, seq_id);
            batch_embd.logits[0] = 1;
            if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch_embd.render(lctx, 0, 1)) != 0) {
                LOG_ERR("mtmd_helper_gen_audio: decode failed\n");
                return 1;
            }
            pos++;
        }

        // a slot emitted while interleaving counts down the block, the switching token itself does not
        if (interleaving && !text_done && --slots_left == 0) {
            speaking   = !speaking;
            slots_left = speaking ? n_audio_block : n_text_block;
        }

        const float * he = llama_get_embeddings_ith(lctx, -1);
        h_state_buf.assign(he, he + n_embd);
        *h_state_out = h_state_buf.data();
        return 0;
    }

    int32_t get_output(int32_t * out_sample_rate, const char ** out_data, size_t * out_data_len, int64_t * out_n_samples) override {
        *out_sample_rate = info.sample_rate;

        if (!stream) {
            if (flush() != 0) {
                return 1;
            }
            if (out_n_samples) {
                *out_n_samples = (int64_t) audio_pcm.size();
            }
            if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
                *out_data     = (const char *) audio_pcm.data();
                *out_data_len = audio_pcm.size() * sizeof(float);
                return 0;
            }
            out_buf.clear();
            if (!write_wav16(out_buf, audio_pcm, info.sample_rate)) {
                LOG_ERR("mtmd_helper_gen_audio: output too large for WAV\n");
                return 1;
            }
            *out_data     = out_buf.data();
            *out_data_len = out_buf.size();
            return 0;
        }

        // streaming: only the audio produced since the previous call, every frame is decoded as it is sampled
        const size_t n_new = audio_pcm.size() - pcm_sent;
        if (out_n_samples) {
            *out_n_samples = (int64_t) n_new;
        }
        if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
            *out_data     = (const char *) (audio_pcm.data() + pcm_sent);
            *out_data_len = n_new * sizeof(float);
            pcm_sent = audio_pcm.size();
            return 0;
        }
        out_buf.clear();
        if (!wav_header_sent) {
            write_wav16_header(out_buf, UINT32_MAX, info.sample_rate);
            wav_header_sent = true;
        }
        append_wav16_pcm(out_buf, audio_pcm.data() + pcm_sent, n_new);
        pcm_sent = audio_pcm.size();
        *out_data     = out_buf.data();
        *out_data_len = out_buf.size();
        return 0;
    }

    // the ISTFT holds back the overlap of the last frame
    int32_t flush() override {
        if (pending_tail) {
            if (!decode_wav(nullptr, 0)) {
                return 1;
            }
            pending_tail = false;
        }
        return 0;
    }

private:
    // checked by the converter
    static constexpr int   n_cb        = 12;
    static constexpr int   schedule[]  = { 4, 4, 4 }; // codebooks revealed per depthformer pass

    // a random order of the codebooks, revealed by the schedule; fb is the feedback embedding of the codes.
    // at the end of audio every code is the end code, its feedback embedding is only built when continuing
    bool sample_frame(const float * h_state, std::vector<int32_t> & codes, const float ** fb, bool * is_eos) {
        std::vector<int> order(n_cb);
        for (int i = 0; i < n_cb; i++) {
            order[(size_t) i] = i;
        }
        std::shuffle(order.begin(), order.end(), rng);

        codes.assign(n_cb, -1);
        mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
        inp.type    = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
        inp.embd    = const_cast<float *>(h_state);
        inp.codes   = codes.data();
        inp.n_codes = codes.size();
        mtmd_gen_out out{};

        int k = 0;
        for (int n_pick : schedule) {
            if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0 || out.n_feats == 0 || out.n_feats % n_cb != 0) {
                LOG_ERR("mtmd_helper_gen_audio: depthformer pass failed\n");
                return false;
            }
            const size_t n_vocab = out.n_feats / n_cb;
            logits.assign(out.feats, out.feats + out.n_feats);
            for (int j = 0; j < n_pick; j++, k++) {
                const int i = order[(size_t) k];
                float * l = logits.data() + (size_t) i * n_vocab;
                apply_rep_penalty(l, n_vocab, i);
                codes[(size_t) i] = sample(l, n_vocab);
            }
        }

        // the last code of every codebook ends the audio
        const int32_t eos = (int32_t) (logits.size() / n_cb) - 1;
        *is_eos = std::find(codes.begin(), codes.end(), eos) != codes.end();
        if (*is_eos) {
            codes.assign(n_cb, eos);
            if (!continuing) {
                *fb = nullptr;
                return true;
            }
        }

        // all codes known: only the feedback embedding
        if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: codebook embedding failed\n");
            return false;
        }
        fb_buf.assign(out.embd, out.embd + n_embd);
        *fb = fb_buf.data();
        return true;
    }

    // CTRL penalty over the codes codebook cb took in the last rep_window frames
    void apply_rep_penalty(float * l, size_t n_vocab, int cb) const {
        if (rep_penalty <= 1.0f || rep_window <= 0) {
            return;
        }
        const size_t n_hist = hist.size() / n_cb;
        const size_t n_win  = std::min(n_hist, (size_t) rep_window);
        std::vector<bool> seen(n_vocab, false);
        for (size_t f = n_hist - n_win; f < n_hist; f++) {
            const int32_t c = hist[f * n_cb + (size_t) cb];
            if (c >= 0 && (size_t) c < n_vocab && !seen[(size_t) c]) {
                seen[(size_t) c] = true;
                l[c] = l[c] > 0.0f ? l[c] / rep_penalty : l[c] * rep_penalty;
            }
        }
    }

    // TODO: reuse the samplers of common (top-k, temperature, penalties) instead of this one
    int32_t sample(const float * l, size_t n_vocab) {
        if (temp <= 0.0f) {
            return (int32_t) (std::max_element(l, l + n_vocab) - l);
        }
        // top-k keeps the codes scoring at least the k-th best, ties included
        float lmin = -INFINITY;
        if (top_k > 0 && (size_t) top_k < n_vocab) {
            std::vector<float> sorted(l, l + n_vocab);
            std::nth_element(sorted.begin(), sorted.begin() + (top_k - 1), sorted.end(), std::greater<float>());
            lmin = sorted[(size_t) top_k - 1];
        }
        const float lmax = *std::max_element(l, l + n_vocab);
        std::vector<double> prob(n_vocab);
        double sum = 0.0;
        for (size_t v = 0; v < n_vocab; v++) {
            prob[v] = l[v] < lmin ? 0.0 : std::exp((double) (l[v] - lmax) / temp);
            sum += prob[v];
        }
        double r = std::uniform_real_distribution<double>(0.0, 1.0)(rng) * sum;
        for (size_t v = 0; v < n_vocab; v++) {
            r -= prob[v];
            if (r <= 0.0) {
                return (int32_t) v;
            }
        }
        return (int32_t) n_vocab - 1;
    }

    // n_codes == 0 flushes the ISTFT tail
    bool decode_wav(const int32_t * codes, size_t n_codes) {
        mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
        inp.type       = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
        inp.codes      = const_cast<int32_t *>(codes);
        inp.n_codes    = n_codes;
        mtmd_gen_out out{};
        if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: codec decode failed\n");
            return false;
        }
        audio_pcm.insert(audio_pcm.end(), out.audio, out.audio + out.n_samples);
        pending_tail = n_codes > 0;
        return true;
    }

    bool find_tokens() {
        tok_audio_start = find_special_token(vocab, "<|audio_start|>");
        tok_mixed_start = find_special_token(vocab, "<|mixed_start|>");
        tok_text_end    = find_special_token(vocab, "<|text_end|>");
        tok_im_end      = find_special_token(vocab, "<|im_end|>");
        if (tok_audio_start == LLAMA_TOKEN_NULL || tok_mixed_start == LLAMA_TOKEN_NULL ||
            tok_text_end == LLAMA_TOKEN_NULL || tok_im_end == LLAMA_TOKEN_NULL) {
            LOG_ERR("mtmd_helper_gen_audio: missing LFM3-Audio control tokens in vocab\n");
            return false;
        }
        return true;
    }

    bool decode(llama_batch batch) {
        std::vector<llama_pos>      positions(batch.n_tokens);
        std::vector<int32_t>        n_seq(batch.n_tokens, 1);
        std::vector<llama_seq_id>   seq(batch.n_tokens, seq_id);
        std::vector<llama_seq_id *> seq_ptr(batch.n_tokens);
        std::vector<int8_t>         logits(batch.n_tokens, 1);
        for (int i = 0; i < batch.n_tokens; i++) {
            positions[i] = pos + i;
            seq_ptr[i]   = &seq[i];
        }
        batch.pos      = positions.data();
        batch.n_seq_id = n_seq.data();
        batch.seq_id   = seq_ptr.data();
        batch.logits   = logits.data();
        if (llama_decode(lctx, batch) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: decode failed\n");
            return false;
        }
        pos += batch.n_tokens;
        return true;
    }

    // generate() modes: text, audio until end of audio, interleaved until <|text_end|>
    enum gen_mode { MODE_TEXT, MODE_AUDIO, MODE_MIXED };
    // checked by the converter
    static constexpr int n_text_block  = 6;  // interleaved_n_text
    static constexpr int n_audio_block = 12; // interleaved_n_audio

    llama_token tok_audio_start = LLAMA_TOKEN_NULL;
    llama_token tok_mixed_start = LLAMA_TOKEN_NULL;
    llama_token tok_text_end    = LLAMA_TOKEN_NULL;
    llama_token tok_im_end      = LLAMA_TOKEN_NULL;

    bool     continuing = false; // the prompt continues a sequence, the response follows the model's switching
    gen_mode mode       = MODE_AUDIO;
    int      slots_left = 0;
    bool     speaking   = false; // interleaving: the current block is audio
    bool     text_done  = false; // interleaving: <|text_end|> was emitted, audio until the end-of-audio frame

    llama_seq_id seq_id = 0;
    int pos = 0;
    std::vector<llama_token> prompt_tokens;
    int prompt_pos = 0;

    float   temp        = 0.0f;
    int32_t top_k       = 0;
    float   rep_penalty = 1.0f;
    int32_t rep_window  = 0; // frames
    std::mt19937 rng;
    std::vector<float>   logits;
    std::vector<float>   fb_buf;
    std::vector<int32_t> hist; // frame-major codes of the frames so far

    bool pending_tail = false; // the ISTFT holds back the overlap of the last frame
    std::vector<float>   audio_pcm;
    std::vector<float>   h_state_buf;
    mtmd_helper_gen_audio_outtype out_type = MTMD_HELPER_GEN_AUDIO_OUTTYPE_WAV;
    std::vector<char> out_buf;
    bool   stream          = false;
    size_t pcm_sent        = 0;     // samples already returned by get_output()
    bool   wav_header_sent = false;
};

// Chatterbox: the backbone emits s3 speech tokens, then one flow-matching mel decode and the NSF-iSTFT vocoder make the PCM
// the multilingual variant runs cfg with an uncond sequence (text rows zeroed), paired as seq_id and n_seq_max / 2 + seq_id
class chatterbox_gen_audio_pipeline : public mtmd_gen_audio_pipeline {
public:
    using mtmd_gen_audio_pipeline::mtmd_gen_audio_pipeline;

    void reset() override {
        seq_id = 0;
        seq_uncond = 0;
        pos = 0;
        ar_idx = 0;
        codes_buf.clear();
        audio_pcm.clear();
        h_state_buf.clear();
        out_buf.clear();
        prompt_embd_buf.clear();
        uncond_embd_buf.clear();
        cond_logits.clear();
        n_prompt = 0;
        prompt_pos = 0;
        decoded = false;
        stream = false;
        pcm_sent = 0;
        wav_header_sent = false;
        gen_state.reset();
    }

    int32_t set_input(const mtmd_helper_gen_audio_inp * inp) override {
        reset();
        seq_id = inp->seq_id;

        if (!ensure_cache()) {
            return 1;
        }

        out_type = inp->out_type;
        stream   = inp->stream;
        if (!init_gen_state(inp->seed)) {
            return 1;
        }

        if (mtl) {
            // the uncond sequence lives half a seq space away from the cond one
            const int32_t n_seq_max = (int32_t) llama_n_seq_max(lctx);
            seq_uncond = (llama_seq_id) (n_seq_max / 2 + seq_id);
            if (!llama_model_classifier_free_guidance(llama_get_model(lctx)) || seq_id >= n_seq_max / 2) {
                LOG_ERR("mtmd_helper_gen_audio: multilingual chatterbox needs a backbone with classifier_free_guidance and a paired cfg sequence "
                        "(n_seq_max = %d, seq_id = %d)\n", n_seq_max, seq_id);
                return 1;
            }
        }
        llama_memory_t mem = llama_get_memory(lctx);
        if (!llama_memory_seq_rm(mem, seq_id, 0, -1) || (mtl && !llama_memory_seq_rm(mem, seq_uncond, 0, -1))) {
            LOG_ERR("mtmd_helper_gen_audio: cannot reset chatterbox sequences\n");
            return 1;
        }

        // the encode gives the talker conditioning rows, set_ref keeps the flow decoder reference
        if (!inp->speaker_ref) {
            LOG_ERR("mtmd_helper_gen_audio: chatterbox requires a speaker reference or a voice\n");
            return 1;
        }
        if (!encode_speaker(inp->speaker_ref, prompt_embd_buf) ||
            mtmd_gen_state_set_ref(mctx, gen_state.get()) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: speaker reference encoding failed\n");
            return 1;
        }

        const int n_e = n_embd;
        auto push_row = [&](const float * src) {
            prompt_embd_buf.insert(prompt_embd_buf.end(), src, src + n_e);
        };
        auto add_pos = [&](float * r, const std::vector<float> & tab, int idx) {
            const float * p = tab.data() + (size_t) idx * n_e;
            for (int j = 0; j < n_e; j++) {
                r[j] += p[j];
            }
        };

        // prompt rows: [conditioning, text, speech bos]
        // no text preprocessing here, the [SPACE] substitution and the case folding are baked in at conversion
        std::string txt(inp->prompt, inp->prompt_len);
        if (mtl && inp->lang && inp->lang[0]) {
            // the reference prefixes the language tag, e.g. "[fr]"
            std::string lang = inp->lang;
            std::transform(lang.begin(), lang.end(), lang.begin(), [](unsigned char c) { return (char) std::tolower(c); });
            txt = "[" + lang + "]" + txt;
        }
        std::vector<llama_token> ids(txt.size() + 16);
        int n_ids = llama_tokenize(vocab, txt.c_str(), (int32_t) txt.size(), ids.data(), (int32_t) ids.size(),
                                   false, true);
        if (n_ids < 1) {
            LOG_ERR("mtmd_helper_gen_audio: tokenization failed\n");
            return 1;
        }
        ids.resize((size_t) n_ids);
        if (mtl) {
            // only the multilingual prompt wraps the text in start/stop tokens
            ids.insert(ids.begin(), text_start);
            ids.push_back(text_stop);
            if (ids.size() > text_pos.size() / (size_t) n_e) {
                LOG_ERR("mtmd_helper_gen_audio: prompt too long (%zu tokens, max %zu)\n", ids.size(), text_pos.size() / (size_t) n_e);
                return 1;
            }
        }
        const size_t text0 = prompt_embd_buf.size() / (size_t) n_e;
        for (size_t i = 0; i < ids.size(); i++) {
            push_row(tok_embd.data() + (size_t) ids[i] * n_e);
            if (mtl) {
                add_pos(prompt_embd_buf.data() + (text0 + i) * n_e, text_pos, (int) i);
            }
        }

        // speech bos opens the AR stream
        push_row(tok_embd.data() + (size_t) llama_vocab_bos(vocab) * n_e);
        if (mtl) {
            add_pos(prompt_embd_buf.data() + prompt_embd_buf.size() - n_e, speech_pos, 0);
        }
        ar_idx = 1;
        n_prompt = (int) (prompt_embd_buf.size() / (size_t) n_e);

        if (mtl) {
            // cfg uncond prompt: text rows are zeroed but keep their learned positions, as in the reference
            uncond_embd_buf = prompt_embd_buf;
            for (size_t i = 0; i < ids.size(); i++) {
                float * r = uncond_embd_buf.data() + (text0 + i) * n_e;
                std::fill(r, r + n_e, 0.0f);
                add_pos(r, text_pos, (int) i);
            }
        }

        prompt_pos = 0;
        return 0;
    }

    int32_t step_prompt(int32_t n_batch) override {
        GGML_ASSERT(n_batch > 0);
        // the uncond prompt follows the cond one on mtl
        const int n_total = mtl ? 2 * n_prompt : n_prompt;
        if (prompt_pos >= n_total) {
            return 0;
        }
        const bool  uncond = prompt_pos >= n_prompt;
        const int   p0     = uncond ? prompt_pos - n_prompt : prompt_pos;
        const int32_t n_tokens_batch = std::min(n_batch, n_prompt - p0);
        const bool  last   = p0 + n_tokens_batch == n_prompt;

        decode_embd_batch batch((uncond ? uncond_embd_buf : prompt_embd_buf).data(), n_prompt, 1, n_embd);
        batch.set_position_normal(0, uncond ? seq_uncond : seq_id);
        if (last) {
            batch.logits[n_prompt - 1] = 1;
        }
        if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch.render(lctx, p0, n_tokens_batch)) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: prompt decode failed\n");
            return -1;
        }
        prompt_pos += n_tokens_batch;

        if (last && mtl) {
            if (!uncond) {
                cfg_read();
            } else {
                cfg_apply();
            }
        }

        if (prompt_pos >= n_total) {
            pos = n_prompt;
            prompt_embd_buf.clear();
            uncond_embd_buf.clear();
            return 0;
        }
        return n_total - prompt_pos;
    }

    int32_t step_gen(llama_token sampled, const float * h_state_in, const float ** h_state_out, bool * out_stop) override {
        GGML_UNUSED(h_state_in);
        if (sampled < 0 || sampled >= llama_vocab_n_tokens(vocab)) {
            LOG_ERR("mtmd_helper_gen_audio: chatterbox requires a token sampled from the backbone\n");
            return 1;
        }

        // the speech stop token is the backbone eos, the multilingual speech positions end the stream too
        if (llama_vocab_is_eog(vocab, sampled) || (mtl && (size_t) ar_idx >= speech_pos.size() / (size_t) n_embd)) {
            *out_stop    = true;
            *h_state_out = nullptr;
            return 0;
        }

        // keep only the 6561 s3gen codes, dropping start/stop and oov ids
        if (sampled >= speech_base && sampled - speech_base < 6561) {
            codes_buf.push_back(sampled - speech_base);
        }

        std::vector<float> e(tok_embd.begin() + (size_t) sampled * n_embd,
                             tok_embd.begin() + (size_t) (sampled + 1) * n_embd);
        if (mtl) {
            // the multilingual backbone takes the token row plus the learned speech position
            const float * p = speech_pos.data() + (size_t) ar_idx * n_embd;
            for (int j = 0; j < n_embd; j++) {
                e[(size_t) j] += p[j];
            }
            ar_idx++;
        }

        if (!decode_one(e.data(), seq_id)) {
            return 1;
        }
        if (mtl) {
            // cfg: the sampled token feeds both branches
            cfg_read();
            if (!decode_one(e.data(), seq_uncond)) {
                return 1;
            }
            cfg_apply();
        }
        pos++;

        const float * h = llama_get_embeddings_ith(lctx, -1);
        h_state_buf.assign(h, h + n_embd);
        *h_state_out = h_state_buf.data();
        return 0;
    }

    int32_t get_output(int32_t * out_sample_rate, const char ** out_data, size_t * out_data_len, int64_t * out_n_samples) override {
        *out_sample_rate = info.sample_rate;

        if (!stream) {
            if (!flush_gen_wav()) {
                return 1;
            }
            if (out_n_samples) {
                *out_n_samples = (int64_t) audio_pcm.size();
            }
            if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
                *out_data     = (const char *) audio_pcm.data();
                *out_data_len = audio_pcm.size() * sizeof(float);
                return 0;
            }
            out_buf.clear();
            if (!write_wav16(out_buf, audio_pcm, info.sample_rate)) {
                LOG_ERR("mtmd_helper_gen_audio: output too large for WAV\n");
                return 1;
            }
            *out_data     = out_buf.data();
            *out_data_len = out_buf.size();
            return 0;
        }

        // streaming: the flow decode is one-shot, so all the audio arrives after flush()
        const size_t n_new = audio_pcm.size() - pcm_sent;
        if (out_n_samples) {
            *out_n_samples = (int64_t) n_new;
        }
        if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
            *out_data     = (const char *) (audio_pcm.data() + pcm_sent);
            *out_data_len = n_new * sizeof(float);
            pcm_sent = audio_pcm.size();
            return 0;
        }
        out_buf.clear();
        if (!wav_header_sent) {
            write_wav16_header(out_buf, UINT32_MAX, info.sample_rate);
            wav_header_sent = true;
        }
        append_wav16_pcm(out_buf, audio_pcm.data() + pcm_sent, n_new);
        pcm_sent = audio_pcm.size();
        *out_data     = out_buf.data();
        *out_data_len = out_buf.size();
        return 0;
    }

    int32_t flush() override {
        return flush_gen_wav() ? 0 : 1;
    }

private:
    bool decode_one(const float * e, llama_seq_id seq) {
        decode_embd_batch batch(e, 1, 1, n_embd);
        batch.set_position_normal(pos, seq);
        batch.logits[0] = 1;
        if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch.render(lctx, 0, 1)) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: step decode failed\n");
            return false;
        }
        return true;
    }

    // cfg of the reference: logits = cond + 0.5 * (cond - uncond)
    // the mix goes into the last output row (the uncond one), the caller samples from it
    void cfg_read() {
        const float * c = llama_get_logits_ith(lctx, -1);
        cond_logits.assign(c, c + llama_vocab_n_tokens(vocab));
    }
    void cfg_apply() {
        float * u = llama_get_logits_ith(lctx, -1);
        for (size_t i = 0; i < cond_logits.size(); i++) {
            u[i] = cond_logits[i] + 0.5f * (cond_logits[i] - u[i]);
        }
    }

    // one GEN_WAV call over the whole utterance, the flow decode is not streamed
    bool flush_gen_wav() {
        if (decoded || codes_buf.empty()) {
            return true;
        }
        if (!mtl) {
            // turbo appends a short silence tail before vocoding
            codes_buf.insert(codes_buf.end(), 3, 4299);
        }
        mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
        inp.type    = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
        inp.codes   = codes_buf.data();
        inp.n_codes = codes_buf.size();
        mtmd_gen_out out{};
        if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: gen_wav decode failed\n");
            return false;
        }
        audio_pcm.assign(out.audio, out.audio + out.n_samples);
        decoded = true;
        return true;
    }

    bool ensure_cache() {
        if (!tok_embd.empty()) {
            return true;
        }
        // fused vocab layout: [text 0..speech_base) then the speech tokens
        speech_base = find_special_token(vocab, "<|speech_0|>");
        if (speech_base == LLAMA_TOKEN_NULL) {
            LOG_ERR("mtmd_helper_gen_audio: fused speech tokens not found in vocab\n");
            return false;
        }

        const uint32_t n_tok_embd = llama_model_get_tok_embd(model, nullptr);
        if (n_tok_embd != (uint32_t) llama_vocab_n_tokens(vocab) * (uint32_t) n_embd) {
            LOG_ERR("mtmd_helper_gen_audio: unexpected token embedding size\n");
            return false;
        }
        tok_embd.resize(n_tok_embd);
        llama_model_get_tok_embd(model, tok_embd.data());

        auto read_table = [&](const char * name, std::vector<float> & dst) {
            const size_t n = mtmd_gen_audio_read_tensor(mctx, name, nullptr, 0);
            dst.resize(n);
            if (n == 0 || mtmd_gen_audio_read_tensor(mctx, name, dst.data(), n) != n) {
                LOG_ERR("mtmd_helper_gen_audio: %s read failed\n", name);
                return false;
            }
            return true;
        };

        // multilingual: the learned position tables
        mtl = mtmd_gen_audio_read_tensor(mctx, "a.gen.t3.text_pos_emb", nullptr, 0) > 0;
        if (mtl && (!read_table("a.gen.t3.text_pos_emb", text_pos) || !read_table("a.gen.t3.speech_pos_emb", speech_pos))) {
            return false;
        }
        return true;
    }

    // vocab and mmproj data fixed across the whole session, read once
    std::vector<float> tok_embd;
    bool mtl = false;
    std::vector<float> text_pos;
    std::vector<float> speech_pos;
    llama_token speech_base = LLAMA_TOKEN_NULL;
    // start_text_token and stop_text_token of the reference, only the multilingual prompt uses them
    static constexpr llama_token text_start = 255;
    static constexpr llama_token text_stop  = 0;

    // per-generation state, cleared by reset()
    llama_seq_id seq_id     = 0;
    llama_seq_id seq_uncond = 0;
    llama_pos pos = 0;
    int ar_idx = 0;
    std::vector<float> prompt_embd_buf;
    std::vector<float> uncond_embd_buf;
    int n_prompt   = 0;
    int prompt_pos = 0;
    std::vector<float> cond_logits;
    std::vector<int32_t> codes_buf;
    bool decoded = false;
    std::vector<float> audio_pcm;
    std::vector<float> h_state_buf;
    mtmd_helper_gen_audio_outtype out_type = MTMD_HELPER_GEN_AUDIO_OUTTYPE_WAV;
    std::vector<char> out_buf;
    bool   stream          = false;
    size_t pcm_sent        = 0; // samples already returned by get_output()
    bool   wav_header_sent = false;
};

// Drama 3: backbone samples the main token of each frame, codebook tower samples the other codes, Fish DAC makes the PCM
// the tower attends over the whole sequence, so it also runs on every prompt row
class drama3_gen_audio_pipeline : public mtmd_gen_audio_pipeline {
public:
    using mtmd_gen_audio_pipeline::mtmd_gen_audio_pipeline;

    void reset() override {
        seq_id = 0;
        pos = 0;
        prompt_tokens.clear();
        prompt_pos = 0;
        frame.clear();
        hist.clear();
        codes_buf.clear();
        n_decoded = 0;
        gen_state.reset();
        pcm_sent = 0;
        wav_header_sent = false;
        audio_pcm.clear();
        h_state_buf.clear();
        out_buf.clear();
    }

    int32_t set_input(const mtmd_helper_gen_audio_inp * inp) override {
        reset();
        seq_id   = inp->seq_id;
        out_type = inp->out_type;
        stream   = inp->stream;
        if (inp->speaker_ref) {
            LOG_WRN("mtmd_helper_gen_audio: voice cloning is not supported yet, the speaker file is ignored\n");
        }

        sem_begin = find_special_token(vocab, "<|semantic:0|>");
        eos       = find_special_token(vocab, "<|im_end|>");
        if (sem_begin == LLAMA_TOKEN_NULL || eos == LLAMA_TOKEN_NULL) {
            LOG_ERR("mtmd_helper_gen_audio: missing Drama 3 tokens in vocab\n");
            return 1;
        }

        // reference-bracket-v1 prompt without references, tokenize each segment alone as the reference does
        std::string text(inp->prompt, inp->prompt_len);
        if (text.rfind("<|speaker:", 0) != 0) {
            text = "<|speaker:0|> " + text;
        }
        const char * segments[] = {
            "<|im_start|>system\n", "convert the provided text to speech", "<|im_end|>\n",
            "<|im_start|>user\n", text.c_str(), "<|im_end|>\n", "<|im_start|>assistant\n<|voice|>",
        };
        for (const char * seg : segments) {
            const int32_t len = (int32_t) strlen(seg);
            std::vector<llama_token> ids(len + 16);
            const int32_t n = llama_tokenize(vocab, seg, len, ids.data(), (int32_t) ids.size(), false, true);
            if (n < 0) {
                LOG_ERR("mtmd_helper_gen_audio: tokenization failed\n");
                return 1;
            }
            prompt_tokens.insert(prompt_tokens.end(), ids.begin(), ids.begin() + n);
        }
        if (prompt_tokens.size() >= llama_n_ctx_seq(lctx) || prompt_tokens.size() > n_tower_rows) {
            LOG_ERR("mtmd_helper_gen_audio: prompt does not fit in the context\n");
            return 1;
        }
        if (!llama_memory_seq_rm(llama_get_memory(lctx), seq_id, 0, -1)) {
            LOG_ERR("mtmd_helper_gen_audio: cannot reset the sequence\n");
            return 1;
        }
        rng.seed(inp->seed == UINT32_MAX ? std::random_device{}() : inp->seed);
        return init_gen_state(inp->seed) ? 0 : 1;
    }

    // run the tower on every prompt row to fill its KV
    int32_t step_prompt(int32_t n_batch) override {
        GGML_ASSERT(n_batch > 0);
        const int n_prompt = (int) prompt_tokens.size();
        if (prompt_pos >= n_prompt) {
            return 0;
        }
        // small batches: every row also outputs logits
        const int n = std::min({ n_batch, n_prompt - prompt_pos, 64 });
        llama_batch batch = llama_batch_init(n, 0, 1);
        for (int i = 0; i < n; i++) {
            batch.token   [i]    = prompt_tokens[(size_t) (prompt_pos + i)];
            batch.pos     [i]    = pos + i;
            batch.n_seq_id[i]    = 1;
            batch.seq_id  [i][0] = seq_id;
            batch.logits  [i]    = 1;
        }
        batch.n_tokens = n;
        const int ret = llama_decode(lctx, batch);
        llama_batch_free(batch);
        if (ret != 0) {
            LOG_ERR("mtmd_helper_gen_audio: prompt decode failed\n");
            return -1;
        }
        for (int i = 0; i < n; i++) {
            const float * h = llama_get_embeddings_ith(lctx, i);
            if (prompt_pos + i == n_prompt - 1) {
                h_state_buf.assign(h, h + n_embd); // first frame comes from the last prompt row
                break;
            }
            if (!run_tower(-1, h)) {
                return -1;
            }
        }
        pos        += n;
        prompt_pos += n;
        return n_prompt - prompt_pos;
    }

    // sample the main token here, ignore the token of the caller
    int32_t step_gen(llama_token sampled, const float * h_state_in, const float ** h_state_out, bool * out_stop) override {
        GGML_UNUSED(sampled);
        GGML_UNUSED(h_state_in);
        *h_state_out = nullptr;
        *out_stop    = false;

        const llama_token main = sample_main(llama_get_logits_ith(lctx, -1));
        const size_t n_rows = prompt_tokens.size() - 1 + codes_buf.size() / n_cb;
        if (main == eos || (uint32_t) pos >= llama_n_ctx_seq(lctx) || n_rows >= n_tower_rows) {
            *out_stop = true;
            return 0;
        }
        hist.push_back(main);
        if (hist.size() > ras_window) {
            hist.erase(hist.begin());
        }

        const float * next_embd = run_tower(main - sem_begin, h_state_buf.data());
        if (!next_embd) {
            return 1;
        }
        codes_buf.insert(codes_buf.end(), frame.begin(), frame.end());

        // text/speech stream: all mrope sections use the same position
        const bool mrope = llama_model_rope_type(model) == LLAMA_ROPE_TYPE_MROPE ||
                           llama_model_rope_type(model) == LLAMA_ROPE_TYPE_IMROPE;
        decode_embd_batch batch(next_embd, 1, mrope ? 4 : 1, n_embd);
        if (mrope) {
            batch.set_position_mrope_1d(pos, seq_id);
        } else {
            batch.set_position_normal(pos, seq_id);
        }
        batch.logits[0] = 1;
        if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch.render(lctx, 0, 1)) != 0) {
            LOG_ERR("mtmd_helper_gen_audio: decode failed\n");
            return 1;
        }
        pos++;
        const float * h = llama_get_embeddings_ith(lctx, -1);
        h_state_buf.assign(h, h + n_embd);
        *h_state_out = h_state_buf.data();

        if (stream && codes_buf.size() / n_cb - n_decoded >= stream_frames) {
            return decode_wav() ? 0 : 1;
        }
        return 0;
    }

    int32_t get_output(int32_t * out_sample_rate, const char ** out_data, size_t * out_data_len, int64_t * out_n_samples) override {
        *out_sample_rate = info.sample_rate;

        if (!stream) {
            if (flush() != 0) {
                return 1;
            }
            if (out_n_samples) {
                *out_n_samples = (int64_t) audio_pcm.size();
            }
            if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
                *out_data     = (const char *) audio_pcm.data();
                *out_data_len = audio_pcm.size() * sizeof(float);
                return 0;
            }
            out_buf.clear();
            if (!write_wav16(out_buf, audio_pcm, info.sample_rate)) {
                LOG_ERR("mtmd_helper_gen_audio: output too large for WAV\n");
                return 1;
            }
            *out_data     = out_buf.data();
            *out_data_len = out_buf.size();
            return 0;
        }

        // streaming: only the audio since the previous call
        const size_t n_new = audio_pcm.size() - pcm_sent;
        if (out_n_samples) {
            *out_n_samples = (int64_t) n_new;
        }
        if (out_type == MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) {
            *out_data     = (const char *) (audio_pcm.data() + pcm_sent);
            *out_data_len = n_new * sizeof(float);
            pcm_sent = audio_pcm.size();
            return 0;
        }
        out_buf.clear();
        if (!wav_header_sent) {
            write_wav16_header(out_buf, UINT32_MAX, info.sample_rate);
            wav_header_sent = true;
        }
        append_wav16_pcm(out_buf, audio_pcm.data() + pcm_sent, n_new);
        pcm_sent = audio_pcm.size();
        *out_data     = out_buf.data();
        *out_data_len = out_buf.size();
        return 0;
    }

    int32_t flush() override {
        return decode_wav() ? 0 : 1;
    }

private:
    // repetition-aware sampling: if a semantic draw repeats one of the last ras_window main tokens, draw again with fixed settings
    static constexpr size_t ras_window = 16;
    static constexpr size_t n_cb       = 10;
    // codebook tower KV rows (mtmd_graph_drama3_gen::n_pos_max): one per prompt row but the last, one per frame
    static constexpr size_t n_tower_rows = 4096;
    // frames per codec call when streaming (0.33 s)
    static constexpr size_t stream_frames = 7;

    // top-p keeps the token that crosses the threshold, as the reference does
    llama_token draw(const std::vector<float> & cand_logits, float temp, int32_t top_k, float top_p) {
        std::vector<std::pair<float, int>> cand(cand_logits.size());
        for (size_t i = 0; i < cand.size(); i++) {
            cand[i] = { cand_logits[i] / temp, (int) i };
        }
        std::sort(cand.begin(), cand.end(), [](const auto & a, const auto & b) { return a.first > b.first; });
        const float  lmax = cand[0].first;
        double       sum  = 0.0;
        std::vector<double> prob(cand.size());
        for (size_t i = 0; i < cand.size(); i++) {
            prob[i] = std::exp((double) (cand[i].first - lmax));
            sum += prob[i];
        }
        size_t n_keep = cand.size();
        if (top_k > 0) {
            n_keep = std::min(n_keep, (size_t) top_k);
        }
        double cum = 0.0;
        for (size_t i = 0; i < n_keep; i++) {
            if (cum > top_p * sum) {
                n_keep = i;
                break;
            }
            cum += prob[i];
        }
        double kept = 0.0;
        for (size_t i = 0; i < n_keep; i++) {
            kept += prob[i];
        }
        double r = std::uniform_real_distribution<double>(0.0, 1.0)(rng) * kept;
        for (size_t i = 0; i < n_keep; i++) {
            r -= prob[i];
            if (r <= 0.0) {
                return cand[i].second;
            }
        }
        return cand[n_keep - 1].second;
    }

    // candidates: eos, then semantic codes 1.. (the reference never samples code 0)
    llama_token sample_main(const float * logits) {
        std::vector<float> cand(n_cb_vocab);
        cand[0] = logits[eos];
        for (int i = 1; i < n_cb_vocab; i++) {
            cand[i] = logits[sem_begin + i];
        }
        auto to_token = [&](int i) { return i == 0 ? eos : sem_begin + i; };
        const llama_token first = to_token(draw(cand, 1.0f, 0, 0.9f));
        if (first != eos && std::find(hist.begin(), hist.end(), first) != hist.end()) {
            return to_token(draw(cand, 1.0f, 30, 0.95f));
        }
        return first;
    }

    // code0 < 0 for a prompt row, else the main code of the next frame
    // returns the next backbone input, the codes of the next frame go to frame
    const float * run_tower(int32_t code0, const float * h) {
        mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
        inp.type    = MTMD_GEN_PROCESS_TYPE_GEN_CODE;
        inp.code0   = code0;
        inp.embd    = const_cast<float *>(h);
        inp.codes   = frame.empty() ? nullptr : frame.data();
        inp.n_codes = frame.size();
        mtmd_gen_out out{};
        if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0 || (code0 >= 0 && out.n_codes != n_cb)) {
            LOG_ERR("mtmd_helper_gen_audio: codebook tower failed\n");
            return nullptr;
        }
        if (code0 >= 0) {
            frame.assign(out.codes, out.codes + out.n_codes);
        }
        return out.embd;
    }

    // the codec is stateful, so frames can be decoded in pieces
    bool decode_wav() {
        const size_t n_frames = codes_buf.size() / n_cb;
        while (n_decoded < n_frames) {
            const size_t n = std::min(n_frames - n_decoded, (size_t) 64);
            mtmd_gen_inp inp = mtmd_gen_inp_default(mctx);
            inp.type    = MTMD_GEN_PROCESS_TYPE_GEN_WAV;
            inp.codes   = codes_buf.data() + n_decoded * n_cb;
            inp.n_codes = n * n_cb;
            mtmd_gen_out out{};
            if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) {
                LOG_ERR("mtmd_helper_gen_audio: codec decode failed\n");
                return false;
            }
            audio_pcm.insert(audio_pcm.end(), out.audio, out.audio + out.n_samples);
            n_decoded += n;
        }
        return true;
    }

    static constexpr int n_cb_vocab = 4096; // <|semantic:0..4095|>

    llama_token sem_begin = LLAMA_TOKEN_NULL;
    llama_token eos       = LLAMA_TOKEN_NULL;

    llama_seq_id seq_id = 0;
    llama_pos    pos    = 0;
    std::vector<llama_token> prompt_tokens;
    int prompt_pos = 0;

    std::mt19937 rng;
    std::vector<int32_t>     frame;     // codes of the last frame, input of the next tower row
    std::vector<llama_token> hist;      // last main tokens, for repetition-aware sampling
    std::vector<int32_t>     codes_buf; // frame-major
    size_t n_decoded = 0;               // frames already through the codec

    std::vector<float>   audio_pcm;
    std::vector<float>   h_state_buf;
    mtmd_helper_gen_audio_outtype out_type = MTMD_HELPER_GEN_AUDIO_OUTTYPE_WAV;
    std::vector<char> out_buf;
    bool   stream          = false;
    size_t pcm_sent        = 0; // samples already returned by get_output()
    bool   wav_header_sent = false;
};

static std::unique_ptr<mtmd_gen_audio_pipeline> make_pipeline(llama_context * lctx, mtmd_context * mctx) {
    switch (mtmd_gen_audio_get_info(mctx).type) {
        case MTMD_GEN_AUDIO_TYPE_QWEN3TTS:
            return std::unique_ptr<mtmd_gen_audio_pipeline>(new qwen3tts_gen_audio_pipeline(lctx, mctx));
        case MTMD_GEN_AUDIO_TYPE_POCKETTTS:
            return std::unique_ptr<mtmd_gen_audio_pipeline>(new pockettts_gen_audio_pipeline(lctx, mctx));
        case MTMD_GEN_AUDIO_TYPE_SOPRANO:
            return std::unique_ptr<mtmd_gen_audio_pipeline>(new soprano_gen_audio_pipeline(lctx, mctx));
        case MTMD_GEN_AUDIO_TYPE_LFM3A:
            return std::unique_ptr<mtmd_gen_audio_pipeline>(new lfm3a_gen_audio_pipeline(lctx, mctx));
        case MTMD_GEN_AUDIO_TYPE_CHATTERBOX:
            return std::unique_ptr<mtmd_gen_audio_pipeline>(new chatterbox_gen_audio_pipeline(lctx, mctx));
        case MTMD_GEN_AUDIO_TYPE_DRAMA3:
            return std::unique_ptr<mtmd_gen_audio_pipeline>(new drama3_gen_audio_pipeline(lctx, mctx));
        default:
            return nullptr;
    }
}

struct mtmd_helper_gen_audio {
    std::unique_ptr<mtmd_gen_audio_pipeline> pipeline;
};

mtmd_helper_gen_audio * mtmd_helper_gen_audio_init(struct llama_context * lctx, struct mtmd_context * mctx) {
    auto * ctx = new mtmd_helper_gen_audio();
    ctx->pipeline = make_pipeline(lctx, mctx);
    return ctx;
}

void mtmd_helper_gen_audio_free(mtmd_helper_gen_audio * ctx) {
    delete ctx;
}

void mtmd_helper_gen_audio_reset(mtmd_helper_gen_audio * ctx) {
    if (ctx && ctx->pipeline) {
        ctx->pipeline->reset();
    }
}

struct mtmd_helper_gen_audio_inp mtmd_helper_gen_audio_inp_default(void) {
    mtmd_helper_gen_audio_inp inp{};
    inp.top_k    = 50;
    inp.top_p    = 1.0f;
    inp.temp     = -1.0f; // model default
    inp.seed     = UINT32_MAX; // random
    inp.out_type = MTMD_HELPER_GEN_AUDIO_OUTTYPE_WAV;
    return inp;
}

int32_t mtmd_helper_gen_audio_set_input(mtmd_helper_gen_audio * ctx, const mtmd_helper_gen_audio_inp * inp) {
    if (!ctx->pipeline) {
        LOG_ERR("mtmd_helper_gen_audio: unsupported or missing gen-audio pipeline\n");
        return 1;
    }
    if (inp->n_past > 0 && !ctx->pipeline->supports_continue()) {
        LOG_ERR("mtmd_helper_gen_audio: the pipeline cannot continue a sequence\n");
        return 1;
    }
    ctx->pipeline->logit_bias.clear();
    return ctx->pipeline->set_input(inp);
}

int32_t mtmd_helper_gen_audio_step_prompt(mtmd_helper_gen_audio * ctx, int32_t n_batch) {
    if (!ctx->pipeline) {
        return -1;
    }
    return ctx->pipeline->step_prompt(n_batch);
}

bool mtmd_helper_gen_audio_next_is_text(mtmd_helper_gen_audio * ctx) {
    return ctx->pipeline && ctx->pipeline->next_is_text();
}

const llama_logit_bias * mtmd_helper_gen_audio_get_logit_bias(mtmd_helper_gen_audio * ctx, size_t * n_bias) {
    *n_bias = ctx->pipeline ? ctx->pipeline->logit_bias.size() : 0;
    return *n_bias ? ctx->pipeline->logit_bias.data() : nullptr;
}

int32_t mtmd_helper_audio_stream_get_logit_bias(const mtmd_context * mctx, const llama_model * model,
                                                llama_logit_bias * out, int32_t n_max) {
    std::vector<llama_logit_bias> bias;
    if (mtmd_gen_audio_get_info(mctx).type == MTMD_GEN_AUDIO_TYPE_LFM3A) {
        // LFM3-Audio live ASR: only <|text_end|> ends the text of a chunk, the stream adds the final <|mixed_end|>
        const llama_vocab * vocab = llama_model_get_vocab(model);
        for (const char * piece : { "<|mixed_end|>", "<|mixed_start|>", "<|audio_start|>", "<|im_start|>", "<|im_end|>", "<|endoftext|>" }) {
            const llama_token tok = find_special_token(vocab, piece);
            if (tok != LLAMA_TOKEN_NULL) {
                bias.push_back({ tok, -INFINITY });
            }
        }
    }
    for (int32_t i = 0; i < n_max && i < (int32_t) bias.size(); i++) {
        out[i] = bias[i];
    }
    return (int32_t) bias.size();
}

int32_t mtmd_helper_gen_audio_step_gen(mtmd_helper_gen_audio * ctx, llama_token sampled,
                                       const float * h_state_in, const float ** h_state_out,
                                       bool * out_stop) {
    if (!ctx->pipeline) {
        return 1;
    }
    bool stop = false;
    const int32_t ret = ctx->pipeline->step_gen(sampled, h_state_in, h_state_out, &stop);
    if (out_stop) {
        *out_stop = stop;
    }
    return ret;
}

int32_t mtmd_helper_gen_audio_get_output(mtmd_helper_gen_audio * ctx, int32_t * out_sample_rate,
                                         const char ** out_data, size_t * out_data_len, int64_t * out_n_samples) {
    if (!ctx->pipeline) {
        return 1;
    }
    return ctx->pipeline->get_output(out_sample_rate, out_data, out_data_len, out_n_samples);
}

int32_t mtmd_helper_gen_audio_flush(mtmd_helper_gen_audio * ctx) {
    if (!ctx->pipeline) {
        return 1;
    }
    return ctx->pipeline->flush();
}