audio-cpp-sys 0.5.0

audio.cpp(ggml 音频推理框架)的底层绑定
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
#include "capi.h"

#include "engine/framework/core/backend.h"
#include "engine/framework/io/json.h"
#include "engine/framework/runtime/model.h"
#include "engine/framework/runtime/registry.h"
#include "engine/framework/runtime/session.h"

#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <memory>
#include <mutex>
#include <string>
#include <vector>

using engine::runtime::ModelRegistry;
using engine::runtime::ModelLoadRequest;
using engine::runtime::ILoadedVoiceModel;
using engine::runtime::IVoiceTaskSession;
using engine::runtime::IOfflineVoiceTaskSession;
using engine::runtime::IStreamingVoiceTaskSession;
using engine::runtime::TaskSpec;
using engine::runtime::SessionOptions;
using engine::runtime::TaskRequest;
using engine::runtime::TaskResult;
using engine::runtime::StreamEvent;
using engine::runtime::NamedAudioBuffer;
using engine::runtime::VoiceTaskKind;
using engine::runtime::RunMode;

namespace json = engine::io::json;

/* ------------------------------------------------------------------ */
/* 不透明结构体                                                         */
/* ------------------------------------------------------------------ */

struct audiocpp_registry {
    ModelRegistry storage;
};

struct audiocpp_model {
    std::unique_ptr<ILoadedVoiceModel> storage;
};

struct EventSink {
    // 串行化 set_event_sink 与事件派发:派发期间持有锁调用回调,因此
    // set(None) 返回后必无在途回调再引用旧 user_data(Rust 侧 Drop 先解绑
    // 再释放即安全)。注意:回调内不得再调回会话方法,否则自死锁。
    std::mutex mu;
    audiocpp_stream_event_cb cb = nullptr;
    void * user_data = nullptr;
};

struct audiocpp_session {
    std::unique_ptr<IVoiceTaskSession> storage;
    EventSink sink;
    // 借用字符串缓存:task_kind / run_mode 由 to_string() 产生临时对象,
    // 不能直接返回其 c_str()(悬垂指针),因此建会话时固化到成员里。
    std::string family;
    std::string task_kind;
    std::string run_mode;
};

/* ------------------------------------------------------------------ */
/* 错误处理                                                             */
/* ------------------------------------------------------------------ */

static thread_local std::string tls_last_error;

static void set_last_error(const std::string & msg) {
    tls_last_error = msg;
}

const char * audiocpp_last_error(void) {
    return tls_last_error.empty() ? nullptr : tls_last_error.c_str();
}

static char * dup_string(const std::string & s) {
    char * out = static_cast<char *>(std::malloc(s.size() + 1));
    if (out != nullptr) {
        std::memcpy(out, s.c_str(), s.size());
        out[s.size()] = '\0';
    }
    return out;
}

// dup_string 的 OOM 检查版:成功把字符串写入 *out 并返回 0;malloc
// 失败时记错误并返回 -1(调用方直接 return 本函数结果即可)。
static int dup_out(char ** out, const std::string & s, const char * what) {
    char * p = dup_string(s);
    if (p == nullptr) {
        set_last_error(std::string("out of memory in ") + what);
        return -1;
    }
    *out = p;
    return 0;
}

void audiocpp_free_string(char * s) {
    std::free(s);
}

/* ------------------------------------------------------------------ */
/* 小工具函数                                                           */
/* ------------------------------------------------------------------ */

static json::Value dump_time_span(const engine::runtime::TimeSpan & span) {
    json::Value::Object obj;
    obj.emplace("start_sample", json::Value::make_number(static_cast<double>(span.start_sample)));
    obj.emplace("end_sample", json::Value::make_number(static_cast<double>(span.end_sample)));
    return json::Value::make_object(std::move(obj));
}

static json::Value dump_speech_segment(const engine::runtime::SpeechSegment & seg) {
    json::Value::Object obj;
    obj.emplace("span", dump_time_span(seg.span));
    obj.emplace("confidence", json::Value::make_number(seg.confidence));
    obj.emplace("text", json::Value::make_string(seg.text));
    return json::Value::make_object(std::move(obj));
}

static json::Value dump_speaker_turn(const engine::runtime::SpeakerTurn & turn) {
    json::Value::Object obj;
    obj.emplace("speaker_id", json::Value::make_string(turn.speaker_id));
    obj.emplace("span", dump_time_span(turn.span));
    obj.emplace("confidence", json::Value::make_number(turn.confidence));
    obj.emplace("text", json::Value::make_string(turn.text));
    return json::Value::make_object(std::move(obj));
}

static json::Value dump_audio_buffer(const engine::runtime::AudioBuffer & audio) {
    json::Value::Object obj;
    obj.emplace("sample_rate", json::Value::make_number(audio.sample_rate));
    obj.emplace("channels", json::Value::make_number(audio.channels));
    obj.emplace("sample_count", json::Value::make_number(static_cast<double>(audio.samples.size())));
    // 附带实际采样数据(f32 数组),供 TTS 等需要取回生成音频的调用方使用。
    // 不含采样数据的空缓冲也照常输出空数组。
    json::Value::Array samples;
    samples.reserve(audio.samples.size());
    for (const float s : audio.samples) {
        samples.push_back(json::Value::make_number(static_cast<double>(s)));
    }
    obj.emplace("samples", json::Value::make_array(std::move(samples)));
    return json::Value::make_object(std::move(obj));
}

static json::Value dump_named_audio_outputs(const std::vector<NamedAudioBuffer> & outputs) {
    json::Value::Array named_audio;
    named_audio.reserve(outputs.size());
    for (const auto & named : outputs) {
        json::Value::Object item;
        item.emplace("id", json::Value::make_string(named.id));
        item.emplace("audio", dump_audio_buffer(named.audio));
        json::Value::Object meta;
        for (const auto & [k, v] : named.meta) {
            meta.emplace(k, json::Value::make_string(v));
        }
        item.emplace("meta", json::Value::make_object(std::move(meta)));
        named_audio.push_back(json::Value::make_object(std::move(item)));
    }
    return json::Value::make_array(std::move(named_audio));
}

