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"
21 #include "buffer_tree.h"
29 #include "write_common.h"
33 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
34 * para_play creates two further tasks: The play task and the i9e task. It is
35 * important whether a function can be called in the context of para_play or
36 * i9e or both. As a rule, all command handlers are called only in i9e context via
37 * the line handler (input mode) or the key handler (command mode) below.
39 * Playlist handling is done exclusively in play context.
42 /** Array of error strings. */
45 static struct lls_parse_result *play_lpr;
47 #define CMD_PTR (lls_cmd(0, play_suite))
48 #define OPT_RESULT(_name) \
49 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
50 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
51 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
52 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
55 * Describes a request to change the state of para_play.
57 * There is only one variable of this type: \a rq of the global play task
58 * structure. Command handlers only set this variable and the post_select()
59 * function of the play task investigates its value during each iteration of
60 * the scheduler run and performs the actual work.
62 enum state_change_request_type {
63 /** Everybody is happy. */
65 /** Stream must be repositioned (com_jmp(), com_ff()). */
67 /** New file should be loaded (com_next()). */
69 /** Someone wants us for dead (com_quit()). */
75 /* A bit array of invalid files (those will be skipped). */
77 /* The file which is currently open. */
78 unsigned current_file;
79 /* When to update the status again. */
80 struct timeval next_update;
82 /* Root of the buffer tree for command and status output. */
83 struct btr_node *btrn;
85 /* The decoding machinery. */
86 struct receiver_node rn;
87 struct filter_node fn;
88 struct writer_node wn;
90 /* See comment to enum state_change_request_type above */
91 enum state_change_request_type rq;
92 /* only relevant if rq == CRT_FILE_CHANGE */
95 bg: read lines at prompt, fg: display status and wait
100 /* We have the *intention* to play. Set by com_play(). */
103 /* as returned by afh_recv->open() */
104 int audio_format_num;
106 /* retrieved via the btr exec mechanism */
107 long unsigned start_chunk;
108 long unsigned seconds;
109 long unsigned num_chunks;
113 typedef int (*play_cmd_handler_t)(struct play_task *pt,
114 struct lls_parse_result *lpr);
115 struct play_command_info {
116 play_cmd_handler_t handler;
118 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
119 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
120 .handler = com_ ## _cmd \
123 static int loglevel = LL_WARNING;
125 /** The log function which writes log messages to stderr. */
126 INIT_STDERR_LOGGING(loglevel);
128 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
130 static struct sched sched = {.max_fileno = 0};
131 static struct play_task play_task;
133 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
134 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
136 static unsigned *shuffle_map;
138 static const char *get_playlist_file(unsigned idx)
140 return lls_input(shuffle_map[idx], play_lpr);
143 static void handle_help_flags(void)
147 if (OPT_GIVEN(DETAILED_HELP))
148 help = lls_long_help(CMD_PTR);
149 else if (OPT_GIVEN(HELP))
150 help = lls_short_help(CMD_PTR);
153 printf("%s\n", help);
158 static void parse_config_or_die(int argc, char *argv[])
160 const struct lls_command *cmd = CMD_PTR;
162 char *cf, *errctx, **cf_argv;
163 struct lls_parse_result *cf_lpr, *merged_lpr;
168 ret = lls(lls_parse(argc, argv, cmd, &play_lpr, &errctx));
171 loglevel = OPT_UINT32_VAL(LOGLEVEL);
172 version_handle_flag("play", OPT_GIVEN(VERSION));
174 if (OPT_GIVEN(CONFIG_FILE))
175 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
177 char *home = para_homedir();
178 cf = make_message("%s/.paraslash/play.conf", home);
181 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
183 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
185 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
190 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
191 para_munmap(map, sz);
195 ret = lls(lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx));
196 lls_free_argv(cf_argv);
199 ret = lls(lls_merge(play_lpr, cf_lpr, cmd, &merged_lpr, &errctx));
200 lls_free_parse_result(cf_lpr, cmd);
203 lls_free_parse_result(play_lpr, cmd);
204 play_lpr = merged_lpr;
205 loglevel = OPT_UINT32_VAL(LOGLEVEL);
207 ret = lls(lls_check_arg_count(play_lpr, 1, INT_MAX, &errctx));
210 num_kmas = OPT_GIVEN(KEY_MAP);
211 for (i = 0; i < num_kmas; i++) {
212 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
213 if (*kma && strchr(kma + 1, ':'))
215 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
223 lls_free_parse_result(play_lpr, cmd);
226 PARA_EMERG_LOG("%s\n", errctx);
228 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
232 static char get_playback_state(struct play_task *pt)
235 case CRT_NONE: return pt->playing? 'P' : 'U';
236 case CRT_REPOS: return 'R';
237 case CRT_FILE_CHANGE: return 'F';
238 case CRT_TERM_RQ: return 'X';
243 static long unsigned get_play_time(struct play_task *pt)
245 char state = get_playback_state(pt);
246 long unsigned result;
248 if (state != 'P' && state != 'U')
250 if (pt->num_chunks == 0 || pt->seconds == 0)
252 /* where the stream started (in seconds) */
253 result = pt->start_chunk * pt->seconds / pt->num_chunks;
254 if (pt->wn.btrn) { /* Add the uptime of the writer node */
255 struct timeval diff = {.tv_sec = 0}, wstime;
256 btr_get_node_start(pt->wn.btrn, &wstime);
257 if (wstime.tv_sec > 0)
258 tv_diff(now, &wstime, &diff);
259 result += diff.tv_sec;
261 result = PARA_MIN(result, pt->seconds);
262 result = PARA_MAX(result, 0UL);
267 static void wipe_receiver_node(struct play_task *pt)
269 PARA_NOTICE_LOG("cleaning up receiver node\n");
270 btr_remove_node(&pt->rn.btrn);
271 AFH_RECV->close(&pt->rn);
272 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
273 memset(&pt->rn, 0, sizeof(struct receiver_node));
276 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
277 static int get_playback_error(struct play_task *pt)
283 err = task_status(pt->wn.task);
286 if (task_status(pt->fn.task) >= 0)
288 if (task_status(pt->rn.task) >= 0)
290 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
291 || err == -E_WRITE_COMMON_EOF)
296 static int eof_cleanup(struct play_task *pt)
298 struct writer *w = writers + DEFAULT_WRITER;
299 const struct filter *decoder;
302 ret = get_playback_error(pt);
305 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
306 task_reap(&pt->wn.task);
308 btr_remove_node(&pt->wn.btrn);
309 w->free_config(pt->wn.conf);
310 memset(&pt->wn, 0, sizeof(struct writer_node));
312 decoder = filter_get(pt->fn.filter_num);
313 task_reap(&pt->fn.task);
315 decoder->close(&pt->fn);
316 btr_remove_node(&pt->fn.btrn);
318 memset(&pt->fn, 0, sizeof(struct filter_node));
320 task_reap(&pt->rn.task);
321 btr_remove_node(&pt->rn.btrn);
323 * On eof (ret > 0), we do not wipe the receiver node struct until a
324 * new file is loaded because we still need it for jumping around when
328 wipe_receiver_node(pt);
332 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
334 return para_random(100) - 50;
337 static void init_shuffle_map(void)
339 unsigned n, num_inputs = lls_num_inputs(play_lpr);
340 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
341 for (n = 0; n < num_inputs; n++)
343 if (!OPT_GIVEN(RANDOMIZE))
346 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
349 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
351 return btr_new_node(&(struct btr_node_description)
352 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
353 .handler = AFH_RECV->execute));
356 static int open_new_file(struct play_task *pt)
359 const char *path = get_playlist_file(pt->next_file);
360 char *tmp = para_strdup(path), *errctx;
361 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
363 PARA_NOTICE_LOG("next file: %s\n", path);
364 wipe_receiver_node(pt);
366 pt->rn.btrn = new_recv_btrn(&pt->rn);
367 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
368 &pt->rn.lpr, &errctx));
371 pt->rn.receiver = AFH_RECV;
372 ret = AFH_RECV->open(&pt->rn);
374 PARA_ERROR_LOG("could not open %s\n", path);
377 pt->audio_format_num = ret;
379 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
381 pt->afhi_txt = make_message("[afhi command failed]\n");
382 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
387 ret = para_atoi32(tmp, &x);
388 pt->seconds = ret < 0? 1 : x;
392 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
397 ret = para_atoi32(tmp, &x);
398 pt->num_chunks = ret < 0? 1 : x;
404 wipe_receiver_node(pt);
408 static int load_file(struct play_task *pt)
413 const struct filter *decoder;
414 static struct lls_parse_result *filter_lpr;
416 btr_remove_node(&pt->rn.btrn);
417 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
418 ret = open_new_file(pt);
422 pt->rn.btrn = new_recv_btrn(&pt->rn);
423 sprintf(buf, "repos %lu", pt->start_chunk);
424 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
426 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
431 /* set up decoding filter */
432 af = audio_format_name(pt->audio_format_num);
433 tmp = make_message("%sdec", af);
434 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
438 pt->fn.filter_num = ret;
439 pt->fn.lpr = filter_lpr;
440 decoder = filter_get(ret);
441 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
442 EMBRACE(.name = filter_name(pt->fn.filter_num),
443 .parent = pt->rn.btrn, .handler = decoder->execute,
444 .context = &pt->fn));
446 decoder->open(&pt->fn);
447 PARA_INFO_LOG("buffer tree:\n");
448 btr_log_tree(pt->rn.btrn, LL_INFO);
450 /* setup default writer */
451 pt->wn.conf = check_writer_arg_or_die(NULL, &pt->wn.writer_num);
453 /* success, register tasks */
454 pt->rn.task = task_register(
455 &(struct task_info) {
456 .name = lls_command_name(AFH_RECV_CMD),
457 .pre_select = AFH_RECV->pre_select,
458 .post_select = AFH_RECV->post_select,
461 sprintf(buf, "%s decoder", af);
462 pt->fn.task = task_register(
463 &(struct task_info) {
465 .pre_select = decoder->pre_select,
466 .post_select = decoder->post_select,
469 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
472 wipe_receiver_node(pt);
476 static int next_valid_file(struct play_task *pt)
478 int i, j = pt->current_file;
479 unsigned num_inputs = lls_num_inputs(play_lpr);
481 for (i = 0; i < num_inputs; i++) {
482 j = (j + 1) % num_inputs;
486 return -E_NO_VALID_FILES;
489 static int load_next_file(struct play_task *pt)
494 if (pt->rq == CRT_NONE) {
496 ret = next_valid_file(pt);
500 } else if (pt->rq == CRT_REPOS)
501 pt->next_file = pt->current_file;
504 PARA_ERROR_LOG("%s: marking file as invalid\n",
505 para_strerror(-ret));
506 pt->invalid[pt->next_file] = true;
510 pt->current_file = pt->next_file;
515 static void kill_stream(struct play_task *pt)
518 task_notify(pt->wn.task, E_EOF);
523 /* only called from com_prev(), nec. only if we have readline */
524 static int previous_valid_file(struct play_task *pt)
526 int i, j = pt->current_file;
527 unsigned num_inputs = lls_num_inputs(play_lpr);
529 for (i = 0; i < num_inputs; i++) {
536 return -E_NO_VALID_FILES;
539 #include "interactive.h"
542 * Define the default (internal) key mappings and helper functions to get the
543 * key sequence or the command from a key id, which is what we obtain from
544 * i9e/readline when the key is pressed.
546 * In some of these helper functions we could return pointers to the constant
547 * arrays defined below. However, for others we can not, so let's better be
548 * consistent and allocate all returned strings on the heap.
551 #define INTERNAL_KEYMAP_ENTRIES \
552 KEYMAP_ENTRY("^", "jmp 0"), \
553 KEYMAP_ENTRY("1", "jmp 10"), \
554 KEYMAP_ENTRY("2", "jmp 21"), \
555 KEYMAP_ENTRY("3", "jmp 32"), \
556 KEYMAP_ENTRY("4", "jmp 43"), \
557 KEYMAP_ENTRY("5", "jmp 54"), \
558 KEYMAP_ENTRY("6", "jmp 65"), \
559 KEYMAP_ENTRY("7", "jmp 76"), \
560 KEYMAP_ENTRY("8", "jmp 87"), \
561 KEYMAP_ENTRY("9", "jmp 98"), \
562 KEYMAP_ENTRY("+", "next"), \
563 KEYMAP_ENTRY("-", "prev"), \
564 KEYMAP_ENTRY(":", "bg"), \
565 KEYMAP_ENTRY("i", "info"), \
566 KEYMAP_ENTRY("l", "ls"), \
567 KEYMAP_ENTRY("s", "play"), \
568 KEYMAP_ENTRY("p", "pause"), \
569 KEYMAP_ENTRY("q", "quit"), \
570 KEYMAP_ENTRY("?", "help"), \
571 KEYMAP_ENTRY("\033[D", "ff -10"), \
572 KEYMAP_ENTRY("\033[C", "ff 10"), \
573 KEYMAP_ENTRY("\033[A", "ff 60"), \
574 KEYMAP_ENTRY("\033[B", "ff -60"), \
576 #define KEYMAP_ENTRY(a, b) a
577 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
579 #define KEYMAP_ENTRY(a, b) b
580 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
582 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
583 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
584 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
586 static inline bool is_internal_key(int key)
588 return key < NUM_INTERNALLY_MAPPED_KEYS;
591 /* for internal keys, the key id is just the array index. */
592 static inline int get_internal_key_map_idx(int key)
594 assert(is_internal_key(key));
599 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
600 * difference is the index to the array of user defined key maps.
602 static inline int get_user_key_map_idx(int key)
604 assert(!is_internal_key(key));
605 return key - NUM_INTERNALLY_MAPPED_KEYS;
608 static inline int get_key_map_idx(int key)
610 return is_internal_key(key)?
611 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
614 static inline const char *get_user_key_map_arg(int key)
616 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
619 static inline char *get_internal_key_map_seq(int key)
621 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
624 static char *get_user_key_map_seq(int key)
626 const char *kma = get_user_key_map_arg(key);
627 const char *p = strchr(kma + 1, ':');
634 result = para_malloc(len + 1);
635 memcpy(result, kma, len);
640 static char *get_key_map_seq(int key)
642 return is_internal_key(key)?
643 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
646 static char *get_key_map_seq_safe(int key)
648 const char hex[] = "0123456789abcdef";
649 char *seq = get_key_map_seq(key), *sseq;
650 size_t n, len = strlen(seq);
652 if (len == 1 && isprint(*seq))
654 sseq = para_malloc(2 + 2 * len + 1);
657 for (n = 0; n < len; n++) {
658 uint8_t val = (seq[n] & 0xf0) >> 4;
659 sseq[2 + 2 * n] = hex[val];
661 sseq[2 + 2 * n + 1] = hex[val];
664 sseq[2 + 2 * n] = '\0';
668 static inline char *get_internal_key_map_cmd(int key)
670 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
673 static char *get_user_key_map_cmd(int key)
675 const char *kma = get_user_key_map_arg(key);
676 const char *p = strchr(kma + 1, ':');
680 return para_strdup(p + 1);
683 static char *get_key_map_cmd(int key)
685 return is_internal_key(key)?
686 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
689 static char **get_mapped_keyseqs(void)
694 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
695 FOR_EACH_MAPPED_KEY(i) {
696 char *seq = get_key_map_seq(i);
703 static struct i9e_completer pp_completers[];
705 I9E_DUMMY_COMPLETER(jmp);
706 I9E_DUMMY_COMPLETER(next);
707 I9E_DUMMY_COMPLETER(prev);
708 I9E_DUMMY_COMPLETER(fg);
709 I9E_DUMMY_COMPLETER(bg);
710 I9E_DUMMY_COMPLETER(ls);
711 I9E_DUMMY_COMPLETER(info);
712 I9E_DUMMY_COMPLETER(play);
713 I9E_DUMMY_COMPLETER(pause);
714 I9E_DUMMY_COMPLETER(stop);
715 I9E_DUMMY_COMPLETER(tasks);
716 I9E_DUMMY_COMPLETER(quit);
717 I9E_DUMMY_COMPLETER(ff);
719 static void help_completer(struct i9e_completion_info *ci,
720 struct i9e_completion_result *result)
722 result->matches = i9e_complete_commands(ci->word, pp_completers);
725 I9E_DUMMY_COMPLETER(SUPERCOMMAND_UNAVAILABLE);
726 static struct i9e_completer pp_completers[] = {
727 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
728 .completer = _name ## _completer}
729 LSG_PLAY_CMD_SUBCOMMANDS
730 #undef LSG_PLAY_CMD_CMD
734 static void attach_stdout(struct play_task *pt, const char *name)
738 pt->btrn = btr_new_node(&(struct btr_node_description)
739 EMBRACE(.name = name));
740 i9e_attach_to_stdout(pt->btrn);
743 static void detach_stdout(struct play_task *pt)
745 btr_remove_node(&pt->btrn);
748 static int com_quit(struct play_task *pt,
749 __a_unused struct lls_parse_result *lpr)
751 pt->rq = CRT_TERM_RQ;
754 EXPORT_PLAY_CMD_HANDLER(quit);
756 static int com_help(struct play_task *pt, struct lls_parse_result *lpr)
761 const struct lls_command *cmd;
763 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
766 PARA_ERROR_LOG("%s\n", errctx);
770 if (lls_num_inputs(lpr) == 0) {
771 if (pt->background) {
772 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
773 sz = xasprintf(&buf, "%s\t%s\n",
774 lls_command_name(cmd), lls_purpose(cmd));
775 btr_add_output(buf, sz, pt->btrn);
779 FOR_EACH_MAPPED_KEY(i) {
780 bool internal = is_internal_key(i);
781 int idx = get_key_map_idx(i);
782 char *seq = get_key_map_seq_safe(i);
783 char *kmc = get_key_map_cmd(i);
784 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
785 internal? "internal" : "user-defined",
787 btr_add_output(buf, sz, pt->btrn);
793 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
797 PARA_ERROR_LOG("%s\n", errctx);
801 cmd = lls_cmd(ret, play_cmd_suite);
802 buf = lls_long_help(cmd);
804 btr_add_output(buf, strlen(buf), pt->btrn);
807 EXPORT_PLAY_CMD_HANDLER(help);
809 static int com_info(struct play_task *pt,
810 __a_unused struct lls_parse_result *lpr)
814 static char dflt[] = "[no information available]";
816 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
817 pt->current_file, get_playlist_file(pt->current_file));
818 btr_add_output(buf, sz, pt->btrn);
819 buf = pt->afhi_txt? pt->afhi_txt : dflt;
820 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
823 EXPORT_PLAY_CMD_HANDLER(info);
825 static void list_file(struct play_task *pt, int num)
830 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
831 "*" : " ", num, get_playlist_file(num));
832 btr_add_output(buf, sz, pt->btrn);
835 static int com_tasks(struct play_task *pt,
836 __a_unused struct lls_parse_result *lpr)
842 buf = get_task_list(&sched);
843 btr_add_output(buf, strlen(buf), pt->btrn);
844 state = get_playback_state(pt);
845 sz = xasprintf(&buf, "state: %c\n", state);
846 btr_add_output(buf, sz, pt->btrn);
849 EXPORT_PLAY_CMD_HANDLER(tasks);
851 static int com_ls(struct play_task *pt,
852 __a_unused struct lls_parse_result *lpr)
855 unsigned num_inputs = lls_num_inputs(play_lpr);
857 for (i = 0; i < num_inputs; i++)
861 EXPORT_PLAY_CMD_HANDLER(ls);
863 static int com_play(struct play_task *pt, struct lls_parse_result *lpr)
869 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
872 PARA_ERROR_LOG("%s\n", errctx);
876 state = get_playback_state(pt);
877 if (lls_num_inputs(lpr) == 0) {
880 pt->next_file = pt->current_file;
885 ret = para_atoi32(lls_input(0, lpr), &x);
888 if (x < 0 || x >= lls_num_inputs(play_lpr))
889 return -ERRNO_TO_PARA_ERROR(EINVAL);
892 pt->rq = CRT_FILE_CHANGE;
895 EXPORT_PLAY_CMD_HANDLER(play);
897 static int com_pause(struct play_task *pt,
898 __a_unused struct lls_parse_result *lpr)
901 long unsigned seconds, ss;
903 state = get_playback_state(pt);
907 seconds = get_play_time(pt);
911 ss = seconds * pt->num_chunks / pt->seconds + 1;
912 ss = PARA_MAX(ss, 0UL);
913 ss = PARA_MIN(ss, pt->num_chunks);
914 pt->start_chunk = ss;
918 EXPORT_PLAY_CMD_HANDLER(pause);
920 static int com_prev(struct play_task *pt,
921 __a_unused struct lls_parse_result *lpr)
925 ret = previous_valid_file(pt);
930 pt->rq = CRT_FILE_CHANGE;
934 EXPORT_PLAY_CMD_HANDLER(prev);
936 static int com_next(struct play_task *pt,
937 __a_unused struct lls_parse_result *lpr)
941 ret = next_valid_file(pt);
946 pt->rq = CRT_FILE_CHANGE;
950 EXPORT_PLAY_CMD_HANDLER(next);
952 static int com_fg(struct play_task *pt,
953 __a_unused struct lls_parse_result *lpr)
955 pt->background = false;
958 EXPORT_PLAY_CMD_HANDLER(fg);
960 static int com_bg(struct play_task *pt,
961 __a_unused struct lls_parse_result *lpr)
963 pt->background = true;
966 EXPORT_PLAY_CMD_HANDLER(bg);
968 static int com_jmp(struct play_task *pt, struct lls_parse_result *lpr)
974 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
977 PARA_ERROR_LOG("%s\n", errctx);
981 ret = para_atoi32(lls_input(0, lpr), &percent);
984 if (percent < 0 || percent > 100)
985 return -ERRNO_TO_PARA_ERROR(EINVAL);
987 return com_next(pt, NULL);
988 if (pt->playing && !pt->fn.btrn)
990 pt->start_chunk = percent * pt->num_chunks / 100;
997 EXPORT_PLAY_CMD_HANDLER(jmp);
999 static int com_ff(struct play_task *pt, struct lls_parse_result *lpr)
1005 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
1008 PARA_ERROR_LOG("%s\n", errctx);
1012 ret = para_atoi32(lls_input(0, lpr), &seconds);
1015 if (pt->playing && !pt->fn.btrn)
1017 seconds += get_play_time(pt);
1018 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
1019 seconds = PARA_MAX(seconds, 0);
1020 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
1021 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
1022 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1029 EXPORT_PLAY_CMD_HANDLER(ff);
1031 static int run_command(char *line, struct play_task *pt)
1035 char *errctx = NULL;
1036 const struct play_command_info *pci;
1037 struct lls_parse_result *lpr;
1038 const struct lls_command *cmd;
1040 attach_stdout(pt, __FUNCTION__);
1041 ret = create_argv(line, " ", &argv);
1047 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1050 cmd = lls_cmd(ret, play_cmd_suite);
1051 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1054 pci = lls_user_data(cmd);
1055 ret = pci->handler(pt, lpr);
1056 lls_free_parse_result(lpr, cmd);
1059 PARA_ERROR_LOG("%s\n", errctx);
1065 static int play_i9e_line_handler(char *line)
1067 return run_command(line, &play_task);
1070 static int play_i9e_key_handler(int key)
1072 struct play_task *pt = &play_task;
1073 int idx = get_key_map_idx(key);
1074 char *seq = get_key_map_seq(key);
1075 char *cmd = get_key_map_cmd(key);
1076 bool internal = is_internal_key(key);
1078 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1079 key, internal? "internal" : "user-defined",
1081 run_command(cmd, pt);
1084 pt->next_update = *now;
1088 static struct i9e_client_info ici = {
1090 .prompt = "para_play> ",
1091 .line_handler = play_i9e_line_handler,
1092 .key_handler = play_i9e_key_handler,
1093 .completers = pp_completers,
1096 static void sigint_handler(int sig)
1098 play_task.background = true;
1099 i9e_signal_dispatch(sig);
1103 * We start with para_log() set to the standard log function which writes to
1104 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1107 static void session_open(struct play_task *pt)
1111 struct sigaction act;
1113 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1114 if (OPT_GIVEN(HISTORY_FILE))
1115 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1117 char *home = para_homedir();
1118 history_file = make_message("%s/.paraslash/play.history",
1122 ici.history_file = history_file;
1123 ici.loglevel = loglevel;
1125 act.sa_handler = sigint_handler;
1126 sigemptyset(&act.sa_mask);
1128 sigaction(SIGINT, &act, NULL);
1129 act.sa_handler = i9e_signal_dispatch;
1130 sigemptyset(&act.sa_mask);
1132 sigaction(SIGWINCH, &act, NULL);
1133 sched.select_function = i9e_select;
1135 ici.bound_keyseqs = get_mapped_keyseqs();
1136 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1137 EMBRACE(.name = __FUNCTION__));
1138 ret = i9e_open(&ici, &sched);
1147 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1151 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1156 if (btr_get_output_queue_size(pt->btrn) > 0)
1158 if (btr_get_input_queue_size(pt->btrn) > 0)
1161 ie9_print_status_bar(str, len);
1165 * If we are about to die we must call i9e_close() to reset the terminal.
1166 * However, i9e_close() must be called in *this* context, i.e. from
1167 * play_task.post_select() rather than from i9e_post_select(), because
1168 * otherwise i9e would access freed memory upon return. So the play task must
1169 * stay alive until the i9e task terminates.
1171 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1172 * and reschedule. In the next iteration, i9e->post_select returns an error and
1173 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1174 * are allowed to call i9e_close() and terminate as well.
1176 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1183 attach_stdout(pt, __FUNCTION__);
1184 ret = i9e_get_error();
1188 para_log = stderr_log;
1189 free(ici.history_file);
1192 if (get_playback_state(pt) == 'X')
1193 i9e_signal_dispatch(SIGTERM);
1197 #else /* HAVE_READLINE */
1199 static int session_post_select(struct sched *s, struct play_task *pt)
1203 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1205 if (read(STDIN_FILENO, &c, 1))
1211 static void session_open(__a_unused struct play_task *pt)
1215 static void session_update_time_string(__a_unused struct play_task *pt,
1216 char *str, __a_unused unsigned len)
1218 printf("\r%s ", str);
1221 #endif /* HAVE_READLINE */
1223 static void play_pre_select(struct sched *s, void *context)
1225 struct play_task *pt = context;
1228 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1229 state = get_playback_state(pt);
1230 if (state == 'R' || state == 'F' || state == 'X')
1231 return sched_min_delay(s);
1232 sched_request_barrier_or_min_delay(&pt->next_update, s);
1235 static unsigned get_time_string(struct play_task *pt, char **result)
1237 int seconds, length;
1238 char state = get_playback_state(pt);
1240 /* do not return anything if things are about to change */
1241 if (state != 'P' && state != 'U') {
1245 length = pt->seconds;
1247 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1248 seconds = get_play_time(pt);
1249 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1253 (length - seconds) / 60,
1254 (length - seconds) % 60,
1255 length? (seconds * 100 + length / 2) / length : 0,
1258 get_playlist_file(pt->current_file)
1262 static int play_post_select(struct sched *s, void *context)
1264 struct play_task *pt = context;
1267 ret = eof_cleanup(pt);
1269 pt->rq = CRT_TERM_RQ;
1272 ret = session_post_select(s, pt);
1275 if (!pt->wn.btrn && !pt->fn.btrn) {
1276 char state = get_playback_state(pt);
1277 if (state == 'P' || state == 'R' || state == 'F') {
1278 PARA_NOTICE_LOG("state: %c\n", state);
1279 ret = load_next_file(pt);
1281 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1282 pt->rq = CRT_TERM_RQ;
1286 pt->next_update = *now;
1289 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1291 unsigned len = get_time_string(pt, &str);
1292 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1294 session_update_time_string(pt, str, len);
1296 tv_add(now, &delay, &pt->next_update);
1304 * The main function of para_play.
1306 * \param argc Standard.
1307 * \param argv Standard.
1309 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1311 int main(int argc, char *argv[])
1314 struct play_task *pt = &play_task;
1315 unsigned num_inputs;
1317 /* needed this early to make help work */
1321 sched.default_timeout.tv_sec = 5;
1322 parse_config_or_die(argc, argv);
1325 num_inputs = lls_num_inputs(play_lpr);
1327 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1328 pt->rq = CRT_FILE_CHANGE;
1329 pt->current_file = num_inputs - 1;
1331 pt->task = task_register(&(struct task_info){
1333 .pre_select = play_pre_select,
1334 .post_select = play_post_select,
1337 ret = schedule(&sched);
1338 sched_shutdown(&sched);
1340 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1341 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;