Commit adf5406ca6
Unsigned
Layout: unified · split
internal/player.go +126 −100
| @@ -2,122 +2,148 @@ package internal | |||
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | // "fmt" | 4 | // "fmt" |
| 5 | "crypto/rand" | ||
| 5 | "encoding/json" | 6 | "encoding/json" |
| 6 | "fmt" | 7 | "fmt" |
| 7 | "net" | 8 | "net" |
| 8 | "os" | ||
| 9 | "os/exec" | 9 | "os/exec" |
| 10 | "strconv" | ||
| 11 | "time" | ||
| 12 | "math/rand" | ||
| 13 | ) | 10 | ) |
| 14 | var logFile = "debug.log" | 11 | var logFile = "debug.log" |
| 15 | 12 | ||
| 16 | // StartMpv starts the mpv player with the given video URL and return ipc socket path. | 13 | func StartVideo(link string, args []string) (string, error) { |
| 17 | func StartMpv(videoURL string) (string, error) { | 14 | // Generate a random number for the socket path |
| 18 | // Generate a random mpvsocket path (Linux only) | 15 | randomBytes := make([]byte, 4) |
| 19 | randomNumber := rand.Intn(100) // Change 100 to the desired range | 16 | _, err := rand.Read(randomBytes) |
| 20 | fmt.Println("random number", randomNumber) | 17 | if err != nil { |
| 21 | mpvSocketPath := "/tmp/mpvsocket"+strconv.Itoa(randomNumber) | 18 | Log("Failed to generate random number", logFile) |
| 22 | 19 | return "", fmt.Errorf("failed to generate random number: %w", err) | |
| 23 | cmd := exec.Command("mpv", "--input-ipc-server="+mpvSocketPath, videoURL) | 20 | } |
| 24 | return mpvSocketPath, cmd.Start() | 21 | randomNumber := fmt.Sprintf("%x", randomBytes) |
| 22 | |||
| 23 | // Create the mpv socket path with the random number | ||
| 24 | mpvSocketPath := fmt.Sprintf("/tmp/curd/curd_mpvsocket_%s", randomNumber) | ||
| 25 | argsStr := "" | ||
| 26 | if len(args) > 0 { | ||
| 27 | argsStr = " " + joinArgs(args) | ||
| 28 | } | ||
| 29 | |||
| 30 | // Build the complete command string | ||
| 31 | command := fmt.Sprintf("mpv%s --no-terminal --really-quiet --input-ipc-server=%s %s", argsStr, mpvSocketPath, link) | ||
| 32 | |||
| 33 | // Execute the command using exec | ||
| 34 | cmd := exec.Command("bash", "-c", command) | ||
| 35 | cmd.Start() | ||
| 36 | |||
| 37 | return mpvSocketPath, nil | ||
| 25 | } | 38 | } |
| 26 | 39 | ||
| 27 | // sendIpcMessage sends a JSON message to the mpv IPC socket and reads the response. | 40 | // Helper function to join args with a space |
| 28 | func sendIpcMessage(socketPath string, msg map[string]interface{}) (map[string]interface{}, error) { | 41 | func joinArgs(args []string) string { |
| 29 | // Create a Unix socket connection | 42 | result := "" |
| 30 | conn, err := net.Dial("unix", socketPath) | 43 | for i, arg := range args { |
| 31 | if err != nil { | 44 | if i > 0 { |
| 32 | return nil, fmt.Errorf("failed to connect to IPC socket: %w", err) | 45 | result += " " |
| 33 | } | 46 | } |
| 34 | defer conn.Close() | 47 | result += arg |
| 35 | 48 | } | |
| 36 | // Marshal the message into JSON | 49 | return result |
| 37 | data, err := json.Marshal(msg) | ||
| 38 | if err != nil { | ||
| 39 | return nil, fmt.Errorf("failed to marshal JSON message: %w", err) | ||
| 40 | } | ||
| 41 | |||
| 42 | // Write the message to the socket | ||
| 43 | _, err = conn.Write(append(data, '\n')) // Ensure newline at the end | ||
| 44 | if err != nil { | ||
| 45 | return nil, fmt.Errorf("failed to send message to IPC socket: %w", err) | ||
| 46 | } | ||
| 47 | |||
| 48 | // Set a read deadline to prevent blocking forever | ||
| 49 | conn.SetReadDeadline(time.Now().Add(2 * time.Second)) | ||
| 50 | |||
| 51 | // Read the response from the socket | ||
| 52 | var response map[string]interface{} | ||
| 53 | decoder := json.NewDecoder(conn) | ||
| 54 | if err := decoder.Decode(&response); err != nil { | ||
| 55 | return nil, fmt.Errorf("failed to decode response: %w", err) | ||
| 56 | } | ||
| 57 | |||
| 58 | return response, nil | ||
| 59 | } | 50 | } |
| 60 | 51 | ||
| 61 | // GetMpvProperty retrieves a property from mpv via IPC. | 52 | func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, error) { |
| 62 | func GetMpvProperty(socketPath, property string) (string, error) { | 53 | conn, err := net.Dial("unix", ipcSocketPath) |
| 63 | // Prepare the JSON message to request the property | 54 | if err != nil { |
| 64 | msg := map[string]interface{}{ | 55 | return nil, err |
| 65 | "command": []interface{}{"get_property", property}, | 56 | } |
| 66 | } | 57 | defer conn.Close() |
| 67 | 58 | ||
| 68 | // Send the message via IPC and get the response | 59 | commandStr, err := json.Marshal(map[string]interface{}{ |
| 69 | response, err := sendIpcMessage(socketPath, msg) | 60 | "command": command, |
| 70 | if err != nil { | 61 | }) |
| 71 | return "", fmt.Errorf("failed to send IPC message: %w", err) | 62 | if err != nil { |
| 72 | } | 63 | return nil, err |
| 73 | 64 | } | |
| 74 | // Check the response for errors and extract the value | 65 | |
| 75 | if errVal, ok := response["error"]; ok && errVal != "success" { | 66 | // Send the command |
| 76 | return "", fmt.Errorf("mpv returned an error: %v", errVal) | 67 | conn.Write(append(commandStr, '\n')) |
| 77 | } | 68 | |
| 78 | 69 | // Receive the response | |
| 79 | // Retrieve the value from the response | 70 | buf := make([]byte, 4096) |
| 80 | if data, ok := response["data"]; ok { | 71 | n, err := conn.Read(buf) |
| 81 | return fmt.Sprintf("%v", data), nil | 72 | if err != nil { |
| 82 | } | 73 | return nil, err |
| 83 | 74 | } | |
| 84 | return "", fmt.Errorf("no data in response") | 75 | |
| 76 | var response map[string]interface{} | ||
| 77 | if err := json.Unmarshal(buf[:n], &response); err != nil { | ||
| 78 | return nil, err | ||
| 79 | } | ||
| 80 | |||
| 81 | if data, exists := response["data"]; exists { | ||
| 82 | return data, nil | ||
| 83 | } | ||
| 84 | |||
| 85 | return nil, nil | ||
| 85 | } | 86 | } |
| 86 | 87 | ||
| 88 | func SeekMPV(ipcSocketPath string, time int) (interface{}, error) { | ||
| 89 | command := []interface{}{"seek", time, "absolute"} | ||
| 90 | return MPVSendCommand(ipcSocketPath, command) | ||
| 91 | } | ||
| 92 | |||
| 93 | func GetMPVPausedStatus(ipcSocketPath string) (bool, error) { | ||
| 94 | status, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "pause"}) | ||
| 95 | if err != nil || status == nil { | ||
| 96 | return false, err | ||
| 97 | } | ||
| 98 | |||
| 99 | paused, ok := status.(bool) | ||
| 100 | if ok { | ||
| 101 | return paused, nil | ||
| 102 | } | ||
| 103 | return false, nil | ||
| 104 | } | ||
| 105 | |||
| 106 | func GetMPVPlaybackSpeed(ipcSocketPath string) (float64, error) { | ||
| 107 | speed, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "speed"}) | ||
| 108 | if err != nil || speed == nil { | ||
| 109 | fmt.Println("Failed to get playback speed.") | ||
| 110 | return 0, err | ||
| 111 | } | ||
| 112 | |||
| 113 | currentSpeed, ok := speed.(float64) | ||
| 114 | if ok { | ||
| 115 | return currentSpeed, nil | ||
| 116 | } | ||
| 87 | 117 | ||
| 88 | // SendMpvCommand sends a command to mpv via IPC. | 118 | return 0, nil |
| 89 | func SendMpvCommand(socketPath, command string, args ...string) error { | ||
| 90 | msg := map[string]interface{}{ | ||
| 91 | "command": append([]interface{}{command}, convertArgs(args)...), | ||
| 92 | } | ||
| 93 | return SendMpvMessage(socketPath, msg) | ||
| 94 | } | 119 | } |
| 95 | 120 | ||
| 96 | // ConvertArgs converts []string to []interface{}. | 121 | func GetPercentageWatched(ipcSocketPath string) (float64, error) { |
| 97 | func convertArgs(args []string) []interface{} { | 122 | currentTime, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "time-pos"}) |
| 98 | interfaceArgs := make([]interface{}, len(args)) | 123 | if err != nil || currentTime == nil { |
| 99 | for i, v := range args { | 124 | return 0, err |
| 100 | interfaceArgs[i] = v | 125 | } |
| 101 | } | 126 | |
| 102 | return interfaceArgs | 127 | duration, err := MPVSendCommand(ipcSocketPath, []interface{}{"get_property", "duration"}) |
| 128 | if err != nil || duration == nil { | ||
| 129 | return 0, err | ||
| 130 | } | ||
| 131 | |||
| 132 | currTime, ok1 := currentTime.(float64) | ||
| 133 | dur, ok2 := duration.(float64) | ||
| 134 | |||
| 135 | if ok1 && ok2 && dur > 0 { | ||
| 136 | percentageWatched := (currTime / dur) * 100 | ||
| 137 | return percentageWatched, nil | ||
| 138 | } | ||
| 139 | |||
| 140 | return 0, nil | ||
| 103 | } | 141 | } |
| 104 | 142 | ||
| 105 | // SendMpvMessage sends a JSON message to mpv via IPC. | 143 | func PercentageWatched(playbackTime int, duration int) *float64 { |
| 106 | func SendMpvMessage(socketPath string, msg map[string]interface{}) error { | 144 | if duration > 0 { |
| 107 | data, err := json.Marshal(msg) | 145 | percentage := (float64(playbackTime) / float64(duration)) * 100 |
| 108 | if err != nil { | 146 | return &percentage |
| 109 | return fmt.Errorf("failed to marshal message: %w", err) | 147 | } |
| 110 | } | 148 | return nil |
| 111 | |||
| 112 | socket, err := os.OpenFile(socketPath, os.O_RDWR|os.O_CREATE, 0666) | ||
| 113 | if err != nil { | ||
| 114 | return fmt.Errorf("failed to open IPC socket: %w", err) | ||
| 115 | } | ||
| 116 | defer socket.Close() | ||
| 117 | |||
| 118 | _, err = socket.Write(data) | ||
| 119 | if err != nil { | ||
| 120 | return fmt.Errorf("failed to send message to mpv: %w", err) | ||
| 121 | } | ||
| 122 | return nil | ||
| 123 | } | 149 | } |