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"
16 #include "buffer_tree.h"
27 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
28 * para_play creates two further tasks: The play task and the i9e task. It is
29 * important whether a function can be called in the context of para_play or
30 * i9e or both. As a rule, all command handlers are called only in i9e context via
31 * the line handler (input mode) or the key handler (command mode) below.
33 * Playlist handling is done exclusively in play context.
36 /** Array of error strings. */
39 static struct lls_parse_result *play_lpr;
41 #define CMD_PTR (lls_cmd(0, play_suite))
42 #define OPT_RESULT(_name) \
43 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
44 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
45 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
46 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
49 * Describes a request to change the state of para_play.
51 * There is only one variable of this type: \a rq of the global play task
52 * structure. Command handlers only set this variable and the post_select()
53 * function of the play task investigates its value during each iteration of
54 * the scheduler run and performs the actual work.
56 enum state_change_request_type {
57 /** Everybody is happy. */
59 /** Stream must be repositioned (com_jmp(), com_ff()). */
61 /** New file should be loaded (com_next()). */
63 /** Someone wants us for dead (com_quit()). */
69 /* A bit array of invalid files (those will be skipped). */
71 /* The file which is currently open. */
72 unsigned current_file;
73 /* When to update the status again. */
74 struct timeval next_update;
76 /* Root of the buffer tree for command and status output. */
77 struct btr_node *btrn;
79 /* The decoding machinery. */
80 struct receiver_node rn;
81 struct filter_node fn;
82 struct writer_node wn;
84 /* See comment to enum \ref state_change_request_type above. */
85 enum state_change_request_type rq;
86 /* only relevant if rq == CRT_FILE_CHANGE */
89 bg: read lines at prompt, fg: display status and wait
94 /* We have the *intention* to play. Set by com_play(). */
97 /* as returned by afh_recv->open() */
100 /* retrieved via the btr exec mechanism */
101 long unsigned start_chunk;
102 long unsigned seconds;
103 long unsigned num_chunks;
107 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
108 struct play_command_info {
109 play_cmd_handler_t handler;
111 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
112 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
113 .handler = com_ ## _cmd \
116 static int loglevel = LL_WARNING;
118 /** The log function which writes log messages to stderr. */
119 INIT_STDERR_LOGGING(loglevel);
121 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
123 static struct sched sched = {.max_fileno = 0};
124 static struct play_task play_task, *pt = &play_task;
126 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
127 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
129 static unsigned *shuffle_map;
131 static const char *get_playlist_file(unsigned idx)
133 return lls_input(shuffle_map[idx], play_lpr);
136 static void handle_help_flags(void)
140 if (OPT_GIVEN(DETAILED_HELP))
141 help = lls_long_help(CMD_PTR);
142 else if (OPT_GIVEN(HELP) || lls_num_inputs(play_lpr) == 0)
143 help = lls_short_help(CMD_PTR);
146 printf("%s\n", help);
151 static void parse_config_or_die(int argc, char *argv[])
153 const struct lls_command *cmd = CMD_PTR;
155 char *cf, *errctx, **cf_argv;
156 struct lls_parse_result *cf_lpr, *merged_lpr;
161 ret = lls(lls_parse(argc, argv, cmd, &play_lpr, &errctx));
164 loglevel = OPT_UINT32_VAL(LOGLEVEL);
165 version_handle_flag("play", OPT_GIVEN(VERSION));
166 handle_help_flags(); /* also handles the zero-arg case */
167 if (OPT_GIVEN(CONFIG_FILE))
168 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
170 char *home = para_homedir();
171 cf = make_message("%s/.paraslash/play.conf", home);
174 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
176 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
178 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
183 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
184 para_munmap(map, sz);
188 ret = lls(lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx));
189 lls_free_argv(cf_argv);
192 ret = lls(lls_merge(play_lpr, cf_lpr, cmd, &merged_lpr, &errctx));
193 lls_free_parse_result(cf_lpr, cmd);
196 lls_free_parse_result(play_lpr, cmd);
197 play_lpr = merged_lpr;
198 loglevel = OPT_UINT32_VAL(LOGLEVEL);
200 num_kmas = OPT_GIVEN(KEY_MAP);
201 for (i = 0; i < num_kmas; i++) {
202 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
203 if (*kma && strchr(kma + 1, ':'))
205 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
213 lls_free_parse_result(play_lpr, cmd);
216 PARA_EMERG_LOG("%s\n", errctx);
218 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
222 static char get_playback_state(void)
225 case CRT_NONE: return pt->playing? 'P' : 'U';
226 case CRT_REPOS: return 'R';
227 case CRT_FILE_CHANGE: return 'F';
228 case CRT_TERM_RQ: return 'X';
233 static long unsigned get_play_time(void)
235 char state = get_playback_state();
236 long unsigned result;
238 if (state != 'P' && state != 'U')
240 if (pt->num_chunks == 0 || pt->seconds == 0)
242 /* where the stream started (in seconds) */
243 result = pt->start_chunk * pt->seconds / pt->num_chunks;
244 if (pt->wn.btrn) { /* Add the uptime of the writer node */
245 struct timeval diff = {.tv_sec = 0}, wstime;
246 btr_get_node_start(pt->wn.btrn, &wstime);
247 if (wstime.tv_sec > 0)
248 tv_diff(now, &wstime, &diff);
249 result += diff.tv_sec;
251 result = PARA_MIN(result, pt->seconds);
252 result = PARA_MAX(result, 0UL);
257 static void wipe_receiver_node(void)
259 PARA_NOTICE_LOG("cleaning up receiver node\n");
260 btr_remove_node(&pt->rn.btrn);
261 AFH_RECV->close(&pt->rn);
262 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
263 memset(&pt->rn, 0, sizeof(struct receiver_node));
266 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
267 static int get_playback_error(void)
273 err = task_status(pt->wn.task);
276 if (task_status(pt->fn.task) >= 0)
278 if (task_status(pt->rn.task) >= 0)
280 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
281 || err == -E_WRITE_COMMON_EOF)
286 static int eof_cleanup(void)
288 const struct filter *decoder;
289 const struct writer *w = writer_get(-1); /* default writer */
292 ret = get_playback_error();
295 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
296 task_reap(&pt->wn.task);
298 btr_remove_node(&pt->wn.btrn);
299 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
300 memset(&pt->wn, 0, sizeof(struct writer_node));
302 decoder = filter_get(pt->fn.filter_num);
303 task_reap(&pt->fn.task);
305 decoder->close(&pt->fn);
306 btr_remove_node(&pt->fn.btrn);
308 memset(&pt->fn, 0, sizeof(struct filter_node));
310 task_reap(&pt->rn.task);
311 btr_remove_node(&pt->rn.btrn);
313 * On eof (ret > 0), we do not wipe the receiver node struct until a
314 * new file is loaded because we still need it for jumping around when
318 wipe_receiver_node();
322 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
324 return para_random(100) - 50;
327 static void init_shuffle_map(void)
329 unsigned n, num_inputs = lls_num_inputs(play_lpr);
330 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
331 for (n = 0; n < num_inputs; n++)
333 if (!OPT_GIVEN(RANDOMIZE))
336 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
339 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
341 return btr_new_node(&(struct btr_node_description)
342 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
343 .handler = AFH_RECV->execute));
346 static int open_new_file(void)
349 const char *path = get_playlist_file(pt->next_file);
350 char *tmp = para_strdup(path), *errctx;
351 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
353 PARA_NOTICE_LOG("next file: %s\n", path);
354 wipe_receiver_node();
356 pt->rn.btrn = new_recv_btrn(&pt->rn);
357 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
358 &pt->rn.lpr, &errctx));
361 pt->rn.receiver = AFH_RECV;
362 ret = AFH_RECV->open(&pt->rn);
364 PARA_ERROR_LOG("could not open %s\n", path);
367 pt->audio_format_num = ret;
369 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
371 pt->afhi_txt = make_message("[afhi command failed]\n");
372 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
377 ret = para_atoi32(tmp, &x);
378 pt->seconds = ret < 0? 1 : x;
382 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
387 ret = para_atoi32(tmp, &x);
388 pt->num_chunks = ret < 0? 1 : x;
394 wipe_receiver_node();
398 static int load_file(void)
403 const struct filter *decoder;
404 static struct lls_parse_result *filter_lpr, *writer_lpr;
406 btr_remove_node(&pt->rn.btrn);
407 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
408 ret = open_new_file();
412 pt->rn.btrn = new_recv_btrn(&pt->rn);
413 sprintf(buf, "repos %lu", pt->start_chunk);
414 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
416 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
421 /* set up decoding filter */
422 af = audio_format_name(pt->audio_format_num);
423 tmp = make_message("%sdec", af);
424 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
428 pt->fn.filter_num = ret;
429 pt->fn.lpr = filter_lpr;
430 decoder = filter_get(ret);
431 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
432 EMBRACE(.name = filter_name(pt->fn.filter_num),
433 .parent = pt->rn.btrn, .handler = decoder->execute,
434 .context = &pt->fn));
436 decoder->open(&pt->fn);
437 PARA_INFO_LOG("buffer tree:\n");
438 btr_log_tree(pt->rn.btrn, LL_INFO);
440 /* setup default writer */
441 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
442 pt->wn.lpr = writer_lpr;
443 /* success, register tasks */
444 pt->rn.task = task_register(
445 &(struct task_info) {
446 .name = lls_command_name(AFH_RECV_CMD),
447 .pre_select = AFH_RECV->pre_select,
448 .post_select = AFH_RECV->post_select,
451 sprintf(buf, "%s decoder", af);
452 pt->fn.task = task_register(
453 &(struct task_info) {
455 .pre_select = decoder->pre_select,
456 .post_select = decoder->post_select,
459 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
462 wipe_receiver_node();
466 static int next_valid_file(void)
468 int i, j = pt->current_file;
469 unsigned num_inputs = lls_num_inputs(play_lpr);
471 for (i = 0; i < num_inputs; i++) {
472 j = (j + 1) % num_inputs;
476 return -E_NO_VALID_FILES;
479 static int load_next_file(void)
484 if (pt->rq == CRT_NONE) {
486 ret = next_valid_file();
490 } else if (pt->rq == CRT_REPOS)
491 pt->next_file = pt->current_file;
494 PARA_ERROR_LOG("%s: marking file as invalid\n",
495 para_strerror(-ret));
496 pt->invalid[pt->next_file] = true;
500 pt->current_file = pt->next_file;
505 static void kill_stream(void)
508 task_notify(pt->wn.task, E_EOF);
513 /* only called from com_prev(), nec. only if we have readline */
514 static int previous_valid_file(void)
516 int i, j = pt->current_file;
517 unsigned num_inputs = lls_num_inputs(play_lpr);
519 for (i = 0; i < num_inputs; i++) {
526 return -E_NO_VALID_FILES;
529 #include "interactive.h"
532 * Define the default (internal) key mappings and helper functions to get the
533 * key sequence or the command from a key id, which is what we obtain from
534 * i9e/readline when the key is pressed.
536 * In some of these helper functions we could return pointers to the constant
537 * arrays defined below. However, for others we can not, so let's better be
538 * consistent and allocate all returned strings on the heap.
541 #define INTERNAL_KEYMAP_ENTRIES \
542 KEYMAP_ENTRY("^", "jmp 0"), \
543 KEYMAP_ENTRY("1", "jmp 10"), \
544 KEYMAP_ENTRY("2", "jmp 21"), \
545 KEYMAP_ENTRY("3", "jmp 32"), \
546 KEYMAP_ENTRY("4", "jmp 43"), \
547 KEYMAP_ENTRY("5", "jmp 54"), \
548 KEYMAP_ENTRY("6", "jmp 65"), \
549 KEYMAP_ENTRY("7", "jmp 76"), \
550 KEYMAP_ENTRY("8", "jmp 87"), \
551 KEYMAP_ENTRY("9", "jmp 98"), \
552 KEYMAP_ENTRY("+", "next"), \
553 KEYMAP_ENTRY("-", "prev"), \
554 KEYMAP_ENTRY(":", "bg"), \
555 KEYMAP_ENTRY("i", "info"), \
556 KEYMAP_ENTRY("l", "ls"), \
557 KEYMAP_ENTRY("s", "play"), \
558 KEYMAP_ENTRY("p", "pause"), \
559 KEYMAP_ENTRY("q", "quit"), \
560 KEYMAP_ENTRY("?", "help"), \
561 KEYMAP_ENTRY("\033[D", "ff -10"), \
562 KEYMAP_ENTRY("\033[C", "ff 10"), \
563 KEYMAP_ENTRY("\033[A", "ff 60"), \
564 KEYMAP_ENTRY("\033[B", "ff -60"), \
566 #define KEYMAP_ENTRY(a, b) a
567 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
569 #define KEYMAP_ENTRY(a, b) b
570 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
572 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
573 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
574 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
576 static inline bool is_internal_key(int key)
578 return key < NUM_INTERNALLY_MAPPED_KEYS;
581 /* for internal keys, the key id is just the array index. */
582 static inline int get_internal_key_map_idx(int key)
584 assert(is_internal_key(key));
589 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
590 * difference is the index to the array of user defined key maps.
592 static inline int get_user_key_map_idx(int key)
594 assert(!is_internal_key(key));
595 return key - NUM_INTERNALLY_MAPPED_KEYS;
598 static inline int get_key_map_idx(int key)
600 return is_internal_key(key)?
601 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
604 static inline const char *get_user_key_map_arg(int key)
606 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
609 static inline char *get_internal_key_map_seq(int key)
611 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
614 static char *get_user_key_map_seq(int key)
616 const char *kma = get_user_key_map_arg(key);
617 const char *p = strchr(kma + 1, ':');
624 result = para_malloc(len + 1);
625 memcpy(result, kma, len);
630 static char *get_key_map_seq(int key)
632 return is_internal_key(key)?
633 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
636 static char *get_key_map_seq_safe(int key)
638 const char hex[] = "0123456789abcdef";
639 char *seq = get_key_map_seq(key), *sseq;
640 size_t n, len = strlen(seq);
642 if (len == 1 && isprint(*seq))
644 sseq = para_malloc(2 + 2 * len + 1);
647 for (n = 0; n < len; n++) {
648 uint8_t val = (seq[n] & 0xf0) >> 4;
649 sseq[2 + 2 * n] = hex[val];
651 sseq[2 + 2 * n + 1] = hex[val];
654 sseq[2 + 2 * n] = '\0';
658 static inline char *get_internal_key_map_cmd(int key)
660 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
663 static char *get_user_key_map_cmd(int key)
665 const char *kma = get_user_key_map_arg(key);
666 const char *p = strchr(kma + 1, ':');
670 return para_strdup(p + 1);
673 static char *get_key_map_cmd(int key)
675 return is_internal_key(key)?
676 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
679 static char **get_mapped_keyseqs(void)
684 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
685 FOR_EACH_MAPPED_KEY(i) {
686 char *seq = get_key_map_seq(i);
693 static struct i9e_completer pp_completers[];
695 I9E_DUMMY_COMPLETER(jmp);
696 I9E_DUMMY_COMPLETER(next);
697 I9E_DUMMY_COMPLETER(prev);
698 I9E_DUMMY_COMPLETER(fg);
699 I9E_DUMMY_COMPLETER(bg);
700 I9E_DUMMY_COMPLETER(ls);
701 I9E_DUMMY_COMPLETER(info);
702 I9E_DUMMY_COMPLETER(play);
703 I9E_DUMMY_COMPLETER(pause);
704 I9E_DUMMY_COMPLETER(tasks);
705 I9E_DUMMY_COMPLETER(quit);
706 I9E_DUMMY_COMPLETER(ff);
708 static void help_completer(struct i9e_completion_info *ci,
709 struct i9e_completion_result *result)
711 result->matches = i9e_complete_commands(ci->word, pp_completers);
714 static struct i9e_completer pp_completers[] = {
715 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
716 .completer = _name ## _completer}
717 LSG_PLAY_CMD_SUBCOMMANDS
718 #undef LSG_PLAY_CMD_CMD
722 static void attach_stdout(const char *name)
726 pt->btrn = btr_new_node(&(struct btr_node_description)
727 EMBRACE(.name = name));
728 i9e_attach_to_stdout(pt->btrn);
731 static void detach_stdout(void)
733 btr_remove_node(&pt->btrn);
736 static int com_quit(__a_unused struct lls_parse_result *lpr)
738 pt->rq = CRT_TERM_RQ;
741 EXPORT_PLAY_CMD_HANDLER(quit);
743 static int com_help(struct lls_parse_result *lpr)
748 const struct lls_command *cmd;
750 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
753 PARA_ERROR_LOG("%s\n", errctx);
757 if (lls_num_inputs(lpr) == 0) {
758 if (pt->background) {
759 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
760 sz = xasprintf(&buf, "%s\t%s\n",
761 lls_command_name(cmd), lls_purpose(cmd));
762 btr_add_output(buf, sz, pt->btrn);
766 FOR_EACH_MAPPED_KEY(i) {
767 bool internal = is_internal_key(i);
768 int idx = get_key_map_idx(i);
769 char *seq = get_key_map_seq_safe(i);
770 char *kmc = get_key_map_cmd(i);
771 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
772 internal? "internal" : "user-defined",
774 btr_add_output(buf, sz, pt->btrn);
780 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
784 PARA_ERROR_LOG("%s\n", errctx);
788 cmd = lls_cmd(ret, play_cmd_suite);
789 buf = lls_long_help(cmd);
791 btr_add_output(buf, strlen(buf), pt->btrn);
794 EXPORT_PLAY_CMD_HANDLER(help);
796 static int com_info(__a_unused struct lls_parse_result *lpr)
800 static char dflt[] = "[no information available]";
802 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
803 pt->current_file, get_playlist_file(pt->current_file));
804 btr_add_output(buf, sz, pt->btrn);
805 buf = pt->afhi_txt? pt->afhi_txt : dflt;
806 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
809 EXPORT_PLAY_CMD_HANDLER(info);
811 static void list_file(int num)
816 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
817 "*" : " ", num, get_playlist_file(num));
818 btr_add_output(buf, sz, pt->btrn);
821 static int com_tasks(__a_unused struct lls_parse_result *lpr)
827 buf = get_task_list(&sched);
828 btr_add_output(buf, strlen(buf), pt->btrn);
829 state = get_playback_state();
830 sz = xasprintf(&buf, "state: %c\n", state);
831 btr_add_output(buf, sz, pt->btrn);
834 EXPORT_PLAY_CMD_HANDLER(tasks);
836 static int com_ls(__a_unused struct lls_parse_result *lpr)
839 unsigned num_inputs = lls_num_inputs(play_lpr);
841 for (i = 0; i < num_inputs; i++)
845 EXPORT_PLAY_CMD_HANDLER(ls);
847 static int com_play(struct lls_parse_result *lpr)
853 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
856 PARA_ERROR_LOG("%s\n", errctx);
860 state = get_playback_state();
861 if (lls_num_inputs(lpr) == 0) {
864 pt->next_file = pt->current_file;
869 ret = para_atoi32(lls_input(0, lpr), &x);
872 if (x < 0 || x >= lls_num_inputs(play_lpr))
873 return -ERRNO_TO_PARA_ERROR(EINVAL);
876 pt->rq = CRT_FILE_CHANGE;
879 EXPORT_PLAY_CMD_HANDLER(play);
881 static int com_pause(__a_unused struct lls_parse_result *lpr)
884 long unsigned seconds, ss;
886 state = get_playback_state();
890 seconds = get_play_time();
894 ss = seconds * pt->num_chunks / pt->seconds + 1;
895 ss = PARA_MAX(ss, 0UL);
896 ss = PARA_MIN(ss, pt->num_chunks);
897 pt->start_chunk = ss;
901 EXPORT_PLAY_CMD_HANDLER(pause);
903 static int com_prev(__a_unused struct lls_parse_result *lpr)
907 ret = previous_valid_file();
912 pt->rq = CRT_FILE_CHANGE;
916 EXPORT_PLAY_CMD_HANDLER(prev);
918 static int com_next(__a_unused struct lls_parse_result *lpr)
922 ret = next_valid_file();
927 pt->rq = CRT_FILE_CHANGE;
931 EXPORT_PLAY_CMD_HANDLER(next);
933 static int com_fg(__a_unused struct lls_parse_result *lpr)
935 pt->background = false;
938 EXPORT_PLAY_CMD_HANDLER(fg);
940 static int com_bg(__a_unused struct lls_parse_result *lpr)
942 pt->background = true;
945 EXPORT_PLAY_CMD_HANDLER(bg);
947 static int com_jmp(struct lls_parse_result *lpr)
953 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
956 PARA_ERROR_LOG("%s\n", errctx);
960 ret = para_atoi32(lls_input(0, lpr), &percent);
963 if (percent < 0 || percent > 100)
964 return -ERRNO_TO_PARA_ERROR(EINVAL);
966 return com_next(NULL);
967 if (pt->playing && !pt->fn.btrn)
969 pt->start_chunk = percent * pt->num_chunks / 100;
976 EXPORT_PLAY_CMD_HANDLER(jmp);
978 static int com_ff(struct lls_parse_result *lpr)
984 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
987 PARA_ERROR_LOG("%s\n", errctx);
991 ret = para_atoi32(lls_input(0, lpr), &seconds);
994 if (pt->playing && !pt->fn.btrn)
996 seconds += get_play_time();
997 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
998 seconds = PARA_MAX(seconds, 0);
999 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
1000 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
1001 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1008 EXPORT_PLAY_CMD_HANDLER(ff);
1010 static int run_command(char *line)
1014 char *errctx = NULL;
1015 const struct play_command_info *pci;
1016 struct lls_parse_result *lpr;
1017 const struct lls_command *cmd;
1019 attach_stdout(__FUNCTION__);
1020 ret = create_argv(line, " ", &argv);
1026 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1029 cmd = lls_cmd(ret, play_cmd_suite);
1030 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1033 pci = lls_user_data(cmd);
1034 ret = pci->handler(lpr);
1035 lls_free_parse_result(lpr, cmd);
1038 PARA_ERROR_LOG("%s\n", errctx);
1044 static int play_i9e_line_handler(char *line)
1046 return run_command(line);
1049 static int play_i9e_key_handler(int key)
1051 int idx = get_key_map_idx(key);
1052 char *seq = get_key_map_seq(key);
1053 char *cmd = get_key_map_cmd(key);
1054 bool internal = is_internal_key(key);
1056 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1057 key, internal? "internal" : "user-defined",
1062 pt->next_update = *now;
1066 static struct i9e_client_info ici = {
1068 .prompt = "para_play> ",
1069 .line_handler = play_i9e_line_handler,
1070 .key_handler = play_i9e_key_handler,
1071 .completers = pp_completers,
1074 static void sigint_handler(int sig)
1076 pt->background = true;
1077 i9e_signal_dispatch(sig);
1081 * We start with para_log() set to the standard log function which writes to
1082 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1085 static void session_open(void)
1089 struct sigaction act;
1091 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1092 if (OPT_GIVEN(HISTORY_FILE))
1093 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1095 char *home = para_homedir();
1096 history_file = make_message("%s/.paraslash/play.history",
1100 ici.history_file = history_file;
1101 ici.loglevel = loglevel;
1103 act.sa_handler = sigint_handler;
1104 sigemptyset(&act.sa_mask);
1106 sigaction(SIGINT, &act, NULL);
1107 act.sa_handler = i9e_signal_dispatch;
1108 sigemptyset(&act.sa_mask);
1110 sigaction(SIGWINCH, &act, NULL);
1111 sched.select_function = i9e_select;
1113 ici.bound_keyseqs = get_mapped_keyseqs();
1114 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1115 EMBRACE(.name = __FUNCTION__));
1116 ret = i9e_open(&ici, &sched);
1125 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1129 static void session_update_time_string(char *str, unsigned len)
1134 if (btr_get_output_queue_size(pt->btrn) > 0)
1136 if (btr_get_input_queue_size(pt->btrn) > 0)
1139 ie9_print_status_bar(str, len);
1143 * If we are about to die we must call i9e_close() to reset the terminal.
1144 * However, i9e_close() must be called in *this* context, i.e. from
1145 * play_task.post_select() rather than from i9e_post_select(), because
1146 * otherwise i9e would access freed memory upon return. So the play task must
1147 * stay alive until the i9e task terminates.
1149 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1150 * and reschedule. In the next iteration, i9e->post_select returns an error and
1151 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1152 * are allowed to call i9e_close() and terminate as well.
1154 static int session_post_select(__a_unused struct sched *s)
1161 attach_stdout(__FUNCTION__);
1162 ret = i9e_get_error();
1166 para_log = stderr_log;
1167 free(ici.history_file);
1170 if (get_playback_state() == 'X')
1171 i9e_signal_dispatch(SIGTERM);
1175 #else /* HAVE_READLINE */
1177 static int session_post_select(struct sched *s)
1181 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1183 if (read(STDIN_FILENO, &c, 1))
1189 static void session_open(void)
1193 static void session_update_time_string(char *str, __a_unused unsigned len)
1195 printf("\r%s ", str);
1198 #endif /* HAVE_READLINE */
1200 static void play_pre_select(struct sched *s, __a_unused void *context)
1204 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1205 state = get_playback_state();
1206 if (state == 'R' || state == 'F' || state == 'X')
1207 return sched_min_delay(s);
1208 sched_request_barrier_or_min_delay(&pt->next_update, s);
1211 static unsigned get_time_string(char **result)
1213 int seconds, length;
1214 char state = get_playback_state();
1216 /* do not return anything if things are about to change */
1217 if (state != 'P' && state != 'U') {
1221 length = pt->seconds;
1223 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1224 seconds = get_play_time();
1225 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1229 (length - seconds) / 60,
1230 (length - seconds) % 60,
1231 length? (seconds * 100 + length / 2) / length : 0,
1234 get_playlist_file(pt->current_file)
1238 static int play_post_select(struct sched *s, __a_unused void *context)
1242 ret = eof_cleanup();
1244 pt->rq = CRT_TERM_RQ;
1247 ret = session_post_select(s);
1250 if (!pt->wn.btrn && !pt->fn.btrn) {
1251 char state = get_playback_state();
1252 if (state == 'P' || state == 'R' || state == 'F') {
1253 PARA_NOTICE_LOG("state: %c\n", state);
1254 ret = load_next_file();
1256 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1257 pt->rq = CRT_TERM_RQ;
1261 pt->next_update = *now;
1264 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1266 unsigned len = get_time_string(&str);
1267 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1269 session_update_time_string(str, len);
1271 tv_add(now, &delay, &pt->next_update);
1279 * The main function of para_play.
1281 * \param argc Standard.
1282 * \param argv Standard.
1284 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1286 int main(int argc, char *argv[])
1289 unsigned num_inputs;
1291 /* needed this early to make help work */
1294 sched.default_timeout.tv_sec = 5;
1295 parse_config_or_die(argc, argv);
1298 num_inputs = lls_num_inputs(play_lpr);
1300 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1301 pt->rq = CRT_FILE_CHANGE;
1302 pt->current_file = num_inputs - 1;
1304 pt->task = task_register(&(struct task_info){
1306 .pre_select = play_pre_select,
1307 .post_select = play_post_select,
1310 ret = schedule(&sched);
1311 sched_shutdown(&sched);
1313 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1314 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;