-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathworker_helper.go
98 lines (83 loc) · 2.18 KB
/
worker_helper.go
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
package mediasoup
import (
"bytes"
"encoding/json"
"io"
"os"
"os/exec"
"strings"
"time"
"github.com/jiyeyuran/mediasoup-go/netcodec"
)
func detectNewCloseMethods(workerBin string) bool {
data, err := os.ReadFile(workerBin)
if err != nil {
return false
}
return bytes.Contains(data, []byte("worker.closeRouter"))
}
func detectNetCodec(settings *WorkerSettings, newCodec func(io.WriteCloser, io.ReadCloser) netcodec.Codec) (ok bool) {
bin := settings.WorkerBin
args := settings.Args()
if wrappedArgs := strings.Fields(settings.WorkerBin); len(wrappedArgs) > 1 {
bin = wrappedArgs[0]
args = append(wrappedArgs[1:], args...)
}
var pipeFiles []io.Closer
defer func() {
for i := len(pipeFiles) - 1; i >= 0; i-- {
pipeFiles[i].Close()
}
}()
producerReader, producerWriter, err := os.Pipe()
if err != nil {
return
}
pipeFiles = append(pipeFiles, producerReader, producerWriter)
consumerReader, consumerWriter, err := os.Pipe()
if err != nil {
return
}
pipeFiles = append(pipeFiles, consumerReader, consumerWriter)
payloadProducerReader, payloadProducerWriter, err := os.Pipe()
if err != nil {
return
}
pipeFiles = append(pipeFiles, payloadProducerReader, payloadProducerWriter)
payloadConsumerReader, payloadConsumerWriter, err := os.Pipe()
if err != nil {
return
}
pipeFiles = append(pipeFiles, payloadConsumerReader, payloadConsumerWriter)
child := exec.Command(bin, args...)
child.ExtraFiles = []*os.File{producerReader, consumerWriter, payloadProducerReader, payloadConsumerWriter}
child.Env = []string{"MEDIASOUP_VERSION=" + settings.WorkerVersion}
if err = child.Start(); err != nil {
return
}
defer child.Process.Kill()
waitTimer := time.NewTimer(time.Second)
defer waitTimer.Stop()
codec := newCodec(producerWriter, consumerReader)
go func() {
<-waitTimer.C
codec.Close()
}()
for {
data, err := codec.ReadPayload()
if err != nil {
return false
}
if len(data) > 0 && data[0] != '{' {
continue
}
var msg struct {
TargetId int `json:"targetId,omitempty"`
Event string `json:"event,omitempty"`
}
if err = json.Unmarshal(data, &msg); err != nil {
return false
}
return msg.TargetId == child.Process.Pid
}
}