/* ------------------------------------------------------------------ */
/* 词级时间戳 / 产物(artifact)/ 模型预检                              */
/* ------------------------------------------------------------------ */

static const char * artifact_kind_to_string(engine::runtime::ArtifactKind k) {
    using engine::runtime::ArtifactKind;
    switch (k) {
        case ArtifactKind::SpeakerEmbedding:   return "speaker_embedding";
        case ArtifactKind::StyleEmbedding:     return "style_embedding";
        case ArtifactKind::PromptEmbedding:    return "prompt_embedding";
        case ArtifactKind::AcousticTokens:     return "acoustic_tokens";
        case ArtifactKind::Midi:               return "midi";
        case ArtifactKind::TranscriptAlignment: return "transcript_alignment";
        case ArtifactKind::DiarizationState:   return "diarization_state";
        case ArtifactKind::VadState:           return "vad_state";
        case ArtifactKind::Custom:             return "custom";
    }
    return "custom";
}

// 把二进制产物编码为 base64(JSON 无法原生承载 bytes)。
static std::string base64_encode(const std::vector<std::byte> & data) {
    static const char * table =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    std::string out;
    out.reserve(((data.size() + 2) / 3) * 4);
    const auto * p = reinterpret_cast<const unsigned char *>(data.data());
    size_t i = 0;
    auto append = [&](uint32_t n) {
        out.push_back(table[(n >> 18) & 0x3F]);
        out.push_back(table[(n >> 12) & 0x3F]);
        out.push_back(table[(n >> 6) & 0x3F]);
        out.push_back(table[n & 0x3F]);
    };
    while (i + 3 <= data.size()) {
        append((uint32_t(p[i]) << 16) | (uint32_t(p[i + 1]) << 8) | uint32_t(p[i + 2]));
        i += 3;
    }
    size_t rem = data.size() - i;
    if (rem == 1) {
        uint32_t n = uint32_t(p[i]) << 16;
        out.push_back(table[(n >> 18) & 0x3F]);
        out.push_back(table[(n >> 12) & 0x3F]);
        out.push_back('=');
        out.push_back('=');
    } else if (rem == 2) {
        uint32_t n = (uint32_t(p[i]) << 16) | (uint32_t(p[i + 1]) << 8);
        out.push_back(table[(n >> 18) & 0x3F]);
        out.push_back(table[(n >> 12) & 0x3F]);
        out.push_back(table[(n >> 6) & 0x3F]);
        out.push_back('=');
    }
    return out;
}

static json::Value dump_word_timestamp(const engine::runtime::WordTimestamp & w) {
    json::Value::Object obj;
    obj.emplace("span", dump_time_span(w.span));
    obj.emplace("word", json::Value::make_string(w.word));
    obj.emplace("confidence", json::Value::make_number(static_cast<double>(w.confidence)));
    return json::Value::make_object(std::move(obj));
}

static json::Value dump_voice_artifact(const engine::runtime::VoiceArtifact & a) {
    json::Value::Object obj;
    obj.emplace("kind", json::Value::make_string(artifact_kind_to_string(a.kind)));
    obj.emplace("id", json::Value::make_string(a.id));
    obj.emplace("payload_base64", json::Value::make_string(base64_encode(a.payload)));
    json::Value::Object meta;
    for (const auto & [k, v] : a.meta) {
        meta.emplace(k, json::Value::make_string(v));
    }
    obj.emplace("meta", json::Value::make_object(std::move(meta)));
    return json::Value::make_object(std::move(obj));
}

static json::Value dump_artifact_list(const std::vector<engine::runtime::VoiceArtifact> & list) {
    json::Value::Array arr;
    arr.reserve(list.size());
    for (const auto & a : list) {
        arr.push_back(dump_voice_artifact(a));
    }
    return json::Value::make_array(std::move(arr));
}

static json::Value dump_task_result(const TaskResult & result) {
    json::Value::Object obj;

    json::Value::Array segments;
    segments.reserve(result.speech_segments.size());
    for (const auto & seg : result.speech_segments) {
        segments.push_back(dump_speech_segment(seg));
    }
    obj.emplace("speech_segments", json::Value::make_array(std::move(segments)));

    json::Value::Array turns;
    turns.reserve(result.speaker_turns.size());
    for (const auto & turn : result.speaker_turns) {
        turns.push_back(dump_speaker_turn(turn));
    }
    obj.emplace("speaker_turns", json::Value::make_array(std::move(turns)));

    if (result.text_output.has_value()) {
        json::Value::Object text;
        text.emplace("text", json::Value::make_string(result.text_output->text));
        text.emplace("language", json::Value::make_string(result.text_output->language));
        obj.emplace("text_output", json::Value::make_object(std::move(text)));
    }
    if (result.audio_output.has_value()) {
        obj.emplace("audio_output", dump_audio_buffer(*result.audio_output));
    }

    obj.emplace("named_audio_outputs", dump_named_audio_outputs(result.named_audio_outputs));

    json::Value::Array words;
    words.reserve(result.word_timestamps.size());
    for (const auto & w : result.word_timestamps) {
        words.push_back(dump_word_timestamp(w));
    }
    obj.emplace("word_timestamps", json::Value::make_array(std::move(words)));

    if (result.artifact_output.has_value()) {
        obj.emplace("artifact_output", dump_voice_artifact(*result.artifact_output));
    }
    obj.emplace("output_artifacts", dump_artifact_list(result.output_artifacts));

    return json::Value::make_object(std::move(obj));
}

