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"
28 /** Array of error strings. */
31 static struct lls_parse_result *play_lpr;
33 #define CMD_PTR (lls_cmd(0, play_suite))
34 #define OPT_RESULT(_name) \
35 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
36 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
37 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
38 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
41 * Describes a request to change the state of para_play.
43 * There is only one variable of this type: \a rq of the global play task
44 * structure. Command handlers only set this variable and the post_monitor()
45 * function of the play task investigates its value during each iteration of
46 * the scheduler run and performs the actual work.
48 enum state_change_request_type {
49 /** Everybody is happy. */
51 /** Stream must be repositioned (com_jmp(), com_ff()). */
53 /** New file should be loaded (com_next()). */
55 /** Someone wants us for dead (com_quit()). */
61 /* A bit array of invalid files (those will be skipped). */
63 /* The file which is currently open. */
64 unsigned current_file;
65 /* When to update the status again. */
66 struct timeval next_update;
68 /* Root of the buffer tree for command and status output. */
69 struct btr_node *btrn;
71 /* The decoding machinery. */
72 struct receiver_node rn;
73 struct filter_node fn;
74 struct writer_node wn;
76 /* See comment to enum \ref state_change_request_type above. */
77 enum state_change_request_type rq;
78 /* only relevant if rq == CRT_FILE_CHANGE */
81 bg: read lines at prompt, fg: display status and wait
86 /* We have the *intention* to play. Set by com_play(). */
89 /* as returned by afh_recv->open() */
92 /* retrieved via the btr exec mechanism */
93 long unsigned start_chunk;
94 long unsigned seconds;
95 long unsigned num_chunks;
99 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
100 struct play_command_info {
101 play_cmd_handler_t handler;
104 static int loglevel = LL_WARNING;
106 /** The log function which writes log messages to stderr. */
107 INIT_STDERR_LOGGING(loglevel);
109 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
111 static struct sched sched;
112 static struct play_task play_task, *pt = &play_task;
114 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
115 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
117 static unsigned *shuffle_map;
119 static const char *get_playlist_file(unsigned idx)
121 return lls_input(shuffle_map[idx], play_lpr);
124 static void handle_help_flags(void)
128 if (OPT_GIVEN(DETAILED_HELP))
129 help = lls_long_help(CMD_PTR);
130 else if (OPT_GIVEN(HELP) || lls_num_inputs(play_lpr) == 0)
131 help = lls_short_help(CMD_PTR);
134 printf("%s\n", help);
139 static void parse_config_or_die(int argc, char *argv[])
145 ret = lls(lls_parse(argc, argv, CMD_PTR, &play_lpr, &errctx));
148 PARA_EMERG_LOG("%s\n", errctx);
150 PARA_EMERG_LOG("failed to parse command line options: %s\n",
151 para_strerror(-ret));
154 loglevel = OPT_UINT32_VAL(LOGLEVEL);
155 version_handle_flag("play", OPT_GIVEN(VERSION));
156 handle_help_flags(); /* also handles the zero-arg case */
157 ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
158 "play.conf", &play_lpr, CMD_PTR, play_suite, 0 /* flags */);
160 PARA_EMERG_LOG("failed to parse config file: %s\n",
161 para_strerror(-ret));
164 loglevel = OPT_UINT32_VAL(LOGLEVEL);
165 num_kmas = OPT_GIVEN(KEY_MAP);
166 for (i = 0; i < num_kmas; i++) {
167 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
168 if (*kma && strchr(kma + 1, ':'))
170 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
175 static char get_playback_state(void)
178 case CRT_NONE: return pt->playing? 'P' : 'U';
179 case CRT_REPOS: return 'R';
180 case CRT_FILE_CHANGE: return 'F';
181 case CRT_TERM_RQ: return 'X';
186 /* returns number of milliseconds */
187 static long unsigned get_play_time(void)
189 char state = get_playback_state();
190 long unsigned result;
192 if (state != 'P' && state != 'U')
194 if (pt->num_chunks == 0 || pt->seconds == 0)
196 /* where the stream started (in milliseconds) */
197 result = 1000ULL * pt->start_chunk * pt->seconds / pt->num_chunks;
198 if (pt->wn.btrn) { /* Add the uptime of the writer node */
199 struct timeval diff = {.tv_sec = 0}, wstime;
200 btr_get_node_start(pt->wn.btrn, &wstime);
201 if (wstime.tv_sec > 0)
202 tv_diff(now, &wstime, &diff);
203 result += tv2ms(&diff);
205 result = PARA_MIN(result, pt->seconds * 1000);
206 result = PARA_MAX(result, 0UL);
210 static void wipe_receiver_node(void)
212 PARA_NOTICE_LOG("cleaning up receiver node\n");
213 btr_remove_node(&pt->rn.btrn);
214 AFH_RECV->close(&pt->rn);
215 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
216 memset(&pt->rn, 0, sizeof(struct receiver_node));
219 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
220 static int get_playback_error(void)
226 err = task_status(pt->wn.task);
229 if (task_status(pt->fn.task) >= 0)
231 if (task_status(pt->rn.task) >= 0)
233 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
234 || err == -E_WRITE_COMMON_EOF)
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);
476 /* only called from com_prev(), nec. only if we have readline */
477 static int previous_valid_file(void)
479 int i, j = pt->current_file;
480 unsigned num_inputs = lls_num_inputs(play_lpr);
482 for (i = 0; i < num_inputs; i++) {
489 return -E_NO_VALID_FILES;
492 #include "interactive.h"
495 * Define the default (internal) key mappings and helper functions to get the
496 * key sequence or the command from a key id, which is what we obtain from
497 * i9e/readline when the key is pressed.
499 * In some of these helper functions we could return pointers to the constant
500 * arrays defined below. However, for others we can not, so let's better be
501 * consistent and allocate all returned strings on the heap.
504 #define INTERNAL_KEYMAP_ENTRIES \
505 KEYMAP_ENTRY("^", "jmp 0"), \
506 KEYMAP_ENTRY("1", "jmp 10"), \
507 KEYMAP_ENTRY("2", "jmp 21"), \
508 KEYMAP_ENTRY("3", "jmp 32"), \
509 KEYMAP_ENTRY("4", "jmp 43"), \
510 KEYMAP_ENTRY("5", "jmp 54"), \
511 KEYMAP_ENTRY("6", "jmp 65"), \
512 KEYMAP_ENTRY("7", "jmp 76"), \
513 KEYMAP_ENTRY("8", "jmp 87"), \
514 KEYMAP_ENTRY("9", "jmp 98"), \
515 KEYMAP_ENTRY("+", "next"), \
516 KEYMAP_ENTRY("-", "prev"), \
517 KEYMAP_ENTRY(":", "bg"), \
518 KEYMAP_ENTRY("i", "info"), \
519 KEYMAP_ENTRY("l", "ls"), \
520 KEYMAP_ENTRY("s", "play"), \
521 KEYMAP_ENTRY("p", "pause"), \
522 KEYMAP_ENTRY("q", "quit"), \
523 KEYMAP_ENTRY("?", "help"), \
524 KEYMAP_ENTRY("\033[D", "ff -10"), \
525 KEYMAP_ENTRY("\033[C", "ff 10"), \
526 KEYMAP_ENTRY("\033[A", "ff 60"), \
527 KEYMAP_ENTRY("\033[B", "ff -60"), \
529 #define KEYMAP_ENTRY(a, b) a
530 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
532 #define KEYMAP_ENTRY(a, b) b
533 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
535 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
536 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
537 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
539 static inline bool is_internal_key(int key)
541 return key < NUM_INTERNALLY_MAPPED_KEYS;
544 /* for internal keys, the key id is just the array index. */
545 static inline int get_internal_key_map_idx(int key)
547 assert(is_internal_key(key));
552 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
553 * difference is the index to the array of user defined key maps.
555 static inline int get_user_key_map_idx(int key)
557 assert(!is_internal_key(key));
558 return key - NUM_INTERNALLY_MAPPED_KEYS;
561 static inline int get_key_map_idx(int key)
563 return is_internal_key(key)?
564 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
567 static inline const char *get_user_key_map_arg(int key)
569 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
572 static inline char *get_internal_key_map_seq(int key)
574 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
577 static char *get_user_key_map_seq(int key)
579 const char *kma = get_user_key_map_arg(key);
580 const char *p = strchr(kma + 1, ':');
587 result = alloc(len + 1);
588 memcpy(result, kma, len);
593 static char *get_key_map_seq(int key)
595 return is_internal_key(key)?
596 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
599 static char *get_key_map_seq_safe(int key)
601 const char hex[] = "0123456789abcdef";
602 char *seq = get_key_map_seq(key), *sseq;
603 size_t n, len = strlen(seq);
605 if (len == 1 && isprint(*seq))
607 sseq = alloc(2 + 2 * len + 1);
610 for (n = 0; n < len; n++) {
611 uint8_t val = (seq[n] & 0xf0) >> 4;
612 sseq[2 + 2 * n] = hex[val];
614 sseq[2 + 2 * n + 1] = hex[val];
617 sseq[2 + 2 * n] = '\0';
621 static inline char *get_internal_key_map_cmd(int key)
623 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
626 static char *get_user_key_map_cmd(int key)
628 const char *kma = get_user_key_map_arg(key);
629 const char *p = strchr(kma + 1, ':');
633 return para_strdup(p + 1);
636 static char *get_key_map_cmd(int key)
638 return is_internal_key(key)?
639 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
642 static char **get_mapped_keyseqs(void)
647 result = arr_alloc(NUM_MAPPED_KEYS + 1, sizeof(char *));
648 FOR_EACH_MAPPED_KEY(i) {
649 char *seq = get_key_map_seq(i);
656 static struct i9e_completer pp_completers[];
658 I9E_DUMMY_COMPLETER(jmp);
659 I9E_DUMMY_COMPLETER(next);
660 I9E_DUMMY_COMPLETER(prev);
661 I9E_DUMMY_COMPLETER(fg);
662 I9E_DUMMY_COMPLETER(bg);
663 I9E_DUMMY_COMPLETER(ls);
664 I9E_DUMMY_COMPLETER(info);
665 I9E_DUMMY_COMPLETER(play);
666 I9E_DUMMY_COMPLETER(pause);
667 I9E_DUMMY_COMPLETER(tasks);
668 I9E_DUMMY_COMPLETER(quit);
669 I9E_DUMMY_COMPLETER(ff);
671 static void help_completer(struct i9e_completion_info *ci,
672 struct i9e_completion_result *cr)
674 char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
676 if (ci->word[0] == '-') {
677 i9e_complete_option(opts, ci, cr);
680 cr->matches = i9e_complete_commands(ci->word, pp_completers);
683 static struct i9e_completer pp_completers[] = {
684 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
685 .completer = _name ## _completer}
686 LSG_PLAY_CMD_SUBCOMMANDS
687 #undef LSG_PLAY_CMD_CMD
691 static void attach_stdout(const char *name)
695 pt->btrn = btr_new_node(&(struct btr_node_description)
696 EMBRACE(.name = name));
697 i9e_attach_to_stdout(pt->btrn);
700 static void detach_stdout(void)
702 btr_remove_node(&pt->btrn);
705 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
706 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
707 .handler = com_ ## _cmd \
710 static int com_quit(__a_unused struct lls_parse_result *lpr)
712 pt->rq = CRT_TERM_RQ;
715 EXPORT_PLAY_CMD_HANDLER(quit);
717 static int com_help(struct lls_parse_result *lpr)
723 const struct lls_opt_result *r =
724 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
725 bool long_help = lls_opt_given(r);
727 if (!pt->background) {
728 FOR_EACH_MAPPED_KEY(i) {
729 bool internal = is_internal_key(i);
730 int idx = get_key_map_idx(i);
731 char *seq = get_key_map_seq_safe(i);
732 char *kmc = get_key_map_cmd(i);
733 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
734 internal? "internal" : "user-defined",
736 btr_add_output(buf, sz, pt->btrn);
742 lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
743 btr_add_output(buf, n, pt->btrn);
746 EXPORT_PLAY_CMD_HANDLER(help);
748 static int com_info(__a_unused struct lls_parse_result *lpr)
752 static char dflt[] = "[no information available]";
754 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
755 pt->current_file, get_playlist_file(pt->current_file));
756 btr_add_output(buf, sz, pt->btrn);
757 buf = pt->afhi_txt? pt->afhi_txt : dflt;
758 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
761 EXPORT_PLAY_CMD_HANDLER(info);
763 static void list_file(int num)
768 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
769 "*" : " ", num, get_playlist_file(num));
770 btr_add_output(buf, sz, pt->btrn);
773 static int com_tasks(__a_unused struct lls_parse_result *lpr)
779 buf = get_task_list(&sched);
780 btr_add_output(buf, strlen(buf), pt->btrn);
781 state = get_playback_state();
782 sz = xasprintf(&buf, "state: %c\n", state);
783 btr_add_output(buf, sz, pt->btrn);
786 EXPORT_PLAY_CMD_HANDLER(tasks);
788 static int com_ls(__a_unused struct lls_parse_result *lpr)
791 unsigned num_inputs = lls_num_inputs(play_lpr);
793 for (i = 0; i < num_inputs; i++)
797 EXPORT_PLAY_CMD_HANDLER(ls);
799 static int com_play(struct lls_parse_result *lpr)
805 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
808 PARA_ERROR_LOG("%s\n", errctx);
812 state = get_playback_state();
813 if (lls_num_inputs(lpr) == 0) {
816 pt->next_file = pt->current_file;
821 ret = para_atoi32(lls_input(0, lpr), &x);
824 if (x < 0 || x >= lls_num_inputs(play_lpr))
825 return -ERRNO_TO_PARA_ERROR(EINVAL);
828 pt->rq = CRT_FILE_CHANGE;
831 EXPORT_PLAY_CMD_HANDLER(play);
833 static int com_pause(__a_unused struct lls_parse_result *lpr)
837 unsigned long cn; /* chunk num */
839 state = get_playback_state();
843 ms = get_play_time();
847 cn = ms * pt->num_chunks / pt->seconds / 1000 + 1;
848 cn = PARA_MIN(cn, pt->num_chunks);
849 pt->start_chunk = cn;
854 EXPORT_PLAY_CMD_HANDLER(pause);
856 static int com_prev(__a_unused struct lls_parse_result *lpr)
860 ret = previous_valid_file();
865 pt->rq = CRT_FILE_CHANGE;
869 EXPORT_PLAY_CMD_HANDLER(prev);
871 static int com_next(__a_unused struct lls_parse_result *lpr)
875 ret = next_valid_file();
880 pt->rq = CRT_FILE_CHANGE;
884 EXPORT_PLAY_CMD_HANDLER(next);
886 static int com_fg(__a_unused struct lls_parse_result *lpr)
888 pt->background = false;
891 EXPORT_PLAY_CMD_HANDLER(fg);
893 static int com_bg(__a_unused struct lls_parse_result *lpr)
895 pt->background = true;
898 EXPORT_PLAY_CMD_HANDLER(bg);
900 static int com_jmp(struct lls_parse_result *lpr)
906 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
909 PARA_ERROR_LOG("%s\n", errctx);
913 ret = para_atoi32(lls_input(0, lpr), &percent);
916 if (percent < 0 || percent > 100)
917 return -ERRNO_TO_PARA_ERROR(EINVAL);
919 return com_next(NULL);
920 if (pt->playing && !pt->fn.btrn)
922 pt->start_chunk = percent * pt->num_chunks / 100;
929 EXPORT_PLAY_CMD_HANDLER(jmp);
931 static int com_ff(struct lls_parse_result *lpr)
937 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
940 PARA_ERROR_LOG("%s\n", errctx);
944 ret = para_atoi32(lls_input(0, lpr), &seconds);
947 if (pt->playing && !pt->fn.btrn)
949 seconds += (get_play_time() + 500) / 1000;
950 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
951 seconds = PARA_MAX(seconds, 0);
952 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
953 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
954 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
961 EXPORT_PLAY_CMD_HANDLER(ff);
963 static int run_command(char *line)
968 const struct play_command_info *pci;
969 struct lls_parse_result *lpr;
970 const struct lls_command *cmd;
972 attach_stdout(__FUNCTION__);
973 ret = create_argv(line, " ", &argv);
979 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
982 cmd = lls_cmd(ret, play_cmd_suite);
983 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
986 pci = lls_user_data(cmd);
987 ret = pci->handler(lpr);
988 lls_free_parse_result(lpr, cmd);
991 PARA_ERROR_LOG("%s\n", errctx);
997 static int play_i9e_line_handler(char *line)
999 return run_command(line);
1002 static int play_i9e_key_handler(int key)
1004 int idx = get_key_map_idx(key);
1005 char *seq = get_key_map_seq(key);
1006 char *cmd = get_key_map_cmd(key);
1007 bool internal = is_internal_key(key);
1009 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1010 key, internal? "internal" : "user-defined",
1015 pt->next_update = *now;
1019 static struct i9e_client_info ici = {
1021 .prompt = "para_play> ",
1022 .line_handler = play_i9e_line_handler,
1023 .key_handler = play_i9e_key_handler,
1024 .completers = pp_completers,
1027 static void sigint_handler(int sig)
1029 pt->background = true;
1030 i9e_signal_dispatch(sig);
1034 * We start with para_log() set to the standard log function which writes to
1035 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1038 static void session_open(void)
1042 struct sigaction act;
1044 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1045 if (OPT_GIVEN(HISTORY_FILE))
1046 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1048 char *home = para_homedir();
1049 char *dot_para = make_message("%s/.paraslash", home);
1052 ret = para_mkdir(dot_para, 0777);
1053 /* warn, but otherwise ignore mkdir error */
1054 if (ret < 0 && ret != -ERRNO_TO_PARA_ERROR(EEXIST))
1055 PARA_WARNING_LOG("Can not create %s: %s\n", dot_para,
1056 para_strerror(-ret));
1057 history_file = make_message("%s/play.history", dot_para);
1060 ici.history_file = history_file;
1061 ici.loglevel = loglevel;
1063 act.sa_handler = sigint_handler;
1064 sigemptyset(&act.sa_mask);
1066 sigaction(SIGINT, &act, NULL);
1067 act.sa_handler = i9e_signal_dispatch;
1068 sigemptyset(&act.sa_mask);
1070 sigaction(SIGWINCH, &act, NULL);
1071 sched.poll_function = i9e_poll;
1073 ici.bound_keyseqs = get_mapped_keyseqs();
1074 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1075 EMBRACE(.name = __FUNCTION__));
1076 ret = i9e_open(&ici, &sched);
1085 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1089 static void session_update_time_string(char *str, unsigned len)
1094 if (btr_get_output_queue_size(pt->btrn) > 0)
1096 if (btr_get_input_queue_size(pt->btrn) > 0)
1099 i9e_print_status_bar(str, len);
1103 * If we are about to die we must call i9e_close() to reset the terminal.
1104 * However, i9e_close() must be called in *this* context, i.e. from
1105 * play_task.post_monitor() rather than from i9e_post_monitor(), because
1106 * otherwise i9e would access freed memory upon return. So the play task must
1107 * stay alive until the i9e task terminates.
1109 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1110 * and reschedule. In the next iteration, i9e->post_monitor returns an error and
1111 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1112 * are allowed to call i9e_close() and terminate as well.
1114 static int session_post_monitor(__a_unused struct sched *s)
1121 attach_stdout(__FUNCTION__);
1122 ret = i9e_get_error();
1126 para_log = stderr_log;
1127 free(ici.history_file);
1130 if (get_playback_state() == 'X')
1131 i9e_signal_dispatch(SIGTERM);
1135 #else /* HAVE_READLINE */
1137 static int session_post_monitor(struct sched *s)
1141 if (!sched_read_ok(STDIN_FILENO, s))
1143 if (read(STDIN_FILENO, &c, 1))
1149 static void session_open(void)
1153 static void session_update_time_string(char *str, __a_unused unsigned len)
1155 printf("\r%s ", str);
1158 #endif /* HAVE_READLINE */
1160 static void play_pre_monitor(struct sched *s, __a_unused void *context)
1164 sched_monitor_readfd(STDIN_FILENO, s);
1165 state = get_playback_state();
1166 if (state == 'R' || state == 'F' || state == 'X')
1167 return sched_min_delay(s);
1168 sched_request_barrier_or_min_delay(&pt->next_update, s);
1171 static unsigned get_time_string(char **result)
1173 int seconds, length;
1174 char state = get_playback_state();
1176 /* do not return anything if things are about to change */
1177 if (state != 'P' && state != 'U') {
1181 length = pt->seconds;
1183 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1184 seconds = (get_play_time() + 500) / 1000;
1185 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1189 (length - seconds) / 60,
1190 (length - seconds) % 60,
1191 length? (seconds * 100 + length / 2) / length : 0,
1194 get_playlist_file(pt->current_file)
1198 static int play_post_monitor(struct sched *s, __a_unused void *context)
1202 ret = eof_cleanup();
1204 pt->rq = CRT_TERM_RQ;
1207 ret = session_post_monitor(s);
1210 if (!pt->wn.btrn && !pt->fn.btrn) {
1211 char state = get_playback_state();
1212 if (state == 'P' || state == 'R' || state == 'F') {
1213 PARA_NOTICE_LOG("state: %c\n", state);
1214 ret = load_next_file();
1216 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1217 pt->rq = CRT_TERM_RQ;
1221 pt->next_update = *now;
1224 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1226 unsigned len = get_time_string(&str);
1227 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1229 session_update_time_string(str, len);
1231 tv_add(now, &delay, &pt->next_update);
1239 * The main function of para_play.
1241 * \param argc See man page.
1242 * \param argv See man page.
1244 * para_play distributes its work by submitting various tasks to the paraslash
1245 * scheduler. The receiver, filter and writer tasks, which are used to play an
1246 * audio file, require one task each to maintain their underlying buffer tree
1247 * node. These tasks only exist when an audio file is playing.
1249 * The i9 task, which is submitted and maintained by the i9e subsystem, reads
1250 * an input line and calls the corresponding command handler such as com_stop()
1251 * which is implemented in this file. The command handlers typically write a
1252 * request to the global play_task structure, whose contents are read and acted
1253 * upon by another task, the play task.
1255 * As a rule, playlist handling is performed exclusively in play context, i.e.
1256 * in the post-monitor step of the play task, while command handlers are only
1257 * called in i9e context.
1259 * \return EXIT_FAILURE or EXIT_SUCCESS.
1261 int main(int argc, char *argv[])
1264 unsigned num_inputs;
1266 sched.default_timeout = 5000;
1267 parse_config_or_die(argc, argv);
1269 num_inputs = lls_num_inputs(play_lpr);
1271 pt->invalid = arr_zalloc(num_inputs, sizeof(*pt->invalid));
1272 pt->rq = CRT_FILE_CHANGE;
1274 pt->task = task_register(&(struct task_info){
1276 .pre_monitor = play_pre_monitor,
1277 .post_monitor = play_post_monitor,
1280 ret = schedule(&sched);
1281 sched_shutdown(&sched);
1283 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1284 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;