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 "play_cmd.lsg.h"
11 #include "write_cmd.lsg.h"
17 #include "buffer_tree.h"
28 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
29 * para_play creates two further tasks: The play task and the i9e task. It is
30 * important whether a function can be called in the context of para_play or
31 * i9e or both. As a rule, all command handlers are called only in i9e context via
32 * the line handler (input mode) or the key handler (command mode) below.
34 * Playlist handling is done exclusively in play context.
37 /** Array of error strings. */
40 static struct lls_parse_result *play_lpr;
42 #define CMD_PTR (lls_cmd(0, play_suite))
43 #define OPT_RESULT(_name) \
44 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
45 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
46 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
47 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
50 * Describes a request to change the state of para_play.
52 * There is only one variable of this type: \a rq of the global play task
53 * structure. Command handlers only set this variable and the post_select()
54 * function of the play task investigates its value during each iteration of
55 * the scheduler run and performs the actual work.
57 enum state_change_request_type {
58 /** Everybody is happy. */
60 /** Stream must be repositioned (com_jmp(), com_ff()). */
62 /** New file should be loaded (com_next()). */
64 /** Someone wants us for dead (com_quit()). */
70 /* A bit array of invalid files (those will be skipped). */
72 /* The file which is currently open. */
73 unsigned current_file;
74 /* When to update the status again. */
75 struct timeval next_update;
77 /* Root of the buffer tree for command and status output. */
78 struct btr_node *btrn;
80 /* The decoding machinery. */
81 struct receiver_node rn;
82 struct filter_node fn;
83 struct writer_node wn;
85 /* See comment to enum \ref state_change_request_type above. */
86 enum state_change_request_type rq;
87 /* only relevant if rq == CRT_FILE_CHANGE */
90 bg: read lines at prompt, fg: display status and wait
95 /* We have the *intention* to play. Set by com_play(). */
98 /* as returned by afh_recv->open() */
101 /* retrieved via the btr exec mechanism */
102 long unsigned start_chunk;
103 long unsigned seconds;
104 long unsigned num_chunks;
108 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
109 struct play_command_info {
110 play_cmd_handler_t handler;
112 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
113 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
114 .handler = com_ ## _cmd \
117 static int loglevel = LL_WARNING;
119 /** The log function which writes log messages to stderr. */
120 INIT_STDERR_LOGGING(loglevel);
122 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
124 static struct sched sched = {.max_fileno = 0};
125 static struct play_task play_task, *pt = &play_task;
127 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
128 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
130 static unsigned *shuffle_map;
132 static const char *get_playlist_file(unsigned idx)
134 return lls_input(shuffle_map[idx], play_lpr);
137 static void handle_help_flags(void)
141 if (OPT_GIVEN(DETAILED_HELP))
142 help = lls_long_help(CMD_PTR);
143 else if (OPT_GIVEN(HELP) || lls_num_inputs(play_lpr) == 0)
144 help = lls_short_help(CMD_PTR);
147 printf("%s\n", help);
152 static void parse_config_or_die(int argc, char *argv[])
154 const struct lls_command *cmd = CMD_PTR;
156 char *cf, *errctx, **cf_argv;
157 struct lls_parse_result *cf_lpr, *merged_lpr;
162 ret = lls(lls_parse(argc, argv, cmd, &play_lpr, &errctx));
165 loglevel = OPT_UINT32_VAL(LOGLEVEL);
166 version_handle_flag("play", OPT_GIVEN(VERSION));
167 handle_help_flags(); /* also handles the zero-arg case */
168 if (OPT_GIVEN(CONFIG_FILE))
169 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
171 char *home = para_homedir();
172 cf = make_message("%s/.paraslash/play.conf", home);
175 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
177 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
179 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
184 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
185 para_munmap(map, sz);
189 ret = lls(lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx));
190 lls_free_argv(cf_argv);
193 ret = lls(lls_merge(play_lpr, cf_lpr, cmd, &merged_lpr, &errctx));
194 lls_free_parse_result(cf_lpr, cmd);
197 lls_free_parse_result(play_lpr, cmd);
198 play_lpr = merged_lpr;
199 loglevel = OPT_UINT32_VAL(LOGLEVEL);
201 num_kmas = OPT_GIVEN(KEY_MAP);
202 for (i = 0; i < num_kmas; i++) {
203 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
204 if (*kma && strchr(kma + 1, ':'))
206 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
214 lls_free_parse_result(play_lpr, cmd);
217 PARA_EMERG_LOG("%s\n", errctx);
219 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
223 static char get_playback_state(void)
226 case CRT_NONE: return pt->playing? 'P' : 'U';
227 case CRT_REPOS: return 'R';
228 case CRT_FILE_CHANGE: return 'F';
229 case CRT_TERM_RQ: return 'X';
234 static long unsigned get_play_time(void)
236 char state = get_playback_state();
237 long unsigned result;
239 if (state != 'P' && state != 'U')
241 if (pt->num_chunks == 0 || pt->seconds == 0)
243 /* where the stream started (in seconds) */
244 result = pt->start_chunk * pt->seconds / pt->num_chunks;
245 if (pt->wn.btrn) { /* Add the uptime of the writer node */
246 struct timeval diff = {.tv_sec = 0}, wstime;
247 btr_get_node_start(pt->wn.btrn, &wstime);
248 if (wstime.tv_sec > 0)
249 tv_diff(now, &wstime, &diff);
250 result += diff.tv_sec;
252 result = PARA_MIN(result, pt->seconds);
253 result = PARA_MAX(result, 0UL);
258 static void wipe_receiver_node(void)
260 PARA_NOTICE_LOG("cleaning up receiver node\n");
261 btr_remove_node(&pt->rn.btrn);
262 AFH_RECV->close(&pt->rn);
263 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
264 memset(&pt->rn, 0, sizeof(struct receiver_node));
267 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
268 static int get_playback_error(void)
274 err = task_status(pt->wn.task);
277 if (task_status(pt->fn.task) >= 0)
279 if (task_status(pt->rn.task) >= 0)
281 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
282 || err == -E_WRITE_COMMON_EOF)
287 static int eof_cleanup(void)
289 const struct filter *decoder;
290 const struct writer *w = writer_get(-1); /* default writer */
293 ret = get_playback_error();
296 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
297 task_reap(&pt->wn.task);
299 btr_remove_node(&pt->wn.btrn);
300 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
301 memset(&pt->wn, 0, sizeof(struct writer_node));
303 decoder = filter_get(pt->fn.filter_num);
304 task_reap(&pt->fn.task);
306 decoder->close(&pt->fn);
307 btr_remove_node(&pt->fn.btrn);
309 memset(&pt->fn, 0, sizeof(struct filter_node));
311 task_reap(&pt->rn.task);
312 btr_remove_node(&pt->rn.btrn);
314 * On eof (ret > 0), we do not wipe the receiver node struct until a
315 * new file is loaded because we still need it for jumping around when
319 wipe_receiver_node();
323 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
325 return para_random(100) - 50;
328 static void init_shuffle_map(void)
330 unsigned n, num_inputs = lls_num_inputs(play_lpr);
331 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
332 for (n = 0; n < num_inputs; n++)
334 if (!OPT_GIVEN(RANDOMIZE))
337 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
340 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
342 return btr_new_node(&(struct btr_node_description)
343 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
344 .handler = AFH_RECV->execute));
347 static int open_new_file(void)
350 const char *path = get_playlist_file(pt->next_file);
351 char *tmp = para_strdup(path), *errctx;
352 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
354 PARA_NOTICE_LOG("next file: %s\n", path);
355 wipe_receiver_node();
357 pt->rn.btrn = new_recv_btrn(&pt->rn);
358 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
359 &pt->rn.lpr, &errctx));
362 pt->rn.receiver = AFH_RECV;
363 ret = AFH_RECV->open(&pt->rn);
365 PARA_ERROR_LOG("could not open %s\n", path);
368 pt->audio_format_num = ret;
370 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
372 pt->afhi_txt = make_message("[afhi command failed]\n");
373 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
378 ret = para_atoi32(tmp, &x);
379 pt->seconds = ret < 0? 1 : x;
383 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
388 ret = para_atoi32(tmp, &x);
389 pt->num_chunks = ret < 0? 1 : x;
395 wipe_receiver_node();
399 static int load_file(void)
404 const struct filter *decoder;
405 static struct lls_parse_result *filter_lpr, *writer_lpr;
407 btr_remove_node(&pt->rn.btrn);
408 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
409 ret = open_new_file();
413 pt->rn.btrn = new_recv_btrn(&pt->rn);
414 sprintf(buf, "repos %lu", pt->start_chunk);
415 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
417 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
422 /* set up decoding filter */
423 af = audio_format_name(pt->audio_format_num);
424 tmp = make_message("%sdec", af);
425 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
429 pt->fn.filter_num = ret;
430 pt->fn.lpr = filter_lpr;
431 decoder = filter_get(ret);
432 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
433 EMBRACE(.name = filter_name(pt->fn.filter_num),
434 .parent = pt->rn.btrn, .handler = decoder->execute,
435 .context = &pt->fn));
437 decoder->open(&pt->fn);
438 PARA_INFO_LOG("buffer tree:\n");
439 btr_log_tree(pt->rn.btrn, LL_INFO);
441 /* setup default writer */
442 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
443 pt->wn.lpr = writer_lpr;
444 /* success, register tasks */
445 pt->rn.task = task_register(
446 &(struct task_info) {
447 .name = lls_command_name(AFH_RECV_CMD),
448 .pre_select = AFH_RECV->pre_select,
449 .post_select = AFH_RECV->post_select,
452 sprintf(buf, "%s decoder", af);
453 pt->fn.task = task_register(
454 &(struct task_info) {
456 .pre_select = decoder->pre_select,
457 .post_select = decoder->post_select,
460 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
463 wipe_receiver_node();
467 static int next_valid_file(void)
469 int i, j = pt->current_file;
470 unsigned num_inputs = lls_num_inputs(play_lpr);
472 for (i = 0; i < num_inputs; i++) {
473 j = (j + 1) % num_inputs;
477 return -E_NO_VALID_FILES;
480 static int load_next_file(void)
485 if (pt->rq == CRT_NONE) {
487 ret = next_valid_file();
491 } else if (pt->rq == CRT_REPOS)
492 pt->next_file = pt->current_file;
495 PARA_ERROR_LOG("%s: marking file as invalid\n",
496 para_strerror(-ret));
497 pt->invalid[pt->next_file] = true;
501 pt->current_file = pt->next_file;
506 static void kill_stream(void)
509 task_notify(pt->wn.task, E_EOF);
514 /* only called from com_prev(), nec. only if we have readline */
515 static int previous_valid_file(void)
517 int i, j = pt->current_file;
518 unsigned num_inputs = lls_num_inputs(play_lpr);
520 for (i = 0; i < num_inputs; i++) {
527 return -E_NO_VALID_FILES;
530 #include "interactive.h"
533 * Define the default (internal) key mappings and helper functions to get the
534 * key sequence or the command from a key id, which is what we obtain from
535 * i9e/readline when the key is pressed.
537 * In some of these helper functions we could return pointers to the constant
538 * arrays defined below. However, for others we can not, so let's better be
539 * consistent and allocate all returned strings on the heap.
542 #define INTERNAL_KEYMAP_ENTRIES \
543 KEYMAP_ENTRY("^", "jmp 0"), \
544 KEYMAP_ENTRY("1", "jmp 10"), \
545 KEYMAP_ENTRY("2", "jmp 21"), \
546 KEYMAP_ENTRY("3", "jmp 32"), \
547 KEYMAP_ENTRY("4", "jmp 43"), \
548 KEYMAP_ENTRY("5", "jmp 54"), \
549 KEYMAP_ENTRY("6", "jmp 65"), \
550 KEYMAP_ENTRY("7", "jmp 76"), \
551 KEYMAP_ENTRY("8", "jmp 87"), \
552 KEYMAP_ENTRY("9", "jmp 98"), \
553 KEYMAP_ENTRY("+", "next"), \
554 KEYMAP_ENTRY("-", "prev"), \
555 KEYMAP_ENTRY(":", "bg"), \
556 KEYMAP_ENTRY("i", "info"), \
557 KEYMAP_ENTRY("l", "ls"), \
558 KEYMAP_ENTRY("s", "play"), \
559 KEYMAP_ENTRY("p", "pause"), \
560 KEYMAP_ENTRY("q", "quit"), \
561 KEYMAP_ENTRY("?", "help"), \
562 KEYMAP_ENTRY("\033[D", "ff -10"), \
563 KEYMAP_ENTRY("\033[C", "ff 10"), \
564 KEYMAP_ENTRY("\033[A", "ff 60"), \
565 KEYMAP_ENTRY("\033[B", "ff -60"), \
567 #define KEYMAP_ENTRY(a, b) a
568 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
570 #define KEYMAP_ENTRY(a, b) b
571 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
573 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
574 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
575 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
577 static inline bool is_internal_key(int key)
579 return key < NUM_INTERNALLY_MAPPED_KEYS;
582 /* for internal keys, the key id is just the array index. */
583 static inline int get_internal_key_map_idx(int key)
585 assert(is_internal_key(key));
590 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
591 * difference is the index to the array of user defined key maps.
593 static inline int get_user_key_map_idx(int key)
595 assert(!is_internal_key(key));
596 return key - NUM_INTERNALLY_MAPPED_KEYS;
599 static inline int get_key_map_idx(int key)
601 return is_internal_key(key)?
602 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
605 static inline const char *get_user_key_map_arg(int key)
607 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
610 static inline char *get_internal_key_map_seq(int key)
612 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
615 static char *get_user_key_map_seq(int key)
617 const char *kma = get_user_key_map_arg(key);
618 const char *p = strchr(kma + 1, ':');
625 result = para_malloc(len + 1);
626 memcpy(result, kma, len);
631 static char *get_key_map_seq(int key)
633 return is_internal_key(key)?
634 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
637 static char *get_key_map_seq_safe(int key)
639 const char hex[] = "0123456789abcdef";
640 char *seq = get_key_map_seq(key), *sseq;
641 size_t n, len = strlen(seq);
643 if (len == 1 && isprint(*seq))
645 sseq = para_malloc(2 + 2 * len + 1);
648 for (n = 0; n < len; n++) {
649 uint8_t val = (seq[n] & 0xf0) >> 4;
650 sseq[2 + 2 * n] = hex[val];
652 sseq[2 + 2 * n + 1] = hex[val];
655 sseq[2 + 2 * n] = '\0';
659 static inline char *get_internal_key_map_cmd(int key)
661 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
664 static char *get_user_key_map_cmd(int key)
666 const char *kma = get_user_key_map_arg(key);
667 const char *p = strchr(kma + 1, ':');
671 return para_strdup(p + 1);
674 static char *get_key_map_cmd(int key)
676 return is_internal_key(key)?
677 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
680 static char **get_mapped_keyseqs(void)
685 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
686 FOR_EACH_MAPPED_KEY(i) {
687 char *seq = get_key_map_seq(i);
694 static struct i9e_completer pp_completers[];
696 I9E_DUMMY_COMPLETER(jmp);
697 I9E_DUMMY_COMPLETER(next);
698 I9E_DUMMY_COMPLETER(prev);
699 I9E_DUMMY_COMPLETER(fg);
700 I9E_DUMMY_COMPLETER(bg);
701 I9E_DUMMY_COMPLETER(ls);
702 I9E_DUMMY_COMPLETER(info);
703 I9E_DUMMY_COMPLETER(play);
704 I9E_DUMMY_COMPLETER(pause);
705 I9E_DUMMY_COMPLETER(tasks);
706 I9E_DUMMY_COMPLETER(quit);
707 I9E_DUMMY_COMPLETER(ff);
709 static void help_completer(struct i9e_completion_info *ci,
710 struct i9e_completion_result *result)
712 char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
714 if (ci->word[0] == '-') {
715 i9e_complete_option(opts, ci, result);
718 result->matches = i9e_complete_commands(ci->word, pp_completers);
721 static struct i9e_completer pp_completers[] = {
722 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
723 .completer = _name ## _completer}
724 LSG_PLAY_CMD_SUBCOMMANDS
725 #undef LSG_PLAY_CMD_CMD
729 static void attach_stdout(const char *name)
733 pt->btrn = btr_new_node(&(struct btr_node_description)
734 EMBRACE(.name = name));
735 i9e_attach_to_stdout(pt->btrn);
738 static void detach_stdout(void)
740 btr_remove_node(&pt->btrn);
743 static int com_quit(__a_unused struct lls_parse_result *lpr)
745 pt->rq = CRT_TERM_RQ;
748 EXPORT_PLAY_CMD_HANDLER(quit);
750 static int com_help(struct lls_parse_result *lpr)
756 const struct lls_opt_result *r =
757 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
758 bool long_help = lls_opt_given(r);
760 if (!pt->background) {
761 FOR_EACH_MAPPED_KEY(i) {
762 bool internal = is_internal_key(i);
763 int idx = get_key_map_idx(i);
764 char *seq = get_key_map_seq_safe(i);
765 char *kmc = get_key_map_cmd(i);
766 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
767 internal? "internal" : "user-defined",
769 btr_add_output(buf, sz, pt->btrn);
775 lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
776 btr_add_output(buf, n, pt->btrn);
779 EXPORT_PLAY_CMD_HANDLER(help);
781 static int com_info(__a_unused struct lls_parse_result *lpr)
785 static char dflt[] = "[no information available]";
787 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
788 pt->current_file, get_playlist_file(pt->current_file));
789 btr_add_output(buf, sz, pt->btrn);
790 buf = pt->afhi_txt? pt->afhi_txt : dflt;
791 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
794 EXPORT_PLAY_CMD_HANDLER(info);
796 static void list_file(int num)
801 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
802 "*" : " ", num, get_playlist_file(num));
803 btr_add_output(buf, sz, pt->btrn);
806 static int com_tasks(__a_unused struct lls_parse_result *lpr)
812 buf = get_task_list(&sched);
813 btr_add_output(buf, strlen(buf), pt->btrn);
814 state = get_playback_state();
815 sz = xasprintf(&buf, "state: %c\n", state);
816 btr_add_output(buf, sz, pt->btrn);
819 EXPORT_PLAY_CMD_HANDLER(tasks);
821 static int com_ls(__a_unused struct lls_parse_result *lpr)
824 unsigned num_inputs = lls_num_inputs(play_lpr);
826 for (i = 0; i < num_inputs; i++)
830 EXPORT_PLAY_CMD_HANDLER(ls);
832 static int com_play(struct lls_parse_result *lpr)
838 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
841 PARA_ERROR_LOG("%s\n", errctx);
845 state = get_playback_state();
846 if (lls_num_inputs(lpr) == 0) {
849 pt->next_file = pt->current_file;
854 ret = para_atoi32(lls_input(0, lpr), &x);
857 if (x < 0 || x >= lls_num_inputs(play_lpr))
858 return -ERRNO_TO_PARA_ERROR(EINVAL);
861 pt->rq = CRT_FILE_CHANGE;
864 EXPORT_PLAY_CMD_HANDLER(play);
866 static int com_pause(__a_unused struct lls_parse_result *lpr)
869 long unsigned seconds, ss;
871 state = get_playback_state();
875 seconds = get_play_time();
879 ss = seconds * pt->num_chunks / pt->seconds + 1;
880 ss = PARA_MAX(ss, 0UL);
881 ss = PARA_MIN(ss, pt->num_chunks);
882 pt->start_chunk = ss;
886 EXPORT_PLAY_CMD_HANDLER(pause);
888 static int com_prev(__a_unused struct lls_parse_result *lpr)
892 ret = previous_valid_file();
897 pt->rq = CRT_FILE_CHANGE;
901 EXPORT_PLAY_CMD_HANDLER(prev);
903 static int com_next(__a_unused struct lls_parse_result *lpr)
907 ret = next_valid_file();
912 pt->rq = CRT_FILE_CHANGE;
916 EXPORT_PLAY_CMD_HANDLER(next);
918 static int com_fg(__a_unused struct lls_parse_result *lpr)
920 pt->background = false;
923 EXPORT_PLAY_CMD_HANDLER(fg);
925 static int com_bg(__a_unused struct lls_parse_result *lpr)
927 pt->background = true;
930 EXPORT_PLAY_CMD_HANDLER(bg);
932 static int com_jmp(struct lls_parse_result *lpr)
938 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
941 PARA_ERROR_LOG("%s\n", errctx);
945 ret = para_atoi32(lls_input(0, lpr), &percent);
948 if (percent < 0 || percent > 100)
949 return -ERRNO_TO_PARA_ERROR(EINVAL);
951 return com_next(NULL);
952 if (pt->playing && !pt->fn.btrn)
954 pt->start_chunk = percent * pt->num_chunks / 100;
961 EXPORT_PLAY_CMD_HANDLER(jmp);
963 static int com_ff(struct lls_parse_result *lpr)
969 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
972 PARA_ERROR_LOG("%s\n", errctx);
976 ret = para_atoi32(lls_input(0, lpr), &seconds);
979 if (pt->playing && !pt->fn.btrn)
981 seconds += get_play_time();
982 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
983 seconds = PARA_MAX(seconds, 0);
984 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
985 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
986 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
993 EXPORT_PLAY_CMD_HANDLER(ff);
995 static int run_command(char *line)
1000 const struct play_command_info *pci;
1001 struct lls_parse_result *lpr;
1002 const struct lls_command *cmd;
1004 attach_stdout(__FUNCTION__);
1005 ret = create_argv(line, " ", &argv);
1011 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1014 cmd = lls_cmd(ret, play_cmd_suite);
1015 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1018 pci = lls_user_data(cmd);
1019 ret = pci->handler(lpr);
1020 lls_free_parse_result(lpr, cmd);
1023 PARA_ERROR_LOG("%s\n", errctx);
1029 static int play_i9e_line_handler(char *line)
1031 return run_command(line);
1034 static int play_i9e_key_handler(int key)
1036 int idx = get_key_map_idx(key);
1037 char *seq = get_key_map_seq(key);
1038 char *cmd = get_key_map_cmd(key);
1039 bool internal = is_internal_key(key);
1041 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1042 key, internal? "internal" : "user-defined",
1047 pt->next_update = *now;
1051 static struct i9e_client_info ici = {
1053 .prompt = "para_play> ",
1054 .line_handler = play_i9e_line_handler,
1055 .key_handler = play_i9e_key_handler,
1056 .completers = pp_completers,
1059 static void sigint_handler(int sig)
1061 pt->background = true;
1062 i9e_signal_dispatch(sig);
1066 * We start with para_log() set to the standard log function which writes to
1067 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1070 static void session_open(void)
1074 struct sigaction act;
1076 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1077 if (OPT_GIVEN(HISTORY_FILE))
1078 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1080 char *home = para_homedir();
1081 history_file = make_message("%s/.paraslash/play.history",
1085 ici.history_file = history_file;
1086 ici.loglevel = loglevel;
1088 act.sa_handler = sigint_handler;
1089 sigemptyset(&act.sa_mask);
1091 sigaction(SIGINT, &act, NULL);
1092 act.sa_handler = i9e_signal_dispatch;
1093 sigemptyset(&act.sa_mask);
1095 sigaction(SIGWINCH, &act, NULL);
1096 sched.select_function = i9e_select;
1098 ici.bound_keyseqs = get_mapped_keyseqs();
1099 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1100 EMBRACE(.name = __FUNCTION__));
1101 ret = i9e_open(&ici, &sched);
1110 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1114 static void session_update_time_string(char *str, unsigned len)
1119 if (btr_get_output_queue_size(pt->btrn) > 0)
1121 if (btr_get_input_queue_size(pt->btrn) > 0)
1124 ie9_print_status_bar(str, len);
1128 * If we are about to die we must call i9e_close() to reset the terminal.
1129 * However, i9e_close() must be called in *this* context, i.e. from
1130 * play_task.post_select() rather than from i9e_post_select(), because
1131 * otherwise i9e would access freed memory upon return. So the play task must
1132 * stay alive until the i9e task terminates.
1134 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1135 * and reschedule. In the next iteration, i9e->post_select returns an error and
1136 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1137 * are allowed to call i9e_close() and terminate as well.
1139 static int session_post_select(__a_unused struct sched *s)
1146 attach_stdout(__FUNCTION__);
1147 ret = i9e_get_error();
1151 para_log = stderr_log;
1152 free(ici.history_file);
1155 if (get_playback_state() == 'X')
1156 i9e_signal_dispatch(SIGTERM);
1160 #else /* HAVE_READLINE */
1162 static int session_post_select(struct sched *s)
1166 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1168 if (read(STDIN_FILENO, &c, 1))
1174 static void session_open(void)
1178 static void session_update_time_string(char *str, __a_unused unsigned len)
1180 printf("\r%s ", str);
1183 #endif /* HAVE_READLINE */
1185 static void play_pre_select(struct sched *s, __a_unused void *context)
1189 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1190 state = get_playback_state();
1191 if (state == 'R' || state == 'F' || state == 'X')
1192 return sched_min_delay(s);
1193 sched_request_barrier_or_min_delay(&pt->next_update, s);
1196 static unsigned get_time_string(char **result)
1198 int seconds, length;
1199 char state = get_playback_state();
1201 /* do not return anything if things are about to change */
1202 if (state != 'P' && state != 'U') {
1206 length = pt->seconds;
1208 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1209 seconds = get_play_time();
1210 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1214 (length - seconds) / 60,
1215 (length - seconds) % 60,
1216 length? (seconds * 100 + length / 2) / length : 0,
1219 get_playlist_file(pt->current_file)
1223 static int play_post_select(struct sched *s, __a_unused void *context)
1227 ret = eof_cleanup();
1229 pt->rq = CRT_TERM_RQ;
1232 ret = session_post_select(s);
1235 if (!pt->wn.btrn && !pt->fn.btrn) {
1236 char state = get_playback_state();
1237 if (state == 'P' || state == 'R' || state == 'F') {
1238 PARA_NOTICE_LOG("state: %c\n", state);
1239 ret = load_next_file();
1241 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1242 pt->rq = CRT_TERM_RQ;
1246 pt->next_update = *now;
1249 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1251 unsigned len = get_time_string(&str);
1252 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1254 session_update_time_string(str, len);
1256 tv_add(now, &delay, &pt->next_update);
1264 * The main function of para_play.
1266 * \param argc Standard.
1267 * \param argv Standard.
1269 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1271 int main(int argc, char *argv[])
1274 unsigned num_inputs;
1276 /* needed this early to make help work */
1279 sched.default_timeout.tv_sec = 5;
1280 parse_config_or_die(argc, argv);
1283 num_inputs = lls_num_inputs(play_lpr);
1285 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1286 pt->rq = CRT_FILE_CHANGE;
1287 pt->current_file = num_inputs - 1;
1289 pt->task = task_register(&(struct task_info){
1291 .pre_select = play_pre_select,
1292 .post_select = play_post_select,
1295 ret = schedule(&sched);
1296 sched_shutdown(&sched);
1298 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1299 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;