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. */
14 #include "recv_cmd.lsg.h"
15 #include "play_cmd.lsg.h"
16 #include "write_cmd.lsg.h"
21 #include "buffer_tree.h"
32 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
33 * para_play creates two further tasks: The play task and the i9e task. It is
34 * important whether a function can be called in the context of para_play or
35 * i9e or both. As a rule, all command handlers are called only in i9e context via
36 * the line handler (input mode) or the key handler (command mode) below.
38 * Playlist handling is done exclusively in play context.
41 /** Array of error strings. */
44 static struct lls_parse_result *play_lpr;
46 #define CMD_PTR (lls_cmd(0, play_suite))
47 #define OPT_RESULT(_name) \
48 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
49 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
50 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
51 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
54 * Describes a request to change the state of para_play.
56 * There is only one variable of this type: \a rq of the global play task
57 * structure. Command handlers only set this variable and the post_select()
58 * function of the play task investigates its value during each iteration of
59 * the scheduler run and performs the actual work.
61 enum state_change_request_type {
62 /** Everybody is happy. */
64 /** Stream must be repositioned (com_jmp(), com_ff()). */
66 /** New file should be loaded (com_next()). */
68 /** Someone wants us for dead (com_quit()). */
74 /* A bit array of invalid files (those will be skipped). */
76 /* The file which is currently open. */
77 unsigned current_file;
78 /* When to update the status again. */
79 struct timeval next_update;
81 /* Root of the buffer tree for command and status output. */
82 struct btr_node *btrn;
84 /* The decoding machinery. */
85 struct receiver_node rn;
86 struct filter_node fn;
87 struct writer_node wn;
89 /* See comment to enum state_change_request_type above */
90 enum state_change_request_type rq;
91 /* only relevant if rq == CRT_FILE_CHANGE */
94 bg: read lines at prompt, fg: display status and wait
99 /* We have the *intention* to play. Set by com_play(). */
102 /* as returned by afh_recv->open() */
103 int audio_format_num;
105 /* retrieved via the btr exec mechanism */
106 long unsigned start_chunk;
107 long unsigned seconds;
108 long unsigned num_chunks;
112 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
113 struct play_command_info {
114 play_cmd_handler_t handler;
116 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
117 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
118 .handler = com_ ## _cmd \
121 static int loglevel = LL_WARNING;
123 /** The log function which writes log messages to stderr. */
124 INIT_STDERR_LOGGING(loglevel);
126 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
128 static struct sched sched = {.max_fileno = 0};
129 static struct play_task play_task, *pt = &play_task;
131 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
132 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
134 static unsigned *shuffle_map;
136 static const char *get_playlist_file(unsigned idx)
138 return lls_input(shuffle_map[idx], play_lpr);
141 static void handle_help_flags(void)
145 if (OPT_GIVEN(DETAILED_HELP))
146 help = lls_long_help(CMD_PTR);
147 else if (OPT_GIVEN(HELP))
148 help = lls_short_help(CMD_PTR);
151 printf("%s\n", help);
156 static void parse_config_or_die(int argc, char *argv[])
158 const struct lls_command *cmd = CMD_PTR;
160 char *cf, *errctx, **cf_argv;
161 struct lls_parse_result *cf_lpr, *merged_lpr;
166 ret = lls(lls_parse(argc, argv, cmd, &play_lpr, &errctx));
169 loglevel = OPT_UINT32_VAL(LOGLEVEL);
170 version_handle_flag("play", OPT_GIVEN(VERSION));
172 if (OPT_GIVEN(CONFIG_FILE))
173 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
175 char *home = para_homedir();
176 cf = make_message("%s/.paraslash/play.conf", home);
179 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
181 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
183 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
188 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
189 para_munmap(map, sz);
193 ret = lls(lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx));
194 lls_free_argv(cf_argv);
197 ret = lls(lls_merge(play_lpr, cf_lpr, cmd, &merged_lpr, &errctx));
198 lls_free_parse_result(cf_lpr, cmd);
201 lls_free_parse_result(play_lpr, cmd);
202 play_lpr = merged_lpr;
203 loglevel = OPT_UINT32_VAL(LOGLEVEL);
205 ret = lls(lls_check_arg_count(play_lpr, 1, INT_MAX, &errctx));
208 num_kmas = OPT_GIVEN(KEY_MAP);
209 for (i = 0; i < num_kmas; i++) {
210 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
211 if (*kma && strchr(kma + 1, ':'))
213 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
221 lls_free_parse_result(play_lpr, cmd);
224 PARA_EMERG_LOG("%s\n", errctx);
226 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
230 static char get_playback_state(void)
233 case CRT_NONE: return pt->playing? 'P' : 'U';
234 case CRT_REPOS: return 'R';
235 case CRT_FILE_CHANGE: return 'F';
236 case CRT_TERM_RQ: return 'X';
241 static long unsigned get_play_time(void)
243 char state = get_playback_state();
244 long unsigned result;
246 if (state != 'P' && state != 'U')
248 if (pt->num_chunks == 0 || pt->seconds == 0)
250 /* where the stream started (in seconds) */
251 result = pt->start_chunk * pt->seconds / pt->num_chunks;
252 if (pt->wn.btrn) { /* Add the uptime of the writer node */
253 struct timeval diff = {.tv_sec = 0}, wstime;
254 btr_get_node_start(pt->wn.btrn, &wstime);
255 if (wstime.tv_sec > 0)
256 tv_diff(now, &wstime, &diff);
257 result += diff.tv_sec;
259 result = PARA_MIN(result, pt->seconds);
260 result = PARA_MAX(result, 0UL);
265 static void wipe_receiver_node(void)
267 PARA_NOTICE_LOG("cleaning up receiver node\n");
268 btr_remove_node(&pt->rn.btrn);
269 AFH_RECV->close(&pt->rn);
270 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
271 memset(&pt->rn, 0, sizeof(struct receiver_node));
274 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
275 static int get_playback_error(void)
281 err = task_status(pt->wn.task);
284 if (task_status(pt->fn.task) >= 0)
286 if (task_status(pt->rn.task) >= 0)
288 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
289 || err == -E_WRITE_COMMON_EOF)
294 static int eof_cleanup(void)
296 const struct filter *decoder;
297 const struct writer *w = writer_get(-1); /* default writer */
300 ret = get_playback_error();
303 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
304 task_reap(&pt->wn.task);
306 btr_remove_node(&pt->wn.btrn);
307 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
308 memset(&pt->wn, 0, sizeof(struct writer_node));
310 decoder = filter_get(pt->fn.filter_num);
311 task_reap(&pt->fn.task);
313 decoder->close(&pt->fn);
314 btr_remove_node(&pt->fn.btrn);
316 memset(&pt->fn, 0, sizeof(struct filter_node));
318 task_reap(&pt->rn.task);
319 btr_remove_node(&pt->rn.btrn);
321 * On eof (ret > 0), we do not wipe the receiver node struct until a
322 * new file is loaded because we still need it for jumping around when
326 wipe_receiver_node();
330 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
332 return para_random(100) - 50;
335 static void init_shuffle_map(void)
337 unsigned n, num_inputs = lls_num_inputs(play_lpr);
338 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
339 for (n = 0; n < num_inputs; n++)
341 if (!OPT_GIVEN(RANDOMIZE))
344 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
347 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
349 return btr_new_node(&(struct btr_node_description)
350 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
351 .handler = AFH_RECV->execute));
354 static int open_new_file(void)
357 const char *path = get_playlist_file(pt->next_file);
358 char *tmp = para_strdup(path), *errctx;
359 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
361 PARA_NOTICE_LOG("next file: %s\n", path);
362 wipe_receiver_node();
364 pt->rn.btrn = new_recv_btrn(&pt->rn);
365 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
366 &pt->rn.lpr, &errctx));
369 pt->rn.receiver = AFH_RECV;
370 ret = AFH_RECV->open(&pt->rn);
372 PARA_ERROR_LOG("could not open %s\n", path);
375 pt->audio_format_num = ret;
377 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
379 pt->afhi_txt = make_message("[afhi command failed]\n");
380 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
385 ret = para_atoi32(tmp, &x);
386 pt->seconds = ret < 0? 1 : x;
390 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
395 ret = para_atoi32(tmp, &x);
396 pt->num_chunks = ret < 0? 1 : x;
402 wipe_receiver_node();
406 static int load_file(void)
411 const struct filter *decoder;
412 static struct lls_parse_result *filter_lpr, *writer_lpr;
414 btr_remove_node(&pt->rn.btrn);
415 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
416 ret = open_new_file();
420 pt->rn.btrn = new_recv_btrn(&pt->rn);
421 sprintf(buf, "repos %lu", pt->start_chunk);
422 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
424 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
429 /* set up decoding filter */
430 af = audio_format_name(pt->audio_format_num);
431 tmp = make_message("%sdec", af);
432 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
436 pt->fn.filter_num = ret;
437 pt->fn.lpr = filter_lpr;
438 decoder = filter_get(ret);
439 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
440 EMBRACE(.name = filter_name(pt->fn.filter_num),
441 .parent = pt->rn.btrn, .handler = decoder->execute,
442 .context = &pt->fn));
444 decoder->open(&pt->fn);
445 PARA_INFO_LOG("buffer tree:\n");
446 btr_log_tree(pt->rn.btrn, LL_INFO);
448 /* setup default writer */
449 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
450 pt->wn.lpr = writer_lpr;
451 /* success, register tasks */
452 pt->rn.task = task_register(
453 &(struct task_info) {
454 .name = lls_command_name(AFH_RECV_CMD),
455 .pre_select = AFH_RECV->pre_select,
456 .post_select = AFH_RECV->post_select,
459 sprintf(buf, "%s decoder", af);
460 pt->fn.task = task_register(
461 &(struct task_info) {
463 .pre_select = decoder->pre_select,
464 .post_select = decoder->post_select,
467 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
470 wipe_receiver_node();
474 static int next_valid_file(void)
476 int i, j = pt->current_file;
477 unsigned num_inputs = lls_num_inputs(play_lpr);
479 for (i = 0; i < num_inputs; i++) {
480 j = (j + 1) % num_inputs;
484 return -E_NO_VALID_FILES;
487 static int load_next_file(void)
492 if (pt->rq == CRT_NONE) {
494 ret = next_valid_file();
498 } else if (pt->rq == CRT_REPOS)
499 pt->next_file = pt->current_file;
502 PARA_ERROR_LOG("%s: marking file as invalid\n",
503 para_strerror(-ret));
504 pt->invalid[pt->next_file] = true;
508 pt->current_file = pt->next_file;
513 static void kill_stream(void)
516 task_notify(pt->wn.task, E_EOF);
521 /* only called from com_prev(), nec. only if we have readline */
522 static int previous_valid_file(void)
524 int i, j = pt->current_file;
525 unsigned num_inputs = lls_num_inputs(play_lpr);
527 for (i = 0; i < num_inputs; i++) {
534 return -E_NO_VALID_FILES;
537 #include "interactive.h"
540 * Define the default (internal) key mappings and helper functions to get the
541 * key sequence or the command from a key id, which is what we obtain from
542 * i9e/readline when the key is pressed.
544 * In some of these helper functions we could return pointers to the constant
545 * arrays defined below. However, for others we can not, so let's better be
546 * consistent and allocate all returned strings on the heap.
549 #define INTERNAL_KEYMAP_ENTRIES \
550 KEYMAP_ENTRY("^", "jmp 0"), \
551 KEYMAP_ENTRY("1", "jmp 10"), \
552 KEYMAP_ENTRY("2", "jmp 21"), \
553 KEYMAP_ENTRY("3", "jmp 32"), \
554 KEYMAP_ENTRY("4", "jmp 43"), \
555 KEYMAP_ENTRY("5", "jmp 54"), \
556 KEYMAP_ENTRY("6", "jmp 65"), \
557 KEYMAP_ENTRY("7", "jmp 76"), \
558 KEYMAP_ENTRY("8", "jmp 87"), \
559 KEYMAP_ENTRY("9", "jmp 98"), \
560 KEYMAP_ENTRY("+", "next"), \
561 KEYMAP_ENTRY("-", "prev"), \
562 KEYMAP_ENTRY(":", "bg"), \
563 KEYMAP_ENTRY("i", "info"), \
564 KEYMAP_ENTRY("l", "ls"), \
565 KEYMAP_ENTRY("s", "play"), \
566 KEYMAP_ENTRY("p", "pause"), \
567 KEYMAP_ENTRY("q", "quit"), \
568 KEYMAP_ENTRY("?", "help"), \
569 KEYMAP_ENTRY("\033[D", "ff -10"), \
570 KEYMAP_ENTRY("\033[C", "ff 10"), \
571 KEYMAP_ENTRY("\033[A", "ff 60"), \
572 KEYMAP_ENTRY("\033[B", "ff -60"), \
574 #define KEYMAP_ENTRY(a, b) a
575 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
577 #define KEYMAP_ENTRY(a, b) b
578 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
580 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
581 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
582 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
584 static inline bool is_internal_key(int key)
586 return key < NUM_INTERNALLY_MAPPED_KEYS;
589 /* for internal keys, the key id is just the array index. */
590 static inline int get_internal_key_map_idx(int key)
592 assert(is_internal_key(key));
597 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
598 * difference is the index to the array of user defined key maps.
600 static inline int get_user_key_map_idx(int key)
602 assert(!is_internal_key(key));
603 return key - NUM_INTERNALLY_MAPPED_KEYS;
606 static inline int get_key_map_idx(int key)
608 return is_internal_key(key)?
609 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
612 static inline const char *get_user_key_map_arg(int key)
614 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
617 static inline char *get_internal_key_map_seq(int key)
619 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
622 static char *get_user_key_map_seq(int key)
624 const char *kma = get_user_key_map_arg(key);
625 const char *p = strchr(kma + 1, ':');
632 result = para_malloc(len + 1);
633 memcpy(result, kma, len);
638 static char *get_key_map_seq(int key)
640 return is_internal_key(key)?
641 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
644 static char *get_key_map_seq_safe(int key)
646 const char hex[] = "0123456789abcdef";
647 char *seq = get_key_map_seq(key), *sseq;
648 size_t n, len = strlen(seq);
650 if (len == 1 && isprint(*seq))
652 sseq = para_malloc(2 + 2 * len + 1);
655 for (n = 0; n < len; n++) {
656 uint8_t val = (seq[n] & 0xf0) >> 4;
657 sseq[2 + 2 * n] = hex[val];
659 sseq[2 + 2 * n + 1] = hex[val];
662 sseq[2 + 2 * n] = '\0';
666 static inline char *get_internal_key_map_cmd(int key)
668 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
671 static char *get_user_key_map_cmd(int key)
673 const char *kma = get_user_key_map_arg(key);
674 const char *p = strchr(kma + 1, ':');
678 return para_strdup(p + 1);
681 static char *get_key_map_cmd(int key)
683 return is_internal_key(key)?
684 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
687 static char **get_mapped_keyseqs(void)
692 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
693 FOR_EACH_MAPPED_KEY(i) {
694 char *seq = get_key_map_seq(i);
701 static struct i9e_completer pp_completers[];
703 I9E_DUMMY_COMPLETER(jmp);
704 I9E_DUMMY_COMPLETER(next);
705 I9E_DUMMY_COMPLETER(prev);
706 I9E_DUMMY_COMPLETER(fg);
707 I9E_DUMMY_COMPLETER(bg);
708 I9E_DUMMY_COMPLETER(ls);
709 I9E_DUMMY_COMPLETER(info);
710 I9E_DUMMY_COMPLETER(play);
711 I9E_DUMMY_COMPLETER(pause);
712 I9E_DUMMY_COMPLETER(stop);
713 I9E_DUMMY_COMPLETER(tasks);
714 I9E_DUMMY_COMPLETER(quit);
715 I9E_DUMMY_COMPLETER(ff);
717 static void help_completer(struct i9e_completion_info *ci,
718 struct i9e_completion_result *result)
720 result->matches = i9e_complete_commands(ci->word, pp_completers);
723 I9E_DUMMY_COMPLETER(SUPERCOMMAND_UNAVAILABLE);
724 static struct i9e_completer pp_completers[] = {
725 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
726 .completer = _name ## _completer}
727 LSG_PLAY_CMD_SUBCOMMANDS
728 #undef LSG_PLAY_CMD_CMD
732 static void attach_stdout(const char *name)
736 pt->btrn = btr_new_node(&(struct btr_node_description)
737 EMBRACE(.name = name));
738 i9e_attach_to_stdout(pt->btrn);
741 static void detach_stdout(void)
743 btr_remove_node(&pt->btrn);
746 static int com_quit(__a_unused struct lls_parse_result *lpr)
748 pt->rq = CRT_TERM_RQ;
751 EXPORT_PLAY_CMD_HANDLER(quit);
753 static int com_help(struct lls_parse_result *lpr)
758 const struct lls_command *cmd;
760 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
763 PARA_ERROR_LOG("%s\n", errctx);
767 if (lls_num_inputs(lpr) == 0) {
768 if (pt->background) {
769 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
770 sz = xasprintf(&buf, "%s\t%s\n",
771 lls_command_name(cmd), lls_purpose(cmd));
772 btr_add_output(buf, sz, pt->btrn);
776 FOR_EACH_MAPPED_KEY(i) {
777 bool internal = is_internal_key(i);
778 int idx = get_key_map_idx(i);
779 char *seq = get_key_map_seq_safe(i);
780 char *kmc = get_key_map_cmd(i);
781 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
782 internal? "internal" : "user-defined",
784 btr_add_output(buf, sz, pt->btrn);
790 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
794 PARA_ERROR_LOG("%s\n", errctx);
798 cmd = lls_cmd(ret, play_cmd_suite);
799 buf = lls_long_help(cmd);
801 btr_add_output(buf, strlen(buf), pt->btrn);
804 EXPORT_PLAY_CMD_HANDLER(help);
806 static int com_info(__a_unused struct lls_parse_result *lpr)
810 static char dflt[] = "[no information available]";
812 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
813 pt->current_file, get_playlist_file(pt->current_file));
814 btr_add_output(buf, sz, pt->btrn);
815 buf = pt->afhi_txt? pt->afhi_txt : dflt;
816 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
819 EXPORT_PLAY_CMD_HANDLER(info);
821 static void list_file(int num)
826 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
827 "*" : " ", num, get_playlist_file(num));
828 btr_add_output(buf, sz, pt->btrn);
831 static int com_tasks(__a_unused struct lls_parse_result *lpr)
837 buf = get_task_list(&sched);
838 btr_add_output(buf, strlen(buf), pt->btrn);
839 state = get_playback_state();
840 sz = xasprintf(&buf, "state: %c\n", state);
841 btr_add_output(buf, sz, pt->btrn);
844 EXPORT_PLAY_CMD_HANDLER(tasks);
846 static int com_ls(__a_unused struct lls_parse_result *lpr)
849 unsigned num_inputs = lls_num_inputs(play_lpr);
851 for (i = 0; i < num_inputs; i++)
855 EXPORT_PLAY_CMD_HANDLER(ls);
857 static int com_play(struct lls_parse_result *lpr)
863 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
866 PARA_ERROR_LOG("%s\n", errctx);
870 state = get_playback_state();
871 if (lls_num_inputs(lpr) == 0) {
874 pt->next_file = pt->current_file;
879 ret = para_atoi32(lls_input(0, lpr), &x);
882 if (x < 0 || x >= lls_num_inputs(play_lpr))
883 return -ERRNO_TO_PARA_ERROR(EINVAL);
886 pt->rq = CRT_FILE_CHANGE;
889 EXPORT_PLAY_CMD_HANDLER(play);
891 static int com_pause(__a_unused struct lls_parse_result *lpr)
894 long unsigned seconds, ss;
896 state = get_playback_state();
900 seconds = get_play_time();
904 ss = seconds * pt->num_chunks / pt->seconds + 1;
905 ss = PARA_MAX(ss, 0UL);
906 ss = PARA_MIN(ss, pt->num_chunks);
907 pt->start_chunk = ss;
911 EXPORT_PLAY_CMD_HANDLER(pause);
913 static int com_prev(__a_unused struct lls_parse_result *lpr)
917 ret = previous_valid_file();
922 pt->rq = CRT_FILE_CHANGE;
926 EXPORT_PLAY_CMD_HANDLER(prev);
928 static int com_next(__a_unused struct lls_parse_result *lpr)
932 ret = next_valid_file();
937 pt->rq = CRT_FILE_CHANGE;
941 EXPORT_PLAY_CMD_HANDLER(next);
943 static int com_fg(__a_unused struct lls_parse_result *lpr)
945 pt->background = false;
948 EXPORT_PLAY_CMD_HANDLER(fg);
950 static int com_bg(__a_unused struct lls_parse_result *lpr)
952 pt->background = true;
955 EXPORT_PLAY_CMD_HANDLER(bg);
957 static int com_jmp(struct lls_parse_result *lpr)
963 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
966 PARA_ERROR_LOG("%s\n", errctx);
970 ret = para_atoi32(lls_input(0, lpr), &percent);
973 if (percent < 0 || percent > 100)
974 return -ERRNO_TO_PARA_ERROR(EINVAL);
976 return com_next(NULL);
977 if (pt->playing && !pt->fn.btrn)
979 pt->start_chunk = percent * pt->num_chunks / 100;
986 EXPORT_PLAY_CMD_HANDLER(jmp);
988 static int com_ff(struct lls_parse_result *lpr)
994 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
997 PARA_ERROR_LOG("%s\n", errctx);
1001 ret = para_atoi32(lls_input(0, lpr), &seconds);
1004 if (pt->playing && !pt->fn.btrn)
1006 seconds += get_play_time();
1007 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
1008 seconds = PARA_MAX(seconds, 0);
1009 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
1010 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
1011 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1018 EXPORT_PLAY_CMD_HANDLER(ff);
1020 static int run_command(char *line)
1024 char *errctx = NULL;
1025 const struct play_command_info *pci;
1026 struct lls_parse_result *lpr;
1027 const struct lls_command *cmd;
1029 attach_stdout(__FUNCTION__);
1030 ret = create_argv(line, " ", &argv);
1036 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1039 cmd = lls_cmd(ret, play_cmd_suite);
1040 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1043 pci = lls_user_data(cmd);
1044 ret = pci->handler(lpr);
1045 lls_free_parse_result(lpr, cmd);
1048 PARA_ERROR_LOG("%s\n", errctx);
1054 static int play_i9e_line_handler(char *line)
1056 return run_command(line);
1059 static int play_i9e_key_handler(int key)
1061 int idx = get_key_map_idx(key);
1062 char *seq = get_key_map_seq(key);
1063 char *cmd = get_key_map_cmd(key);
1064 bool internal = is_internal_key(key);
1066 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1067 key, internal? "internal" : "user-defined",
1072 pt->next_update = *now;
1076 static struct i9e_client_info ici = {
1078 .prompt = "para_play> ",
1079 .line_handler = play_i9e_line_handler,
1080 .key_handler = play_i9e_key_handler,
1081 .completers = pp_completers,
1084 static void sigint_handler(int sig)
1086 pt->background = true;
1087 i9e_signal_dispatch(sig);
1091 * We start with para_log() set to the standard log function which writes to
1092 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1095 static void session_open(void)
1099 struct sigaction act;
1101 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1102 if (OPT_GIVEN(HISTORY_FILE))
1103 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1105 char *home = para_homedir();
1106 history_file = make_message("%s/.paraslash/play.history",
1110 ici.history_file = history_file;
1111 ici.loglevel = loglevel;
1113 act.sa_handler = sigint_handler;
1114 sigemptyset(&act.sa_mask);
1116 sigaction(SIGINT, &act, NULL);
1117 act.sa_handler = i9e_signal_dispatch;
1118 sigemptyset(&act.sa_mask);
1120 sigaction(SIGWINCH, &act, NULL);
1121 sched.select_function = i9e_select;
1123 ici.bound_keyseqs = get_mapped_keyseqs();
1124 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1125 EMBRACE(.name = __FUNCTION__));
1126 ret = i9e_open(&ici, &sched);
1135 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1139 static void session_update_time_string(char *str, unsigned len)
1144 if (btr_get_output_queue_size(pt->btrn) > 0)
1146 if (btr_get_input_queue_size(pt->btrn) > 0)
1149 ie9_print_status_bar(str, len);
1153 * If we are about to die we must call i9e_close() to reset the terminal.
1154 * However, i9e_close() must be called in *this* context, i.e. from
1155 * play_task.post_select() rather than from i9e_post_select(), because
1156 * otherwise i9e would access freed memory upon return. So the play task must
1157 * stay alive until the i9e task terminates.
1159 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1160 * and reschedule. In the next iteration, i9e->post_select returns an error and
1161 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1162 * are allowed to call i9e_close() and terminate as well.
1164 static int session_post_select(__a_unused struct sched *s)
1171 attach_stdout(__FUNCTION__);
1172 ret = i9e_get_error();
1176 para_log = stderr_log;
1177 free(ici.history_file);
1180 if (get_playback_state() == 'X')
1181 i9e_signal_dispatch(SIGTERM);
1185 #else /* HAVE_READLINE */
1187 static int session_post_select(struct sched *s)
1191 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1193 if (read(STDIN_FILENO, &c, 1))
1199 static void session_open(void)
1203 static void session_update_time_string(char *str, __a_unused unsigned len)
1205 printf("\r%s ", str);
1208 #endif /* HAVE_READLINE */
1210 static void play_pre_select(struct sched *s, __a_unused void *context)
1214 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1215 state = get_playback_state();
1216 if (state == 'R' || state == 'F' || state == 'X')
1217 return sched_min_delay(s);
1218 sched_request_barrier_or_min_delay(&pt->next_update, s);
1221 static unsigned get_time_string(char **result)
1223 int seconds, length;
1224 char state = get_playback_state();
1226 /* do not return anything if things are about to change */
1227 if (state != 'P' && state != 'U') {
1231 length = pt->seconds;
1233 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1234 seconds = get_play_time();
1235 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1239 (length - seconds) / 60,
1240 (length - seconds) % 60,
1241 length? (seconds * 100 + length / 2) / length : 0,
1244 get_playlist_file(pt->current_file)
1248 static int play_post_select(struct sched *s, __a_unused void *context)
1252 ret = eof_cleanup();
1254 pt->rq = CRT_TERM_RQ;
1257 ret = session_post_select(s);
1260 if (!pt->wn.btrn && !pt->fn.btrn) {
1261 char state = get_playback_state();
1262 if (state == 'P' || state == 'R' || state == 'F') {
1263 PARA_NOTICE_LOG("state: %c\n", state);
1264 ret = load_next_file();
1266 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1267 pt->rq = CRT_TERM_RQ;
1271 pt->next_update = *now;
1274 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1276 unsigned len = get_time_string(&str);
1277 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1279 session_update_time_string(str, len);
1281 tv_add(now, &delay, &pt->next_update);
1289 * The main function of para_play.
1291 * \param argc Standard.
1292 * \param argv Standard.
1294 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1296 int main(int argc, char *argv[])
1299 unsigned num_inputs;
1301 /* needed this early to make help work */
1304 sched.default_timeout.tv_sec = 5;
1305 parse_config_or_die(argc, argv);
1308 num_inputs = lls_num_inputs(play_lpr);
1310 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1311 pt->rq = CRT_FILE_CHANGE;
1312 pt->current_file = num_inputs - 1;
1314 pt->task = task_register(&(struct task_info){
1316 .pre_select = play_pre_select,
1317 .post_select = play_post_select,
1320 ret = schedule(&sched);
1321 sched_shutdown(&sched);
1323 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1324 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;