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. */
16 #include "play.cmdline.h"
17 #include "play_cmd.lsg.h"
20 #include "buffer_tree.h"
28 #include "write_common.h"
32 * Besides playback tasks which correspond to the receiver/filter/writer nodes,
33 * para_play creates two further tasks: The play task and the i9e task. It is
34 * important whether a function can be called in the context of para_play or
35 * i9e or both. As a rule, all command handlers are called only in i9e context via
36 * the line handler (input mode) or the key handler (command mode) below.
38 * Playlist handling is done exclusively in play context.
41 /** Array of error strings. */
45 * Describes a request to change the state of para_play.
47 * There is only one variable of this type: \a rq of the global play task
48 * structure. Command handlers only set this variable and the post_select()
49 * function of the play task investigates its value during each iteration of
50 * the scheduler run and performs the actual work.
52 enum state_change_request_type {
53 /** Everybody is happy. */
55 /** Stream must be repositioned (com_jmp(), com_ff()). */
57 /** New file should be loaded (com_next()). */
59 /** Someone wants us for dead (com_quit()). */
65 /* A bit array of invalid files (those will be skipped). */
67 /* The file which is currently open. */
68 unsigned current_file;
69 /* When to update the status again. */
70 struct timeval next_update;
72 /* Root of the buffer tree for command and status output. */
73 struct btr_node *btrn;
75 /* The decoding machinery. */
76 struct receiver_node rn;
77 struct filter_node fn;
78 struct writer_node wn;
80 /* See comment to enum state_change_request_type above */
81 enum state_change_request_type rq;
82 /* only relevant if rq == CRT_FILE_CHANGE */
85 bg: read lines at prompt, fg: display status and wait
90 /* We have the *intention* to play. Set by com_play(). */
93 /* as returned by afh_recv->open() */
96 /* retrieved via the btr exec mechanism */
97 long unsigned start_chunk;
98 long unsigned seconds;
99 long unsigned num_chunks;
103 typedef int (*play_cmd_handler_t)(struct play_task *pt,
104 struct lls_parse_result *lpr);
105 struct play_command_info {
106 play_cmd_handler_t handler;
108 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
109 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
110 .handler = com_ ## _cmd \
113 /* Activate the afh receiver. */
114 extern void afh_recv_init(struct receiver *r);
116 /** Initialization code for a receiver struct. */
117 #define AFH_RECEIVER {.name = "afh", .init = afh_recv_init},
118 /** This expands to the array of all receivers. */
119 DEFINE_RECEIVER_ARRAY;
121 static int loglevel = LL_WARNING;
123 /** The log function which writes log messages to stderr. */
124 INIT_STDERR_LOGGING(loglevel);
126 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
128 /** Iterate over all files in the playlist. */
129 #define FOR_EACH_PLAYLIST_FILE(i) for (i = 0; i < conf.inputs_num; i++)
130 static struct play_args_info conf;
132 static struct sched sched = {.max_fileno = 0};
133 static struct play_task play_task;
134 static struct receiver *afh_recv;
136 static void check_afh_receiver_or_die(void)
140 FOR_EACH_RECEIVER(i) {
141 struct receiver *r = receivers + i;
142 if (strcmp(r->name, "afh"))
147 PARA_EMERG_LOG("fatal: afh receiver not found\n");
151 __noreturn static void print_help_and_die(void)
153 struct ggo_help help = DEFINE_GGO_HELP(play);
154 unsigned flags = conf.detailed_help_given?
155 GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
157 ggo_print_help(&help, flags);
158 printf("supported audio formats: %s\n", AUDIO_FORMAT_HANDLERS);
162 static void parse_config_or_die(int argc, char *argv[])
166 struct play_cmdline_parser_params params = {
170 .check_ambiguity = 0,
174 play_cmdline_parser_ext(argc, argv, &conf, ¶ms);
175 loglevel = get_loglevel_by_name(conf.loglevel_arg);
176 version_handle_flag("play", conf.version_given);
177 if (conf.help_given || conf.detailed_help_given)
178 print_help_and_die();
179 if (conf.config_file_given)
180 config_file = para_strdup(conf.config_file_arg);
182 char *home = para_homedir();
183 config_file = make_message("%s/.paraslash/play.conf", home);
186 ret = file_exists(config_file);
187 if (conf.config_file_given && !ret) {
188 PARA_EMERG_LOG("can not read config file %s\n", config_file);
192 params.initialize = 0;
193 params.check_required = 1;
194 play_cmdline_parser_config_file(config_file, &conf, ¶ms);
195 loglevel = get_loglevel_by_name(conf.loglevel_arg);
197 for (i = 0; i < conf.key_map_given; i++) {
198 char *kma = conf.key_map_arg[i];
199 if (*kma && strchr(kma + 1, ':'))
201 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
211 static char get_playback_state(struct play_task *pt)
214 case CRT_NONE: return pt->playing? 'P' : 'U';
215 case CRT_REPOS: return 'R';
216 case CRT_FILE_CHANGE: return 'F';
217 case CRT_TERM_RQ: return 'X';
222 static long unsigned get_play_time(struct play_task *pt)
224 char state = get_playback_state(pt);
225 long unsigned result;
227 if (state != 'P' && state != 'U')
229 if (pt->num_chunks == 0 || pt->seconds == 0)
231 /* where the stream started (in seconds) */
232 result = pt->start_chunk * pt->seconds / pt->num_chunks;
233 if (pt->wn.btrn) { /* Add the uptime of the writer node */
234 struct timeval diff = {.tv_sec = 0}, wstime;
235 btr_get_node_start(pt->wn.btrn, &wstime);
236 if (wstime.tv_sec > 0)
237 tv_diff(now, &wstime, &diff);
238 result += diff.tv_sec;
240 result = PARA_MIN(result, pt->seconds);
241 result = PARA_MAX(result, 0UL);
245 static void wipe_receiver_node(struct play_task *pt)
247 PARA_NOTICE_LOG("cleaning up receiver node\n");
248 btr_remove_node(&pt->rn.btrn);
249 afh_recv->close(&pt->rn);
250 afh_recv->free_config(pt->rn.conf);
251 memset(&pt->rn, 0, sizeof(struct receiver_node));
254 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
255 static int get_playback_error(struct play_task *pt)
261 err = task_status(pt->wn.task);
264 if (task_status(pt->fn.task) >= 0)
266 if (task_status(pt->rn.task) >= 0)
268 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
269 || err == -E_WRITE_COMMON_EOF)
274 static int eof_cleanup(struct play_task *pt)
276 struct writer *w = writers + DEFAULT_WRITER;
277 const struct filter *decoder = filter_get(pt->fn.filter_num);
280 ret = get_playback_error(pt);
283 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
284 task_reap(&pt->wn.task);
286 btr_remove_node(&pt->wn.btrn);
287 w->free_config(pt->wn.conf);
288 memset(&pt->wn, 0, sizeof(struct writer_node));
290 task_reap(&pt->fn.task);
292 decoder->close(&pt->fn);
293 btr_remove_node(&pt->fn.btrn);
295 memset(&pt->fn, 0, sizeof(struct filter_node));
297 task_reap(&pt->rn.task);
298 btr_remove_node(&pt->rn.btrn);
300 * On eof (ret > 0), we do not wipe the receiver node struct until a
301 * new file is loaded because we still need it for jumping around when
305 wipe_receiver_node(pt);
309 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
311 return para_random(100) - 50;
314 static void shuffle(char **base, size_t num)
317 qsort(base, num, sizeof(char *), shuffle_compare);
320 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
322 return btr_new_node(&(struct btr_node_description)
323 EMBRACE(.name = afh_recv->name, .context = rn,
324 .handler = afh_recv->execute));
327 static int open_new_file(struct play_task *pt)
330 char *tmp, *path = conf.inputs[pt->next_file], *afh_recv_conf[] =
331 {"play", "-f", path, "-b", "0", NULL};
333 PARA_NOTICE_LOG("next file: %s\n", path);
334 wipe_receiver_node(pt);
336 pt->rn.btrn = new_recv_btrn(&pt->rn);
337 pt->rn.conf = afh_recv->parse_config(ARRAY_SIZE(afh_recv_conf) - 1,
340 pt->rn.receiver = afh_recv;
341 ret = afh_recv->open(&pt->rn);
343 PARA_ERROR_LOG("could not open %s\n", path);
346 pt->audio_format_num = ret;
348 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
350 pt->afhi_txt = make_message("[afhi command failed]\n");
351 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
356 ret = para_atoi32(tmp, &x);
357 pt->seconds = ret < 0? 1 : x;
361 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
366 ret = para_atoi32(tmp, &x);
367 pt->num_chunks = ret < 0? 1 : x;
373 wipe_receiver_node(pt);
377 static int load_file(struct play_task *pt)
382 const struct filter *decoder;
384 btr_remove_node(&pt->rn.btrn);
385 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
386 ret = open_new_file(pt);
390 pt->rn.btrn = new_recv_btrn(&pt->rn);
391 sprintf(buf, "repos %lu", pt->start_chunk);
392 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
394 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
399 /* set up decoding filter */
400 af = audio_format_name(pt->audio_format_num);
401 tmp = make_message("%sdec", af);
402 PARA_INFO_LOG("decoder: %s\n", tmp);
403 ret = check_filter_arg(tmp, &pt->fn.conf);
407 pt->fn.filter_num = ret;
408 decoder = filter_get(ret);
409 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
410 EMBRACE(.name = decoder->name, .parent = pt->rn.btrn,
411 .handler = decoder->execute, .context = &pt->fn));
413 decoder->open(&pt->fn);
414 PARA_INFO_LOG("buffer tree:\n");
415 btr_log_tree(pt->rn.btrn, LL_INFO);
417 /* setup default writer */
418 pt->wn.conf = check_writer_arg_or_die(NULL, &pt->wn.writer_num);
420 /* success, register tasks */
421 pt->rn.task = task_register(
422 &(struct task_info) {
423 .name = afh_recv->name,
424 .pre_select = afh_recv->pre_select,
425 .post_select = afh_recv->post_select,
428 sprintf(buf, "%s decoder", af);
429 pt->fn.task = task_register(
430 &(struct task_info) {
432 .pre_select = decoder->pre_select,
433 .post_select = decoder->post_select,
436 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
439 wipe_receiver_node(pt);
443 static int next_valid_file(struct play_task *pt)
445 int i, j = pt->current_file;
447 FOR_EACH_PLAYLIST_FILE(i) {
448 j = (j + 1) % conf.inputs_num;
452 return -E_NO_VALID_FILES;
455 static int load_next_file(struct play_task *pt)
460 if (pt->rq == CRT_NONE) {
462 ret = next_valid_file(pt);
466 } else if (pt->rq == CRT_REPOS)
467 pt->next_file = pt->current_file;
470 PARA_ERROR_LOG("%s: marking file as invalid\n",
471 para_strerror(-ret));
472 pt->invalid[pt->next_file] = true;
476 pt->current_file = pt->next_file;
481 static void kill_stream(struct play_task *pt)
484 task_notify(pt->wn.task, E_EOF);
489 /* only called from com_prev(), nec. only if we have readline */
490 static int previous_valid_file(struct play_task *pt)
492 int i, j = pt->current_file;
494 FOR_EACH_PLAYLIST_FILE(i) {
497 j = conf.inputs_num - 1;
501 return -E_NO_VALID_FILES;
504 #include "interactive.h"
507 * Define the default (internal) key mappings and helper functions to get the
508 * key sequence or the command from a key id, which is what we obtain from
509 * i9e/readline when the key is pressed.
511 * In some of these helper functions we could return pointers to the constant
512 * arrays defined below. However, for others we can not, so let's better be
513 * consistent and allocate all returned strings on the heap.
516 #define INTERNAL_KEYMAP_ENTRIES \
517 KEYMAP_ENTRY("^", "jmp 0"), \
518 KEYMAP_ENTRY("1", "jmp 10"), \
519 KEYMAP_ENTRY("2", "jmp 21"), \
520 KEYMAP_ENTRY("3", "jmp 32"), \
521 KEYMAP_ENTRY("4", "jmp 43"), \
522 KEYMAP_ENTRY("5", "jmp 54"), \
523 KEYMAP_ENTRY("6", "jmp 65"), \
524 KEYMAP_ENTRY("7", "jmp 76"), \
525 KEYMAP_ENTRY("8", "jmp 87"), \
526 KEYMAP_ENTRY("9", "jmp 98"), \
527 KEYMAP_ENTRY("+", "next"), \
528 KEYMAP_ENTRY("-", "prev"), \
529 KEYMAP_ENTRY(":", "bg"), \
530 KEYMAP_ENTRY("i", "info"), \
531 KEYMAP_ENTRY("l", "ls"), \
532 KEYMAP_ENTRY("s", "play"), \
533 KEYMAP_ENTRY("p", "pause"), \
534 KEYMAP_ENTRY("q", "quit"), \
535 KEYMAP_ENTRY("?", "help"), \
536 KEYMAP_ENTRY("\033[D", "ff -10"), \
537 KEYMAP_ENTRY("\033[C", "ff 10"), \
538 KEYMAP_ENTRY("\033[A", "ff 60"), \
539 KEYMAP_ENTRY("\033[B", "ff -60"), \
541 #define KEYMAP_ENTRY(a, b) a
542 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
544 #define KEYMAP_ENTRY(a, b) b
545 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
547 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
548 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + conf.key_map_given)
549 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
551 static inline bool is_internal_key(int key)
553 return key < NUM_INTERNALLY_MAPPED_KEYS;
556 /* for internal keys, the key id is just the array index. */
557 static inline int get_internal_key_map_idx(int key)
559 assert(is_internal_key(key));
564 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
565 * difference is the index to the array of user defined key maps.
567 static inline int get_user_key_map_idx(int key)
569 assert(!is_internal_key(key));
570 return key - NUM_INTERNALLY_MAPPED_KEYS;
573 static inline int get_key_map_idx(int key)
575 return is_internal_key(key)?
576 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
579 static inline char *get_user_key_map_arg(int key)
581 return conf.key_map_arg[get_user_key_map_idx(key)];
584 static inline char *get_internal_key_map_seq(int key)
586 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
589 static char *get_user_key_map_seq(int key)
591 const char *kma = get_user_key_map_arg(key);
592 const char *p = strchr(kma + 1, ':');
599 result = para_malloc(len + 1);
600 memcpy(result, kma, len);
605 static char *get_key_map_seq(int key)
607 return is_internal_key(key)?
608 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
611 static char *get_key_map_seq_safe(int key)
613 const char hex[] = "0123456789abcdef";
614 char *seq = get_key_map_seq(key), *sseq;
615 size_t n, len = strlen(seq);
617 if (len == 1 && isprint(*seq))
619 sseq = para_malloc(2 + 2 * len + 1);
622 for (n = 0; n < len; n++) {
623 uint8_t val = (seq[n] & 0xf0) >> 4;
624 sseq[2 + 2 * n] = hex[val];
626 sseq[2 + 2 * n + 1] = hex[val];
629 sseq[2 + 2 * n] = '\0';
633 static inline char *get_internal_key_map_cmd(int key)
635 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
638 static char *get_user_key_map_cmd(int key)
640 const char *kma = get_user_key_map_arg(key);
641 const char *p = strchr(kma + 1, ':');
645 return para_strdup(p + 1);
648 static char *get_key_map_cmd(int key)
650 return is_internal_key(key)?
651 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
654 static char **get_mapped_keyseqs(void)
659 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
660 FOR_EACH_MAPPED_KEY(i) {
661 char *seq = get_key_map_seq(i);
668 static struct i9e_completer pp_completers[];
670 I9E_DUMMY_COMPLETER(jmp);
671 I9E_DUMMY_COMPLETER(next);
672 I9E_DUMMY_COMPLETER(prev);
673 I9E_DUMMY_COMPLETER(fg);
674 I9E_DUMMY_COMPLETER(bg);
675 I9E_DUMMY_COMPLETER(ls);
676 I9E_DUMMY_COMPLETER(info);
677 I9E_DUMMY_COMPLETER(play);
678 I9E_DUMMY_COMPLETER(pause);
679 I9E_DUMMY_COMPLETER(stop);
680 I9E_DUMMY_COMPLETER(tasks);
681 I9E_DUMMY_COMPLETER(quit);
682 I9E_DUMMY_COMPLETER(ff);
684 static void help_completer(struct i9e_completion_info *ci,
685 struct i9e_completion_result *result)
687 result->matches = i9e_complete_commands(ci->word, pp_completers);
690 I9E_DUMMY_COMPLETER(SUPERCOMMAND_UNAVAILABLE);
691 static struct i9e_completer pp_completers[] = {
692 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
693 .completer = _name ## _completer}
694 LSG_PLAY_CMD_SUBCOMMANDS
695 #undef LSG_PLAY_CMD_CMD
699 static void attach_stdout(struct play_task *pt, const char *name)
703 pt->btrn = btr_new_node(&(struct btr_node_description)
704 EMBRACE(.name = name));
705 i9e_attach_to_stdout(pt->btrn);
708 static void detach_stdout(struct play_task *pt)
710 btr_remove_node(&pt->btrn);
713 static int com_quit(struct play_task *pt,
714 __a_unused struct lls_parse_result *lpr)
716 pt->rq = CRT_TERM_RQ;
719 EXPORT_PLAY_CMD_HANDLER(quit);
721 static int com_help(struct play_task *pt, struct lls_parse_result *lpr)
726 const struct lls_command *cmd;
728 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
731 PARA_ERROR_LOG("%s\n", errctx);
735 if (lls_num_inputs(lpr) == 0) {
736 if (pt->background) {
737 for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
738 sz = xasprintf(&buf, "%s\t%s\n",
739 lls_command_name(cmd), lls_purpose(cmd));
740 btr_add_output(buf, sz, pt->btrn);
744 FOR_EACH_MAPPED_KEY(i) {
745 bool internal = is_internal_key(i);
746 int idx = get_key_map_idx(i);
747 char *seq = get_key_map_seq_safe(i);
748 char *kmc = get_key_map_cmd(i);
749 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
750 internal? "internal" : "user-defined",
752 btr_add_output(buf, sz, pt->btrn);
758 ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
762 PARA_ERROR_LOG("%s\n", errctx);
766 cmd = lls_cmd(ret, play_cmd_suite);
767 buf = lls_long_help(cmd);
769 btr_add_output(buf, strlen(buf), pt->btrn);
772 EXPORT_PLAY_CMD_HANDLER(help);
774 static int com_info(struct play_task *pt,
775 __a_unused struct lls_parse_result *lpr)
779 static char dflt[] = "[no information available]";
781 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
782 pt->current_file, conf.inputs[pt->current_file]);
783 btr_add_output(buf, sz, pt->btrn);
784 buf = pt->afhi_txt? pt->afhi_txt : dflt;
785 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
788 EXPORT_PLAY_CMD_HANDLER(info);
790 static void list_file(struct play_task *pt, int num)
795 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
796 "*" : " ", num, conf.inputs[num]);
797 btr_add_output(buf, sz, pt->btrn);
800 static int com_tasks(struct play_task *pt,
801 __a_unused struct lls_parse_result *lpr)
807 buf = get_task_list(&sched);
808 btr_add_output(buf, strlen(buf), pt->btrn);
809 state = get_playback_state(pt);
810 sz = xasprintf(&buf, "state: %c\n", state);
811 btr_add_output(buf, sz, pt->btrn);
814 EXPORT_PLAY_CMD_HANDLER(tasks);
816 static int com_ls(struct play_task *pt,
817 __a_unused struct lls_parse_result *lpr)
821 FOR_EACH_PLAYLIST_FILE(i)
825 EXPORT_PLAY_CMD_HANDLER(ls);
827 static int com_play(struct play_task *pt, struct lls_parse_result *lpr)
833 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
836 PARA_ERROR_LOG("%s\n", errctx);
840 state = get_playback_state(pt);
841 if (lls_num_inputs(lpr) == 0) {
844 pt->next_file = pt->current_file;
849 ret = para_atoi32(lls_input(0, lpr), &x);
852 if (x < 0 || x >= conf.inputs_num)
853 return -ERRNO_TO_PARA_ERROR(EINVAL);
856 pt->rq = CRT_FILE_CHANGE;
859 EXPORT_PLAY_CMD_HANDLER(play);
861 static int com_pause(struct play_task *pt,
862 __a_unused struct lls_parse_result *lpr)
865 long unsigned seconds, ss;
867 state = get_playback_state(pt);
871 seconds = get_play_time(pt);
875 ss = seconds * pt->num_chunks / pt->seconds + 1;
876 ss = PARA_MAX(ss, 0UL);
877 ss = PARA_MIN(ss, pt->num_chunks);
878 pt->start_chunk = ss;
882 EXPORT_PLAY_CMD_HANDLER(pause);
884 static int com_prev(struct play_task *pt,
885 __a_unused struct lls_parse_result *lpr)
889 ret = previous_valid_file(pt);
894 pt->rq = CRT_FILE_CHANGE;
898 EXPORT_PLAY_CMD_HANDLER(prev);
900 static int com_next(struct play_task *pt,
901 __a_unused struct lls_parse_result *lpr)
905 ret = next_valid_file(pt);
910 pt->rq = CRT_FILE_CHANGE;
914 EXPORT_PLAY_CMD_HANDLER(next);
916 static int com_fg(struct play_task *pt,
917 __a_unused struct lls_parse_result *lpr)
919 pt->background = false;
922 EXPORT_PLAY_CMD_HANDLER(fg);
924 static int com_bg(struct play_task *pt,
925 __a_unused struct lls_parse_result *lpr)
927 pt->background = true;
930 EXPORT_PLAY_CMD_HANDLER(bg);
932 static int com_jmp(struct play_task *pt, struct lls_parse_result *lpr)
938 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
941 PARA_ERROR_LOG("%s\n", errctx);
945 ret = para_atoi32(lls_input(0, lpr), &percent);
948 if (percent < 0 || percent > 100)
949 return -ERRNO_TO_PARA_ERROR(EINVAL);
951 return com_next(pt, NULL);
952 if (pt->playing && !pt->fn.btrn)
954 pt->start_chunk = percent * pt->num_chunks / 100;
961 EXPORT_PLAY_CMD_HANDLER(jmp);
963 static int com_ff(struct play_task *pt, struct lls_parse_result *lpr)
969 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
972 PARA_ERROR_LOG("%s\n", errctx);
976 ret = para_atoi32(lls_input(0, lpr), &seconds);
979 if (pt->playing && !pt->fn.btrn)
981 seconds += get_play_time(pt);
982 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
983 seconds = PARA_MAX(seconds, 0);
984 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
985 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
986 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
993 EXPORT_PLAY_CMD_HANDLER(ff);
995 static int run_command(char *line, struct play_task *pt)
1000 const struct play_command_info *pci;
1001 struct lls_parse_result *lpr;
1002 const struct lls_command *cmd;
1004 attach_stdout(pt, __FUNCTION__);
1005 ret = create_argv(line, " ", &argv);
1011 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1014 cmd = lls_cmd(ret, play_cmd_suite);
1015 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1018 pci = lls_user_data(cmd);
1019 ret = pci->handler(pt, lpr);
1020 lls_free_parse_result(lpr, cmd);
1023 PARA_ERROR_LOG("%s\n", errctx);
1029 static int play_i9e_line_handler(char *line)
1031 return run_command(line, &play_task);
1034 static int play_i9e_key_handler(int key)
1036 struct play_task *pt = &play_task;
1037 int idx = get_key_map_idx(key);
1038 char *seq = get_key_map_seq(key);
1039 char *cmd = get_key_map_cmd(key);
1040 bool internal = is_internal_key(key);
1042 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1043 key, internal? "internal" : "user-defined",
1045 run_command(cmd, pt);
1048 pt->next_update = *now;
1052 static struct i9e_client_info ici = {
1054 .prompt = "para_play> ",
1055 .line_handler = play_i9e_line_handler,
1056 .key_handler = play_i9e_key_handler,
1057 .completers = pp_completers,
1060 static void sigint_handler(int sig)
1062 play_task.background = true;
1063 i9e_signal_dispatch(sig);
1067 * We start with para_log() set to the standard log function which writes to
1068 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1071 static void session_open(struct play_task *pt)
1075 struct sigaction act;
1077 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1078 if (conf.history_file_given)
1079 history_file = para_strdup(conf.history_file_arg);
1081 char *home = para_homedir();
1082 history_file = make_message("%s/.paraslash/play.history",
1086 ici.history_file = history_file;
1087 ici.loglevel = loglevel;
1089 act.sa_handler = sigint_handler;
1090 sigemptyset(&act.sa_mask);
1092 sigaction(SIGINT, &act, NULL);
1093 act.sa_handler = i9e_signal_dispatch;
1094 sigemptyset(&act.sa_mask);
1096 sigaction(SIGWINCH, &act, NULL);
1097 sched.select_function = i9e_select;
1099 ici.bound_keyseqs = get_mapped_keyseqs();
1100 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1101 EMBRACE(.name = __FUNCTION__));
1102 ret = i9e_open(&ici, &sched);
1111 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1115 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1120 if (btr_get_output_queue_size(pt->btrn) > 0)
1122 if (btr_get_input_queue_size(pt->btrn) > 0)
1125 ie9_print_status_bar(str, len);
1129 * If we are about to die we must call i9e_close() to reset the terminal.
1130 * However, i9e_close() must be called in *this* context, i.e. from
1131 * play_task.post_select() rather than from i9e_post_select(), because
1132 * otherwise i9e would access freed memory upon return. So the play task must
1133 * stay alive until the i9e task terminates.
1135 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1136 * and reschedule. In the next iteration, i9e->post_select returns an error and
1137 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1138 * are allowed to call i9e_close() and terminate as well.
1140 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1147 attach_stdout(pt, __FUNCTION__);
1148 ret = i9e_get_error();
1152 para_log = stderr_log;
1153 free(ici.history_file);
1156 if (get_playback_state(pt) == 'X')
1157 i9e_signal_dispatch(SIGTERM);
1161 #else /* HAVE_READLINE */
1163 static int session_post_select(struct sched *s, struct play_task *pt)
1167 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1169 if (read(STDIN_FILENO, &c, 1))
1175 static void session_open(__a_unused struct play_task *pt)
1179 static void session_update_time_string(__a_unused struct play_task *pt,
1180 char *str, __a_unused unsigned len)
1182 printf("\r%s ", str);
1185 #endif /* HAVE_READLINE */
1187 static void play_pre_select(struct sched *s, void *context)
1189 struct play_task *pt = context;
1192 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1193 state = get_playback_state(pt);
1194 if (state == 'R' || state == 'F' || state == 'X')
1195 return sched_min_delay(s);
1196 sched_request_barrier_or_min_delay(&pt->next_update, s);
1199 static unsigned get_time_string(struct play_task *pt, char **result)
1201 int seconds, length;
1202 char state = get_playback_state(pt);
1204 /* do not return anything if things are about to change */
1205 if (state != 'P' && state != 'U') {
1209 length = pt->seconds;
1211 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1212 seconds = get_play_time(pt);
1213 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1217 (length - seconds) / 60,
1218 (length - seconds) % 60,
1219 length? (seconds * 100 + length / 2) / length : 0,
1222 conf.inputs[pt->current_file]
1226 static int play_post_select(struct sched *s, void *context)
1228 struct play_task *pt = context;
1231 ret = eof_cleanup(pt);
1233 pt->rq = CRT_TERM_RQ;
1236 ret = session_post_select(s, pt);
1239 if (!pt->wn.btrn && !pt->fn.btrn) {
1240 char state = get_playback_state(pt);
1241 if (state == 'P' || state == 'R' || state == 'F') {
1242 PARA_NOTICE_LOG("state: %c\n", state);
1243 ret = load_next_file(pt);
1245 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1246 pt->rq = CRT_TERM_RQ;
1250 pt->next_update = *now;
1253 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1255 unsigned len = get_time_string(pt, &str);
1256 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1258 session_update_time_string(pt, str, len);
1260 tv_add(now, &delay, &pt->next_update);
1268 * The main function of para_play.
1270 * \param argc Standard.
1271 * \param argv Standard.
1273 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1275 int main(int argc, char *argv[])
1278 struct play_task *pt = &play_task;
1280 /* needed this early to make help work */
1285 sched.default_timeout.tv_sec = 5;
1287 parse_config_or_die(argc, argv);
1288 if (conf.inputs_num == 0)
1289 print_help_and_die();
1290 check_afh_receiver_or_die();
1293 if (conf.randomize_given)
1294 shuffle(conf.inputs, conf.inputs_num);
1295 pt->invalid = para_calloc(sizeof(*pt->invalid) * conf.inputs_num);
1296 pt->rq = CRT_FILE_CHANGE;
1297 pt->current_file = conf.inputs_num - 1;
1299 pt->task = task_register(&(struct task_info){
1301 .pre_select = play_pre_select,
1302 .post_select = play_post_select,
1305 ret = schedule(&sched);
1306 sched_shutdown(&sched);
1308 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1309 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;