static json::Value dump_stream_event(const StreamEvent & event) {
    json::Value::Object obj;
    json::Value::Array activity;
    for (const auto & ev : event.voice_activity) {
        json::Value::Object item;
        switch (ev.kind) {
            case engine::runtime::VoiceActivityEvent::Kind::SpeechStart:
                item.emplace("kind", json::Value::make_string("speech_start"));
                break;
            case engine::runtime::VoiceActivityEvent::Kind::SpeechEnd:
                item.emplace("kind", json::Value::make_string("speech_end"));
                break;
            default:
                item.emplace("kind", json::Value::make_string("speech_segment"));
                break;
        }
        item.emplace("sample", json::Value::make_number(static_cast<double>(ev.sample)));
        item.emplace("probability", json::Value::make_number(ev.probability));
        if (ev.segment.has_value()) {
            item.emplace("segment", dump_speech_segment(*ev.segment));
        }
        activity.push_back(json::Value::make_object(std::move(item)));
    }
    obj.emplace("voice_activity", json::Value::make_array(std::move(activity)));
    if (event.partial_text.has_value()) {
        json::Value::Object text;
        text.emplace("text", json::Value::make_string(event.partial_text->text));
        text.emplace("language", json::Value::make_string(event.partial_text->language));
        obj.emplace("partial_text", json::Value::make_object(std::move(text)));
    }
    if (event.audio_output.has_value()) {
        obj.emplace("audio_output", dump_audio_buffer(*event.audio_output));
    }
    if (!event.named_audio_outputs.empty()) {
        obj.emplace("named_audio_outputs", dump_named_audio_outputs(event.named_audio_outputs));
    }
    json::Value::Array turns;
    turns.reserve(event.speaker_turns.size());
    for (const auto & turn : event.speaker_turns) {
        turns.push_back(dump_speaker_turn(turn));
    }
    obj.emplace("speaker_turns", json::Value::make_array(std::move(turns)));
    json::Value::Array words;
    words.reserve(event.word_timestamps.size());
    for (const auto & w : event.word_timestamps) {
        words.push_back(dump_word_timestamp(w));
    }
    obj.emplace("word_timestamps", json::Value::make_array(std::move(words)));
    if (!event.output_artifacts.empty()) {
        obj.emplace("output_artifacts", dump_artifact_list(event.output_artifacts));
    }
    obj.emplace("is_final", json::Value::make_bool(event.is_final));
    return json::Value::make_object(std::move(obj));
}

static json::Value dump_capabilities(const engine::runtime::CapabilitySet & caps) {
    json::Value::Object obj;
    json::Value::Array tasks;
    for (const auto & task : caps.supported_tasks) {
        json::Value::Object item;
        item.emplace("task", json::Value::make_string(engine::runtime::to_string(task.task)));
        json::Value::Array modes;
        for (const auto mode : task.modes) {
            modes.push_back(json::Value::make_string(engine::runtime::to_string(mode)));
        }
        item.emplace("modes", json::Value::make_array(std::move(modes)));
        tasks.push_back(json::Value::make_object(std::move(item)));
    }
    obj.emplace("supported_tasks", json::Value::make_array(std::move(tasks)));
    json::Value::Array languages;
    for (const auto & lang : caps.languages) {
        languages.push_back(json::Value::make_string(lang));
    }
    obj.emplace("languages", json::Value::make_array(std::move(languages)));
    obj.emplace("supports_speaker_reference", json::Value::make_bool(caps.supports_speaker_reference));
    obj.emplace("supports_style_condition", json::Value::make_bool(caps.supports_style_condition));
    obj.emplace("supports_timestamps", json::Value::make_bool(caps.supports_timestamps));
    return json::Value::make_object(std::move(obj));
}

static json::Value dump_metadata(const engine::runtime::ModelMetadata & meta) {
    json::Value::Object obj;
    obj.emplace("family", json::Value::make_string(meta.family));
    obj.emplace("variant", json::Value::make_string(meta.variant));
    obj.emplace("description", json::Value::make_string(meta.description));
    json::Value::Array configs;
    for (const auto & c : meta.config_candidates) {
        configs.push_back(json::Value::make_string(c));
    }
    obj.emplace("config_candidates", json::Value::make_array(std::move(configs)));
    json::Value::Array weights;
    for (const auto & w : meta.weight_candidates) {
        weights.push_back(json::Value::make_string(w));
    }
    obj.emplace("weight_candidates", json::Value::make_array(std::move(weights)));
    return json::Value::make_object(std::move(obj));
}

static json::Value dump_cli_option(const engine::runtime::CliOptionInfo & o) {
    json::Value::Object obj;
    obj.emplace("name", json::Value::make_string(o.name));
    obj.emplace("value_name", json::Value::make_string(o.value_name));
    obj.emplace("description", json::Value::make_string(o.description));
    obj.emplace("required", json::Value::make_bool(o.required));
    if (o.default_value.has_value()) {
        obj.emplace("default_value", json::Value::make_string(*o.default_value));
    }
    if (o.min_value.has_value()) {
        obj.emplace("min_value", json::Value::make_string(*o.min_value));
    }
    if (o.max_value.has_value()) {
        obj.emplace("max_value", json::Value::make_string(*o.max_value));
    }
    return json::Value::make_object(std::move(obj));
}

