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);
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_user_key_map_seq(int key)
575 const char *kma = get_user_key_map_arg(key);
576 const char *p = strchr(kma + 1, ':');
583 result = alloc(len + 1);
584 memcpy(result, kma, len);
589 static char *get_key_map_seq(int key)
591 return is_internal_key(key)?
592 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
595 static char *get_key_map_seq_safe(int key)
597 const char hex[] = "0123456789abcdef";
598 char *seq = get_key_map_seq(key), *sseq;
599 size_t n, len = strlen(seq);
601 if (len == 1 && isprint(*seq))
603 sseq = alloc(2 + 2 * len + 1);
606 for (n = 0; n < len; n++) {
607 uint8_t val = (seq[n] & 0xf0) >> 4;
608 sseq[2 + 2 * n] = hex[val];
610 sseq[2 + 2 * n + 1] = hex[val];
613 sseq[2 + 2 * n] = '\0';
617 static inline char *get_internal_key_map_cmd(int key)
619 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
622 static char *get_user_key_map_cmd(int key)
624 const char *kma = get_user_key_map_arg(key);
625 const char *p = strchr(kma + 1, ':');
629 return para_strdup(p + 1);
632 static char *get_key_map_cmd(int key)
634 return is_internal_key(key)?
635 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
638 static char **get_mapped_keyseqs(void)
643 result = arr_alloc(NUM_MAPPED_KEYS + 1, sizeof(char *));
644 FOR_EACH_MAPPED_KEY(i) {
645 char *seq = get_key_map_seq(i);
652 static struct i9e_completer pp_completers[];
654 I9E_DUMMY_COMPLETER(jmp);
655 I9E_DUMMY_COMPLETER(next);
656 I9E_DUMMY_COMPLETER(prev);
657 I9E_DUMMY_COMPLETER(fg);
658 I9E_DUMMY_COMPLETER(bg);
659 I9E_DUMMY_COMPLETER(ls);
660 I9E_DUMMY_COMPLETER(info);
661 I9E_DUMMY_COMPLETER(play);
662 I9E_DUMMY_COMPLETER(pause);
663 I9E_DUMMY_COMPLETER(tasks);
664 I9E_DUMMY_COMPLETER(quit);
665 I9E_DUMMY_COMPLETER(ff);
667 static void help_completer(struct i9e_completion_info *ci,
668 struct i9e_completion_result *cr)
670 char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
672 if (ci->word[0] == '-') {
673 i9e_complete_option(opts, ci, cr);
676 cr->matches = i9e_complete_commands(ci->word, pp_completers);
679 static struct i9e_completer pp_completers[] = {
680 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
681 .completer = _name ## _completer}
682 LSG_PLAY_CMD_SUBCOMMANDS
683 #undef LSG_PLAY_CMD_CMD
687 static void attach_stdout(const char *name)
691 pt->btrn = btr_new_node(&(struct btr_node_description)
692 EMBRACE(.name = name));
693 i9e_attach_to_stdout(pt->btrn);
696 static void detach_stdout(void)
698 btr_remove_node(&pt->btrn);
701 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
702 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
703 .handler = com_ ## _cmd \
706 static int com_quit(__a_unused struct lls_parse_result *lpr)
708 pt->rq = CRT_TERM_RQ;
711 EXPORT_PLAY_CMD_HANDLER(quit);
713 static int com_help(struct lls_parse_result *lpr)
719 const struct lls_opt_result *r =
720 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
721 bool long_help = lls_opt_given(r);
723 if (!pt->background) {
724 FOR_EACH_MAPPED_KEY(i) {
725 bool internal = is_internal_key(i);
726 int idx = get_key_map_idx(i);
727 char *seq = get_key_map_seq_safe(i);
728 char *kmc = get_key_map_cmd(i);
729 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
730 internal? "internal" : "user-defined",
732 btr_add_output(buf, sz, pt->btrn);
738 lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
739 btr_add_output(buf, n, pt->btrn);
742 EXPORT_PLAY_CMD_HANDLER(help);
744 static int com_info(__a_unused struct lls_parse_result *lpr)
748 static char dflt[] = "[no information available]";
750 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
751 pt->current_file, get_playlist_file(pt->current_file));
752 btr_add_output(buf, sz, pt->btrn);
753 buf = pt->afhi_txt? pt->afhi_txt : dflt;
754 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
757 EXPORT_PLAY_CMD_HANDLER(info);
759 static void list_file(int num)
764 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
765 "*" : " ", num, get_playlist_file(num));
766 btr_add_output(buf, sz, pt->btrn);
769 static int com_tasks(__a_unused struct lls_parse_result *lpr)
775 buf = get_task_list(&sched);
776 btr_add_output(buf, strlen(buf), pt->btrn);
777 state = get_playback_state();
778 sz = xasprintf(&buf, "state: %c\n", state);
779 btr_add_output(buf, sz, pt->btrn);
782 EXPORT_PLAY_CMD_HANDLER(tasks);
784 static int com_ls(__a_unused struct lls_parse_result *lpr)
787 unsigned num_inputs = lls_num_inputs(play_lpr);
789 for (i = 0; i < num_inputs; i++)
793 EXPORT_PLAY_CMD_HANDLER(ls);
795 static int com_play(struct lls_parse_result *lpr)
801 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
804 PARA_ERROR_LOG("%s\n", errctx);
808 state = get_playback_state();
809 if (lls_num_inputs(lpr) == 0) {
812 pt->next_file = pt->current_file;
817 ret = para_atoi32(lls_input(0, lpr), &x);
820 if (x < 0 || x >= lls_num_inputs(play_lpr))
821 return -ERRNO_TO_PARA_ERROR(EINVAL);
824 pt->rq = CRT_FILE_CHANGE;
827 EXPORT_PLAY_CMD_HANDLER(play);
829 static int com_pause(__a_unused struct lls_parse_result *lpr)
833 unsigned long cn; /* chunk num */
835 state = get_playback_state();
839 ms = get_play_time();
843 cn = ms * pt->num_chunks / pt->seconds / 1000 + 1;
844 cn = PARA_MIN(cn, pt->num_chunks);
845 pt->start_chunk = cn;
850 EXPORT_PLAY_CMD_HANDLER(pause);
852 static int com_prev(__a_unused struct lls_parse_result *lpr)
856 ret = previous_valid_file();
861 pt->rq = CRT_FILE_CHANGE;
865 EXPORT_PLAY_CMD_HANDLER(prev);
867 static int com_next(__a_unused struct lls_parse_result *lpr)
871 ret = next_valid_file();
876 pt->rq = CRT_FILE_CHANGE;
880 EXPORT_PLAY_CMD_HANDLER(next);
882 static int com_fg(__a_unused struct lls_parse_result *lpr)
884 pt->background = false;
887 EXPORT_PLAY_CMD_HANDLER(fg);
889 static int com_bg(__a_unused struct lls_parse_result *lpr)
891 pt->background = true;
894 EXPORT_PLAY_CMD_HANDLER(bg);
896 static int com_jmp(struct lls_parse_result *lpr)
902 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
905 PARA_ERROR_LOG("%s\n", errctx);
909 ret = para_atoi32(lls_input(0, lpr), &percent);
912 if (percent < 0 || percent > 100)
913 return -ERRNO_TO_PARA_ERROR(EINVAL);
915 return com_next(NULL);
916 if (pt->playing && !pt->fn.btrn)
918 pt->start_chunk = percent * pt->num_chunks / 100;
925 EXPORT_PLAY_CMD_HANDLER(jmp);
927 static int com_ff(struct lls_parse_result *lpr)
933 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
936 PARA_ERROR_LOG("%s\n", errctx);
940 ret = para_atoi32(lls_input(0, lpr), &seconds);
943 if (pt->playing && !pt->fn.btrn)
945 seconds += (get_play_time() + 500) / 1000;
946 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
947 seconds = PARA_MAX(seconds, 0);
948 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
949 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
950 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
957 EXPORT_PLAY_CMD_HANDLER(ff);
959 static int run_command(char *line)
964 const struct play_command_info *pci;
965 struct lls_parse_result *lpr;
966 const struct lls_command *cmd;
968 attach_stdout(__FUNCTION__);
969 ret = create_argv(line, " ", &argv);
975 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
978 cmd = lls_cmd(ret, play_cmd_suite);
979 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
982 pci = lls_user_data(cmd);
983 ret = pci->handler(lpr);
984 lls_free_parse_result(lpr, cmd);
987 PARA_ERROR_LOG("%s\n", errctx);
993 static int play_i9e_line_handler(char *line)
995 return run_command(line);
998 static int play_i9e_key_handler(int key)
1000 int idx = get_key_map_idx(key);
1001 char *seq = get_key_map_seq(key);
1002 char *cmd = get_key_map_cmd(key);
1003 bool internal = is_internal_key(key);
1005 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1006 key, internal? "internal" : "user-defined",
1011 pt->next_update = *now;
1015 static struct i9e_client_info ici = {
1017 .prompt = "para_play> ",
1018 .line_handler = play_i9e_line_handler,
1019 .key_handler = play_i9e_key_handler,
1020 .completers = pp_completers,
1023 static void sigint_handler(int sig)
1025 pt->background = true;
1026 i9e_signal_dispatch(sig);
1030 * We start with para_log() set to the standard log function which writes to
1031 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1034 static void session_open(void)
1038 struct sigaction act;
1040 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1041 if (OPT_GIVEN(HISTORY_FILE))
1042 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1044 char *home = para_homedir();
1045 char *dot_para = make_message("%s/.paraslash", home);
1048 ret = para_mkdir(dot_para);
1049 /* warn, but otherwise ignore mkdir error */
1051 PARA_WARNING_LOG("Can not create %s: %s\n", dot_para,
1052 para_strerror(-ret));
1053 history_file = make_message("%s/play.history", dot_para);
1056 ici.history_file = history_file;
1057 ici.loglevel = loglevel;
1059 act.sa_handler = sigint_handler;
1060 sigemptyset(&act.sa_mask);
1062 sigaction(SIGINT, &act, NULL);
1063 act.sa_handler = i9e_signal_dispatch;
1064 sigemptyset(&act.sa_mask);
1066 sigaction(SIGWINCH, &act, NULL);
1067 sched.poll_function = i9e_poll;
1069 ici.bound_keyseqs = get_mapped_keyseqs();
1070 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1071 EMBRACE(.name = __FUNCTION__));
1072 ret = i9e_open(&ici, &sched);
1081 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1085 static void session_update_time_string(char *str, unsigned len)
1090 if (btr_get_output_queue_size(pt->btrn) > 0)
1092 if (btr_get_input_queue_size(pt->btrn) > 0)
1095 i9e_print_status_bar(str, len);
1099 * If we are about to die we must call i9e_close() to reset the terminal.
1100 * However, i9e_close() must be called in *this* context, i.e. from
1101 * play_task.post_monitor() rather than from i9e_post_monitor(), because
1102 * otherwise i9e would access freed memory upon return. So the play task must
1103 * stay alive until the i9e task terminates.
1105 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1106 * and reschedule. In the next iteration, i9e->post_monitor returns an error and
1107 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1108 * are allowed to call i9e_close() and terminate as well.
1110 static int session_post_monitor(__a_unused struct sched *s)
1117 attach_stdout(__FUNCTION__);
1118 ret = i9e_get_error();
1122 para_log = stderr_log;
1123 free(ici.history_file);
1126 if (get_playback_state() == 'X')
1127 i9e_signal_dispatch(SIGTERM);
1131 static void play_pre_monitor(struct sched *s, __a_unused void *context)
1135 sched_monitor_readfd(STDIN_FILENO, s);
1136 state = get_playback_state();
1137 if (state == 'R' || state == 'F' || state == 'X')
1138 return sched_min_delay(s);
1139 sched_request_barrier_or_min_delay(&pt->next_update, s);
1142 static unsigned get_time_string(char **result)
1144 int seconds, length;
1145 char state = get_playback_state();
1147 /* do not return anything if things are about to change */
1148 if (state != 'P' && state != 'U') {
1152 length = pt->seconds;
1154 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1155 seconds = (get_play_time() + 500) / 1000;
1156 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1160 (length - seconds) / 60,
1161 (length - seconds) % 60,
1162 length? (seconds * 100 + length / 2) / length : 0,
1165 get_playlist_file(pt->current_file)
1169 static int play_post_monitor(struct sched *s, __a_unused void *context)
1173 ret = eof_cleanup();
1175 pt->rq = CRT_TERM_RQ;
1178 ret = session_post_monitor(s);
1181 if (!pt->wn.btrn && !pt->fn.btrn) {
1182 char state = get_playback_state();
1183 if (state == 'P' || state == 'R' || state == 'F') {
1184 PARA_NOTICE_LOG("state: %c\n", state);
1185 ret = load_next_file();
1187 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1188 pt->rq = CRT_TERM_RQ;
1192 pt->next_update = *now;
1195 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1197 unsigned len = get_time_string(&str);
1198 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1200 session_update_time_string(str, len);
1202 tv_add(now, &delay, &pt->next_update);
1210 * The main function of para_play.
1212 * \param argc See man page.
1213 * \param argv See man page.
1215 * para_play distributes its work by submitting various tasks to the paraslash
1216 * scheduler. The receiver, filter and writer tasks, which are used to play an
1217 * audio file, require one task each to maintain their underlying buffer tree
1218 * node. These tasks only exist when an audio file is playing.
1220 * The i9 task, which is submitted and maintained by the i9e subsystem, reads
1221 * an input line and calls the corresponding command handler such as com_stop()
1222 * which is implemented in this file. The command handlers typically write a
1223 * request to the global play_task structure, whose contents are read and acted
1224 * upon by another task, the play task.
1226 * As a rule, playlist handling is performed exclusively in play context, i.e.
1227 * in the post-monitor step of the play task, while command handlers are only
1228 * called in i9e context.
1230 * \return EXIT_FAILURE or EXIT_SUCCESS.
1232 int main(int argc, char *argv[])
1235 unsigned num_inputs;
1237 sched.default_timeout = 5000;
1238 parse_config_or_die(argc, argv);
1240 num_inputs = lls_num_inputs(play_lpr);
1242 pt->invalid = arr_zalloc(num_inputs, sizeof(*pt->invalid));
1243 pt->rq = CRT_FILE_CHANGE;
1245 pt->task = task_register(&(struct task_info){
1247 .pre_monitor = play_pre_monitor,
1248 .post_monitor = play_post_monitor,
1251 ret = schedule(&sched);
1252 sched_shutdown(&sched);
1254 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1255 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;