Disabled query on exit for emus process.
[emus.git] / emus.el
1 ;;; emus.el --- Simple mp3 player  -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2019 Tim Vaughan
4
5 ;; Author: Tim Vaughan <timv@ughan.xyz>
6 ;; Created: 12 December 2019
7 ;; Version: 1.0
8 ;; Keywords: multimedia
9 ;; Homepage: http://thelambdalab.xy/emus
10 ;; Package-Requires: ((emacs "26"))
11
12 ;; This file is not part of GNU Emacs.
13
14 ;; This program is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; This program is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with this file.  If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;; This is a simple package for playing audio from a local directory
30 ;; tree of mp3 files.  It uses the program mpg123 as its back-end.
31 ;; Currently the library is loaded completely every time emus starts.
32
33 ;;; Code:
34
35 (provide 'emus)
36
37
38 ;;; Dependencies
39 ;;
40
41 (require 'seq)
42
43
44 ;;; Global constants
45 ;;
46
47 (defconst emus-version "1.0.0"
48   "Current version of emus.")
49
50
51 ;;; Customizations
52 ;;
53
54 (defgroup emus nil
55   "Simple music player for Emacs."
56   :group 'multimedia)
57
58 (defcustom emus-directory "~/Music/"
59   "Directory containing audio files for emus."
60   :type '(string))
61
62 (defcustom emus-mpg123-program "mpg123"
63   "Name of (and, optionally, path to) mpg123 binary."
64   :type '(string))
65
66 (defface emus-artist
67   '((t :inherit font-lock-keyword-face :background "#333"))
68   "Face used for artist names in browser.")
69
70 (defface emus-album
71   '((t :inherit font-lock-function-name-face :background "#222"))
72   "Face used for album names in browser.")
73
74 (defface emus-track
75   '((t :inherit font-lock-string-face))
76   "Face used for track titles in browser.")
77
78 (defface emus-track-current
79   '((t :inherit font-lock-string-face :inverse-video t))
80   "Face used for track titles in browser.")
81
82 (defface emus-cursor
83   '((t :inherit bold))
84   "Face used for current track cursor")
85
86 ;;; Library
87 ;;
88
89 (defun emus-get-audio-files ()
90   "Get all mp3 files in main emus directory."
91   (directory-files-recursively emus-directory ".*\\.mp3"))
92
93 (defvar emus-records nil
94   "Emus audio library.")
95
96 (defun emus-make-record (artist album title filename &optional pos)
97   (vector artist album title filename pos))
98
99 (defun emus-record-artist (record)
100   (elt record 0))
101
102 (defun emus-record-album (record)
103   (elt record 1))
104
105 (defun emus-record-title (record)
106   (elt record 2))
107
108 (defun emus-record-file (record)
109   (elt record 3))
110
111 (defun emus-record-browser-pos (record)
112   (elt record 4))
113
114 (defun emus-set-record-browser-pos (record pos)
115   (aset record 4 pos))
116
117 (defun emus--load-library (then)
118   (emus--suspend-cp)
119   (setq emus-state 'stopped)
120   (let ((proc (emus-get-process))
121         (tagstr "")
122         (filenames (emus-get-audio-files)))
123     (setq emus-records nil)
124     (set-process-filter proc (lambda (proc string)
125                                (setq tagstr (concat tagstr string))
126                                (when (string-suffix-p "@P 1\n" string)
127                                  (add-to-list 'emus-records
128                                               (emus--make-record-from-tagstr (car filenames)
129                                                                              tagstr))
130                                  (setq tagstr "")
131                                  (setq filenames (cdr filenames))
132                                  (if filenames
133                                      (emus-send-cmd "lp" (car filenames))
134                                    (set-process-filter proc nil)
135                                    (setq emus-records (reverse emus-records))
136                                    (emus--sort-records)
137                                    (unless emus-current-record
138                                      (setq emus-current-record (car emus-records)))
139                                    (funcall then)
140                                    ;; (emus-render-records)
141                                    (emus--resume-cp)))))
142     (emus-send-cmd "lp" (car filenames))))
143
144 (defun emus--make-record-from-tagstr (filename tagstr)
145   (let ((artist "")
146         (album "")
147         (title ""))
148     (dolist (line (split-string tagstr "\n"))
149       (let ((found-artist (elt (split-string line "@I ID3v2.artist:") 1))
150             (found-album (elt (split-string line "@I ID3v2.album:") 1))
151             (found-title (elt (split-string line "@I ID3v2.title:") 1)))
152         (cond
153          (found-artist (setq artist found-artist))
154          (found-album (setq album found-album))
155          (found-title (setq title found-title)))))
156     (emus-make-record artist album title filename nil)))
157
158 (defun emus--sort-records ()
159   (sort emus-records
160         (lambda (r1 r2)
161           (let ((artist1 (emus-record-artist r1))
162                 (artist2 (emus-record-artist r2)))
163             (if (string= artist1 artist2)
164                 (let ((album1 (emus-record-album r1))
165                       (album2 (emus-record-album r2)))
166                   (string< album1 album2))
167               (string< artist1 artist2))))))
168
169 (defmacro emus--with-library (&rest args)
170   `(if emus-records
171        (progn ,@args)
172      (emus--load-library
173       (lambda () ,@args))))
174
175 ;;; mpg123 process
176 ;;
177
178 (defvar emus-proc-in-use nil)
179
180 (defun emus-get-process ()
181   "Return current or new mpg123 process."
182   (let* ((emus-process-raw (get-process "emus-process"))
183          (emus-process (if emus-process-raw
184                            (if (process-live-p emus-process-raw)
185                                emus-process-raw
186                              (kill-process emus-process-raw)
187                              nil))))
188     (if emus-process
189         emus-process
190       (let ((proc
191              (make-process :name "emus-process"
192                            ;; :buffer (get-buffer-create "*emus-process*")
193                            :command `(,emus-mpg123-program "-R"))))
194         (set-process-query-on-exit-flag proc nil)
195         (process-send-string proc "silence\n")
196         proc))))
197                     
198
199 (defun emus-send-cmd (cmd &rest args)
200   (process-send-string (emus-get-process)
201                        (concat
202                         (seq-reduce (lambda (s1 s2) (concat s1 " " s2)) args cmd)
203                         "\n")))
204
205 (defun emus-send-and-process (respfun predfun cmd &rest args)
206   (let ((respstr ""))
207     (set-process-filter (emus-get-process)
208                         (lambda (proc string)
209                           (setq respstr (concat respstr string))
210                           (when (funcall predfun respstr)
211                             (set-process-filter proc nil)
212                             (funcall respfun respstr))))
213     (apply #'emus-send-cmd cmd args)))
214
215
216 ;;; Playback
217 ;;
218
219 (defvar emus-current-record nil)
220 (defvar emus-state 'stopped)
221 (defvar emus-continuous-playback t)
222
223 (defun emus--suspend-cp ()
224   (setq emus-continuous-playback nil))
225
226 (defun emus--resume-cp ()
227   (setq emus-continuous-playback t)
228   (set-process-filter (emus-get-process)
229                       (lambda (proc string)
230                         (and emus-continuous-playback
231                              (eq emus-state 'playing)
232                              (string-suffix-p "@P 0\n" string)
233                              (emus-play-next)))))
234
235 (defun emus-play-record (record)
236   "Set RECORD as current and start playing."
237   (emus--with-library
238    (let ((old-record emus-current-record))
239      (emus-send-cmd "l" (emus-record-file record))
240      (setq emus-state 'playing)
241      (setq emus-current-record record)
242      (emus--update-record old-record)
243      (emus--update-record record)
244      (emus--resume-cp))))
245
246 (defun emus-select-record (record)
247   "Set RECORD as current, but do not start playing."
248   (emus--with-library
249    (let ((old-record emus-current-record))
250      (setq emus-state 'stopped)
251      (setq emus-current-record record)
252      (emus--update-record old-record)
253      (emus--update-record record)
254      (emus-send-cmd "o")
255      (emus--resume-cp))))
256
257 (defun emus-stop ()
258   "Stop playback of the current record."
259   (interactive)
260   (emus--with-library
261    (setq emus-state 'stopped)
262    (emus--update-record emus-current-record)
263    (emus-send-cmd "s")))
264
265 (defun emus-playpause ()
266   (interactive)
267   (emus--with-library
268    (when emus-current-record
269      (if (eq emus-state 'stopped)
270          (emus-play-record emus-current-record)
271        (emus-send-cmd "p")
272        (pcase emus-state
273          ((or 'paused 'stopped) (setq emus-state 'playing))
274          ('playing (setq emus-state 'paused)))
275        (unless (eq emus-state 'paused)))
276      (emus--update-record emus-current-record))))
277
278 (defvar emus-current-volume 100)
279
280 (defun emus-set-volume (pct)
281   (emus--with-library
282    (setq emus-current-volume pct)
283    (emus-send-cmd "v" (number-to-string pct))))
284
285 (defun emus-volume-increase-by (delta)
286   (emus-set-volume (max 0 (min 100 (+ emus-current-volume delta)))))
287
288 (defun emus-volume-up ()
289   (interactive)
290   (emus-volume-increase-by 10))
291
292 (defun emus-volume-down ()
293   (interactive)
294   (emus-volume-increase-by -10))
295
296 (defun emus-play-nearby (offset)
297   (let ((idx (seq-position emus-records emus-current-record)))
298     (if idx
299         (let ((next-record (elt emus-records (+ idx offset))))
300           (if next-record
301               (if (eq emus-state 'playing)
302                   (emus-play-record next-record)
303                 (emus-select-record next-record))
304             (error "Track does not exist")))
305       (error "No track is currently selected"))))
306
307 (defun emus-play-next ()
308   (interactive)
309   (emus-play-nearby 1))
310
311 (defun emus-play-prev ()
312   (interactive)
313   (emus-play-nearby -1))
314
315 (defun emus-display-status ()
316   (interactive)
317   (emus--with-library
318    (message
319     (concat "Emus: Volume %d%%"
320             (pcase emus-state
321               ('stopped " [Stopped]")
322               ('paused " [Paused]")
323               ('playing " [Playing]")
324               (_ ""))
325             (if emus-current-record
326                 (format " - %.30s (%.20s)"
327                         (emus-record-title emus-current-record)
328                         (emus-record-artist emus-current-record))
329               ""))
330     emus-current-volume)))
331
332
333 ;;; Browser
334 ;;
335
336 (defun emus--insert-record (record &optional prev-record first)
337   (let* ((artist (emus-record-artist record))
338          (album (emus-record-album record))
339          (title (emus-record-title record))
340          (help-str (format "mouse-1, RET: Play '%.30s' (%.20s)" title artist)))
341     (when (or prev-record first)
342       (unless (equal (emus-record-artist prev-record) artist)
343         (insert-text-button
344          (propertize artist 'face 'emus-artist)
345          'action #'emus--click-record
346          'follow-link t
347          'help-echo help-str
348          'emus-record record)
349         (insert (propertize "\n" 'face 'emus-artist)))
350       (unless (equal (emus-record-album prev-record) album)
351         (insert-text-button
352          (propertize (concat "  " album) 'face 'emus-album)
353          'action #'emus--click-record
354          'follow-link t
355          'help-echo help-str
356          'emus-record record)
357         (insert (propertize "\n" 'face 'emus-album))))
358     (emus-set-record-browser-pos record (point))
359     (let ((is-current (equal record emus-current-record)))
360       (insert-text-button
361        (concat
362         (if is-current
363             (propertize
364              (pcase emus-state
365                ('playing "->")
366                ('paused "-)")
367                ('stopped "-]"))
368              'face 'emus-cursor)
369           (propertize "  " 'face 'default))
370         (propertize (format "   %s" title)
371                     'face (if is-current
372                               'emus-track-current
373                             'emus-track)))
374        'action #'emus--click-record
375        'follow-link t
376        'help-echo help-str
377        'emus-record record)
378       (insert (propertize "\n"
379                           'face (if is-current
380                                     'emus-track-current
381                                   'emus-track))))))
382
383 (defun emus--update-record (record)
384   (let ((record-pos (emus-record-browser-pos record)))
385     (when (and (get-buffer "*emus*")
386                (emus-record-browser-pos record))
387       (with-current-buffer "*emus*"
388         (let ((inhibit-read-only t)
389               (old-point (point)))
390             (goto-char record-pos)
391             (search-forward "\n")
392             (delete-region record-pos (point))
393             (goto-char record-pos)
394             (emus--insert-record record)
395             (goto-char old-point))))))
396
397 (defun emus--render-records ()
398   (with-current-buffer "*emus*"
399     (let ((inhibit-read-only t)
400           (old-pos (point)))
401       (erase-buffer)
402       (goto-char (point-min))
403       (let ((prev-record nil))
404         (dolist (record emus-records)
405           (emus--insert-record record prev-record (not prev-record))
406           (setq prev-record record)))
407       (goto-char old-pos))))
408
409 (defun emus--click-record (button)
410   (emus-play-record (button-get button 'emus-record))
411   (emus-display-status))
412
413 (defun emus-centre-current ()
414   (interactive)
415   (when (get-buffer "*emus*")
416     (switch-to-buffer "*emus*")
417     (when emus-current-record
418       (goto-char (emus-record-browser-pos emus-current-record))
419       (recenter))))
420
421 (defun emus-browse ()
422   "Switch to *emus* audio library browser."
423   (interactive)
424   (emus--with-library
425    (switch-to-buffer "*emus*")
426    (emus-browser-mode)
427    (emus--render-records)
428    (emus-centre-current)))
429
430 (defun emus-refresh ()
431   (interactive)
432   (emus-stop)
433   (setq emus-records nil)
434   (emus-browse))
435
436 (defun emus-playpause-status () (interactive) (emus-playpause) (emus-display-status))
437 (defun emus-stop-status () (interactive) (emus-stop) (emus-display-status))
438 (defun emus-volume-up-status () (interactive) (emus-volume-up) (emus-display-status))
439 (defun emus-volume-down-status () (interactive) (emus-volume-down) (emus-display-status))
440 (defun emus-refresh-status () (interactive) (emus-refresh) (emus-display-status))
441 (defun emus-play-next-status () (interactive) (emus-play-next) (emus-display-status))
442 (defun emus-play-prev-status () (interactive) (emus-play-prev) (emus-display-status))
443 (defun emus-centre-current-status () (interactive) (emus-centre-current) (emus-display-status))
444
445 (defvar emus-browser-mode-map
446   (let ((map (make-sparse-keymap)))
447     (define-key map (kbd "SPC") 'emus-playpause-status)
448     (define-key map (kbd "o") 'emus-stop-status)
449     (define-key map (kbd "+") 'emus-volume-up-status)
450     (define-key map (kbd "=") 'emus-volume-up-status)
451     (define-key map (kbd "-") 'emus-volume-down-status)
452     (define-key map (kbd "R") 'emus-refresh-status)
453     (define-key map (kbd "n") 'emus-play-next-status)
454     (define-key map (kbd "p") 'emus-play-prev-status)
455     (define-key map (kbd "c") 'emus-centre-current-status)
456     (when (fboundp 'evil-define-key*)
457       (evil-define-key* 'motion map
458         (kbd "SPC") 'emus-playpause-status
459         (kbd "o") 'emus-stop-status
460         (kbd "+") 'emus-volume-up-status
461         (kbd "=") 'emus-volume-up-status
462         (kbd "-") 'emus-volume-down-status
463         (kbd "R") 'emus-refresh-status
464         (kbd "n") 'emus-play-next-status
465         (kbd "p") 'emus-play-prev-status
466         (kbd "c") 'emus-centre-current-status))
467     map)
468   "Keymap for emus.")
469
470 (define-derived-mode emus-browser-mode special-mode "emus-browser"
471   "Major mode for EMUS music player.")
472
473 (when (fboundp 'evil-set-initial-state)
474   (evil-set-initial-state 'emus-browser-mode 'motion))
475
476 ;;; emus.el ends here