internal/player.go

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