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 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 I9E_DUMMY_COMPLETER(SUPERCOMMAND_UNAVAILABLE);
722 static struct i9e_completer pp_completers[] = {
723 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
724 .completer = _name ## _completer}
725 LSG_PLAY_CMD_SUBCOMMANDS
726 #undef LSG_PLAY_CMD_CMD
730 static void attach_stdout(const char *name)
734 pt->btrn = btr_new_node(&(struct btr_node_description)
735 EMBRACE(.name = name));
736 i9e_attach_to_stdout(pt->btrn);
739 static void detach_stdout(void)
741 btr_remove_node(&pt->btrn);
744 static int com_quit(__a_unused struct lls_parse_result *lpr)
746 pt->rq = CRT_TERM_RQ;
749 EXPORT_PLAY_CMD_HANDLER(quit);
751 static int com_help(struct lls_parse_result *lpr)
756 const struct lls_command *cmd;
758 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
761 PARA_ERROR_LOG("%s\n", errctx);
765 if (lls_num_inputs(lpr) == 0) {
766 if (pt->background) {
767 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
768 sz = xasprintf(&buf, "%s\t%s\n",
769 lls_command_name(cmd), lls_purpose(cmd));
770 btr_add_output(buf, sz, pt->btrn);
774 FOR_EACH_MAPPED_KEY(i) {
775 bool internal = is_internal_key(i);
776 int idx = get_key_map_idx(i);
777 char *seq = get_key_map_seq_safe(i);
778 char *kmc = get_key_map_cmd(i);
779 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
780 internal? "internal" : "user-defined",
782 btr_add_output(buf, sz, pt->btrn);
788 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
792 PARA_ERROR_LOG("%s\n", errctx);
796 cmd = lls_cmd(ret, play_cmd_suite);
797 buf = lls_long_help(cmd);
799 btr_add_output(buf, strlen(buf), pt->btrn);
802 EXPORT_PLAY_CMD_HANDLER(help);
804 static int com_info(__a_unused struct lls_parse_result *lpr)
808 static char dflt[] = "[no information available]";
810 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
811 pt->current_file, get_playlist_file(pt->current_file));
812 btr_add_output(buf, sz, pt->btrn);
813 buf = pt->afhi_txt? pt->afhi_txt : dflt;
814 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
817 EXPORT_PLAY_CMD_HANDLER(info);
819 static void list_file(int num)
824 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
825 "*" : " ", num, get_playlist_file(num));
826 btr_add_output(buf, sz, pt->btrn);
829 static int com_tasks(__a_unused struct lls_parse_result *lpr)
835 buf = get_task_list(&sched);
836 btr_add_output(buf, strlen(buf), pt->btrn);
837 state = get_playback_state();
838 sz = xasprintf(&buf, "state: %c\n", state);
839 btr_add_output(buf, sz, pt->btrn);
842 EXPORT_PLAY_CMD_HANDLER(tasks);
844 static int com_ls(__a_unused struct lls_parse_result *lpr)
847 unsigned num_inputs = lls_num_inputs(play_lpr);
849 for (i = 0; i < num_inputs; i++)
853 EXPORT_PLAY_CMD_HANDLER(ls);
855 static int com_play(struct lls_parse_result *lpr)
861 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
864 PARA_ERROR_LOG("%s\n", errctx);
868 state = get_playback_state();
869 if (lls_num_inputs(lpr) == 0) {
872 pt->next_file = pt->current_file;
877 ret = para_atoi32(lls_input(0, lpr), &x);
880 if (x < 0 || x >= lls_num_inputs(play_lpr))
881 return -ERRNO_TO_PARA_ERROR(EINVAL);
884 pt->rq = CRT_FILE_CHANGE;
887 EXPORT_PLAY_CMD_HANDLER(play);
889 static int com_pause(__a_unused struct lls_parse_result *lpr)
892 long unsigned seconds, ss;
894 state = get_playback_state();
898 seconds = get_play_time();
902 ss = seconds * pt->num_chunks / pt->seconds + 1;
903 ss = PARA_MAX(ss, 0UL);
904 ss = PARA_MIN(ss, pt->num_chunks);
905 pt->start_chunk = ss;
909 EXPORT_PLAY_CMD_HANDLER(pause);
911 static int com_prev(__a_unused struct lls_parse_result *lpr)
915 ret = previous_valid_file();
920 pt->rq = CRT_FILE_CHANGE;
924 EXPORT_PLAY_CMD_HANDLER(prev);
926 static int com_next(__a_unused struct lls_parse_result *lpr)
930 ret = next_valid_file();
935 pt->rq = CRT_FILE_CHANGE;
939 EXPORT_PLAY_CMD_HANDLER(next);
941 static int com_fg(__a_unused struct lls_parse_result *lpr)
943 pt->background = false;
946 EXPORT_PLAY_CMD_HANDLER(fg);
948 static int com_bg(__a_unused struct lls_parse_result *lpr)
950 pt->background = true;
953 EXPORT_PLAY_CMD_HANDLER(bg);
955 static int com_jmp(struct lls_parse_result *lpr)
961 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
964 PARA_ERROR_LOG("%s\n", errctx);
968 ret = para_atoi32(lls_input(0, lpr), &percent);
971 if (percent < 0 || percent > 100)
972 return -ERRNO_TO_PARA_ERROR(EINVAL);
974 return com_next(NULL);
975 if (pt->playing && !pt->fn.btrn)
977 pt->start_chunk = percent * pt->num_chunks / 100;
984 EXPORT_PLAY_CMD_HANDLER(jmp);
986 static int com_ff(struct lls_parse_result *lpr)
992 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
995 PARA_ERROR_LOG("%s\n", errctx);
999 ret = para_atoi32(lls_input(0, lpr), &seconds);
1002 if (pt->playing && !pt->fn.btrn)
1004 seconds += get_play_time();
1005 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
1006 seconds = PARA_MAX(seconds, 0);
1007 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
1008 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
1009 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1016 EXPORT_PLAY_CMD_HANDLER(ff);
1018 static int run_command(char *line)
1022 char *errctx = NULL;
1023 const struct play_command_info *pci;
1024 struct lls_parse_result *lpr;
1025 const struct lls_command *cmd;
1027 attach_stdout(__FUNCTION__);
1028 ret = create_argv(line, " ", &argv);
1034 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1037 cmd = lls_cmd(ret, play_cmd_suite);
1038 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1041 pci = lls_user_data(cmd);
1042 ret = pci->handler(lpr);
1043 lls_free_parse_result(lpr, cmd);
1046 PARA_ERROR_LOG("%s\n", errctx);
1052 static int play_i9e_line_handler(char *line)
1054 return run_command(line);
1057 static int play_i9e_key_handler(int key)
1059 int idx = get_key_map_idx(key);
1060 char *seq = get_key_map_seq(key);
1061 char *cmd = get_key_map_cmd(key);
1062 bool internal = is_internal_key(key);
1064 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1065 key, internal? "internal" : "user-defined",
1070 pt->next_update = *now;
1074 static struct i9e_client_info ici = {
1076 .prompt = "para_play> ",
1077 .line_handler = play_i9e_line_handler,
1078 .key_handler = play_i9e_key_handler,
1079 .completers = pp_completers,
1082 static void sigint_handler(int sig)
1084 pt->background = true;
1085 i9e_signal_dispatch(sig);
1089 * We start with para_log() set to the standard log function which writes to
1090 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1093 static void session_open(void)
1097 struct sigaction act;
1099 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1100 if (OPT_GIVEN(HISTORY_FILE))
1101 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1103 char *home = para_homedir();
1104 history_file = make_message("%s/.paraslash/play.history",
1108 ici.history_file = history_file;
1109 ici.loglevel = loglevel;
1111 act.sa_handler = sigint_handler;
1112 sigemptyset(&act.sa_mask);
1114 sigaction(SIGINT, &act, NULL);
1115 act.sa_handler = i9e_signal_dispatch;
1116 sigemptyset(&act.sa_mask);
1118 sigaction(SIGWINCH, &act, NULL);
1119 sched.select_function = i9e_select;
1121 ici.bound_keyseqs = get_mapped_keyseqs();
1122 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1123 EMBRACE(.name = __FUNCTION__));
1124 ret = i9e_open(&ici, &sched);
1133 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1137 static void session_update_time_string(char *str, unsigned len)
1142 if (btr_get_output_queue_size(pt->btrn) > 0)
1144 if (btr_get_input_queue_size(pt->btrn) > 0)
1147 ie9_print_status_bar(str, len);
1151 * If we are about to die we must call i9e_close() to reset the terminal.
1152 * However, i9e_close() must be called in *this* context, i.e. from
1153 * play_task.post_select() rather than from i9e_post_select(), because
1154 * otherwise i9e would access freed memory upon return. So the play task must
1155 * stay alive until the i9e task terminates.
1157 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1158 * and reschedule. In the next iteration, i9e->post_select returns an error and
1159 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1160 * are allowed to call i9e_close() and terminate as well.
1162 static int session_post_select(__a_unused struct sched *s)
1169 attach_stdout(__FUNCTION__);
1170 ret = i9e_get_error();
1174 para_log = stderr_log;
1175 free(ici.history_file);
1178 if (get_playback_state() == 'X')
1179 i9e_signal_dispatch(SIGTERM);
1183 #else /* HAVE_READLINE */
1185 static int session_post_select(struct sched *s)
1189 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1191 if (read(STDIN_FILENO, &c, 1))
1197 static void session_open(void)
1201 static void session_update_time_string(char *str, __a_unused unsigned len)
1203 printf("\r%s ", str);
1206 #endif /* HAVE_READLINE */
1208 static void play_pre_select(struct sched *s, __a_unused void *context)
1212 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1213 state = get_playback_state();
1214 if (state == 'R' || state == 'F' || state == 'X')
1215 return sched_min_delay(s);
1216 sched_request_barrier_or_min_delay(&pt->next_update, s);
1219 static unsigned get_time_string(char **result)
1221 int seconds, length;
1222 char state = get_playback_state();
1224 /* do not return anything if things are about to change */
1225 if (state != 'P' && state != 'U') {
1229 length = pt->seconds;
1231 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1232 seconds = get_play_time();
1233 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1237 (length - seconds) / 60,
1238 (length - seconds) % 60,
1239 length? (seconds * 100 + length / 2) / length : 0,
1242 get_playlist_file(pt->current_file)
1246 static int play_post_select(struct sched *s, __a_unused void *context)
1250 ret = eof_cleanup();
1252 pt->rq = CRT_TERM_RQ;
1255 ret = session_post_select(s);
1258 if (!pt->wn.btrn && !pt->fn.btrn) {
1259 char state = get_playback_state();
1260 if (state == 'P' || state == 'R' || state == 'F') {
1261 PARA_NOTICE_LOG("state: %c\n", state);
1262 ret = load_next_file();
1264 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1265 pt->rq = CRT_TERM_RQ;
1269 pt->next_update = *now;
1272 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1274 unsigned len = get_time_string(&str);
1275 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1277 session_update_time_string(str, len);
1279 tv_add(now, &delay, &pt->next_update);
1287 * The main function of para_play.
1289 * \param argc Standard.
1290 * \param argv Standard.
1292 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1294 int main(int argc, char *argv[])
1297 unsigned num_inputs;
1299 /* needed this early to make help work */
1302 sched.default_timeout.tv_sec = 5;
1303 parse_config_or_die(argc, argv);
1306 num_inputs = lls_num_inputs(play_lpr);
1308 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1309 pt->rq = CRT_FILE_CHANGE;
1310 pt->current_file = num_inputs - 1;
1312 pt->task = task_register(&(struct task_info){
1314 .pre_select = play_pre_select,
1315 .post_select = play_post_select,
1318 ret = schedule(&sched);
1319 sched_shutdown(&sched);
1321 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1322 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;