internal/player.go

204 lines · 5348 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, title 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    // Add the title to MPV arguments
 49    titleArg := fmt.Sprintf("--title=%s", title)
 50    args = append(args, titleArg)
 51
 52    // Prepare arguments for mpv
 53    var mpvArgs []string
 54    mpvArgs = append(mpvArgs, "--no-terminal", "--really-quiet", fmt.Sprintf("--input-ipc-server=%s", mpvSocketPath), link)
 55    // Add any additional arguments passed
 56    if len(args) > 0 {
 57        mpvArgs = append(mpvArgs, args...)    }
 58
 59    if runtime.GOOS == "windows" {
 60        // Get the path to mpv.exe for Windows
 61        mpvPath, err := getMPVPath()
 62        if err != nil {
 63            CurdOut("Error: Failed to get MPV path")
 64            Log("Failed to get mpv path.", logFile)
 65            return "", err
 66        }
 67
 68        // Create command for Windows
 69        command = exec.Command(mpvPath, mpvArgs...)
 70    } else {
 71        // Create command for Unix-like systems
 72        command = exec.Command("mpv", mpvArgs...)
 73    }
 74
 75    // Start the mpv process
 76    err = command.Start()
 77    if err != nil {
 78        CurdOut("Error: Failed to start mpv process")
 79        return "", fmt.Errorf("failed to start mpv: %w", err)
 80    }
 81    return mpvSocketPath, nil
 82}
 83
 84// Helper function to join args with a space
 85func joinArgs(args []string) string {
 86    result := ""
 87    for i, arg := range args {
 88        if i > 0 {
 89            result += " "
 90        }
 91        result += arg
 92    }
 93    return result
 94}
 95
 96func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, error) {
 97    var conn net.Conn
 98    var err error
 99
100    if runtime.GOOS == "windows" {
101        // Use named pipe for Windows
102        conn, err = winio.DialPipe(ipcSocketPath, nil)
103    } else {
104        conn, err = net.Dial("unix", ipcSocketPath)
105    }
106    if err != nil {
107        return nil, err
108    }
109    defer conn.Close()
110
111    commandStr, err := json.Marshal(map[string]interface{}{
112        "command": command,
113    })
114    if err != nil {
115        return nil, err
116    }
117
118    // Send the command
119    _, err = conn.Write(append(commandStr, '\n'))
120    if err != nil {
121        return nil, err
122    }
123
124    // Receive the response
125    buf := make([]byte, 4096)
126    n, err := conn.Read(buf)
127    if err != nil {
128        return nil, err
129    }
130
131    var response map[string]interface{}
132    if err := json.Unmarshal(buf[:n], &response); err != nil {
133        return nil, err
134    }
135
136    if data, exists := response["data"]; exists {
137        return data, nil
138    }
139
140    return nil, nil
141}
142
143func SeekMPV(ipcSocketPath string, time int) (interface{}, error) {
144    command := []interface{}{"seek", time, "absolute"}
145    return MPVSendCommand(ipcSocketPath, command)
146}
147
148func GetMPVPausedStatus(ipcSocketPath string) (bool, error) {
149    status, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "pause"})
150    if err != nil || status == nil {
151        return false, err
152    }
153
154    paused, ok := status.(bool)
155    if ok {
156        return paused, nil
157    }
158    return false, nil
159}
160
161func GetMPVPlaybackSpeed(ipcSocketPath string) (float64, error) {
162    speed, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "speed"})
163    if err != nil || speed == nil {
164        Log("Failed to get playback speed.", logFile)
165        return 0, err
166    }
167
168    currentSpeed, ok := speed.(float64)
169    if ok {
170        return currentSpeed, nil
171    }
172
173    return 0, nil
174}
175
176func GetPercentageWatched(ipcSocketPath string) (float64, error) {
177    currentTime, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "time-pos"})
178    if err != nil || currentTime == nil {
179        return 0, err
180    }
181
182    duration, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "duration"})
183    if err != nil || duration == nil {
184        return 0, err
185    }
186
187    currTime, ok1 := currentTime.(float64)
188    dur, ok2 := duration.(float64)
189
190    if ok1 && ok2 && dur > 0 {
191        percentageWatched := (currTime / dur) * 100
192        return percentageWatched, nil
193    }
194
195    return 0, nil
196}
197
198func PercentageWatched(playbackTime int, duration int) float64 {
199    if duration > 0 {
200        percentage := (float64(playbackTime) / float64(duration)) * 100
201        return percentage
202    }
203    return float64(0)
204}