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, ':');
586 result = alloc(len + 1);
587 memcpy(result, kma, len);
592 static char *get_key_map_seq(int key)
594 return is_internal_key(key)?
595 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
598 static char *get_key_map_seq_safe(int key)
600 const char hex[] = "0123456789abcdef";
601 char *seq = get_key_map_seq(key), *sseq;
602 size_t n, len = strlen(seq);
604 if (len == 1 && isprint(*seq))
606 sseq = alloc(2 + 2 * len + 1);
609 for (n = 0; n < len; n++) {
610 uint8_t val = (seq[n] & 0xf0) >> 4;
611 sseq[2 + 2 * n] = hex[val];
613 sseq[2 + 2 * n + 1] = hex[val];
616 sseq[2 + 2 * n] = '\0';
620 static inline char *get_internal_key_map_cmd(int key)
622 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
625 static char *get_user_key_map_cmd(int key)
627 const char *kma = get_user_key_map_arg(key);
628 const char *p = strchr(kma + 1, ':');
632 return para_strdup(p + 1);
635 static char *get_key_map_cmd(int key)
637 return is_internal_key(key)?
638 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
641 static char **get_mapped_keyseqs(void)
646 result = arr_alloc(NUM_MAPPED_KEYS + 1, sizeof(char *));
647 FOR_EACH_MAPPED_KEY(i) {
648 char *seq = get_key_map_seq(i);
655 static struct i9e_completer pp_completers[];
657 I9E_DUMMY_COMPLETER(jmp);
658 I9E_DUMMY_COMPLETER(next);
659 I9E_DUMMY_COMPLETER(prev);
660 I9E_DUMMY_COMPLETER(fg);
661 I9E_DUMMY_COMPLETER(bg);
662 I9E_DUMMY_COMPLETER(ls);
663 I9E_DUMMY_COMPLETER(info);
664 I9E_DUMMY_COMPLETER(play);
665 I9E_DUMMY_COMPLETER(pause);
666 I9E_DUMMY_COMPLETER(tasks);
667 I9E_DUMMY_COMPLETER(quit);
668 I9E_DUMMY_COMPLETER(ff);
670 static void help_completer(struct i9e_completion_info *ci,
671 struct i9e_completion_result *cr)
673 char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
675 if (ci->word[0] == '-') {
676 i9e_complete_option(opts, ci, cr);
679 cr->matches = i9e_complete_commands(ci->word, pp_completers);
682 static struct i9e_completer pp_completers[] = {
683 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
684 .completer = _name ## _completer}
685 LSG_PLAY_CMD_SUBCOMMANDS
686 #undef LSG_PLAY_CMD_CMD
690 static void attach_stdout(const char *name)
694 pt->btrn = btr_new_node(&(struct btr_node_description)
695 EMBRACE(.name = name));
696 i9e_attach_to_stdout(pt->btrn);
699 static void detach_stdout(void)
701 btr_remove_node(&pt->btrn);
704 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
705 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
706 .handler = com_ ## _cmd \
709 static int com_quit(__a_unused struct lls_parse_result *lpr)
711 pt->rq = CRT_TERM_RQ;
714 EXPORT_PLAY_CMD_HANDLER(quit);
716 static int com_help(struct lls_parse_result *lpr)
722 const struct lls_opt_result *r =
723 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
724 bool long_help = lls_opt_given(r);
726 if (!pt->background) {
727 FOR_EACH_MAPPED_KEY(i) {
728 bool internal = is_internal_key(i);
729 int idx = get_key_map_idx(i);
730 char *seq = get_key_map_seq_safe(i);
731 char *kmc = get_key_map_cmd(i);
732 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
733 internal? "internal" : "user-defined",
735 btr_add_output(buf, sz, pt->btrn);
741 lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
742 btr_add_output(buf, n, pt->btrn);
745 EXPORT_PLAY_CMD_HANDLER(help);
747 static int com_info(__a_unused struct lls_parse_result *lpr)
751 static char dflt[] = "[no information available]";
753 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
754 pt->current_file, get_playlist_file(pt->current_file));
755 btr_add_output(buf, sz, pt->btrn);
756 buf = pt->afhi_txt? pt->afhi_txt : dflt;
757 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
760 EXPORT_PLAY_CMD_HANDLER(info);
762 static void list_file(int num)
767 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
768 "*" : " ", num, get_playlist_file(num));
769 btr_add_output(buf, sz, pt->btrn);
772 static int com_tasks(__a_unused struct lls_parse_result *lpr)
778 buf = get_task_list(&sched);
779 btr_add_output(buf, strlen(buf), pt->btrn);
780 state = get_playback_state();
781 sz = xasprintf(&buf, "state: %c\n", state);
782 btr_add_output(buf, sz, pt->btrn);
785 EXPORT_PLAY_CMD_HANDLER(tasks);
787 static int com_ls(__a_unused struct lls_parse_result *lpr)
790 unsigned num_inputs = lls_num_inputs(play_lpr);
792 for (i = 0; i < num_inputs; i++)
796 EXPORT_PLAY_CMD_HANDLER(ls);
798 static int com_play(struct lls_parse_result *lpr)
804 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
807 PARA_ERROR_LOG("%s\n", errctx);
811 state = get_playback_state();
812 if (lls_num_inputs(lpr) == 0) {
815 pt->next_file = pt->current_file;
820 ret = para_atoi32(lls_input(0, lpr), &x);
823 if (x < 0 || x >= lls_num_inputs(play_lpr))
824 return -ERRNO_TO_PARA_ERROR(EINVAL);
827 pt->rq = CRT_FILE_CHANGE;
830 EXPORT_PLAY_CMD_HANDLER(play);
832 static int com_pause(__a_unused struct lls_parse_result *lpr)
836 unsigned long cn; /* chunk num */
838 state = get_playback_state();
842 ms = get_play_time();
846 cn = ms * pt->num_chunks / pt->seconds / 1000 + 1;
847 cn = PARA_MIN(cn, pt->num_chunks);
848 pt->start_chunk = cn;
853 EXPORT_PLAY_CMD_HANDLER(pause);
855 static int com_prev(__a_unused struct lls_parse_result *lpr)
859 ret = previous_valid_file();
864 pt->rq = CRT_FILE_CHANGE;
868 EXPORT_PLAY_CMD_HANDLER(prev);
870 static int com_next(__a_unused struct lls_parse_result *lpr)
874 ret = next_valid_file();
879 pt->rq = CRT_FILE_CHANGE;
883 EXPORT_PLAY_CMD_HANDLER(next);
885 static int com_fg(__a_unused struct lls_parse_result *lpr)
887 pt->background = false;
890 EXPORT_PLAY_CMD_HANDLER(fg);
892 static int com_bg(__a_unused struct lls_parse_result *lpr)
894 pt->background = true;
897 EXPORT_PLAY_CMD_HANDLER(bg);
899 static int com_jmp(struct lls_parse_result *lpr)
905 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
908 PARA_ERROR_LOG("%s\n", errctx);
912 ret = para_atoi32(lls_input(0, lpr), &percent);
915 if (percent < 0 || percent > 100)
916 return -ERRNO_TO_PARA_ERROR(EINVAL);
918 return com_next(NULL);
919 if (pt->playing && !pt->fn.btrn)
921 pt->start_chunk = percent * pt->num_chunks / 100;
928 EXPORT_PLAY_CMD_HANDLER(jmp);
930 static int com_ff(struct lls_parse_result *lpr)
936 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
939 PARA_ERROR_LOG("%s\n", errctx);
943 ret = para_atoi32(lls_input(0, lpr), &seconds);
946 if (pt->playing && !pt->fn.btrn)
948 seconds += (get_play_time() + 500) / 1000;
949 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
950 seconds = PARA_MAX(seconds, 0);
951 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
952 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
953 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
960 EXPORT_PLAY_CMD_HANDLER(ff);
962 static int run_command(char *line)
967 const struct play_command_info *pci;
968 struct lls_parse_result *lpr;
969 const struct lls_command *cmd;
971 attach_stdout(__FUNCTION__);
972 ret = create_argv(line, " ", &argv);
978 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
981 cmd = lls_cmd(ret, play_cmd_suite);
982 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
985 pci = lls_user_data(cmd);
986 ret = pci->handler(lpr);
987 lls_free_parse_result(lpr, cmd);
990 PARA_ERROR_LOG("%s\n", errctx);
996 static int play_i9e_line_handler(char *line)
998 return run_command(line);
1001 static int play_i9e_key_handler(int key)
1003 int idx = get_key_map_idx(key);
1004 char *seq = get_key_map_seq(key);
1005 char *cmd = get_key_map_cmd(key);
1006 bool internal = is_internal_key(key);
1008 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1009 key, internal? "internal" : "user-defined",
1014 pt->next_update = *now;
1018 static struct i9e_client_info ici = {
1020 .prompt = "para_play> ",
1021 .line_handler = play_i9e_line_handler,
1022 .key_handler = play_i9e_key_handler,
1023 .completers = pp_completers,
1026 static void sigint_handler(int sig)
1028 pt->background = true;
1029 i9e_signal_dispatch(sig);
1033 * We start with para_log() set to the standard log function which writes to
1034 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1037 static void session_open(void)
1041 struct sigaction act;
1043 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1044 if (OPT_GIVEN(HISTORY_FILE))
1045 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1047 char *home = para_homedir();
1048 char *dot_para = make_message("%s/.paraslash", home);
1051 ret = para_mkdir(dot_para, 0777);
1052 /* warn, but otherwise ignore mkdir error */
1053 if (ret < 0 && ret != -ERRNO_TO_PARA_ERROR(EEXIST))
1054 PARA_WARNING_LOG("Can not create %s: %s\n", dot_para,
1055 para_strerror(-ret));
1056 history_file = make_message("%s/play.history", dot_para);
1059 ici.history_file = history_file;
1060 ici.loglevel = loglevel;
1062 act.sa_handler = sigint_handler;
1063 sigemptyset(&act.sa_mask);
1065 sigaction(SIGINT, &act, NULL);
1066 act.sa_handler = i9e_signal_dispatch;
1067 sigemptyset(&act.sa_mask);
1069 sigaction(SIGWINCH, &act, NULL);
1070 sched.poll_function = i9e_poll;
1072 ici.bound_keyseqs = get_mapped_keyseqs();
1073 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1074 EMBRACE(.name = __FUNCTION__));
1075 ret = i9e_open(&ici, &sched);
1084 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1088 static void session_update_time_string(char *str, unsigned len)
1093 if (btr_get_output_queue_size(pt->btrn) > 0)
1095 if (btr_get_input_queue_size(pt->btrn) > 0)
1098 i9e_print_status_bar(str, len);
1102 * If we are about to die we must call i9e_close() to reset the terminal.
1103 * However, i9e_close() must be called in *this* context, i.e. from
1104 * play_task.post_monitor() rather than from i9e_post_monitor(), because
1105 * otherwise i9e would access freed memory upon return. So the play task must
1106 * stay alive until the i9e task terminates.
1108 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1109 * and reschedule. In the next iteration, i9e->post_monitor returns an error and
1110 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1111 * are allowed to call i9e_close() and terminate as well.
1113 static int session_post_monitor(__a_unused struct sched *s)
1120 attach_stdout(__FUNCTION__);
1121 ret = i9e_get_error();
1125 para_log = stderr_log;
1126 free(ici.history_file);
1129 if (get_playback_state() == 'X')
1130 i9e_signal_dispatch(SIGTERM);
1134 #else /* HAVE_READLINE */
1136 static int session_post_monitor(struct sched *s)
1140 if (!sched_read_ok(STDIN_FILENO, s))
1142 if (read(STDIN_FILENO, &c, 1))
1148 static void session_open(void)
1152 static void session_update_time_string(char *str, __a_unused unsigned len)
1154 printf("\r%s ", str);
1157 #endif /* HAVE_READLINE */
1159 static void play_pre_monitor(struct sched *s, __a_unused void *context)
1163 sched_monitor_readfd(STDIN_FILENO, s);
1164 state = get_playback_state();
1165 if (state == 'R' || state == 'F' || state == 'X')
1166 return sched_min_delay(s);
1167 sched_request_barrier_or_min_delay(&pt->next_update, s);
1170 static unsigned get_time_string(char **result)
1172 int seconds, length;
1173 char state = get_playback_state();
1175 /* do not return anything if things are about to change */
1176 if (state != 'P' && state != 'U') {
1180 length = pt->seconds;
1182 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1183 seconds = (get_play_time() + 500) / 1000;
1184 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1188 (length - seconds) / 60,
1189 (length - seconds) % 60,
1190 length? (seconds * 100 + length / 2) / length : 0,
1193 get_playlist_file(pt->current_file)
1197 static int play_post_monitor(struct sched *s, __a_unused void *context)
1201 ret = eof_cleanup();
1203 pt->rq = CRT_TERM_RQ;
1206 ret = session_post_monitor(s);
1209 if (!pt->wn.btrn && !pt->fn.btrn) {
1210 char state = get_playback_state();
1211 if (state == 'P' || state == 'R' || state == 'F') {
1212 PARA_NOTICE_LOG("state: %c\n", state);
1213 ret = load_next_file();
1215 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1216 pt->rq = CRT_TERM_RQ;
1220 pt->next_update = *now;
1223 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1225 unsigned len = get_time_string(&str);
1226 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1228 session_update_time_string(str, len);
1230 tv_add(now, &delay, &pt->next_update);
1238 * The main function of para_play.
1240 * \param argc See man page.
1241 * \param argv See man page.
1243 * para_play distributes its work by submitting various tasks to the paraslash
1244 * scheduler. The receiver, filter and writer tasks, which are used to play an
1245 * audio file, require one task each to maintain their underlying buffer tree
1246 * node. These tasks only exist when an audio file is playing.
1248 * The i9 task, which is submitted and maintained by the i9e subsystem, reads
1249 * an input line and calls the corresponding command handler such as com_stop()
1250 * which is implemented in this file. The command handlers typically write a
1251 * request to the global play_task structure, whose contents are read and acted
1252 * upon by another task, the play task.
1254 * As a rule, playlist handling is performed exclusively in play context, i.e.
1255 * in the post-monitor step of the play task, while command handlers are only
1256 * called in i9e context.
1258 * \return EXIT_FAILURE or EXIT_SUCCESS.
1260 int main(int argc, char *argv[])
1263 unsigned num_inputs;
1265 sched.default_timeout = 5000;
1266 parse_config_or_die(argc, argv);
1268 num_inputs = lls_num_inputs(play_lpr);
1270 pt->invalid = arr_zalloc(num_inputs, sizeof(*pt->invalid));
1271 pt->rq = CRT_FILE_CHANGE;
1273 pt->task = task_register(&(struct task_info){
1275 .pre_monitor = play_pre_monitor,
1276 .post_monitor = play_post_monitor,
1279 ret = schedule(&sched);
1280 sched_shutdown(&sched);
1282 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1283 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;