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"
16 #include "buffer_tree.h"
27 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
28 * para_play creates two further tasks: The play task and the i9e task. It is
29 * important whether a function can be called in the context of para_play or
30 * i9e or both. As a rule, all command handlers are called only in i9e context via
31 * the line handler (input mode) or the key handler (command mode) below.
33 * Playlist handling is done exclusively in play context.
36 /** Array of error strings. */
39 static struct lls_parse_result *play_lpr;
41 #define CMD_PTR (lls_cmd(0, play_suite))
42 #define OPT_RESULT(_name) \
43 (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
44 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
45 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
46 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
49 * Describes a request to change the state of para_play.
51 * There is only one variable of this type: \a rq of the global play task
52 * structure. Command handlers only set this variable and the post_select()
53 * function of the play task investigates its value during each iteration of
54 * the scheduler run and performs the actual work.
56 enum state_change_request_type {
57 /** Everybody is happy. */
59 /** Stream must be repositioned (com_jmp(), com_ff()). */
61 /** New file should be loaded (com_next()). */
63 /** Someone wants us for dead (com_quit()). */
69 /* A bit array of invalid files (those will be skipped). */
71 /* The file which is currently open. */
72 unsigned current_file;
73 /* When to update the status again. */
74 struct timeval next_update;
76 /* Root of the buffer tree for command and status output. */
77 struct btr_node *btrn;
79 /* The decoding machinery. */
80 struct receiver_node rn;
81 struct filter_node fn;
82 struct writer_node wn;
84 /* See comment to enum \ref state_change_request_type above. */
85 enum state_change_request_type rq;
86 /* only relevant if rq == CRT_FILE_CHANGE */
89 bg: read lines at prompt, fg: display status and wait
94 /* We have the *intention* to play. Set by com_play(). */
97 /* as returned by afh_recv->open() */
100 /* retrieved via the btr exec mechanism */
101 long unsigned start_chunk;
102 long unsigned seconds;
103 long unsigned num_chunks;
107 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
108 struct play_command_info {
109 play_cmd_handler_t handler;
111 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
112 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
113 .handler = com_ ## _cmd \
116 static int loglevel = LL_WARNING;
118 /** The log function which writes log messages to stderr. */
119 INIT_STDERR_LOGGING(loglevel);
121 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
123 static struct sched sched = {.max_fileno = 0};
124 static struct play_task play_task, *pt = &play_task;
126 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
127 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
129 static unsigned *shuffle_map;
131 static const char *get_playlist_file(unsigned idx)
133 return lls_input(shuffle_map[idx], play_lpr);
136 static void handle_help_flags(void)
140 if (OPT_GIVEN(DETAILED_HELP))
141 help = lls_long_help(CMD_PTR);
142 else if (OPT_GIVEN(HELP))
143 help = lls_short_help(CMD_PTR);
146 printf("%s\n", help);
151 static void parse_config_or_die(int argc, char *argv[])
153 const struct lls_command *cmd = CMD_PTR;
155 char *cf, *errctx, **cf_argv;
156 struct lls_parse_result *cf_lpr, *merged_lpr;
161 ret = lls(lls_parse(argc, argv, cmd, &play_lpr, &errctx));
164 loglevel = OPT_UINT32_VAL(LOGLEVEL);
165 version_handle_flag("play", OPT_GIVEN(VERSION));
167 if (OPT_GIVEN(CONFIG_FILE))
168 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
170 char *home = para_homedir();
171 cf = make_message("%s/.paraslash/play.conf", home);
174 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
176 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
178 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
183 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
184 para_munmap(map, sz);
188 ret = lls(lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx));
189 lls_free_argv(cf_argv);
192 ret = lls(lls_merge(play_lpr, cf_lpr, cmd, &merged_lpr, &errctx));
193 lls_free_parse_result(cf_lpr, cmd);
196 lls_free_parse_result(play_lpr, cmd);
197 play_lpr = merged_lpr;
198 loglevel = OPT_UINT32_VAL(LOGLEVEL);
200 ret = lls(lls_check_arg_count(play_lpr, 1, INT_MAX, &errctx));
203 num_kmas = OPT_GIVEN(KEY_MAP);
204 for (i = 0; i < num_kmas; i++) {
205 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
206 if (*kma && strchr(kma + 1, ':'))
208 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
216 lls_free_parse_result(play_lpr, cmd);
219 PARA_EMERG_LOG("%s\n", errctx);
221 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
225 static char get_playback_state(void)
228 case CRT_NONE: return pt->playing? 'P' : 'U';
229 case CRT_REPOS: return 'R';
230 case CRT_FILE_CHANGE: return 'F';
231 case CRT_TERM_RQ: return 'X';
236 static long unsigned get_play_time(void)
238 char state = get_playback_state();
239 long unsigned result;
241 if (state != 'P' && state != 'U')
243 if (pt->num_chunks == 0 || pt->seconds == 0)
245 /* where the stream started (in seconds) */
246 result = pt->start_chunk * pt->seconds / pt->num_chunks;
247 if (pt->wn.btrn) { /* Add the uptime of the writer node */
248 struct timeval diff = {.tv_sec = 0}, wstime;
249 btr_get_node_start(pt->wn.btrn, &wstime);
250 if (wstime.tv_sec > 0)
251 tv_diff(now, &wstime, &diff);
252 result += diff.tv_sec;
254 result = PARA_MIN(result, pt->seconds);
255 result = PARA_MAX(result, 0UL);
260 static void wipe_receiver_node(void)
262 PARA_NOTICE_LOG("cleaning up receiver node\n");
263 btr_remove_node(&pt->rn.btrn);
264 AFH_RECV->close(&pt->rn);
265 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
266 memset(&pt->rn, 0, sizeof(struct receiver_node));
269 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
270 static int get_playback_error(void)
276 err = task_status(pt->wn.task);
279 if (task_status(pt->fn.task) >= 0)
281 if (task_status(pt->rn.task) >= 0)
283 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
284 || err == -E_WRITE_COMMON_EOF)
289 static int eof_cleanup(void)
291 const struct filter *decoder;
292 const struct writer *w = writer_get(-1); /* default writer */
295 ret = get_playback_error();
298 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
299 task_reap(&pt->wn.task);
301 btr_remove_node(&pt->wn.btrn);
302 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
303 memset(&pt->wn, 0, sizeof(struct writer_node));
305 decoder = filter_get(pt->fn.filter_num);
306 task_reap(&pt->fn.task);
308 decoder->close(&pt->fn);
309 btr_remove_node(&pt->fn.btrn);
311 memset(&pt->fn, 0, sizeof(struct filter_node));
313 task_reap(&pt->rn.task);
314 btr_remove_node(&pt->rn.btrn);
316 * On eof (ret > 0), we do not wipe the receiver node struct until a
317 * new file is loaded because we still need it for jumping around when
321 wipe_receiver_node();
325 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
327 return para_random(100) - 50;
330 static void init_shuffle_map(void)
332 unsigned n, num_inputs = lls_num_inputs(play_lpr);
333 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
334 for (n = 0; n < num_inputs; n++)
336 if (!OPT_GIVEN(RANDOMIZE))
339 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
342 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
344 return btr_new_node(&(struct btr_node_description)
345 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
346 .handler = AFH_RECV->execute));
349 static int open_new_file(void)
352 const char *path = get_playlist_file(pt->next_file);
353 char *tmp = para_strdup(path), *errctx;
354 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
356 PARA_NOTICE_LOG("next file: %s\n", path);
357 wipe_receiver_node();
359 pt->rn.btrn = new_recv_btrn(&pt->rn);
360 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
361 &pt->rn.lpr, &errctx));
364 pt->rn.receiver = AFH_RECV;
365 ret = AFH_RECV->open(&pt->rn);
367 PARA_ERROR_LOG("could not open %s\n", path);
370 pt->audio_format_num = ret;
372 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
374 pt->afhi_txt = make_message("[afhi command failed]\n");
375 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
380 ret = para_atoi32(tmp, &x);
381 pt->seconds = ret < 0? 1 : x;
385 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
390 ret = para_atoi32(tmp, &x);
391 pt->num_chunks = ret < 0? 1 : x;
397 wipe_receiver_node();
401 static int load_file(void)
406 const struct filter *decoder;
407 static struct lls_parse_result *filter_lpr, *writer_lpr;
409 btr_remove_node(&pt->rn.btrn);
410 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
411 ret = open_new_file();
415 pt->rn.btrn = new_recv_btrn(&pt->rn);
416 sprintf(buf, "repos %lu", pt->start_chunk);
417 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
419 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
424 /* set up decoding filter */
425 af = audio_format_name(pt->audio_format_num);
426 tmp = make_message("%sdec", af);
427 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
431 pt->fn.filter_num = ret;
432 pt->fn.lpr = filter_lpr;
433 decoder = filter_get(ret);
434 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
435 EMBRACE(.name = filter_name(pt->fn.filter_num),
436 .parent = pt->rn.btrn, .handler = decoder->execute,
437 .context = &pt->fn));
439 decoder->open(&pt->fn);
440 PARA_INFO_LOG("buffer tree:\n");
441 btr_log_tree(pt->rn.btrn, LL_INFO);
443 /* setup default writer */
444 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
445 pt->wn.lpr = writer_lpr;
446 /* success, register tasks */
447 pt->rn.task = task_register(
448 &(struct task_info) {
449 .name = lls_command_name(AFH_RECV_CMD),
450 .pre_select = AFH_RECV->pre_select,
451 .post_select = AFH_RECV->post_select,
454 sprintf(buf, "%s decoder", af);
455 pt->fn.task = task_register(
456 &(struct task_info) {
458 .pre_select = decoder->pre_select,
459 .post_select = decoder->post_select,
462 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
465 wipe_receiver_node();
469 static int next_valid_file(void)
471 int i, j = pt->current_file;
472 unsigned num_inputs = lls_num_inputs(play_lpr);
474 for (i = 0; i < num_inputs; i++) {
475 j = (j + 1) % num_inputs;
479 return -E_NO_VALID_FILES;
482 static int load_next_file(void)
487 if (pt->rq == CRT_NONE) {
489 ret = next_valid_file();
493 } else if (pt->rq == CRT_REPOS)
494 pt->next_file = pt->current_file;
497 PARA_ERROR_LOG("%s: marking file as invalid\n",
498 para_strerror(-ret));
499 pt->invalid[pt->next_file] = true;
503 pt->current_file = pt->next_file;
508 static void kill_stream(void)
511 task_notify(pt->wn.task, E_EOF);
516 /* only called from com_prev(), nec. only if we have readline */
517 static int previous_valid_file(void)
519 int i, j = pt->current_file;
520 unsigned num_inputs = lls_num_inputs(play_lpr);
522 for (i = 0; i < num_inputs; i++) {
529 return -E_NO_VALID_FILES;
532 #include "interactive.h"
535 * Define the default (internal) key mappings and helper functions to get the
536 * key sequence or the command from a key id, which is what we obtain from
537 * i9e/readline when the key is pressed.
539 * In some of these helper functions we could return pointers to the constant
540 * arrays defined below. However, for others we can not, so let's better be
541 * consistent and allocate all returned strings on the heap.
544 #define INTERNAL_KEYMAP_ENTRIES \
545 KEYMAP_ENTRY("^", "jmp 0"), \
546 KEYMAP_ENTRY("1", "jmp 10"), \
547 KEYMAP_ENTRY("2", "jmp 21"), \
548 KEYMAP_ENTRY("3", "jmp 32"), \
549 KEYMAP_ENTRY("4", "jmp 43"), \
550 KEYMAP_ENTRY("5", "jmp 54"), \
551 KEYMAP_ENTRY("6", "jmp 65"), \
552 KEYMAP_ENTRY("7", "jmp 76"), \
553 KEYMAP_ENTRY("8", "jmp 87"), \
554 KEYMAP_ENTRY("9", "jmp 98"), \
555 KEYMAP_ENTRY("+", "next"), \
556 KEYMAP_ENTRY("-", "prev"), \
557 KEYMAP_ENTRY(":", "bg"), \
558 KEYMAP_ENTRY("i", "info"), \
559 KEYMAP_ENTRY("l", "ls"), \
560 KEYMAP_ENTRY("s", "play"), \
561 KEYMAP_ENTRY("p", "pause"), \
562 KEYMAP_ENTRY("q", "quit"), \
563 KEYMAP_ENTRY("?", "help"), \
564 KEYMAP_ENTRY("\033[D", "ff -10"), \
565 KEYMAP_ENTRY("\033[C", "ff 10"), \
566 KEYMAP_ENTRY("\033[A", "ff 60"), \
567 KEYMAP_ENTRY("\033[B", "ff -60"), \
569 #define KEYMAP_ENTRY(a, b) a
570 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
572 #define KEYMAP_ENTRY(a, b) b
573 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
575 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
576 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
577 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
579 static inline bool is_internal_key(int key)
581 return key < NUM_INTERNALLY_MAPPED_KEYS;
584 /* for internal keys, the key id is just the array index. */
585 static inline int get_internal_key_map_idx(int key)
587 assert(is_internal_key(key));
592 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
593 * difference is the index to the array of user defined key maps.
595 static inline int get_user_key_map_idx(int key)
597 assert(!is_internal_key(key));
598 return key - NUM_INTERNALLY_MAPPED_KEYS;
601 static inline int get_key_map_idx(int key)
603 return is_internal_key(key)?
604 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
607 static inline const char *get_user_key_map_arg(int key)
609 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
612 static inline char *get_internal_key_map_seq(int key)
614 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
617 static char *get_user_key_map_seq(int key)
619 const char *kma = get_user_key_map_arg(key);
620 const char *p = strchr(kma + 1, ':');
627 result = para_malloc(len + 1);
628 memcpy(result, kma, len);
633 static char *get_key_map_seq(int key)
635 return is_internal_key(key)?
636 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
639 static char *get_key_map_seq_safe(int key)
641 const char hex[] = "0123456789abcdef";
642 char *seq = get_key_map_seq(key), *sseq;
643 size_t n, len = strlen(seq);
645 if (len == 1 && isprint(*seq))
647 sseq = para_malloc(2 + 2 * len + 1);
650 for (n = 0; n < len; n++) {
651 uint8_t val = (seq[n] & 0xf0) >> 4;
652 sseq[2 + 2 * n] = hex[val];
654 sseq[2 + 2 * n + 1] = hex[val];
657 sseq[2 + 2 * n] = '\0';
661 static inline char *get_internal_key_map_cmd(int key)
663 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
666 static char *get_user_key_map_cmd(int key)
668 const char *kma = get_user_key_map_arg(key);
669 const char *p = strchr(kma + 1, ':');
673 return para_strdup(p + 1);
676 static char *get_key_map_cmd(int key)
678 return is_internal_key(key)?
679 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
682 static char **get_mapped_keyseqs(void)
687 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
688 FOR_EACH_MAPPED_KEY(i) {
689 char *seq = get_key_map_seq(i);
696 static struct i9e_completer pp_completers[];
698 I9E_DUMMY_COMPLETER(jmp);
699 I9E_DUMMY_COMPLETER(next);
700 I9E_DUMMY_COMPLETER(prev);
701 I9E_DUMMY_COMPLETER(fg);
702 I9E_DUMMY_COMPLETER(bg);
703 I9E_DUMMY_COMPLETER(ls);
704 I9E_DUMMY_COMPLETER(info);
705 I9E_DUMMY_COMPLETER(play);
706 I9E_DUMMY_COMPLETER(pause);
707 I9E_DUMMY_COMPLETER(tasks);
708 I9E_DUMMY_COMPLETER(quit);
709 I9E_DUMMY_COMPLETER(ff);
711 static void help_completer(struct i9e_completion_info *ci,
712 struct i9e_completion_result *result)
714 result->matches = i9e_complete_commands(ci->word, pp_completers);
717 static struct i9e_completer pp_completers[] = {
718 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
719 .completer = _name ## _completer}
720 LSG_PLAY_CMD_SUBCOMMANDS
721 #undef LSG_PLAY_CMD_CMD
725 static void attach_stdout(const char *name)
729 pt->btrn = btr_new_node(&(struct btr_node_description)
730 EMBRACE(.name = name));
731 i9e_attach_to_stdout(pt->btrn);
734 static void detach_stdout(void)
736 btr_remove_node(&pt->btrn);
739 static int com_quit(__a_unused struct lls_parse_result *lpr)
741 pt->rq = CRT_TERM_RQ;
744 EXPORT_PLAY_CMD_HANDLER(quit);
746 static int com_help(struct lls_parse_result *lpr)
751 const struct lls_command *cmd;
753 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
756 PARA_ERROR_LOG("%s\n", errctx);
760 if (lls_num_inputs(lpr) == 0) {
761 if (pt->background) {
762 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
763 sz = xasprintf(&buf, "%s\t%s\n",
764 lls_command_name(cmd), lls_purpose(cmd));
765 btr_add_output(buf, sz, pt->btrn);
769 FOR_EACH_MAPPED_KEY(i) {
770 bool internal = is_internal_key(i);
771 int idx = get_key_map_idx(i);
772 char *seq = get_key_map_seq_safe(i);
773 char *kmc = get_key_map_cmd(i);
774 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
775 internal? "internal" : "user-defined",
777 btr_add_output(buf, sz, pt->btrn);
783 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
787 PARA_ERROR_LOG("%s\n", errctx);
791 cmd = lls_cmd(ret, play_cmd_suite);
792 buf = lls_long_help(cmd);
794 btr_add_output(buf, strlen(buf), pt->btrn);
797 EXPORT_PLAY_CMD_HANDLER(help);
799 static int com_info(__a_unused struct lls_parse_result *lpr)
803 static char dflt[] = "[no information available]";
805 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
806 pt->current_file, get_playlist_file(pt->current_file));
807 btr_add_output(buf, sz, pt->btrn);
808 buf = pt->afhi_txt? pt->afhi_txt : dflt;
809 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
812 EXPORT_PLAY_CMD_HANDLER(info);
814 static void list_file(int num)
819 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
820 "*" : " ", num, get_playlist_file(num));
821 btr_add_output(buf, sz, pt->btrn);
824 static int com_tasks(__a_unused struct lls_parse_result *lpr)
830 buf = get_task_list(&sched);
831 btr_add_output(buf, strlen(buf), pt->btrn);
832 state = get_playback_state();
833 sz = xasprintf(&buf, "state: %c\n", state);
834 btr_add_output(buf, sz, pt->btrn);
837 EXPORT_PLAY_CMD_HANDLER(tasks);
839 static int com_ls(__a_unused struct lls_parse_result *lpr)
842 unsigned num_inputs = lls_num_inputs(play_lpr);
844 for (i = 0; i < num_inputs; i++)
848 EXPORT_PLAY_CMD_HANDLER(ls);
850 static int com_play(struct lls_parse_result *lpr)
856 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
859 PARA_ERROR_LOG("%s\n", errctx);
863 state = get_playback_state();
864 if (lls_num_inputs(lpr) == 0) {
867 pt->next_file = pt->current_file;
872 ret = para_atoi32(lls_input(0, lpr), &x);
875 if (x < 0 || x >= lls_num_inputs(play_lpr))
876 return -ERRNO_TO_PARA_ERROR(EINVAL);
879 pt->rq = CRT_FILE_CHANGE;
882 EXPORT_PLAY_CMD_HANDLER(play);
884 static int com_pause(__a_unused struct lls_parse_result *lpr)
887 long unsigned seconds, ss;
889 state = get_playback_state();
893 seconds = get_play_time();
897 ss = seconds * pt->num_chunks / pt->seconds + 1;
898 ss = PARA_MAX(ss, 0UL);
899 ss = PARA_MIN(ss, pt->num_chunks);
900 pt->start_chunk = ss;
904 EXPORT_PLAY_CMD_HANDLER(pause);
906 static int com_prev(__a_unused struct lls_parse_result *lpr)
910 ret = previous_valid_file();
915 pt->rq = CRT_FILE_CHANGE;
919 EXPORT_PLAY_CMD_HANDLER(prev);
921 static int com_next(__a_unused struct lls_parse_result *lpr)
925 ret = next_valid_file();
930 pt->rq = CRT_FILE_CHANGE;
934 EXPORT_PLAY_CMD_HANDLER(next);
936 static int com_fg(__a_unused struct lls_parse_result *lpr)
938 pt->background = false;
941 EXPORT_PLAY_CMD_HANDLER(fg);
943 static int com_bg(__a_unused struct lls_parse_result *lpr)
945 pt->background = true;
948 EXPORT_PLAY_CMD_HANDLER(bg);
950 static int com_jmp(struct lls_parse_result *lpr)
956 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
959 PARA_ERROR_LOG("%s\n", errctx);
963 ret = para_atoi32(lls_input(0, lpr), &percent);
966 if (percent < 0 || percent > 100)
967 return -ERRNO_TO_PARA_ERROR(EINVAL);
969 return com_next(NULL);
970 if (pt->playing && !pt->fn.btrn)
972 pt->start_chunk = percent * pt->num_chunks / 100;
979 EXPORT_PLAY_CMD_HANDLER(jmp);
981 static int com_ff(struct lls_parse_result *lpr)
987 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
990 PARA_ERROR_LOG("%s\n", errctx);
994 ret = para_atoi32(lls_input(0, lpr), &seconds);
997 if (pt->playing && !pt->fn.btrn)
999 seconds += get_play_time();
1000 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
1001 seconds = PARA_MAX(seconds, 0);
1002 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
1003 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
1004 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1011 EXPORT_PLAY_CMD_HANDLER(ff);
1013 static int run_command(char *line)
1017 char *errctx = NULL;
1018 const struct play_command_info *pci;
1019 struct lls_parse_result *lpr;
1020 const struct lls_command *cmd;
1022 attach_stdout(__FUNCTION__);
1023 ret = create_argv(line, " ", &argv);
1029 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1032 cmd = lls_cmd(ret, play_cmd_suite);
1033 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1036 pci = lls_user_data(cmd);
1037 ret = pci->handler(lpr);
1038 lls_free_parse_result(lpr, cmd);
1041 PARA_ERROR_LOG("%s\n", errctx);
1047 static int play_i9e_line_handler(char *line)
1049 return run_command(line);
1052 static int play_i9e_key_handler(int key)
1054 int idx = get_key_map_idx(key);
1055 char *seq = get_key_map_seq(key);
1056 char *cmd = get_key_map_cmd(key);
1057 bool internal = is_internal_key(key);
1059 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1060 key, internal? "internal" : "user-defined",
1065 pt->next_update = *now;
1069 static struct i9e_client_info ici = {
1071 .prompt = "para_play> ",
1072 .line_handler = play_i9e_line_handler,
1073 .key_handler = play_i9e_key_handler,
1074 .completers = pp_completers,
1077 static void sigint_handler(int sig)
1079 pt->background = true;
1080 i9e_signal_dispatch(sig);
1084 * We start with para_log() set to the standard log function which writes to
1085 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1088 static void session_open(void)
1092 struct sigaction act;
1094 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1095 if (OPT_GIVEN(HISTORY_FILE))
1096 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1098 char *home = para_homedir();
1099 history_file = make_message("%s/.paraslash/play.history",
1103 ici.history_file = history_file;
1104 ici.loglevel = loglevel;
1106 act.sa_handler = sigint_handler;
1107 sigemptyset(&act.sa_mask);
1109 sigaction(SIGINT, &act, NULL);
1110 act.sa_handler = i9e_signal_dispatch;
1111 sigemptyset(&act.sa_mask);
1113 sigaction(SIGWINCH, &act, NULL);
1114 sched.select_function = i9e_select;
1116 ici.bound_keyseqs = get_mapped_keyseqs();
1117 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1118 EMBRACE(.name = __FUNCTION__));
1119 ret = i9e_open(&ici, &sched);
1128 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1132 static void session_update_time_string(char *str, unsigned len)
1137 if (btr_get_output_queue_size(pt->btrn) > 0)
1139 if (btr_get_input_queue_size(pt->btrn) > 0)
1142 ie9_print_status_bar(str, len);
1146 * If we are about to die we must call i9e_close() to reset the terminal.
1147 * However, i9e_close() must be called in *this* context, i.e. from
1148 * play_task.post_select() rather than from i9e_post_select(), because
1149 * otherwise i9e would access freed memory upon return. So the play task must
1150 * stay alive until the i9e task terminates.
1152 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1153 * and reschedule. In the next iteration, i9e->post_select returns an error and
1154 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1155 * are allowed to call i9e_close() and terminate as well.
1157 static int session_post_select(__a_unused struct sched *s)
1164 attach_stdout(__FUNCTION__);
1165 ret = i9e_get_error();
1169 para_log = stderr_log;
1170 free(ici.history_file);
1173 if (get_playback_state() == 'X')
1174 i9e_signal_dispatch(SIGTERM);
1178 #else /* HAVE_READLINE */
1180 static int session_post_select(struct sched *s)
1184 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1186 if (read(STDIN_FILENO, &c, 1))
1192 static void session_open(void)
1196 static void session_update_time_string(char *str, __a_unused unsigned len)
1198 printf("\r%s ", str);
1201 #endif /* HAVE_READLINE */
1203 static void play_pre_select(struct sched *s, __a_unused void *context)
1207 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1208 state = get_playback_state();
1209 if (state == 'R' || state == 'F' || state == 'X')
1210 return sched_min_delay(s);
1211 sched_request_barrier_or_min_delay(&pt->next_update, s);
1214 static unsigned get_time_string(char **result)
1216 int seconds, length;
1217 char state = get_playback_state();
1219 /* do not return anything if things are about to change */
1220 if (state != 'P' && state != 'U') {
1224 length = pt->seconds;
1226 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1227 seconds = get_play_time();
1228 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1232 (length - seconds) / 60,
1233 (length - seconds) % 60,
1234 length? (seconds * 100 + length / 2) / length : 0,
1237 get_playlist_file(pt->current_file)
1241 static int play_post_select(struct sched *s, __a_unused void *context)
1245 ret = eof_cleanup();
1247 pt->rq = CRT_TERM_RQ;
1250 ret = session_post_select(s);
1253 if (!pt->wn.btrn && !pt->fn.btrn) {
1254 char state = get_playback_state();
1255 if (state == 'P' || state == 'R' || state == 'F') {
1256 PARA_NOTICE_LOG("state: %c\n", state);
1257 ret = load_next_file();
1259 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1260 pt->rq = CRT_TERM_RQ;
1264 pt->next_update = *now;
1267 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1269 unsigned len = get_time_string(&str);
1270 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1272 session_update_time_string(str, len);
1274 tv_add(now, &delay, &pt->next_update);
1282 * The main function of para_play.
1284 * \param argc Standard.
1285 * \param argv Standard.
1287 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1289 int main(int argc, char *argv[])
1292 unsigned num_inputs;
1294 /* needed this early to make help work */
1297 sched.default_timeout.tv_sec = 5;
1298 parse_config_or_die(argc, argv);
1301 num_inputs = lls_num_inputs(play_lpr);
1303 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1304 pt->rq = CRT_FILE_CHANGE;
1305 pt->current_file = num_inputs - 1;
1307 pt->task = task_register(&(struct task_info){
1309 .pre_select = play_pre_select,
1310 .post_select = play_post_select,
1313 ret = schedule(&sched);
1314 sched_shutdown(&sched);
1316 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1317 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;