internal/player.go
200 lines · 5225 bytes
1package internal
2
3import (
4 // "fmt"
5 "crypto/rand"
6 "encoding/json"
7 "fmt"
8 "net"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "runtime"
13 "github.com/Microsoft/go-winio"
14)
15var logFile = "debug.log"
16
17func getMPVPath() (string, error) {
18 exePath, err := os.Executable()
19 if err != nil {
20 return "", err
21 }
22 exeDir := filepath.Dir(exePath)
23 mpvPath := filepath.Join(exeDir, "bin", "mpv.exe") // Adjust the relative path
24 return mpvPath, nil
25}
26
27func StartVideo(link string, args []string) (string, error) {
28 var command *exec.Cmd
29
30 // Generate a random number for the socket path
31 randomBytes := make([]byte, 4)
32 _, err := rand.Read(randomBytes)
33 if err != nil {
34 Log("Failed to generate random number", logFile)
35 return "", fmt.Errorf("failed to generate random number: %w", err)
36 }
37
38 randomNumber := fmt.Sprintf("%x", randomBytes)
39
40 // Create the mpv socket path with the random number
41 var mpvSocketPath string
42 if runtime.GOOS == "windows" {
43 mpvSocketPath = fmt.Sprintf(`\\.\pipe\curd_mpvsocket_%s`, randomNumber)
44 } else {
45 mpvSocketPath = fmt.Sprintf("/tmp/curd/curd_mpvsocket_%s", randomNumber)
46 }
47
48 // Prepare arguments for mpv
49 var mpvArgs []string
50 mpvArgs = append(mpvArgs, "--no-terminal", "--really-quiet", fmt.Sprintf("--input-ipc-server=%s", mpvSocketPath), link)
51 // Add any additional arguments passed
52 if len(args) > 0 {
53 mpvArgs = append(mpvArgs, args...) }
54
55 if runtime.GOOS == "windows" {
56 // Get the path to mpv.exe for Windows
57 mpvPath, err := getMPVPath()
58 if err != nil {
59 fmt.Println("Error: Failed to get MPV path")
60 Log("Failed to get mpv path.", logFile)
61 return "", err
62 }
63
64 // Create command for Windows
65 command = exec.Command(mpvPath, mpvArgs...)
66 } else {
67 // Create command for Unix-like systems
68 command = exec.Command("mpv", mpvArgs...)
69 }
70
71 // Start the mpv process
72 err = command.Start()
73 if err != nil {
74 fmt.Println("Error: Failed to start mpv process")
75 return "", fmt.Errorf("failed to start mpv: %w", err)
76 }
77 return mpvSocketPath, nil
78}
79
80// Helper function to join args with a space
81func joinArgs(args []string) string {
82 result := ""
83 for i, arg := range args {
84 if i > 0 {
85 result += " "
86 }
87 result += arg
88 }
89 return result
90}
91
92func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, error) {
93 var conn net.Conn
94 var err error
95
96 if runtime.GOOS == "windows" {
97 // Use named pipe for Windows
98 conn, err = winio.DialPipe(ipcSocketPath, nil)
99 } else {
100 conn, err = net.Dial("unix", ipcSocketPath)
101 }
102 if err != nil {
103 return nil, err
104 }
105 defer conn.Close()
106
107 commandStr, err := json.Marshal(map[string]interface{}{
108 "command": command,
109 })
110 if err != nil {
111 return nil, err
112 }
113
114 // Send the command
115 _, err = conn.Write(append(commandStr, '\n'))
116 if err != nil {
117 return nil, err
118 }
119
120 // Receive the response
121 buf := make([]byte, 4096)
122 n, err := conn.Read(buf)
123 if err != nil {
124 return nil, err
125 }
126
127 var response map[string]interface{}
128 if err := json.Unmarshal(buf[:n], &response); err != nil {
129 return nil, err
130 }
131
132 if data, exists := response["data"]; exists {
133 return data, nil
134 }
135
136 return nil, nil
137}
138
139func SeekMPV(ipcSocketPath string, time int) (interface{}, error) {
140 command := []interface{}{"seek", time, "absolute"}
141 return MPVSendCommand(ipcSocketPath, command)
142}
143
144func GetMPVPausedStatus(ipcSocketPath string) (bool, error) {
145 status, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "pause"})
146 if err != nil || status == nil {
147 return false, err
148 }
149
150 paused, ok := status.(bool)
151 if ok {
152 return paused, nil
153 }
154 return false, nil
155}
156
157func GetMPVPlaybackSpeed(ipcSocketPath string) (float64, error) {
158 speed, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "speed"})
159 if err != nil || speed == nil {
160 Log("Failed to get playback speed.", logFile)
161 return 0, err
162 }
163
164 currentSpeed, ok := speed.(float64)
165 if ok {
166 return currentSpeed, nil
167 }
168
169 return 0, nil
170}
171
172func GetPercentageWatched(ipcSocketPath string) (float64, error) {
173 currentTime, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "time-pos"})
174 if err != nil || currentTime == nil {
175 return 0, err
176 }
177
178 duration, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "duration"})
179 if err != nil || duration == nil {
180 return 0, err
181 }
182
183 currTime, ok1 := currentTime.(float64)
184 dur, ok2 := duration.(float64)
185
186 if ok1 && ok2 && dur > 0 {
187 percentageWatched := (currTime / dur) * 100
188 return percentageWatched, nil
189 }
190
191 return 0, nil
192}
193
194func PercentageWatched(playbackTime int, duration int) float64 {
195 if duration > 0 {
196 percentage := (float64(playbackTime) / float64(duration)) * 100
197 return percentage
198 }
199 return float64(0)
200}