static json::Value dump_inspection(const engine::runtime::ModelInspection & insp) {
    json::Value::Object root;
    root.emplace("metadata", dump_metadata(insp.metadata));
    root.emplace("capabilities", dump_capabilities(insp.capabilities));

    json::Value::Object cli;
    json::Value::Array req, sess, load;
    for (const auto & o : insp.cli.request_options) {
        req.push_back(dump_cli_option(o));
    }
    for (const auto & o : insp.cli.session_options) {
        sess.push_back(dump_cli_option(o));
    }
    for (const auto & o : insp.cli.load_options) {
        load.push_back(dump_cli_option(o));
    }
    cli.emplace("request_options", json::Value::make_array(std::move(req)));
    cli.emplace("session_options", json::Value::make_array(std::move(sess)));
    cli.emplace("load_options", json::Value::make_array(std::move(load)));
    root.emplace("cli", json::Value::make_object(std::move(cli)));

    json::Value::Array cfgs, wts;
    for (const auto & a : insp.discovered_configs) {
        json::Value::Object item;
        item.emplace("id", json::Value::make_string(a.id));
        item.emplace("path", json::Value::make_string(a.path.string()));
        cfgs.push_back(json::Value::make_object(std::move(item)));
    }
    for (const auto & a : insp.discovered_weights) {
        json::Value::Object item;
        item.emplace("id", json::Value::make_string(a.id));
        item.emplace("path", json::Value::make_string(a.path.string()));
        wts.push_back(json::Value::make_object(std::move(item)));
    }
    root.emplace("discovered_configs", json::Value::make_array(std::move(cfgs)));
    root.emplace("discovered_weights", json::Value::make_array(std::move(wts)));
    root.emplace("model_root", json::Value::make_string(insp.model_root.string()));
    return json::Value::make_object(std::move(root));
}

/* ------------------------------------------------------------------ */
/* WAV 加载(极简 RIFF/WAVE PCM 读取器)                                */
/* ------------------------------------------------------------------ */

static int audio_load_wav_impl(const char * path, int * sample_rate, int * channels,
                               size_t * count, float ** samples) {
    FILE * f = std::fopen(path, "rb");
    if (f == nullptr) {
        set_last_error("could not open wav file");
        return -1;
    }
    struct RiffHeader {
        char id[4];
        uint32_t size;
        char wave[4];
    } riff;
    if (std::fread(&riff, sizeof(riff), 1, f) != 1 ||
        std::memcmp(riff.id, "RIFF", 4) != 0 || std::memcmp(riff.wave, "WAVE", 4) != 0) {
        set_last_error("not a RIFF/WAVE file");
        std::fclose(f);
        return -1;
    }
    uint16_t audio_format = 0;
    uint16_t num_channels = 0;
    uint32_t sample_rate32 = 0;
    uint16_t bits_per_sample = 0;
    std::vector<uint8_t> data;
    bool have_fmt = false;

    while (true) {
        char chunk_id[4];
        uint32_t chunk_size = 0;
        if (std::fread(chunk_id, 4, 1, f) != 1) {
            break;
        }
        if (std::fread(&chunk_size, 4, 1, f) != 1) {
            break;
        }
        if (std::memcmp(chunk_id, "fmt ", 4) == 0) {
            uint16_t format_tag = 0;
            uint16_t n_channels = 0;
            uint32_t n_sample_rate = 0;
            uint32_t n_byte_rate = 0;
            uint16_t n_block_align = 0;
            uint16_t n_bits = 0;
            if (std::fread(&format_tag, 2, 1, f) != 1 ||
                std::fread(&n_channels, 2, 1, f) != 1 ||
                std::fread(&n_sample_rate, 4, 1, f) != 1 ||
                std::fread(&n_byte_rate, 4, 1, f) != 1 ||
                std::fread(&n_block_align, 2, 1, f) != 1 ||
                std::fread(&n_bits, 2, 1, f) != 1) {
                break;
            }
            audio_format = format_tag;
            num_channels = n_channels;
            sample_rate32 = n_sample_rate;
            bits_per_sample = n_bits;
            have_fmt = true;
            if (chunk_size > 16) {
                // chunk_size 为 uint32,直接转 long 在 Windows(32 位 long)
                // 上会截断;超大声明一律拒绝(合法 fmt 块远小于此)。
                if (chunk_size - 16 > 0x40000000u ||
                    std::fseek(f, static_cast<long>(chunk_size) - 16L, SEEK_CUR) != 0) {
                    break;
                }
            }
        } else if (std::memcmp(chunk_id, "data", 4) == 0) {
            // data 块上限 1GiB:既防损坏文件的 chunk_size 触发 bad_alloc,
            // 也保证后续 long 型 fseek 不截断(1GiB 音频约 17 小时单声道)。
            if (chunk_size > 0x40000000u) {
                set_last_error("wav data chunk too large");
                std::fclose(f);
                return -1;
            }
            data.resize(chunk_size);
            if (chunk_size != 0 && std::fread(data.data(), chunk_size, 1, f) != 1) {
                break;
            }
        } else {
            if (chunk_size > 0x40000000u ||
                std::fseek(f, static_cast<long>(chunk_size), SEEK_CUR) != 0) {
                break;
            }
        }
        if (chunk_size % 2 != 0) {
            if (std::fseek(f, 1, SEEK_CUR) != 0) {
                break;
            }
        }
    }
    std::fclose(f);

    if (!have_fmt || data.empty()) {
        set_last_error("missing fmt or data chunk");
        return -1;
    }
    const size_t bytes_per_sample = bits_per_sample / 8;
    if (bytes_per_sample == 0 || num_channels == 0) {
        set_last_error("bad wav format");
        return -1;
    }
    const size_t n = data.size() / bytes_per_sample;
    auto * out = static_cast<float *>(std::malloc(n * sizeof(float)));
    if (out == nullptr) {
        set_last_error("out of memory");
        return -1;
    }
    // float 格式(format 3)必须是 32 位,否则步进错位会越界读。
    if (audio_format == 3 && bits_per_sample == 32) {
        for (size_t i = 0; i < n; ++i) {
            float v;
            std::memcpy(&v, data.data() + i * bytes_per_sample, sizeof(float));
            out[i] = v;
        }
    } else if (audio_format == 1 && bits_per_sample == 16) {
        const int16_t * src = reinterpret_cast<const int16_t *>(data.data());
        for (size_t i = 0; i < n; ++i) {
            out[i] = static_cast<float>(src[i]) / 32768.0f;
        }
    } else if (audio_format == 1 && bits_per_sample == 32) {
        const int32_t * src = reinterpret_cast<const int32_t *>(data.data());
        for (size_t i = 0; i < n; ++i) {
            out[i] = static_cast<float>(src[i]) / 2147483648.0f;
        }
    } else {
        set_last_error("unsupported wav sample format");
        std::free(out);
        return -1;
    }
    if (sample_rate != nullptr) {
        *sample_rate = static_cast<int>(sample_rate32);
    }
    if (channels != nullptr) {
        *channels = num_channels;
    }
    if (count != nullptr) {
        *count = n;
    }
    if (samples != nullptr) {
        *samples = out;
    } else {
        // 调用方不取缓冲时自行释放,避免泄漏。
        std::free(out);
    }
    return 0;
}

