2 * Copyright (C) 2012 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file play.c Paraslash's standalone player. */
14 #include "recv_cmd.lsg.h"
15 #include "play_cmd.lsg.h"
16 #include "write_cmd.lsg.h"
21 #include "buffer_tree.h"
32 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
33 * para_play creates two further tasks: The play task and the i9e task. It is
34 * important whether a function can be called in the context of para_play or
35 * i9e or both. As a rule, all command handlers are called only in i9e context via
36 * the line handler (input mode) or the key handler (command mode) below.
38 * Playlist handling is done exclusively in play context.
41 /** Array of error strings. */
44 static struct lls_parse_result *play_lpr;
46 #define CMD_PTR (lls_cmd(0, play_suite))
47 #define OPT_RESULT(_name) \
48 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
49 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
50 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
51 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
54 * Describes a request to change the state of para_play.
56 * There is only one variable of this type: \a rq of the global play task
57 * structure. Command handlers only set this variable and the post_select()
58 * function of the play task investigates its value during each iteration of
59 * the scheduler run and performs the actual work.
61 enum state_change_request_type {
62 /** Everybody is happy. */
64 /** Stream must be repositioned (com_jmp(), com_ff()). */
66 /** New file should be loaded (com_next()). */
68 /** Someone wants us for dead (com_quit()). */
74 /* A bit array of invalid files (those will be skipped). */
76 /* The file which is currently open. */
77 unsigned current_file;
78 /* When to update the status again. */
79 struct timeval next_update;
81 /* Root of the buffer tree for command and status output. */
82 struct btr_node *btrn;
84 /* The decoding machinery. */
85 struct receiver_node rn;
86 struct filter_node fn;
87 struct writer_node wn;
89 /* See comment to enum state_change_request_type above */
90 enum state_change_request_type rq;
91 /* only relevant if rq == CRT_FILE_CHANGE */
94 bg: read lines at prompt, fg: display status and wait
99 /* We have the *intention* to play. Set by com_play(). */
102 /* as returned by afh_recv->open() */
103 int audio_format_num;
105 /* retrieved via the btr exec mechanism */
106 long unsigned start_chunk;
107 long unsigned seconds;
108 long unsigned num_chunks;
112 typedef int (*play_cmd_handler_t)(struct play_task *pt,
113 struct lls_parse_result *lpr);
114 struct play_command_info {
115 play_cmd_handler_t handler;
117 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
118 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
119 .handler = com_ ## _cmd \
122 static int loglevel = LL_WARNING;
124 /** The log function which writes log messages to stderr. */
125 INIT_STDERR_LOGGING(loglevel);
127 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
129 static struct sched sched = {.max_fileno = 0};
130 static struct play_task play_task;
132 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
133 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
135 static unsigned *shuffle_map;
137 static const char *get_playlist_file(unsigned idx)
139 return lls_input(shuffle_map[idx], play_lpr);
142 static void handle_help_flags(void)
146 if (OPT_GIVEN(DETAILED_HELP))
147 help = lls_long_help(CMD_PTR);
148 else if (OPT_GIVEN(HELP))
149 help = lls_short_help(CMD_PTR);
152 printf("%s\n", help);
157 static void parse_config_or_die(int argc, char *argv[])
159 const struct lls_command *cmd = CMD_PTR;
161 char *cf, *errctx, **cf_argv;
162 struct lls_parse_result *cf_lpr, *merged_lpr;
167 ret = lls(lls_parse(argc, argv, cmd, &play_lpr, &errctx));
170 loglevel = OPT_UINT32_VAL(LOGLEVEL);
171 version_handle_flag("play", OPT_GIVEN(VERSION));
173 if (OPT_GIVEN(CONFIG_FILE))
174 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
176 char *home = para_homedir();
177 cf = make_message("%s/.paraslash/play.conf", home);
180 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
182 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
184 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
189 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
190 para_munmap(map, sz);
194 ret = lls(lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx));
195 lls_free_argv(cf_argv);
198 ret = lls(lls_merge(play_lpr, cf_lpr, cmd, &merged_lpr, &errctx));
199 lls_free_parse_result(cf_lpr, cmd);
202 lls_free_parse_result(play_lpr, cmd);
203 play_lpr = merged_lpr;
204 loglevel = OPT_UINT32_VAL(LOGLEVEL);
206 ret = lls(lls_check_arg_count(play_lpr, 1, INT_MAX, &errctx));
209 num_kmas = OPT_GIVEN(KEY_MAP);
210 for (i = 0; i < num_kmas; i++) {
211 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
212 if (*kma && strchr(kma + 1, ':'))
214 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
222 lls_free_parse_result(play_lpr, cmd);
225 PARA_EMERG_LOG("%s\n", errctx);
227 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
231 static char get_playback_state(struct play_task *pt)
234 case CRT_NONE: return pt->playing? 'P' : 'U';
235 case CRT_REPOS: return 'R';
236 case CRT_FILE_CHANGE: return 'F';
237 case CRT_TERM_RQ: return 'X';
242 static long unsigned get_play_time(struct play_task *pt)
244 char state = get_playback_state(pt);
245 long unsigned result;
247 if (state != 'P' && state != 'U')
249 if (pt->num_chunks == 0 || pt->seconds == 0)
251 /* where the stream started (in seconds) */
252 result = pt->start_chunk * pt->seconds / pt->num_chunks;
253 if (pt->wn.btrn) { /* Add the uptime of the writer node */
254 struct timeval diff = {.tv_sec = 0}, wstime;
255 btr_get_node_start(pt->wn.btrn, &wstime);
256 if (wstime.tv_sec > 0)
257 tv_diff(now, &wstime, &diff);
258 result += diff.tv_sec;
260 result = PARA_MIN(result, pt->seconds);
261 result = PARA_MAX(result, 0UL);
266 static void wipe_receiver_node(struct play_task *pt)
268 PARA_NOTICE_LOG("cleaning up receiver node\n");
269 btr_remove_node(&pt->rn.btrn);
270 AFH_RECV->close(&pt->rn);
271 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
272 memset(&pt->rn, 0, sizeof(struct receiver_node));
275 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
276 static int get_playback_error(struct play_task *pt)
282 err = task_status(pt->wn.task);
285 if (task_status(pt->fn.task) >= 0)
287 if (task_status(pt->rn.task) >= 0)
289 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
290 || err == -E_WRITE_COMMON_EOF)
295 static int eof_cleanup(struct play_task *pt)
297 const struct filter *decoder;
298 const struct writer *w = writer_get(-1); /* default writer */
301 ret = get_playback_error(pt);
304 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
305 task_reap(&pt->wn.task);
307 btr_remove_node(&pt->wn.btrn);
308 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
309 memset(&pt->wn, 0, sizeof(struct writer_node));
311 decoder = filter_get(pt->fn.filter_num);
312 task_reap(&pt->fn.task);
314 decoder->close(&pt->fn);
315 btr_remove_node(&pt->fn.btrn);
317 memset(&pt->fn, 0, sizeof(struct filter_node));
319 task_reap(&pt->rn.task);
320 btr_remove_node(&pt->rn.btrn);
322 * On eof (ret > 0), we do not wipe the receiver node struct until a
323 * new file is loaded because we still need it for jumping around when
327 wipe_receiver_node(pt);
331 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
333 return para_random(100) - 50;
336 static void init_shuffle_map(void)
338 unsigned n, num_inputs = lls_num_inputs(play_lpr);
339 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
340 for (n = 0; n < num_inputs; n++)
342 if (!OPT_GIVEN(RANDOMIZE))
345 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
348 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
350 return btr_new_node(&(struct btr_node_description)
351 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
352 .handler = AFH_RECV->execute));
355 static int open_new_file(struct play_task *pt)
358 const char *path = get_playlist_file(pt->next_file);
359 char *tmp = para_strdup(path), *errctx;
360 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
362 PARA_NOTICE_LOG("next file: %s\n", path);
363 wipe_receiver_node(pt);
365 pt->rn.btrn = new_recv_btrn(&pt->rn);
366 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
367 &pt->rn.lpr, &errctx));
370 pt->rn.receiver = AFH_RECV;
371 ret = AFH_RECV->open(&pt->rn);
373 PARA_ERROR_LOG("could not open %s\n", path);
376 pt->audio_format_num = ret;
378 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
380 pt->afhi_txt = make_message("[afhi command failed]\n");
381 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
386 ret = para_atoi32(tmp, &x);
387 pt->seconds = ret < 0? 1 : x;
391 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
396 ret = para_atoi32(tmp, &x);
397 pt->num_chunks = ret < 0? 1 : x;
403 wipe_receiver_node(pt);
407 static int load_file(struct play_task *pt)
412 const struct filter *decoder;
413 static struct lls_parse_result *filter_lpr, *writer_lpr;
415 btr_remove_node(&pt->rn.btrn);
416 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
417 ret = open_new_file(pt);
421 pt->rn.btrn = new_recv_btrn(&pt->rn);
422 sprintf(buf, "repos %lu", pt->start_chunk);
423 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
425 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
430 /* set up decoding filter */
431 af = audio_format_name(pt->audio_format_num);
432 tmp = make_message("%sdec", af);
433 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
437 pt->fn.filter_num = ret;
438 pt->fn.lpr = filter_lpr;
439 decoder = filter_get(ret);
440 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
441 EMBRACE(.name = filter_name(pt->fn.filter_num),
442 .parent = pt->rn.btrn, .handler = decoder->execute,
443 .context = &pt->fn));
445 decoder->open(&pt->fn);
446 PARA_INFO_LOG("buffer tree:\n");
447 btr_log_tree(pt->rn.btrn, LL_INFO);
449 /* setup default writer */
450 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
451 pt->wn.lpr = writer_lpr;
452 /* success, register tasks */
453 pt->rn.task = task_register(
454 &(struct task_info) {
455 .name = lls_command_name(AFH_RECV_CMD),
456 .pre_select = AFH_RECV->pre_select,
457 .post_select = AFH_RECV->post_select,
460 sprintf(buf, "%s decoder", af);
461 pt->fn.task = task_register(
462 &(struct task_info) {
464 .pre_select = decoder->pre_select,
465 .post_select = decoder->post_select,
468 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
471 wipe_receiver_node(pt);
475 static int next_valid_file(struct play_task *pt)
477 int i, j = pt->current_file;
478 unsigned num_inputs = lls_num_inputs(play_lpr);
480 for (i = 0; i < num_inputs; i++) {
481 j = (j + 1) % num_inputs;
485 return -E_NO_VALID_FILES;
488 static int load_next_file(struct play_task *pt)
493 if (pt->rq == CRT_NONE) {
495 ret = next_valid_file(pt);
499 } else if (pt->rq == CRT_REPOS)
500 pt->next_file = pt->current_file;
503 PARA_ERROR_LOG("%s: marking file as invalid\n",
504 para_strerror(-ret));
505 pt->invalid[pt->next_file] = true;
509 pt->current_file = pt->next_file;
514 static void kill_stream(struct play_task *pt)
517 task_notify(pt->wn.task, E_EOF);
522 /* only called from com_prev(), nec. only if we have readline */
523 static int previous_valid_file(struct play_task *pt)
525 int i, j = pt->current_file;
526 unsigned num_inputs = lls_num_inputs(play_lpr);
528 for (i = 0; i < num_inputs; i++) {
535 return -E_NO_VALID_FILES;
538 #include "interactive.h"
541 * Define the default (internal) key mappings and helper functions to get the
542 * key sequence or the command from a key id, which is what we obtain from
543 * i9e/readline when the key is pressed.
545 * In some of these helper functions we could return pointers to the constant
546 * arrays defined below. However, for others we can not, so let's better be
547 * consistent and allocate all returned strings on the heap.
550 #define INTERNAL_KEYMAP_ENTRIES \
551 KEYMAP_ENTRY("^", "jmp 0"), \
552 KEYMAP_ENTRY("1", "jmp 10"), \
553 KEYMAP_ENTRY("2", "jmp 21"), \
554 KEYMAP_ENTRY("3", "jmp 32"), \
555 KEYMAP_ENTRY("4", "jmp 43"), \
556 KEYMAP_ENTRY("5", "jmp 54"), \
557 KEYMAP_ENTRY("6", "jmp 65"), \
558 KEYMAP_ENTRY("7", "jmp 76"), \
559 KEYMAP_ENTRY("8", "jmp 87"), \
560 KEYMAP_ENTRY("9", "jmp 98"), \
561 KEYMAP_ENTRY("+", "next"), \
562 KEYMAP_ENTRY("-", "prev"), \
563 KEYMAP_ENTRY(":", "bg"), \
564 KEYMAP_ENTRY("i", "info"), \
565 KEYMAP_ENTRY("l", "ls"), \
566 KEYMAP_ENTRY("s", "play"), \
567 KEYMAP_ENTRY("p", "pause"), \
568 KEYMAP_ENTRY("q", "quit"), \
569 KEYMAP_ENTRY("?", "help"), \
570 KEYMAP_ENTRY("\033[D", "ff -10"), \
571 KEYMAP_ENTRY("\033[C", "ff 10"), \
572 KEYMAP_ENTRY("\033[A", "ff 60"), \
573 KEYMAP_ENTRY("\033[B", "ff -60"), \
575 #define KEYMAP_ENTRY(a, b) a
576 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
578 #define KEYMAP_ENTRY(a, b) b
579 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
581 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
582 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
583 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
585 static inline bool is_internal_key(int key)
587 return key < NUM_INTERNALLY_MAPPED_KEYS;
590 /* for internal keys, the key id is just the array index. */
591 static inline int get_internal_key_map_idx(int key)
593 assert(is_internal_key(key));
598 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
599 * difference is the index to the array of user defined key maps.
601 static inline int get_user_key_map_idx(int key)
603 assert(!is_internal_key(key));
604 return key - NUM_INTERNALLY_MAPPED_KEYS;
607 static inline int get_key_map_idx(int key)
609 return is_internal_key(key)?
610 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
613 static inline const char *get_user_key_map_arg(int key)
615 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
618 static inline char *get_internal_key_map_seq(int key)
620 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
623 static char *get_user_key_map_seq(int key)
625 const char *kma = get_user_key_map_arg(key);
626 const char *p = strchr(kma + 1, ':');
633 result = para_malloc(len + 1);
634 memcpy(result, kma, len);
639 static char *get_key_map_seq(int key)
641 return is_internal_key(key)?
642 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
645 static char *get_key_map_seq_safe(int key)
647 const char hex[] = "0123456789abcdef";
648 char *seq = get_key_map_seq(key), *sseq;
649 size_t n, len = strlen(seq);
651 if (len == 1 && isprint(*seq))
653 sseq = para_malloc(2 + 2 * len + 1);
656 for (n = 0; n < len; n++) {
657 uint8_t val = (seq[n] & 0xf0) >> 4;
658 sseq[2 + 2 * n] = hex[val];
660 sseq[2 + 2 * n + 1] = hex[val];
663 sseq[2 + 2 * n] = '\0';
667 static inline char *get_internal_key_map_cmd(int key)
669 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
672 static char *get_user_key_map_cmd(int key)
674 const char *kma = get_user_key_map_arg(key);
675 const char *p = strchr(kma + 1, ':');
679 return para_strdup(p + 1);
682 static char *get_key_map_cmd(int key)
684 return is_internal_key(key)?
685 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
688 static char **get_mapped_keyseqs(void)
693 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
694 FOR_EACH_MAPPED_KEY(i) {
695 char *seq = get_key_map_seq(i);
702 static struct i9e_completer pp_completers[];
704 I9E_DUMMY_COMPLETER(jmp);
705 I9E_DUMMY_COMPLETER(next);
706 I9E_DUMMY_COMPLETER(prev);
707 I9E_DUMMY_COMPLETER(fg);
708 I9E_DUMMY_COMPLETER(bg);
709 I9E_DUMMY_COMPLETER(ls);
710 I9E_DUMMY_COMPLETER(info);
711 I9E_DUMMY_COMPLETER(play);
712 I9E_DUMMY_COMPLETER(pause);
713 I9E_DUMMY_COMPLETER(stop);
714 I9E_DUMMY_COMPLETER(tasks);
715 I9E_DUMMY_COMPLETER(quit);
716 I9E_DUMMY_COMPLETER(ff);
718 static void help_completer(struct i9e_completion_info *ci,
719 struct i9e_completion_result *result)
721 result->matches = i9e_complete_commands(ci->word, pp_completers);
724 I9E_DUMMY_COMPLETER(SUPERCOMMAND_UNAVAILABLE);
725 static struct i9e_completer pp_completers[] = {
726 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
727 .completer = _name ## _completer}
728 LSG_PLAY_CMD_SUBCOMMANDS
729 #undef LSG_PLAY_CMD_CMD
733 static void attach_stdout(struct play_task *pt, const char *name)
737 pt->btrn = btr_new_node(&(struct btr_node_description)
738 EMBRACE(.name = name));
739 i9e_attach_to_stdout(pt->btrn);
742 static void detach_stdout(struct play_task *pt)
744 btr_remove_node(&pt->btrn);
747 static int com_quit(struct play_task *pt,
748 __a_unused struct lls_parse_result *lpr)
750 pt->rq = CRT_TERM_RQ;
753 EXPORT_PLAY_CMD_HANDLER(quit);
755 static int com_help(struct play_task *pt, struct lls_parse_result *lpr)
760 const struct lls_command *cmd;
762 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
765 PARA_ERROR_LOG("%s\n", errctx);
769 if (lls_num_inputs(lpr) == 0) {
770 if (pt->background) {
771 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
772 sz = xasprintf(&buf, "%s\t%s\n",
773 lls_command_name(cmd), lls_purpose(cmd));
774 btr_add_output(buf, sz, pt->btrn);
778 FOR_EACH_MAPPED_KEY(i) {
779 bool internal = is_internal_key(i);
780 int idx = get_key_map_idx(i);
781 char *seq = get_key_map_seq_safe(i);
782 char *kmc = get_key_map_cmd(i);
783 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
784 internal? "internal" : "user-defined",
786 btr_add_output(buf, sz, pt->btrn);
792 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
796 PARA_ERROR_LOG("%s\n", errctx);
800 cmd = lls_cmd(ret, play_cmd_suite);
801 buf = lls_long_help(cmd);
803 btr_add_output(buf, strlen(buf), pt->btrn);
806 EXPORT_PLAY_CMD_HANDLER(help);
808 static int com_info(struct play_task *pt,
809 __a_unused struct lls_parse_result *lpr)
813 static char dflt[] = "[no information available]";
815 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
816 pt->current_file, get_playlist_file(pt->current_file));
817 btr_add_output(buf, sz, pt->btrn);
818 buf = pt->afhi_txt? pt->afhi_txt : dflt;
819 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
822 EXPORT_PLAY_CMD_HANDLER(info);
824 static void list_file(struct play_task *pt, int num)
829 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
830 "*" : " ", num, get_playlist_file(num));
831 btr_add_output(buf, sz, pt->btrn);
834 static int com_tasks(struct play_task *pt,
835 __a_unused struct lls_parse_result *lpr)
841 buf = get_task_list(&sched);
842 btr_add_output(buf, strlen(buf), pt->btrn);
843 state = get_playback_state(pt);
844 sz = xasprintf(&buf, "state: %c\n", state);
845 btr_add_output(buf, sz, pt->btrn);
848 EXPORT_PLAY_CMD_HANDLER(tasks);
850 static int com_ls(struct play_task *pt,
851 __a_unused struct lls_parse_result *lpr)
854 unsigned num_inputs = lls_num_inputs(play_lpr);
856 for (i = 0; i < num_inputs; i++)
860 EXPORT_PLAY_CMD_HANDLER(ls);
862 static int com_play(struct play_task *pt, struct lls_parse_result *lpr)
868 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
871 PARA_ERROR_LOG("%s\n", errctx);
875 state = get_playback_state(pt);
876 if (lls_num_inputs(lpr) == 0) {
879 pt->next_file = pt->current_file;
884 ret = para_atoi32(lls_input(0, lpr), &x);
887 if (x < 0 || x >= lls_num_inputs(play_lpr))
888 return -ERRNO_TO_PARA_ERROR(EINVAL);
891 pt->rq = CRT_FILE_CHANGE;
894 EXPORT_PLAY_CMD_HANDLER(play);
896 static int com_pause(struct play_task *pt,
897 __a_unused struct lls_parse_result *lpr)
900 long unsigned seconds, ss;
902 state = get_playback_state(pt);
906 seconds = get_play_time(pt);
910 ss = seconds * pt->num_chunks / pt->seconds + 1;
911 ss = PARA_MAX(ss, 0UL);
912 ss = PARA_MIN(ss, pt->num_chunks);
913 pt->start_chunk = ss;
917 EXPORT_PLAY_CMD_HANDLER(pause);
919 static int com_prev(struct play_task *pt,
920 __a_unused struct lls_parse_result *lpr)
924 ret = previous_valid_file(pt);
929 pt->rq = CRT_FILE_CHANGE;
933 EXPORT_PLAY_CMD_HANDLER(prev);
935 static int com_next(struct play_task *pt,
936 __a_unused struct lls_parse_result *lpr)
940 ret = next_valid_file(pt);
945 pt->rq = CRT_FILE_CHANGE;
949 EXPORT_PLAY_CMD_HANDLER(next);
951 static int com_fg(struct play_task *pt,
952 __a_unused struct lls_parse_result *lpr)
954 pt->background = false;
957 EXPORT_PLAY_CMD_HANDLER(fg);
959 static int com_bg(struct play_task *pt,
960 __a_unused struct lls_parse_result *lpr)
962 pt->background = true;
965 EXPORT_PLAY_CMD_HANDLER(bg);
967 static int com_jmp(struct play_task *pt, struct lls_parse_result *lpr)
973 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
976 PARA_ERROR_LOG("%s\n", errctx);
980 ret = para_atoi32(lls_input(0, lpr), &percent);
983 if (percent < 0 || percent > 100)
984 return -ERRNO_TO_PARA_ERROR(EINVAL);
986 return com_next(pt, NULL);
987 if (pt->playing && !pt->fn.btrn)
989 pt->start_chunk = percent * pt->num_chunks / 100;
996 EXPORT_PLAY_CMD_HANDLER(jmp);
998 static int com_ff(struct play_task *pt, struct lls_parse_result *lpr)
1004 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
1007 PARA_ERROR_LOG("%s\n", errctx);
1011 ret = para_atoi32(lls_input(0, lpr), &seconds);
1014 if (pt->playing && !pt->fn.btrn)
1016 seconds += get_play_time(pt);
1017 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
1018 seconds = PARA_MAX(seconds, 0);
1019 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
1020 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
1021 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1028 EXPORT_PLAY_CMD_HANDLER(ff);
1030 static int run_command(char *line, struct play_task *pt)
1034 char *errctx = NULL;
1035 const struct play_command_info *pci;
1036 struct lls_parse_result *lpr;
1037 const struct lls_command *cmd;
1039 attach_stdout(pt, __FUNCTION__);
1040 ret = create_argv(line, " ", &argv);
1046 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1049 cmd = lls_cmd(ret, play_cmd_suite);
1050 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1053 pci = lls_user_data(cmd);
1054 ret = pci->handler(pt, lpr);
1055 lls_free_parse_result(lpr, cmd);
1058 PARA_ERROR_LOG("%s\n", errctx);
1064 static int play_i9e_line_handler(char *line)
1066 return run_command(line, &play_task);
1069 static int play_i9e_key_handler(int key)
1071 struct play_task *pt = &play_task;
1072 int idx = get_key_map_idx(key);
1073 char *seq = get_key_map_seq(key);
1074 char *cmd = get_key_map_cmd(key);
1075 bool internal = is_internal_key(key);
1077 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1078 key, internal? "internal" : "user-defined",
1080 run_command(cmd, pt);
1083 pt->next_update = *now;
1087 static struct i9e_client_info ici = {
1089 .prompt = "para_play> ",
1090 .line_handler = play_i9e_line_handler,
1091 .key_handler = play_i9e_key_handler,
1092 .completers = pp_completers,
1095 static void sigint_handler(int sig)
1097 play_task.background = true;
1098 i9e_signal_dispatch(sig);
1102 * We start with para_log() set to the standard log function which writes to
1103 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1106 static void session_open(struct play_task *pt)
1110 struct sigaction act;
1112 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1113 if (OPT_GIVEN(HISTORY_FILE))
1114 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1116 char *home = para_homedir();
1117 history_file = make_message("%s/.paraslash/play.history",
1121 ici.history_file = history_file;
1122 ici.loglevel = loglevel;
1124 act.sa_handler = sigint_handler;
1125 sigemptyset(&act.sa_mask);
1127 sigaction(SIGINT, &act, NULL);
1128 act.sa_handler = i9e_signal_dispatch;
1129 sigemptyset(&act.sa_mask);
1131 sigaction(SIGWINCH, &act, NULL);
1132 sched.select_function = i9e_select;
1134 ici.bound_keyseqs = get_mapped_keyseqs();
1135 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1136 EMBRACE(.name = __FUNCTION__));
1137 ret = i9e_open(&ici, &sched);
1146 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1150 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1155 if (btr_get_output_queue_size(pt->btrn) > 0)
1157 if (btr_get_input_queue_size(pt->btrn) > 0)
1160 ie9_print_status_bar(str, len);
1164 * If we are about to die we must call i9e_close() to reset the terminal.
1165 * However, i9e_close() must be called in *this* context, i.e. from
1166 * play_task.post_select() rather than from i9e_post_select(), because
1167 * otherwise i9e would access freed memory upon return. So the play task must
1168 * stay alive until the i9e task terminates.
1170 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1171 * and reschedule. In the next iteration, i9e->post_select returns an error and
1172 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1173 * are allowed to call i9e_close() and terminate as well.
1175 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1182 attach_stdout(pt, __FUNCTION__);
1183 ret = i9e_get_error();
1187 para_log = stderr_log;
1188 free(ici.history_file);
1191 if (get_playback_state(pt) == 'X')
1192 i9e_signal_dispatch(SIGTERM);
1196 #else /* HAVE_READLINE */
1198 static int session_post_select(struct sched *s, struct play_task *pt)
1202 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1204 if (read(STDIN_FILENO, &c, 1))
1210 static void session_open(__a_unused struct play_task *pt)
1214 static void session_update_time_string(__a_unused struct play_task *pt,
1215 char *str, __a_unused unsigned len)
1217 printf("\r%s ", str);
1220 #endif /* HAVE_READLINE */
1222 static void play_pre_select(struct sched *s, void *context)
1224 struct play_task *pt = context;
1227 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1228 state = get_playback_state(pt);
1229 if (state == 'R' || state == 'F' || state == 'X')
1230 return sched_min_delay(s);
1231 sched_request_barrier_or_min_delay(&pt->next_update, s);
1234 static unsigned get_time_string(struct play_task *pt, char **result)
1236 int seconds, length;
1237 char state = get_playback_state(pt);
1239 /* do not return anything if things are about to change */
1240 if (state != 'P' && state != 'U') {
1244 length = pt->seconds;
1246 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1247 seconds = get_play_time(pt);
1248 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1252 (length - seconds) / 60,
1253 (length - seconds) % 60,
1254 length? (seconds * 100 + length / 2) / length : 0,
1257 get_playlist_file(pt->current_file)
1261 static int play_post_select(struct sched *s, void *context)
1263 struct play_task *pt = context;
1266 ret = eof_cleanup(pt);
1268 pt->rq = CRT_TERM_RQ;
1271 ret = session_post_select(s, pt);
1274 if (!pt->wn.btrn && !pt->fn.btrn) {
1275 char state = get_playback_state(pt);
1276 if (state == 'P' || state == 'R' || state == 'F') {
1277 PARA_NOTICE_LOG("state: %c\n", state);
1278 ret = load_next_file(pt);
1280 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1281 pt->rq = CRT_TERM_RQ;
1285 pt->next_update = *now;
1288 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1290 unsigned len = get_time_string(pt, &str);
1291 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1293 session_update_time_string(pt, str, len);
1295 tv_add(now, &delay, &pt->next_update);
1303 * The main function of para_play.
1305 * \param argc Standard.
1306 * \param argv Standard.
1308 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1310 int main(int argc, char *argv[])
1313 struct play_task *pt = &play_task;
1314 unsigned num_inputs;
1316 /* needed this early to make help work */
1319 sched.default_timeout.tv_sec = 5;
1320 parse_config_or_die(argc, argv);
1323 num_inputs = lls_num_inputs(play_lpr);
1325 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1326 pt->rq = CRT_FILE_CHANGE;
1327 pt->current_file = num_inputs - 1;
1329 pt->task = task_register(&(struct task_info){
1331 .pre_select = play_pre_select,
1332 .post_select = play_post_select,
1335 ret = schedule(&sched);
1336 sched_shutdown(&sched);
1338 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1339 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;