525 lines
21 KiB
Racket
525 lines
21 KiB
Racket
#lang racket/base
|
|
|
|
(require json
|
|
net/url
|
|
racket-audio
|
|
racket/contract
|
|
racket/file
|
|
racket/path
|
|
racket/port
|
|
racket/string
|
|
simple-log
|
|
"player-agent-translate.rkt")
|
|
|
|
(provide (struct-out player-agent-runtime)
|
|
make-player-agent-runtime)
|
|
|
|
(sl-def-log player-agent)
|
|
|
|
(struct exn:fail:agent-denied exn:fail () #:transparent)
|
|
|
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
; goal : Expose the small procedure-based interface of a running agent.
|
|
; pre : Constructor fields are lifecycle/query procedures and a stable ID.
|
|
; post : Creating or recognizing a value changes no external state.
|
|
; result : player-agent-runtime? recognizes values returned by the factory.
|
|
; internals: make-player-agent-runtime stores its local start!, reconnect!,
|
|
; shutdown!, snapshot and current-track procedures in this struct.
|
|
; Those procedures retain access to the factory closure, keeping the
|
|
; shared polling and audio state private without introducing a class.
|
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
(struct player-agent-runtime
|
|
(start! reconnect! shutdown! snapshot current-track running? app-id)
|
|
#:transparent)
|
|
|
|
;;; Normalizes a configured server address and converts it to a URL value.
|
|
(define (base-url value)
|
|
(string->url
|
|
(regexp-replace #px"/+$" (string-trim value) "")))
|
|
|
|
;;; Resolves an agent API path relative to a normalized server URL.
|
|
(define (endpoint-url base path)
|
|
(combine-url/relative (base-url base) path))
|
|
|
|
;;; Posts JSON to an agent API endpoint and reads its JSON response.
|
|
;;; Authorization failures receive a distinct exception for poll-loop.
|
|
(define (post-json base path data)
|
|
(let ((input
|
|
(post-pure-port
|
|
(endpoint-url base path)
|
|
(jsexpr->bytes data)
|
|
(list "Content-Type: application/json"
|
|
"Cache-Control: no-store"))))
|
|
(dynamic-wind
|
|
void
|
|
(λ ()
|
|
(let ((response (read-json input)))
|
|
(when (and (hash? response)
|
|
(string? (hash-ref response 'error #f)))
|
|
(if (equal? (hash-ref response 'code #f)
|
|
"agent-not-authorized")
|
|
(raise
|
|
(exn:fail:agent-denied
|
|
(hash-ref response 'error)
|
|
(current-continuation-marks)))
|
|
(error 'player-agent (hash-ref response 'error))))
|
|
response))
|
|
(λ () (close-input-port input)))))
|
|
|
|
;;; Converts racket-audio states to the state names sent to the web player.
|
|
(define (normal-state state)
|
|
(cond
|
|
((memq state '(initialized no-media)) "stopped")
|
|
((eq? state 'transitioning) "starting")
|
|
(else (symbol->string state))))
|
|
|
|
;;; Deletes a temporary media file and logs recoverable deletion failures.
|
|
(define (safe-delete-file file)
|
|
(when (and file (file-exists? file))
|
|
(with-handlers ((exn:fail?
|
|
(λ (exception)
|
|
(warn-player-agent
|
|
"Could not remove temporary media file ~a: ~a"
|
|
file
|
|
(exn-message exception)))))
|
|
(delete-file file))))
|
|
|
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
;; Provided functions
|
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
|
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
; goal : Create the headless polling and audio runtime for one agent.
|
|
; pre : Server URL, display name and application ID are strings; callbacks
|
|
; accept the status/denial messages supplied to them.
|
|
; post : Mutable state is initialized but no worker thread or audio backend
|
|
; is started until the returned start! procedure is called.
|
|
; result : A player-agent-runtime containing its lifecycle/query procedures.
|
|
; internals: start! launches poll-loop, which registers through post-json and
|
|
; sends snapshots until it receives a command. A command worker runs
|
|
; execute-command! and acknowledges it only after completion.
|
|
; ensure-audio! connects racket-audio callbacks to update-from-audio!
|
|
; and advance-at-decoder-eof!. with-agent-state protects their shared
|
|
; state; stop! and shutdown! stop threads, audio and cached files.
|
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
(define/contract (make-player-agent-runtime initial-server-url
|
|
initial-name
|
|
app-id
|
|
#:status-callback
|
|
[status-callback void]
|
|
#:denied-callback
|
|
[denied-callback void])
|
|
(->* (string? string? string?)
|
|
(#:status-callback (-> string? any/c)
|
|
#:denied-callback (-> string? any/c))
|
|
player-agent-runtime?)
|
|
(let* ((server-url initial-server-url)
|
|
(assigned-name initial-name)
|
|
(state-lock (make-semaphore 1))
|
|
(worker #f)
|
|
(command-worker #f)
|
|
(executing-command-id 0)
|
|
(running #f)
|
|
(authorization-notified? #f)
|
|
(audio #f)
|
|
(current-media-key #f)
|
|
(cached-media (make-hash))
|
|
(prefetched-track #f)
|
|
(auto-started-key #f)
|
|
(pending-auto-music-id #f)
|
|
(music-tracks (make-hash))
|
|
(current-track-value #f)
|
|
(acknowledged-command 0)
|
|
(ended-counter 0)
|
|
(logical-volume 50)
|
|
(agent-state
|
|
(hasheq 'state "stopped"
|
|
'position 0
|
|
'duration 'null
|
|
'rate 'null
|
|
'channels 'null
|
|
'bits 'null
|
|
'format ""
|
|
'volume logical-volume
|
|
'error 'null)))
|
|
|
|
;;; Runs a procedure while holding the semaphore for shared agent state.
|
|
(define (with-agent-state proc)
|
|
(call-with-semaphore state-lock proc))
|
|
|
|
;;; Replaces an unavailable state value with its JSON fallback.
|
|
(define (state-value value fallback)
|
|
(if (eq? value #f) fallback value))
|
|
|
|
;;; Returns the latest audio state while holding the state semaphore.
|
|
(define (snapshot)
|
|
(with-agent-state (λ () agent-state)))
|
|
|
|
;;; Returns the currently audible track while holding the state semaphore.
|
|
(define (current-track)
|
|
(with-agent-state (λ () current-track-value)))
|
|
|
|
;;; Stores an error in the state reported by the next poll.
|
|
(define (set-agent-error! message)
|
|
(with-agent-state
|
|
(λ ()
|
|
(set! agent-state (hash-set agent-state 'error message)))))
|
|
|
|
;;; Removes an earlier error from the state reported by the next poll.
|
|
(define (clear-agent-error!)
|
|
(with-agent-state
|
|
(λ ()
|
|
(set! agent-state (hash-set agent-state 'error 'null)))))
|
|
|
|
;;; Copies racket-audio state into the agent snapshot.
|
|
;;; It also confirms when a prefetched track has become audible.
|
|
(define (update-from-audio! state full-state)
|
|
(with-agent-state
|
|
(λ ()
|
|
(let ((audible-music-id (hash-ref full-state 'at-music-id #f)))
|
|
(set! agent-state
|
|
(hasheq
|
|
'state (normal-state state)
|
|
'position (state-value (hash-ref full-state 'at-second #f) 0)
|
|
'duration (state-value (hash-ref full-state 'duration #f) 'null)
|
|
'rate (state-value (hash-ref full-state 'rate #f) 'null)
|
|
'channels (state-value (hash-ref full-state 'channels #f) 'null)
|
|
'bits (state-value (hash-ref full-state 'bits #f) 'null)
|
|
'format (let ((decoder (hash-ref full-state 'decoder #f)))
|
|
(if decoder (format "~a" decoder) ""))
|
|
'volume logical-volume
|
|
'error 'null))
|
|
(when (and pending-auto-music-id
|
|
(number? audible-music-id)
|
|
(= pending-auto-music-id audible-music-id))
|
|
(let ((audible-track
|
|
(hash-ref music-tracks audible-music-id #f)))
|
|
(when audible-track
|
|
(set! current-track-value audible-track)
|
|
(hash-clear! music-tracks)
|
|
(hash-set! music-tracks audible-music-id audible-track)))
|
|
(set! pending-auto-music-id #f)
|
|
(set! ended-counter (+ ended-counter 1)))))))
|
|
|
|
;;; Creates and configures the audio player on first use.
|
|
;;; Its callbacks update reported state and continue prefetched playback.
|
|
(define (ensure-audio!)
|
|
(unless audio
|
|
(set! audio
|
|
(make-audio-player
|
|
(λ (_handle state full-state)
|
|
(update-from-audio! state full-state))
|
|
(λ (handle)
|
|
(advance-at-decoder-eof! handle))))
|
|
(audio-ao-buf-ms! audio 500)
|
|
(audio-buf-seconds! audio 4 10)
|
|
(let ((scaled (/ logical-volume 100.0)))
|
|
(audio-volume! audio (* 100.0 scaled scaled))))
|
|
audio)
|
|
|
|
;;; Downloads one protected media resource to a temporary local file.
|
|
;;; A failed download closes its port and removes its partial file.
|
|
(define (download-media! token filename)
|
|
(let* ((extension
|
|
(or (path-get-extension (string->path filename)) #""))
|
|
(target
|
|
(make-temporary-file
|
|
(string-append "rkt-player-agent-~a"
|
|
(bytes->string/utf-8 extension))))
|
|
(path (format "/api/agent/media/~a/~a" app-id token))
|
|
(input (get-pure-port (endpoint-url server-url path))))
|
|
(with-handlers ((exn:fail?
|
|
(λ (exception)
|
|
(close-input-port input)
|
|
(safe-delete-file target)
|
|
(raise exception))))
|
|
(call-with-output-file
|
|
target
|
|
(λ (output) (copy-port input output))
|
|
#:exists 'truncate/replace)
|
|
(close-input-port input)
|
|
target)))
|
|
|
|
;;; Selects the stable cache key carried by a playback command.
|
|
(define (command-cache-key data)
|
|
(hash-ref data 'cacheKey (hash-ref data 'mediaToken)))
|
|
|
|
;;; Returns cached media or downloads and records it when absent.
|
|
(define (ensure-media-cached! data)
|
|
(let* ((key (command-cache-key data))
|
|
(found (hash-ref cached-media key #f)))
|
|
(if (and found (file-exists? found))
|
|
found
|
|
(let ((downloaded
|
|
(download-media!
|
|
(hash-ref data 'mediaToken)
|
|
(hash-ref data 'filename "track"))))
|
|
(hash-set! cached-media key downloaded)
|
|
downloaded))))
|
|
|
|
;;; Removes every cached media file except the entry identified by keep-key.
|
|
(define (discard-unused-media! keep-key)
|
|
(let loop ((remaining (hash->list cached-media)))
|
|
(unless (null? remaining)
|
|
(let ((entry (car remaining)))
|
|
(unless (equal? (car entry) keep-key)
|
|
(safe-delete-file (cdr entry))
|
|
(hash-remove! cached-media (car entry))))
|
|
(loop (cdr remaining)))))
|
|
|
|
;;; Continues with prefetched media when the current decoder reaches EOF.
|
|
;;; Decoder EOF precedes audible EOF, so audio-play! queues behind the buffer.
|
|
(define (advance-at-decoder-eof! handle)
|
|
(let ((prepared
|
|
(with-agent-state
|
|
(λ ()
|
|
(let ((value prefetched-track))
|
|
(set! prefetched-track #f)
|
|
value)))))
|
|
(cond
|
|
(prepared
|
|
(let* ((data (car prepared))
|
|
(path (cdr prepared))
|
|
(key (command-cache-key data)))
|
|
(with-handlers
|
|
((exn:fail?
|
|
(λ (exception)
|
|
(warn-player-agent "Could not start prefetched track: ~a"
|
|
(exn-message exception))
|
|
(set-agent-error! (exn-message exception))
|
|
(with-agent-state
|
|
(λ () (set! ended-counter (+ ended-counter 1)))))))
|
|
(let ((music-id (audio-play! handle path)))
|
|
(info-player-agent "Queued prefetched track ~a as music id ~a"
|
|
(hash-ref data 'filename "track")
|
|
music-id)
|
|
(set! current-media-key key)
|
|
(discard-unused-media! key)
|
|
(with-agent-state
|
|
(λ ()
|
|
(hash-set! music-tracks music-id data)
|
|
(set! auto-started-key key)
|
|
(set! pending-auto-music-id music-id)))))))
|
|
(else
|
|
(warn-player-agent
|
|
"Decoder reached EOF before the next track was prefetched")
|
|
(with-agent-state
|
|
(λ () (set! ended-counter (+ ended-counter 1))))))))
|
|
|
|
;;; Applies one server command to audio, cache and reported agent state.
|
|
;;; Play and prefetch commands also maintain gapless track bookkeeping.
|
|
(define (execute-command! command)
|
|
(let ((action (hash-ref command 'action ""))
|
|
(data (hash-ref command 'data (hasheq))))
|
|
(info-player-agent "Executing command ~a" action)
|
|
(cond
|
|
((string=? action "play")
|
|
(let* ((next-key (command-cache-key data))
|
|
(already-started?
|
|
(with-agent-state
|
|
(λ ()
|
|
(let ((matches?
|
|
(and auto-started-key
|
|
(equal? auto-started-key next-key))))
|
|
(when matches?
|
|
(set! auto-started-key #f))
|
|
matches?)))))
|
|
(with-agent-state
|
|
(λ () (set! current-track-value data)))
|
|
(unless already-started?
|
|
(with-agent-state
|
|
(λ ()
|
|
(set! prefetched-track #f)
|
|
(set! auto-started-key #f)
|
|
(set! pending-auto-music-id #f)
|
|
(set! agent-state
|
|
(hash-set
|
|
(hash-set agent-state 'state "starting")
|
|
'error 'null))))
|
|
(let* ((next-media (ensure-media-cached! data))
|
|
;; audio-play! interrupts and closes the previous decoder.
|
|
(music-id (audio-play! (ensure-audio!) next-media)))
|
|
(with-agent-state
|
|
(λ ()
|
|
(hash-clear! music-tracks)
|
|
(hash-set! music-tracks music-id data)))
|
|
(set! current-media-key next-key)
|
|
(discard-unused-media! next-key)))))
|
|
((string=? action "prefetch")
|
|
(let ((key (command-cache-key data))
|
|
(path (ensure-media-cached! data)))
|
|
(with-agent-state
|
|
(λ () (set! prefetched-track (cons data path))))
|
|
(info-player-agent "Prefetched ~a"
|
|
(hash-ref data 'filename "track"))
|
|
(let loop ((remaining (hash->list cached-media)))
|
|
(unless (null? remaining)
|
|
(let ((entry (car remaining)))
|
|
(unless (or (equal? (car entry) current-media-key)
|
|
(equal? (car entry) key))
|
|
(safe-delete-file (cdr entry))
|
|
(hash-remove! cached-media (car entry))))
|
|
(loop (cdr remaining))))))
|
|
((string=? action "pause")
|
|
(audio-pause! (ensure-audio!) #t))
|
|
((string=? action "resume")
|
|
(audio-pause! (ensure-audio!) #f))
|
|
((string=? action "stop")
|
|
(with-agent-state
|
|
(λ ()
|
|
(set! prefetched-track #f)
|
|
(set! auto-started-key #f)
|
|
(set! pending-auto-music-id #f)))
|
|
(when audio
|
|
(audio-stop! audio)))
|
|
((string=? action "seek")
|
|
(audio-seek! (ensure-audio!) (hash-ref data 'percentage 0)))
|
|
((string=? action "volume")
|
|
(set! logical-volume (min 100 (max 0 (hash-ref data 'value 50))))
|
|
(let ((scaled (/ logical-volume 100.0)))
|
|
(audio-volume! (ensure-audio!) (* 100.0 scaled scaled)))
|
|
(with-agent-state
|
|
(λ ()
|
|
(set! agent-state
|
|
(hash-set agent-state 'volume logical-volume)))))
|
|
(else
|
|
(error 'player-agent "unknown command: ~a" action)))))
|
|
|
|
;;; Registers the agent and repeatedly exchanges state for server commands.
|
|
;;; Connection and authorization failures are reported before a delayed retry.
|
|
(define (poll-loop)
|
|
(with-handlers
|
|
((exn:fail:agent-denied?
|
|
(λ (exception)
|
|
(let ((message (format (tr 'denied-message) app-id)))
|
|
(warn-player-agent "Agent authorization refused: ~a"
|
|
(exn-message exception))
|
|
(set-agent-error! message)
|
|
(status-callback
|
|
(tr 'unauthorized-status))
|
|
(unless authorization-notified?
|
|
(set! authorization-notified? #t)
|
|
(denied-callback message))
|
|
(when running
|
|
(sleep 3)
|
|
(poll-loop)))))
|
|
(exn:fail?
|
|
(λ (exception)
|
|
(warn-player-agent "Connection cycle failed: ~a"
|
|
(exn-message exception))
|
|
(set-agent-error! (exn-message exception))
|
|
(status-callback
|
|
(format (tr 'disconnected) (exn-message exception)))
|
|
(when running
|
|
(sleep 3)
|
|
(poll-loop)))))
|
|
(post-json server-url
|
|
"/api/agent/register"
|
|
(hasheq 'appId app-id 'name assigned-name))
|
|
(clear-agent-error!)
|
|
(status-callback (tr 'connected))
|
|
(info-player-agent "Registered at ~a as ~a" server-url assigned-name)
|
|
(let loop ()
|
|
(when running
|
|
(let* ((response
|
|
(post-json
|
|
server-url
|
|
"/api/agent/poll"
|
|
(hasheq 'appId app-id
|
|
'name assigned-name
|
|
'ack acknowledged-command
|
|
'endedCounter ended-counter
|
|
'state (snapshot))))
|
|
(command (hash-ref response 'command 'null)))
|
|
(when (and (hash? command)
|
|
(> (hash-ref command 'id 0) acknowledged-command)
|
|
(not (= (hash-ref command 'id 0)
|
|
executing-command-id)))
|
|
(set! executing-command-id (hash-ref command 'id))
|
|
(set! command-worker
|
|
(thread
|
|
(λ ()
|
|
(with-handlers
|
|
((exn:fail?
|
|
(λ (exception)
|
|
(warn-player-agent "Command failed: ~a"
|
|
(exn-message exception))
|
|
(set-agent-error! (exn-message exception)))))
|
|
(clear-agent-error!)
|
|
(execute-command! command))
|
|
(set! acknowledged-command (hash-ref command 'id))
|
|
(set! executing-command-id 0)
|
|
(set! command-worker #f))))))
|
|
(sleep 1)
|
|
(loop)))))
|
|
|
|
;;; Starts the polling worker once and reports the connecting state.
|
|
(define (start!)
|
|
(unless running
|
|
(set! running #t)
|
|
(status-callback (tr 'connecting))
|
|
(set! worker (thread poll-loop))))
|
|
|
|
;;; Stops polling and command workers and clears their lifecycle state.
|
|
(define (stop!)
|
|
(set! running #f)
|
|
(when (and worker (not (thread-dead? worker)))
|
|
(kill-thread worker))
|
|
(when (and command-worker (not (thread-dead? command-worker)))
|
|
(kill-thread command-worker))
|
|
(set! worker #f)
|
|
(set! command-worker #f)
|
|
(set! executing-command-id 0))
|
|
|
|
;;; Restarts the runtime with a new normalized server address and name.
|
|
(define (reconnect! new-server-url new-name)
|
|
(stop!)
|
|
(set! authorization-notified? #f)
|
|
(set! server-url (string-trim new-server-url))
|
|
(set! assigned-name (string-trim new-name))
|
|
(start!))
|
|
|
|
;;; Stops the runtime, closes audio and removes all cached media files.
|
|
(define (shutdown!)
|
|
(stop!)
|
|
(when audio
|
|
(with-handlers ((exn:fail? void))
|
|
(audio-quit! audio))
|
|
(set! audio #f))
|
|
(let loop ((paths (hash-values cached-media)))
|
|
(unless (null? paths)
|
|
(safe-delete-file (car paths))
|
|
(loop (cdr paths))))
|
|
(hash-clear! cached-media))
|
|
|
|
(player-agent-runtime start!
|
|
reconnect!
|
|
shutdown!
|
|
snapshot
|
|
current-track
|
|
(λ () running)
|
|
app-id)))
|
|
|
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
;; Tests for module player-agent-core.rkt
|
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
|
|
(module+ test
|
|
(require rackunit)
|
|
|
|
(check-equal? (normal-state 'initialized) "stopped")
|
|
(check-equal? (normal-state 'transitioning) "starting")
|
|
(check-equal? (normal-state 'playing) "playing")
|
|
|
|
(let* ((app-id (make-string 64 #\a))
|
|
(runtime
|
|
(make-player-agent-runtime "http://127.0.0.1:1234"
|
|
"Test agent"
|
|
app-id)))
|
|
(check-false ((player-agent-runtime-running? runtime)))
|
|
(check-false ((player-agent-runtime-current-track runtime)))
|
|
(check-equal?
|
|
(hash-ref ((player-agent-runtime-snapshot runtime)) 'state)
|
|
"stopped")
|
|
(check-equal? (player-agent-runtime-app-id runtime) app-id)))
|