// 导出的 WAV 入口:参数校验 + 全函数异常保护(resize / malloc /
// filesystem 相关操作均可抛,绝不能穿过 C 边界)。
int audiocpp_audio_load_wav(const char * path, int * sample_rate, int * channels,
                            size_t * count, float ** samples) {
    if (samples != nullptr) {
        *samples = nullptr;
    }
    if (count != nullptr) {
        *count = 0;
    }
    if (path == nullptr) {
        set_last_error("null wav path");
        return -1;
    }
    try {
        return audio_load_wav_impl(path, sample_rate, channels, count, samples);
    } catch (const std::exception & ex) {
        set_last_error(std::string("wav load failed: ") + ex.what());
        return -1;
    } catch (...) {
        set_last_error("wav load failed: unknown error");
        return -1;
    }
}

void audiocpp_audio_free(float * samples) {
    std::free(samples);
}

/* ------------------------------------------------------------------ */
/* 请求解析                                                             */
/* ------------------------------------------------------------------ */

static void fill_options_from_json(std::unordered_map<std::string, std::string> & dst,
                                   const json::Value * options) {
    if (options == nullptr || !options->is_object()) {
        return;
    }
    for (const auto & [key, value] : options->as_object()) {
        if (value.is_string()) {
            dst.emplace(key, value.as_string());
        } else {
            dst.emplace(key, json::stringify(value));
        }
    }
}

static TaskRequest parse_task_request(const json::Value & root) {
    TaskRequest request;
    fill_options_from_json(request.options, root.find("options"));

    if (const auto * text = root.find("text"); text != nullptr && text->is_string()) {
        engine::runtime::Transcript transcript;
        transcript.text = text->as_string();
        if (const auto * lang = root.find("language"); lang != nullptr && lang->is_string()) {
            transcript.language = lang->as_string();
        }
        request.text_input = std::move(transcript);
    }

    if (const auto * audio = root.find("audio"); audio != nullptr && audio->is_object()) {
        engine::runtime::AudioBuffer buf;
        buf.sample_rate = json::optional_i32(*audio, "sample_rate", 0);
        buf.channels = json::optional_i32(*audio, "channels", 1);
        if (const auto * samples = audio->find("samples"); samples != nullptr && samples->is_array()) {
            buf.samples = json::number_array_as<float>(*samples);
        }
        if (!buf.samples.empty()) {
            request.audio_input = std::move(buf);
        }
    }

    if (const auto * audio_path = root.find("audio_path"); audio_path != nullptr && audio_path->is_string()) {
        int sr = 0, ch = 0;
        size_t n = 0;
        float * samples = nullptr;
        if (audiocpp_audio_load_wav(audio_path->as_string().c_str(), &sr, &ch, &n, &samples) == 0) {
            engine::runtime::AudioBuffer buf;
            buf.sample_rate = sr;
            buf.channels = ch;
            buf.samples.assign(samples, samples + n);
            std::free(samples);
            request.audio_input = std::move(buf);
        }
    }

    // `voice`:说话人参考 / 风格条件(语音克隆、风格控制等)。
    if (const auto * voice = root.find("voice"); voice != nullptr && voice->is_object()) {
        engine::runtime::VoiceCondition cond;
        if (const auto * speaker = voice->find("speaker"); speaker != nullptr && speaker->is_object()) {
            engine::runtime::VoiceReference ref;
            if (const auto * cached = speaker->find("cached_voice_id");
                cached != nullptr && cached->is_string()) {
                ref.cached_voice_id = cached->as_string();
            }
            if (const auto * audio = speaker->find("audio"); audio != nullptr && audio->is_object()) {
                engine::runtime::AudioBuffer buf;
                buf.sample_rate = json::optional_i32(*audio, "sample_rate", 0);
                buf.channels = json::optional_i32(*audio, "channels", 1);
                if (const auto * samples = audio->find("samples");
                    samples != nullptr && samples->is_array()) {
                    buf.samples = json::number_array_as<float>(*samples);
                }
                if (!buf.samples.empty()) {
                    ref.audio = std::move(buf);
                }
            } else if (const auto * speaker_path = speaker->find("audio_path");
                       speaker_path != nullptr && speaker_path->is_string()) {
                int sr = 0, ch = 0;
                size_t n = 0;
                float * samples = nullptr;
                if (audiocpp_audio_load_wav(speaker_path->as_string().c_str(), &sr, &ch, &n, &samples) == 0) {
                    engine::runtime::AudioBuffer buf;
                    buf.sample_rate = sr;
                    buf.channels = ch;
                    buf.samples.assign(samples, samples + n);
                    std::free(samples);
                    ref.audio = std::move(buf);
                }
            }
            cond.speaker = std::move(ref);
        }
        if (const auto * style = voice->find("style"); style != nullptr && style->is_object()) {
            engine::runtime::StyleCondition sc;
            if (const auto * v = style->find("language"); v != nullptr && v->is_string()) {
                sc.language = v->as_string();
            }
            if (const auto * v = style->find("emotion"); v != nullptr && v->is_string()) {
                sc.emotion = v->as_string();
            }
            if (const auto * v = style->find("speaking_rate"); v != nullptr && v->is_number()) {
                sc.speaking_rate = static_cast<float>(v->as_number());
            }
            if (const auto * v = style->find("pitch_shift"); v != nullptr && v->is_number()) {
                sc.pitch_shift = static_cast<float>(v->as_number());
            }
            if (const auto * v = style->find("energy_scale"); v != nullptr && v->is_number()) {
                sc.energy_scale = static_cast<float>(v->as_number());
            }
            if (const auto * tags = style->find("tags"); tags != nullptr && tags->is_object()) {
                for (const auto & [k, v] : tags->as_object()) {
                    if (v.is_string()) {
                        sc.tags.emplace(k, v.as_string());
                    }
                }
            }
            cond.style = std::move(sc);
        }
        request.voice = std::move(cond);
    }

    return request;
}

