Track selection now moves point in brwoser buffer.
[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 ;;; Customizations
45 ;;
46
47 (defgroup emus nil
48   "Simple music player for Emacs."
49   :group 'multimedia)
50
51 (defcustom emus-directory "~/Music/"
52   "Directory containing audio files for emus."
53   :type '(string))
54
55 (defcustom emus-mpg123-program "mpg123"
56   "Name of (and, optionally, path to) mpg123 binary."
57   :type '(string))
58
59 (defface emus-artist
60   '((t :inherit font-lock-string-face :background "#333"))
61   "Face used for artist names in browser.")
62
63 (defface emus-album
64   '((t :inherit font-lock-constant-face :background "#222"))
65   "Face used for album names in browser.")
66
67 (defface emus-track
68   '((t :inherit font-lock-keyword-face))
69   "Face used for track titles in browser.")
70
71 (defface emus-track-current
72   '((t :inherit font-lock-keyword-face :inverse-video t))
73   "Face used for track titles in browser.")
74
75 (defface emus-cursor
76   '((t :inherit bold))
77   "Face used for current track cursor")
78
79
80 ;;; Global variables
81
82 (defvar emus--proc-in-use nil
83   "If non-nil, disables `emus-send-cmd'.
84 Used to prevent commands from interfering with library construction.")
85
86 (defvar emus-tracks nil
87   "Emus audio library.")
88
89 (defvar emus-current-track nil
90   "Currently-selected emus track.")
91
92 (defvar emus-state 'stopped
93   "Current playback state.")
94
95 (defvar emus-continuous-playback t
96   "If non-nil, emus will automatically play the next track when the current track is finished.")
97
98 (defvar emus-current-volume 100
99   "The current playback volume.")
100
101
102 ;;; mpg123 process
103 ;;
104
105
106 (defun emus-get-process ()
107   "Return current or new mpg123 process."
108   (let* ((emus-process-raw (get-process "emus-process"))
109          (emus-process (if emus-process-raw
110                            (if (process-live-p emus-process-raw)
111                                emus-process-raw
112                              (kill-process emus-process-raw)
113                              nil))))
114     (if emus-process
115         emus-process
116       (let ((proc
117              (make-process :name "emus-process"
118                            ;; :buffer (get-buffer-create "*emus-process*")
119                            :command `(,emus-mpg123-program "-R"))))
120         (set-process-query-on-exit-flag proc nil)
121         (process-send-string proc "silence\n")
122         proc))))
123
124 (defun emus--send-cmd-raw (cmd &rest args)
125   "Send a command CMD with args ARGS to the mpg123 process.
126 This procedure does not respect `emus--proc-in-use' and thus should only
127 be used by `emus--load-library'."
128     (process-send-string (emus-get-process)
129                          (concat
130                           (seq-reduce (lambda (s1 s2) (concat s1 " " s2)) args cmd)
131                           "\n")))
132
133 (defun emus-send-cmd (cmd &rest args)
134   "Send a command CMD with args ARGS to the mpg123 process."
135   (unless emus--proc-in-use
136     (apply #'emus--send-cmd-raw cmd args)))
137
138
139 ;;; Library
140 ;;
141
142 (defun emus-get-audio-files ()
143   "Get all mp3 files in main emus directory."
144   (directory-files-recursively emus-directory ".*\\.mp3"))
145
146 (defun emus-make-track (artist album title filename &optional pos)
147   "Create an object representing an emus track.
148 ARTIST, ALBUM and TITLE are used to describe the track, FILENAME
149 refers to the mp3 file containing the track.  If non-nil, POS
150 specifies the position of the record representing this track in the
151 emus browser buffer."
152   (vector artist album title filename pos))
153
154 (defun emus-track-artist (track)
155   "The artist corresponding to TRACK."
156   (elt track 0))
157
158 (defun emus-track-album (track)
159   "The album corresponding to TRACK."
160   (elt track 1))
161
162 (defun emus-track-title (track)
163   "The title of TRACK."
164   (elt track 2))
165
166 (defun emus-track-file (track)
167   "The mp3 file corresponding to TRACK."
168   (elt track 3))
169
170 (defun emus-track-browser-pos (track)
171   "The location of the browser buffer record corresponding to TRACK."
172   (elt track 4))
173
174 (defun emus-set-track-browser-pos (track pos)
175   "Set the location of the browser buffer record corresponding to TRACK to POS."
176   (aset track 4 pos))
177
178 (defun emus--load-library (then)
179   "Initialize the emus track library.
180 Once the library is initialized, the function THEN is called."
181   (unless emus--proc-in-use
182     (setq emus--proc-in-use t)
183     (emus--suspend-cp)
184     (setq emus-state 'stopped)
185     (let ((proc (emus-get-process))
186           (tagstr "")
187           (filenames (emus-get-audio-files)))
188       (setq emus-tracks nil)
189       (set-process-filter proc (lambda (proc string)
190                                  (setq tagstr (concat tagstr string))
191                                  (when (string-suffix-p "@P 1\n" string)
192                                    (add-to-list 'emus-tracks
193                                                 (emus--make-track-from-tagstr (car filenames)
194                                                                               tagstr))
195                                    (setq tagstr "")
196                                    (setq filenames (cdr filenames))
197                                    (if filenames
198                                        (emus--send-cmd-raw "lp" (car filenames))
199                                      (set-process-filter proc nil)
200                                      (setq emus-tracks (reverse emus-tracks))
201                                      (emus--sort-tracks)
202                                      (unless emus-current-track
203                                        (setq emus-current-track (car emus-tracks)))
204                                      (funcall then)
205                                      (emus--resume-cp)
206                                      (setq emus--proc-in-use nil)))))
207       (emus--send-cmd-raw "lp" (car filenames)))))
208
209 (defun emus--make-track-from-tagstr (filename tagstr)
210   "Parse TAGSTR to populate the fields of a track corresponding to FILENAME."
211   (let ((artist "")
212         (album "")
213         (title ""))
214     (dolist (line (split-string tagstr "\n"))
215       (let ((found-artist (elt (split-string line "@I ID3v2.artist:") 1))
216             (found-album (elt (split-string line "@I ID3v2.album:") 1))
217             (found-title (elt (split-string line "@I ID3v2.title:") 1)))
218         (cond
219          (found-artist (setq artist found-artist))
220          (found-album (setq album found-album))
221          (found-title (setq title found-title)))))
222     (emus-make-track artist album title filename nil)))
223
224 (defun emus--sort-tracks ()
225   "Sort the library tracks according to artist and album.
226 Leaves the track titles unsorted, so they will appear in the order specified
227 by the filesystem."
228   (sort emus-tracks
229         (lambda (r1 r2)
230           (let ((artist1 (emus-track-artist r1))
231                 (artist2 (emus-track-artist r2)))
232             (if (string= artist1 artist2)
233                 (let ((album1 (emus-track-album r1))
234                       (album2 (emus-track-album r2)))
235                   (string< album1 album2))
236               (string< artist1 artist2))))))
237
238 (defmacro emus--with-library (&rest body)
239   "Evaluate BODY with the library initialized."
240   `(if emus-tracks
241        (progn ,@body)
242      (emus--load-library
243       (lambda () ,@body))))
244
245
246 ;;; Playback
247 ;;
248
249 (defun emus--suspend-cp ()
250   "Suspend continuous playback."
251   (setq emus-continuous-playback nil))
252
253 (defun emus--resume-cp ()
254   "Resume continuous playback."
255   (setq emus-continuous-playback t)
256   (set-process-filter (emus-get-process)
257                       (lambda (_proc string)
258                         (and emus-continuous-playback
259                              (eq emus-state 'playing)
260                              (string-suffix-p "@P 0\n" string)
261                              (emus-play-next)))))
262
263 (defun emus-play-track (track)
264   "Set TRACK as current and start playing."
265   (emus--with-library
266    (let ((old-track emus-current-track))
267      (emus-send-cmd "l" (emus-track-file track))
268      (setq emus-state 'playing)
269      (setq emus-current-track track)
270      (emus--update-track old-track)
271      (emus--update-track track)
272      (emus--resume-cp)
273      (emus-goto-current))))
274
275 (defun emus-select-track (track)
276   "Set TRACK as current, but do not start playing."
277   (emus--with-library
278    (let ((old-track emus-current-track))
279      (setq emus-state 'stopped)
280      (setq emus-current-track track)
281      (emus--update-track old-track)
282      (emus--update-track track)
283      (emus-send-cmd "o")
284      (emus--resume-cp)
285      (emus-goto-current))))
286
287 (defun emus-stop ()
288   "Stop playback of the current track."
289   (interactive)
290   (emus--with-library
291    (setq emus-state 'stopped)
292    (emus--update-track emus-current-track)
293    (emus-send-cmd "s")))
294
295 (defun emus-playpause ()
296   "Begin playback of the current track.
297 If the track is already playing, pause playback.
298 If the track is currently paused, resume playback."
299   (interactive)
300   (emus--with-library
301    (when emus-current-track
302      (if (eq emus-state 'stopped)
303          (emus-play-track emus-current-track)
304        (emus-send-cmd "p")
305        (pcase emus-state
306          ((or 'paused 'stopped) (setq emus-state 'playing))
307          ('playing (setq emus-state 'paused)))
308        (unless (eq emus-state 'paused)))
309      (emus--update-track emus-current-track))))
310
311 (defun emus-set-volume (pct)
312   "Set the playback volume to PCT %."
313   (emus--with-library
314    (setq emus-current-volume pct)
315    (emus-send-cmd "v" (number-to-string pct))))
316
317 (defun emus-volume-increase-by (delta)
318   "Increase the playback volume by DELTA %."
319   (emus-set-volume (max 0 (min 100 (+ emus-current-volume delta)))))
320
321 (defun emus-volume-up ()
322   "Increase the playback volume by 10%."
323   (interactive)
324   (emus-volume-increase-by 10))
325
326 (defun emus-volume-down ()
327   "Decrease the playback volume by 10%."
328   (interactive)
329   (emus-volume-increase-by -10))
330
331 (defun emus--play-adjacent-track (&optional prev)
332   "Play the next track in the library, or the previous if PREV is non-nil."
333   (emus--with-library
334    (let ((idx (seq-position emus-tracks emus-current-track))
335          (offset (if prev -1 +1)))
336      (if idx
337          (let ((next-track (elt emus-tracks (+ idx offset))))
338            (if next-track
339                (if (eq emus-state 'playing)
340                    (emus-play-track next-track)
341                  (emus-select-track next-track))
342              (error "Track does not exist")))
343        (error "No track selected")))))
344
345 (defun emus--play-adjacent-album (&optional prev)
346   "Play the first track of the next album in the library.
347 If PREV is non-nil, plays the last track of the previous album."
348   (emus--with-library
349    (let ((idx (seq-position emus-tracks emus-current-track)))
350      (if idx
351          (let* ((search-list (if prev
352                                  (reverse (seq-subseq emus-tracks 0 idx))
353                                (seq-subseq emus-tracks (+ idx 1))))
354                 (current-album (emus-track-album emus-current-track))
355                 (next-track (seq-some (lambda (r)
356                                         (if (string= (emus-track-album r)
357                                                      current-album)
358                                             nil
359                                           r))
360                                       search-list)))
361            (if next-track
362                (if (eq emus-state 'playing)
363                    (emus-play-track next-track)
364                  (emus-select-track next-track))
365              (error "Track does not exist")))
366        (error "No track selected")))))
367
368 (defun emus-play-next ()
369   "Play the next track in the library."
370   (interactive)
371   (emus--play-adjacent-track))
372
373 (defun emus-play-prev ()
374   "Play the previous track in the library."
375   (interactive)
376   (emus--play-adjacent-track t))
377
378 (defun emus-play-next-album ()
379   "Play the first track of the next album in the library."
380   (interactive)
381   (emus--play-adjacent-album))
382
383 (defun emus-play-prev-album ()
384   "Play the last track of the previous album in the library."
385   (interactive)
386   (emus--play-adjacent-album t))
387
388 (defun emus-jump (seconds)
389   "Jump forward in current track by SECONDS seconds."
390   (emus--with-library
391    (emus-send-cmd "jump" (format "%+ds" seconds))))
392
393 (defun emus-jump-10s-forward ()
394   "Jump 10 seconds forward in current track."
395   (interactive)
396   (emus-jump 10))
397
398 (defun emus-jump-10s-backward ()
399   "Jump 10 seconds backward in current track."
400   (interactive)
401   (emus-jump -10))
402
403 (defun emus-display-status ()
404   "Display the current playback status in the minibuffer."
405   (interactive)
406   (emus--with-library
407    (message
408     (concat "Emus: Volume %d%%"
409             (pcase emus-state
410               ('stopped " [Stopped]")
411               ('paused " [Paused]")
412               ('playing " [Playing]")
413               (_ ""))
414             (if emus-current-track
415                 (format " - %.30s (%.20s)"
416                         (emus-track-title emus-current-track)
417                         (emus-track-artist emus-current-track))
418               ""))
419     emus-current-volume)))
420
421
422 ;;; Browser
423 ;;
424
425 (defun emus--insert-track (track &optional prev-track first)
426   "Insert a button representing TRACK into the current buffer.
427
428 When provided, PREV-TRACK is used to determine whether to insert additional
429 headers representing the artist or the album title.
430
431 If non-nil, FIRST indicates that the track is the first in the library
432 and thus requires both artist and album headers."
433   (let* ((artist (emus-track-artist track))
434          (album (emus-track-album track))
435          (title (emus-track-title track))
436          (help-str (format "mouse-1, RET: Play '%.30s' (%.20s)" title artist)))
437     (when (or prev-track first)
438       (unless (equal (emus-track-artist prev-track) artist)
439         (insert-text-button
440          (propertize artist 'face 'emus-artist)
441          'action #'emus--click-track
442          'follow-link t
443          'help-echo help-str
444          'emus-track track)
445         (insert (propertize "\n" 'face 'emus-artist)))
446       (unless (equal (emus-track-album prev-track) album)
447         (insert-text-button
448          (propertize (concat "  " album) 'face 'emus-album)
449          'action #'emus--click-track
450          'follow-link t
451          'help-echo help-str
452          'emus-track track)
453         (insert (propertize "\n" 'face 'emus-album))))
454     (emus-set-track-browser-pos track (point))
455     (let ((is-current (equal track emus-current-track)))
456       (insert-text-button
457        (concat
458         (if is-current
459             (propertize
460              (pcase emus-state
461                ('playing "->")
462                ('paused "-)")
463                ('stopped "-]"))
464              'face 'emus-cursor)
465           (propertize "  " 'face 'default))
466         (propertize (format "   %s" title)
467                     'face (if is-current
468                               'emus-track-current
469                             'emus-track)))
470        'action #'emus--click-track
471        'follow-link t
472        'help-echo help-str
473        'emus-track track)
474       (insert (propertize "\n"
475                           'face (if is-current
476                                     'emus-track-current
477                                   'emus-track))))))
478
479 (defun emus--update-track (track)
480   "Rerender entry for TRACK in emus browser buffer.
481 Used to update browser display when `emus-current-track' and/or `emus-state' changes."
482   (let ((track-pos (emus-track-browser-pos track)))
483     (when (and (get-buffer "*emus*")
484                (emus-track-browser-pos track))
485       (with-current-buffer "*emus*"
486         (let ((inhibit-read-only t)
487               (old-point (point)))
488           (goto-char track-pos)
489           (search-forward "\n")
490           (delete-region track-pos (point))
491           (goto-char track-pos)
492           (emus--insert-track track)
493           (goto-char old-point))))))
494
495 (defun emus--render-tracks ()
496   "Render all library tracks in emus browser buffer."
497   (with-current-buffer "*emus*"
498     (let ((inhibit-read-only t)
499           (old-pos (point)))
500       (erase-buffer)
501       (goto-char (point-min))
502       (let ((prev-track nil))
503         (dolist (track emus-tracks)
504           (emus--insert-track track prev-track (not prev-track))
505           (setq prev-track track)))
506       (goto-char old-pos))))
507
508 (defun emus--click-track (button)
509   "Begin playback of track indicated by BUTTON."
510   (emus-play-track (button-get button 'emus-track))
511   (emus-display-status))
512
513 (defun emus-goto-current ()
514   "Move point to the current track in the browser buffer, if available."
515   (interactive)
516   (when (and (get-buffer "*emus*")
517              emus-current-track)
518     (with-current-buffer "*emus*"
519         (goto-char (emus-track-browser-pos emus-current-track)))))
520
521 (defun emus-browse ()
522   "Switch to *emus* audio library browser."
523   (interactive)
524   (emus--with-library
525    (pop-to-buffer "*emus*")
526    (emus-browser-mode)
527    (emus--render-tracks)
528    (emus-goto-current)))
529
530 (defun emus-refresh ()
531   "Refresh the emus library."
532   (interactive)
533   (emus-stop)
534   (setq emus-tracks nil)
535   (emus-browse))
536
537
538 ;;; Playback + status display commands
539 ;;
540
541 (defun emus-playpause-status ()
542   "Start, pause or resume playback, then display the emus status in the minibuffer."
543   (interactive)
544   (emus-playpause)
545   (emus-display-status))
546
547 (defun emus-stop-status ()
548   "Stop playback, then display the emus status in the minibuffer."
549   (interactive)
550   (emus-stop)
551   (emus-display-status))
552
553 (defun emus-volume-up-status ()
554   "Increase volume by 10%, then display the emus status in the minibuffer."
555   (interactive)
556   (emus-volume-up)
557   (emus-display-status))
558
559 (defun emus-volume-down-status ()
560   "Decrease volume by 10%, then display the emus status in the minibuffer."
561   (interactive)
562   (emus-volume-down)
563   (emus-display-status))
564
565 (defun emus-play-next-status ()
566   "Play next track, then display the emus status in the minibuffer."
567   (interactive)
568   (emus-play-next)
569   (emus-display-status))
570
571 (defun emus-play-prev-status ()
572   "Play previous track, then display the emus status in the minibuffer."
573   (interactive)
574   (emus-play-prev)
575   (emus-display-status))
576
577 (defun emus-play-next-album-status ()
578   "Play first track of next album, then display the emus status in the minibuffer."
579   (interactive)
580   (emus-play-next-album)
581   (emus-display-status))
582
583 (defun emus-play-prev-album-status ()
584   "Play last track of previous album, then display the emus status in the minibuffer."
585   (interactive)
586   (emus-play-prev-album)
587   (emus-display-status))
588
589 (defun emus-jump-10s-forward-status ()
590   "Jump 10s forward in current track, then display the emus status in the minibuffer."
591   (interactive)
592   (emus-jump-10s-forward)
593   (emus-display-status))
594
595 (defun emus-jump-10s-backward-status ()
596   "Jump 10s backward in current track, then display the emus status in the minibuffer."
597   (interactive)
598   (emus-jump-10s-backward)
599   (emus-display-status))
600
601 (defun emus-goto-current-status ()
602   "Move point to the current track, then display the emus status in the minibuffer."
603   (interactive)
604   (emus-goto-current)
605   (emus-display-status))
606
607 (defun emus-refresh-status ()
608   "Refresh the emus library, then display the emus status in the minibuffer."
609   (interactive)
610   (emus-stop)
611   (setq emus-tracks nil)
612   (emus--with-library
613    (emus-browse)
614    (emus-display-status)))
615
616 (defvar emus-browser-mode-map
617   (let ((map (make-sparse-keymap)))
618     (define-key map (kbd "SPC") 'emus-playpause-status)
619     (define-key map (kbd "o") 'emus-stop-status)
620     (define-key map (kbd "+") 'emus-volume-up-status)
621     (define-key map (kbd "=") 'emus-volume-up-status)
622     (define-key map (kbd "-") 'emus-volume-down-status)
623     (define-key map (kbd "R") 'emus-refresh-status)
624     (define-key map (kbd "n") 'emus-play-next-status)
625     (define-key map (kbd "p") 'emus-play-prev-status)
626     (define-key map (kbd "N") 'emus-play-next-album-status)
627     (define-key map (kbd "P") 'emus-play-prev-album-status)
628     (define-key map (kbd ",") 'emus-jump-10s-backward-status)
629     (define-key map (kbd ".") 'emus-jump-10s-forward-status)
630     (define-key map (kbd "c") 'emus-goto-current-status)
631     (when (fboundp 'evil-define-key*)
632       (evil-define-key* 'motion map
633                         (kbd "SPC") 'emus-playpause-status
634                         (kbd "o") 'emus-stop-status
635                         (kbd "+") 'emus-volume-up-status
636                         (kbd "=") 'emus-volume-up-status
637                         (kbd "-") 'emus-volume-down-status
638                         (kbd "R") 'emus-refresh-status
639                         (kbd "n") 'emus-play-next-status
640                         (kbd "p") 'emus-play-prev-status
641                         (kbd "N") 'emus-play-next-album-status
642                         (kbd "P") 'emus-play-prev-album-status
643                         (kbd ",") 'emus-jump-10s-backward-status
644                         (kbd ".") 'emus-jump-10s-forward-status
645                         (kbd "c") 'emus-goto-current-status))
646     map)
647   "Keymap for emus browser.")
648
649 (define-derived-mode emus-browser-mode special-mode "emus-browser"
650   "Major mode for EMUS music player file browser.")
651
652 (when (fboundp 'evil-set-initial-state)
653   (evil-set-initial-state 'emus-browser-mode 'motion))
654
655 ;;; emus.el ends here