internal/player.go

390 lines · 10671 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
131	// Wait for the socket to become available with retries
132	socketReady := false
133	maxRetries := 10
134	retryDelay := 300 * time.Millisecond
135
136	Log(fmt.Sprintf("Waiting for MPV socket to be ready at %s", mpvSocketPath))
137	for i := 0; i < maxRetries; i++ {
138		time.Sleep(retryDelay)
139
140		// Try to connect to the socket
141		conn, err := connectToPipe(mpvSocketPath)
142		if err == nil {
143			conn.Close()
144			socketReady = true
145			Log(fmt.Sprintf("MPV socket ready after %d attempts", i+1))
146			break
147		}
148
149		Log(fmt.Sprintf("Attempt %d/%d - Socket not ready yet: %v", i+1, maxRetries, err))
150	}
151
152	if !socketReady {
153		Log(fmt.Sprintf("Failed to connect to MPV socket after %d attempts", maxRetries))
154		// Don't fail here, just warn and continue - the next commands will handle any further issues
155	}
156
157	return mpvSocketPath, nil
158}
159
160// Helper function to join args with a space
161func joinArgs(args []string) string {
162	result := ""
163	for i, arg := range args {
164		if i > 0 {
165			result += " "
166		}
167		result += arg
168	}
169	return result
170}
171
172func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, error) {
173	// Use a retry mechanism for transient errors
174	var lastErr error
175	maxRetries := 3
176	retryDelay := 100 * time.Millisecond
177
178	for attempt := 0; attempt < maxRetries; attempt++ {
179		if attempt > 0 {
180			time.Sleep(retryDelay)
181			Log(fmt.Sprintf("Retrying MPV command, attempt %d/%d", attempt+1, maxRetries))
182		}
183
184		conn, err := connectToPipe(ipcSocketPath)
185		if err != nil {
186			lastErr = err
187			Log(fmt.Sprintf("Connect error (attempt %d/%d): %v", attempt+1, maxRetries, err))
188			continue // Try again
189		}
190		defer conn.Close()
191
192		commandStr, err := json.Marshal(map[string]interface{}{
193			"command": command,
194		})
195		if err != nil {
196			return nil, err // Don't retry on JSON marshalling errors
197		}
198
199		// Send the command
200		_, err = conn.Write(append(commandStr, '\n'))
201		if err != nil {
202			lastErr = err
203			Log(fmt.Sprintf("Write error (attempt %d/%d): %v", attempt+1, maxRetries, err))
204			continue // Try again
205		}
206
207		// Receive the response with timeout
208		buf := make([]byte, 4096)
209		// Set read deadline for 1 second
210		if deadline, ok := conn.(interface{ SetReadDeadline(time.Time) error }); ok {
211			deadline.SetReadDeadline(time.Now().Add(1 * time.Second))
212		}
213
214		n, err := conn.Read(buf)
215		if err != nil {
216			lastErr = err
217			Log(fmt.Sprintf("Read error (attempt %d/%d): %v", attempt+1, maxRetries, err))
218			continue // Try again
219		}
220
221		var response map[string]interface{}
222		if err := json.Unmarshal(buf[:n], &response); err != nil {
223			lastErr = err
224			Log(fmt.Sprintf("JSON parse error (attempt %d/%d): %v", attempt+1, maxRetries, err))
225			continue // Try again
226		}
227
228		// Success!
229		if data, exists := response["data"]; exists {
230			return data, nil
231		}
232		return nil, nil
233	}
234
235	// All retries failed
236	return nil, fmt.Errorf("command failed after %d attempts: %w", maxRetries, lastErr)
237}
238
239func SeekMPV(ipcSocketPath string, time int) (interface{}, error) {
240	command := []interface{}{"seek", time, "absolute"}
241	return MPVSendCommand(ipcSocketPath, command)
242}
243
244func GetMPVPausedStatus(ipcSocketPath string) (bool, error) {
245	status, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "pause"})
246	if err != nil || status == nil {
247		return false, err
248	}
249
250	paused, ok := status.(bool)
251	if ok {
252		return paused, nil
253	}
254	return false, nil
255}
256
257func GetMPVPlaybackSpeed(ipcSocketPath string) (float64, error) {
258	speed, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "speed"})
259	if err != nil || speed == nil {
260		Log("Failed to get playback speed.")
261		return 0, err
262	}
263
264	currentSpeed, ok := speed.(float64)
265	if ok {
266		return currentSpeed, nil
267	}
268
269	return 0, nil
270}
271
272func GetPercentageWatched(ipcSocketPath string) (float64, error) {
273	currentTime, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "time-pos"})
274	if err != nil || currentTime == nil {
275		return 0, err
276	}
277
278	duration, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "duration"})
279	if err != nil || duration == nil {
280		return 0, err
281	}
282
283	currTime, ok1 := currentTime.(float64)
284	dur, ok2 := duration.(float64)
285
286	if ok1 && ok2 && dur > 0 {
287		percentageWatched := (currTime / dur) * 100
288		return percentageWatched, nil
289	}
290
291	return 0, nil
292}
293
294func PercentageWatched(playbackTime int, duration int) float64 {
295	if duration > 0 {
296		percentage := (float64(playbackTime) / float64(duration)) * 100
297		return percentage
298	}
299	return float64(0)
300}
301
302func HasActivePlayback(ipcSocketPath string) (bool, error) {
303	maxRetries := 3
304	var lastErr error
305
306	for attempt := 0; attempt < maxRetries; attempt++ {
307		if attempt > 0 {
308			time.Sleep(200 * time.Millisecond)
309		}
310
311		// Get the time-pos property from MPV
312		timePos, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "time-pos"})
313
314		if err != nil {
315			// Check specifically for "property unavailable" error - this is a valid state
316			if strings.Contains(err.Error(), "property unavailable") {
317				Log("HasActivePlayback: Property unavailable, nothing is playing")
318				return false, nil
319			}
320
321			// Check for socket connection errors - these might be temporary
322			if strings.Contains(err.Error(), "connect: connection refused") ||
323				strings.Contains(err.Error(), "connect: no such file or directory") {
324				lastErr = err
325				Log(fmt.Sprintf("HasActivePlayback: Connection error (attempt %d/%d): %v",
326					attempt+1, maxRetries, err))
327				continue // Try again
328			}
329
330			// Other errors should be returned
331			return false, fmt.Errorf("error getting time-pos: %w", err)
332		}
333
334		// If we got a valid response, something is playing
335		if timePos != nil {
336			return true, nil
337		}
338
339		// No error but no position either - likely nothing is playing
340		return false, nil
341	}
342
343	// If we get here, all retries failed
344	Log(fmt.Sprintf("HasActivePlayback: Failed after %d attempts: %v", maxRetries, lastErr))
345	return false, fmt.Errorf("failed to check playback status: %w", lastErr)
346}
347
348func IsMPVRunning(socketPath string) bool {
349	if socketPath == "" {
350		return false
351	}
352
353	maxRetries := 3
354	for attempt := 0; attempt < maxRetries; attempt++ {
355		if attempt > 0 {
356			time.Sleep(200 * time.Millisecond)
357			Log(fmt.Sprintf("Retrying MPV connection check, attempt %d/%d", attempt+1, maxRetries))
358		}
359
360		// Try to connect to the socket
361		conn, err := connectToPipe(socketPath)
362		if err != nil {
363			Log(fmt.Sprintf("IsMPVRunning: Connection error (attempt %d/%d): %v",
364				attempt+1, maxRetries, err))
365			continue
366		}
367		defer conn.Close()
368
369		// Send a simple command to check if MPV responds
370		_, err = MPVSendCommand(socketPath, []interface{}{"get_property", "pid"})
371		if err == nil {
372			return true
373		}
374
375		Log(fmt.Sprintf("IsMPVRunning: Command failed (attempt %d/%d): %v",
376			attempt+1, maxRetries, err))
377	}
378
379	// After all retries, conclude MPV is not running
380	return false
381}
382
383func ExitMPV(ipcSocketPath string) error {
384	// Send command to close MPV
385	_, err := MPVSendCommand(ipcSocketPath, []interface{}{"quit"})
386	if err != nil {
387		Log("Error closing MPV: " + err.Error())
388	}
389	return err
390}