/* ------------------------------------------------------------------ */
/* 注册表                                                               */
/* ------------------------------------------------------------------ */

audiocpp_registry * audiocpp_registry_default(void) {
    try {
        auto reg = engine::runtime::make_default_registry();
        return new audiocpp_registry{std::move(reg)};
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return nullptr;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_registry_default");
        return nullptr;
    }
}

int audiocpp_registry_families_json(const audiocpp_registry * reg, char ** out_json) {
    if (out_json == nullptr || reg == nullptr) {
        set_last_error("null out_json or registry");
        return -1;
    }
        *out_json = nullptr;
    try {
        json::Value::Array arr;
        for (const auto & family : reg->storage.families()) {
            arr.push_back(json::Value::make_string(family));
        }
        return dup_out(out_json, json::stringify(json::Value::make_array(std::move(arr))),
                       "audiocpp_registry_families_json");
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_registry_families_json");
        return -1;
    }
}

int audiocpp_registry_loaders_json(const audiocpp_registry * reg, char ** out_json) {
    if (out_json == nullptr || reg == nullptr) {
        set_last_error("null out_json or registry");
        return -1;
    }
    *out_json = nullptr;
    try {
        json::Value::Object root;
        json::Value::Array arr;
        for (const auto & adv : reg->storage.advertise_loaders()) {
            json::Value::Object item;
            item.emplace("family", json::Value::make_string(adv.family));
            item.emplace("capabilities", dump_capabilities(adv.capabilities));
            item.emplace("instructions_policy", json::Value::make_string(adv.instructions_policy));
            json::Value::Array endpoints;
            for (const auto & e : adv.api_endpoints) {
                endpoints.push_back(json::Value::make_string(e));
            }
            item.emplace("api_endpoints", json::Value::make_array(std::move(endpoints)));
            arr.push_back(json::Value::make_object(std::move(item)));
        }
        root.emplace("loaders", json::Value::make_array(std::move(arr)));
        return dup_out(out_json, json::stringify(json::Value::make_object(std::move(root))),
                       "audiocpp_registry_loaders_json");
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_registry_loaders_json");
        return -1;
    }
}

int audiocpp_registry_devices_json(char ** out_json) {
    if (out_json == nullptr) {
        set_last_error("null out_json");
        return -1;
    }
    *out_json = nullptr;
    try {
        json::Value::Array arr;
        for (const auto & dev : engine::core::list_backend_devices()) {
            json::Value::Object item;
            item.emplace("backend", json::Value::make_string(dev.backend));
            item.emplace("index", json::Value::make_number(dev.index));
            item.emplace("name", json::Value::make_string(dev.name));
            item.emplace("type", json::Value::make_string(dev.type));
            arr.push_back(json::Value::make_object(std::move(item)));
        }
        return dup_out(out_json, json::stringify(json::Value::make_array(std::move(arr))),
                       "audiocpp_registry_devices_json");
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_registry_devices_json");
        return -1;
    }
}

int audiocpp_registry_supports_family(const audiocpp_registry * reg, const char * family) {
    // 返回 1 支持、0 不支持、-1 出错(传参非法或内部异常,详情见 last_error)。
    if (reg == nullptr || family == nullptr) {
        set_last_error("null reg or family");
        return -1;
    }
    try {
        return reg->storage.supports_family(std::string(family)) ? 1 : 0;
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_registry_supports_family");
        return -1;
    }
}

int audiocpp_registry_inspect_json(const audiocpp_registry * reg,
                                   const char * model_path,
                                   char ** out_json) {
    if (reg == nullptr || model_path == nullptr || out_json == nullptr) {
        set_last_error("null reg, model_path or out_json");
        return -1;
    }
    *out_json = nullptr;
    try {
        auto inspection = reg->storage.inspect(std::filesystem::path(model_path));
        return dup_out(out_json, json::stringify(dump_inspection(inspection)),
                       "audiocpp_registry_inspect_json");
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_registry_inspect_json");
        return -1;
    }
}

audiocpp_model * audiocpp_registry_load(const audiocpp_registry * reg,
                                        const char * model_path,
                                        const char * family_hint,
                                        const char * load_options_json) {
    if (reg == nullptr || model_path == nullptr) {
        set_last_error("null registry or model_path");
        return nullptr;
    }
    try {
        ModelLoadRequest request;
        request.model_path = model_path;
        if (family_hint != nullptr && *family_hint != '\0') {
            request.family_hint = std::string(family_hint);
        }
        if (load_options_json != nullptr && *load_options_json != '\0') {
            const json::Value root = json::parse(load_options_json);
            if (const auto * config_id = root.find("config_id"); config_id != nullptr && config_id->is_string()) {
                request.config_id = config_id->as_string();
            }
            if (const auto * weight_id = root.find("weight_id"); weight_id != nullptr && weight_id->is_string()) {
                request.weight_id = weight_id->as_string();
            }
            if (const auto * spec = root.find("model_spec_override");
                spec != nullptr && spec->is_string()) {
                request.model_spec_override = std::filesystem::path(spec->as_string());
            }
            fill_options_from_json(request.options, root.find("options"));
        }
        auto model = reg->storage.load(request);
        return new audiocpp_model{std::move(model)};
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return nullptr;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_registry_load");
        return nullptr;
    }
}

