|
7 | 7 | "path/filepath" |
8 | 8 | "strings" |
9 | 9 | "sync" |
| 10 | + "sync/atomic" |
10 | 11 | "unsafe" |
11 | 12 |
|
12 | 13 | "github.com/go-audio/wav" |
|
29 | 30 | CppGetTokenID func(i int, j int) int |
30 | 31 | CppGetSegmentSpeakerTurnNext func(i int) bool |
31 | 32 | CppSetAbort func(v int) |
| 33 | + // Set by main.go via purego.RegisterLibFunc. Installs (or clears with cb=0) |
| 34 | + // the C-side trampoline that whisper.cpp invokes per new segment. |
| 35 | + CppSetNewSegmentCallback func(cbPtr uintptr, userData uintptr) |
32 | 36 | ) |
33 | 37 |
|
| 38 | +// streamCallStates maps per-AudioTranscriptionStream call IDs to the |
| 39 | +// state the Go callback needs to emit deltas. Only one entry is ever |
| 40 | +// live today (base.SingleThread), but the map shape mirrors |
| 41 | +// sherpa-onnx's TTS callback registry and survives a future SingleThread |
| 42 | +// removal without a contract change. |
| 43 | +var ( |
| 44 | + streamCallStates sync.Map // uint64 -> *streamCallState |
| 45 | + streamCallSeq atomic.Uint64 |
| 46 | + goNewSegmentCb uintptr // purego.NewCallback(onNewSegment) result; set in main.go at boot |
| 47 | +) |
| 48 | + |
| 49 | +type streamCallState struct { |
| 50 | + results chan *pb.TranscriptStreamResponse |
| 51 | + diarize bool |
| 52 | + // nextIdx tracks how many segments we've already emitted. The C |
| 53 | + // trampoline passes idx_first = total - n_new, but we walk from |
| 54 | + // nextIdx to (idx_first + n_new) defensively in case whisper.cpp ever |
| 55 | + // coalesces multiple commits into a single callback invocation. |
| 56 | + nextIdx int |
| 57 | + // assembled mirrors the literal concat of every Delta sent on results. |
| 58 | + // We reuse it as the final TranscriptResult.Text so the e2e |
| 59 | + // invariant `final.Text == concat(deltas)` holds exactly. Written from |
| 60 | + // the cgo decode thread inside onNewSegment and read by the streaming |
| 61 | + // method after CppTranscribe returns; the cgo boundary provides the |
| 62 | + // happens-before edge. |
| 63 | + assembled strings.Builder |
| 64 | +} |
| 65 | + |
| 66 | +// onNewSegment is the Go side of the C trampoline declared in |
| 67 | +// gowhisper.cpp:new_segment_cb. Whisper.cpp invokes it once per |
| 68 | +// new-segment event during whisper_full(). Reads segment text via the |
| 69 | +// existing CppGetSegment* getters (safe to call against the singleton |
| 70 | +// ctx; whisper.cpp is the only writer and it has already published the |
| 71 | +// segments by the time this fires). |
| 72 | +// |
| 73 | +// Sends deltas synchronously: if the channel is full, this blocks the |
| 74 | +// whisper decode thread. That's the intended backpressure path - |
| 75 | +// dropping deltas would break the concat(deltas) == final.Text invariant |
| 76 | +// the e2e suite asserts. |
| 77 | +func onNewSegment(idxFirst int32, nNew int32, userData uintptr) { |
| 78 | + v, ok := streamCallStates.Load(uint64(userData)) |
| 79 | + if !ok { |
| 80 | + return // call already torn down (race with cancel + cb fire) |
| 81 | + } |
| 82 | + state := v.(*streamCallState) |
| 83 | + end := int(idxFirst) + int(nNew) |
| 84 | + for i := state.nextIdx; i < end; i++ { |
| 85 | + txt := strings.ToValidUTF8(strings.Clone(CppGetSegmentText(i)), "�") |
| 86 | + txt = strings.TrimSpace(txt) |
| 87 | + if state.diarize && CppGetSegmentSpeakerTurnNext(i) { |
| 88 | + txt += " [SPEAKER_TURN]" |
| 89 | + } |
| 90 | + if txt == "" { |
| 91 | + state.nextIdx = i + 1 |
| 92 | + continue |
| 93 | + } |
| 94 | + // Prefix subsequent deltas with a single space so the assembled |
| 95 | + // stream reads as one space-joined transcript. The first delta has |
| 96 | + // no leading space, otherwise concat(deltas) would not match |
| 97 | + // final.Text and the e2e invariant would break. |
| 98 | + var delta string |
| 99 | + if state.assembled.Len() == 0 { |
| 100 | + delta = txt |
| 101 | + } else { |
| 102 | + delta = " " + txt |
| 103 | + } |
| 104 | + state.results <- &pb.TranscriptStreamResponse{Delta: delta} |
| 105 | + state.assembled.WriteString(delta) |
| 106 | + state.nextIdx = i + 1 |
| 107 | + } |
| 108 | +} |
| 109 | + |
34 | 110 | type Whisper struct { |
35 | 111 | base.SingleThread |
36 | 112 | } |
@@ -200,3 +276,120 @@ func (w *Whisper) AudioTranscription(ctx context.Context, opts *pb.TranscriptReq |
200 | 276 | Duration: duration, |
201 | 277 | }, nil |
202 | 278 | } |
| 279 | + |
| 280 | +// AudioTranscriptionStream runs whisper_full() and emits deltas via |
| 281 | +// whisper.cpp's new_segment_callback as segments are decoded, then a |
| 282 | +// final TranscriptResult. The offline AudioTranscription is unchanged; |
| 283 | +// both paths share whisper's single-instance ctx and the SingleThread |
| 284 | +// concurrency model. |
| 285 | +func (w *Whisper) AudioTranscriptionStream(ctx context.Context, opts *pb.TranscriptRequest, results chan *pb.TranscriptStreamResponse) error { |
| 286 | + defer close(results) |
| 287 | + |
| 288 | + if err := ctx.Err(); err != nil { |
| 289 | + return status.Error(codes.Canceled, "transcription cancelled") |
| 290 | + } |
| 291 | + |
| 292 | + dir, err := os.MkdirTemp("", "whisper") |
| 293 | + if err != nil { |
| 294 | + return err |
| 295 | + } |
| 296 | + defer func() { _ = os.RemoveAll(dir) }() |
| 297 | + |
| 298 | + convertedPath := filepath.Join(dir, "converted.wav") |
| 299 | + if err := utils.AudioToWav(opts.Dst, convertedPath); err != nil { |
| 300 | + return err |
| 301 | + } |
| 302 | + |
| 303 | + fh, err := os.Open(convertedPath) |
| 304 | + if err != nil { |
| 305 | + return err |
| 306 | + } |
| 307 | + defer func() { _ = fh.Close() }() |
| 308 | + |
| 309 | + d := wav.NewDecoder(fh) |
| 310 | + buf, err := d.FullPCMBuffer() |
| 311 | + if err != nil { |
| 312 | + return err |
| 313 | + } |
| 314 | + data := buf.AsFloat32Buffer().Data |
| 315 | + var duration float32 |
| 316 | + if buf.Format != nil && buf.Format.SampleRate > 0 { |
| 317 | + duration = float32(len(data)) / float32(buf.Format.SampleRate) |
| 318 | + } |
| 319 | + |
| 320 | + // Register per-call state and install the C-side callback. defer |
| 321 | + // teardown so even a panic clears the C pointer (otherwise a stale |
| 322 | + // callback fires on the next AudioTranscription call). |
| 323 | + callID := streamCallSeq.Add(1) |
| 324 | + state := &streamCallState{ |
| 325 | + results: results, |
| 326 | + diarize: opts.Diarize, |
| 327 | + } |
| 328 | + streamCallStates.Store(callID, state) |
| 329 | + CppSetNewSegmentCallback(goNewSegmentCb, uintptr(callID)) |
| 330 | + defer func() { |
| 331 | + CppSetNewSegmentCallback(0, 0) |
| 332 | + streamCallStates.Delete(callID) |
| 333 | + }() |
| 334 | + |
| 335 | + // Same abort-watcher pattern as AudioTranscription. Joined synchronously |
| 336 | + // so a late CppSetAbort(1) cannot fire after this function returns. |
| 337 | + done := make(chan struct{}) |
| 338 | + var wg sync.WaitGroup |
| 339 | + wg.Add(1) |
| 340 | + go func() { |
| 341 | + defer wg.Done() |
| 342 | + select { |
| 343 | + case <-ctx.Done(): |
| 344 | + CppSetAbort(1) |
| 345 | + case <-done: |
| 346 | + } |
| 347 | + }() |
| 348 | + defer func() { |
| 349 | + close(done) |
| 350 | + wg.Wait() |
| 351 | + }() |
| 352 | + |
| 353 | + segsLen := uintptr(0xdeadbeef) |
| 354 | + segsLenPtr := unsafe.Pointer(&segsLen) |
| 355 | + ret := CppTranscribe(opts.Threads, opts.Language, opts.Translate, opts.Diarize, data, uintptr(len(data)), segsLenPtr, opts.Prompt) |
| 356 | + if ret == 2 { |
| 357 | + return status.Error(codes.Canceled, "transcription cancelled") |
| 358 | + } |
| 359 | + if ret != 0 { |
| 360 | + return fmt.Errorf("Failed Transcribe") |
| 361 | + } |
| 362 | + |
| 363 | + // Build the final TranscriptResult. Segments[] mirrors the offline |
| 364 | + // path so the SSE done event carries the same per-segment shape. |
| 365 | + // final.Text reuses the assembled stream so concat(deltas) == final.Text |
| 366 | + // holds exactly, matching the e2e contract. |
| 367 | + segments := []*pb.TranscriptSegment{} |
| 368 | + for i := range int(segsLen) { |
| 369 | + s := CppGetSegmentStart(i) * 10000000 |
| 370 | + t := CppGetSegmentEnd(i) * 10000000 |
| 371 | + txt := strings.ToValidUTF8(strings.Clone(CppGetSegmentText(i)), "�") |
| 372 | + tokens := make([]int32, CppNTokens(i)) |
| 373 | + if opts.Diarize && CppGetSegmentSpeakerTurnNext(i) { |
| 374 | + txt += " [SPEAKER_TURN]" |
| 375 | + } |
| 376 | + for j := range tokens { |
| 377 | + tokens[j] = int32(CppGetTokenID(i, j)) |
| 378 | + } |
| 379 | + segments = append(segments, &pb.TranscriptSegment{ |
| 380 | + Id: int32(i), |
| 381 | + Text: txt, |
| 382 | + Start: s, End: t, |
| 383 | + Tokens: tokens, |
| 384 | + }) |
| 385 | + } |
| 386 | + |
| 387 | + final := &pb.TranscriptResult{ |
| 388 | + Segments: segments, |
| 389 | + Text: state.assembled.String(), |
| 390 | + Language: opts.Language, |
| 391 | + Duration: duration, |
| 392 | + } |
| 393 | + results <- &pb.TranscriptStreamResponse{FinalResult: final} |
| 394 | + return nil |
| 395 | +} |
0 commit comments