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