void audiocpp_registry_free(audiocpp_registry * reg) {
    delete reg;
}

/* ------------------------------------------------------------------ */
/* 模型                                                                 */
/* ------------------------------------------------------------------ */

int audiocpp_model_metadata_json(const audiocpp_model * model, char ** out_json) {
    if (out_json == nullptr || model == nullptr) {
        set_last_error("null out_json or model");
        return -1;
    }
    *out_json = nullptr;
    try {
        return dup_out(out_json, json::stringify(dump_metadata(model->storage->metadata())),
                       "audiocpp_model_metadata_json");
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_model_metadata_json");
        return -1;
    }
}

int audiocpp_model_capabilities_json(const audiocpp_model * model, char ** out_json) {
    if (out_json == nullptr || model == nullptr) {
        set_last_error("null out_json or model");
        return -1;
    }
    *out_json = nullptr;
    try {
        return dup_out(out_json, json::stringify(dump_capabilities(model->storage->capabilities())),
                       "audiocpp_model_capabilities_json");
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_model_capabilities_json");
        return -1;
    }
}

audiocpp_session * audiocpp_model_create_task_session(const audiocpp_model * model,
                                                      const char * task,
                                                      const char * mode,
                                                      const char * backend,
                                                      int device,
                                                      int threads,
                                                      const char * session_options_json) {
    if (model == nullptr || task == nullptr) {
        set_last_error("null model or task");
        return nullptr;
    }
    try {
        const auto task_kind = engine::runtime::parse_voice_task_kind(task);
        const RunMode run_mode = (mode != nullptr && std::string(mode) == "streaming")
                                     ? RunMode::Streaming
                                     : RunMode::Offline;
        TaskSpec spec{task_kind, run_mode};

        SessionOptions opts;
        std::string backend_name = backend != nullptr ? backend : "cpu";
        if (backend_name == "cuda") {
            opts.backend.type = engine::core::BackendType::Cuda;
        } else if (backend_name == "hip" || backend_name == "rocm") {
            opts.backend.type = engine::core::BackendType::Hip;
        } else if (backend_name == "vulkan") {
            opts.backend.type = engine::core::BackendType::Vulkan;
        } else if (backend_name == "metal") {
            opts.backend.type = engine::core::BackendType::Metal;
        } else if (backend_name == "best") {
            opts.backend.type = engine::core::BackendType::BestAvailable;
        } else {
            opts.backend.type = engine::core::BackendType::Cpu;
        }
        opts.backend.device = device;
        opts.backend.threads = threads > 0 ? threads : 1;
        if (session_options_json != nullptr && *session_options_json != '\0') {
            const json::Value root = json::parse(session_options_json);
            fill_options_from_json(opts.options, root.find("options"));
        }

        auto session = model->storage->create_task_session(spec, opts);
        auto * wrapper = new audiocpp_session{std::move(session), EventSink{}, {}, {}, {}};
        wrapper->family = wrapper->storage->family();
        wrapper->task_kind = engine::runtime::to_string(wrapper->storage->task_kind());
        wrapper->run_mode = engine::runtime::to_string(wrapper->storage->run_mode());
        return wrapper;
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return nullptr;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_model_create_task_session");
        return nullptr;
    }
}

void audiocpp_model_free(audiocpp_model * model) {
    delete model;
}

/* ------------------------------------------------------------------ */
/* 会话                                                                 */
/* ------------------------------------------------------------------ */

void audiocpp_session_free(audiocpp_session * session) {
    delete session;
}

const char * audiocpp_session_family(audiocpp_session * session) {
    return session != nullptr ? session->family.c_str() : nullptr;
}

const char * audiocpp_session_task_kind(audiocpp_session * session) {
    return session != nullptr ? session->task_kind.c_str() : nullptr;
}

const char * audiocpp_session_run_mode(audiocpp_session * session) {
    return session != nullptr ? session->run_mode.c_str() : nullptr;
}

int audiocpp_session_streaming_policy_json(audiocpp_session * session, char ** out_json) {
    if (out_json == nullptr || session == nullptr) {
        set_last_error("null out_json or session");
        return -1;
    }
    *out_json = nullptr;
    try {
        auto * streaming = dynamic_cast<IStreamingVoiceTaskSession *>(session->storage.get());
        if (streaming == nullptr) {
            set_last_error("session does not support streaming");
            return -1;
        }
        const auto policy = streaming->streaming_policy();
        json::Value::Object obj;
        const char * input = "none";
        if (policy.input == engine::runtime::StreamingInputKind::AudioChunks) {
            input = "audio_chunks";
        }
        obj.emplace("input", json::Value::make_string(input));
        const char * output = "final_result";
        if (policy.output == engine::runtime::StreamingOutputKind::PullEvents) {
            output = "pull_events";
        }
        obj.emplace("output", json::Value::make_string(output));
        obj.emplace("preferred_audio_chunk_samples",
                    json::Value::make_number(static_cast<double>(policy.preferred_audio_chunk_samples)));
        obj.emplace("preferred_audio_chunk_seconds", json::Value::make_number(policy.preferred_audio_chunk_seconds));
        return dup_out(out_json, json::stringify(json::Value::make_object(std::move(obj))),
                       "audiocpp_session_streaming_policy_json");
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_session_streaming_policy_json");
        return -1;
    }
}

