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_select()
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;
112 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
113 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
114 .handler = com_ ## _cmd \
117 static int loglevel = LL_WARNING;
119 /** The log function which writes log messages to stderr. */
120 INIT_STDERR_LOGGING(loglevel);
122 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
124 static struct sched sched = {.max_fileno = 0};
125 static struct play_task play_task, *pt = &play_task;
127 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
128 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
130 static unsigned *shuffle_map;
132 static const char *get_playlist_file(unsigned idx)
134 return lls_input(shuffle_map[idx], play_lpr);
137 static void handle_help_flags(void)
141 if (OPT_GIVEN(DETAILED_HELP))
142 help = lls_long_help(CMD_PTR);
143 else if (OPT_GIVEN(HELP) || lls_num_inputs(play_lpr) == 0)
144 help = lls_short_help(CMD_PTR);
147 printf("%s\n", help);
152 static void parse_config_or_die(int argc, char *argv[])
158 ret = lls(lls_parse(argc, argv, CMD_PTR, &play_lpr, &errctx));
161 PARA_EMERG_LOG("%s\n", errctx);
163 PARA_EMERG_LOG("failed to parse command line options: %s\n",
164 para_strerror(-ret));
167 loglevel = OPT_UINT32_VAL(LOGLEVEL);
168 version_handle_flag("play", OPT_GIVEN(VERSION));
169 handle_help_flags(); /* also handles the zero-arg case */
170 ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
171 "play.conf", &play_lpr, CMD_PTR, play_suite, 0 /* flags */);
173 PARA_EMERG_LOG("failed to parse config file: %s\n",
174 para_strerror(-ret));
177 loglevel = OPT_UINT32_VAL(LOGLEVEL);
178 num_kmas = OPT_GIVEN(KEY_MAP);
179 for (i = 0; i < num_kmas; i++) {
180 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
181 if (*kma && strchr(kma + 1, ':'))
183 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
188 static char get_playback_state(void)
191 case CRT_NONE: return pt->playing? 'P' : 'U';
192 case CRT_REPOS: return 'R';
193 case CRT_FILE_CHANGE: return 'F';
194 case CRT_TERM_RQ: return 'X';
199 static long unsigned get_play_time(void)
201 char state = get_playback_state();
202 long unsigned result;
204 if (state != 'P' && state != 'U')
206 if (pt->num_chunks == 0 || pt->seconds == 0)
208 /* where the stream started (in seconds) */
209 result = pt->start_chunk * pt->seconds / pt->num_chunks;
210 if (pt->wn.btrn) { /* Add the uptime of the writer node */
211 struct timeval diff = {.tv_sec = 0}, wstime;
212 btr_get_node_start(pt->wn.btrn, &wstime);
213 if (wstime.tv_sec > 0)
214 tv_diff(now, &wstime, &diff);
215 result += diff.tv_sec;
217 result = PARA_MIN(result, pt->seconds);
218 result = PARA_MAX(result, 0UL);
222 static void wipe_receiver_node(void)
224 PARA_NOTICE_LOG("cleaning up receiver node\n");
225 btr_remove_node(&pt->rn.btrn);
226 AFH_RECV->close(&pt->rn);
227 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
228 memset(&pt->rn, 0, sizeof(struct receiver_node));
231 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
232 static int get_playback_error(void)
238 err = task_status(pt->wn.task);
241 if (task_status(pt->fn.task) >= 0)
243 if (task_status(pt->rn.task) >= 0)
245 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
246 || err == -E_WRITE_COMMON_EOF)
251 static int eof_cleanup(void)
253 const struct filter *decoder;
254 const struct writer *w = writer_get(-1); /* default writer */
257 ret = get_playback_error();
260 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
261 task_reap(&pt->wn.task);
263 btr_remove_node(&pt->wn.btrn);
264 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
265 memset(&pt->wn, 0, sizeof(struct writer_node));
267 decoder = filter_get(pt->fn.filter_num);
268 task_reap(&pt->fn.task);
270 decoder->close(&pt->fn);
271 btr_remove_node(&pt->fn.btrn);
273 memset(&pt->fn, 0, sizeof(struct filter_node));
275 task_reap(&pt->rn.task);
276 btr_remove_node(&pt->rn.btrn);
278 * On eof (ret > 0), we do not wipe the receiver node struct until a
279 * new file is loaded because we still need it for jumping around when
283 wipe_receiver_node();
287 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
289 return para_random(100) - 50;
292 static void init_shuffle_map(void)
294 unsigned n, num_inputs = lls_num_inputs(play_lpr);
295 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
296 for (n = 0; n < num_inputs; n++)
298 if (!OPT_GIVEN(RANDOMIZE))
301 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
304 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
306 return btr_new_node(&(struct btr_node_description)
307 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
308 .handler = AFH_RECV->execute));
311 static int open_new_file(void)
314 const char *path = get_playlist_file(pt->next_file);
315 char *tmp = para_strdup(path), *errctx;
316 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
318 PARA_NOTICE_LOG("next file: %s\n", path);
319 wipe_receiver_node();
321 pt->rn.btrn = new_recv_btrn(&pt->rn);
322 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
323 &pt->rn.lpr, &errctx));
326 pt->rn.receiver = AFH_RECV;
327 ret = AFH_RECV->open(&pt->rn);
329 PARA_ERROR_LOG("could not open %s\n", path);
332 pt->audio_format_num = ret;
334 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
336 pt->afhi_txt = make_message("[afhi command failed]\n");
337 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
342 ret = para_atoi32(tmp, &x);
343 pt->seconds = ret < 0? 1 : x;
347 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
352 ret = para_atoi32(tmp, &x);
353 pt->num_chunks = ret < 0? 1 : x;
359 wipe_receiver_node();
363 static int load_file(void)
368 const struct filter *decoder;
369 static struct lls_parse_result *filter_lpr, *writer_lpr;
371 btr_remove_node(&pt->rn.btrn);
372 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
373 ret = open_new_file();
377 pt->rn.btrn = new_recv_btrn(&pt->rn);
378 sprintf(buf, "repos %lu", pt->start_chunk);
379 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
381 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
386 /* set up decoding filter */
387 af = audio_format_name(pt->audio_format_num);
388 tmp = make_message("%sdec", af);
389 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
393 pt->fn.filter_num = ret;
394 pt->fn.lpr = filter_lpr;
395 decoder = filter_get(ret);
396 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
397 EMBRACE(.name = filter_name(pt->fn.filter_num),
398 .parent = pt->rn.btrn, .handler = decoder->execute,
399 .context = &pt->fn));
401 decoder->open(&pt->fn);
402 PARA_INFO_LOG("buffer tree:\n");
403 btr_log_tree(pt->rn.btrn, LL_INFO);
405 /* setup default writer */
406 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
407 pt->wn.lpr = writer_lpr;
408 /* success, register tasks */
409 pt->rn.task = task_register(
410 &(struct task_info) {
411 .name = lls_command_name(AFH_RECV_CMD),
412 .pre_select = AFH_RECV->pre_select,
413 .post_select = AFH_RECV->post_select,
416 sprintf(buf, "%s decoder", af);
417 pt->fn.task = task_register(
418 &(struct task_info) {
420 .pre_select = decoder->pre_select,
421 .post_select = decoder->post_select,
424 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
427 wipe_receiver_node();
431 static int next_valid_file(void)
433 int i, j = pt->current_file;
434 unsigned num_inputs = lls_num_inputs(play_lpr);
436 if (j == num_inputs - 1) {
437 switch (OPT_UINT32_VAL(END_OF_PLAYLIST)) {
438 case EOP_LOOP: break;
442 case EOP_QUIT: return -E_EOP;
445 for (i = 0; i < num_inputs; i++) {
446 j = (j + 1) % num_inputs;
450 return -E_NO_VALID_FILES;
453 static int load_next_file(void)
458 if (pt->rq == CRT_NONE) {
460 ret = next_valid_file();
464 } else if (pt->rq == CRT_REPOS)
465 pt->next_file = pt->current_file;
468 PARA_ERROR_LOG("%s: marking file as invalid\n",
469 para_strerror(-ret));
470 pt->invalid[pt->next_file] = true;
474 pt->current_file = pt->next_file;
479 static void kill_stream(void)
482 task_notify(pt->wn.task, E_EOF);
487 /* only called from com_prev(), nec. only if we have readline */
488 static int previous_valid_file(void)
490 int i, j = pt->current_file;
491 unsigned num_inputs = lls_num_inputs(play_lpr);
493 for (i = 0; i < num_inputs; i++) {
500 return -E_NO_VALID_FILES;
503 #include "interactive.h"
506 * Define the default (internal) key mappings and helper functions to get the
507 * key sequence or the command from a key id, which is what we obtain from
508 * i9e/readline when the key is pressed.
510 * In some of these helper functions we could return pointers to the constant
511 * arrays defined below. However, for others we can not, so let's better be
512 * consistent and allocate all returned strings on the heap.
515 #define INTERNAL_KEYMAP_ENTRIES \
516 KEYMAP_ENTRY("^", "jmp 0"), \
517 KEYMAP_ENTRY("1", "jmp 10"), \
518 KEYMAP_ENTRY("2", "jmp 21"), \
519 KEYMAP_ENTRY("3", "jmp 32"), \
520 KEYMAP_ENTRY("4", "jmp 43"), \
521 KEYMAP_ENTRY("5", "jmp 54"), \
522 KEYMAP_ENTRY("6", "jmp 65"), \
523 KEYMAP_ENTRY("7", "jmp 76"), \
524 KEYMAP_ENTRY("8", "jmp 87"), \
525 KEYMAP_ENTRY("9", "jmp 98"), \
526 KEYMAP_ENTRY("+", "next"), \
527 KEYMAP_ENTRY("-", "prev"), \
528 KEYMAP_ENTRY(":", "bg"), \
529 KEYMAP_ENTRY("i", "info"), \
530 KEYMAP_ENTRY("l", "ls"), \
531 KEYMAP_ENTRY("s", "play"), \
532 KEYMAP_ENTRY("p", "pause"), \
533 KEYMAP_ENTRY("q", "quit"), \
534 KEYMAP_ENTRY("?", "help"), \
535 KEYMAP_ENTRY("\033[D", "ff -10"), \
536 KEYMAP_ENTRY("\033[C", "ff 10"), \
537 KEYMAP_ENTRY("\033[A", "ff 60"), \
538 KEYMAP_ENTRY("\033[B", "ff -60"), \
540 #define KEYMAP_ENTRY(a, b) a
541 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
543 #define KEYMAP_ENTRY(a, b) b
544 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
546 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
547 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
548 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
550 static inline bool is_internal_key(int key)
552 return key < NUM_INTERNALLY_MAPPED_KEYS;
555 /* for internal keys, the key id is just the array index. */
556 static inline int get_internal_key_map_idx(int key)
558 assert(is_internal_key(key));
563 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
564 * difference is the index to the array of user defined key maps.
566 static inline int get_user_key_map_idx(int key)
568 assert(!is_internal_key(key));
569 return key - NUM_INTERNALLY_MAPPED_KEYS;
572 static inline int get_key_map_idx(int key)
574 return is_internal_key(key)?
575 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
578 static inline const char *get_user_key_map_arg(int key)
580 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
583 static inline char *get_internal_key_map_seq(int key)
585 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
588 static char *get_user_key_map_seq(int key)
590 const char *kma = get_user_key_map_arg(key);
591 const char *p = strchr(kma + 1, ':');
598 result = para_malloc(len + 1);
599 memcpy(result, kma, len);
604 static char *get_key_map_seq(int key)
606 return is_internal_key(key)?
607 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
610 static char *get_key_map_seq_safe(int key)
612 const char hex[] = "0123456789abcdef";
613 char *seq = get_key_map_seq(key), *sseq;
614 size_t n, len = strlen(seq);
616 if (len == 1 && isprint(*seq))
618 sseq = para_malloc(2 + 2 * len + 1);
621 for (n = 0; n < len; n++) {
622 uint8_t val = (seq[n] & 0xf0) >> 4;
623 sseq[2 + 2 * n] = hex[val];
625 sseq[2 + 2 * n + 1] = hex[val];
628 sseq[2 + 2 * n] = '\0';
632 static inline char *get_internal_key_map_cmd(int key)
634 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
637 static char *get_user_key_map_cmd(int key)
639 const char *kma = get_user_key_map_arg(key);
640 const char *p = strchr(kma + 1, ':');
644 return para_strdup(p + 1);
647 static char *get_key_map_cmd(int key)
649 return is_internal_key(key)?
650 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
653 static char **get_mapped_keyseqs(void)
658 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
659 FOR_EACH_MAPPED_KEY(i) {
660 char *seq = get_key_map_seq(i);
667 static struct i9e_completer pp_completers[];
669 I9E_DUMMY_COMPLETER(jmp);
670 I9E_DUMMY_COMPLETER(next);
671 I9E_DUMMY_COMPLETER(prev);
672 I9E_DUMMY_COMPLETER(fg);
673 I9E_DUMMY_COMPLETER(bg);
674 I9E_DUMMY_COMPLETER(ls);
675 I9E_DUMMY_COMPLETER(info);
676 I9E_DUMMY_COMPLETER(play);
677 I9E_DUMMY_COMPLETER(pause);
678 I9E_DUMMY_COMPLETER(tasks);
679 I9E_DUMMY_COMPLETER(quit);
680 I9E_DUMMY_COMPLETER(ff);
682 static void help_completer(struct i9e_completion_info *ci,
683 struct i9e_completion_result *cr)
685 char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
687 if (ci->word[0] == '-') {
688 i9e_complete_option(opts, ci, cr);
691 cr->matches = i9e_complete_commands(ci->word, pp_completers);
694 static struct i9e_completer pp_completers[] = {
695 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
696 .completer = _name ## _completer}
697 LSG_PLAY_CMD_SUBCOMMANDS
698 #undef LSG_PLAY_CMD_CMD
702 static void attach_stdout(const char *name)
706 pt->btrn = btr_new_node(&(struct btr_node_description)
707 EMBRACE(.name = name));
708 i9e_attach_to_stdout(pt->btrn);
711 static void detach_stdout(void)
713 btr_remove_node(&pt->btrn);
716 static int com_quit(__a_unused struct lls_parse_result *lpr)
718 pt->rq = CRT_TERM_RQ;
721 EXPORT_PLAY_CMD_HANDLER(quit);
723 static int com_help(struct lls_parse_result *lpr)
729 const struct lls_opt_result *r =
730 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
731 bool long_help = lls_opt_given(r);
733 if (!pt->background) {
734 FOR_EACH_MAPPED_KEY(i) {
735 bool internal = is_internal_key(i);
736 int idx = get_key_map_idx(i);
737 char *seq = get_key_map_seq_safe(i);
738 char *kmc = get_key_map_cmd(i);
739 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
740 internal? "internal" : "user-defined",
742 btr_add_output(buf, sz, pt->btrn);
748 lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
749 btr_add_output(buf, n, pt->btrn);
752 EXPORT_PLAY_CMD_HANDLER(help);
754 static int com_info(__a_unused struct lls_parse_result *lpr)
758 static char dflt[] = "[no information available]";
760 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
761 pt->current_file, get_playlist_file(pt->current_file));
762 btr_add_output(buf, sz, pt->btrn);
763 buf = pt->afhi_txt? pt->afhi_txt : dflt;
764 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
767 EXPORT_PLAY_CMD_HANDLER(info);
769 static void list_file(int num)
774 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
775 "*" : " ", num, get_playlist_file(num));
776 btr_add_output(buf, sz, pt->btrn);
779 static int com_tasks(__a_unused struct lls_parse_result *lpr)
785 buf = get_task_list(&sched);
786 btr_add_output(buf, strlen(buf), pt->btrn);
787 state = get_playback_state();
788 sz = xasprintf(&buf, "state: %c\n", state);
789 btr_add_output(buf, sz, pt->btrn);
792 EXPORT_PLAY_CMD_HANDLER(tasks);
794 static int com_ls(__a_unused struct lls_parse_result *lpr)
797 unsigned num_inputs = lls_num_inputs(play_lpr);
799 for (i = 0; i < num_inputs; i++)
803 EXPORT_PLAY_CMD_HANDLER(ls);
805 static int com_play(struct lls_parse_result *lpr)
811 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
814 PARA_ERROR_LOG("%s\n", errctx);
818 state = get_playback_state();
819 if (lls_num_inputs(lpr) == 0) {
822 pt->next_file = pt->current_file;
827 ret = para_atoi32(lls_input(0, lpr), &x);
830 if (x < 0 || x >= lls_num_inputs(play_lpr))
831 return -ERRNO_TO_PARA_ERROR(EINVAL);
834 pt->rq = CRT_FILE_CHANGE;
837 EXPORT_PLAY_CMD_HANDLER(play);
839 static int com_pause(__a_unused struct lls_parse_result *lpr)
842 long unsigned seconds, ss;
844 state = get_playback_state();
848 seconds = get_play_time();
852 ss = seconds * pt->num_chunks / pt->seconds + 1;
853 ss = PARA_MAX(ss, 0UL);
854 ss = PARA_MIN(ss, pt->num_chunks);
855 pt->start_chunk = ss;
859 EXPORT_PLAY_CMD_HANDLER(pause);
861 static int com_prev(__a_unused struct lls_parse_result *lpr)
865 ret = previous_valid_file();
870 pt->rq = CRT_FILE_CHANGE;
874 EXPORT_PLAY_CMD_HANDLER(prev);
876 static int com_next(__a_unused struct lls_parse_result *lpr)
880 ret = next_valid_file();
885 pt->rq = CRT_FILE_CHANGE;
889 EXPORT_PLAY_CMD_HANDLER(next);
891 static int com_fg(__a_unused struct lls_parse_result *lpr)
893 pt->background = false;
896 EXPORT_PLAY_CMD_HANDLER(fg);
898 static int com_bg(__a_unused struct lls_parse_result *lpr)
900 pt->background = true;
903 EXPORT_PLAY_CMD_HANDLER(bg);
905 static int com_jmp(struct lls_parse_result *lpr)
911 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
914 PARA_ERROR_LOG("%s\n", errctx);
918 ret = para_atoi32(lls_input(0, lpr), &percent);
921 if (percent < 0 || percent > 100)
922 return -ERRNO_TO_PARA_ERROR(EINVAL);
924 return com_next(NULL);
925 if (pt->playing && !pt->fn.btrn)
927 pt->start_chunk = percent * pt->num_chunks / 100;
934 EXPORT_PLAY_CMD_HANDLER(jmp);
936 static int com_ff(struct lls_parse_result *lpr)
942 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
945 PARA_ERROR_LOG("%s\n", errctx);
949 ret = para_atoi32(lls_input(0, lpr), &seconds);
952 if (pt->playing && !pt->fn.btrn)
954 seconds += get_play_time();
955 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
956 seconds = PARA_MAX(seconds, 0);
957 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
958 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
959 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
966 EXPORT_PLAY_CMD_HANDLER(ff);
968 static int run_command(char *line)
973 const struct play_command_info *pci;
974 struct lls_parse_result *lpr;
975 const struct lls_command *cmd;
977 attach_stdout(__FUNCTION__);
978 ret = create_argv(line, " ", &argv);
984 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
987 cmd = lls_cmd(ret, play_cmd_suite);
988 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
991 pci = lls_user_data(cmd);
992 ret = pci->handler(lpr);
993 lls_free_parse_result(lpr, cmd);
996 PARA_ERROR_LOG("%s\n", errctx);
1002 static int play_i9e_line_handler(char *line)
1004 return run_command(line);
1007 static int play_i9e_key_handler(int key)
1009 int idx = get_key_map_idx(key);
1010 char *seq = get_key_map_seq(key);
1011 char *cmd = get_key_map_cmd(key);
1012 bool internal = is_internal_key(key);
1014 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1015 key, internal? "internal" : "user-defined",
1020 pt->next_update = *now;
1024 static struct i9e_client_info ici = {
1026 .prompt = "para_play> ",
1027 .line_handler = play_i9e_line_handler,
1028 .key_handler = play_i9e_key_handler,
1029 .completers = pp_completers,
1032 static void sigint_handler(int sig)
1034 pt->background = true;
1035 i9e_signal_dispatch(sig);
1039 * We start with para_log() set to the standard log function which writes to
1040 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1043 static void session_open(void)
1047 struct sigaction act;
1049 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1050 if (OPT_GIVEN(HISTORY_FILE))
1051 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1053 char *home = para_homedir();
1054 char *dot_para = make_message("%s/.paraslash", home);
1057 ret = para_mkdir(dot_para, 0777);
1058 /* warn, but otherwise ignore mkdir error */
1059 if (ret < 0 && ret != -ERRNO_TO_PARA_ERROR(EEXIST))
1060 PARA_WARNING_LOG("Can not create %s: %s\n", dot_para,
1061 para_strerror(-ret));
1062 history_file = make_message("%s/play.history", dot_para);
1065 ici.history_file = history_file;
1066 ici.loglevel = loglevel;
1068 act.sa_handler = sigint_handler;
1069 sigemptyset(&act.sa_mask);
1071 sigaction(SIGINT, &act, NULL);
1072 act.sa_handler = i9e_signal_dispatch;
1073 sigemptyset(&act.sa_mask);
1075 sigaction(SIGWINCH, &act, NULL);
1076 sched.select_function = i9e_select;
1078 ici.bound_keyseqs = get_mapped_keyseqs();
1079 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1080 EMBRACE(.name = __FUNCTION__));
1081 ret = i9e_open(&ici, &sched);
1090 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1094 static void session_update_time_string(char *str, unsigned len)
1099 if (btr_get_output_queue_size(pt->btrn) > 0)
1101 if (btr_get_input_queue_size(pt->btrn) > 0)
1104 ie9_print_status_bar(str, len);
1108 * If we are about to die we must call i9e_close() to reset the terminal.
1109 * However, i9e_close() must be called in *this* context, i.e. from
1110 * play_task.post_select() rather than from i9e_post_select(), because
1111 * otherwise i9e would access freed memory upon return. So the play task must
1112 * stay alive until the i9e task terminates.
1114 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1115 * and reschedule. In the next iteration, i9e->post_select returns an error and
1116 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1117 * are allowed to call i9e_close() and terminate as well.
1119 static int session_post_select(__a_unused struct sched *s)
1126 attach_stdout(__FUNCTION__);
1127 ret = i9e_get_error();
1131 para_log = stderr_log;
1132 free(ici.history_file);
1135 if (get_playback_state() == 'X')
1136 i9e_signal_dispatch(SIGTERM);
1140 #else /* HAVE_READLINE */
1142 static int session_post_select(struct sched *s)
1146 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1148 if (read(STDIN_FILENO, &c, 1))
1154 static void session_open(void)
1158 static void session_update_time_string(char *str, __a_unused unsigned len)
1160 printf("\r%s ", str);
1163 #endif /* HAVE_READLINE */
1165 static void play_pre_select(struct sched *s, __a_unused void *context)
1169 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1170 state = get_playback_state();
1171 if (state == 'R' || state == 'F' || state == 'X')
1172 return sched_min_delay(s);
1173 sched_request_barrier_or_min_delay(&pt->next_update, s);
1176 static unsigned get_time_string(char **result)
1178 int seconds, length;
1179 char state = get_playback_state();
1181 /* do not return anything if things are about to change */
1182 if (state != 'P' && state != 'U') {
1186 length = pt->seconds;
1188 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1189 seconds = get_play_time();
1190 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1194 (length - seconds) / 60,
1195 (length - seconds) % 60,
1196 length? (seconds * 100 + length / 2) / length : 0,
1199 get_playlist_file(pt->current_file)
1203 static int play_post_select(struct sched *s, __a_unused void *context)
1207 ret = eof_cleanup();
1209 pt->rq = CRT_TERM_RQ;
1212 ret = session_post_select(s);
1215 if (!pt->wn.btrn && !pt->fn.btrn) {
1216 char state = get_playback_state();
1217 if (state == 'P' || state == 'R' || state == 'F') {
1218 PARA_NOTICE_LOG("state: %c\n", state);
1219 ret = load_next_file();
1221 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1222 pt->rq = CRT_TERM_RQ;
1226 pt->next_update = *now;
1229 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1231 unsigned len = get_time_string(&str);
1232 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1234 session_update_time_string(str, len);
1236 tv_add(now, &delay, &pt->next_update);
1244 * The main function of para_play.
1246 * \param argc Standard.
1247 * \param argv Standard.
1249 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1251 int main(int argc, char *argv[])
1254 unsigned num_inputs;
1256 sched.default_timeout.tv_sec = 5;
1257 parse_config_or_die(argc, argv);
1259 num_inputs = lls_num_inputs(play_lpr);
1261 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1262 pt->rq = CRT_FILE_CHANGE;
1264 pt->task = task_register(&(struct task_info){
1266 .pre_select = play_pre_select,
1267 .post_select = play_post_select,
1270 ret = schedule(&sched);
1271 sched_shutdown(&sched);
1273 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1274 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;