1 /* Copyright (C) 2012 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file play.c Paraslash's standalone player. */
9 #include "recv_cmd.lsg.h"
10 #include "filter_cmd.lsg.h"
11 #include "play_cmd.lsg.h"
12 #include "write_cmd.lsg.h"
18 #include "buffer_tree.h"
28 /** Array of error strings. */
31 static struct lls_parse_result *play_lpr;
33 #define CMD_PTR (lls_cmd(0, play_suite))
34 #define OPT_RESULT(_name) \
35 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
36 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
37 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
38 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
41 * Describes a request to change the state of para_play.
43 * There is only one variable of this type: \a rq of the global play task
44 * structure. Command handlers only set this variable and the post_monitor()
45 * function of the play task investigates its value during each iteration of
46 * the scheduler run and performs the actual work.
48 enum state_change_request_type {
49 /** Everybody is happy. */
51 /** Stream must be repositioned (com_jmp(), com_ff()). */
53 /** New file should be loaded (com_next()). */
55 /** Someone wants us for dead (com_quit()). */
61 /* A bit array of invalid files (those will be skipped). */
63 /* The file which is currently open. */
64 unsigned current_file;
65 /* When to update the status again. */
66 struct timeval next_update;
68 /* Root of the buffer tree for command and status output. */
69 struct btr_node *btrn;
71 /* The decoding machinery. */
72 struct receiver_node rn;
73 struct filter_node fn;
74 struct writer_node wn;
76 /* See comment to enum \ref state_change_request_type above. */
77 enum state_change_request_type rq;
78 /* only relevant if rq == CRT_FILE_CHANGE */
81 bg: read lines at prompt, fg: display status and wait
86 /* We have the *intention* to play. Set by com_play(). */
89 /* as returned by afh_recv->open() */
92 /* retrieved via the btr exec mechanism */
93 long unsigned start_chunk;
94 long unsigned seconds;
95 long unsigned num_chunks;
99 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
100 struct play_command_info {
101 play_cmd_handler_t handler;
104 static int loglevel = LL_WARNING;
106 /** The log function which writes log messages to stderr. */
107 INIT_STDERR_LOGGING(loglevel);
109 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
111 static struct sched sched;
112 static struct play_task play_task, *pt = &play_task;
114 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
115 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
117 static unsigned *shuffle_map;
119 static const char *get_playlist_file(unsigned idx)
121 return lls_input(shuffle_map[idx], play_lpr);
124 static void handle_help_flags(void)
128 if (OPT_GIVEN(DETAILED_HELP))
129 help = lls_long_help(CMD_PTR);
130 else if (OPT_GIVEN(HELP) || lls_num_inputs(play_lpr) == 0)
131 help = lls_short_help(CMD_PTR);
134 printf("%s\n", help);
139 static void parse_config_or_die(int argc, char *argv[])
145 ret = lls(lls_parse(argc, argv, CMD_PTR, &play_lpr, &errctx));
148 PARA_EMERG_LOG("%s\n", errctx);
150 PARA_EMERG_LOG("failed to parse command line options: %s\n",
151 para_strerror(-ret));
154 loglevel = OPT_UINT32_VAL(LOGLEVEL);
155 version_handle_flag("play", OPT_GIVEN(VERSION));
156 handle_help_flags(); /* also handles the zero-arg case */
157 ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
158 "play.conf", &play_lpr, CMD_PTR, play_suite, 0 /* flags */);
160 PARA_EMERG_LOG("failed to parse config file: %s\n",
161 para_strerror(-ret));
164 loglevel = OPT_UINT32_VAL(LOGLEVEL);
165 num_kmas = OPT_GIVEN(KEY_MAP);
166 for (i = 0; i < num_kmas; i++) {
167 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
168 if (*kma && strchr(kma + 1, ':'))
170 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
175 static char get_playback_state(void)
178 case CRT_NONE: return pt->playing? 'P' : 'U';
179 case CRT_REPOS: return 'R';
180 case CRT_FILE_CHANGE: return 'F';
181 case CRT_TERM_RQ: return 'X';
186 /* returns number of milliseconds */
187 static long unsigned get_play_time(void)
189 char state = get_playback_state();
190 long unsigned result;
192 if (state != 'P' && state != 'U')
194 if (pt->num_chunks == 0 || pt->seconds == 0)
196 /* where the stream started (in milliseconds) */
197 result = 1000ULL * pt->start_chunk * pt->seconds / pt->num_chunks;
198 if (pt->wn.btrn) { /* Add the uptime of the writer node */
199 struct timeval diff = {.tv_sec = 0}, wstime;
200 btr_get_node_start(pt->wn.btrn, &wstime);
201 if (wstime.tv_sec > 0)
202 tv_diff(now, &wstime, &diff);
203 result += tv2ms(&diff);
205 result = PARA_MIN(result, pt->seconds * 1000);
206 result = PARA_MAX(result, 0UL);
210 static void wipe_receiver_node(void)
212 PARA_NOTICE_LOG("cleaning up receiver node\n");
213 btr_remove_node(&pt->rn.btrn);
214 AFH_RECV->close(&pt->rn);
215 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
216 memset(&pt->rn, 0, sizeof(struct receiver_node));
219 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
220 static int get_playback_error(void)
226 err = task_status(pt->wn.task);
229 if (task_status(pt->fn.task) >= 0)
231 if (task_status(pt->rn.task) >= 0)
238 static int eof_cleanup(void)
240 const struct filter *decoder;
241 const struct writer *w = writer_get(-1); /* default writer */
244 ret = get_playback_error();
247 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
248 task_reap(&pt->wn.task);
250 btr_remove_node(&pt->wn.btrn);
251 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
252 memset(&pt->wn, 0, sizeof(struct writer_node));
254 decoder = filter_get(pt->fn.filter_num);
255 task_reap(&pt->fn.task);
257 decoder->close(&pt->fn);
258 btr_remove_node(&pt->fn.btrn);
259 lls_free_parse_result(pt->fn.lpr, FILTER_CMD(pt->fn.filter_num));
261 memset(&pt->fn, 0, sizeof(struct filter_node));
263 task_reap(&pt->rn.task);
264 btr_remove_node(&pt->rn.btrn);
266 * On eof (ret > 0), we do not wipe the receiver node struct until a
267 * new file is loaded because we still need it for jumping around when
271 wipe_receiver_node();
275 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
277 return para_random(100) - 50;
280 static void init_shuffle_map(void)
282 unsigned n, num_inputs = lls_num_inputs(play_lpr);
283 shuffle_map = arr_alloc(num_inputs, sizeof(unsigned));
284 for (n = 0; n < num_inputs; n++)
286 if (!OPT_GIVEN(RANDOMIZE))
289 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
292 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
294 return btr_new_node(&(struct btr_node_description)
295 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
296 .handler = AFH_RECV->execute));
299 static int open_new_file(void)
302 const char *path = get_playlist_file(pt->next_file);
303 char *tmp = para_strdup(path), *errctx;
304 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
306 PARA_NOTICE_LOG("next file: %s\n", path);
307 wipe_receiver_node();
309 pt->rn.btrn = new_recv_btrn(&pt->rn);
310 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
311 &pt->rn.lpr, &errctx));
314 pt->rn.receiver = AFH_RECV;
315 ret = AFH_RECV->open(&pt->rn);
317 PARA_ERROR_LOG("could not open %s\n", path);
320 pt->audio_format_num = ret;
322 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
324 pt->afhi_txt = make_message("[afhi command failed]\n");
325 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
330 ret = para_atoi32(tmp, &x);
331 pt->seconds = ret < 0? 1 : x;
335 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
340 ret = para_atoi32(tmp, &x);
341 pt->num_chunks = ret < 0? 1 : x;
347 wipe_receiver_node();
351 static int load_file(void)
356 const struct filter *decoder;
357 static struct lls_parse_result *filter_lpr, *writer_lpr;
359 btr_remove_node(&pt->rn.btrn);
360 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
361 ret = open_new_file();
365 pt->rn.btrn = new_recv_btrn(&pt->rn);
366 sprintf(buf, "repos %lu", pt->start_chunk);
367 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
369 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
374 /* set up decoding filter */
375 af = audio_format_name(pt->audio_format_num);
376 tmp = make_message("%sdec", af);
377 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
381 pt->fn.filter_num = ret;
382 pt->fn.lpr = filter_lpr;
383 decoder = filter_get(ret);
384 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
385 EMBRACE(.name = filter_name(pt->fn.filter_num),
386 .parent = pt->rn.btrn, .handler = decoder->execute,
387 .context = &pt->fn));
389 decoder->open(&pt->fn);
390 PARA_INFO_LOG("buffer tree:\n");
391 btr_log_tree(pt->rn.btrn, LL_INFO);
393 /* setup default writer */
394 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
395 pt->wn.lpr = writer_lpr;
396 /* success, register tasks */
397 pt->rn.task = task_register(
398 &(struct task_info) {
399 .name = lls_command_name(AFH_RECV_CMD),
400 .pre_monitor = AFH_RECV->pre_monitor,
401 .post_monitor = AFH_RECV->post_monitor,
404 sprintf(buf, "%s decoder", af);
405 pt->fn.task = task_register(
406 &(struct task_info) {
408 .pre_monitor = decoder->pre_monitor,
409 .post_monitor = decoder->post_monitor,
412 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
415 wipe_receiver_node();
419 static int next_valid_file(void)
421 int i, j = pt->current_file;
422 unsigned num_inputs = lls_num_inputs(play_lpr);
424 if (j == num_inputs - 1) {
425 switch (OPT_UINT32_VAL(END_OF_PLAYLIST)) {
426 case EOP_LOOP: break;
430 case EOP_QUIT: return -E_EOP;
433 for (i = 0; i < num_inputs; i++) {
434 j = (j + 1) % num_inputs;
438 return -E_NO_VALID_FILES;
441 static int load_next_file(void)
446 if (pt->rq == CRT_NONE) {
448 ret = next_valid_file();
452 } else if (pt->rq == CRT_REPOS)
453 pt->next_file = pt->current_file;
456 PARA_ERROR_LOG("%s: marking file as invalid\n",
457 para_strerror(-ret));
458 pt->invalid[pt->next_file] = true;
462 pt->current_file = pt->next_file;
467 static void kill_stream(void)
470 task_notify(pt->wn.task, E_EOF);
475 /* only called from com_prev(), nec. only if we have readline */
476 static int previous_valid_file(void)
478 int i, j = pt->current_file;
479 unsigned num_inputs = lls_num_inputs(play_lpr);
481 for (i = 0; i < num_inputs; i++) {
488 return -E_NO_VALID_FILES;
491 #include "interactive.h"
494 * Define the default (internal) key mappings and helper functions to get the
495 * key sequence or the command from a key id, which is what we obtain from
496 * i9e/readline when the key is pressed.
498 * In some of these helper functions we could return pointers to the constant
499 * arrays defined below. However, for others we can not, so let's better be
500 * consistent and allocate all returned strings on the heap.
503 #define INTERNAL_KEYMAP_ENTRIES \
504 KEYMAP_ENTRY("^", "jmp 0"), \
505 KEYMAP_ENTRY("1", "jmp 10"), \
506 KEYMAP_ENTRY("2", "jmp 21"), \
507 KEYMAP_ENTRY("3", "jmp 32"), \
508 KEYMAP_ENTRY("4", "jmp 43"), \
509 KEYMAP_ENTRY("5", "jmp 54"), \
510 KEYMAP_ENTRY("6", "jmp 65"), \
511 KEYMAP_ENTRY("7", "jmp 76"), \
512 KEYMAP_ENTRY("8", "jmp 87"), \
513 KEYMAP_ENTRY("9", "jmp 98"), \
514 KEYMAP_ENTRY("+", "next"), \
515 KEYMAP_ENTRY("-", "prev"), \
516 KEYMAP_ENTRY(":", "bg"), \
517 KEYMAP_ENTRY("i", "info"), \
518 KEYMAP_ENTRY("l", "ls"), \
519 KEYMAP_ENTRY("s", "play"), \
520 KEYMAP_ENTRY("p", "pause"), \
521 KEYMAP_ENTRY("q", "quit"), \
522 KEYMAP_ENTRY("?", "help"), \
523 KEYMAP_ENTRY("\033[D", "ff -10"), \
524 KEYMAP_ENTRY("\033[C", "ff 10"), \
525 KEYMAP_ENTRY("\033[A", "ff 60"), \
526 KEYMAP_ENTRY("\033[B", "ff -60"), \
528 #define KEYMAP_ENTRY(a, b) a
529 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
531 #define KEYMAP_ENTRY(a, b) b
532 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
534 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
535 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
536 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
538 static inline bool is_internal_key(int key)
540 return key < NUM_INTERNALLY_MAPPED_KEYS;
543 /* for internal keys, the key id is just the array index. */
544 static inline int get_internal_key_map_idx(int key)
546 assert(is_internal_key(key));
551 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
552 * difference is the index to the array of user defined key maps.
554 static inline int get_user_key_map_idx(int key)
556 assert(!is_internal_key(key));
557 return key - NUM_INTERNALLY_MAPPED_KEYS;
560 static inline int get_key_map_idx(int key)
562 return is_internal_key(key)?
563 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
566 static inline const char *get_user_key_map_arg(int key)
568 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
571 static inline char *get_internal_key_map_seq(int key)
573 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
576 static char *get_user_key_map_seq(int key)
578 const char *kma = get_user_key_map_arg(key);
579 const char *p = strchr(kma + 1, ':');
585 result = alloc(len + 1);
586 memcpy(result, kma, len);
591 static char *get_key_map_seq(int key)
593 return is_internal_key(key)?
594 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
597 static char *get_key_map_seq_safe(int key)
599 const char hex[] = "0123456789abcdef";
600 char *seq = get_key_map_seq(key), *sseq;
601 size_t n, len = strlen(seq);
603 if (len == 1 && isprint(*seq))
605 sseq = alloc(2 + 2 * len + 1);
608 for (n = 0; n < len; n++) {
609 uint8_t val = (seq[n] & 0xf0) >> 4;
610 sseq[2 + 2 * n] = hex[val];
612 sseq[2 + 2 * n + 1] = hex[val];
615 sseq[2 + 2 * n] = '\0';
619 static inline char *get_internal_key_map_cmd(int key)
621 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
624 static char *get_user_key_map_cmd(int key)
626 const char *kma = get_user_key_map_arg(key);
627 const char *p = strchr(kma + 1, ':');
631 return para_strdup(p + 1);
634 static char *get_key_map_cmd(int key)
636 return is_internal_key(key)?
637 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
640 static char **get_mapped_keyseqs(void)
645 result = arr_alloc(NUM_MAPPED_KEYS + 1, sizeof(char *));
646 FOR_EACH_MAPPED_KEY(i) {
647 char *seq = get_key_map_seq(i);
654 static struct i9e_completer pp_completers[];
656 I9E_DUMMY_COMPLETER(jmp);
657 I9E_DUMMY_COMPLETER(next);
658 I9E_DUMMY_COMPLETER(prev);
659 I9E_DUMMY_COMPLETER(fg);
660 I9E_DUMMY_COMPLETER(bg);
661 I9E_DUMMY_COMPLETER(ls);
662 I9E_DUMMY_COMPLETER(info);
663 I9E_DUMMY_COMPLETER(play);
664 I9E_DUMMY_COMPLETER(pause);
665 I9E_DUMMY_COMPLETER(tasks);
666 I9E_DUMMY_COMPLETER(quit);
667 I9E_DUMMY_COMPLETER(ff);
669 static void help_completer(struct i9e_completion_info *ci,
670 struct i9e_completion_result *cr)
672 char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
674 if (ci->word[0] == '-') {
675 i9e_complete_option(opts, ci, cr);
678 cr->matches = i9e_complete_commands(ci->word, pp_completers);
681 static struct i9e_completer pp_completers[] = {
682 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
683 .completer = _name ## _completer}
684 LSG_PLAY_CMD_SUBCOMMANDS
685 #undef LSG_PLAY_CMD_CMD
689 static void attach_stdout(const char *name)
693 pt->btrn = btr_new_node(&(struct btr_node_description)
694 EMBRACE(.name = name));
695 i9e_attach_to_stdout(pt->btrn);
698 static void detach_stdout(void)
700 btr_remove_node(&pt->btrn);
703 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
704 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
705 .handler = com_ ## _cmd \
708 static int com_quit(__a_unused struct lls_parse_result *lpr)
710 pt->rq = CRT_TERM_RQ;
713 EXPORT_PLAY_CMD_HANDLER(quit);
715 static int com_help(struct lls_parse_result *lpr)
721 const struct lls_opt_result *r =
722 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
723 bool long_help = lls_opt_given(r);
725 if (!pt->background) {
726 FOR_EACH_MAPPED_KEY(i) {
727 bool internal = is_internal_key(i);
728 int idx = get_key_map_idx(i);
729 char *seq = get_key_map_seq_safe(i);
730 char *kmc = get_key_map_cmd(i);
731 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
732 internal? "internal" : "user-defined",
734 btr_add_output(buf, sz, pt->btrn);
740 lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
741 btr_add_output(buf, n, pt->btrn);
744 EXPORT_PLAY_CMD_HANDLER(help);
746 static int com_info(__a_unused struct lls_parse_result *lpr)
750 static char dflt[] = "[no information available]";
752 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
753 pt->current_file, get_playlist_file(pt->current_file));
754 btr_add_output(buf, sz, pt->btrn);
755 buf = pt->afhi_txt? pt->afhi_txt : dflt;
756 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
759 EXPORT_PLAY_CMD_HANDLER(info);
761 static void list_file(int num)
766 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
767 "*" : " ", num, get_playlist_file(num));
768 btr_add_output(buf, sz, pt->btrn);
771 static int com_tasks(__a_unused struct lls_parse_result *lpr)
777 buf = get_task_list(&sched);
778 btr_add_output(buf, strlen(buf), pt->btrn);
779 state = get_playback_state();
780 sz = xasprintf(&buf, "state: %c\n", state);
781 btr_add_output(buf, sz, pt->btrn);
784 EXPORT_PLAY_CMD_HANDLER(tasks);
786 static int com_ls(__a_unused struct lls_parse_result *lpr)
789 unsigned num_inputs = lls_num_inputs(play_lpr);
791 for (i = 0; i < num_inputs; i++)
795 EXPORT_PLAY_CMD_HANDLER(ls);
797 static int com_play(struct lls_parse_result *lpr)
803 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
806 PARA_ERROR_LOG("%s\n", errctx);
810 state = get_playback_state();
811 if (lls_num_inputs(lpr) == 0) {
814 pt->next_file = pt->current_file;
819 ret = para_atoi32(lls_input(0, lpr), &x);
822 if (x < 0 || x >= lls_num_inputs(play_lpr))
823 return -ERRNO_TO_PARA_ERROR(EINVAL);
826 pt->rq = CRT_FILE_CHANGE;
829 EXPORT_PLAY_CMD_HANDLER(play);
831 static int com_pause(__a_unused struct lls_parse_result *lpr)
835 unsigned long cn; /* chunk num */
837 state = get_playback_state();
841 ms = get_play_time();
845 cn = ms * pt->num_chunks / pt->seconds / 1000 + 1;
846 cn = PARA_MIN(cn, pt->num_chunks);
847 pt->start_chunk = cn;
852 EXPORT_PLAY_CMD_HANDLER(pause);
854 static int com_prev(__a_unused struct lls_parse_result *lpr)
858 ret = previous_valid_file();
863 pt->rq = CRT_FILE_CHANGE;
867 EXPORT_PLAY_CMD_HANDLER(prev);
869 static int com_next(__a_unused struct lls_parse_result *lpr)
873 ret = next_valid_file();
878 pt->rq = CRT_FILE_CHANGE;
882 EXPORT_PLAY_CMD_HANDLER(next);
884 static int com_fg(__a_unused struct lls_parse_result *lpr)
886 pt->background = false;
889 EXPORT_PLAY_CMD_HANDLER(fg);
891 static int com_bg(__a_unused struct lls_parse_result *lpr)
893 pt->background = true;
896 EXPORT_PLAY_CMD_HANDLER(bg);
898 static int com_jmp(struct lls_parse_result *lpr)
904 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
907 PARA_ERROR_LOG("%s\n", errctx);
911 ret = para_atoi32(lls_input(0, lpr), &percent);
914 if (percent < 0 || percent > 100)
915 return -ERRNO_TO_PARA_ERROR(EINVAL);
917 return com_next(NULL);
918 if (pt->playing && !pt->fn.btrn)
920 pt->start_chunk = percent * pt->num_chunks / 100;
927 EXPORT_PLAY_CMD_HANDLER(jmp);
929 static int com_ff(struct lls_parse_result *lpr)
935 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
938 PARA_ERROR_LOG("%s\n", errctx);
942 ret = para_atoi32(lls_input(0, lpr), &seconds);
945 if (pt->playing && !pt->fn.btrn)
947 seconds += (get_play_time() + 500) / 1000;
948 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
949 seconds = PARA_MAX(seconds, 0);
950 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
951 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
952 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
959 EXPORT_PLAY_CMD_HANDLER(ff);
961 static int run_command(char *line)
966 const struct play_command_info *pci;
967 struct lls_parse_result *lpr;
968 const struct lls_command *cmd;
970 attach_stdout(__FUNCTION__);
971 ret = create_argv(line, " ", &argv);
977 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
980 cmd = lls_cmd(ret, play_cmd_suite);
981 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
984 pci = lls_user_data(cmd);
985 ret = pci->handler(lpr);
986 lls_free_parse_result(lpr, cmd);
989 PARA_ERROR_LOG("%s\n", errctx);
995 static int play_i9e_line_handler(char *line)
997 return run_command(line);
1000 static int play_i9e_key_handler(int key)
1002 int idx = get_key_map_idx(key);
1003 char *seq = get_key_map_seq(key);
1004 char *cmd = get_key_map_cmd(key);
1005 bool internal = is_internal_key(key);
1007 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1008 key, internal? "internal" : "user-defined",
1013 pt->next_update = *now;
1017 static struct i9e_client_info ici = {
1019 .prompt = "para_play> ",
1020 .line_handler = play_i9e_line_handler,
1021 .key_handler = play_i9e_key_handler,
1022 .completers = pp_completers,
1025 static void sigint_handler(int sig)
1027 pt->background = true;
1028 i9e_signal_dispatch(sig);
1032 * We start with para_log() set to the standard log function which writes to
1033 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1036 static void session_open(void)
1040 struct sigaction act;
1042 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1043 if (OPT_GIVEN(HISTORY_FILE))
1044 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1046 char *home = para_homedir();
1047 char *dot_para = make_message("%s/.paraslash", home);
1050 ret = para_mkdir(dot_para);
1051 /* warn, but otherwise ignore mkdir error */
1053 PARA_WARNING_LOG("Can not create %s: %s\n", dot_para,
1054 para_strerror(-ret));
1055 history_file = make_message("%s/play.history", dot_para);
1058 ici.history_file = history_file;
1059 ici.loglevel = loglevel;
1061 act.sa_handler = sigint_handler;
1062 sigemptyset(&act.sa_mask);
1064 sigaction(SIGINT, &act, NULL);
1065 act.sa_handler = i9e_signal_dispatch;
1066 sigemptyset(&act.sa_mask);
1068 sigaction(SIGWINCH, &act, NULL);
1069 sched.poll_function = i9e_poll;
1071 ici.bound_keyseqs = get_mapped_keyseqs();
1072 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1073 EMBRACE(.name = __FUNCTION__));
1074 ret = i9e_open(&ici, &sched);
1083 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1087 static void session_update_time_string(char *str, unsigned len)
1092 if (btr_get_output_queue_size(pt->btrn) > 0)
1094 if (btr_get_input_queue_size(pt->btrn) > 0)
1097 i9e_print_status_bar(str, len);
1101 * If we are about to die we must call i9e_close() to reset the terminal.
1102 * However, i9e_close() must be called in *this* context, i.e. from
1103 * play_task.post_monitor() rather than from i9e_post_monitor(), because
1104 * otherwise i9e would access freed memory upon return. So the play task must
1105 * stay alive until the i9e task terminates.
1107 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1108 * and reschedule. In the next iteration, i9e->post_monitor returns an error and
1109 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1110 * are allowed to call i9e_close() and terminate as well.
1112 static int session_post_monitor(__a_unused struct sched *s)
1119 attach_stdout(__FUNCTION__);
1120 ret = i9e_get_error();
1124 para_log = stderr_log;
1125 free(ici.history_file);
1128 if (get_playback_state() == 'X')
1129 i9e_signal_dispatch(SIGTERM);
1133 #else /* HAVE_READLINE */
1135 static int session_post_monitor(struct sched *s)
1139 if (!sched_read_ok(STDIN_FILENO, s))
1141 if (read(STDIN_FILENO, &c, 1))
1147 static void session_open(void)
1151 static void session_update_time_string(char *str, __a_unused unsigned len)
1153 printf("\r%s ", str);
1156 #endif /* HAVE_READLINE */
1158 static void play_pre_monitor(struct sched *s, __a_unused void *context)
1162 sched_monitor_readfd(STDIN_FILENO, s);
1163 state = get_playback_state();
1164 if (state == 'R' || state == 'F' || state == 'X')
1165 return sched_min_delay(s);
1166 sched_request_barrier_or_min_delay(&pt->next_update, s);
1169 static unsigned get_time_string(char **result)
1171 int seconds, length;
1172 char state = get_playback_state();
1174 /* do not return anything if things are about to change */
1175 if (state != 'P' && state != 'U') {
1179 length = pt->seconds;
1181 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1182 seconds = (get_play_time() + 500) / 1000;
1183 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1187 (length - seconds) / 60,
1188 (length - seconds) % 60,
1189 length? (seconds * 100 + length / 2) / length : 0,
1192 get_playlist_file(pt->current_file)
1196 static int play_post_monitor(struct sched *s, __a_unused void *context)
1200 ret = eof_cleanup();
1202 pt->rq = CRT_TERM_RQ;
1205 ret = session_post_monitor(s);
1208 if (!pt->wn.btrn && !pt->fn.btrn) {
1209 char state = get_playback_state();
1210 if (state == 'P' || state == 'R' || state == 'F') {
1211 PARA_NOTICE_LOG("state: %c\n", state);
1212 ret = load_next_file();
1214 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1215 pt->rq = CRT_TERM_RQ;
1219 pt->next_update = *now;
1222 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1224 unsigned len = get_time_string(&str);
1225 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1227 session_update_time_string(str, len);
1229 tv_add(now, &delay, &pt->next_update);
1237 * The main function of para_play.
1239 * \param argc See man page.
1240 * \param argv See man page.
1242 * para_play distributes its work by submitting various tasks to the paraslash
1243 * scheduler. The receiver, filter and writer tasks, which are used to play an
1244 * audio file, require one task each to maintain their underlying buffer tree
1245 * node. These tasks only exist when an audio file is playing.
1247 * The i9 task, which is submitted and maintained by the i9e subsystem, reads
1248 * an input line and calls the corresponding command handler such as com_stop()
1249 * which is implemented in this file. The command handlers typically write a
1250 * request to the global play_task structure, whose contents are read and acted
1251 * upon by another task, the play task.
1253 * As a rule, playlist handling is performed exclusively in play context, i.e.
1254 * in the post-monitor step of the play task, while command handlers are only
1255 * called in i9e context.
1257 * \return EXIT_FAILURE or EXIT_SUCCESS.
1259 int main(int argc, char *argv[])
1262 unsigned num_inputs;
1264 sched.default_timeout = 5000;
1265 parse_config_or_die(argc, argv);
1267 num_inputs = lls_num_inputs(play_lpr);
1269 pt->invalid = arr_zalloc(num_inputs, sizeof(*pt->invalid));
1270 pt->rq = CRT_FILE_CHANGE;
1272 pt->task = task_register(&(struct task_info){
1274 .pre_monitor = play_pre_monitor,
1275 .post_monitor = play_post_monitor,
1278 ret = schedule(&sched);
1279 sched_shutdown(&sched);
1281 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1282 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;