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 "play_cmd.lsg.h"
11 #include "write_cmd.lsg.h"
17 #include "buffer_tree.h"
28 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
29 * para_play creates two further tasks: The play task and the i9e task. It is
30 * important whether a function can be called in the context of para_play or
31 * i9e or both. As a rule, all command handlers are called only in i9e context via
32 * the line handler (input mode) or the key handler (command mode) below.
34 * Playlist handling is done exclusively in play context.
37 /** Array of error strings. */
40 static struct lls_parse_result *play_lpr;
42 #define CMD_PTR (lls_cmd(0, play_suite))
43 #define OPT_RESULT(_name) \
44 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
45 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
46 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
47 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
50 * Describes a request to change the state of para_play.
52 * There is only one variable of this type: \a rq of the global play task
53 * structure. Command handlers only set this variable and the post_monitor()
54 * function of the play task investigates its value during each iteration of
55 * the scheduler run and performs the actual work.
57 enum state_change_request_type {
58 /** Everybody is happy. */
60 /** Stream must be repositioned (com_jmp(), com_ff()). */
62 /** New file should be loaded (com_next()). */
64 /** Someone wants us for dead (com_quit()). */
70 /* A bit array of invalid files (those will be skipped). */
72 /* The file which is currently open. */
73 unsigned current_file;
74 /* When to update the status again. */
75 struct timeval next_update;
77 /* Root of the buffer tree for command and status output. */
78 struct btr_node *btrn;
80 /* The decoding machinery. */
81 struct receiver_node rn;
82 struct filter_node fn;
83 struct writer_node wn;
85 /* See comment to enum \ref state_change_request_type above. */
86 enum state_change_request_type rq;
87 /* only relevant if rq == CRT_FILE_CHANGE */
90 bg: read lines at prompt, fg: display status and wait
95 /* We have the *intention* to play. Set by com_play(). */
98 /* as returned by afh_recv->open() */
101 /* retrieved via the btr exec mechanism */
102 long unsigned start_chunk;
103 long unsigned seconds;
104 long unsigned num_chunks;
108 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
109 struct play_command_info {
110 play_cmd_handler_t handler;
113 static int loglevel = LL_WARNING;
115 /** The log function which writes log messages to stderr. */
116 INIT_STDERR_LOGGING(loglevel);
118 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
120 static struct sched sched;
121 static struct play_task play_task, *pt = &play_task;
123 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
124 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
126 static unsigned *shuffle_map;
128 static const char *get_playlist_file(unsigned idx)
130 return lls_input(shuffle_map[idx], play_lpr);
133 static void handle_help_flags(void)
137 if (OPT_GIVEN(DETAILED_HELP))
138 help = lls_long_help(CMD_PTR);
139 else if (OPT_GIVEN(HELP) || lls_num_inputs(play_lpr) == 0)
140 help = lls_short_help(CMD_PTR);
143 printf("%s\n", help);
148 static void parse_config_or_die(int argc, char *argv[])
154 ret = lls(lls_parse(argc, argv, CMD_PTR, &play_lpr, &errctx));
157 PARA_EMERG_LOG("%s\n", errctx);
159 PARA_EMERG_LOG("failed to parse command line options: %s\n",
160 para_strerror(-ret));
163 loglevel = OPT_UINT32_VAL(LOGLEVEL);
164 version_handle_flag("play", OPT_GIVEN(VERSION));
165 handle_help_flags(); /* also handles the zero-arg case */
166 ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
167 "play.conf", &play_lpr, CMD_PTR, play_suite, 0 /* flags */);
169 PARA_EMERG_LOG("failed to parse config file: %s\n",
170 para_strerror(-ret));
173 loglevel = OPT_UINT32_VAL(LOGLEVEL);
174 num_kmas = OPT_GIVEN(KEY_MAP);
175 for (i = 0; i < num_kmas; i++) {
176 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
177 if (*kma && strchr(kma + 1, ':'))
179 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
184 static char get_playback_state(void)
187 case CRT_NONE: return pt->playing? 'P' : 'U';
188 case CRT_REPOS: return 'R';
189 case CRT_FILE_CHANGE: return 'F';
190 case CRT_TERM_RQ: return 'X';
195 static long unsigned get_play_time(void)
197 char state = get_playback_state();
198 long unsigned result;
200 if (state != 'P' && state != 'U')
202 if (pt->num_chunks == 0 || pt->seconds == 0)
204 /* where the stream started (in seconds) */
205 result = pt->start_chunk * pt->seconds / pt->num_chunks;
206 if (pt->wn.btrn) { /* Add the uptime of the writer node */
207 struct timeval diff = {.tv_sec = 0}, wstime;
208 btr_get_node_start(pt->wn.btrn, &wstime);
209 if (wstime.tv_sec > 0)
210 tv_diff(now, &wstime, &diff);
211 result += diff.tv_sec;
213 result = PARA_MIN(result, pt->seconds);
214 result = PARA_MAX(result, 0UL);
218 static void wipe_receiver_node(void)
220 PARA_NOTICE_LOG("cleaning up receiver node\n");
221 btr_remove_node(&pt->rn.btrn);
222 AFH_RECV->close(&pt->rn);
223 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
224 memset(&pt->rn, 0, sizeof(struct receiver_node));
227 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
228 static int get_playback_error(void)
234 err = task_status(pt->wn.task);
237 if (task_status(pt->fn.task) >= 0)
239 if (task_status(pt->rn.task) >= 0)
241 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
242 || err == -E_WRITE_COMMON_EOF)
247 static int eof_cleanup(void)
249 const struct filter *decoder;
250 const struct writer *w = writer_get(-1); /* default writer */
253 ret = get_playback_error();
256 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
257 task_reap(&pt->wn.task);
259 btr_remove_node(&pt->wn.btrn);
260 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
261 memset(&pt->wn, 0, sizeof(struct writer_node));
263 decoder = filter_get(pt->fn.filter_num);
264 task_reap(&pt->fn.task);
266 decoder->close(&pt->fn);
267 btr_remove_node(&pt->fn.btrn);
269 memset(&pt->fn, 0, sizeof(struct filter_node));
271 task_reap(&pt->rn.task);
272 btr_remove_node(&pt->rn.btrn);
274 * On eof (ret > 0), we do not wipe the receiver node struct until a
275 * new file is loaded because we still need it for jumping around when
279 wipe_receiver_node();
283 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
285 return para_random(100) - 50;
288 static void init_shuffle_map(void)
290 unsigned n, num_inputs = lls_num_inputs(play_lpr);
291 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
292 for (n = 0; n < num_inputs; n++)
294 if (!OPT_GIVEN(RANDOMIZE))
297 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
300 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
302 return btr_new_node(&(struct btr_node_description)
303 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
304 .handler = AFH_RECV->execute));
307 static int open_new_file(void)
310 const char *path = get_playlist_file(pt->next_file);
311 char *tmp = para_strdup(path), *errctx;
312 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
314 PARA_NOTICE_LOG("next file: %s\n", path);
315 wipe_receiver_node();
317 pt->rn.btrn = new_recv_btrn(&pt->rn);
318 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
319 &pt->rn.lpr, &errctx));
322 pt->rn.receiver = AFH_RECV;
323 ret = AFH_RECV->open(&pt->rn);
325 PARA_ERROR_LOG("could not open %s\n", path);
328 pt->audio_format_num = ret;
330 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
332 pt->afhi_txt = make_message("[afhi command failed]\n");
333 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
338 ret = para_atoi32(tmp, &x);
339 pt->seconds = ret < 0? 1 : x;
343 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
348 ret = para_atoi32(tmp, &x);
349 pt->num_chunks = ret < 0? 1 : x;
355 wipe_receiver_node();
359 static int load_file(void)
364 const struct filter *decoder;
365 static struct lls_parse_result *filter_lpr, *writer_lpr;
367 btr_remove_node(&pt->rn.btrn);
368 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
369 ret = open_new_file();
373 pt->rn.btrn = new_recv_btrn(&pt->rn);
374 sprintf(buf, "repos %lu", pt->start_chunk);
375 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
377 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
382 /* set up decoding filter */
383 af = audio_format_name(pt->audio_format_num);
384 tmp = make_message("%sdec", af);
385 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
389 pt->fn.filter_num = ret;
390 pt->fn.lpr = filter_lpr;
391 decoder = filter_get(ret);
392 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
393 EMBRACE(.name = filter_name(pt->fn.filter_num),
394 .parent = pt->rn.btrn, .handler = decoder->execute,
395 .context = &pt->fn));
397 decoder->open(&pt->fn);
398 PARA_INFO_LOG("buffer tree:\n");
399 btr_log_tree(pt->rn.btrn, LL_INFO);
401 /* setup default writer */
402 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
403 pt->wn.lpr = writer_lpr;
404 /* success, register tasks */
405 pt->rn.task = task_register(
406 &(struct task_info) {
407 .name = lls_command_name(AFH_RECV_CMD),
408 .pre_monitor = AFH_RECV->pre_monitor,
409 .post_monitor = AFH_RECV->post_monitor,
412 sprintf(buf, "%s decoder", af);
413 pt->fn.task = task_register(
414 &(struct task_info) {
416 .pre_monitor = decoder->pre_monitor,
417 .post_monitor = decoder->post_monitor,
420 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
423 wipe_receiver_node();
427 static int next_valid_file(void)
429 int i, j = pt->current_file;
430 unsigned num_inputs = lls_num_inputs(play_lpr);
432 if (j == num_inputs - 1) {
433 switch (OPT_UINT32_VAL(END_OF_PLAYLIST)) {
434 case EOP_LOOP: break;
438 case EOP_QUIT: return -E_EOP;
441 for (i = 0; i < num_inputs; i++) {
442 j = (j + 1) % num_inputs;
446 return -E_NO_VALID_FILES;
449 static int load_next_file(void)
454 if (pt->rq == CRT_NONE) {
456 ret = next_valid_file();
460 } else if (pt->rq == CRT_REPOS)
461 pt->next_file = pt->current_file;
464 PARA_ERROR_LOG("%s: marking file as invalid\n",
465 para_strerror(-ret));
466 pt->invalid[pt->next_file] = true;
470 pt->current_file = pt->next_file;
475 static void kill_stream(void)
478 task_notify(pt->wn.task, E_EOF);
483 /* only called from com_prev(), nec. only if we have readline */
484 static int previous_valid_file(void)
486 int i, j = pt->current_file;
487 unsigned num_inputs = lls_num_inputs(play_lpr);
489 for (i = 0; i < num_inputs; i++) {
496 return -E_NO_VALID_FILES;
499 #include "interactive.h"
502 * Define the default (internal) key mappings and helper functions to get the
503 * key sequence or the command from a key id, which is what we obtain from
504 * i9e/readline when the key is pressed.
506 * In some of these helper functions we could return pointers to the constant
507 * arrays defined below. However, for others we can not, so let's better be
508 * consistent and allocate all returned strings on the heap.
511 #define INTERNAL_KEYMAP_ENTRIES \
512 KEYMAP_ENTRY("^", "jmp 0"), \
513 KEYMAP_ENTRY("1", "jmp 10"), \
514 KEYMAP_ENTRY("2", "jmp 21"), \
515 KEYMAP_ENTRY("3", "jmp 32"), \
516 KEYMAP_ENTRY("4", "jmp 43"), \
517 KEYMAP_ENTRY("5", "jmp 54"), \
518 KEYMAP_ENTRY("6", "jmp 65"), \
519 KEYMAP_ENTRY("7", "jmp 76"), \
520 KEYMAP_ENTRY("8", "jmp 87"), \
521 KEYMAP_ENTRY("9", "jmp 98"), \
522 KEYMAP_ENTRY("+", "next"), \
523 KEYMAP_ENTRY("-", "prev"), \
524 KEYMAP_ENTRY(":", "bg"), \
525 KEYMAP_ENTRY("i", "info"), \
526 KEYMAP_ENTRY("l", "ls"), \
527 KEYMAP_ENTRY("s", "play"), \
528 KEYMAP_ENTRY("p", "pause"), \
529 KEYMAP_ENTRY("q", "quit"), \
530 KEYMAP_ENTRY("?", "help"), \
531 KEYMAP_ENTRY("\033[D", "ff -10"), \
532 KEYMAP_ENTRY("\033[C", "ff 10"), \
533 KEYMAP_ENTRY("\033[A", "ff 60"), \
534 KEYMAP_ENTRY("\033[B", "ff -60"), \
536 #define KEYMAP_ENTRY(a, b) a
537 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
539 #define KEYMAP_ENTRY(a, b) b
540 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
542 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
543 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
544 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
546 static inline bool is_internal_key(int key)
548 return key < NUM_INTERNALLY_MAPPED_KEYS;
551 /* for internal keys, the key id is just the array index. */
552 static inline int get_internal_key_map_idx(int key)
554 assert(is_internal_key(key));
559 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
560 * difference is the index to the array of user defined key maps.
562 static inline int get_user_key_map_idx(int key)
564 assert(!is_internal_key(key));
565 return key - NUM_INTERNALLY_MAPPED_KEYS;
568 static inline int get_key_map_idx(int key)
570 return is_internal_key(key)?
571 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
574 static inline const char *get_user_key_map_arg(int key)
576 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
579 static inline char *get_internal_key_map_seq(int key)
581 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
584 static char *get_user_key_map_seq(int key)
586 const char *kma = get_user_key_map_arg(key);
587 const char *p = strchr(kma + 1, ':');
594 result = para_malloc(len + 1);
595 memcpy(result, kma, len);
600 static char *get_key_map_seq(int key)
602 return is_internal_key(key)?
603 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
606 static char *get_key_map_seq_safe(int key)
608 const char hex[] = "0123456789abcdef";
609 char *seq = get_key_map_seq(key), *sseq;
610 size_t n, len = strlen(seq);
612 if (len == 1 && isprint(*seq))
614 sseq = para_malloc(2 + 2 * len + 1);
617 for (n = 0; n < len; n++) {
618 uint8_t val = (seq[n] & 0xf0) >> 4;
619 sseq[2 + 2 * n] = hex[val];
621 sseq[2 + 2 * n + 1] = hex[val];
624 sseq[2 + 2 * n] = '\0';
628 static inline char *get_internal_key_map_cmd(int key)
630 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
633 static char *get_user_key_map_cmd(int key)
635 const char *kma = get_user_key_map_arg(key);
636 const char *p = strchr(kma + 1, ':');
640 return para_strdup(p + 1);
643 static char *get_key_map_cmd(int key)
645 return is_internal_key(key)?
646 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
649 static char **get_mapped_keyseqs(void)
654 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
655 FOR_EACH_MAPPED_KEY(i) {
656 char *seq = get_key_map_seq(i);
663 static struct i9e_completer pp_completers[];
665 I9E_DUMMY_COMPLETER(jmp);
666 I9E_DUMMY_COMPLETER(next);
667 I9E_DUMMY_COMPLETER(prev);
668 I9E_DUMMY_COMPLETER(fg);
669 I9E_DUMMY_COMPLETER(bg);
670 I9E_DUMMY_COMPLETER(ls);
671 I9E_DUMMY_COMPLETER(info);
672 I9E_DUMMY_COMPLETER(play);
673 I9E_DUMMY_COMPLETER(pause);
674 I9E_DUMMY_COMPLETER(tasks);
675 I9E_DUMMY_COMPLETER(quit);
676 I9E_DUMMY_COMPLETER(ff);
678 static void help_completer(struct i9e_completion_info *ci,
679 struct i9e_completion_result *cr)
681 char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
683 if (ci->word[0] == '-') {
684 i9e_complete_option(opts, ci, cr);
687 cr->matches = i9e_complete_commands(ci->word, pp_completers);
690 static struct i9e_completer pp_completers[] = {
691 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
692 .completer = _name ## _completer}
693 LSG_PLAY_CMD_SUBCOMMANDS
694 #undef LSG_PLAY_CMD_CMD
698 static void attach_stdout(const char *name)
702 pt->btrn = btr_new_node(&(struct btr_node_description)
703 EMBRACE(.name = name));
704 i9e_attach_to_stdout(pt->btrn);
707 static void detach_stdout(void)
709 btr_remove_node(&pt->btrn);
712 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
713 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
714 .handler = com_ ## _cmd \
717 static int com_quit(__a_unused struct lls_parse_result *lpr)
719 pt->rq = CRT_TERM_RQ;
722 EXPORT_PLAY_CMD_HANDLER(quit);
724 static int com_help(struct lls_parse_result *lpr)
730 const struct lls_opt_result *r =
731 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
732 bool long_help = lls_opt_given(r);
734 if (!pt->background) {
735 FOR_EACH_MAPPED_KEY(i) {
736 bool internal = is_internal_key(i);
737 int idx = get_key_map_idx(i);
738 char *seq = get_key_map_seq_safe(i);
739 char *kmc = get_key_map_cmd(i);
740 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
741 internal? "internal" : "user-defined",
743 btr_add_output(buf, sz, pt->btrn);
749 lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
750 btr_add_output(buf, n, pt->btrn);
753 EXPORT_PLAY_CMD_HANDLER(help);
755 static int com_info(__a_unused struct lls_parse_result *lpr)
759 static char dflt[] = "[no information available]";
761 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
762 pt->current_file, get_playlist_file(pt->current_file));
763 btr_add_output(buf, sz, pt->btrn);
764 buf = pt->afhi_txt? pt->afhi_txt : dflt;
765 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
768 EXPORT_PLAY_CMD_HANDLER(info);
770 static void list_file(int num)
775 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
776 "*" : " ", num, get_playlist_file(num));
777 btr_add_output(buf, sz, pt->btrn);
780 static int com_tasks(__a_unused struct lls_parse_result *lpr)
786 buf = get_task_list(&sched);
787 btr_add_output(buf, strlen(buf), pt->btrn);
788 state = get_playback_state();
789 sz = xasprintf(&buf, "state: %c\n", state);
790 btr_add_output(buf, sz, pt->btrn);
793 EXPORT_PLAY_CMD_HANDLER(tasks);
795 static int com_ls(__a_unused struct lls_parse_result *lpr)
798 unsigned num_inputs = lls_num_inputs(play_lpr);
800 for (i = 0; i < num_inputs; i++)
804 EXPORT_PLAY_CMD_HANDLER(ls);
806 static int com_play(struct lls_parse_result *lpr)
812 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
815 PARA_ERROR_LOG("%s\n", errctx);
819 state = get_playback_state();
820 if (lls_num_inputs(lpr) == 0) {
823 pt->next_file = pt->current_file;
828 ret = para_atoi32(lls_input(0, lpr), &x);
831 if (x < 0 || x >= lls_num_inputs(play_lpr))
832 return -ERRNO_TO_PARA_ERROR(EINVAL);
835 pt->rq = CRT_FILE_CHANGE;
838 EXPORT_PLAY_CMD_HANDLER(play);
840 static int com_pause(__a_unused struct lls_parse_result *lpr)
843 long unsigned seconds, ss;
845 state = get_playback_state();
849 seconds = get_play_time();
853 ss = seconds * pt->num_chunks / pt->seconds + 1;
854 ss = PARA_MAX(ss, 0UL);
855 ss = PARA_MIN(ss, pt->num_chunks);
856 pt->start_chunk = ss;
861 EXPORT_PLAY_CMD_HANDLER(pause);
863 static int com_prev(__a_unused struct lls_parse_result *lpr)
867 ret = previous_valid_file();
872 pt->rq = CRT_FILE_CHANGE;
876 EXPORT_PLAY_CMD_HANDLER(prev);
878 static int com_next(__a_unused struct lls_parse_result *lpr)
882 ret = next_valid_file();
887 pt->rq = CRT_FILE_CHANGE;
891 EXPORT_PLAY_CMD_HANDLER(next);
893 static int com_fg(__a_unused struct lls_parse_result *lpr)
895 pt->background = false;
898 EXPORT_PLAY_CMD_HANDLER(fg);
900 static int com_bg(__a_unused struct lls_parse_result *lpr)
902 pt->background = true;
905 EXPORT_PLAY_CMD_HANDLER(bg);
907 static int com_jmp(struct lls_parse_result *lpr)
913 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
916 PARA_ERROR_LOG("%s\n", errctx);
920 ret = para_atoi32(lls_input(0, lpr), &percent);
923 if (percent < 0 || percent > 100)
924 return -ERRNO_TO_PARA_ERROR(EINVAL);
926 return com_next(NULL);
927 if (pt->playing && !pt->fn.btrn)
929 pt->start_chunk = percent * pt->num_chunks / 100;
936 EXPORT_PLAY_CMD_HANDLER(jmp);
938 static int com_ff(struct lls_parse_result *lpr)
944 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
947 PARA_ERROR_LOG("%s\n", errctx);
951 ret = para_atoi32(lls_input(0, lpr), &seconds);
954 if (pt->playing && !pt->fn.btrn)
956 seconds += get_play_time();
957 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
958 seconds = PARA_MAX(seconds, 0);
959 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
960 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
961 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
968 EXPORT_PLAY_CMD_HANDLER(ff);
970 static int run_command(char *line)
975 const struct play_command_info *pci;
976 struct lls_parse_result *lpr;
977 const struct lls_command *cmd;
979 attach_stdout(__FUNCTION__);
980 ret = create_argv(line, " ", &argv);
986 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
989 cmd = lls_cmd(ret, play_cmd_suite);
990 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
993 pci = lls_user_data(cmd);
994 ret = pci->handler(lpr);
995 lls_free_parse_result(lpr, cmd);
998 PARA_ERROR_LOG("%s\n", errctx);
1004 static int play_i9e_line_handler(char *line)
1006 return run_command(line);
1009 static int play_i9e_key_handler(int key)
1011 int idx = get_key_map_idx(key);
1012 char *seq = get_key_map_seq(key);
1013 char *cmd = get_key_map_cmd(key);
1014 bool internal = is_internal_key(key);
1016 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1017 key, internal? "internal" : "user-defined",
1022 pt->next_update = *now;
1026 static struct i9e_client_info ici = {
1028 .prompt = "para_play> ",
1029 .line_handler = play_i9e_line_handler,
1030 .key_handler = play_i9e_key_handler,
1031 .completers = pp_completers,
1034 static void sigint_handler(int sig)
1036 pt->background = true;
1037 i9e_signal_dispatch(sig);
1041 * We start with para_log() set to the standard log function which writes to
1042 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1045 static void session_open(void)
1049 struct sigaction act;
1051 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1052 if (OPT_GIVEN(HISTORY_FILE))
1053 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1055 char *home = para_homedir();
1056 char *dot_para = make_message("%s/.paraslash", home);
1059 ret = para_mkdir(dot_para, 0777);
1060 /* warn, but otherwise ignore mkdir error */
1061 if (ret < 0 && ret != -ERRNO_TO_PARA_ERROR(EEXIST))
1062 PARA_WARNING_LOG("Can not create %s: %s\n", dot_para,
1063 para_strerror(-ret));
1064 history_file = make_message("%s/play.history", dot_para);
1067 ici.history_file = history_file;
1068 ici.loglevel = loglevel;
1070 act.sa_handler = sigint_handler;
1071 sigemptyset(&act.sa_mask);
1073 sigaction(SIGINT, &act, NULL);
1074 act.sa_handler = i9e_signal_dispatch;
1075 sigemptyset(&act.sa_mask);
1077 sigaction(SIGWINCH, &act, NULL);
1078 sched.poll_function = i9e_poll;
1080 ici.bound_keyseqs = get_mapped_keyseqs();
1081 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1082 EMBRACE(.name = __FUNCTION__));
1083 ret = i9e_open(&ici, &sched);
1092 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1096 static void session_update_time_string(char *str, unsigned len)
1101 if (btr_get_output_queue_size(pt->btrn) > 0)
1103 if (btr_get_input_queue_size(pt->btrn) > 0)
1106 i9e_print_status_bar(str, len);
1110 * If we are about to die we must call i9e_close() to reset the terminal.
1111 * However, i9e_close() must be called in *this* context, i.e. from
1112 * play_task.post_monitor() rather than from i9e_post_monitor(), because
1113 * otherwise i9e would access freed memory upon return. So the play task must
1114 * stay alive until the i9e task terminates.
1116 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1117 * and reschedule. In the next iteration, i9e->post_monitor returns an error and
1118 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1119 * are allowed to call i9e_close() and terminate as well.
1121 static int session_post_monitor(__a_unused struct sched *s)
1128 attach_stdout(__FUNCTION__);
1129 ret = i9e_get_error();
1133 para_log = stderr_log;
1134 free(ici.history_file);
1137 if (get_playback_state() == 'X')
1138 i9e_signal_dispatch(SIGTERM);
1142 #else /* HAVE_READLINE */
1144 static int session_post_monitor(struct sched *s)
1148 if (!sched_read_ok(STDIN_FILENO, s))
1150 if (read(STDIN_FILENO, &c, 1))
1156 static void session_open(void)
1160 static void session_update_time_string(char *str, __a_unused unsigned len)
1162 printf("\r%s ", str);
1165 #endif /* HAVE_READLINE */
1167 static void play_pre_monitor(struct sched *s, __a_unused void *context)
1171 sched_monitor_readfd(STDIN_FILENO, s);
1172 state = get_playback_state();
1173 if (state == 'R' || state == 'F' || state == 'X')
1174 return sched_min_delay(s);
1175 sched_request_barrier_or_min_delay(&pt->next_update, s);
1178 static unsigned get_time_string(char **result)
1180 int seconds, length;
1181 char state = get_playback_state();
1183 /* do not return anything if things are about to change */
1184 if (state != 'P' && state != 'U') {
1188 length = pt->seconds;
1190 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1191 seconds = get_play_time();
1192 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1196 (length - seconds) / 60,
1197 (length - seconds) % 60,
1198 length? (seconds * 100 + length / 2) / length : 0,
1201 get_playlist_file(pt->current_file)
1205 static int play_post_monitor(struct sched *s, __a_unused void *context)
1209 ret = eof_cleanup();
1211 pt->rq = CRT_TERM_RQ;
1214 ret = session_post_monitor(s);
1217 if (!pt->wn.btrn && !pt->fn.btrn) {
1218 char state = get_playback_state();
1219 if (state == 'P' || state == 'R' || state == 'F') {
1220 PARA_NOTICE_LOG("state: %c\n", state);
1221 ret = load_next_file();
1223 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1224 pt->rq = CRT_TERM_RQ;
1228 pt->next_update = *now;
1231 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1233 unsigned len = get_time_string(&str);
1234 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1236 session_update_time_string(str, len);
1238 tv_add(now, &delay, &pt->next_update);
1246 * The main function of para_play.
1248 * \param argc Standard.
1249 * \param argv Standard.
1251 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1253 int main(int argc, char *argv[])
1256 unsigned num_inputs;
1258 sched.default_timeout = 5000;
1259 parse_config_or_die(argc, argv);
1261 num_inputs = lls_num_inputs(play_lpr);
1263 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1264 pt->rq = CRT_FILE_CHANGE;
1266 pt->task = task_register(&(struct task_info){
1268 .pre_monitor = play_pre_monitor,
1269 .post_monitor = play_post_monitor,
1272 ret = schedule(&sched);
1273 sched_shutdown(&sched);
1275 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1276 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;