internal/player.go
264 lines · 7151 bytes
1package internal
2
3import (
4 // "fmt"
5 "crypto/rand"
6 "encoding/json"
7 "fmt"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "runtime"
12 "strings"
13)
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, title string, anime *Anime) (string, error) {
28 var command *exec.Cmd
29 var mpvSocketPath string
30 var err error
31
32 // Check if we have an existing socket and if MPV is still running
33 if anime.Ep.Player.SocketPath != "" && IsMPVRunning(anime.Ep.Player.SocketPath) {
34 // Reuse existing socket
35 mpvSocketPath = anime.Ep.Player.SocketPath
36
37 // Load the new file in the existing MPV instance
38 command := []interface{}{"loadfile", link}
39 _, err = MPVSendCommand(mpvSocketPath, command)
40 if err != nil {
41 return "", fmt.Errorf("failed to load file in existing MPV instance: %w", err)
42 }
43
44 // Set the new title
45 _, err = MPVSendCommand(mpvSocketPath, []interface{}{"set_property", "force-media-title", title})
46 if err != nil {
47 Log(fmt.Sprintf("Failed to set title: %v", err), logFile)
48 }
49
50 return mpvSocketPath, nil
51 }
52
53 if anime.Ep.Player.SocketPath == "" {
54 // Generate a random number for the socket path
55 randomBytes := make([]byte, 4)
56 _, err = rand.Read(randomBytes)
57 if err != nil {
58 Log("Failed to generate random number", logFile)
59 return "", fmt.Errorf("failed to generate random number: %w", err)
60 }
61
62 randomNumber := fmt.Sprintf("%x", randomBytes)
63
64 // Create the mpv socket path with the random number
65 if runtime.GOOS == "windows" {
66 mpvSocketPath = fmt.Sprintf(`\\.\pipe\curd_mpvsocket_%s`, randomNumber)
67 } else {
68 mpvSocketPath = fmt.Sprintf("/tmp/curd_mpvsocket_%s", randomNumber)
69 }
70 } else {
71 mpvSocketPath = anime.Ep.Player.SocketPath
72 }
73
74 // Add the title to MPV arguments
75 titleArgs := []string{fmt.Sprintf("--title=%s", title), fmt.Sprintf("--force-media-title=%s", title)}
76
77 // Keep the window open after episode completes, new episode starts in the same mpv window
78 args = append(args, "--force-window=yes", "--idle=yes")
79 args = append(args, titleArgs...)
80
81 // Prepare arguments for mpv
82 var mpvArgs []string
83 mpvArgs = append(mpvArgs, "--no-terminal", "--really-quiet", fmt.Sprintf("--input-ipc-server=%s", mpvSocketPath), link)
84 // Add any additional arguments passed
85 if len(args) > 0 {
86 mpvArgs = append(mpvArgs, args...)
87 }
88
89 if runtime.GOOS == "windows" {
90 // Get the path to mpv.exe for Windows
91 mpvPath, err := getMPVPath()
92 if err != nil {
93 CurdOut("Error: Failed to get MPV path")
94 Log("Failed to get mpv path.", logFile)
95 return "", err
96 }
97
98 // Create command for Windows
99 command = exec.Command(mpvPath, mpvArgs...)
100 } else {
101 // Create command for Unix-like systems
102 command = exec.Command("mpv", mpvArgs...)
103 }
104
105 // Start the mpv process
106 err = command.Start()
107 if err != nil {
108 CurdOut("Error: Failed to start mpv process")
109 return "", fmt.Errorf("failed to start mpv: %w", err)
110 }
111 return mpvSocketPath, nil
112}
113
114// Helper function to join args with a space
115func joinArgs(args []string) string {
116 result := ""
117 for i, arg := range args {
118 if i > 0 {
119 result += " "
120 }
121 result += arg
122 }
123 return result
124}
125
126func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, error) {
127 conn, err := connectToPipe(ipcSocketPath)
128 if err != nil {
129 return nil, err
130 }
131 defer conn.Close()
132
133 commandStr, err := json.Marshal(map[string]interface{}{
134 "command": command,
135 })
136 if err != nil {
137 return nil, err
138 }
139
140 // Send the command
141 _, err = conn.Write(append(commandStr, '\n'))
142 if err != nil {
143 return nil, err
144 }
145
146 // Receive the response
147 buf := make([]byte, 4096)
148 n, err := conn.Read(buf)
149 if err != nil {
150 return nil, err
151 }
152
153 var response map[string]interface{}
154 if err := json.Unmarshal(buf[:n], &response); err != nil {
155 return nil, err
156 }
157
158 if data, exists := response["data"]; exists {
159 return data, nil
160 }
161
162 return nil, nil
163}
164
165func SeekMPV(ipcSocketPath string, time int) (interface{}, error) {
166 command := []interface{}{"seek", time, "absolute"}
167 return MPVSendCommand(ipcSocketPath, command)
168}
169
170func GetMPVPausedStatus(ipcSocketPath string) (bool, error) {
171 status, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "pause"})
172 if err != nil || status == nil {
173 return false, err
174 }
175
176 paused, ok := status.(bool)
177 if ok {
178 return paused, nil
179 }
180 return false, nil
181}
182
183func GetMPVPlaybackSpeed(ipcSocketPath string) (float64, error) {
184 speed, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "speed"})
185 if err != nil || speed == nil {
186 Log("Failed to get playback speed.", logFile)
187 return 0, err
188 }
189
190 currentSpeed, ok := speed.(float64)
191 if ok {
192 return currentSpeed, nil
193 }
194
195 return 0, nil
196}
197
198func GetPercentageWatched(ipcSocketPath string) (float64, error) {
199 currentTime, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "time-pos"})
200 if err != nil || currentTime == nil {
201 return 0, err
202 }
203
204 duration, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "duration"})
205 if err != nil || duration == nil {
206 return 0, err
207 }
208
209 currTime, ok1 := currentTime.(float64)
210 dur, ok2 := duration.(float64)
211
212 if ok1 && ok2 && dur > 0 {
213 percentageWatched := (currTime / dur) * 100
214 return percentageWatched, nil
215 }
216
217 return 0, nil
218}
219
220func PercentageWatched(playbackTime int, duration int) float64 {
221 if duration > 0 {
222 percentage := (float64(playbackTime) / float64(duration)) * 100
223 return percentage
224 }
225 return float64(0)
226}
227
228func HasActivePlayback(ipcSocketPath string) (bool, error) {
229 // Get the time-pos property from MPV
230 timePos, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "time-pos"})
231 if err != nil {
232 // Check specifically for "property unavailable" error
233 if strings.Contains(err.Error(), "property unavailable") {
234 // This indicates nothing is playing
235 return false, nil
236 }
237 return false, fmt.Errorf("error getting time-pos: %w", err)
238 }
239
240 // If we got a valid response, something is playing
241 if timePos != nil {
242 return true, nil
243 }
244
245 // Default to false if we can't determine the status
246 return false, nil
247}
248
249func IsMPVRunning(socketPath string) bool {
250 if socketPath == "" {
251 return false
252 }
253
254 // Try to connect to the socket
255 conn, err := connectToPipe(socketPath)
256 if err != nil {
257 return false
258 }
259 defer conn.Close()
260
261 // Send a simple command to check if MPV responds
262 _, err = MPVSendCommand(socketPath, []interface{}{"get_property", "pid"})
263 return err == nil
264}