Fixed more typos.
[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: 8 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-tracks nil
94   "Emus audio library.")
95
96 (defun emus-make-track (artist album title filename &optional pos)
97   (vector artist album title filename pos))
98
99 (defun emus-track-artist (track)
100   (elt track 0))
101
102 (defun emus-track-album (track)
103   (elt track 1))
104
105 (defun emus-track-title (track)
106   (elt track 2))
107
108 (defun emus-track-file (track)
109   (elt track 3))
110
111 (defun emus-track-browser-pos (track)
112   (elt track 4))
113
114 (defun emus-set-track-browser-pos (track pos)
115   (aset track 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-tracks 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-tracks
128                                               (emus--make-track-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-tracks (reverse emus-tracks))
136                                    (emus--sort-tracks)
137                                    (unless emus-current-track
138                                      (setq emus-current-track (car emus-tracks)))
139                                    (funcall then)
140                                    ;; (emus-render-tracks)
141                                    (emus--resume-cp)))))
142     (emus-send-cmd "lp" (car filenames))))
143
144 (defun emus--make-track-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-track artist album title filename nil)))
157
158 (defun emus--sort-tracks ()
159   (sort emus-tracks
160         (lambda (r1 r2)
161           (let ((artist1 (emus-track-artist r1))
162                 (artist2 (emus-track-artist r2)))
163             (if (string= artist1 artist2)
164                 (let ((album1 (emus-track-album r1))
165                       (album2 (emus-track-album r2)))
166                   (string< album1 album2))
167               (string< artist1 artist2))))))
168
169 (defmacro emus--with-library (&rest args)
170   `(if emus-tracks
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-track 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-track (track)
236   "Set TRACK as current and start playing."
237   (emus--with-library
238    (let ((old-track emus-current-track))
239      (emus-send-cmd "l" (emus-track-file track))
240      (setq emus-state 'playing)
241      (setq emus-current-track track)
242      (emus--update-track old-track)
243      (emus--update-track track)
244      (emus--resume-cp))))
245
246 (defun emus-select-track (track)
247   "Set TRACK as current, but do not start playing."
248   (emus--with-library
249    (let ((old-track emus-current-track))
250      (setq emus-state 'stopped)
251      (setq emus-current-track track)
252      (emus--update-track old-track)
253      (emus--update-track track)
254      (emus-send-cmd "o")
255      (emus--resume-cp))))
256
257 (defun emus-stop ()
258   "Stop playback of the current track."
259   (interactive)
260   (emus--with-library
261    (setq emus-state 'stopped)
262    (emus--update-track emus-current-track)
263    (emus-send-cmd "s")))
264
265 (defun emus-playpause ()
266   (interactive)
267   (emus--with-library
268    (when emus-current-track
269      (if (eq emus-state 'stopped)
270          (emus-play-track emus-current-track)
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-track emus-current-track))))
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-adjacent-track (&optional prev)
297   (emus--with-library
298    (let ((idx (seq-position emus-tracks emus-current-track))
299          (offset (if prev -1 +1)))
300      (if idx
301          (let ((next-track (elt emus-tracks (+ idx offset))))
302            (if next-track
303                (if (eq emus-state 'playing)
304                    (emus-play-track next-track)
305                  (emus-select-track next-track))
306              (error "Track does not exist")))
307        (error "No track selected")))))
308
309 (defun emus--play-adjacent-album (&optional prev)
310   (emus--with-library
311    (let ((idx (seq-position emus-tracks emus-current-track)))
312      (if idx
313          (let* ((search-list (if prev
314                                  (reverse (seq-subseq emus-tracks 0 idx))
315                                (seq-subseq emus-tracks (+ idx 1))))
316                 (current-album (emus-track-album emus-current-track))
317                 (next-track (seq-some (lambda (r)
318                                         (if (string= (emus-track-album r)
319                                                      current-album)
320                                             nil
321                                           r))
322                                       search-list)))
323            (if next-track
324                (if (eq emus-state 'playing)
325                    (emus-play-track next-track)
326                  (emus-select-track next-track))
327              (error "Track does not exist")))
328        (error "No track selected")))))
329
330 (defun emus-play-next ()
331   (interactive)
332   (emus--play-adjacent-track))
333
334 (defun emus-play-prev ()
335   (interactive)
336   (emus--play-adjacent-track t))
337
338 (defun emus-play-next-album ()
339   (interactive)
340   (emus--play-adjacent-album))
341
342 (defun emus-play-prev-album ()
343   (interactive)
344   (emus--play-adjacent-album t))
345
346 (defun emus-jump (seconds)
347   "Jump forward in current track by SECONDS seconds."
348   (emus--with-library
349    (emus-send-cmd "jump" (format "%+ds" seconds))))
350
351 (defun emus-jump-10s-forward ()
352   "Jump 10 seconds forward in current track."
353   (interactive)
354   (emus-jump 10))
355
356 (defun emus-jump-10s-backward ()
357   "Jump 10 seconds backward in current track."
358   (interactive)
359   (emus-jump -10))
360
361 (defun emus-display-status ()
362   (interactive)
363   (emus--with-library
364    (message
365     (concat "Emus: Volume %d%%"
366             (pcase emus-state
367               ('stopped " [Stopped]")
368               ('paused " [Paused]")
369               ('playing " [Playing]")
370               (_ ""))
371             (if emus-current-track
372                 (format " - %.30s (%.20s)"
373                         (emus-track-title emus-current-track)
374                         (emus-track-artist emus-current-track))
375               ""))
376     emus-current-volume)))
377
378
379 ;;; Browser
380 ;;
381
382 (defun emus--insert-track (track &optional prev-track first)
383   (let* ((artist (emus-track-artist track))
384          (album (emus-track-album track))
385          (title (emus-track-title track))
386          (help-str (format "mouse-1, RET: Play '%.30s' (%.20s)" title artist)))
387     (when (or prev-track first)
388       (unless (equal (emus-track-artist prev-track) artist)
389         (insert-text-button
390          (propertize artist 'face 'emus-artist)
391          'action #'emus--click-track
392          'follow-link t
393          'help-echo help-str
394          'emus-track track)
395         (insert (propertize "\n" 'face 'emus-artist)))
396       (unless (equal (emus-track-album prev-track) album)
397         (insert-text-button
398          (propertize (concat "  " album) 'face 'emus-album)
399          'action #'emus--click-track
400          'follow-link t
401          'help-echo help-str
402          'emus-track track)
403         (insert (propertize "\n" 'face 'emus-album))))
404     (emus-set-track-browser-pos track (point))
405     (let ((is-current (equal track emus-current-track)))
406       (insert-text-button
407        (concat
408         (if is-current
409             (propertize
410              (pcase emus-state
411                ('playing "->")
412                ('paused "-)")
413                ('stopped "-]"))
414              'face 'emus-cursor)
415           (propertize "  " 'face 'default))
416         (propertize (format "   %s" title)
417                     'face (if is-current
418                               'emus-track-current
419                             'emus-track)))
420        'action #'emus--click-track
421        'follow-link t
422        'help-echo help-str
423        'emus-track track)
424       (insert (propertize "\n"
425                           'face (if is-current
426                                     'emus-track-current
427                                   'emus-track))))))
428
429 (defun emus--update-track (track)
430   (let ((track-pos (emus-track-browser-pos track)))
431     (when (and (get-buffer "*emus*")
432                (emus-track-browser-pos track))
433       (with-current-buffer "*emus*"
434         (let ((inhibit-read-only t)
435               (old-point (point)))
436           (goto-char track-pos)
437           (search-forward "\n")
438           (delete-region track-pos (point))
439           (goto-char track-pos)
440           (emus--insert-track track)
441           (goto-char old-point))))))
442
443 (defun emus--render-tracks ()
444   (with-current-buffer "*emus*"
445     (let ((inhibit-read-only t)
446           (old-pos (point)))
447       (erase-buffer)
448       (goto-char (point-min))
449       (let ((prev-track nil))
450         (dolist (track emus-tracks)
451           (emus--insert-track track prev-track (not prev-track))
452           (setq prev-track track)))
453       (goto-char old-pos))))
454
455 (defun emus--click-track (button)
456   (emus-play-track (button-get button 'emus-track))
457   (emus-display-status))
458
459 (defun emus-centre-current ()
460   (interactive)
461   (when (get-buffer "*emus*")
462     (switch-to-buffer "*emus*")
463     (when emus-current-track
464       (goto-char (emus-track-browser-pos emus-current-track))
465       (recenter))))
466
467 (defun emus-browse ()
468   "Switch to *emus* audio library browser."
469   (interactive)
470   (emus--with-library
471    (switch-to-buffer "*emus*")
472    (emus-browser-mode)
473    (emus--render-tracks)
474    (emus-centre-current)))
475
476 (defun emus-refresh ()
477   (interactive)
478   (emus-stop)
479   (setq emus-tracks nil)
480   (emus-browse))
481
482 (defun emus-playpause-status () (interactive) (emus-playpause) (emus-display-status))
483 (defun emus-stop-status () (interactive) (emus-stop) (emus-display-status))
484 (defun emus-volume-up-status () (interactive) (emus-volume-up) (emus-display-status))
485 (defun emus-volume-down-status () (interactive) (emus-volume-down) (emus-display-status))
486 (defun emus-play-next-status () (interactive) (emus-play-next) (emus-display-status))
487 (defun emus-play-prev-status () (interactive) (emus-play-prev) (emus-display-status))
488 (defun emus-play-next-album-status () (interactive) (emus-play-next-album) (emus-display-status))
489 (defun emus-play-prev-album-status () (interactive) (emus-play-prev-album) (emus-display-status))
490 (defun emus-jump-10s-forward-status () (interactive) (emus-jump-10s-forward) (emus-display-status))
491 (defun emus-jump-10s-backward-status () (interactive) (emus-jump-10s-backward) (emus-display-status))
492 (defun emus-centre-current-status () (interactive) (emus-centre-current) (emus-display-status))
493
494 (defun emus-refresh-status ()
495   (interactive)
496   (emus-stop)
497   (setq emus-tracks nil)
498   (emus--with-library
499    (emus-browse)
500    (emus-display-status)))
501
502 (defvar emus-browser-mode-map
503   (let ((map (make-sparse-keymap)))
504     (define-key map (kbd "SPC") 'emus-playpause-status)
505     (define-key map (kbd "o") 'emus-stop-status)
506     (define-key map (kbd "+") 'emus-volume-up-status)
507     (define-key map (kbd "=") 'emus-volume-up-status)
508     (define-key map (kbd "-") 'emus-volume-down-status)
509     (define-key map (kbd "R") 'emus-refresh-status)
510     (define-key map (kbd "n") 'emus-play-next-status)
511     (define-key map (kbd "p") 'emus-play-prev-status)
512     (define-key map (kbd "N") 'emus-play-next-album-status)
513     (define-key map (kbd "P") 'emus-play-prev-album-status)
514     (define-key map (kbd ",") 'emus-jump-10s-backward-status)
515     (define-key map (kbd ".") 'emus-jump-10s-forward-status)
516     (define-key map (kbd "c") 'emus-centre-current-status)
517     (when (fboundp 'evil-define-key*)
518       (evil-define-key* 'motion map
519                         (kbd "SPC") 'emus-playpause-status
520                         (kbd "o") 'emus-stop-status
521                         (kbd "+") 'emus-volume-up-status
522                         (kbd "=") 'emus-volume-up-status
523                         (kbd "-") 'emus-volume-down-status
524                         (kbd "R") 'emus-refresh-status
525                         (kbd "n") 'emus-play-next-status
526                         (kbd "p") 'emus-play-prev-status
527                         (kbd "N") 'emus-play-next-album-status
528                         (kbd "P") 'emus-play-prev-album-status
529                         (kbd ",") 'emus-jump-10s-backward-status
530                         (kbd ".") 'emus-jump-10s-forward-status
531                         (kbd "c") 'emus-centre-current-status))
532     map)
533   "Keymap for emus.")
534
535 (define-derived-mode emus-browser-mode special-mode "emus-browser"
536   "Major mode for EMUS music player file browser.")
537
538 (when (fboundp 'evil-set-initial-state)
539   (evil-set-initial-state 'emus-browser-mode 'motion))
540
541 ;;; emus.el ends here