From ba263bd8922aff9656051b526cbe755b57649ff6 Mon Sep 17 00:00:00 2001 From: Hans Dijkema Date: Wed, 22 Apr 2026 15:01:54 +0200 Subject: [PATCH] reuse mp3 ffi handlers --- mp3-decoder.rkt | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/mp3-decoder.rkt b/mp3-decoder.rkt index c776352..2744cd6 100644 --- a/mp3-decoder.rkt +++ b/mp3-decoder.rkt @@ -2,7 +2,9 @@ (require ffi/unsafe "libmpg123-ffi.rkt" - "private/utils.rkt") + "private/utils.rkt" + (prefix-in fin: finalizer) + ) (provide mp3-open mp3-valid? @@ -26,6 +28,13 @@ ;; Functions to do the good stuff ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + (define mp3-handles '()) + + (register-finalizer mp3-handles + (λ (handles) + (for-each (λ (handle) + (handle 'delete)) handles))) + (define (mp3-valid? mp3-file) #t) @@ -43,8 +52,13 @@ (define (mp3-open mp3-file* cb-stream-info cb-audio) (let ((mp3-file (if (path? mp3-file*) (path->string mp3-file*) mp3-file*))) (if (file-exists? mp3-file) - (let ((handler (mpg123-ffi-decoder-handler))) - (handler 'new) + (let ((handler (if (null? mp3-handles) + (let ((h (mpg123-ffi-decoder-handler))) + (h 'new) + h) + (let ((h (car mp3-handles))) + (set! mp3-handles (cdr mp3-handles)) + h)))) (handler 'init mp3-file) (let ((h (make-mp3-handle handler cb-stream-info @@ -81,7 +95,6 @@ (let loop () (if (eq? (mp3-handle-stop handle) #t) (begin - (newline) (dbg-sound "Stopping mp3 decoding") (set-mp3-handle-reading! handle #f) 'stopped-reading @@ -102,7 +115,7 @@ ) )) (ffi-handler 'close) - (ffi-handler 'delete) + (set! mp3-handles (cons ffi-handler mp3-handles)) ) )