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