2 * Copyright (C) 2012 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file play.c Paraslash's standalone player. */
13 #include "recv_cmd.lsg.h"
14 #include "play_cmd.lsg.h"
15 #include "write_cmd.lsg.h"
20 #include "buffer_tree.h"
31 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
32 * para_play creates two further tasks: The play task and the i9e task. It is
33 * important whether a function can be called in the context of para_play or
34 * i9e or both. As a rule, all command handlers are called only in i9e context via
35 * the line handler (input mode) or the key handler (command mode) below.
37 * Playlist handling is done exclusively in play context.
40 /** Array of error strings. */
43 static struct lls_parse_result *play_lpr;
45 #define CMD_PTR (lls_cmd(0, play_suite))
46 #define OPT_RESULT(_name) \
47 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
48 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
49 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
50 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
53 * Describes a request to change the state of para_play.
55 * There is only one variable of this type: \a rq of the global play task
56 * structure. Command handlers only set this variable and the post_select()
57 * function of the play task investigates its value during each iteration of
58 * the scheduler run and performs the actual work.
60 enum state_change_request_type {
61 /** Everybody is happy. */
63 /** Stream must be repositioned (com_jmp(), com_ff()). */
65 /** New file should be loaded (com_next()). */
67 /** Someone wants us for dead (com_quit()). */
73 /* A bit array of invalid files (those will be skipped). */
75 /* The file which is currently open. */
76 unsigned current_file;
77 /* When to update the status again. */
78 struct timeval next_update;
80 /* Root of the buffer tree for command and status output. */
81 struct btr_node *btrn;
83 /* The decoding machinery. */
84 struct receiver_node rn;
85 struct filter_node fn;
86 struct writer_node wn;
88 /* See comment to enum \ref state_change_request_type above. */
89 enum state_change_request_type rq;
90 /* only relevant if rq == CRT_FILE_CHANGE */
93 bg: read lines at prompt, fg: display status and wait
98 /* We have the *intention* to play. Set by com_play(). */
101 /* as returned by afh_recv->open() */
102 int audio_format_num;
104 /* retrieved via the btr exec mechanism */
105 long unsigned start_chunk;
106 long unsigned seconds;
107 long unsigned num_chunks;
111 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
112 struct play_command_info {
113 play_cmd_handler_t handler;
115 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
116 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
117 .handler = com_ ## _cmd \
120 static int loglevel = LL_WARNING;
122 /** The log function which writes log messages to stderr. */
123 INIT_STDERR_LOGGING(loglevel);
125 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
127 static struct sched sched = {.max_fileno = 0};
128 static struct play_task play_task, *pt = &play_task;
130 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
131 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
133 static unsigned *shuffle_map;
135 static const char *get_playlist_file(unsigned idx)
137 return lls_input(shuffle_map[idx], play_lpr);
140 static void handle_help_flags(void)
144 if (OPT_GIVEN(DETAILED_HELP))
145 help = lls_long_help(CMD_PTR);
146 else if (OPT_GIVEN(HELP))
147 help = lls_short_help(CMD_PTR);
150 printf("%s\n", help);
155 static void parse_config_or_die(int argc, char *argv[])
157 const struct lls_command *cmd = CMD_PTR;
159 char *cf, *errctx, **cf_argv;
160 struct lls_parse_result *cf_lpr, *merged_lpr;
165 ret = lls(lls_parse(argc, argv, cmd, &play_lpr, &errctx));
168 loglevel = OPT_UINT32_VAL(LOGLEVEL);
169 version_handle_flag("play", OPT_GIVEN(VERSION));
171 if (OPT_GIVEN(CONFIG_FILE))
172 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
174 char *home = para_homedir();
175 cf = make_message("%s/.paraslash/play.conf", home);
178 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
180 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
182 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
187 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
188 para_munmap(map, sz);
192 ret = lls(lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx));
193 lls_free_argv(cf_argv);
196 ret = lls(lls_merge(play_lpr, cf_lpr, cmd, &merged_lpr, &errctx));
197 lls_free_parse_result(cf_lpr, cmd);
200 lls_free_parse_result(play_lpr, cmd);
201 play_lpr = merged_lpr;
202 loglevel = OPT_UINT32_VAL(LOGLEVEL);
204 ret = lls(lls_check_arg_count(play_lpr, 1, INT_MAX, &errctx));
207 num_kmas = OPT_GIVEN(KEY_MAP);
208 for (i = 0; i < num_kmas; i++) {
209 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
210 if (*kma && strchr(kma + 1, ':'))
212 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
220 lls_free_parse_result(play_lpr, cmd);
223 PARA_EMERG_LOG("%s\n", errctx);
225 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
229 static char get_playback_state(void)
232 case CRT_NONE: return pt->playing? 'P' : 'U';
233 case CRT_REPOS: return 'R';
234 case CRT_FILE_CHANGE: return 'F';
235 case CRT_TERM_RQ: return 'X';
240 static long unsigned get_play_time(void)
242 char state = get_playback_state();
243 long unsigned result;
245 if (state != 'P' && state != 'U')
247 if (pt->num_chunks == 0 || pt->seconds == 0)
249 /* where the stream started (in seconds) */
250 result = pt->start_chunk * pt->seconds / pt->num_chunks;
251 if (pt->wn.btrn) { /* Add the uptime of the writer node */
252 struct timeval diff = {.tv_sec = 0}, wstime;
253 btr_get_node_start(pt->wn.btrn, &wstime);
254 if (wstime.tv_sec > 0)
255 tv_diff(now, &wstime, &diff);
256 result += diff.tv_sec;
258 result = PARA_MIN(result, pt->seconds);
259 result = PARA_MAX(result, 0UL);
264 static void wipe_receiver_node(void)
266 PARA_NOTICE_LOG("cleaning up receiver node\n");
267 btr_remove_node(&pt->rn.btrn);
268 AFH_RECV->close(&pt->rn);
269 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
270 memset(&pt->rn, 0, sizeof(struct receiver_node));
273 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
274 static int get_playback_error(void)
280 err = task_status(pt->wn.task);
283 if (task_status(pt->fn.task) >= 0)
285 if (task_status(pt->rn.task) >= 0)
287 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
288 || err == -E_WRITE_COMMON_EOF)
293 static int eof_cleanup(void)
295 const struct filter *decoder;
296 const struct writer *w = writer_get(-1); /* default writer */
299 ret = get_playback_error();
302 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
303 task_reap(&pt->wn.task);
305 btr_remove_node(&pt->wn.btrn);
306 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
307 memset(&pt->wn, 0, sizeof(struct writer_node));
309 decoder = filter_get(pt->fn.filter_num);
310 task_reap(&pt->fn.task);
312 decoder->close(&pt->fn);
313 btr_remove_node(&pt->fn.btrn);
315 memset(&pt->fn, 0, sizeof(struct filter_node));
317 task_reap(&pt->rn.task);
318 btr_remove_node(&pt->rn.btrn);
320 * On eof (ret > 0), we do not wipe the receiver node struct until a
321 * new file is loaded because we still need it for jumping around when
325 wipe_receiver_node();
329 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
331 return para_random(100) - 50;
334 static void init_shuffle_map(void)
336 unsigned n, num_inputs = lls_num_inputs(play_lpr);
337 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
338 for (n = 0; n < num_inputs; n++)
340 if (!OPT_GIVEN(RANDOMIZE))
343 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
346 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
348 return btr_new_node(&(struct btr_node_description)
349 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
350 .handler = AFH_RECV->execute));
353 static int open_new_file(void)
356 const char *path = get_playlist_file(pt->next_file);
357 char *tmp = para_strdup(path), *errctx;
358 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
360 PARA_NOTICE_LOG("next file: %s\n", path);
361 wipe_receiver_node();
363 pt->rn.btrn = new_recv_btrn(&pt->rn);
364 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
365 &pt->rn.lpr, &errctx));
368 pt->rn.receiver = AFH_RECV;
369 ret = AFH_RECV->open(&pt->rn);
371 PARA_ERROR_LOG("could not open %s\n", path);
374 pt->audio_format_num = ret;
376 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
378 pt->afhi_txt = make_message("[afhi command failed]\n");
379 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
384 ret = para_atoi32(tmp, &x);
385 pt->seconds = ret < 0? 1 : x;
389 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
394 ret = para_atoi32(tmp, &x);
395 pt->num_chunks = ret < 0? 1 : x;
401 wipe_receiver_node();
405 static int load_file(void)
410 const struct filter *decoder;
411 static struct lls_parse_result *filter_lpr, *writer_lpr;
413 btr_remove_node(&pt->rn.btrn);
414 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
415 ret = open_new_file();
419 pt->rn.btrn = new_recv_btrn(&pt->rn);
420 sprintf(buf, "repos %lu", pt->start_chunk);
421 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
423 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
428 /* set up decoding filter */
429 af = audio_format_name(pt->audio_format_num);
430 tmp = make_message("%sdec", af);
431 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
435 pt->fn.filter_num = ret;
436 pt->fn.lpr = filter_lpr;
437 decoder = filter_get(ret);
438 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
439 EMBRACE(.name = filter_name(pt->fn.filter_num),
440 .parent = pt->rn.btrn, .handler = decoder->execute,
441 .context = &pt->fn));
443 decoder->open(&pt->fn);
444 PARA_INFO_LOG("buffer tree:\n");
445 btr_log_tree(pt->rn.btrn, LL_INFO);
447 /* setup default writer */
448 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
449 pt->wn.lpr = writer_lpr;
450 /* success, register tasks */
451 pt->rn.task = task_register(
452 &(struct task_info) {
453 .name = lls_command_name(AFH_RECV_CMD),
454 .pre_select = AFH_RECV->pre_select,
455 .post_select = AFH_RECV->post_select,
458 sprintf(buf, "%s decoder", af);
459 pt->fn.task = task_register(
460 &(struct task_info) {
462 .pre_select = decoder->pre_select,
463 .post_select = decoder->post_select,
466 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
469 wipe_receiver_node();
473 static int next_valid_file(void)
475 int i, j = pt->current_file;
476 unsigned num_inputs = lls_num_inputs(play_lpr);
478 for (i = 0; i < num_inputs; i++) {
479 j = (j + 1) % num_inputs;
483 return -E_NO_VALID_FILES;
486 static int load_next_file(void)
491 if (pt->rq == CRT_NONE) {
493 ret = next_valid_file();
497 } else if (pt->rq == CRT_REPOS)
498 pt->next_file = pt->current_file;
501 PARA_ERROR_LOG("%s: marking file as invalid\n",
502 para_strerror(-ret));
503 pt->invalid[pt->next_file] = true;
507 pt->current_file = pt->next_file;
512 static void kill_stream(void)
515 task_notify(pt->wn.task, E_EOF);
520 /* only called from com_prev(), nec. only if we have readline */
521 static int previous_valid_file(void)
523 int i, j = pt->current_file;
524 unsigned num_inputs = lls_num_inputs(play_lpr);
526 for (i = 0; i < num_inputs; i++) {
533 return -E_NO_VALID_FILES;
536 #include "interactive.h"
539 * Define the default (internal) key mappings and helper functions to get the
540 * key sequence or the command from a key id, which is what we obtain from
541 * i9e/readline when the key is pressed.
543 * In some of these helper functions we could return pointers to the constant
544 * arrays defined below. However, for others we can not, so let's better be
545 * consistent and allocate all returned strings on the heap.
548 #define INTERNAL_KEYMAP_ENTRIES \
549 KEYMAP_ENTRY("^", "jmp 0"), \
550 KEYMAP_ENTRY("1", "jmp 10"), \
551 KEYMAP_ENTRY("2", "jmp 21"), \
552 KEYMAP_ENTRY("3", "jmp 32"), \
553 KEYMAP_ENTRY("4", "jmp 43"), \
554 KEYMAP_ENTRY("5", "jmp 54"), \
555 KEYMAP_ENTRY("6", "jmp 65"), \
556 KEYMAP_ENTRY("7", "jmp 76"), \
557 KEYMAP_ENTRY("8", "jmp 87"), \
558 KEYMAP_ENTRY("9", "jmp 98"), \
559 KEYMAP_ENTRY("+", "next"), \
560 KEYMAP_ENTRY("-", "prev"), \
561 KEYMAP_ENTRY(":", "bg"), \
562 KEYMAP_ENTRY("i", "info"), \
563 KEYMAP_ENTRY("l", "ls"), \
564 KEYMAP_ENTRY("s", "play"), \
565 KEYMAP_ENTRY("p", "pause"), \
566 KEYMAP_ENTRY("q", "quit"), \
567 KEYMAP_ENTRY("?", "help"), \
568 KEYMAP_ENTRY("\033[D", "ff -10"), \
569 KEYMAP_ENTRY("\033[C", "ff 10"), \
570 KEYMAP_ENTRY("\033[A", "ff 60"), \
571 KEYMAP_ENTRY("\033[B", "ff -60"), \
573 #define KEYMAP_ENTRY(a, b) a
574 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
576 #define KEYMAP_ENTRY(a, b) b
577 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
579 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
580 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
581 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
583 static inline bool is_internal_key(int key)
585 return key < NUM_INTERNALLY_MAPPED_KEYS;
588 /* for internal keys, the key id is just the array index. */
589 static inline int get_internal_key_map_idx(int key)
591 assert(is_internal_key(key));
596 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
597 * difference is the index to the array of user defined key maps.
599 static inline int get_user_key_map_idx(int key)
601 assert(!is_internal_key(key));
602 return key - NUM_INTERNALLY_MAPPED_KEYS;
605 static inline int get_key_map_idx(int key)
607 return is_internal_key(key)?
608 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
611 static inline const char *get_user_key_map_arg(int key)
613 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
616 static inline char *get_internal_key_map_seq(int key)
618 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
621 static char *get_user_key_map_seq(int key)
623 const char *kma = get_user_key_map_arg(key);
624 const char *p = strchr(kma + 1, ':');
631 result = para_malloc(len + 1);
632 memcpy(result, kma, len);
637 static char *get_key_map_seq(int key)
639 return is_internal_key(key)?
640 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
643 static char *get_key_map_seq_safe(int key)
645 const char hex[] = "0123456789abcdef";
646 char *seq = get_key_map_seq(key), *sseq;
647 size_t n, len = strlen(seq);
649 if (len == 1 && isprint(*seq))
651 sseq = para_malloc(2 + 2 * len + 1);
654 for (n = 0; n < len; n++) {
655 uint8_t val = (seq[n] & 0xf0) >> 4;
656 sseq[2 + 2 * n] = hex[val];
658 sseq[2 + 2 * n + 1] = hex[val];
661 sseq[2 + 2 * n] = '\0';
665 static inline char *get_internal_key_map_cmd(int key)
667 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
670 static char *get_user_key_map_cmd(int key)
672 const char *kma = get_user_key_map_arg(key);
673 const char *p = strchr(kma + 1, ':');
677 return para_strdup(p + 1);
680 static char *get_key_map_cmd(int key)
682 return is_internal_key(key)?
683 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
686 static char **get_mapped_keyseqs(void)
691 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
692 FOR_EACH_MAPPED_KEY(i) {
693 char *seq = get_key_map_seq(i);
700 static struct i9e_completer pp_completers[];
702 I9E_DUMMY_COMPLETER(jmp);
703 I9E_DUMMY_COMPLETER(next);
704 I9E_DUMMY_COMPLETER(prev);
705 I9E_DUMMY_COMPLETER(fg);
706 I9E_DUMMY_COMPLETER(bg);
707 I9E_DUMMY_COMPLETER(ls);
708 I9E_DUMMY_COMPLETER(info);
709 I9E_DUMMY_COMPLETER(play);
710 I9E_DUMMY_COMPLETER(pause);
711 I9E_DUMMY_COMPLETER(tasks);
712 I9E_DUMMY_COMPLETER(quit);
713 I9E_DUMMY_COMPLETER(ff);
715 static void help_completer(struct i9e_completion_info *ci,
716 struct i9e_completion_result *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)
755 const struct lls_command *cmd;
757 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
760 PARA_ERROR_LOG("%s\n", errctx);
764 if (lls_num_inputs(lpr) == 0) {
765 if (pt->background) {
766 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
767 sz = xasprintf(&buf, "%s\t%s\n",
768 lls_command_name(cmd), lls_purpose(cmd));
769 btr_add_output(buf, sz, pt->btrn);
773 FOR_EACH_MAPPED_KEY(i) {
774 bool internal = is_internal_key(i);
775 int idx = get_key_map_idx(i);
776 char *seq = get_key_map_seq_safe(i);
777 char *kmc = get_key_map_cmd(i);
778 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
779 internal? "internal" : "user-defined",
781 btr_add_output(buf, sz, pt->btrn);
787 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
791 PARA_ERROR_LOG("%s\n", errctx);
795 cmd = lls_cmd(ret, play_cmd_suite);
796 buf = lls_long_help(cmd);
798 btr_add_output(buf, strlen(buf), pt->btrn);
801 EXPORT_PLAY_CMD_HANDLER(help);
803 static int com_info(__a_unused struct lls_parse_result *lpr)
807 static char dflt[] = "[no information available]";
809 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
810 pt->current_file, get_playlist_file(pt->current_file));
811 btr_add_output(buf, sz, pt->btrn);
812 buf = pt->afhi_txt? pt->afhi_txt : dflt;
813 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
816 EXPORT_PLAY_CMD_HANDLER(info);
818 static void list_file(int num)
823 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
824 "*" : " ", num, get_playlist_file(num));
825 btr_add_output(buf, sz, pt->btrn);
828 static int com_tasks(__a_unused struct lls_parse_result *lpr)
834 buf = get_task_list(&sched);
835 btr_add_output(buf, strlen(buf), pt->btrn);
836 state = get_playback_state();
837 sz = xasprintf(&buf, "state: %c\n", state);
838 btr_add_output(buf, sz, pt->btrn);
841 EXPORT_PLAY_CMD_HANDLER(tasks);
843 static int com_ls(__a_unused struct lls_parse_result *lpr)
846 unsigned num_inputs = lls_num_inputs(play_lpr);
848 for (i = 0; i < num_inputs; i++)
852 EXPORT_PLAY_CMD_HANDLER(ls);
854 static int com_play(struct lls_parse_result *lpr)
860 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
863 PARA_ERROR_LOG("%s\n", errctx);
867 state = get_playback_state();
868 if (lls_num_inputs(lpr) == 0) {
871 pt->next_file = pt->current_file;
876 ret = para_atoi32(lls_input(0, lpr), &x);
879 if (x < 0 || x >= lls_num_inputs(play_lpr))
880 return -ERRNO_TO_PARA_ERROR(EINVAL);
883 pt->rq = CRT_FILE_CHANGE;
886 EXPORT_PLAY_CMD_HANDLER(play);
888 static int com_pause(__a_unused struct lls_parse_result *lpr)
891 long unsigned seconds, ss;
893 state = get_playback_state();
897 seconds = get_play_time();
901 ss = seconds * pt->num_chunks / pt->seconds + 1;
902 ss = PARA_MAX(ss, 0UL);
903 ss = PARA_MIN(ss, pt->num_chunks);
904 pt->start_chunk = ss;
908 EXPORT_PLAY_CMD_HANDLER(pause);
910 static int com_prev(__a_unused struct lls_parse_result *lpr)
914 ret = previous_valid_file();
919 pt->rq = CRT_FILE_CHANGE;
923 EXPORT_PLAY_CMD_HANDLER(prev);
925 static int com_next(__a_unused struct lls_parse_result *lpr)
929 ret = next_valid_file();
934 pt->rq = CRT_FILE_CHANGE;
938 EXPORT_PLAY_CMD_HANDLER(next);
940 static int com_fg(__a_unused struct lls_parse_result *lpr)
942 pt->background = false;
945 EXPORT_PLAY_CMD_HANDLER(fg);
947 static int com_bg(__a_unused struct lls_parse_result *lpr)
949 pt->background = true;
952 EXPORT_PLAY_CMD_HANDLER(bg);
954 static int com_jmp(struct lls_parse_result *lpr)
960 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
963 PARA_ERROR_LOG("%s\n", errctx);
967 ret = para_atoi32(lls_input(0, lpr), &percent);
970 if (percent < 0 || percent > 100)
971 return -ERRNO_TO_PARA_ERROR(EINVAL);
973 return com_next(NULL);
974 if (pt->playing && !pt->fn.btrn)
976 pt->start_chunk = percent * pt->num_chunks / 100;
983 EXPORT_PLAY_CMD_HANDLER(jmp);
985 static int com_ff(struct lls_parse_result *lpr)
991 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
994 PARA_ERROR_LOG("%s\n", errctx);
998 ret = para_atoi32(lls_input(0, lpr), &seconds);
1001 if (pt->playing && !pt->fn.btrn)
1003 seconds += get_play_time();
1004 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
1005 seconds = PARA_MAX(seconds, 0);
1006 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
1007 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
1008 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1015 EXPORT_PLAY_CMD_HANDLER(ff);
1017 static int run_command(char *line)
1021 char *errctx = NULL;
1022 const struct play_command_info *pci;
1023 struct lls_parse_result *lpr;
1024 const struct lls_command *cmd;
1026 attach_stdout(__FUNCTION__);
1027 ret = create_argv(line, " ", &argv);
1033 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1036 cmd = lls_cmd(ret, play_cmd_suite);
1037 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1040 pci = lls_user_data(cmd);
1041 ret = pci->handler(lpr);
1042 lls_free_parse_result(lpr, cmd);
1045 PARA_ERROR_LOG("%s\n", errctx);
1051 static int play_i9e_line_handler(char *line)
1053 return run_command(line);
1056 static int play_i9e_key_handler(int key)
1058 int idx = get_key_map_idx(key);
1059 char *seq = get_key_map_seq(key);
1060 char *cmd = get_key_map_cmd(key);
1061 bool internal = is_internal_key(key);
1063 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1064 key, internal? "internal" : "user-defined",
1069 pt->next_update = *now;
1073 static struct i9e_client_info ici = {
1075 .prompt = "para_play> ",
1076 .line_handler = play_i9e_line_handler,
1077 .key_handler = play_i9e_key_handler,
1078 .completers = pp_completers,
1081 static void sigint_handler(int sig)
1083 pt->background = true;
1084 i9e_signal_dispatch(sig);
1088 * We start with para_log() set to the standard log function which writes to
1089 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1092 static void session_open(void)
1096 struct sigaction act;
1098 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1099 if (OPT_GIVEN(HISTORY_FILE))
1100 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1102 char *home = para_homedir();
1103 history_file = make_message("%s/.paraslash/play.history",
1107 ici.history_file = history_file;
1108 ici.loglevel = loglevel;
1110 act.sa_handler = sigint_handler;
1111 sigemptyset(&act.sa_mask);
1113 sigaction(SIGINT, &act, NULL);
1114 act.sa_handler = i9e_signal_dispatch;
1115 sigemptyset(&act.sa_mask);
1117 sigaction(SIGWINCH, &act, NULL);
1118 sched.select_function = i9e_select;
1120 ici.bound_keyseqs = get_mapped_keyseqs();
1121 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1122 EMBRACE(.name = __FUNCTION__));
1123 ret = i9e_open(&ici, &sched);
1132 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1136 static void session_update_time_string(char *str, unsigned len)
1141 if (btr_get_output_queue_size(pt->btrn) > 0)
1143 if (btr_get_input_queue_size(pt->btrn) > 0)
1146 ie9_print_status_bar(str, len);
1150 * If we are about to die we must call i9e_close() to reset the terminal.
1151 * However, i9e_close() must be called in *this* context, i.e. from
1152 * play_task.post_select() rather than from i9e_post_select(), because
1153 * otherwise i9e would access freed memory upon return. So the play task must
1154 * stay alive until the i9e task terminates.
1156 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1157 * and reschedule. In the next iteration, i9e->post_select returns an error and
1158 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1159 * are allowed to call i9e_close() and terminate as well.
1161 static int session_post_select(__a_unused struct sched *s)
1168 attach_stdout(__FUNCTION__);
1169 ret = i9e_get_error();
1173 para_log = stderr_log;
1174 free(ici.history_file);
1177 if (get_playback_state() == 'X')
1178 i9e_signal_dispatch(SIGTERM);
1182 #else /* HAVE_READLINE */
1184 static int session_post_select(struct sched *s)
1188 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1190 if (read(STDIN_FILENO, &c, 1))
1196 static void session_open(void)
1200 static void session_update_time_string(char *str, __a_unused unsigned len)
1202 printf("\r%s ", str);
1205 #endif /* HAVE_READLINE */
1207 static void play_pre_select(struct sched *s, __a_unused void *context)
1211 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1212 state = get_playback_state();
1213 if (state == 'R' || state == 'F' || state == 'X')
1214 return sched_min_delay(s);
1215 sched_request_barrier_or_min_delay(&pt->next_update, s);
1218 static unsigned get_time_string(char **result)
1220 int seconds, length;
1221 char state = get_playback_state();
1223 /* do not return anything if things are about to change */
1224 if (state != 'P' && state != 'U') {
1228 length = pt->seconds;
1230 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1231 seconds = get_play_time();
1232 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1236 (length - seconds) / 60,
1237 (length - seconds) % 60,
1238 length? (seconds * 100 + length / 2) / length : 0,
1241 get_playlist_file(pt->current_file)
1245 static int play_post_select(struct sched *s, __a_unused void *context)
1249 ret = eof_cleanup();
1251 pt->rq = CRT_TERM_RQ;
1254 ret = session_post_select(s);
1257 if (!pt->wn.btrn && !pt->fn.btrn) {
1258 char state = get_playback_state();
1259 if (state == 'P' || state == 'R' || state == 'F') {
1260 PARA_NOTICE_LOG("state: %c\n", state);
1261 ret = load_next_file();
1263 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1264 pt->rq = CRT_TERM_RQ;
1268 pt->next_update = *now;
1271 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1273 unsigned len = get_time_string(&str);
1274 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1276 session_update_time_string(str, len);
1278 tv_add(now, &delay, &pt->next_update);
1286 * The main function of para_play.
1288 * \param argc Standard.
1289 * \param argv Standard.
1291 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1293 int main(int argc, char *argv[])
1296 unsigned num_inputs;
1298 /* needed this early to make help work */
1301 sched.default_timeout.tv_sec = 5;
1302 parse_config_or_die(argc, argv);
1305 num_inputs = lls_num_inputs(play_lpr);
1307 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1308 pt->rq = CRT_FILE_CHANGE;
1309 pt->current_file = num_inputs - 1;
1311 pt->task = task_register(&(struct task_info){
1313 .pre_select = play_pre_select,
1314 .post_select = play_post_select,
1317 ret = schedule(&sched);
1318 sched_shutdown(&sched);
1320 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1321 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;