1 /* Copyright (C) 2012 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file play.c Paraslash's standalone player. */
9 #include "recv_cmd.lsg.h"
10 #include "filter_cmd.lsg.h"
11 #include "play_cmd.lsg.h"
12 #include "write_cmd.lsg.h"
18 #include "buffer_tree.h"
27 #include "interactive.h"
29 /** Array of error strings. */
32 static struct lls_parse_result *play_lpr;
34 #define CMD_PTR (lls_cmd(0, play_suite))
35 #define OPT_RESULT(_name) \
36 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
37 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
38 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
39 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
42 * Describes a request to change the state of para_play.
44 * There is only one variable of this type: \a rq of the global play task
45 * structure. Command handlers only set this variable and the post_monitor()
46 * function of the play task investigates its value during each iteration of
47 * the scheduler run and performs the actual work.
49 enum state_change_request_type {
50 /** Everybody is happy. */
52 /** Stream must be repositioned (com_jmp(), com_ff()). */
54 /** New file should be loaded (com_next()). */
56 /** Someone wants us for dead (com_quit()). */
62 /* A bit array of invalid files (those will be skipped). */
64 /* The file which is currently open. */
65 unsigned current_file;
66 /* When to update the status again. */
67 struct timeval next_update;
69 /* Root of the buffer tree for command and status output. */
70 struct btr_node *btrn;
72 /* The decoding machinery. */
73 struct receiver_node rn;
74 struct filter_node fn;
75 struct writer_node wn;
77 /* See comment to enum \ref state_change_request_type above. */
78 enum state_change_request_type rq;
79 /* only relevant if rq == CRT_FILE_CHANGE */
82 bg: read lines at prompt, fg: display status and wait
87 /* We have the *intention* to play. Set by com_play(). */
90 /* as returned by afh_recv->open() */
93 /* retrieved via the btr exec mechanism */
94 long unsigned start_chunk;
95 long unsigned seconds;
96 long unsigned num_chunks;
100 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
101 struct play_command_info {
102 play_cmd_handler_t handler;
105 static int loglevel = LL_WARNING;
107 /** The log function which writes log messages to stderr. */
108 INIT_STDERR_LOGGING(loglevel);
110 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
112 static struct sched sched;
113 static struct play_task play_task, *pt = &play_task;
115 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
116 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
118 static unsigned *shuffle_map;
120 static const char *get_playlist_file(unsigned idx)
122 return lls_input(shuffle_map[idx], play_lpr);
125 static void handle_help_flags(void)
129 if (OPT_GIVEN(DETAILED_HELP))
130 help = lls_long_help(CMD_PTR);
131 else if (OPT_GIVEN(HELP) || lls_num_inputs(play_lpr) == 0)
132 help = lls_short_help(CMD_PTR);
135 printf("%s\n", help);
140 static void parse_config_or_die(int argc, char *argv[])
146 ret = lls(lls_parse(argc, argv, CMD_PTR, &play_lpr, &errctx));
149 PARA_EMERG_LOG("%s\n", errctx);
151 PARA_EMERG_LOG("failed to parse command line options: %s\n",
152 para_strerror(-ret));
155 loglevel = OPT_UINT32_VAL(LOGLEVEL);
156 version_handle_flag("play", OPT_GIVEN(VERSION));
157 handle_help_flags(); /* also handles the zero-arg case */
158 ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
159 "play.conf", &play_lpr, CMD_PTR, play_suite, 0 /* flags */);
161 PARA_EMERG_LOG("failed to parse config file: %s\n",
162 para_strerror(-ret));
165 loglevel = OPT_UINT32_VAL(LOGLEVEL);
166 num_kmas = OPT_GIVEN(KEY_MAP);
167 for (i = 0; i < num_kmas; i++) {
168 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
169 if (*kma && strchr(kma + 1, ':'))
171 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
176 static char get_playback_state(void)
179 case CRT_NONE: return pt->playing? 'P' : 'U';
180 case CRT_REPOS: return 'R';
181 case CRT_FILE_CHANGE: return 'F';
182 case CRT_TERM_RQ: return 'X';
187 /* returns number of milliseconds */
188 static long unsigned get_play_time(void)
190 char state = get_playback_state();
191 long unsigned result;
193 if (state != 'P' && state != 'U')
195 if (pt->num_chunks == 0 || pt->seconds == 0)
197 /* where the stream started (in milliseconds) */
198 result = 1000ULL * pt->start_chunk * pt->seconds / pt->num_chunks;
199 if (pt->wn.btrn) { /* Add the uptime of the writer node */
200 struct timeval diff = {.tv_sec = 0}, wstime;
201 btr_get_node_start(pt->wn.btrn, &wstime);
202 if (wstime.tv_sec > 0)
203 tv_diff(now, &wstime, &diff);
204 result += tv2ms(&diff);
206 result = PARA_MIN(result, pt->seconds * 1000);
207 result = PARA_MAX(result, 0UL);
211 static void wipe_receiver_node(void)
213 PARA_NOTICE_LOG("cleaning up receiver node\n");
214 btr_remove_node(&pt->rn.btrn);
215 AFH_RECV->close(&pt->rn);
216 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
217 memset(&pt->rn, 0, sizeof(struct receiver_node));
220 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
221 static int get_playback_error(void)
227 err = task_status(pt->wn.task);
230 if (task_status(pt->fn.task) >= 0)
232 if (task_status(pt->rn.task) >= 0)
239 static int eof_cleanup(void)
241 const struct filter *decoder;
242 const struct writer *w = writer_get(-1); /* default writer */
245 ret = get_playback_error();
248 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
249 task_reap(&pt->wn.task);
251 btr_remove_node(&pt->wn.btrn);
252 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
253 memset(&pt->wn, 0, sizeof(struct writer_node));
255 decoder = filter_get(pt->fn.filter_num);
256 task_reap(&pt->fn.task);
257 if (decoder && decoder->close)
258 decoder->close(&pt->fn);
259 btr_remove_node(&pt->fn.btrn);
260 lls_free_parse_result(pt->fn.lpr, FILTER_CMD(pt->fn.filter_num));
262 memset(&pt->fn, 0, sizeof(struct filter_node));
264 task_reap(&pt->rn.task);
265 btr_remove_node(&pt->rn.btrn);
267 * On eof (ret > 0), we do not wipe the receiver node struct until a
268 * new file is loaded because we still need it for jumping around when
272 wipe_receiver_node();
276 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
278 return para_random(100) - 50;
281 static void init_shuffle_map(void)
283 unsigned n, num_inputs = lls_num_inputs(play_lpr);
284 shuffle_map = arr_alloc(num_inputs, sizeof(unsigned));
285 for (n = 0; n < num_inputs; n++)
287 if (!OPT_GIVEN(RANDOMIZE))
290 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
293 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
295 return btr_new_node(&(struct btr_node_description)
296 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
297 .handler = AFH_RECV->execute));
300 static int open_new_file(void)
303 const char *path = get_playlist_file(pt->next_file);
304 char *tmp = para_strdup(path), *errctx;
305 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
307 PARA_NOTICE_LOG("next file: %s\n", path);
308 wipe_receiver_node();
310 pt->rn.btrn = new_recv_btrn(&pt->rn);
311 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
312 &pt->rn.lpr, &errctx));
315 pt->rn.receiver = AFH_RECV;
316 ret = AFH_RECV->open(&pt->rn);
318 PARA_ERROR_LOG("could not open %s\n", path);
321 pt->audio_format_num = ret;
323 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
325 pt->afhi_txt = make_message("[afhi command failed]\n");
326 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
331 ret = para_atoi32(tmp, &x);
332 pt->seconds = ret < 0? 1 : x;
336 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
341 ret = para_atoi32(tmp, &x);
342 pt->num_chunks = ret < 0? 1 : x;
348 wipe_receiver_node();
352 static int load_file(void)
357 const struct filter *decoder;
358 static struct lls_parse_result *filter_lpr, *writer_lpr;
360 btr_remove_node(&pt->rn.btrn);
361 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
362 ret = open_new_file();
366 pt->rn.btrn = new_recv_btrn(&pt->rn);
367 sprintf(buf, "repos %lu", pt->start_chunk);
368 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
370 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
375 /* set up decoding filter */
376 af = audio_format_name(pt->audio_format_num);
377 tmp = make_message("%sdec", af);
378 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
382 pt->fn.filter_num = ret;
383 pt->fn.lpr = filter_lpr;
384 decoder = filter_get(ret);
385 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
386 EMBRACE(.name = filter_name(pt->fn.filter_num),
387 .parent = pt->rn.btrn, .handler = decoder->execute,
388 .context = &pt->fn));
390 decoder->open(&pt->fn);
391 PARA_INFO_LOG("buffer tree:\n");
392 btr_log_tree(pt->rn.btrn, LL_INFO);
394 /* setup default writer */
395 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
396 pt->wn.lpr = writer_lpr;
397 /* success, register tasks */
398 pt->rn.task = task_register(
399 &(struct task_info) {
400 .name = lls_command_name(AFH_RECV_CMD),
401 .pre_monitor = AFH_RECV->pre_monitor,
402 .post_monitor = AFH_RECV->post_monitor,
405 sprintf(buf, "%s decoder", af);
406 pt->fn.task = task_register(
407 &(struct task_info) {
409 .pre_monitor = decoder->pre_monitor,
410 .post_monitor = decoder->post_monitor,
413 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
416 wipe_receiver_node();
420 static int next_valid_file(void)
422 int i, j = pt->current_file;
423 unsigned num_inputs = lls_num_inputs(play_lpr);
425 if (j == num_inputs - 1) {
426 switch (OPT_UINT32_VAL(END_OF_PLAYLIST)) {
427 case EOP_LOOP: break;
431 case EOP_QUIT: return -E_EOP;
434 for (i = 0; i < num_inputs; i++) {
435 j = (j + 1) % num_inputs;
439 return -E_NO_VALID_FILES;
442 static int load_next_file(void)
447 if (pt->rq == CRT_NONE) {
449 ret = next_valid_file();
453 } else if (pt->rq == CRT_REPOS)
454 pt->next_file = pt->current_file;
457 PARA_ERROR_LOG("%s: marking file as invalid\n",
458 para_strerror(-ret));
459 pt->invalid[pt->next_file] = true;
463 pt->current_file = pt->next_file;
468 static void kill_stream(void)
471 task_notify(pt->wn.task, E_EOF);
474 /* only called from com_prev(), nec. only if we have readline */
475 static int previous_valid_file(void)
477 int i, j = pt->current_file;
478 unsigned num_inputs = lls_num_inputs(play_lpr);
480 for (i = 0; i < num_inputs; i++) {
487 return -E_NO_VALID_FILES;
491 * Define the default (internal) key mappings and helper functions to get the
492 * key sequence or the command from a key id, which is what we obtain from
493 * i9e/readline when the key is pressed.
495 * In some of these helper functions we could return pointers to the constant
496 * arrays defined below. However, for others we can not, so let's better be
497 * consistent and allocate all returned strings on the heap.
500 #define INTERNAL_KEYMAP_ENTRIES \
501 KEYMAP_ENTRY("^", "jmp 0"), \
502 KEYMAP_ENTRY("1", "jmp 10"), \
503 KEYMAP_ENTRY("2", "jmp 21"), \
504 KEYMAP_ENTRY("3", "jmp 32"), \
505 KEYMAP_ENTRY("4", "jmp 43"), \
506 KEYMAP_ENTRY("5", "jmp 54"), \
507 KEYMAP_ENTRY("6", "jmp 65"), \
508 KEYMAP_ENTRY("7", "jmp 76"), \
509 KEYMAP_ENTRY("8", "jmp 87"), \
510 KEYMAP_ENTRY("9", "jmp 98"), \
511 KEYMAP_ENTRY("+", "next"), \
512 KEYMAP_ENTRY("-", "prev"), \
513 KEYMAP_ENTRY(":", "bg"), \
514 KEYMAP_ENTRY("i", "info"), \
515 KEYMAP_ENTRY("l", "ls"), \
516 KEYMAP_ENTRY("s", "play"), \
517 KEYMAP_ENTRY("p", "pause"), \
518 KEYMAP_ENTRY("q", "quit"), \
519 KEYMAP_ENTRY("?", "help"), \
520 KEYMAP_ENTRY("\033[D", "ff -10"), \
521 KEYMAP_ENTRY("\033[C", "ff 10"), \
522 KEYMAP_ENTRY("\033[A", "ff 60"), \
523 KEYMAP_ENTRY("\033[B", "ff -60"), \
525 #define KEYMAP_ENTRY(a, b) a
526 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
528 #define KEYMAP_ENTRY(a, b) b
529 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
531 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
532 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
533 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
535 static inline bool is_internal_key(int key)
537 return key < NUM_INTERNALLY_MAPPED_KEYS;
540 /* for internal keys, the key id is just the array index. */
541 static inline int get_internal_key_map_idx(int key)
543 assert(is_internal_key(key));
548 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
549 * difference is the index to the array of user defined key maps.
551 static inline int get_user_key_map_idx(int key)
553 assert(!is_internal_key(key));
554 return key - NUM_INTERNALLY_MAPPED_KEYS;
557 static inline int get_key_map_idx(int key)
559 return is_internal_key(key)?
560 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
563 static inline const char *get_user_key_map_arg(int key)
565 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
568 static inline char *get_internal_key_map_seq(int key)
570 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
573 static char *get_key_map_seq(int key)
579 if (is_internal_key(key))
580 return get_internal_key_map_seq(key);
581 kma = get_user_key_map_arg(key);
582 p = strchr(kma + 1, ':');
583 assert(p); /* We checked earlier that kma contains a colon */
585 result = alloc(len + 1);
586 memcpy(result, kma, len);
591 static char *get_key_map_seq_safe(int key)
593 const char hex[] = "0123456789abcdef";
594 char *seq = get_key_map_seq(key), *sseq;
595 size_t n, len = strlen(seq);
597 if (len == 1 && isprint(*seq))
599 sseq = alloc(2 + 2 * len + 1);
602 for (n = 0; n < len; n++) {
603 uint8_t val = (seq[n] & 0xf0) >> 4;
604 sseq[2 + 2 * n] = hex[val];
606 sseq[2 + 2 * n + 1] = hex[val];
609 sseq[2 + 2 * n] = '\0';
613 static inline char *get_internal_key_map_cmd(int key)
615 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
618 static char *get_user_key_map_cmd(int key)
620 const char *kma = get_user_key_map_arg(key);
621 const char *p = strchr(kma + 1, ':');
625 return para_strdup(p + 1);
628 static char *get_key_map_cmd(int key)
630 return is_internal_key(key)?
631 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
634 static char **get_mapped_keyseqs(void)
639 result = arr_alloc(NUM_MAPPED_KEYS + 1, sizeof(char *));
640 FOR_EACH_MAPPED_KEY(i) {
641 char *seq = get_key_map_seq(i);
648 static struct i9e_completer pp_completers[];
650 I9E_DUMMY_COMPLETER(jmp);
651 I9E_DUMMY_COMPLETER(next);
652 I9E_DUMMY_COMPLETER(prev);
653 I9E_DUMMY_COMPLETER(fg);
654 I9E_DUMMY_COMPLETER(bg);
655 I9E_DUMMY_COMPLETER(ls);
656 I9E_DUMMY_COMPLETER(info);
657 I9E_DUMMY_COMPLETER(play);
658 I9E_DUMMY_COMPLETER(pause);
659 I9E_DUMMY_COMPLETER(tasks);
660 I9E_DUMMY_COMPLETER(quit);
661 I9E_DUMMY_COMPLETER(ff);
663 static void help_completer(struct i9e_completion_info *ci,
664 struct i9e_completion_result *cr)
666 char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
668 if (ci->word[0] == '-') {
669 i9e_complete_option(opts, ci, cr);
672 cr->matches = i9e_complete_commands(ci->word, pp_completers);
675 static struct i9e_completer pp_completers[] = {
676 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
677 .completer = _name ## _completer}
678 LSG_PLAY_CMD_SUBCOMMANDS
679 #undef LSG_PLAY_CMD_CMD
683 static void attach_stdout(const char *name)
687 pt->btrn = btr_new_node(&(struct btr_node_description)
688 EMBRACE(.name = name));
689 i9e_attach_to_stdout(pt->btrn);
692 static void detach_stdout(void)
694 btr_remove_node(&pt->btrn);
697 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
698 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
699 .handler = com_ ## _cmd \
702 static int com_quit(__a_unused struct lls_parse_result *lpr)
704 pt->rq = CRT_TERM_RQ;
707 EXPORT_PLAY_CMD_HANDLER(quit);
709 static int com_help(struct lls_parse_result *lpr)
715 const struct lls_opt_result *r =
716 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
717 bool long_help = lls_opt_given(r);
719 if (!pt->background) {
720 FOR_EACH_MAPPED_KEY(i) {
721 bool internal = is_internal_key(i);
722 int idx = get_key_map_idx(i);
723 char *seq = get_key_map_seq_safe(i);
724 char *kmc = get_key_map_cmd(i);
725 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
726 internal? "internal" : "user-defined",
728 btr_add_output(buf, sz, pt->btrn);
734 lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
735 btr_add_output(buf, n, pt->btrn);
738 EXPORT_PLAY_CMD_HANDLER(help);
740 static int com_info(__a_unused struct lls_parse_result *lpr)
744 static char dflt[] = "[no information available]";
746 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
747 pt->current_file, get_playlist_file(pt->current_file));
748 btr_add_output(buf, sz, pt->btrn);
749 buf = pt->afhi_txt? pt->afhi_txt : dflt;
750 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
753 EXPORT_PLAY_CMD_HANDLER(info);
755 static void list_file(int num)
760 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
761 "*" : " ", num, get_playlist_file(num));
762 btr_add_output(buf, sz, pt->btrn);
765 static int com_tasks(__a_unused struct lls_parse_result *lpr)
771 buf = get_task_list(&sched);
772 btr_add_output(buf, strlen(buf), pt->btrn);
773 state = get_playback_state();
774 sz = xasprintf(&buf, "state: %c\n", state);
775 btr_add_output(buf, sz, pt->btrn);
778 EXPORT_PLAY_CMD_HANDLER(tasks);
780 static int com_ls(__a_unused struct lls_parse_result *lpr)
783 unsigned num_inputs = lls_num_inputs(play_lpr);
785 for (i = 0; i < num_inputs; i++)
789 EXPORT_PLAY_CMD_HANDLER(ls);
791 static int com_play(struct lls_parse_result *lpr)
797 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
800 PARA_ERROR_LOG("%s\n", errctx);
804 state = get_playback_state();
805 if (lls_num_inputs(lpr) == 0) {
808 pt->next_file = pt->current_file;
813 ret = para_atoi32(lls_input(0, lpr), &x);
816 if (x < 0 || x >= lls_num_inputs(play_lpr))
817 return -ERRNO_TO_PARA_ERROR(EINVAL);
820 pt->rq = CRT_FILE_CHANGE;
823 EXPORT_PLAY_CMD_HANDLER(play);
825 static int com_pause(__a_unused struct lls_parse_result *lpr)
829 unsigned long cn; /* chunk num */
831 state = get_playback_state();
835 ms = get_play_time();
839 cn = ms * pt->num_chunks / pt->seconds / 1000 + 1;
840 cn = PARA_MIN(cn, pt->num_chunks);
841 pt->start_chunk = cn;
846 EXPORT_PLAY_CMD_HANDLER(pause);
848 static int com_prev(__a_unused struct lls_parse_result *lpr)
852 ret = previous_valid_file();
857 pt->rq = CRT_FILE_CHANGE;
861 EXPORT_PLAY_CMD_HANDLER(prev);
863 static int com_next(__a_unused struct lls_parse_result *lpr)
867 ret = next_valid_file();
872 pt->rq = CRT_FILE_CHANGE;
876 EXPORT_PLAY_CMD_HANDLER(next);
878 static int com_fg(__a_unused struct lls_parse_result *lpr)
880 pt->background = false;
883 EXPORT_PLAY_CMD_HANDLER(fg);
885 static int com_bg(__a_unused struct lls_parse_result *lpr)
887 pt->background = true;
890 EXPORT_PLAY_CMD_HANDLER(bg);
892 static int com_jmp(struct lls_parse_result *lpr)
898 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
901 PARA_ERROR_LOG("%s\n", errctx);
905 ret = para_atoi32(lls_input(0, lpr), &percent);
908 if (percent < 0 || percent > 100)
909 return -ERRNO_TO_PARA_ERROR(EINVAL);
911 return com_next(NULL);
912 if (pt->playing && !pt->fn.btrn)
914 pt->start_chunk = (uint64_t)percent * pt->num_chunks / 100;
921 EXPORT_PLAY_CMD_HANDLER(jmp);
923 static int com_ff(struct lls_parse_result *lpr)
929 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
932 PARA_ERROR_LOG("%s\n", errctx);
936 ret = para_atoi32(lls_input(0, lpr), &seconds);
939 if (pt->playing && !pt->fn.btrn)
941 seconds += (get_play_time() + 500) / 1000;
942 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
943 seconds = PARA_MAX(seconds, 0);
944 pt->start_chunk = (uint64_t)pt->num_chunks * seconds / pt->seconds;
945 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
946 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
953 EXPORT_PLAY_CMD_HANDLER(ff);
955 static int run_command(char *line)
960 const struct play_command_info *pci;
961 struct lls_parse_result *lpr;
962 const struct lls_command *cmd;
964 attach_stdout(__FUNCTION__);
965 ret = create_argv(line, " ", &argv);
971 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
974 cmd = lls_cmd(ret, play_cmd_suite);
975 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
978 pci = lls_user_data(cmd);
979 ret = pci->handler(lpr);
980 lls_free_parse_result(lpr, cmd);
983 PARA_ERROR_LOG("%s\n", errctx);
989 static int play_i9e_line_handler(char *line)
991 return run_command(line);
994 static int play_i9e_key_handler(int key)
996 int idx = get_key_map_idx(key);
997 char *seq = get_key_map_seq(key);
998 char *cmd = get_key_map_cmd(key);
999 bool internal = is_internal_key(key);
1001 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1002 key, internal? "internal" : "user-defined",
1007 pt->next_update = *now;
1011 static struct i9e_client_info ici = {
1013 .prompt = "para_play> ",
1014 .line_handler = play_i9e_line_handler,
1015 .key_handler = play_i9e_key_handler,
1016 .completers = pp_completers,
1019 static void sigint_handler(int sig)
1021 pt->background = true;
1022 i9e_signal_dispatch(sig);
1026 * We start with para_log() set to the standard log function which writes to
1027 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1030 static void session_open(void)
1034 struct sigaction act;
1036 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1037 if (OPT_GIVEN(HISTORY_FILE))
1038 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1040 const char *confdir = get_confdir();
1042 ret = para_mkdir(confdir);
1043 /* warn, but otherwise ignore mkdir error */
1045 PARA_WARNING_LOG("Can not create %s: %s\n", confdir,
1046 para_strerror(-ret));
1047 history_file = make_message("%s/play.history", confdir);
1049 ici.history_file = history_file;
1050 ici.loglevel = loglevel;
1052 act.sa_handler = sigint_handler;
1053 sigemptyset(&act.sa_mask);
1055 sigaction(SIGINT, &act, NULL);
1056 act.sa_handler = i9e_signal_dispatch;
1057 sigemptyset(&act.sa_mask);
1059 sigaction(SIGWINCH, &act, NULL);
1060 sched.poll_function = i9e_poll;
1062 ici.bound_keyseqs = get_mapped_keyseqs();
1063 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1064 EMBRACE(.name = __FUNCTION__));
1065 ret = i9e_open(&ici, &sched);
1074 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1078 static void session_update_time_string(char *str, unsigned len)
1083 if (btr_get_output_queue_size(pt->btrn) > 0)
1085 if (btr_get_input_queue_size(pt->btrn) > 0)
1088 i9e_print_status_bar(str, len);
1091 static void play_pre_monitor(struct sched *s, __a_unused void *context)
1095 sched_monitor_readfd(STDIN_FILENO, s);
1096 state = get_playback_state();
1097 if (state == 'R' || state == 'F' || state == 'X')
1098 return sched_min_delay(s);
1099 sched_request_barrier_or_min_delay(&pt->next_update, s);
1102 static unsigned get_time_string(char **result)
1104 int seconds, length;
1105 char state = get_playback_state();
1107 /* do not return anything if things are about to change */
1108 if (state != 'P' && state != 'U') {
1112 length = pt->seconds;
1114 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1115 seconds = (get_play_time() + 500) / 1000;
1116 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1120 (length - seconds) / 60,
1121 (length - seconds) % 60,
1122 length? (seconds * 100 + length / 2) / length : 0,
1125 get_playlist_file(pt->current_file)
1129 static int play_post_monitor(__a_unused struct sched *s, __a_unused void *context)
1136 attach_stdout(__FUNCTION__);
1137 i9e_error = i9e_get_error();
1138 ret = eof_cleanup();
1139 if (pt->rq == CRT_TERM_RQ || i9e_error < 0) /* com_quit() or CTRL+D */
1140 kill_stream(); /* terminate receiver/filter/writer */
1141 if ((ret < 0 || pt->rq == CRT_TERM_RQ) && i9e_error >= 0)
1142 i9e_signal_dispatch(SIGTERM); /* terminate the i9e task */
1143 if (ret < 0) /* unexpected error from the writer node */
1145 if (ret != 0 && i9e_error < 0) /* eof, and i9e has died */
1147 if (!pt->wn.btrn && !pt->fn.btrn) {
1148 char state = get_playback_state();
1149 if (state == 'P' || state == 'R' || state == 'F') {
1150 PARA_NOTICE_LOG("state: %c\n", state);
1151 ret = load_next_file();
1153 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1154 pt->rq = CRT_TERM_RQ;
1157 pt->next_update = *now;
1160 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1162 unsigned len = get_time_string(&str);
1163 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1165 session_update_time_string(str, len);
1167 tv_add(now, &delay, &pt->next_update);
1173 * The main function of para_play.
1175 * \param argc See man page.
1176 * \param argv See man page.
1178 * para_play distributes its work by submitting various tasks to the paraslash
1179 * scheduler. The receiver, filter and writer tasks, which are used to play an
1180 * audio file, require one task each to maintain their underlying buffer tree
1181 * node. These tasks only exist when an audio file is playing.
1183 * The i9 task, which is submitted and maintained by the i9e subsystem, reads
1184 * an input line and calls the corresponding command handler such as com_stop()
1185 * which is implemented in this file. The command handlers typically write a
1186 * request to the global play_task structure, whose contents are read and acted
1187 * upon by another task, the play task.
1189 * As a rule, playlist handling is performed exclusively in play context, i.e.
1190 * in the post-monitor step of the play task, while command handlers are only
1191 * called in i9e context.
1193 * \return EXIT_FAILURE or EXIT_SUCCESS.
1195 int main(int argc, char *argv[])
1198 unsigned num_inputs;
1200 sched.default_timeout = 5000;
1201 parse_config_or_die(argc, argv);
1203 num_inputs = lls_num_inputs(play_lpr);
1205 pt->invalid = arr_zalloc(num_inputs, sizeof(*pt->invalid));
1206 pt->rq = CRT_FILE_CHANGE;
1208 pt->task = task_register(&(struct task_info){
1210 .pre_monitor = play_pre_monitor,
1211 .post_monitor = play_post_monitor,
1214 ret = schedule(&sched);
1215 sched_shutdown(&sched);
1217 wipe_receiver_node();
1218 para_log = stderr_log;
1219 free(ici.history_file);
1221 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1222 free(get_confdir());
1223 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;