internal/player.go

188 lines · 4983 bytes

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