-
Notifications
You must be signed in to change notification settings - Fork 211
Expand file tree
/
Copy pathai_mediaserver.go
More file actions
1438 lines (1256 loc) · 46.1 KB
/
ai_mediaserver.go
File metadata and controls
1438 lines (1256 loc) · 46.1 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
package server
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"strings"
"time"
"github.com/livepeer/go-livepeer/monitor"
"github.com/cenkalti/backoff"
"github.com/getkin/kin-openapi/openapi3filter"
"github.com/livepeer/go-livepeer/ai/worker"
"github.com/livepeer/go-livepeer/clog"
"github.com/livepeer/go-livepeer/common"
"github.com/livepeer/go-livepeer/core"
"github.com/livepeer/go-livepeer/media"
"github.com/livepeer/go-tools/drivers"
middleware "github.com/oapi-codegen/nethttp-middleware"
"github.com/oapi-codegen/runtime"
)
type ImageToVideoResponseAsync struct {
RequestID string `json:"request_id"`
}
type ImageToVideoResultRequest struct {
RequestID string `json:"request_id"`
}
type ImageToVideoResultResponse struct {
Result *ImageToVideoResult `json:"result,omitempty"`
Status ImageToVideoStatus `json:"status"`
}
type ImageToVideoResult struct {
*worker.ImageResponse
Error *APIError `json:"error,omitempty"`
}
type ImageToVideoStatus string
const (
Processing ImageToVideoStatus = "processing"
Complete ImageToVideoStatus = "complete"
)
// @title Live Video-To-Video AI
// @version 0.0.0
func startAIMediaServer(ctx context.Context, ls *LivepeerServer) error {
swagger, err := worker.GetSwagger()
if err != nil {
return err
}
swagger.Servers = nil
opts := &middleware.Options{
Options: openapi3filter.Options{
ExcludeRequestBody: true,
AuthenticationFunc: openapi3filter.NoopAuthenticationFunc,
},
ErrorHandler: func(w http.ResponseWriter, message string, statusCode int) {
clog.Errorf(context.Background(), "oapi validation error statusCode=%v message=%v", statusCode, message)
},
}
oapiReqValidator := middleware.OapiRequestValidatorWithOptions(swagger, opts)
openapi3filter.RegisterBodyDecoder("image/png", openapi3filter.FileBodyDecoder)
ls.HTTPMux.Handle("/text-to-image", oapiReqValidator(aiMediaServerHandle(ls, jsonDecoder[worker.GenTextToImageJSONRequestBody], processTextToImage)))
ls.HTTPMux.Handle("/image-to-image", oapiReqValidator(aiMediaServerHandle(ls, multipartDecoder[worker.GenImageToImageMultipartRequestBody], processImageToImage)))
ls.HTTPMux.Handle("/upscale", oapiReqValidator(aiMediaServerHandle(ls, multipartDecoder[worker.GenUpscaleMultipartRequestBody], processUpscale)))
ls.HTTPMux.Handle("/image-to-video", oapiReqValidator(ls.ImageToVideo()))
ls.HTTPMux.Handle("/image-to-video/result", ls.ImageToVideoResult())
ls.HTTPMux.Handle("/audio-to-text", oapiReqValidator(aiMediaServerHandle(ls, multipartDecoder[worker.GenAudioToTextMultipartRequestBody], processAudioToText)))
ls.HTTPMux.Handle("/llm", oapiReqValidator(ls.LLM()))
ls.HTTPMux.Handle("/segment-anything-2", oapiReqValidator(aiMediaServerHandle(ls, multipartDecoder[worker.GenSegmentAnything2MultipartRequestBody], processSegmentAnything2)))
ls.HTTPMux.Handle("/image-to-text", oapiReqValidator(aiMediaServerHandle(ls, multipartDecoder[worker.GenImageToTextMultipartRequestBody], processImageToText)))
ls.HTTPMux.Handle("/text-to-speech", oapiReqValidator(aiMediaServerHandle(ls, jsonDecoder[worker.GenTextToSpeechJSONRequestBody], processTextToSpeech)))
// This is called by the media server when the stream is ready
ls.HTTPMux.Handle("POST /live/video-to-video/{stream}/start", ls.StartLiveVideo())
ls.HTTPMux.Handle("POST /live/video-to-video/{prefix}/{stream}/start", ls.StartLiveVideo())
ls.HTTPMux.Handle("POST /live/video-to-video/{stream}/update", ls.UpdateLiveVideo())
ls.HTTPMux.Handle("OPTIONS /live/video-to-video/{stream}/update", ls.WithCode(http.StatusNoContent))
ls.HTTPMux.Handle("/live/video-to-video/smoketest", ls.SmokeTestLiveVideo())
// Configure WHIP ingest only if an addr is specified.
// TODO use a proper cli flag
if os.Getenv("LIVE_AI_WHIP_ADDR") != "" {
whipServer := media.NewWHIPServer()
ls.HTTPMux.Handle("POST /live/video-to-video/{stream}/whip", ls.CreateWhip(whipServer))
ls.HTTPMux.Handle("HEAD /live/video-to-video/{stream}/whip", ls.WithCode(http.StatusMethodNotAllowed))
ls.HTTPMux.Handle("OPTIONS /live/video-to-video/{stream}/whip", ls.WithCode(http.StatusNoContent))
}
if os.Getenv("LIVE_AI_WHEP_ADDR") != "" {
whepServer := media.NewWHEPServer()
// path is {stream}-{request}-out but golang router won't match that
ls.HTTPMux.Handle("POST /live/video-to-video/{path}/whep", ls.CreateWhep(whepServer))
ls.HTTPMux.Handle("HEAD /live/video-to-video/{path}/whep", ls.WithCode(http.StatusMethodNotAllowed))
ls.HTTPMux.Handle("OPTIONS /live/video-to-video/{path}/whep", ls.WithCode(http.StatusNoContent))
ls.HTTPMux.Handle("PATCH /live/video-to-video/{path}/whep", ls.WithCode(http.StatusNotImplemented))
}
// Stream status
ls.HTTPMux.Handle("OPTIONS /live/video-to-video/{streamId}/status", ls.WithCode(http.StatusNoContent))
ls.HTTPMux.Handle("/live/video-to-video/{streamId}/status", ls.GetLiveVideoToVideoStatus())
//API for dynamic capabilities
ls.HTTPMux.Handle("/process/request/", ls.SubmitJob())
media.StartFileCleanup(ctx, ls.LivepeerNode.WorkDir)
startHearbeats(ctx, ls.LivepeerNode)
return nil
}
func generateGatewayLiveURL(hostname, stream, pathSuffix string) string {
return fmt.Sprintf("https://%s/live/video-to-video/%s/%s", hostname, stream, pathSuffix)
}
func generateWhepUrl(streamName, requestID string) string {
whepURL := os.Getenv("LIVE_AI_WHEP_URL")
if whepURL == "" {
whepURL = "http://localhost:8889/" // default mediamtx output
}
whepURL = fmt.Sprintf("%s%s-%s-out/whep", whepURL, streamName, requestID)
return whepURL
}
func aiMediaServerHandle[I, O any](ls *LivepeerServer, decoderFunc func(*I, *http.Request) error, processorFunc func(context.Context, aiRequestParams, I) (O, error)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
remoteAddr := getRemoteAddr(r)
ctx := clog.AddVal(r.Context(), clog.ClientIP, remoteAddr)
requestID := string(core.RandomManifestID())
ctx = clog.AddVal(ctx, "request_id", requestID)
params := aiRequestParams{
node: ls.LivepeerNode,
os: drivers.NodeStorage.NewSession(requestID),
sessManager: ls.AISessionManager,
}
var req I
if err := decoderFunc(&req, r); err != nil {
respondJsonError(ctx, w, err, http.StatusBadRequest)
return
}
resp, err := processorFunc(ctx, params, req)
if err != nil {
var serviceUnavailableErr *ServiceUnavailableError
var badRequestErr *BadRequestError
if errors.As(err, &serviceUnavailableErr) {
respondJsonError(ctx, w, err, http.StatusServiceUnavailable)
return
}
if errors.As(err, &badRequestErr) {
respondJsonError(ctx, w, err, http.StatusBadRequest)
return
}
respondJsonError(ctx, w, err, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(resp)
})
}
func (ls *LivepeerServer) ImageToVideo() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
remoteAddr := getRemoteAddr(r)
ctx := clog.AddVal(r.Context(), clog.ClientIP, remoteAddr)
requestID := string(core.RandomManifestID())
ctx = clog.AddVal(ctx, "request_id", requestID)
multiRdr, err := r.MultipartReader()
if err != nil {
respondJsonError(ctx, w, err, http.StatusBadRequest)
return
}
var req worker.GenImageToVideoMultipartRequestBody
if err := runtime.BindMultipart(&req, *multiRdr); err != nil {
respondJsonError(ctx, w, err, http.StatusBadRequest)
return
}
var async bool
prefer := r.Header.Get("Prefer")
if prefer == "respond-async" {
async = true
}
clog.V(common.VERBOSE).Infof(ctx, "Received ImageToVideo request imageSize=%v model_id=%v async=%v", req.Image.FileSize(), *req.ModelId, async)
params := aiRequestParams{
node: ls.LivepeerNode,
os: drivers.NodeStorage.NewSession(requestID),
sessManager: ls.AISessionManager,
}
if !async {
start := time.Now()
resp, err := processImageToVideo(ctx, params, req)
if err != nil {
var serviceUnavailableErr *ServiceUnavailableError
var badRequestErr *BadRequestError
if errors.As(err, &serviceUnavailableErr) {
respondJsonError(ctx, w, err, http.StatusServiceUnavailable)
return
}
if errors.As(err, &badRequestErr) {
respondJsonError(ctx, w, err, http.StatusBadRequest)
return
}
respondJsonError(ctx, w, err, http.StatusInternalServerError)
return
}
took := time.Since(start)
clog.Infof(ctx, "Processed ImageToVideo request imageSize=%v model_id=%v took=%v", req.Image.FileSize(), *req.ModelId, took)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(resp)
return
}
var data bytes.Buffer
if err := json.NewEncoder(&data).Encode(req); err != nil {
respondJsonError(ctx, w, err, http.StatusInternalServerError)
return
}
path, err := params.os.SaveData(ctx, "request.json", bytes.NewReader(data.Bytes()), nil, 0)
if err != nil {
respondJsonError(ctx, w, err, http.StatusInternalServerError)
return
}
clog.Infof(ctx, "Saved ImageToVideo request path=%v", requestID, path)
cctx := clog.Clone(context.Background(), ctx)
go func(ctx context.Context) {
start := time.Now()
var data bytes.Buffer
resp, err := processImageToVideo(ctx, params, req)
if err != nil {
clog.Errorf(ctx, "Error processing ImageToVideo request err=%v", err)
handleAPIError(ctx, &data, err, http.StatusInternalServerError)
} else {
took := time.Since(start)
clog.Infof(ctx, "Processed ImageToVideo request imageSize=%v model_id=%v took=%v", req.Image.FileSize(), *req.ModelId, took)
if err := json.NewEncoder(&data).Encode(resp); err != nil {
clog.Errorf(ctx, "Error JSON encoding ImageToVideo response err=%v", err)
return
}
}
path, err := params.os.SaveData(ctx, "result.json", bytes.NewReader(data.Bytes()), nil, 0)
if err != nil {
clog.Errorf(ctx, "Error saving ImageToVideo result to object store err=%v", err)
return
}
clog.Infof(ctx, "Saved ImageToVideo result path=%v", path)
}(cctx)
resp := &ImageToVideoResponseAsync{
RequestID: requestID,
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusAccepted)
_ = json.NewEncoder(w).Encode(resp)
})
}
func (ls *LivepeerServer) LLM() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
remoteAddr := getRemoteAddr(r)
ctx := clog.AddVal(r.Context(), clog.ClientIP, remoteAddr)
requestID := string(core.RandomManifestID())
ctx = clog.AddVal(ctx, "request_id", requestID)
var req worker.GenLLMJSONRequestBody
if err := jsonDecoder(&req, r); err != nil {
respondJsonError(ctx, w, err, http.StatusBadRequest)
return
}
//check required fields
if req.Model == nil || req.Messages == nil || req.Stream == nil || req.MaxTokens == nil || len(req.Messages) == 0 {
respondJsonError(ctx, w, errors.New("missing required fields"), http.StatusBadRequest)
return
}
clog.V(common.VERBOSE).Infof(ctx, "Received LLM request model_id=%v stream=%v", *req.Model, *req.Stream)
params := aiRequestParams{
node: ls.LivepeerNode,
os: drivers.NodeStorage.NewSession(requestID),
sessManager: ls.AISessionManager,
}
start := time.Now()
resp, err := processLLM(ctx, params, req)
if err != nil {
var e *ServiceUnavailableError
if errors.As(err, &e) {
respondJsonError(ctx, w, err, http.StatusServiceUnavailable)
return
}
respondJsonError(ctx, w, err, http.StatusInternalServerError)
return
}
took := time.Since(start)
clog.V(common.VERBOSE).Infof(ctx, "Processed LLM request model_id=%v took=%v", *req.Model, took)
if streamChan, ok := resp.(chan *worker.LLMResponse); ok {
// Handle streaming response (SSE)
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
for chunk := range streamChan {
data, _ := json.Marshal(chunk)
fmt.Fprintf(w, "data: %s\n\n", data)
w.(http.Flusher).Flush()
if chunk.Choices[0].FinishReason != nil && *chunk.Choices[0].FinishReason != "" {
break
}
}
} else if llmResp, ok := resp.(*worker.LLMResponse); ok {
// Handle non-streaming response
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(llmResp)
} else {
http.Error(w, "Unexpected response type", http.StatusInternalServerError)
}
})
}
func (ls *LivepeerServer) ImageToVideoResult() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
remoteAddr := getRemoteAddr(r)
ctx := clog.AddVal(r.Context(), clog.ClientIP, remoteAddr)
var req ImageToVideoResultRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondJsonError(ctx, w, err, http.StatusBadRequest)
return
}
ctx = clog.AddVal(ctx, "request_id", req.RequestID)
clog.V(common.VERBOSE).Infof(ctx, "Received ImageToVideoResult request request_id=%v", req.RequestID)
sess := drivers.NodeStorage.NewSession(req.RequestID)
_, err := sess.ReadData(ctx, "request.json")
if err != nil {
respondJsonError(ctx, w, errors.New("invalid request ID"), http.StatusBadRequest)
return
}
resp := ImageToVideoResultResponse{
Status: Processing,
}
reader, err := sess.ReadData(ctx, "result.json")
if err != nil {
// TODO: Distinguish between error reading data vs. file DNE
// Right now we assume that this file will exist when processing is done even
// if an error was encountered
w.WriteHeader(http.StatusAccepted)
_ = json.NewEncoder(w).Encode(resp)
return
}
resp.Status = Complete
if err := json.NewDecoder(reader.Body).Decode(&resp.Result); err != nil {
respondJsonError(ctx, w, err, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(resp)
})
}
// @Summary Start Live Video
// @Accept multipart/form-data
// @Param stream path string true "Stream Key"
// @Param source_id formData string true "MediaMTX source ID, used for calls back to MediaMTX"
// @Param source_type formData string true "MediaMTX specific source type (webrtcSession/rtmpConn)"
// @Param query formData string true "Queryparams from the original ingest URL"
// @Success 200
// @Router /live/video-to-video/{stream}/start [get]
func (ls *LivepeerServer) StartLiveVideo() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Create fresh context instead of using r.Context() since ctx will outlive the request
ctx := context.Background()
requestID := string(core.RandomManifestID())
ctx = clog.AddVal(ctx, "request_id", requestID)
streamName := r.PathValue("stream")
if streamName == "" {
clog.Errorf(ctx, "Missing stream name")
http.Error(w, "Missing stream name", http.StatusBadRequest)
return
}
streamRequestTime := time.Now().UnixMilli()
ctx = clog.AddVal(ctx, "stream", streamName)
sourceID := r.FormValue("source_id")
if sourceID == "" {
clog.Errorf(ctx, "Missing source_id")
http.Error(w, "Missing source_id", http.StatusBadRequest)
return
}
ctx = clog.AddVal(ctx, "source_id", sourceID)
sourceType := r.FormValue("source_type")
if sourceType == "" {
clog.Errorf(ctx, "Missing source_type")
http.Error(w, "Missing source_type", http.StatusBadRequest)
return
}
sourceType = strings.ToLower(sourceType) // mediamtx changed casing between versions
sourceTypeStr, err := media.MediamtxSourceTypeToString(sourceType)
if err != nil {
clog.Errorf(ctx, "Invalid source type %s", sourceType)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
ctx = clog.AddVal(ctx, "source_type", sourceType)
remoteHost, err := getRemoteHost(r.RemoteAddr)
if err != nil {
clog.Errorf(ctx, "Could not find callback host: %s", err.Error())
http.Error(w, "Could not find callback host", http.StatusBadRequest)
return
}
ctx = clog.AddVal(ctx, "remote_addr", remoteHost)
queryParams := r.FormValue("query")
qp, err := url.ParseQuery(queryParams)
if err != nil {
clog.Errorf(ctx, "invalid query params, err=%w", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// If auth webhook is set and returns an output URL, this will be replaced
outputURL := qp.Get("rtmpOutput")
// Currently for webrtc we need to add a path prefix due to the ingress setup
mediaMTXStreamPrefix := r.PathValue("prefix")
if mediaMTXStreamPrefix != "" {
mediaMTXStreamPrefix = mediaMTXStreamPrefix + "/"
}
mediaMTXInputURL := fmt.Sprintf("rtmp://%s/%s%s", remoteHost, mediaMTXStreamPrefix, streamName)
mediaMTXRtmpURL := r.FormValue("rtmp_url")
if mediaMTXRtmpURL != "" {
mediaMTXInputURL = mediaMTXRtmpURL
}
mediaMTXOutputURL := mediaMTXInputURL + "-out"
mediaMTXOutputAlias := fmt.Sprintf("%s-%s-out", mediaMTXInputURL, requestID)
// convention to avoid re-subscribing to our own streams
// in case we want to push outputs back into mediamtx -
// use an `-out` suffix for the stream name.
if strings.HasSuffix(streamName, "-out") {
// skip for now; we don't want to re-publish our own outputs
return
}
// if auth webhook returns pipeline config these will be replaced
pipeline := qp.Get("pipeline")
rawParams := qp.Get("params")
streamID := qp.Get("streamId")
orchestrator := qp.Get("orchestrator")
var pipelineID string
var pipelineParams map[string]interface{}
if rawParams != "" {
if err := json.Unmarshal([]byte(rawParams), &pipelineParams); err != nil {
clog.Errorf(ctx, "Invalid pipeline params: %s", err)
http.Error(w, "Invalid model params", http.StatusBadRequest)
return
}
}
mediaMTXClient := media.NewMediaMTXClient(remoteHost, ls.mediaMTXApiPassword, sourceID, sourceType)
whepURL := generateWhepUrl(streamName, requestID)
if LiveAIAuthWebhookURL != nil {
authResp, err := authenticateAIStream(LiveAIAuthWebhookURL, ls.liveAIAuthApiKey, AIAuthRequest{
Stream: streamName,
Type: sourceTypeStr,
QueryParams: queryParams,
GatewayHost: ls.LivepeerNode.GatewayHost,
WhepURL: whepURL,
UpdateURL: generateGatewayLiveURL(ls.LivepeerNode.GatewayHost, streamName, "/update"),
StatusURL: generateGatewayLiveURL(ls.LivepeerNode.GatewayHost, streamID, "/status"),
})
if err != nil {
kickErr := mediaMTXClient.KickInputConnection(ctx)
if kickErr != nil {
clog.Errorf(ctx, "failed to kick input connection: %s", kickErr.Error())
}
clog.Errorf(ctx, "Live AI auth failed: %s", err.Error())
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
if authResp.RTMPOutputURL != "" {
outputURL = authResp.RTMPOutputURL
}
if authResp.Pipeline != "" {
pipeline = authResp.Pipeline
}
if len(authResp.paramsMap) > 0 {
if _, ok := authResp.paramsMap["prompt"]; !ok && pipeline == "comfyui" {
pipelineParams = map[string]interface{}{"prompt": authResp.paramsMap}
} else {
pipelineParams = authResp.paramsMap
}
}
if authResp.StreamID != "" {
streamID = authResp.StreamID
}
if authResp.PipelineID != "" {
pipelineID = authResp.PipelineID
}
}
ctx = clog.AddVal(ctx, "stream_id", streamID)
clog.Infof(ctx, "Received live video AI request for %s. pipelineParams=%v", streamName, pipelineParams)
// collect all RTMP outputs
var rtmpOutputs []string
if outputURL != "" {
rtmpOutputs = append(rtmpOutputs, outputURL)
}
if mediaMTXOutputURL != "" {
rtmpOutputs = append(rtmpOutputs, mediaMTXOutputURL, mediaMTXOutputAlias)
}
clog.Info(ctx, "RTMP outputs", "destinations", rtmpOutputs)
// channel that blocks until after orch selection is complete
// avoids a race condition with closing the control channel
orchSelection := make(chan bool)
// Clear any previous gateway status
GatewayStatus.Clear(streamID)
GatewayStatus.StoreKey(streamID, "whep_url", whepURL)
monitor.SendQueueEventAsync("stream_trace", map[string]interface{}{
"type": "gateway_receive_stream_request",
"timestamp": streamRequestTime,
"stream_id": streamID,
"pipeline_id": pipelineID,
"request_id": requestID,
"orchestrator_info": map[string]interface{}{
"address": "",
"url": "",
},
})
// Count `ai_live_attempts` after successful parameters validation
clog.V(common.VERBOSE).Infof(ctx, "AI Live video attempt")
monitor.AILiveVideoAttempt(pipeline) // this `pipeline` is actually modelID
sendErrorEvent := LiveErrorEventSender(ctx, streamID, map[string]string{
"type": "error",
"request_id": requestID,
"stream_id": streamID,
"pipeline_id": pipelineID,
"pipeline": pipeline,
})
// this function is called when the pipeline hits a fatal error, we kick the input connection to allow
// the client to reconnect and restart the pipeline
segmenterCtx, cancelSegmenter := context.WithCancel(clog.Clone(context.Background(), ctx))
kickInput := func(err error) {
defer cancelSegmenter()
if err == nil {
return
}
clog.Errorf(ctx, "Live video pipeline finished with error: %s", err)
sendErrorEvent(err)
err = mediaMTXClient.KickInputConnection(ctx)
if err != nil {
clog.Errorf(ctx, "Failed to kick input connection: %s", err)
}
}
ssr := media.NewSwitchableSegmentReader()
params := aiRequestParams{
node: ls.LivepeerNode,
os: drivers.NodeStorage.NewSession(requestID),
sessManager: ls.AISessionManager,
liveParams: &liveRequestParams{
segmentReader: ssr,
rtmpOutputs: rtmpOutputs,
localRTMPPrefix: mediaMTXInputURL,
stream: streamName,
paymentProcessInterval: ls.livePaymentInterval,
outSegmentTimeout: ls.outSegmentTimeout,
requestID: requestID,
streamID: streamID,
pipelineID: pipelineID,
pipeline: pipeline,
kickInput: kickInput,
sendErrorEvent: sendErrorEvent,
orchestrator: orchestrator,
},
}
registerControl(ctx, params)
// Create a special parent context for orchestrator cancellation
orchCtx, orchCancel := context.WithCancel(ctx)
// Kick off the RTMP pull and segmentation as soon as possible
go func() {
ms := media.MediaSegmenter{Workdir: ls.LivepeerNode.WorkDir, MediaMTXClient: mediaMTXClient}
ms.RunSegmentation(segmenterCtx, mediaMTXInputURL, ssr.Read)
sendErrorEvent(errors.New("mediamtx ingest disconnected"))
monitor.SendQueueEventAsync("stream_trace", map[string]interface{}{
"type": "gateway_ingest_stream_closed",
"timestamp": time.Now().UnixMilli(),
"stream_id": streamID,
"pipeline_id": pipelineID,
"request_id": requestID,
"orchestrator_info": map[string]interface{}{
"address": "",
"url": "",
},
})
ssr.Close()
<-orchSelection // wait for selection to complete
cleanupControl(ctx, params)
orchCancel()
}()
req := worker.GenLiveVideoToVideoJSONRequestBody{
ModelId: &pipeline,
Params: &pipelineParams,
GatewayRequestId: &requestID,
StreamId: &streamID,
}
processStream(orchCtx, params, req)
close(orchSelection)
})
}
func processStream(ctx context.Context, params aiRequestParams, req worker.GenLiveVideoToVideoJSONRequestBody) {
orchSwapper := NewOrchestratorSwapper(params)
isFirst, firstProcessed := true, make(chan interface{})
go func() {
var err error
for {
perOrchCtx, perOrchCancel := context.WithCancelCause(ctx)
params.liveParams = newLiveParams(params, perOrchCancel)
var resp interface{}
resp, err = processAIRequest(perOrchCtx, params, req)
if err != nil {
clog.Errorf(ctx, "Error processing AI Request: %s", err)
perOrchCancel(err)
break
}
if err = startProcessing(perOrchCtx, params, resp); err != nil {
clog.Errorf(ctx, "Error starting processing: %s", err)
perOrchCancel(err)
break
}
if isFirst {
isFirst = false
firstProcessed <- struct{}{}
}
<-perOrchCtx.Done()
err = context.Cause(perOrchCtx)
if errors.Is(err, context.Canceled) {
// this happens if parent ctx was cancelled without a CancelCause
// or if passing `nil` as a CancelCause
err = nil
}
if !params.inputStreamExists() {
clog.Info(ctx, "No input stream, skipping orchestrator swap")
break
}
if swapErr := orchSwapper.checkSwap(ctx); swapErr != nil {
if err != nil {
err = fmt.Errorf("%w: %w", swapErr, err)
} else {
err = swapErr
}
break
}
clog.Infof(ctx, "Retrying stream with a different orchestrator")
// will swap, but first notify with the reason for the swap
if err == nil {
err = errors.New("unknown swap reason")
}
// report the swap
monitor.SendQueueEventAsync("stream_trace", map[string]interface{}{
"type": "orchestrator_swap",
"stream_id": params.liveParams.streamID,
"request_id": params.liveParams.requestID,
"pipeline": params.liveParams.pipeline,
"pipeline_id": params.liveParams.pipelineID,
"message": err.Error(),
"orchestrator_info": map[string]interface{}{
"address": params.liveParams.sess.Address(),
"url": params.liveParams.sess.Transcoder(),
},
})
}
if isFirst {
// failed before selecting an orchestrator
firstProcessed <- struct{}{}
}
params.liveParams.kickInput(err)
}()
<-firstProcessed
}
func newLiveParams(aiParams aiRequestParams, cancelOrch context.CancelCauseFunc) *liveRequestParams {
params := aiParams.liveParams
return &liveRequestParams{
segmentReader: params.segmentReader,
rtmpOutputs: params.rtmpOutputs,
localRTMPPrefix: params.localRTMPPrefix,
stream: params.stream,
paymentProcessInterval: params.paymentProcessInterval,
outSegmentTimeout: params.outSegmentTimeout,
requestID: params.requestID,
streamID: params.streamID,
pipelineID: params.pipelineID,
pipeline: params.pipeline,
sendErrorEvent: params.sendErrorEvent,
kickInput: params.kickInput,
orchestrator: params.orchestrator,
startTime: time.Now(),
kickOrch: cancelOrch,
paymentSender: choosePaymentSender(aiParams),
}
}
func choosePaymentSender(params aiRequestParams) LivePaymentSender {
if hasRemoteSigner(params) {
return NewRemotePaymentSender(params.node)
}
return &livePaymentSender{}
}
func startProcessing(ctx context.Context, params aiRequestParams, res interface{}) error {
resp := res.(*worker.GenLiveVideoToVideoResponse)
host := params.liveParams.sess.Transcoder()
pub, err := common.AppendHostname(resp.JSON200.PublishUrl, host)
if err != nil {
return fmt.Errorf("invalid publish URL: %w", err)
}
sub, err := common.AppendHostname(resp.JSON200.SubscribeUrl, host)
if err != nil {
return fmt.Errorf("invalid subscribe URL: %w", err)
}
control, err := common.AppendHostname(*resp.JSON200.ControlUrl, host)
if err != nil {
return fmt.Errorf("invalid control URL: %w", err)
}
events, err := common.AppendHostname(*resp.JSON200.EventsUrl, host)
if err != nil {
return fmt.Errorf("invalid events URL: %w", err)
}
if resp.JSON200.ManifestId != nil {
ctx = clog.AddVal(ctx, "manifest_id", *resp.JSON200.ManifestId)
params.liveParams.manifestID = *resp.JSON200.ManifestId
}
clog.V(common.VERBOSE).Infof(ctx, "pub %s sub %s control %s events %s", pub, sub, control, events)
startControlPublish(ctx, control, params)
startTricklePublish(ctx, pub, params, params.liveParams.sess)
startTrickleSubscribe(ctx, sub, params, params.liveParams.sess)
startEventsSubscribe(ctx, events, params, params.liveParams.sess)
return nil
}
func getRemoteHost(remoteAddr string) (string, error) {
if remoteAddr == "" {
return "", errors.New("remoteAddr is empty")
}
// Handle IPv6 addresses by splitting on last colon
host, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
return "", fmt.Errorf("couldn't parse remote host: %w", err)
}
// Clean up IPv6 brackets if present
host = strings.Trim(host, "[]")
if host == "::1" {
return "127.0.0.1", nil
}
return host, nil
}
// @Summary Update Live Stream
// @Param stream path string true "Stream Key"
// @Param params body string true "update request"
// @Success 200
// @Router /live/video-to-video/{stream}/update [post]
func (ls *LivepeerServer) UpdateLiveVideo() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Get stream from path param
stream := r.PathValue("stream")
if stream == "" {
http.Error(w, "Missing stream name", http.StatusBadRequest)
return
}
ls.LivepeerNode.LiveMu.RLock()
// NB: LiveMu is a global lock, avoid holding it
// during blocking network actions ... can't defer
p, ok := ls.LivepeerNode.LivePipelines[stream]
ls.LivepeerNode.LiveMu.RUnlock()
if !ok {
// Stream not found
http.Error(w, "Stream not found", http.StatusNotFound)
return
}
reader := http.MaxBytesReader(w, r.Body, 1*1024*104) // 1 MB
defer reader.Close()
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
params := string(data)
ls.LivepeerNode.LiveMu.Lock()
p.Params = data
reportUpdate := p.ReportUpdate
controlPub := p.ControlPub
ls.LivepeerNode.LiveMu.Unlock()
if controlPub == nil {
clog.Info(ctx, "No orchestrator available, caching params", "stream", stream, "params", params)
return
}
clog.V(6).Infof(ctx, "Sending Live Video Update Control API stream=%s, params=%s", stream, params)
if err := controlPub.Write(bytes.NewReader(data)); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
reportUpdate(data)
corsHeaders(w, r.Method)
})
}
// @Summary Get Live Stream Status
// @Param stream path string true "Stream ID"
// @Success 200
// @Router /live/video-to-video/{stream}/status [get]
func (ls *LivepeerServer) GetLiveVideoToVideoStatus() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
corsHeaders(w, r.Method)
streamId := r.PathValue("streamId")
if streamId == "" {
http.Error(w, "stream id is required", http.StatusBadRequest)
return
}
ctx := r.Context()
ctx = clog.AddVal(ctx, "stream", streamId)
// Get status for specific stream
status, exists := StreamStatusStore.Get(streamId)
gatewayStatus, gatewayExists := GatewayStatus.Get(streamId)
if !exists && !gatewayExists {
http.Error(w, "Stream not found", http.StatusNotFound)
return
}
if gatewayExists {
if status == nil {
status = make(map[string]any)
} else {
// Clone so we can safely update the object (shallow)
status = maps.Clone(status)
}
status["gateway_status"] = gatewayStatus
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(status); err != nil {
clog.Errorf(ctx, "Failed to encode stream status err=%v", err)
http.Error(w, "Failed to encode status", http.StatusInternalServerError)
return
}
})
}
func (ls *LivepeerServer) CreateWhip(server *media.WHIPServer) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// two main sequential parts here
//
// WHIP : stream setup, await tracks
// Others: auth, selection, job setup
// Run them in parallel
streamRequestTime := time.Now().UnixMilli()
corsHeaders(w, r.Method)
// NB: deliberately not using r.Context since ctx will outlive the request
ctx := context.Background()
requestID := string(core.RandomManifestID())
ctx = clog.AddVal(ctx, "request_id", requestID)
streamName := r.PathValue("stream")
if streamName == "" {
http.Error(w, "Missing stream name", http.StatusBadRequest)
return
}
ctx = clog.AddVal(ctx, "stream", streamName)
ssr := media.NewSwitchableSegmentReader()
whipConn := media.NewWHIPConnection()
whepURL := generateWhepUrl(streamName, requestID)
go func() {
internalOutputHost := os.Getenv("LIVE_AI_PLAYBACK_HOST") // TODO proper cli arg
if internalOutputHost == "" {
internalOutputHost = "rtmp://localhost/"
}
mediamtxOutputURL := internalOutputHost + streamName + "-out"
mediaMTXOutputAlias := fmt.Sprintf("%s%s-%s-out", internalOutputHost, streamName, requestID)
outputURL := r.URL.Query().Get("rtmpOutput")
streamID := r.URL.Query().Get("streamId")
pipelineID := ""
pipeline := r.URL.Query().Get("pipeline")
pipelineParams := make(map[string]interface{})
sourceTypeStr := "livepeer-whip"
queryParams := r.URL.Query().Encode()
orchestrator := r.URL.Query().Get("orchestrator")
rawParams := r.URL.Query().Get("params")
if rawParams != "" {
if err := json.Unmarshal([]byte(rawParams), &pipelineParams); err != nil {
clog.Errorf(ctx, "Invalid pipeline params: %s", err)
http.Error(w, "Invalid pipeline params", http.StatusBadRequest)
return
}
}
// collect RTMP outputs
var rtmpOutputs []string