int audiocpp_session_prepare(audiocpp_session * session, const char * request_json) {
    if (session == nullptr || request_json == nullptr) {
        set_last_error("null session or request_json");
        return -1;
    }
    try {
        const json::Value root = json::parse(request_json);
        const auto request = parse_task_request(root);
        session->storage->prepare(engine::runtime::build_preparation_request(request));
        return 0;
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_session_prepare");
        return -1;
    }
}

int audiocpp_session_run_offline(audiocpp_session * session,
                                 const char * request_json,
                                 char ** out_json) {
    if (out_json != nullptr) {
        *out_json = nullptr;
    }
    if (session == nullptr || request_json == nullptr) {
        set_last_error("null session or request_json");
        return -1;
    }
    try {
        auto * offline = dynamic_cast<IOfflineVoiceTaskSession *>(session->storage.get());
        if (offline == nullptr) {
            set_last_error("session does not support offline execution");
            return -1;
        }
        const json::Value root = json::parse(request_json);
        const auto request = parse_task_request(root);
        session->storage->prepare(engine::runtime::build_preparation_request(request));
        const TaskResult result = offline->run(request);
        if (out_json != nullptr) {
            return dup_out(out_json, json::stringify(dump_task_result(result)),
                           "audiocpp_session_run_offline");
        }
        return 0;
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_session_run_offline");
        return -1;
    }
}

void audiocpp_session_set_event_sink(audiocpp_session * session,
                                      audiocpp_stream_event_cb cb,
                                      void * user_data) {
    if (session == nullptr) {
        set_last_error("null session in audiocpp_session_set_event_sink");
        return;
    }
    try {
        std::lock_guard<std::mutex> lock(session->sink.mu);
        session->sink.cb = cb;
        session->sink.user_data = user_data;
        auto * streaming = dynamic_cast<IStreamingVoiceTaskSession *>(session->storage.get());
        if (streaming == nullptr) {
            return;
        }
        if (cb == nullptr) {
            streaming->set_stream_event_sink(nullptr);
            return;
        }
        EventSink * sink = &session->sink;
        streaming->set_stream_event_sink([sink](const StreamEvent & event) {
            // 派发期间持有锁:set(None) 返回后必无在途回调引用旧 user_data。
            // 因此回调内不得再调回会话方法(会自死锁),见 capi.h。
            std::lock_guard<std::mutex> dispatch_lock(sink->mu);
            if (sink->cb != nullptr) {
                const std::string json_str = json::stringify(dump_stream_event(event));
                sink->cb(sink->user_data, json_str.c_str(), event.is_final ? 1 : 0);
            }
        });
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
    } catch (...) {
        set_last_error("unknown exception in audiocpp_session_set_event_sink");
    }
}

int audiocpp_session_start(audiocpp_session * session, const char * request_json) {
    if (session == nullptr || request_json == nullptr) {
        set_last_error("null session or request_json");
        return -1;
    }
    try {
        auto * streaming = dynamic_cast<IStreamingVoiceTaskSession *>(session->storage.get());
        if (streaming == nullptr) {
            set_last_error("session does not support streaming");
            return -1;
        }
        const json::Value root = json::parse(request_json);
        const auto request = parse_task_request(root);
        session->storage->prepare(engine::runtime::build_preparation_request(request));
        streaming->start_stream(request);
        return 0;
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_session_start");
        return -1;
    }
}

int audiocpp_session_process_audio(audiocpp_session * session,
                                   const float * samples,
                                   size_t count,
                                   int sample_rate,
                                   int channels,
                                   int64_t start_sample,
                                   char ** out_event_json) {
    if (out_event_json != nullptr) {
        *out_event_json = nullptr;
    }
    if (session == nullptr || (count != 0 && samples == nullptr)) {
        set_last_error("null session or samples");
        return -1;
    }
    try {
        auto * streaming = dynamic_cast<IStreamingVoiceTaskSession *>(session->storage.get());
        if (streaming == nullptr) {
            set_last_error("session does not support streaming");
            return -1;
        }
        engine::runtime::AudioChunk chunk;
        chunk.sample_rate = sample_rate;
        chunk.channels = channels;
        chunk.start_sample = start_sample;
        // count==0 时不触碰 samples(可能为 null 的空 slice 指针)。
        if (count != 0) {
            chunk.samples.assign(samples, samples + count);
        }
        const StreamEvent event = streaming->process_audio_chunk(chunk);
        if (out_event_json != nullptr) {
            return dup_out(out_event_json, json::stringify(dump_stream_event(event)),
                           "audiocpp_session_process_audio");
        }
        return 0;
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_session_process_audio");
        return -1;
    }
}

int audiocpp_session_finish(audiocpp_session * session, char ** out_json) {
    if (out_json != nullptr) {
        *out_json = nullptr;
    }
    if (session == nullptr) {
        set_last_error("null session");
        return -1;
    }
    try {
        auto * streaming = dynamic_cast<IStreamingVoiceTaskSession *>(session->storage.get());
        if (streaming == nullptr) {
            set_last_error("session does not support streaming");
            return -1;
        }
        const TaskResult result = streaming->finish_stream();
        if (out_json != nullptr) {
            return dup_out(out_json, json::stringify(dump_task_result(result)),
                           "audiocpp_session_finish");
        }
        return 0;
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_session_finish");
        return -1;
    }
}

int audiocpp_session_reset(audiocpp_session * session) {
    if (session == nullptr) {
        set_last_error("null session in audiocpp_session_reset");
        return -1;
    }
    try {
        auto * streaming = dynamic_cast<IStreamingVoiceTaskSession *>(session->storage.get());
        if (streaming != nullptr) {
            streaming->reset();
        }
        return 0;
    } catch (const std::exception & ex) {
        set_last_error(ex.what());
        return -1;
    } catch (...) {
        set_last_error("unknown exception in audiocpp_session_reset");
        return -1;
    }
}