Cleaning up browser.
[emus.git] / emus.el
1 ;;; emus.el --- Simple music player for Emacs.  -*- lexical-binding:t -*-
2
3 ;; Author: Tim Vaughan <timv@ughan.xyz>
4 ;; Version: 1.0
5 ;; Keywords: multimedia
6 ;; URL: https://thelambdalab.xyz/emus
7
8 ;;; Commentary:
9
10 ;; This is a simple package for playing audio from a local library
11 ;; of audio files.
12
13 ;;; Code:
14
15 ;;; Customizations
16 ;;
17
18 (defgroup emus nil
19   "Simple music player for Emacs."
20   :group 'multimedia)
21
22 (defcustom emus-directory "~/Music/"
23   "Directory containing audio files for emus."
24   :type '(string))
25
26 (defcustom emus-mpg123-program "mpg123"
27   "Name of (and, optionally, path to) mpg123 binary."
28   :type '(string))
29
30 (defface emus-artist
31   '((t :inherit font-lock-keyword-face))
32   "Face used for artist names in browser.")
33
34 (defface emus-album
35   '((t :inherit font-lock-function-name-face))
36   "Face used for album names in browser.")
37
38 (defface emus-title
39   '((t :inherit font-lock-string-face))
40   "Face used for track titles in browser.")
41
42 ;;; Library
43 ;;
44
45 (defun emus-get-audio-files ()
46   "Get all mp3 files in main emus directory."
47   (directory-files-recursively emus-directory ".*\\.mp3"))
48
49 (defvar emus-records nil
50   "Emus audio library.")
51
52 (defun emus-make-record (filename tagstr)
53   (let ((artist "")
54         (album "")
55         (title ""))
56     (dolist (line (split-string tagstr "\n"))
57       (let ((found-artist (elt (split-string line "@I ID3v2.artist:") 1))
58             (found-album (elt (split-string line "@I ID3v2.album:") 1))
59             (found-title (elt (split-string line "@I ID3v2.title:") 1)))
60         (cond
61          (found-artist (setq artist found-artist))
62          (found-album (setq album found-album))
63          (found-title (setq title found-title)))))
64     (vector artist album title filename nil)))
65
66 (defun emus-record-artist (record)
67   (elt record 0))
68
69 (defun emus-record-album (record)
70   (elt record 1))
71
72 (defun emus-record-title (record)
73   (elt record 2))
74
75 (defun emus-record-file (record)
76   (elt record 3))
77
78 (defun emus-record-browser-pos (record)
79   (elt record 4))
80
81 (defun emus-set-record-browser-pos (record pos)
82   (aset record 4 pos))
83
84 (defun emus-update-records ()
85   (interactive)
86   (emus--suspend-cp)
87   (setq emus-state 'stopped)
88   (let ((proc (emus-get-process))
89         (tagstr "")
90         (filenames (emus-get-audio-files)))
91     (setq emus-records nil)
92     (set-process-filter proc (lambda (proc string)
93                                (setq tagstr (concat tagstr string))
94                                (when (string-suffix-p "@P 1\n" string)
95                                  (add-to-list 'emus-records
96                                               (emus-make-record (car filenames)
97                                                                 tagstr))
98                                  (setq tagstr "")
99                                  (setq filenames (cdr filenames))
100                                  (if filenames
101                                      (emus-send-cmd "lp" (car filenames))
102                                    (set-process-filter proc nil)
103                                    (setq emus-records (reverse emus-records))
104                                    (emus-sort-records)
105                                    (emus-render-records)
106                                    (emus--resume-cp)))))
107     (emus-send-cmd "lp" (car filenames))))
108
109 (defun emus-sort-records ()
110   (sort emus-records
111         (lambda (r1 r2)
112           (let ((artist1 (emus-record-artist r1))
113                 (artist2 (emus-record-artist r2)))
114             (if (string= artist1 artist2)
115                 (let ((album1 (emus-record-album r1))
116                       (album2 (emus-record-album r2)))
117                   (string< album1 album2))
118               (string< artist1 artist2))))))        
119
120 ;;; mpg123 process
121 ;;
122
123 (defvar emus-proc-in-use nil)
124
125 (defun emus-get-process ()
126   "Return current or new mpg123 process."
127   (let* ((emus-process-raw (get-process "emus-process"))
128          (emus-process (if emus-process-raw
129                            (if (process-live-p emus-process-raw)
130                                emus-process-raw
131                              (kill-process emus-process-raw)
132                              nil))))
133     (if emus-process
134         emus-process
135       (let ((proc
136              (make-process :name "emus-process"
137                            ;; :buffer (get-buffer-create "*emus-process*")
138                            :command `(,emus-mpg123-program "-R"))))
139         (process-send-string proc "silence\n")
140         proc))))
141                     
142
143 (defun emus-send-cmd (cmd &rest args)
144   (process-send-string (emus-get-process)
145                        (concat
146                         (seq-reduce (lambda (s1 s2) (concat s1 " " s2)) args cmd)
147                         "\n")))
148
149 (defun emus-send-and-process (respfun predfun cmd &rest args)
150   (let ((respstr ""))
151     (set-process-filter (emus-get-process)
152                         (lambda (proc string)
153                           (setq respstr (concat respstr string))
154                           (when (funcall predfun respstr)
155                             (set-process-filter proc nil)
156                             (funcall respfun respstr))))
157     (apply #'emus-send-cmd cmd args)))
158
159
160 ;;; Playback
161 ;;
162
163 (defvar emus-current-record nil)
164 (defvar emus-state 'stopped)
165 (defvar emus-continuous-playback t)
166
167 (defun emus--suspend-cp ()
168   (setq emus-continuous-playback nil))
169
170 (defun emus--resume-cp ()
171   (setq emus-continuous-playback t)
172   (set-process-filter (emus-get-process)
173                       (lambda (proc string)
174                         (and emus-continuous-playback
175                              (eq emus-state 'playing)
176                              (string-suffix-p "@P 0\n" string)
177                              (emus-play-next)))))
178
179 (defun emus-play-record (record)
180   (let ((old-record emus-current-record))
181     (emus-send-cmd "l" (emus-record-file record))
182     (setq emus-state 'playing)
183     (setq emus-current-record record)
184     (emus-update-record old-record)
185     (emus-update-record record)
186     (emus--resume-cp)))
187
188 (defun emus-stop ()
189   (interactive)
190   (setq emus-state 'stopped)
191   (emus-update-record emus-current-record)
192   (emus-send-cmd "s"))
193
194 (defun emus-playpause ()
195   (interactive)
196   (when emus-current-record
197     (if (eq emus-state 'stopped)
198         (emus-play-record emus-current-record)
199       (emus-send-cmd "p")
200       (pcase emus-state
201         ((or 'paused 'stopped) (setq emus-state 'playing))
202         ('playing (setq emus-state 'paused)))
203       (unless (eq emus-state 'paused)))
204     (emus-update-record emus-current-record)))
205
206 (defun emus-set-volume (pct)
207   (emus-send-cmd "v" (number-to-string pct)))
208
209 (defvar emus-current-volume 100)
210
211 (defun emus-volume-delta (delta)
212   (setq emus-current-volume (max 0 (min 100 (+ emus-current-volume delta))))
213   (emus-set-volume emus-current-volume))
214
215 (defun emus-volume-up ()
216   (interactive)
217   (emus-volume-delta 10))
218
219 (defun emus-volume-down ()
220   (interactive)
221   (emus-volume-delta -10))
222
223 (defun emus--play-nearby (offset)
224   (let ((idx (seq-position emus-records emus-current-record)))
225     (if idx
226         (let ((next-record (elt emus-records (+ idx offset))))
227           (if next-record
228               (emus-play-record next-record)
229             (error "Track does not exist")))
230       (error "No track is currently selected."))))
231
232 (defun emus-play-next ()
233   (interactive)
234   (emus--play-nearby 1))
235
236 (defun emus-play-prev ()
237   (interactive)
238   (emus--play-nearby -1))
239
240 (defun emus-display-status ()
241   (interactive)
242   (message
243    (concat "Emus: Volume %d%%"
244            (pcase emus-state
245              ('stopped " [Stopped]")
246              ('paused " [Paused]")
247              ('playing " [Playing]")
248              (_ ""))
249            (if emus-current-record
250                (format " - %.30s (%.20s)"
251                        (emus-record-title emus-current-record)
252                        (emus-record-artist emus-current-record))
253              ""))
254    emus-current-volume))
255
256
257 ;;; Browser
258 ;;
259
260 (defun emus-insert-record (record &optional prev-record first)
261   (let ((artist (emus-record-artist record))
262         (album (emus-record-album record))
263         (title (emus-record-title record)))
264     (when (or prev-record first)
265       (unless (equal (emus-record-artist prev-record) artist)
266         (insert-text-button
267          (propertize artist 'face 'emus-artist)
268          'action #'emus-click-record
269          'follow-link t
270          'emus-record record)
271         (insert "\n"))
272       (unless (equal (emus-record-album prev-record) album)
273         (insert-text-button
274          (propertize (concat "  " album) 'face 'emus-album)
275          'action #'emus-click-record
276          'follow-link t
277          'emus-record record)
278         (insert "\n")))
279     (emus-set-record-browser-pos record (point))
280     (let ((is-current (equal record emus-current-record)))
281       (insert-text-button
282        (concat
283         (if is-current
284             (pcase emus-state
285               ('playing (propertize ">" 'face 'bold))
286               ('paused (propertize ")" 'face 'bold))
287               ('stopped (propertize "]" 'face 'bold)))
288           (propertize " " 'face 'default))
289         (propertize (format "    %s" title)
290                     'face 'emus-title))
291        'action #'emus-click-record
292        'follow-link t
293        'emus-record record)))
294   (insert "\n"))
295
296 (defun emus-update-record (record)
297   (let ((record-pos (emus-record-browser-pos record)))
298     (when (and (get-buffer "*emus*")
299                (emus-record-browser-pos record))
300       (with-current-buffer "*emus*"
301         (let ((inhibit-read-only t)
302               (old-point (point)))
303             (goto-char record-pos)
304             (search-forward "\n")
305             (delete-region record-pos (point))
306             (goto-char record-pos)
307             (emus-insert-record record)
308             (goto-char old-point))))))
309
310 (defun emus-render-records ()
311   (save-mark-and-excursion
312     (with-current-buffer "*emus*"
313       (let ((inhibit-read-only t))
314         (erase-buffer)
315         (goto-char (point-min))
316         (let ((prev-record nil))
317           (dolist (record emus-records)
318             (emus-insert-record record prev-record (not prev-record))
319             (setq prev-record record)))))))
320
321 (defun emus-click-record (button)
322   (emus-play-record (button-get button 'emus-record)))
323
324 (defun emus-browse ()
325   "Switch to *emus* audio library browser."
326   (interactive)
327   (switch-to-buffer "*emus*")
328   (emus-browser-mode)
329   (emus-volume emus-current-volume)
330   (if emus-records
331       (emus-render-records)
332     (emus-update-records)))
333
334 (defvar emus-browser-mode-map
335   (let ((map (make-sparse-keymap)))
336     (define-key map (kbd "SPC") 'emus-playpause)
337     (define-key map (kbd "o") 'emus-stop)
338     (define-key map (kbd "+") 'emus-volume-up)
339     (define-key map (kbd "=") 'emus-volume-up)
340     (define-key map (kbd "-") 'emus-volume-down)
341     (define-key map (kbd "R") 'emus-update-records)
342     (define-key map (kbd "n") 'emus-play-next)
343     (define-key map (kbd "p") 'emus-play-prev)
344     (when (fboundp 'evil-define-key*)
345       (evil-define-key* 'motion map
346         (kbd "SPC") 'emus-playpause
347         (kbd "o") 'emus-stop
348         (kbd "+") 'emus-volume-up
349         (kbd "=") 'emus-volume-up
350         (kbd "-") 'emus-volume-down
351         (kbd "R") 'emus-update-records
352         (kbd "n") 'emus-play-next
353         (kbd "p") 'emus-play-prev))
354     map)
355   "Keymap for emus.")
356
357 (define-derived-mode emus-browser-mode special-mode "emus-browser"
358   "Major mode for EMUS music player.")
359
360 (when (fboundp 'evil-set-initial-state)
361   (evil-set-initial-state 'emus-browser-mode 'motion))
362
363 ;;; Debugging
364
365 ;;; emus.el ends here