ad7a5bd22234839deddc9caea3ab141a71e8233f
[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         (process-send-string proc "silence\n")
195         proc))))
196                     
197
198 (defun emus-send-cmd (cmd &rest args)
199   (process-send-string (emus-get-process)
200                        (concat
201                         (seq-reduce (lambda (s1 s2) (concat s1 " " s2)) args cmd)
202                         "\n")))
203
204 (defun emus-send-and-process (respfun predfun cmd &rest args)
205   (let ((respstr ""))
206     (set-process-filter (emus-get-process)
207                         (lambda (proc string)
208                           (setq respstr (concat respstr string))
209                           (when (funcall predfun respstr)
210                             (set-process-filter proc nil)
211                             (funcall respfun respstr))))
212     (apply #'emus-send-cmd cmd args)))
213
214
215 ;;; Playback
216 ;;
217
218 (defvar emus-current-record nil)
219 (defvar emus-state 'stopped)
220 (defvar emus-continuous-playback t)
221
222 (defun emus--suspend-cp ()
223   (setq emus-continuous-playback nil))
224
225 (defun emus--resume-cp ()
226   (setq emus-continuous-playback t)
227   (set-process-filter (emus-get-process)
228                       (lambda (proc string)
229                         (and emus-continuous-playback
230                              (eq emus-state 'playing)
231                              (string-suffix-p "@P 0\n" string)
232                              (emus-play-next)))))
233
234 (defun emus-play-record (record)
235   "Set RECORD as current and start playing."
236   (emus--with-library
237    (let ((old-record emus-current-record))
238      (emus-send-cmd "l" (emus-record-file record))
239      (setq emus-state 'playing)
240      (setq emus-current-record record)
241      (emus--update-record old-record)
242      (emus--update-record record)
243      (emus--resume-cp))))
244
245 (defun emus-select-record (record)
246   "Set RECORD as current, but do not start playing."
247   (emus--with-library
248    (let ((old-record emus-current-record))
249      (setq emus-state 'stopped)
250      (setq emus-current-record record)
251      (emus--update-record old-record)
252      (emus--update-record record)
253      (emus-send-cmd "o")
254      (emus--resume-cp))))
255
256 (defun emus-stop ()
257   "Stop playback of the current record."
258   (interactive)
259   (emus--with-library
260    (setq emus-state 'stopped)
261    (emus--update-record emus-current-record)
262    (emus-send-cmd "s")))
263
264 (defun emus-playpause ()
265   (interactive)
266   (emus--with-library
267    (when emus-current-record
268      (if (eq emus-state 'stopped)
269          (emus-play-record emus-current-record)
270        (emus-send-cmd "p")
271        (pcase emus-state
272          ((or 'paused 'stopped) (setq emus-state 'playing))
273          ('playing (setq emus-state 'paused)))
274        (unless (eq emus-state 'paused)))
275      (emus--update-record emus-current-record))))
276
277 (defvar emus-current-volume 100)
278
279 (defun emus-set-volume (pct)
280   (emus--with-library
281    (setq emus-current-volume pct)
282    (emus-send-cmd "v" (number-to-string pct))))
283
284 (defun emus-volume-increase-by (delta)
285   (emus-set-volume (max 0 (min 100 (+ emus-current-volume delta)))))
286
287 (defun emus-volume-up ()
288   (interactive)
289   (emus-volume-increase-by 10))
290
291 (defun emus-volume-down ()
292   (interactive)
293   (emus-volume-increase-by -10))
294
295 (defun emus-play-nearby (offset)
296   (let ((idx (seq-position emus-records emus-current-record)))
297     (if idx
298         (let ((next-record (elt emus-records (+ idx offset))))
299           (if next-record
300               (if (eq emus-state 'playing)
301                   (emus-play-record next-record)
302                 (emus-select-record next-record))
303             (error "Track does not exist")))
304       (error "No track is currently selected"))))
305
306 (defun emus-play-next ()
307   (interactive)
308   (emus-play-nearby 1))
309
310 (defun emus-play-prev ()
311   (interactive)
312   (emus-play-nearby -1))
313
314 (defun emus-display-status ()
315   (interactive)
316   (emus--with-library
317    (message
318     (concat "Emus: Volume %d%%"
319             (pcase emus-state
320               ('stopped " [Stopped]")
321               ('paused " [Paused]")
322               ('playing " [Playing]")
323               (_ ""))
324             (if emus-current-record
325                 (format " - %.30s (%.20s)"
326                         (emus-record-title emus-current-record)
327                         (emus-record-artist emus-current-record))
328               ""))
329     emus-current-volume)))
330
331
332 ;;; Browser
333 ;;
334
335 (defun emus--insert-record (record &optional prev-record first)
336   (let* ((artist (emus-record-artist record))
337          (album (emus-record-album record))
338          (title (emus-record-title record))
339          (help-str (format "mouse-1, RET: Play '%.30s' (%.20s)" title artist)))
340     (when (or prev-record first)
341       (unless (equal (emus-record-artist prev-record) artist)
342         (insert-text-button
343          (propertize artist 'face 'emus-artist)
344          'action #'emus--click-record
345          'follow-link t
346          'help-echo help-str
347          'emus-record record)
348         (insert (propertize "\n" 'face 'emus-artist)))
349       (unless (equal (emus-record-album prev-record) album)
350         (insert-text-button
351          (propertize (concat "  " album) 'face 'emus-album)
352          'action #'emus--click-record
353          'follow-link t
354          'help-echo help-str
355          'emus-record record)
356         (insert (propertize "\n" 'face 'emus-album))))
357     (emus-set-record-browser-pos record (point))
358     (let ((is-current (equal record emus-current-record)))
359       (insert-text-button
360        (concat
361         (if is-current
362             (propertize
363              (pcase emus-state
364                ('playing "->")
365                ('paused "-)")
366                ('stopped "-]"))
367              'face 'emus-cursor)
368           (propertize "  " 'face 'default))
369         (propertize (format "   %s" title)
370                     'face (if is-current
371                               'emus-track-current
372                             'emus-track)))
373        'action #'emus--click-record
374        'follow-link t
375        'help-echo help-str
376        'emus-record record)
377       (insert (propertize "\n"
378                           'face (if is-current
379                                     'emus-track-current
380                                   'emus-track))))))
381
382 (defun emus--update-record (record)
383   (let ((record-pos (emus-record-browser-pos record)))
384     (when (and (get-buffer "*emus*")
385                (emus-record-browser-pos record))
386       (with-current-buffer "*emus*"
387         (let ((inhibit-read-only t)
388               (old-point (point)))
389             (goto-char record-pos)
390             (search-forward "\n")
391             (delete-region record-pos (point))
392             (goto-char record-pos)
393             (emus--insert-record record)
394             (goto-char old-point))))))
395
396 (defun emus--render-records ()
397   (with-current-buffer "*emus*"
398     (let ((inhibit-read-only t)
399           (old-pos (point)))
400       (erase-buffer)
401       (goto-char (point-min))
402       (let ((prev-record nil))
403         (dolist (record emus-records)
404           (emus--insert-record record prev-record (not prev-record))
405           (setq prev-record record)))
406       (goto-char old-pos))))
407
408 (defun emus--click-record (button)
409   (emus-play-record (button-get button 'emus-record))
410   (emus-display-status))
411
412 (defun emus-centre-current ()
413   (interactive)
414   (when (get-buffer "*emus*")
415     (switch-to-buffer "*emus*")
416     (when emus-current-record
417       (goto-char (emus-record-browser-pos emus-current-record))
418       (recenter))))
419
420 (defun emus-browse ()
421   "Switch to *emus* audio library browser."
422   (interactive)
423   (emus--with-library
424    (switch-to-buffer "*emus*")
425    (emus-browser-mode)
426    (emus--render-records)
427    (emus-centre-current)))
428
429 (defun emus-refresh ()
430   (interactive)
431   (emus-stop)
432   (setq emus-records nil)
433   (emus-browse))
434
435 (defun emus-playpause-status () (interactive) (emus-playpause) (emus-display-status))
436 (defun emus-stop-status () (interactive) (emus-stop) (emus-display-status))
437 (defun emus-volume-up-status () (interactive) (emus-volume-up) (emus-display-status))
438 (defun emus-volume-down-status () (interactive) (emus-volume-down) (emus-display-status))
439 (defun emus-refresh-status () (interactive) (emus-refresh) (emus-display-status))
440 (defun emus-play-next-status () (interactive) (emus-play-next) (emus-display-status))
441 (defun emus-play-prev-status () (interactive) (emus-play-prev) (emus-display-status))
442 (defun emus-centre-current-status () (interactive) (emus-centre-current) (emus-display-status))
443
444 (defvar emus-browser-mode-map
445   (let ((map (make-sparse-keymap)))
446     (define-key map (kbd "SPC") 'emus-playpause-status)
447     (define-key map (kbd "o") 'emus-stop-status)
448     (define-key map (kbd "+") 'emus-volume-up-status)
449     (define-key map (kbd "=") 'emus-volume-up-status)
450     (define-key map (kbd "-") 'emus-volume-down-status)
451     (define-key map (kbd "R") 'emus-refresh-status)
452     (define-key map (kbd "n") 'emus-play-next-status)
453     (define-key map (kbd "p") 'emus-play-prev-status)
454     (define-key map (kbd "c") 'emus-centre-current-status)
455     (when (fboundp 'evil-define-key*)
456       (evil-define-key* 'motion map
457         (kbd "SPC") 'emus-playpause-status
458         (kbd "o") 'emus-stop-status
459         (kbd "+") 'emus-volume-up-status
460         (kbd "=") 'emus-volume-up-status
461         (kbd "-") 'emus-volume-down-status
462         (kbd "R") 'emus-refresh-status
463         (kbd "n") 'emus-play-next-status
464         (kbd "p") 'emus-play-prev-status
465         (kbd "c") 'emus-centre-current-status))
466     map)
467   "Keymap for emus.")
468
469 (define-derived-mode emus-browser-mode special-mode "emus-browser"
470   "Major mode for EMUS music player.")
471
472 (when (fboundp 'evil-set-initial-state)
473   (evil-set-initial-state 'emus-browser-mode 'motion))
474
475 ;;; emus.el ends here