1 ;;; emus.el --- Simple mp3 player -*- lexical-binding:t -*-
3 ;; Copyright (C) 2019 Tim Vaughan
5 ;; Author: Tim Vaughan <timv@ughan.xyz>
6 ;; Created: 8 December 2019
8 ;; Keywords: multimedia
9 ;; Homepage: http://thelambdalab.xy/emus
10 ;; Package-Requires: ((emacs "26"))
12 ;; This file is not part of GNU Emacs.
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.
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.
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/>.
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.
48 "Simple music player for Emacs."
51 (defcustom emus-directory "~/Music/"
52 "Directory containing audio files for emus."
55 (defcustom emus-mpg123-program "mpg123"
56 "Name of (and, optionally, path to) mpg123 binary."
59 (defcustom emus-mpg123-args nil
60 "Arguments to pass to mpg123."
61 :type '(repeat string))
64 '((((background dark)) :inherit font-lock-string-face :background "#222" :extend t)
65 (t :inherit font-lock-string-face :background "#ddd" :extend t))
66 "Face used for artist names in browser.")
69 '((((background dark)) :inherit font-lock-constant-face :background "#111" :extend t)
70 (t :inherit font-lock-constant-face :background "#eee" :extend t))
71 "Face used for album names in browser.")
74 '((t :inherit font-lock-keyword-face))
75 "Face used for track titles in browser.")
77 (defface emus-track-current
78 '((t :inherit font-lock-keyword-face :inverse-video t :extend t))
79 "Face used for track titles in browser.")
83 "Face used for current track cursor")
88 (defvar emus--proc-in-use nil
89 "If non-nil, disables `emus-send-cmd'.
90 Used to prevent commands from interfering with library construction.")
92 (defvar emus-tracks nil
93 "Emus audio library.")
95 (defvar emus-current-track nil
96 "Currently-selected emus track.")
98 (defvar emus-state 'stopped
99 "Current playback state.")
101 (defvar emus-continuous-playback t
102 "If non-nil, emus will automatically play the next track when the current track is finished.")
104 (defvar emus-current-volume 100
105 "The current playback volume.")
107 (defvar emus-current-progress ""
108 "String describing the progress through the current track.")
110 (defvar emus-progress-enabled t
111 "Current state of progress tracking.
113 To enable or disable progress tracking, using `emus-toggle-progress-tracking'.
114 (Changing the value of this variable will not affect anything.)")
120 (defun emus-get-process ()
121 "Return current or new mpg123 process."
122 (let* ((emus-process-raw (get-process "emus-process"))
123 (emus-process (if emus-process-raw
124 (if (process-live-p emus-process-raw)
126 (kill-process emus-process-raw)
131 (make-process :name "emus-process"
132 :command `(,emus-mpg123-program
135 (set-process-query-on-exit-flag proc nil)
136 (unless emus-progress-enabled
137 (process-send-string proc "silence\n"))
140 (defun emus--send-cmd-raw (cmd &rest args)
141 "Send a command CMD with args ARGS to the mpg123 process.
142 This procedure does not respect `emus--proc-in-use' and thus should only
143 be used by `emus--load-library'."
144 (process-send-string (emus-get-process)
146 (seq-reduce (lambda (s1 s2) (concat s1 " " s2)) args cmd)
149 (defun emus-send-cmd (cmd &rest args)
150 "Send a command CMD with args ARGS to the mpg123 process."
151 (unless emus--proc-in-use
152 (apply #'emus--send-cmd-raw cmd args)))
154 (defun emus-kill-process ()
155 "Kill any existing mpg123 process."
156 (let ((emus-process (get-process "emus-process")))
158 (kill-process emus-process))
159 (setq emus-state 'stopped
160 emus--proc-in-use nil
166 (defun emus-get-audio-files ()
167 "Get all mp3 files in main emus directory."
170 (directory-files-recursively emus-directory ".*\\.mp3")))
172 (defun emus-get-playlist-files ()
173 "Get all m3u files in the main emus music directory."
176 (directory-files-recursively emus-directory ".*\\.m3u")))
178 (defun emus-make-track (artist album title filename &optional pos)
179 "Create an object representing an emus track.
180 ARTIST, ALBUM and TITLE are used to describe the track, FILENAME
181 refers to the mp3 file containing the track. If non-nil, POS
182 specifies the position of the record representing this track in the
183 emus browser buffer."
184 (list artist album title filename pos))
186 (defun emus-track-artist (track)
187 "The artist corresponding to TRACK."
190 (defun emus-track-album (track)
191 "The album corresponding to TRACK."
194 (defun emus-track-title (track)
195 "The title of TRACK."
198 (defun emus-track-file (track)
199 "The mp3 file corresponding to TRACK."
202 (defun emus-track-browser-pos (track)
203 "The location of the browser buffer record corresponding to TRACK."
206 (defun emus-set-track-browser-pos (track pos)
207 "Set the location of the browser buffer record corresponding to TRACK to POS."
208 (setf (seq-elt track 4) pos))
210 (defun emus--load-library (then)
211 "Initialize the emus track library.
212 Once the library is initialized, the function THEN is called."
213 (unless emus--proc-in-use
214 (setq emus--proc-in-use t)
216 (setq emus-state 'stopped)
217 (setq emus-tracks nil)
218 (let ((proc (emus-get-process))
220 (filenames (emus-get-audio-files)))
221 (set-process-filter proc (lambda (proc string)
222 (setq tagstr (concat tagstr string))
223 (when (string-suffix-p "@P 1\n" string)
224 (add-to-list 'emus-tracks
225 (emus--make-track-from-tagstr (car filenames)
228 (setq filenames (cdr filenames))
230 (emus--send-cmd-raw "lp" (car filenames))
231 (set-process-filter proc nil)
232 (setq emus-tracks (reverse emus-tracks))
234 (emus--add-tracks-from-playlist-files)
235 (unless emus-current-track
236 (setq emus-current-track (car emus-tracks)))
239 (setq emus--proc-in-use nil)))))
240 (emus--send-cmd-raw "lp" (car filenames)))))
242 (defun emus--dump-tracks ()
245 (defun emus--make-track-from-tagstr (filename tagstr)
246 "Parse TAGSTR to populate the fields of a track corresponding to FILENAME."
247 (let ((artist "Unknown Artist")
248 (album "Unknown Album")
250 (dolist (line (split-string tagstr "\n"))
251 (let ((found-artist (elt (split-string line "@I ID3v2.artist:") 1))
252 (found-album (elt (split-string line "@I ID3v2.album:") 1))
253 (found-title (elt (split-string line "@I ID3v2.title:") 1)))
255 (found-artist (setq artist found-artist))
256 (found-album (setq album found-album))
257 (found-title (setq title found-title)))))
258 (emus-make-track artist album title filename)))
260 (defun emus--add-tracks-from-playlist-files ()
262 (dolist (filename (emus-get-playlist-files))
263 (let ((artist "Playlists")
264 (album (file-name-base filename))
266 (lines (split-string (with-temp-buffer
267 (insert-file-contents filename)
271 (pcase (string-trim line)
276 (let display-title (* any))
278 (setq title display-title))
279 ((rx (: string-start (* space) "#"))) ;skip other comments
280 ((rx (let filename (+ any)))
281 (setq tracks (cons (emus-make-track artist album (or title filename) filename)
283 (setq title nil))))))
284 (setq emus-tracks (append emus-tracks (reverse tracks)))))
286 (defun emus--sort-tracks ()
287 "Sort the library tracks according to artist and album.
288 Leaves the track titles unsorted, so they will appear in the order specified
293 (let ((artist1 (emus-track-artist r1))
294 (artist2 (emus-track-artist r2)))
295 (if (string= artist1 artist2)
296 (let ((album1 (emus-track-album r1))
297 (album2 (emus-track-album r2)))
298 (string< album1 album2))
299 (string< artist1 artist2)))))))
301 (defmacro emus--with-library (&rest body)
302 "Evaluate BODY with the library initialized."
304 (unless emus--proc-in-use ,@body)
306 (lambda () ,@body))))
312 (defun emus--suspend-cp ()
313 "Suspend continuous playback."
314 (setq emus-continuous-playback nil))
316 (defun emus--resume-cp ()
317 "Resume continuous playback."
318 (setq emus-continuous-playback t))
320 (defun emus--timestamp (seconds-total)
321 "Produce a timestamp string representation of SECONDS-TOTAL."
322 (let* ((seconds (truncate (mod seconds-total 60)))
323 (minutes (truncate (/ seconds-total 60))))
324 (format "%02d:%02d" minutes seconds)))
326 (defun emus-play-track (track)
327 "Set TRACK as current and start playing."
329 (let ((old-track emus-current-track))
330 (emus-send-cmd "l" (emus-track-file track))
331 (setq emus-state 'playing)
332 (setq emus-current-track track)
333 (setq emus-current-progress (if emus-progress-enabled "" " (progress disabled)"))
336 (lambda (_proc string)
337 (dolist (line (string-split string "\n"))
340 (guard emus-continuous-playback)
341 (guard (eq emus-state 'playing)))
343 ((and (guard emus-progress-enabled)
345 "@I ICY-META: StreamTitle="
346 (let str (+ (not ";")))
348 (message (concat "Emus: Playing stream " str)))
349 ((and (guard emus-progress-enabled)
356 (let left-str (+ (not " ")))
358 (let right-str (+ any)))))
359 (let* ((left (string-to-number left-str))
360 (right (string-to-number right-str))
361 (total (+ left right)))
362 (setq emus-current-progress
364 (emus--timestamp left)
365 (emus--timestamp total)))))
367 (emus--update-track old-track)
368 (emus--update-track track)
370 (emus-goto-current))))
372 (defun emus-select-track (track)
373 "Set TRACK as current, but do not start playing."
375 (let ((old-track emus-current-track))
376 (setq emus-state 'stopped)
377 (setq emus-current-track track)
378 (emus--update-track old-track)
379 (emus--update-track track)
382 (emus-goto-current))))
385 "Stop playback of the current track."
388 (setq emus-state 'stopped)
389 (emus--update-track emus-current-track)
390 (emus-send-cmd "s")))
392 (defun emus-playpause ()
393 "Begin playback of the current track.
394 If the track is already playing, pause playback.
395 If the track is currently paused, resume playback."
398 (when emus-current-track
399 (if (eq emus-state 'stopped)
400 (emus-play-track emus-current-track)
403 ((or 'paused 'stopped) (setq emus-state 'playing))
404 ('playing (setq emus-state 'paused)))
405 (unless (eq emus-state 'paused)))
406 (emus--update-track emus-current-track))))
408 (defun emus-set-volume (pct)
409 "Set the playback volume to PCT %."
411 (setq emus-current-volume pct)
412 (emus-send-cmd "v" (number-to-string pct))))
414 (defun emus-volume-increase-by (delta)
415 "Increase the playback volume by DELTA %."
416 (emus-set-volume (max 0 (min 100 (+ emus-current-volume delta)))))
418 (defun emus-volume-up ()
419 "Increase the playback volume by 10%."
421 (emus-volume-increase-by 10))
423 (defun emus-volume-down ()
424 "Decrease the playback volume by 10%."
426 (emus-volume-increase-by -10))
428 (defun emus--play-adjacent-track (&optional prev)
429 "Play the next track in the library, or the previous if PREV is non-nil."
431 (let ((idx (seq-position emus-tracks emus-current-track))
432 (offset (if prev -1 +1)))
434 (let ((next-track (elt emus-tracks (+ idx offset))))
436 (if (eq emus-state 'playing)
437 (emus-play-track next-track)
438 (emus-select-track next-track))
439 (error "Track does not exist")))
440 (error "No track selected")))))
442 (defun emus--play-adjacent-album (&optional prev)
443 "Play the first track of the next album in the library.
444 If PREV is non-nil, plays the last track of the previous album."
446 (let ((idx (seq-position emus-tracks emus-current-track)))
448 (let* ((search-list (if prev
449 (reverse (seq-subseq emus-tracks 0 idx))
450 (seq-subseq emus-tracks (+ idx 1))))
451 (current-album (emus-track-album emus-current-track))
452 (next-track (seq-some (lambda (r)
453 (if (string= (emus-track-album r)
459 (if (eq emus-state 'playing)
460 (emus-play-track next-track)
461 (emus-select-track next-track))
462 (error "Track does not exist")))
463 (error "No track selected")))))
465 (defun emus-play-next ()
466 "Play the next track in the library."
468 (emus--play-adjacent-track))
470 (defun emus-play-prev ()
471 "Play the previous track in the library."
473 (emus--play-adjacent-track t))
475 (defun emus-play-next-album ()
476 "Play the first track of the next album in the library."
478 (emus--play-adjacent-album))
480 (defun emus-play-prev-album ()
481 "Play the last track of the previous album in the library."
483 (emus--play-adjacent-album t))
485 (defun emus-jump (seconds)
486 "Jump forward in current track by SECONDS seconds."
488 (emus-send-cmd "jump" (format "%+ds" seconds))))
490 (defun emus-jump-10s-forward ()
491 "Jump 10 seconds forward in current track."
495 (defun emus-jump-10s-backward ()
496 "Jump 10 seconds backward in current track."
500 (defun emus-jump-1m-forward ()
501 "Jump 1 minute forward in current track."
505 (defun emus-jump-1m-backward ()
506 "Jump 1 minute backward in current track."
510 (defun emus-display-status ()
511 "Display the current playback status in the minibuffer."
515 (concat "Emus: Volume %d%%"
517 ('stopped " [Stopped]")
518 ('paused (format " [Paused%s]" emus-current-progress))
519 ('playing (format " [Playing%s]" emus-current-progress))
523 (if emus-current-track
524 (format "- %.30s (%.20s, %.20s)"
525 (emus-track-title emus-current-track)
526 (emus-track-album emus-current-track)
527 (emus-track-artist emus-current-track))
530 (defun emus-toggle-progress-tracking ()
531 "Enable/disable progress tracking."
533 (setq emus-progress-enabled (not emus-progress-enabled))
534 (if emus-progress-enabled
536 (emus-send-cmd "progress")
537 (setq emus-current-progress ""))
539 (emus-send-cmd "silence")
540 (setq emus-current-progress " (progress diabled)"))))
546 (defun emus--insert-track (track &optional prev-track first)
547 "Insert a button representing TRACK into the current buffer.
549 When provided, PREV-TRACK is used to determine whether to insert additional
550 headers representing the artist or the album title.
552 If non-nil, FIRST indicates that the track is the first in the library
553 and thus requires both artist and album headers."
554 (let* ((artist (emus-track-artist track))
555 (album (emus-track-album track))
556 (title (emus-track-title track))
557 (album-symb (intern (concat artist album)))
558 (help-str (format "mouse-1, RET: Play '%.30s' (%.20s)" title artist))
559 (field (intern album))) ;Allows easy jumping between albums with cursor.
560 (when (or prev-track first)
561 (unless (equal (emus-track-artist prev-track) artist)
563 (propertize artist 'face 'emus-artist)
564 'action #'emus--click-track
569 (insert (propertize "\n"
572 (unless (equal (emus-track-album prev-track) album)
574 (propertize (concat " " album) 'face 'emus-album)
575 'action #'emus--click-track
580 (insert (propertize "\n"
583 (emus-set-track-browser-pos track (point))
584 (let ((is-current (equal track emus-current-track)))
594 (propertize " " 'face 'default))
595 (propertize (format " %s" title)
599 'action #'emus--click-track
603 'invisible album-symb
605 (insert (propertize "\n"
610 'invisible album-symb)))))
612 (defun emus--update-track (track)
613 "Rerender entry for TRACK in emus browser buffer.
614 Used to update browser display when `emus-current-track' and/or `emus-state' changes."
615 (let ((track-pos (emus-track-browser-pos track)))
616 (when (and (get-buffer "*emus*")
617 (emus-track-browser-pos track))
618 (with-current-buffer "*emus*"
619 (let ((inhibit-read-only t)
621 (goto-char track-pos)
622 (search-forward "\n")
623 (delete-region track-pos (point))
624 (goto-char track-pos)
625 (emus--insert-track track)
626 (goto-char old-point))))))
628 (defun emus--render-tracks ()
629 "Render all library tracks in emus browser buffer."
630 (with-current-buffer "*emus*"
631 (let ((inhibit-read-only t)
634 (goto-char (point-min))
635 (let ((prev-track nil))
636 (dolist (track emus-tracks)
637 (emus--insert-track track prev-track (not prev-track))
638 (setq prev-track track)))
639 (goto-char old-pos))))
641 (defun emus--click-track (button)
642 "Begin playback of track indicated by BUTTON."
643 (emus-play-track (button-get button 'emus-track))
644 (emus-display-status))
646 (defun emus-goto-current ()
647 "Move point to the current track in the browser buffer, if available."
649 (when (and (get-buffer "*emus*")
651 (with-current-buffer "*emus*"
652 (goto-char (emus-track-browser-pos emus-current-track)))))
654 (defun emus-browse ()
655 "Switch to *emus* audio library browser."
658 (pop-to-buffer-same-window "*emus*")
660 (emus--render-tracks)
661 (emus-goto-current)))
663 (defun emus-refresh ()
664 "Refresh the emus library."
667 (setq emus-tracks nil)
671 ;;; Playback + status display commands
674 (defun emus-playpause-status ()
675 "Start, pause or resume playback, then display the emus status in the minibuffer."
678 (emus-display-status))
680 (defun emus-stop-status ()
681 "Stop playback, then display the emus status in the minibuffer."
684 (emus-display-status))
686 (defun emus-volume-up-status ()
687 "Increase volume by 10%, then display the emus status in the minibuffer."
690 (emus-display-status))
692 (defun emus-volume-down-status ()
693 "Decrease volume by 10%, then display the emus status in the minibuffer."
696 (emus-display-status))
698 (defun emus-play-next-status ()
699 "Play next track, then display the emus status in the minibuffer."
702 (emus-display-status))
704 (defun emus-play-prev-status ()
705 "Play previous track, then display the emus status in the minibuffer."
708 (emus-display-status))
710 (defun emus-play-next-album-status ()
711 "Play first track of next album, then display the emus status in the minibuffer."
713 (emus-play-next-album)
714 (emus-display-status))
716 (defun emus-play-prev-album-status ()
717 "Play last track of previous album, then display the emus status in the minibuffer."
719 (emus-play-prev-album)
720 (emus-display-status))
722 (defun emus-jump-10s-forward-status ()
723 "Jump 10s forward in current track, then display the emus status in the minibuffer."
725 (emus-jump-10s-forward)
726 (emus-display-status))
728 (defun emus-jump-10s-backward-status ()
729 "Jump 10s backward in current track, then display the emus status in the minibuffer."
731 (emus-jump-10s-backward)
732 (emus-display-status))
734 (defun emus-jump-1m-forward-status ()
735 "Jump 10s forward in current track, then display the emus status in the minibuffer."
737 (emus-jump-1m-forward)
738 (emus-display-status))
740 (defun emus-jump-1m-backward-status ()
741 "Jump 10s backward in current track, then display the emus status in the minibuffer."
743 (emus-jump-1m-backward)
744 (emus-display-status))
746 (defun emus-toggle-progress-status ()
747 "Toggle progress tracking, then display the emus status in the minibuffer."
749 (emus-toggle-progress-tracking)
750 (emus-display-status))
752 (defun emus-goto-current-status ()
753 "Move point to the current track, then display the emus status in the minibuffer."
756 (emus-display-status))
758 (defun emus-refresh-status ()
759 "Refresh the emus library, then display the emus status in the minibuffer."
762 (setq emus-tracks nil)
764 (emus-display-status))
766 (defun emus-restart-browse ()
767 "Restart the emus process, then refresh the browse window."
769 (message "Restarting mpg123.")
771 (run-at-time 0.1 nil #'emus-browse)) ;Slight delay to wait for kill signal to take effect
773 (defun emus-restart-status ()
774 "Restart the emus process, then display the status."
776 (message "Restarting mpg123.")
778 (run-at-time 0.1 nil #'emus-display-status)) ;Slight delay to wait for kill signal to take effect
781 (defvar emus-browser-mode-map
782 (let ((map (make-sparse-keymap)))
783 (define-key map (kbd "SPC") 'emus-playpause-status)
784 (define-key map (kbd "o") 'emus-stop-status)
785 (define-key map (kbd "+") 'emus-volume-up-status)
786 (define-key map (kbd "=") 'emus-volume-up-status)
787 (define-key map (kbd "-") 'emus-volume-down-status)
788 (define-key map (kbd "R") 'emus-refresh-status)
789 (define-key map (kbd "n") 'emus-play-next-status)
790 (define-key map (kbd "p") 'emus-play-prev-status)
791 (define-key map (kbd "N") 'emus-play-next-album-status)
792 (define-key map (kbd "P") 'emus-play-prev-album-status)
793 (define-key map (kbd ",") 'emus-jump-10s-backward-status)
794 (define-key map (kbd ".") 'emus-jump-10s-forward-status)
795 (define-key map (kbd "<") 'emus-jump-1m-backward-status)
796 (define-key map (kbd ">") 'emus-jump-1m-forward-status)
797 (define-key map (kbd "c") 'emus-goto-current-status)
798 (define-key map (kbd "#") 'emus-toggle-progress-status)
799 (define-key map (kbd "!") 'emus-restart-browse)
800 (when (fboundp 'evil-define-key*)
801 (evil-define-key* 'motion map
802 (kbd "SPC") 'emus-playpause-status
803 (kbd "o") 'emus-stop-status
804 (kbd "+") 'emus-volume-up-status
805 (kbd "=") 'emus-volume-up-status
806 (kbd "-") 'emus-volume-down-status
807 (kbd "R") 'emus-refresh-status
808 (kbd "n") 'emus-play-next-status
809 (kbd "p") 'emus-play-prev-status
810 (kbd "N") 'emus-play-next-album-status
811 (kbd "P") 'emus-play-prev-album-status
812 (kbd ",") 'emus-jump-10s-backward-status
813 (kbd ".") 'emus-jump-10s-forward-status
814 (kbd "<") 'emus-jump-1m-backward-status
815 (kbd ">") 'emus-jump-1m-forward-status
816 (kbd "c") 'emus-goto-current-status
817 (kbd "#") 'emus-toggle-progress-status
818 (kbd "!") #'emus-restart-browse))
820 "Keymap for emus browser.")
822 (define-derived-mode emus-browser-mode special-mode "emus-browser"
823 "Major mode for EMUS music player file browser."
824 (setq-local buffer-invisibility-spec nil))
826 (when (fboundp 'evil-set-initial-state)
827 (evil-set-initial-state 'emus-browser-mode 'motion))
829 ;;; emus.el ends here