2 * Copyright (C) 2012 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file play.c Paraslash's standalone player. */
14 #include "recv_cmd.lsg.h"
17 #include "play.cmdline.h"
18 #include "play_cmd.lsg.h"
21 #include "buffer_tree.h"
29 #include "write_common.h"
33 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
34 * para_play creates two further tasks: The play task and the i9e task. It is
35 * important whether a function can be called in the context of para_play or
36 * i9e or both. As a rule, all command handlers are called only in i9e context via
37 * the line handler (input mode) or the key handler (command mode) below.
39 * Playlist handling is done exclusively in play context.
42 /** Array of error strings. */
46 * Describes a request to change the state of para_play.
48 * There is only one variable of this type: \a rq of the global play task
49 * structure. Command handlers only set this variable and the post_select()
50 * function of the play task investigates its value during each iteration of
51 * the scheduler run and performs the actual work.
53 enum state_change_request_type {
54 /** Everybody is happy. */
56 /** Stream must be repositioned (com_jmp(), com_ff()). */
58 /** New file should be loaded (com_next()). */
60 /** Someone wants us for dead (com_quit()). */
66 /* A bit array of invalid files (those will be skipped). */
68 /* The file which is currently open. */
69 unsigned current_file;
70 /* When to update the status again. */
71 struct timeval next_update;
73 /* Root of the buffer tree for command and status output. */
74 struct btr_node *btrn;
76 /* The decoding machinery. */
77 struct receiver_node rn;
78 struct filter_node fn;
79 struct writer_node wn;
81 /* See comment to enum state_change_request_type above */
82 enum state_change_request_type rq;
83 /* only relevant if rq == CRT_FILE_CHANGE */
86 bg: read lines at prompt, fg: display status and wait
91 /* We have the *intention* to play. Set by com_play(). */
94 /* as returned by afh_recv->open() */
97 /* retrieved via the btr exec mechanism */
98 long unsigned start_chunk;
99 long unsigned seconds;
100 long unsigned num_chunks;
104 typedef int (*play_cmd_handler_t)(struct play_task *pt,
105 struct lls_parse_result *lpr);
106 struct play_command_info {
107 play_cmd_handler_t handler;
109 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
110 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
111 .handler = com_ ## _cmd \
114 static int loglevel = LL_WARNING;
116 /** The log function which writes log messages to stderr. */
117 INIT_STDERR_LOGGING(loglevel);
119 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
121 /** Iterate over all files in the playlist. */
122 #define FOR_EACH_PLAYLIST_FILE(i) for (i = 0; i < conf.inputs_num; i++)
123 static struct play_args_info conf;
125 static struct sched sched = {.max_fileno = 0};
126 static struct play_task play_task;
128 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
129 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
131 __noreturn static void print_help_and_die(void)
133 struct ggo_help help = DEFINE_GGO_HELP(play);
134 unsigned flags = conf.detailed_help_given?
135 GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
137 ggo_print_help(&help, flags);
138 printf("supported audio formats: %s\n", AUDIO_FORMAT_HANDLERS);
142 static void parse_config_or_die(int argc, char *argv[])
146 struct play_cmdline_parser_params params = {
150 .check_ambiguity = 0,
154 play_cmdline_parser_ext(argc, argv, &conf, ¶ms);
155 loglevel = get_loglevel_by_name(conf.loglevel_arg);
156 version_handle_flag("play", conf.version_given);
157 if (conf.help_given || conf.detailed_help_given)
158 print_help_and_die();
159 if (conf.config_file_given)
160 config_file = para_strdup(conf.config_file_arg);
162 char *home = para_homedir();
163 config_file = make_message("%s/.paraslash/play.conf", home);
166 ret = file_exists(config_file);
167 if (conf.config_file_given && !ret) {
168 PARA_EMERG_LOG("can not read config file %s\n", config_file);
172 params.initialize = 0;
173 params.check_required = 1;
174 play_cmdline_parser_config_file(config_file, &conf, ¶ms);
175 loglevel = get_loglevel_by_name(conf.loglevel_arg);
177 for (i = 0; i < conf.key_map_given; i++) {
178 char *kma = conf.key_map_arg[i];
179 if (*kma && strchr(kma + 1, ':'))
181 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
191 static char get_playback_state(struct play_task *pt)
194 case CRT_NONE: return pt->playing? 'P' : 'U';
195 case CRT_REPOS: return 'R';
196 case CRT_FILE_CHANGE: return 'F';
197 case CRT_TERM_RQ: return 'X';
202 static long unsigned get_play_time(struct play_task *pt)
204 char state = get_playback_state(pt);
205 long unsigned result;
207 if (state != 'P' && state != 'U')
209 if (pt->num_chunks == 0 || pt->seconds == 0)
211 /* where the stream started (in seconds) */
212 result = pt->start_chunk * pt->seconds / pt->num_chunks;
213 if (pt->wn.btrn) { /* Add the uptime of the writer node */
214 struct timeval diff = {.tv_sec = 0}, wstime;
215 btr_get_node_start(pt->wn.btrn, &wstime);
216 if (wstime.tv_sec > 0)
217 tv_diff(now, &wstime, &diff);
218 result += diff.tv_sec;
220 result = PARA_MIN(result, pt->seconds);
221 result = PARA_MAX(result, 0UL);
226 static void wipe_receiver_node(struct play_task *pt)
228 PARA_NOTICE_LOG("cleaning up receiver node\n");
229 btr_remove_node(&pt->rn.btrn);
230 AFH_RECV->close(&pt->rn);
231 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
232 memset(&pt->rn, 0, sizeof(struct receiver_node));
235 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
236 static int get_playback_error(struct play_task *pt)
242 err = task_status(pt->wn.task);
245 if (task_status(pt->fn.task) >= 0)
247 if (task_status(pt->rn.task) >= 0)
249 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
250 || err == -E_WRITE_COMMON_EOF)
255 static int eof_cleanup(struct play_task *pt)
257 struct writer *w = writers + DEFAULT_WRITER;
258 const struct filter *decoder = filter_get(pt->fn.filter_num);
261 ret = get_playback_error(pt);
264 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
265 task_reap(&pt->wn.task);
267 btr_remove_node(&pt->wn.btrn);
268 w->free_config(pt->wn.conf);
269 memset(&pt->wn, 0, sizeof(struct writer_node));
271 task_reap(&pt->fn.task);
273 decoder->close(&pt->fn);
274 btr_remove_node(&pt->fn.btrn);
276 memset(&pt->fn, 0, sizeof(struct filter_node));
278 task_reap(&pt->rn.task);
279 btr_remove_node(&pt->rn.btrn);
281 * On eof (ret > 0), we do not wipe the receiver node struct until a
282 * new file is loaded because we still need it for jumping around when
286 wipe_receiver_node(pt);
290 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
292 return para_random(100) - 50;
295 static void shuffle(char **base, size_t num)
298 qsort(base, num, sizeof(char *), shuffle_compare);
301 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
303 return btr_new_node(&(struct btr_node_description)
304 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
305 .handler = AFH_RECV->execute));
308 static int open_new_file(struct play_task *pt)
311 char *tmp, *path = conf.inputs[pt->next_file], *errctx = NULL,
312 *argv[] = {"play", "-f", path, "-b", "0", NULL};
314 PARA_NOTICE_LOG("next file: %s\n", path);
315 wipe_receiver_node(pt);
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(pt);
359 static int load_file(struct play_task *pt)
364 const struct filter *decoder;
366 btr_remove_node(&pt->rn.btrn);
367 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
368 ret = open_new_file(pt);
372 pt->rn.btrn = new_recv_btrn(&pt->rn);
373 sprintf(buf, "repos %lu", pt->start_chunk);
374 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
376 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
381 /* set up decoding filter */
382 af = audio_format_name(pt->audio_format_num);
383 tmp = make_message("%sdec", af);
384 PARA_INFO_LOG("decoder: %s\n", tmp);
385 ret = check_filter_arg(tmp, &pt->fn.conf);
389 pt->fn.filter_num = ret;
390 decoder = filter_get(ret);
391 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
392 EMBRACE(.name = decoder->name, .parent = pt->rn.btrn,
393 .handler = decoder->execute, .context = &pt->fn));
395 decoder->open(&pt->fn);
396 PARA_INFO_LOG("buffer tree:\n");
397 btr_log_tree(pt->rn.btrn, LL_INFO);
399 /* setup default writer */
400 pt->wn.conf = check_writer_arg_or_die(NULL, &pt->wn.writer_num);
402 /* success, register tasks */
403 pt->rn.task = task_register(
404 &(struct task_info) {
405 .name = lls_command_name(AFH_RECV_CMD),
406 .pre_select = AFH_RECV->pre_select,
407 .post_select = AFH_RECV->post_select,
410 sprintf(buf, "%s decoder", af);
411 pt->fn.task = task_register(
412 &(struct task_info) {
414 .pre_select = decoder->pre_select,
415 .post_select = decoder->post_select,
418 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
421 wipe_receiver_node(pt);
425 static int next_valid_file(struct play_task *pt)
427 int i, j = pt->current_file;
429 FOR_EACH_PLAYLIST_FILE(i) {
430 j = (j + 1) % conf.inputs_num;
434 return -E_NO_VALID_FILES;
437 static int load_next_file(struct play_task *pt)
442 if (pt->rq == CRT_NONE) {
444 ret = next_valid_file(pt);
448 } else if (pt->rq == CRT_REPOS)
449 pt->next_file = pt->current_file;
452 PARA_ERROR_LOG("%s: marking file as invalid\n",
453 para_strerror(-ret));
454 pt->invalid[pt->next_file] = true;
458 pt->current_file = pt->next_file;
463 static void kill_stream(struct play_task *pt)
466 task_notify(pt->wn.task, E_EOF);
471 /* only called from com_prev(), nec. only if we have readline */
472 static int previous_valid_file(struct play_task *pt)
474 int i, j = pt->current_file;
476 FOR_EACH_PLAYLIST_FILE(i) {
479 j = conf.inputs_num - 1;
483 return -E_NO_VALID_FILES;
486 #include "interactive.h"
489 * Define the default (internal) key mappings and helper functions to get the
490 * key sequence or the command from a key id, which is what we obtain from
491 * i9e/readline when the key is pressed.
493 * In some of these helper functions we could return pointers to the constant
494 * arrays defined below. However, for others we can not, so let's better be
495 * consistent and allocate all returned strings on the heap.
498 #define INTERNAL_KEYMAP_ENTRIES \
499 KEYMAP_ENTRY("^", "jmp 0"), \
500 KEYMAP_ENTRY("1", "jmp 10"), \
501 KEYMAP_ENTRY("2", "jmp 21"), \
502 KEYMAP_ENTRY("3", "jmp 32"), \
503 KEYMAP_ENTRY("4", "jmp 43"), \
504 KEYMAP_ENTRY("5", "jmp 54"), \
505 KEYMAP_ENTRY("6", "jmp 65"), \
506 KEYMAP_ENTRY("7", "jmp 76"), \
507 KEYMAP_ENTRY("8", "jmp 87"), \
508 KEYMAP_ENTRY("9", "jmp 98"), \
509 KEYMAP_ENTRY("+", "next"), \
510 KEYMAP_ENTRY("-", "prev"), \
511 KEYMAP_ENTRY(":", "bg"), \
512 KEYMAP_ENTRY("i", "info"), \
513 KEYMAP_ENTRY("l", "ls"), \
514 KEYMAP_ENTRY("s", "play"), \
515 KEYMAP_ENTRY("p", "pause"), \
516 KEYMAP_ENTRY("q", "quit"), \
517 KEYMAP_ENTRY("?", "help"), \
518 KEYMAP_ENTRY("\033[D", "ff -10"), \
519 KEYMAP_ENTRY("\033[C", "ff 10"), \
520 KEYMAP_ENTRY("\033[A", "ff 60"), \
521 KEYMAP_ENTRY("\033[B", "ff -60"), \
523 #define KEYMAP_ENTRY(a, b) a
524 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
526 #define KEYMAP_ENTRY(a, b) b
527 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
529 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
530 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + conf.key_map_given)
531 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
533 static inline bool is_internal_key(int key)
535 return key < NUM_INTERNALLY_MAPPED_KEYS;
538 /* for internal keys, the key id is just the array index. */
539 static inline int get_internal_key_map_idx(int key)
541 assert(is_internal_key(key));
546 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
547 * difference is the index to the array of user defined key maps.
549 static inline int get_user_key_map_idx(int key)
551 assert(!is_internal_key(key));
552 return key - NUM_INTERNALLY_MAPPED_KEYS;
555 static inline int get_key_map_idx(int key)
557 return is_internal_key(key)?
558 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
561 static inline char *get_user_key_map_arg(int key)
563 return conf.key_map_arg[get_user_key_map_idx(key)];
566 static inline char *get_internal_key_map_seq(int key)
568 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
571 static char *get_user_key_map_seq(int key)
573 const char *kma = get_user_key_map_arg(key);
574 const char *p = strchr(kma + 1, ':');
581 result = para_malloc(len + 1);
582 memcpy(result, kma, len);
587 static char *get_key_map_seq(int key)
589 return is_internal_key(key)?
590 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
593 static char *get_key_map_seq_safe(int key)
595 const char hex[] = "0123456789abcdef";
596 char *seq = get_key_map_seq(key), *sseq;
597 size_t n, len = strlen(seq);
599 if (len == 1 && isprint(*seq))
601 sseq = para_malloc(2 + 2 * len + 1);
604 for (n = 0; n < len; n++) {
605 uint8_t val = (seq[n] & 0xf0) >> 4;
606 sseq[2 + 2 * n] = hex[val];
608 sseq[2 + 2 * n + 1] = hex[val];
611 sseq[2 + 2 * n] = '\0';
615 static inline char *get_internal_key_map_cmd(int key)
617 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
620 static char *get_user_key_map_cmd(int key)
622 const char *kma = get_user_key_map_arg(key);
623 const char *p = strchr(kma + 1, ':');
627 return para_strdup(p + 1);
630 static char *get_key_map_cmd(int key)
632 return is_internal_key(key)?
633 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
636 static char **get_mapped_keyseqs(void)
641 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
642 FOR_EACH_MAPPED_KEY(i) {
643 char *seq = get_key_map_seq(i);
650 static struct i9e_completer pp_completers[];
652 I9E_DUMMY_COMPLETER(jmp);
653 I9E_DUMMY_COMPLETER(next);
654 I9E_DUMMY_COMPLETER(prev);
655 I9E_DUMMY_COMPLETER(fg);
656 I9E_DUMMY_COMPLETER(bg);
657 I9E_DUMMY_COMPLETER(ls);
658 I9E_DUMMY_COMPLETER(info);
659 I9E_DUMMY_COMPLETER(play);
660 I9E_DUMMY_COMPLETER(pause);
661 I9E_DUMMY_COMPLETER(stop);
662 I9E_DUMMY_COMPLETER(tasks);
663 I9E_DUMMY_COMPLETER(quit);
664 I9E_DUMMY_COMPLETER(ff);
666 static void help_completer(struct i9e_completion_info *ci,
667 struct i9e_completion_result *result)
669 result->matches = i9e_complete_commands(ci->word, pp_completers);
672 I9E_DUMMY_COMPLETER(SUPERCOMMAND_UNAVAILABLE);
673 static struct i9e_completer pp_completers[] = {
674 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
675 .completer = _name ## _completer}
676 LSG_PLAY_CMD_SUBCOMMANDS
677 #undef LSG_PLAY_CMD_CMD
681 static void attach_stdout(struct play_task *pt, const char *name)
685 pt->btrn = btr_new_node(&(struct btr_node_description)
686 EMBRACE(.name = name));
687 i9e_attach_to_stdout(pt->btrn);
690 static void detach_stdout(struct play_task *pt)
692 btr_remove_node(&pt->btrn);
695 static int com_quit(struct play_task *pt,
696 __a_unused struct lls_parse_result *lpr)
698 pt->rq = CRT_TERM_RQ;
701 EXPORT_PLAY_CMD_HANDLER(quit);
703 static int com_help(struct play_task *pt, struct lls_parse_result *lpr)
708 const struct lls_command *cmd;
710 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
713 PARA_ERROR_LOG("%s\n", errctx);
717 if (lls_num_inputs(lpr) == 0) {
718 if (pt->background) {
719 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
720 sz = xasprintf(&buf, "%s\t%s\n",
721 lls_command_name(cmd), lls_purpose(cmd));
722 btr_add_output(buf, sz, pt->btrn);
726 FOR_EACH_MAPPED_KEY(i) {
727 bool internal = is_internal_key(i);
728 int idx = get_key_map_idx(i);
729 char *seq = get_key_map_seq_safe(i);
730 char *kmc = get_key_map_cmd(i);
731 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
732 internal? "internal" : "user-defined",
734 btr_add_output(buf, sz, pt->btrn);
740 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
744 PARA_ERROR_LOG("%s\n", errctx);
748 cmd = lls_cmd(ret, play_cmd_suite);
749 buf = lls_long_help(cmd);
751 btr_add_output(buf, strlen(buf), pt->btrn);
754 EXPORT_PLAY_CMD_HANDLER(help);
756 static int com_info(struct play_task *pt,
757 __a_unused struct lls_parse_result *lpr)
761 static char dflt[] = "[no information available]";
763 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
764 pt->current_file, conf.inputs[pt->current_file]);
765 btr_add_output(buf, sz, pt->btrn);
766 buf = pt->afhi_txt? pt->afhi_txt : dflt;
767 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
770 EXPORT_PLAY_CMD_HANDLER(info);
772 static void list_file(struct play_task *pt, int num)
777 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
778 "*" : " ", num, conf.inputs[num]);
779 btr_add_output(buf, sz, pt->btrn);
782 static int com_tasks(struct play_task *pt,
783 __a_unused struct lls_parse_result *lpr)
789 buf = get_task_list(&sched);
790 btr_add_output(buf, strlen(buf), pt->btrn);
791 state = get_playback_state(pt);
792 sz = xasprintf(&buf, "state: %c\n", state);
793 btr_add_output(buf, sz, pt->btrn);
796 EXPORT_PLAY_CMD_HANDLER(tasks);
798 static int com_ls(struct play_task *pt,
799 __a_unused struct lls_parse_result *lpr)
803 FOR_EACH_PLAYLIST_FILE(i)
807 EXPORT_PLAY_CMD_HANDLER(ls);
809 static int com_play(struct play_task *pt, struct lls_parse_result *lpr)
815 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
818 PARA_ERROR_LOG("%s\n", errctx);
822 state = get_playback_state(pt);
823 if (lls_num_inputs(lpr) == 0) {
826 pt->next_file = pt->current_file;
831 ret = para_atoi32(lls_input(0, lpr), &x);
834 if (x < 0 || x >= conf.inputs_num)
835 return -ERRNO_TO_PARA_ERROR(EINVAL);
838 pt->rq = CRT_FILE_CHANGE;
841 EXPORT_PLAY_CMD_HANDLER(play);
843 static int com_pause(struct play_task *pt,
844 __a_unused struct lls_parse_result *lpr)
847 long unsigned seconds, ss;
849 state = get_playback_state(pt);
853 seconds = get_play_time(pt);
857 ss = seconds * pt->num_chunks / pt->seconds + 1;
858 ss = PARA_MAX(ss, 0UL);
859 ss = PARA_MIN(ss, pt->num_chunks);
860 pt->start_chunk = ss;
864 EXPORT_PLAY_CMD_HANDLER(pause);
866 static int com_prev(struct play_task *pt,
867 __a_unused struct lls_parse_result *lpr)
871 ret = previous_valid_file(pt);
876 pt->rq = CRT_FILE_CHANGE;
880 EXPORT_PLAY_CMD_HANDLER(prev);
882 static int com_next(struct play_task *pt,
883 __a_unused struct lls_parse_result *lpr)
887 ret = next_valid_file(pt);
892 pt->rq = CRT_FILE_CHANGE;
896 EXPORT_PLAY_CMD_HANDLER(next);
898 static int com_fg(struct play_task *pt,
899 __a_unused struct lls_parse_result *lpr)
901 pt->background = false;
904 EXPORT_PLAY_CMD_HANDLER(fg);
906 static int com_bg(struct play_task *pt,
907 __a_unused struct lls_parse_result *lpr)
909 pt->background = true;
912 EXPORT_PLAY_CMD_HANDLER(bg);
914 static int com_jmp(struct play_task *pt, struct lls_parse_result *lpr)
920 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
923 PARA_ERROR_LOG("%s\n", errctx);
927 ret = para_atoi32(lls_input(0, lpr), &percent);
930 if (percent < 0 || percent > 100)
931 return -ERRNO_TO_PARA_ERROR(EINVAL);
933 return com_next(pt, NULL);
934 if (pt->playing && !pt->fn.btrn)
936 pt->start_chunk = percent * pt->num_chunks / 100;
943 EXPORT_PLAY_CMD_HANDLER(jmp);
945 static int com_ff(struct play_task *pt, struct lls_parse_result *lpr)
951 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
954 PARA_ERROR_LOG("%s\n", errctx);
958 ret = para_atoi32(lls_input(0, lpr), &seconds);
961 if (pt->playing && !pt->fn.btrn)
963 seconds += get_play_time(pt);
964 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
965 seconds = PARA_MAX(seconds, 0);
966 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
967 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
968 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
975 EXPORT_PLAY_CMD_HANDLER(ff);
977 static int run_command(char *line, struct play_task *pt)
982 const struct play_command_info *pci;
983 struct lls_parse_result *lpr;
984 const struct lls_command *cmd;
986 attach_stdout(pt, __FUNCTION__);
987 ret = create_argv(line, " ", &argv);
993 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
996 cmd = lls_cmd(ret, play_cmd_suite);
997 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1000 pci = lls_user_data(cmd);
1001 ret = pci->handler(pt, lpr);
1002 lls_free_parse_result(lpr, cmd);
1005 PARA_ERROR_LOG("%s\n", errctx);
1011 static int play_i9e_line_handler(char *line)
1013 return run_command(line, &play_task);
1016 static int play_i9e_key_handler(int key)
1018 struct play_task *pt = &play_task;
1019 int idx = get_key_map_idx(key);
1020 char *seq = get_key_map_seq(key);
1021 char *cmd = get_key_map_cmd(key);
1022 bool internal = is_internal_key(key);
1024 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1025 key, internal? "internal" : "user-defined",
1027 run_command(cmd, pt);
1030 pt->next_update = *now;
1034 static struct i9e_client_info ici = {
1036 .prompt = "para_play> ",
1037 .line_handler = play_i9e_line_handler,
1038 .key_handler = play_i9e_key_handler,
1039 .completers = pp_completers,
1042 static void sigint_handler(int sig)
1044 play_task.background = true;
1045 i9e_signal_dispatch(sig);
1049 * We start with para_log() set to the standard log function which writes to
1050 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1053 static void session_open(struct play_task *pt)
1057 struct sigaction act;
1059 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1060 if (conf.history_file_given)
1061 history_file = para_strdup(conf.history_file_arg);
1063 char *home = para_homedir();
1064 history_file = make_message("%s/.paraslash/play.history",
1068 ici.history_file = history_file;
1069 ici.loglevel = loglevel;
1071 act.sa_handler = sigint_handler;
1072 sigemptyset(&act.sa_mask);
1074 sigaction(SIGINT, &act, NULL);
1075 act.sa_handler = i9e_signal_dispatch;
1076 sigemptyset(&act.sa_mask);
1078 sigaction(SIGWINCH, &act, NULL);
1079 sched.select_function = i9e_select;
1081 ici.bound_keyseqs = get_mapped_keyseqs();
1082 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1083 EMBRACE(.name = __FUNCTION__));
1084 ret = i9e_open(&ici, &sched);
1093 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1097 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1102 if (btr_get_output_queue_size(pt->btrn) > 0)
1104 if (btr_get_input_queue_size(pt->btrn) > 0)
1107 ie9_print_status_bar(str, len);
1111 * If we are about to die we must call i9e_close() to reset the terminal.
1112 * However, i9e_close() must be called in *this* context, i.e. from
1113 * play_task.post_select() rather than from i9e_post_select(), because
1114 * otherwise i9e would access freed memory upon return. So the play task must
1115 * stay alive until the i9e task terminates.
1117 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1118 * and reschedule. In the next iteration, i9e->post_select returns an error and
1119 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1120 * are allowed to call i9e_close() and terminate as well.
1122 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1129 attach_stdout(pt, __FUNCTION__);
1130 ret = i9e_get_error();
1134 para_log = stderr_log;
1135 free(ici.history_file);
1138 if (get_playback_state(pt) == 'X')
1139 i9e_signal_dispatch(SIGTERM);
1143 #else /* HAVE_READLINE */
1145 static int session_post_select(struct sched *s, struct play_task *pt)
1149 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1151 if (read(STDIN_FILENO, &c, 1))
1157 static void session_open(__a_unused struct play_task *pt)
1161 static void session_update_time_string(__a_unused struct play_task *pt,
1162 char *str, __a_unused unsigned len)
1164 printf("\r%s ", str);
1167 #endif /* HAVE_READLINE */
1169 static void play_pre_select(struct sched *s, void *context)
1171 struct play_task *pt = context;
1174 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1175 state = get_playback_state(pt);
1176 if (state == 'R' || state == 'F' || state == 'X')
1177 return sched_min_delay(s);
1178 sched_request_barrier_or_min_delay(&pt->next_update, s);
1181 static unsigned get_time_string(struct play_task *pt, char **result)
1183 int seconds, length;
1184 char state = get_playback_state(pt);
1186 /* do not return anything if things are about to change */
1187 if (state != 'P' && state != 'U') {
1191 length = pt->seconds;
1193 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1194 seconds = get_play_time(pt);
1195 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1199 (length - seconds) / 60,
1200 (length - seconds) % 60,
1201 length? (seconds * 100 + length / 2) / length : 0,
1204 conf.inputs[pt->current_file]
1208 static int play_post_select(struct sched *s, void *context)
1210 struct play_task *pt = context;
1213 ret = eof_cleanup(pt);
1215 pt->rq = CRT_TERM_RQ;
1218 ret = session_post_select(s, pt);
1221 if (!pt->wn.btrn && !pt->fn.btrn) {
1222 char state = get_playback_state(pt);
1223 if (state == 'P' || state == 'R' || state == 'F') {
1224 PARA_NOTICE_LOG("state: %c\n", state);
1225 ret = load_next_file(pt);
1227 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1228 pt->rq = CRT_TERM_RQ;
1232 pt->next_update = *now;
1235 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1237 unsigned len = get_time_string(pt, &str);
1238 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1240 session_update_time_string(pt, str, len);
1242 tv_add(now, &delay, &pt->next_update);
1250 * The main function of para_play.
1252 * \param argc Standard.
1253 * \param argv Standard.
1255 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1257 int main(int argc, char *argv[])
1260 struct play_task *pt = &play_task;
1262 /* needed this early to make help work */
1267 sched.default_timeout.tv_sec = 5;
1269 parse_config_or_die(argc, argv);
1270 if (conf.inputs_num == 0)
1271 print_help_and_die();
1274 if (conf.randomize_given)
1275 shuffle(conf.inputs, conf.inputs_num);
1276 pt->invalid = para_calloc(sizeof(*pt->invalid) * conf.inputs_num);
1277 pt->rq = CRT_FILE_CHANGE;
1278 pt->current_file = conf.inputs_num - 1;
1280 pt->task = task_register(&(struct task_info){
1282 .pre_select = play_pre_select,
1283 .post_select = play_post_select,
1286 ret = schedule(&sched);
1287 sched_shutdown(&sched);
1289 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1290 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;