-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkokoro-service.cpp
More file actions
1817 lines (1600 loc) · 72 KB
/
Copy pathkokoro-service.cpp
File metadata and controls
1817 lines (1600 loc) · 72 KB
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
// kokoro-service.cpp — Text-to-Speech (TTS) synthesis stage using Kokoro + espeak-ng.
//
// Pipeline position: LLaMA → [Kokoro] → OAP
//
// Receives response text from LLaMA and synthesizes 24kHz float32 PCM audio using
// the Kokoro TTS model (CoreML). Streams audio chunks to the
// Outbound Audio Processor (OAP) for downsampling and G.711 encoding.
//
// Phonemization pipeline:
// 1. espeak-ng (via libespeak-ng) converts text → IPA phoneme string.
// Language selection: German ("de") or English ("en-us") based on detect_german().
// A phoneme cache (PHONEME_CACHE_MAX=10000 entries, LRU eviction) avoids re-running
// espeak-ng for repeated phrases.
// 2. KokoroVocab maps phoneme strings → int64 token IDs using a greedy longest-match
// scan (up to 4 chars per token, UTF-8 aware) over the vocab.json lookup table.
// 3. Input is padded to 512 tokens and passed to the duration model.
//
// Model architecture (two-stage):
// Stage 1 — Duration model: predicts phoneme durations and generates alignment tensors
// (pred_dur, d, t_en, s, ref_s). Runs the style encoder over a reference style
// embedding from voice.bin.
// Stage 2 — Decoder model: generates the audio waveform from the alignment tensors.
// On Apple Silicon: uses CoreML ANE (Apple Neural Engine) split decoder when
// compiled with -DKOKORO_COREML. Falls back to TorchScript GPU path otherwise.
//
// CoreML split decoder (KOKORO_COREML):
// CoreMLDurationModel and CoreMLDecoderModel wrap MLModel instances configured with
// MLComputeUnitsAll (ANE + GPU + CPU). Data is bridged to CoreML
// via MLMultiArray memory copies. This path provides ~2-4× speedup on M-series chips
// compared to CPU-only inference for the decoder stage alone.
//
// Audio output normalization:
// normalize_audio() scales audio to 0.90 peak ceiling to prevent clipping distortion
// in the G.711 encoder. Skips near-silent (peak < 0.01) and already-normalized audio.
//
// SPEECH_ACTIVE handling:
// If a SPEECH_ACTIVE signal arrives during synthesis (caller starts speaking),
// the current synthesis is abandoned immediately and the output buffer is cleared.
// This prevents stale TTS audio from playing over the caller's speech.
//
// CMD port (Kokoro diagnostic port 13144): PING, STATUS, SET_LOG_LEVEL commands.
// STATUS returns: active call count, dock connection state, speed, G2P backend.
#include "ktensor.h"
#include "har_source.h"
#include "neural-g2p.h"
#include <espeak-ng/speak_lib.h>
#include "interconnect.h"
#include "tts-engine-client.h"
#include "tts-common.h"
#include <atomic>
#include <chrono>
#include <cmath>
#include <csignal>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <future>
#include <map>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#include <unistd.h>
#include <getopt.h>
#include <cmath>
#ifdef KOKORO_COREML
#import <CoreML/CoreML.h>
#import <Foundation/Foundation.h>
#endif
using namespace whispertalk;
// Shared TTS audio constants (single source of truth: tts-common.h).
static constexpr int KOKORO_SAMPLE_RATE = static_cast<int>(whispertalk::tts::kTTSSampleRate);
// Hard upper bound on a single synthesis output. Long LLaMA responses can
// easily exceed 10 s after multi-chunk merging in pipeline_.synthesize();
// 120 s is the realistic ceiling for a single conversational turn and
// covers the worst-case sentence we have observed in production.
static constexpr size_t MAX_AUDIO_SAMPLES = 120 * static_cast<size_t>(KOKORO_SAMPLE_RATE);
static constexpr size_t PHONEME_CACHE_MAX = 10000;
// Diagnostic cmd port for the Kokoro engine (see spec §4.2). Separate from
// the TTS dock's own cmd port (13142) so operators can query the engine
// process directly without going through the dock.
static constexpr uint16_t KOKORO_ENGINE_CMD_PORT = whispertalk::tts::kKokoroEngineCmdPort;
struct KokoroVocab {
std::map<std::string, int64_t> phoneme_to_id;
bool load(const std::string& path) {
std::ifstream f(path);
if (!f.is_open()) return false;
std::string content((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
size_t pos = 0;
while ((pos = content.find("\"", pos)) != std::string::npos) {
pos++;
size_t end = content.find("\"", pos);
if (end == std::string::npos) break;
std::string key = content.substr(pos, end - pos);
pos = end + 1;
size_t colon = content.find(":", pos);
if (colon == std::string::npos) break;
size_t num_start = colon + 1;
while (num_start < content.size() && (content[num_start] == ' ' || content[num_start] == '\n'))
num_start++;
size_t num_end = num_start;
while (num_end < content.size() && (std::isdigit(content[num_end]) || content[num_end] == '-'))
num_end++;
if (num_end > num_start) {
int64_t val = std::stoll(content.substr(num_start, num_end - num_start));
phoneme_to_id[key] = val;
}
pos = num_end;
}
return !phoneme_to_id.empty();
}
std::vector<int64_t> encode(const std::string& phonemes) const {
std::vector<int64_t> ids;
ids.push_back(0);
size_t i = 0;
while (i < phonemes.size()) {
bool found = false;
for (int len = 4; len >= 1; len--) {
if (i + len > phonemes.size()) continue;
std::string key = phonemes.substr(i, len);
auto it = phoneme_to_id.find(key);
if (it != phoneme_to_id.end()) {
ids.push_back(it->second);
i += len;
found = true;
break;
}
}
if (!found) {
unsigned char c = static_cast<unsigned char>(phonemes[i]);
if ((c & 0x80) != 0) {
int bytes = 1;
if ((c & 0xE0) == 0xC0) bytes = 2;
else if ((c & 0xF0) == 0xE0) bytes = 3;
else if ((c & 0xF8) == 0xF0) bytes = 4;
if (i + bytes <= phonemes.size()) {
std::string utf8char = phonemes.substr(i, bytes);
auto it = phoneme_to_id.find(utf8char);
if (it != phoneme_to_id.end()) {
ids.push_back(it->second);
}
}
i += bytes;
} else {
i++;
}
}
}
ids.push_back(0);
return ids;
}
};
#ifdef KOKORO_COREML
class CoreMLDurationModel {
public:
bool load(const std::string& mlmodelc_path) {
@autoreleasepool {
NSString* path = [NSString stringWithUTF8String:mlmodelc_path.c_str()];
NSURL* url = [NSURL fileURLWithPath:path];
MLModelConfiguration* config = [[MLModelConfiguration alloc] init];
config.computeUnits = MLComputeUnitsAll;
NSError* error = nil;
model_ = [MLModel modelWithContentsOfURL:url configuration:config error:&error];
if (error || !model_) {
std::fprintf(stderr, "CoreML: Failed to load duration model: %s\n",
error ? [[error description] UTF8String] : "unknown error");
return false;
}
[model_ retain];
std::printf("CoreML duration model loaded from %s\n", mlmodelc_path.c_str());
available_ = true;
return true;
}
}
struct DurationOutput {
std::vector<int64_t> pred_dur;
KTensor d;
KTensor t_en;
KTensor s;
KTensor ref_s_out;
};
bool predict(const std::vector<int32_t>& input_ids_vec,
const KTensor& ref_s_tensor,
float speed_val,
const std::vector<int32_t>& attention_mask_vec,
DurationOutput& output) {
if (!available_) return false;
@autoreleasepool {
NSError* error = nil;
NSArray<NSNumber*>* ids_shape = @[@1, @512];
MLMultiArray* input_ids_arr = [[MLMultiArray alloc]
initWithShape:ids_shape dataType:MLMultiArrayDataTypeInt32 error:&error];
if (error) return false;
int32_t* ids_ptr = (int32_t*)input_ids_arr.dataPointer;
for (int i = 0; i < 512; i++) {
ids_ptr[i] = (i < (int)input_ids_vec.size()) ? input_ids_vec[i] : 0;
}
NSArray<NSNumber*>* ref_shape = @[@1, @256];
MLMultiArray* ref_s_arr = [[MLMultiArray alloc]
initWithShape:ref_shape dataType:MLMultiArrayDataTypeFloat32 error:&error];
if (error) return false;
std::memcpy((float*)ref_s_arr.dataPointer, ref_s_tensor.ptr(), 256 * sizeof(float));
NSArray<NSNumber*>* speed_shape = @[@1];
MLMultiArray* speed_arr = [[MLMultiArray alloc]
initWithShape:speed_shape dataType:MLMultiArrayDataTypeFloat32 error:&error];
if (error) return false;
((float*)speed_arr.dataPointer)[0] = speed_val;
MLMultiArray* mask_arr = [[MLMultiArray alloc]
initWithShape:ids_shape dataType:MLMultiArrayDataTypeInt32 error:&error];
if (error) return false;
int32_t* mask_ptr = (int32_t*)mask_arr.dataPointer;
for (int i = 0; i < 512; i++) {
mask_ptr[i] = (i < (int)attention_mask_vec.size()) ? attention_mask_vec[i] : 0;
}
NSDictionary* input_dict = @{
@"input_ids": input_ids_arr,
@"ref_s": ref_s_arr,
@"speed": speed_arr,
@"attention_mask": mask_arr
};
auto features = [[MLDictionaryFeatureProvider alloc] initWithDictionary:input_dict error:&error];
if (error) return false;
auto result = [model_ predictionFromFeatures:features error:&error];
if (error || !result) {
std::fprintf(stderr, "CoreML duration predict failed: %s\n",
error ? [[error description] UTF8String] : "unknown");
return false;
}
auto extract = [&](NSString* name, std::initializer_list<int64_t> shape) -> KTensor {
MLMultiArray* arr = [result featureValueForName:name].multiArrayValue;
if (!arr) return {};
auto t = KTensor::zeros(shape);
std::memcpy(t.ptr(), (float*)arr.dataPointer, t.numel() * sizeof(float));
return t;
};
{
MLMultiArray* arr = [result featureValueForName:@"pred_dur"].multiArrayValue;
if (!arr) return false;
output.pred_dur.resize(512);
int32_t* src = (int32_t*)arr.dataPointer;
for (int i = 0; i < 512; i++) output.pred_dur[i] = src[i];
}
output.d = extract(@"d", {1, 512, 640});
output.t_en = extract(@"t_en", {1, 512, 512});
output.s = extract(@"s", {1, 128});
output.ref_s_out = extract(@"ref_s_out", {1, 256});
return !output.pred_dur.empty() && output.t_en.defined() && output.d.defined();
}
}
bool is_available() const { return available_; }
~CoreMLDurationModel() {
if (model_) [model_ release];
}
private:
MLModel* model_ = nil;
bool available_ = false;
};
class CoreMLSplitDecoder {
public:
struct BucketInfo {
std::string name;
int asr_frames;
int f0_frames;
int har_channels;
int har_time;
MLModel* model = nil;
};
bool load(const std::string& variants_dir) {
@autoreleasepool {
struct { const char* name; int asr; int f0; int harc; int hart; } buckets[] = {
{"3s", 72, 144, 11, 8641},
{"5s", 120, 240, 11, 14401},
{"10s", 240, 480, 11, 28801},
};
MLModelConfiguration* config = [[MLModelConfiguration alloc] init];
config.computeUnits = MLComputeUnitsAll;
for (auto& b : buckets) {
std::string path = variants_dir + "/kokoro_decoder_split_" + b.name + ".mlmodelc";
struct stat st;
if (stat(path.c_str(), &st) != 0) continue;
NSString* ns_path = [NSString stringWithUTF8String:path.c_str()];
NSURL* url = [NSURL fileURLWithPath:ns_path];
NSError* error = nil;
MLModel* model = [MLModel modelWithContentsOfURL:url configuration:config error:&error];
if (error || !model) {
std::fprintf(stderr, "CoreML: Failed to load split decoder %s: %s\n",
b.name, error ? [[error description] UTF8String] : "unknown");
continue;
}
BucketInfo info;
info.name = b.name;
info.asr_frames = b.asr;
info.f0_frames = b.f0;
info.har_channels = b.harc;
info.har_time = b.hart;
info.model = model;
[model retain];
buckets_.push_back(info);
std::printf("CoreML split decoder loaded: %s (asr=%d, f0=%d)\n", b.name, b.asr, b.f0);
}
if (buckets_.empty()) return false;
std::string har_path = variants_dir + "/har_weights.bin";
if (!har_source_.load(har_path)) {
std::fprintf(stderr, "HAR weights not found: %s\n", har_path.c_str());
return false;
}
std::printf("HAR source loaded from %s\n", har_path.c_str());
available_ = true;
return true;
}
}
const BucketInfo* select_bucket(int f0_frames) const {
for (auto& b : buckets_) {
if (b.f0_frames >= f0_frames) return &b;
}
return buckets_.empty() ? nullptr : &buckets_.back();
}
int max_asr_frames() const {
if (buckets_.empty()) return 0;
return buckets_.back().asr_frames;
}
std::vector<float> decode(const BucketInfo& bucket,
const KTensor& asr,
const KTensor& f0_pred,
const KTensor& n_pred,
const KTensor& ref_s,
const std::vector<float>& har) {
@autoreleasepool {
NSError* error = nil;
auto make_array = [&](NSArray<NSNumber*>* shape, const float* src, int64_t count) -> MLMultiArray* {
MLMultiArray* arr = [[MLMultiArray alloc] initWithShape:shape
dataType:MLMultiArrayDataTypeFloat32 error:&error];
if (error) return nil;
std::memcpy((float*)arr.dataPointer, src, count * sizeof(float));
return arr;
};
auto asr_arr = make_array(@[@1, @512, @(bucket.asr_frames)], asr.ptr(), asr.numel());
auto f0_arr = make_array(@[@1, @(bucket.f0_frames)], f0_pred.ptr(), f0_pred.numel());
auto n_arr = make_array(@[@1, @(bucket.f0_frames)], n_pred.ptr(), n_pred.numel());
auto refs_arr = make_array(@[@1, @256], ref_s.ptr(), ref_s.numel());
int64_t har_total = (int64_t)(bucket.har_channels * 2) * bucket.har_time;
auto har_arr = make_array(@[@1, @(bucket.har_channels * 2), @(bucket.har_time)], har.data(), har_total);
if (!asr_arr || !f0_arr || !n_arr || !refs_arr || !har_arr) return {};
NSDictionary* input_dict = @{
@"asr": asr_arr, @"F0_pred": f0_arr, @"N_pred": n_arr,
@"ref_s": refs_arr, @"har": har_arr
};
auto features = [[MLDictionaryFeatureProvider alloc] initWithDictionary:input_dict error:&error];
if (error) return {};
auto result = [bucket.model predictionFromFeatures:features error:&error];
if (error || !result) {
std::fprintf(stderr, "CoreML split decoder predict failed: %s\n",
error ? [[error description] UTF8String] : "unknown");
return {};
}
MLMultiArray* wav = [result featureValueForName:@"waveform"].multiArrayValue;
if (!wav) return {};
int64_t n_samples = wav.count;
std::vector<float> samples(n_samples);
std::memcpy(samples.data(), (float*)wav.dataPointer, n_samples * sizeof(float));
return samples;
}
}
std::vector<float> compute_har(const float* f0, int f0_frames) {
return har_source_.compute(f0, f0_frames);
}
bool is_available() const { return available_; }
~CoreMLSplitDecoder() {
for (auto& b : buckets_) {
if (b.model) [b.model release];
}
}
private:
std::vector<BucketInfo> buckets_;
HarSource har_source_;
bool available_ = false;
};
class CoreMLF0NPredictor {
public:
struct BucketInfo {
std::string name;
int asr_frames;
int f0_frames;
MLModel* model = nil;
};
bool load(const std::string& coreml_dir) {
@autoreleasepool {
struct { const char* name; int asr; int f0; } buckets[] = {
{"3s", 72, 144},
{"5s", 120, 240},
{"10s", 240, 480},
};
MLModelConfiguration* config = [[MLModelConfiguration alloc] init];
config.computeUnits = MLComputeUnitsAll;
for (auto& b : buckets) {
std::string path = coreml_dir + "/kokoro_f0n_" + b.name + ".mlmodelc";
struct stat st;
if (stat(path.c_str(), &st) != 0) {
path = coreml_dir + "/kokoro_f0n_" + b.name + ".mlpackage";
if (stat(path.c_str(), &st) != 0) continue;
}
NSString* ns_path = [NSString stringWithUTF8String:path.c_str()];
NSURL* url = [NSURL fileURLWithPath:ns_path];
NSError* error = nil;
MLModel* model = [MLModel modelWithContentsOfURL:url configuration:config error:&error];
if (error || !model) {
std::fprintf(stderr, "CoreML: Failed to load F0N predictor %s: %s\n",
b.name, error ? [[error description] UTF8String] : "unknown");
continue;
}
BucketInfo info;
info.name = b.name;
info.asr_frames = b.asr;
info.f0_frames = b.f0;
info.model = model;
[model retain];
buckets_.push_back(info);
std::printf("CoreML F0/N predictor loaded: %s (asr=%d, f0=%d)\n", b.name, b.asr, b.f0);
}
available_ = !buckets_.empty();
return available_;
}
}
const BucketInfo* select_bucket(int asr_frames) const {
for (auto& b : buckets_) {
if (b.asr_frames >= asr_frames) return &b;
}
return buckets_.empty() ? nullptr : &buckets_.back();
}
bool predict(const BucketInfo& bucket,
const float* en_data, int en_dim, int en_frames,
const float* s_data,
KTensor& f0_out, KTensor& n_out) {
@autoreleasepool {
NSError* error = nil;
MLMultiArray* en_arr = [[MLMultiArray alloc]
initWithShape:@[@1, @(en_dim), @(bucket.asr_frames)]
dataType:MLMultiArrayDataTypeFloat32 error:&error];
if (error) return false;
float* en_ptr = (float*)en_arr.dataPointer;
std::memset(en_ptr, 0, sizeof(float) * en_dim * bucket.asr_frames);
int actual = std::min(en_frames, bucket.asr_frames);
for (int ch = 0; ch < en_dim; ch++) {
std::memcpy(en_ptr + ch * bucket.asr_frames,
en_data + ch * en_frames,
actual * sizeof(float));
}
MLMultiArray* s_arr = [[MLMultiArray alloc]
initWithShape:@[@1, @128]
dataType:MLMultiArrayDataTypeFloat32 error:&error];
if (error) return false;
std::memcpy((float*)s_arr.dataPointer, s_data, 128 * sizeof(float));
NSDictionary* input_dict = @{@"en": en_arr, @"s": s_arr};
auto features = [[MLDictionaryFeatureProvider alloc] initWithDictionary:input_dict error:&error];
if (error) return false;
auto result = [bucket.model predictionFromFeatures:features error:&error];
if (error || !result) {
std::fprintf(stderr, "CoreML F0N predict failed: %s\n",
error ? [[error description] UTF8String] : "unknown");
return false;
}
MLMultiArray* f0_arr = [result featureValueForName:@"F0_pred"].multiArrayValue;
MLMultiArray* n_arr_out = [result featureValueForName:@"N_pred"].multiArrayValue;
if (!f0_arr || !n_arr_out) return false;
f0_out = KTensor::zeros({1, (int64_t)bucket.f0_frames});
n_out = KTensor::zeros({1, (int64_t)bucket.f0_frames});
std::memcpy(f0_out.ptr(), (float*)f0_arr.dataPointer, bucket.f0_frames * sizeof(float));
std::memcpy(n_out.ptr(), (float*)n_arr_out.dataPointer, bucket.f0_frames * sizeof(float));
return true;
}
}
bool is_available() const { return available_; }
~CoreMLF0NPredictor() {
for (auto& b : buckets_) {
if (b.model) [b.model release];
}
}
private:
std::vector<BucketInfo> buckets_;
bool available_ = false;
};
#endif
struct AlignedIntermediates {
KTensor asr;
KTensor f0_pred;
KTensor n_pred;
KTensor ref_s_dec;
KTensor ref_s_full;
bool valid = false;
std::vector<int64_t> pred_dur;
int actual_len = 0;
int64_t total_frames = 0;
KTensor d_enc;
KTensor s_style;
};
class KokoroPipeline {
public:
bool initialize(const std::string& models_dir, const std::string& voice_name, const std::string& variant) {
std::string base_dir = models_dir + "/" + variant;
std::string vocab_path = base_dir + "/vocab.json";
std::string voice_path = base_dir + "/" + voice_name + "_voice.bin";
std::string variants_dir = base_dir + "/decoder_variants";
if (!vocab_.load(vocab_path)) {
std::fprintf(stderr, "Failed to load vocab from %s\n", vocab_path.c_str());
return false;
}
std::printf("Loaded vocab: %zu entries\n", vocab_.phoneme_to_id.size());
if (!load_voice_pack(voice_path, voice_name)) {
return false;
}
#ifdef KOKORO_COREML
std::string coreml_path = base_dir + "/coreml/kokoro_duration.mlmodelc";
struct stat st;
if (stat(coreml_path.c_str(), &st) == 0) {
coreml_duration_ = std::make_unique<CoreMLDurationModel>();
if (coreml_duration_->load(coreml_path)) {
std::printf("CoreML duration model ENABLED (ANE)\n");
coreml_available_ = true;
} else {
coreml_duration_.reset();
std::fprintf(stderr, "CoreML duration model load failed\n");
return false;
}
} else {
std::fprintf(stderr, "CoreML duration model not found at %s\n", coreml_path.c_str());
return false;
}
coreml_split_decoder_ = std::make_unique<CoreMLSplitDecoder>();
if (coreml_split_decoder_->load(variants_dir)) {
std::printf("CoreML split decoder ENABLED (ANE)\n");
} else {
coreml_split_decoder_.reset();
std::fprintf(stderr, "CoreML split decoder load failed from %s\n", variants_dir.c_str());
return false;
}
std::string coreml_dir = base_dir + "/coreml";
coreml_f0n_ = std::make_unique<CoreMLF0NPredictor>();
if (coreml_f0n_->load(coreml_dir)) {
std::printf("CoreML F0/N predictor ENABLED (ANE)\n");
} else {
coreml_f0n_.reset();
std::printf("CoreML F0/N predictor not available — using zero F0/N fallback\n");
}
#else
std::fprintf(stderr, "FATAL: kokoro-service requires CoreML (macOS). Build with KOKORO_COREML=ON\n");
return false;
#endif
std::string espeak_data = tts::resolve_espeak_data_dir();
if (espeak_data.empty()) {
std::fprintf(stderr, "Cannot find espeak-ng-data directory. "
"Set ESPEAK_NG_DATA env var or install espeak-ng.\n");
return false;
}
std::printf("Using espeak-ng data: %s\n", espeak_data.c_str());
int result = espeak_Initialize(AUDIO_OUTPUT_RETRIEVAL, 0,
espeak_data.c_str(), 0);
if (result == -1) {
std::fprintf(stderr, "Failed to initialize espeak-ng\n");
return false;
}
espeak_SetVoiceByName("de");
std::printf("espeak-ng initialized (German)\n");
#ifdef __APPLE__
if (g2p_backend_ != G2PBackend::ESPEAK) {
std::string g2p_path = models_dir + "/g2p/de_g2p.mlmodelc";
neural_g2p_ = std::make_unique<NeuralG2P>();
if (!neural_g2p_->load(g2p_path)) {
neural_g2p_.reset();
std::printf("Neural G2P not available — using espeak-ng for German\n");
} else {
std::printf("Neural G2P loaded (German)\n");
}
} else {
std::printf("Neural G2P skipped (--g2p espeak)\n");
}
#endif
warmup();
return true;
}
void warmup() {
std::printf("Warming up CoreML models...\n");
auto t0 = std::chrono::steady_clock::now();
auto samples = synthesize("Hallo.", 1.0f);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - t0).count();
std::printf("CoreML warmup done: %lldms (%zu samples)\n", (long long)ms, samples.size());
}
static bool detect_german(const std::string& text) {
static const char* umlaut_markers[] = {
"ä", "ö", "ü", "Ä", "Ö", "Ü", "ß",
"möchte", "könnte", "würde", "für",
nullptr
};
for (int i = 0; umlaut_markers[i]; i++) {
if (text.find(umlaut_markers[i]) != std::string::npos) return true;
}
static const char* de_words[] = {
"ich", "und", "nicht", "haben", "werden",
"bitte", "danke", "gerne",
nullptr
};
for (int i = 0; de_words[i]; i++) {
std::string word = de_words[i];
size_t pos = 0;
while ((pos = text.find(word, pos)) != std::string::npos) {
bool left_ok = (pos == 0 || !std::isalpha(static_cast<unsigned char>(text[pos - 1])));
bool right_ok = (pos + word.size() >= text.size() ||
!std::isalpha(static_cast<unsigned char>(text[pos + word.size()])));
if (left_ok && right_ok) return true;
pos += word.size();
}
}
int ascii_alpha = 0;
for (unsigned char c : text) {
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) ascii_alpha++;
}
return ascii_alpha < (int)text.size() / 2;
}
static std::string clean_phonemes(const std::string& ph) {
std::string out;
out.reserve(ph.size());
for (size_t i = 0; i < ph.size(); i++) {
unsigned char c = static_cast<unsigned char>(ph[i]);
if (c == '\n' || c == '\r') continue;
if (c == '(' || c == ')') continue;
out.push_back(ph[i]);
}
while (!out.empty() && (out.back() == ' ' || out.back() == '\t')) out.pop_back();
return out;
}
std::string phonemize(const std::string& text) {
bool is_de = detect_german(text);
std::string cache_key = text + (is_de ? "|de" : "|en");
{
std::lock_guard<std::mutex> lock(cache_mutex_);
auto it = phoneme_cache_.find(cache_key);
if (it != phoneme_cache_.end()) return it->second;
}
std::string result;
#ifdef __APPLE__
bool use_neural_g2p = is_de &&
neural_g2p_ && neural_g2p_->is_available() &&
g2p_backend_ != G2PBackend::ESPEAK;
if (use_neural_g2p) {
result = neural_g2p_->phonemize(text);
} else {
#endif
{
std::lock_guard<std::mutex> lock(espeak_mutex_);
espeak_SetVoiceByName(is_de ? "de" : "en-us");
const char* ptr = text.c_str();
while (ptr && *ptr) {
const char* ph = espeak_TextToPhonemes(
(const void**)&ptr, espeakCHARS_UTF8, espeakPHONEMES_IPA);
if (ph) result += ph;
}
}
#ifdef __APPLE__
}
#endif
result = clean_phonemes(result);
{
std::lock_guard<std::mutex> lock(cache_mutex_);
if (phoneme_cache_.size() >= PHONEME_CACHE_MAX) {
phoneme_cache_.clear();
}
phoneme_cache_[cache_key] = result;
}
return result;
}
std::vector<float> synthesize(const std::string& text, float speed = 1.0f,
const KTensor* prev_ref_s = nullptr,
KTensor* ref_s_out = nullptr) {
std::string phonemes = phonemize(text);
if (phonemes.empty()) return {};
auto ids = vocab_.encode(phonemes);
if (ids.size() <= 2) return {};
KTensor ref_s;
if (prev_ref_s && prev_ref_s->defined() && prev_ref_s->numel() == 256) {
ref_s = KTensor::from_data(prev_ref_s->ptr(), {1, 256});
} else {
int phoneme_count = static_cast<int>(ids.size()) - 2;
int voice_idx = std::min(phoneme_count - 1, voice_entries_ - 1);
voice_idx = std::max(0, voice_idx);
ref_s = KTensor::from_data(voice_pack_.ptr() + voice_idx * 256, {1, 256});
}
#ifdef KOKORO_COREML
return synthesize_coreml(ids, ref_s, speed, ref_s_out);
#else
(void)speed;
(void)ref_s_out;
return {};
#endif
}
#ifdef KOKORO_COREML
std::vector<float> decode_part(const AlignedIntermediates& inter,
int phon_start, int phon_end,
int64_t frame_start, int64_t num_frames) {
if (num_frames <= 0) return {};
auto asr_slice = KTensor::zeros({1, 512, num_frames});
int64_t src_time = inter.asr.size(2);
for (int ch = 0; ch < 512; ch++) {
std::memcpy(asr_slice.ptr() + (int64_t)ch * num_frames,
inter.asr.ptr() + (int64_t)ch * src_time + frame_start,
num_frames * sizeof(float));
}
KTensor f0_pred, n_pred;
bool f0n_ok = false;
if (coreml_f0n_ && coreml_f0n_->is_available() && inter.d_enc.defined() && inter.s_style.defined()) {
int d_dim = 640;
auto en = KTensor::zeros({1, (int64_t)d_dim, num_frames});
{
int64_t pos = 0;
for (int i = phon_start; i < phon_end; i++) {
int64_t dur = inter.pred_dur[i];
if (dur <= 0) continue;
int64_t frames = std::min(dur, num_frames - pos);
for (int ch = 0; ch < d_dim; ch++) {
float val = inter.d_enc.at3(0, i, ch);
std::fill_n(en.ptr() + (int64_t)ch * num_frames + pos, frames, val);
}
pos += dur;
}
}
auto* f0n_bucket = coreml_f0n_->select_bucket((int)num_frames);
if (f0n_bucket) {
f0n_ok = coreml_f0n_->predict(*f0n_bucket, en.ptr(), d_dim, (int)num_frames,
inter.s_style.ptr(), f0_pred, n_pred);
if (f0n_ok) {
int64_t f0n_actual = num_frames * 2;
if (f0n_actual < (int64_t)f0_pred.size(1))
f0_pred.truncate_last_dim(f0n_actual);
if (f0n_actual < (int64_t)n_pred.size(1))
n_pred.truncate_last_dim(f0n_actual);
}
}
}
if (!f0n_ok) {
int64_t f0_len = num_frames * 2;
f0_pred = KTensor::zeros({1, f0_len});
n_pred = KTensor::zeros({1, f0_len});
}
int f0_len = static_cast<int>(f0_pred.size(1));
auto* sb = coreml_split_decoder_->select_bucket(f0_len);
if (!sb) return {};
int asr_frames = sb->asr_frames;
int f0_frames = sb->f0_frames;
auto f0_padded = KTensor::zeros({1, (int64_t)f0_frames});
auto n_padded = KTensor::zeros({1, (int64_t)f0_frames});
int f0_actual = std::min(f0_len, f0_frames);
std::memcpy(f0_padded.ptr(), f0_pred.ptr(), f0_actual * sizeof(float));
std::memcpy(n_padded.ptr(), n_pred.ptr(), f0_actual * sizeof(float));
float* f0_ptr = f0_padded.ptr();
int f0_frames_cap = f0_frames;
auto har_future = std::async(std::launch::async,
[this, f0_ptr, f0_frames_cap]() {
return coreml_split_decoder_->compute_har(f0_ptr, f0_frames_cap);
});
auto asr_padded = KTensor::zeros({1, 512, (int64_t)asr_frames});
int asr_actual = std::min((int)num_frames, asr_frames);
for (int ch = 0; ch < 512; ch++) {
std::memcpy(asr_padded.ptr() + (int64_t)ch * asr_frames,
asr_slice.ptr() + (int64_t)ch * num_frames,
asr_actual * sizeof(float));
}
auto har = har_future.get();
if (har.empty()) return {};
int har_time = sb->har_time;
int har_channels = sb->har_channels * 2;
int64_t har_expected = (int64_t)har_channels * har_time;
std::vector<float> har_padded(har_expected, 0.0f);
int har_actual_frames = std::min((int)(har.size() / har_channels), har_time);
for (int c = 0; c < har_channels; c++) {
std::memcpy(har_padded.data() + c * har_time,
har.data() + c * har_actual_frames,
har_actual_frames * sizeof(float));
}
auto audio = coreml_split_decoder_->decode(*sb, asr_padded, f0_padded, n_padded,
inter.ref_s_dec, har_padded);
if (!audio.empty() && num_frames < asr_frames) {
int64_t samples_per_frame = (int64_t)audio.size() / asr_frames;
int64_t trim_to = num_frames * samples_per_frame;
if (trim_to > 0 && (int64_t)audio.size() > trim_to)
audio.resize(trim_to);
}
return audio;
}
std::vector<float> synthesize_coreml(const std::vector<int64_t>& ids,
const KTensor& ref_s,
float speed,
KTensor* ref_s_out = nullptr) {
if (!coreml_available_ || !coreml_split_decoder_) return {};
auto intermediates = run_duration_and_align(ids, ref_s, speed);
if (!intermediates.valid) return {};
if (ref_s_out && intermediates.ref_s_full.defined() && intermediates.ref_s_full.numel() == 256) {
*ref_s_out = intermediates.ref_s_full;
}
const int max_asr = coreml_split_decoder_->max_asr_frames();
if (intermediates.total_frames > max_asr && intermediates.actual_len > 2) {
struct ChunkRange { int phon_start; int phon_end; int64_t frame_start; int64_t num_frames; };
std::vector<ChunkRange> chunks;
int64_t cum = 0;
int chunk_start = 0;
int64_t chunk_frame_start = 0;
for (int i = 0; i < intermediates.actual_len; i++) {
int64_t next = cum + intermediates.pred_dur[i];
if (next > max_asr && i > chunk_start) {
chunks.push_back({chunk_start, i, chunk_frame_start, cum});
chunk_frame_start += cum;
chunk_start = i;
cum = intermediates.pred_dur[i];
} else {
cum = next;
}
}
if (chunk_start < intermediates.actual_len) {
chunks.push_back({chunk_start, intermediates.actual_len, chunk_frame_start, cum});
}
std::fprintf(stderr, "Splitting long synthesis (total_frames=%lld > max_asr=%d) into %zu chunks\n",
(long long)intermediates.total_frames, max_asr, chunks.size());
std::vector<float> result;
// Equal-power crossfade at chunk seams masks F0/N discontinuities and
// zero-padded edges between independently-decoded segments. 8ms @24kHz
// = 192 samples — short enough to be inaudible musically, long enough
// to suppress the click/pop and brief energy gap that otherwise harms
// Whisper re-transcription.
constexpr int kCrossfadeSamples = 192;
for (auto& c : chunks) {
auto part = decode_part(intermediates, c.phon_start, c.phon_end,
c.frame_start, c.num_frames);
if (part.empty()) continue;
if (result.empty()) {
result = std::move(part);
continue;
}
int xf = std::min<int>({kCrossfadeSamples,
(int)result.size(),
(int)part.size()});
if (xf <= 0) {
result.insert(result.end(), part.begin(), part.end());
continue;
}
int tail = (int)result.size() - xf;
for (int i = 0; i < xf; i++) {
float t = (float)(i + 1) / (float)(xf + 1);
// Equal-power (constant energy) crossfade weights.
float w_out = std::cos(t * 1.5707963267948966f);
float w_in = std::sin(t * 1.5707963267948966f);
result[tail + i] = result[tail + i] * w_out + part[i] * w_in;
}
result.insert(result.end(), part.begin() + xf, part.end());
}
return result;
}
int f0_len = static_cast<int>(intermediates.f0_pred.size(1));
auto* sb = coreml_split_decoder_->select_bucket(f0_len);
if (!sb) {
std::fprintf(stderr, "No decoder bucket for f0_len=%d\n", f0_len);
return {};
}
int asr_frames = sb->asr_frames;
int f0_frames = sb->f0_frames;
auto f0_padded = KTensor::zeros({1, (int64_t)f0_frames});
auto n_padded = KTensor::zeros({1, (int64_t)f0_frames});
int f0_actual = std::min(f0_len, f0_frames);
std::memcpy(f0_padded.ptr(), intermediates.f0_pred.ptr(), f0_actual * sizeof(float));
std::memcpy(n_padded.ptr(), intermediates.n_pred.ptr(), f0_actual * sizeof(float));
float* f0_ptr = f0_padded.ptr();
int f0_frames_cap = f0_frames;
auto har_future = std::async(std::launch::async,
[this, f0_ptr, f0_frames_cap]() {
return coreml_split_decoder_->compute_har(f0_ptr, f0_frames_cap);
});
auto asr_padded = KTensor::zeros({1, 512, (int64_t)asr_frames});
int asr_actual = std::min((int)intermediates.asr.size(2), asr_frames);
int64_t src_time = intermediates.asr.size(2);
for (int ch = 0; ch < 512; ch++) {
std::memcpy(asr_padded.ptr() + (int64_t)ch * asr_frames,
intermediates.asr.ptr() + (int64_t)ch * src_time,
asr_actual * sizeof(float));