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);
223 static void wipe_receiver_node(void)
225 PARA_NOTICE_LOG("cleaning up receiver node\n");
226 btr_remove_node(&pt->rn.btrn);
227 AFH_RECV->close(&pt->rn);
228 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
229 memset(&pt->rn, 0, sizeof(struct receiver_node));
232 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
233 static int get_playback_error(void)
239 err = task_status(pt->wn.task);
242 if (task_status(pt->fn.task) >= 0)
244 if (task_status(pt->rn.task) >= 0)
246 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
247 || err == -E_WRITE_COMMON_EOF)
252 static int eof_cleanup(void)
254 const struct filter *decoder;
255 const struct writer *w = writer_get(-1); /* default writer */
258 ret = get_playback_error();
261 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
262 task_reap(&pt->wn.task);
264 btr_remove_node(&pt->wn.btrn);
265 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
266 memset(&pt->wn, 0, sizeof(struct writer_node));
268 decoder = filter_get(pt->fn.filter_num);
269 task_reap(&pt->fn.task);
271 decoder->close(&pt->fn);
272 btr_remove_node(&pt->fn.btrn);
274 memset(&pt->fn, 0, sizeof(struct filter_node));
276 task_reap(&pt->rn.task);
277 btr_remove_node(&pt->rn.btrn);
279 * On eof (ret > 0), we do not wipe the receiver node struct until a
280 * new file is loaded because we still need it for jumping around when
284 wipe_receiver_node();
288 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
290 return para_random(100) - 50;
293 static void init_shuffle_map(void)
295 unsigned n, num_inputs = lls_num_inputs(play_lpr);
296 shuffle_map = para_malloc(num_inputs * sizeof(unsigned));
297 for (n = 0; n < num_inputs; n++)
299 if (!OPT_GIVEN(RANDOMIZE))
302 qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
305 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
307 return btr_new_node(&(struct btr_node_description)
308 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
309 .handler = AFH_RECV->execute));
312 static int open_new_file(void)
315 const char *path = get_playlist_file(pt->next_file);
316 char *tmp = para_strdup(path), *errctx;
317 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
319 PARA_NOTICE_LOG("next file: %s\n", path);
320 wipe_receiver_node();
322 pt->rn.btrn = new_recv_btrn(&pt->rn);
323 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
324 &pt->rn.lpr, &errctx));
327 pt->rn.receiver = AFH_RECV;
328 ret = AFH_RECV->open(&pt->rn);
330 PARA_ERROR_LOG("could not open %s\n", path);
333 pt->audio_format_num = ret;
335 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
337 pt->afhi_txt = make_message("[afhi command failed]\n");
338 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
343 ret = para_atoi32(tmp, &x);
344 pt->seconds = ret < 0? 1 : x;
348 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
353 ret = para_atoi32(tmp, &x);
354 pt->num_chunks = ret < 0? 1 : x;
360 wipe_receiver_node();
364 static int load_file(void)
369 const struct filter *decoder;
370 static struct lls_parse_result *filter_lpr, *writer_lpr;
372 btr_remove_node(&pt->rn.btrn);
373 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
374 ret = open_new_file();
378 pt->rn.btrn = new_recv_btrn(&pt->rn);
379 sprintf(buf, "repos %lu", pt->start_chunk);
380 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
382 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
387 /* set up decoding filter */
388 af = audio_format_name(pt->audio_format_num);
389 tmp = make_message("%sdec", af);
390 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
394 pt->fn.filter_num = ret;
395 pt->fn.lpr = filter_lpr;
396 decoder = filter_get(ret);
397 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
398 EMBRACE(.name = filter_name(pt->fn.filter_num),
399 .parent = pt->rn.btrn, .handler = decoder->execute,
400 .context = &pt->fn));
402 decoder->open(&pt->fn);
403 PARA_INFO_LOG("buffer tree:\n");
404 btr_log_tree(pt->rn.btrn, LL_INFO);
406 /* setup default writer */
407 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
408 pt->wn.lpr = writer_lpr;
409 /* success, register tasks */
410 pt->rn.task = task_register(
411 &(struct task_info) {
412 .name = lls_command_name(AFH_RECV_CMD),
413 .pre_select = AFH_RECV->pre_select,
414 .post_select = AFH_RECV->post_select,
417 sprintf(buf, "%s decoder", af);
418 pt->fn.task = task_register(
419 &(struct task_info) {
421 .pre_select = decoder->pre_select,
422 .post_select = decoder->post_select,
425 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
428 wipe_receiver_node();
432 static int next_valid_file(void)
434 int i, j = pt->current_file;
435 unsigned num_inputs = lls_num_inputs(play_lpr);
437 for (i = 0; i < num_inputs; i++) {
438 j = (j + 1) % num_inputs;
442 return -E_NO_VALID_FILES;
445 static int load_next_file(void)
450 if (pt->rq == CRT_NONE) {
452 ret = next_valid_file();
456 } else if (pt->rq == CRT_REPOS)
457 pt->next_file = pt->current_file;
460 PARA_ERROR_LOG("%s: marking file as invalid\n",
461 para_strerror(-ret));
462 pt->invalid[pt->next_file] = true;
466 pt->current_file = pt->next_file;
471 static void kill_stream(void)
474 task_notify(pt->wn.task, E_EOF);
479 /* only called from com_prev(), nec. only if we have readline */
480 static int previous_valid_file(void)
482 int i, j = pt->current_file;
483 unsigned num_inputs = lls_num_inputs(play_lpr);
485 for (i = 0; i < num_inputs; i++) {
492 return -E_NO_VALID_FILES;
495 #include "interactive.h"
498 * Define the default (internal) key mappings and helper functions to get the
499 * key sequence or the command from a key id, which is what we obtain from
500 * i9e/readline when the key is pressed.
502 * In some of these helper functions we could return pointers to the constant
503 * arrays defined below. However, for others we can not, so let's better be
504 * consistent and allocate all returned strings on the heap.
507 #define INTERNAL_KEYMAP_ENTRIES \
508 KEYMAP_ENTRY("^", "jmp 0"), \
509 KEYMAP_ENTRY("1", "jmp 10"), \
510 KEYMAP_ENTRY("2", "jmp 21"), \
511 KEYMAP_ENTRY("3", "jmp 32"), \
512 KEYMAP_ENTRY("4", "jmp 43"), \
513 KEYMAP_ENTRY("5", "jmp 54"), \
514 KEYMAP_ENTRY("6", "jmp 65"), \
515 KEYMAP_ENTRY("7", "jmp 76"), \
516 KEYMAP_ENTRY("8", "jmp 87"), \
517 KEYMAP_ENTRY("9", "jmp 98"), \
518 KEYMAP_ENTRY("+", "next"), \
519 KEYMAP_ENTRY("-", "prev"), \
520 KEYMAP_ENTRY(":", "bg"), \
521 KEYMAP_ENTRY("i", "info"), \
522 KEYMAP_ENTRY("l", "ls"), \
523 KEYMAP_ENTRY("s", "play"), \
524 KEYMAP_ENTRY("p", "pause"), \
525 KEYMAP_ENTRY("q", "quit"), \
526 KEYMAP_ENTRY("?", "help"), \
527 KEYMAP_ENTRY("\033[D", "ff -10"), \
528 KEYMAP_ENTRY("\033[C", "ff 10"), \
529 KEYMAP_ENTRY("\033[A", "ff 60"), \
530 KEYMAP_ENTRY("\033[B", "ff -60"), \
532 #define KEYMAP_ENTRY(a, b) a
533 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
535 #define KEYMAP_ENTRY(a, b) b
536 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
538 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
539 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
540 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
542 static inline bool is_internal_key(int key)
544 return key < NUM_INTERNALLY_MAPPED_KEYS;
547 /* for internal keys, the key id is just the array index. */
548 static inline int get_internal_key_map_idx(int key)
550 assert(is_internal_key(key));
555 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
556 * difference is the index to the array of user defined key maps.
558 static inline int get_user_key_map_idx(int key)
560 assert(!is_internal_key(key));
561 return key - NUM_INTERNALLY_MAPPED_KEYS;
564 static inline int get_key_map_idx(int key)
566 return is_internal_key(key)?
567 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
570 static inline const char *get_user_key_map_arg(int key)
572 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
575 static inline char *get_internal_key_map_seq(int key)
577 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
580 static char *get_user_key_map_seq(int key)
582 const char *kma = get_user_key_map_arg(key);
583 const char *p = strchr(kma + 1, ':');
590 result = para_malloc(len + 1);
591 memcpy(result, kma, len);
596 static char *get_key_map_seq(int key)
598 return is_internal_key(key)?
599 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
602 static char *get_key_map_seq_safe(int key)
604 const char hex[] = "0123456789abcdef";
605 char *seq = get_key_map_seq(key), *sseq;
606 size_t n, len = strlen(seq);
608 if (len == 1 && isprint(*seq))
610 sseq = para_malloc(2 + 2 * len + 1);
613 for (n = 0; n < len; n++) {
614 uint8_t val = (seq[n] & 0xf0) >> 4;
615 sseq[2 + 2 * n] = hex[val];
617 sseq[2 + 2 * n + 1] = hex[val];
620 sseq[2 + 2 * n] = '\0';
624 static inline char *get_internal_key_map_cmd(int key)
626 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
629 static char *get_user_key_map_cmd(int key)
631 const char *kma = get_user_key_map_arg(key);
632 const char *p = strchr(kma + 1, ':');
636 return para_strdup(p + 1);
639 static char *get_key_map_cmd(int key)
641 return is_internal_key(key)?
642 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
645 static char **get_mapped_keyseqs(void)
650 result = para_malloc((NUM_MAPPED_KEYS + 1) * sizeof(char *));
651 FOR_EACH_MAPPED_KEY(i) {
652 char *seq = get_key_map_seq(i);
659 static struct i9e_completer pp_completers[];
661 I9E_DUMMY_COMPLETER(jmp);
662 I9E_DUMMY_COMPLETER(next);
663 I9E_DUMMY_COMPLETER(prev);
664 I9E_DUMMY_COMPLETER(fg);
665 I9E_DUMMY_COMPLETER(bg);
666 I9E_DUMMY_COMPLETER(ls);
667 I9E_DUMMY_COMPLETER(info);
668 I9E_DUMMY_COMPLETER(play);
669 I9E_DUMMY_COMPLETER(pause);
670 I9E_DUMMY_COMPLETER(tasks);
671 I9E_DUMMY_COMPLETER(quit);
672 I9E_DUMMY_COMPLETER(ff);
674 static void help_completer(struct i9e_completion_info *ci,
675 struct i9e_completion_result *cr)
677 char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
679 if (ci->word[0] == '-') {
680 i9e_complete_option(opts, ci, cr);
683 cr->matches = i9e_complete_commands(ci->word, pp_completers);
686 static struct i9e_completer pp_completers[] = {
687 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
688 .completer = _name ## _completer}
689 LSG_PLAY_CMD_SUBCOMMANDS
690 #undef LSG_PLAY_CMD_CMD
694 static void attach_stdout(const char *name)
698 pt->btrn = btr_new_node(&(struct btr_node_description)
699 EMBRACE(.name = name));
700 i9e_attach_to_stdout(pt->btrn);
703 static void detach_stdout(void)
705 btr_remove_node(&pt->btrn);
708 static int com_quit(__a_unused struct lls_parse_result *lpr)
710 pt->rq = CRT_TERM_RQ;
713 EXPORT_PLAY_CMD_HANDLER(quit);
715 static int com_help(struct lls_parse_result *lpr)
721 const struct lls_opt_result *r =
722 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
723 bool long_help = lls_opt_given(r);
725 if (!pt->background) {
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 lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
741 btr_add_output(buf, n, pt->btrn);
744 EXPORT_PLAY_CMD_HANDLER(help);
746 static int com_info(__a_unused struct lls_parse_result *lpr)
750 static char dflt[] = "[no information available]";
752 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
753 pt->current_file, get_playlist_file(pt->current_file));
754 btr_add_output(buf, sz, pt->btrn);
755 buf = pt->afhi_txt? pt->afhi_txt : dflt;
756 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
759 EXPORT_PLAY_CMD_HANDLER(info);
761 static void list_file(int num)
766 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
767 "*" : " ", num, get_playlist_file(num));
768 btr_add_output(buf, sz, pt->btrn);
771 static int com_tasks(__a_unused struct lls_parse_result *lpr)
777 buf = get_task_list(&sched);
778 btr_add_output(buf, strlen(buf), pt->btrn);
779 state = get_playback_state();
780 sz = xasprintf(&buf, "state: %c\n", state);
781 btr_add_output(buf, sz, pt->btrn);
784 EXPORT_PLAY_CMD_HANDLER(tasks);
786 static int com_ls(__a_unused struct lls_parse_result *lpr)
789 unsigned num_inputs = lls_num_inputs(play_lpr);
791 for (i = 0; i < num_inputs; i++)
795 EXPORT_PLAY_CMD_HANDLER(ls);
797 static int com_play(struct lls_parse_result *lpr)
803 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
806 PARA_ERROR_LOG("%s\n", errctx);
810 state = get_playback_state();
811 if (lls_num_inputs(lpr) == 0) {
814 pt->next_file = pt->current_file;
819 ret = para_atoi32(lls_input(0, lpr), &x);
822 if (x < 0 || x >= lls_num_inputs(play_lpr))
823 return -ERRNO_TO_PARA_ERROR(EINVAL);
826 pt->rq = CRT_FILE_CHANGE;
829 EXPORT_PLAY_CMD_HANDLER(play);
831 static int com_pause(__a_unused struct lls_parse_result *lpr)
834 long unsigned seconds, ss;
836 state = get_playback_state();
840 seconds = get_play_time();
844 ss = seconds * pt->num_chunks / pt->seconds + 1;
845 ss = PARA_MAX(ss, 0UL);
846 ss = PARA_MIN(ss, pt->num_chunks);
847 pt->start_chunk = ss;
851 EXPORT_PLAY_CMD_HANDLER(pause);
853 static int com_prev(__a_unused struct lls_parse_result *lpr)
857 ret = previous_valid_file();
862 pt->rq = CRT_FILE_CHANGE;
866 EXPORT_PLAY_CMD_HANDLER(prev);
868 static int com_next(__a_unused struct lls_parse_result *lpr)
872 ret = next_valid_file();
877 pt->rq = CRT_FILE_CHANGE;
881 EXPORT_PLAY_CMD_HANDLER(next);
883 static int com_fg(__a_unused struct lls_parse_result *lpr)
885 pt->background = false;
888 EXPORT_PLAY_CMD_HANDLER(fg);
890 static int com_bg(__a_unused struct lls_parse_result *lpr)
892 pt->background = true;
895 EXPORT_PLAY_CMD_HANDLER(bg);
897 static int com_jmp(struct lls_parse_result *lpr)
903 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
906 PARA_ERROR_LOG("%s\n", errctx);
910 ret = para_atoi32(lls_input(0, lpr), &percent);
913 if (percent < 0 || percent > 100)
914 return -ERRNO_TO_PARA_ERROR(EINVAL);
916 return com_next(NULL);
917 if (pt->playing && !pt->fn.btrn)
919 pt->start_chunk = percent * pt->num_chunks / 100;
926 EXPORT_PLAY_CMD_HANDLER(jmp);
928 static int com_ff(struct lls_parse_result *lpr)
934 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
937 PARA_ERROR_LOG("%s\n", errctx);
941 ret = para_atoi32(lls_input(0, lpr), &seconds);
944 if (pt->playing && !pt->fn.btrn)
946 seconds += get_play_time();
947 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
948 seconds = PARA_MAX(seconds, 0);
949 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
950 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
951 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
958 EXPORT_PLAY_CMD_HANDLER(ff);
960 static int run_command(char *line)
965 const struct play_command_info *pci;
966 struct lls_parse_result *lpr;
967 const struct lls_command *cmd;
969 attach_stdout(__FUNCTION__);
970 ret = create_argv(line, " ", &argv);
976 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
979 cmd = lls_cmd(ret, play_cmd_suite);
980 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
983 pci = lls_user_data(cmd);
984 ret = pci->handler(lpr);
985 lls_free_parse_result(lpr, cmd);
988 PARA_ERROR_LOG("%s\n", errctx);
994 static int play_i9e_line_handler(char *line)
996 return run_command(line);
999 static int play_i9e_key_handler(int key)
1001 int idx = get_key_map_idx(key);
1002 char *seq = get_key_map_seq(key);
1003 char *cmd = get_key_map_cmd(key);
1004 bool internal = is_internal_key(key);
1006 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1007 key, internal? "internal" : "user-defined",
1012 pt->next_update = *now;
1016 static struct i9e_client_info ici = {
1018 .prompt = "para_play> ",
1019 .line_handler = play_i9e_line_handler,
1020 .key_handler = play_i9e_key_handler,
1021 .completers = pp_completers,
1024 static void sigint_handler(int sig)
1026 pt->background = true;
1027 i9e_signal_dispatch(sig);
1031 * We start with para_log() set to the standard log function which writes to
1032 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1035 static void session_open(void)
1039 struct sigaction act;
1041 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1042 if (OPT_GIVEN(HISTORY_FILE))
1043 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1045 char *home = para_homedir();
1046 history_file = make_message("%s/.paraslash/play.history",
1050 ici.history_file = history_file;
1051 ici.loglevel = loglevel;
1053 act.sa_handler = sigint_handler;
1054 sigemptyset(&act.sa_mask);
1056 sigaction(SIGINT, &act, NULL);
1057 act.sa_handler = i9e_signal_dispatch;
1058 sigemptyset(&act.sa_mask);
1060 sigaction(SIGWINCH, &act, NULL);
1061 sched.select_function = i9e_select;
1063 ici.bound_keyseqs = get_mapped_keyseqs();
1064 pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1065 EMBRACE(.name = __FUNCTION__));
1066 ret = i9e_open(&ici, &sched);
1075 PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1079 static void session_update_time_string(char *str, unsigned len)
1084 if (btr_get_output_queue_size(pt->btrn) > 0)
1086 if (btr_get_input_queue_size(pt->btrn) > 0)
1089 ie9_print_status_bar(str, len);
1093 * If we are about to die we must call i9e_close() to reset the terminal.
1094 * However, i9e_close() must be called in *this* context, i.e. from
1095 * play_task.post_select() rather than from i9e_post_select(), because
1096 * otherwise i9e would access freed memory upon return. So the play task must
1097 * stay alive until the i9e task terminates.
1099 * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1100 * and reschedule. In the next iteration, i9e->post_select returns an error and
1101 * terminates. Subsequent calls to i9e_get_error() then return negative and we
1102 * are allowed to call i9e_close() and terminate as well.
1104 static int session_post_select(__a_unused struct sched *s)
1111 attach_stdout(__FUNCTION__);
1112 ret = i9e_get_error();
1116 para_log = stderr_log;
1117 free(ici.history_file);
1120 if (get_playback_state() == 'X')
1121 i9e_signal_dispatch(SIGTERM);
1125 #else /* HAVE_READLINE */
1127 static int session_post_select(struct sched *s)
1131 if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1133 if (read(STDIN_FILENO, &c, 1))
1139 static void session_open(void)
1143 static void session_update_time_string(char *str, __a_unused unsigned len)
1145 printf("\r%s ", str);
1148 #endif /* HAVE_READLINE */
1150 static void play_pre_select(struct sched *s, __a_unused void *context)
1154 para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1155 state = get_playback_state();
1156 if (state == 'R' || state == 'F' || state == 'X')
1157 return sched_min_delay(s);
1158 sched_request_barrier_or_min_delay(&pt->next_update, s);
1161 static unsigned get_time_string(char **result)
1163 int seconds, length;
1164 char state = get_playback_state();
1166 /* do not return anything if things are about to change */
1167 if (state != 'P' && state != 'U') {
1171 length = pt->seconds;
1173 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1174 seconds = get_play_time();
1175 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1179 (length - seconds) / 60,
1180 (length - seconds) % 60,
1181 length? (seconds * 100 + length / 2) / length : 0,
1184 get_playlist_file(pt->current_file)
1188 static int play_post_select(struct sched *s, __a_unused void *context)
1192 ret = eof_cleanup();
1194 pt->rq = CRT_TERM_RQ;
1197 ret = session_post_select(s);
1200 if (!pt->wn.btrn && !pt->fn.btrn) {
1201 char state = get_playback_state();
1202 if (state == 'P' || state == 'R' || state == 'F') {
1203 PARA_NOTICE_LOG("state: %c\n", state);
1204 ret = load_next_file();
1206 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1207 pt->rq = CRT_TERM_RQ;
1211 pt->next_update = *now;
1214 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1216 unsigned len = get_time_string(&str);
1217 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1219 session_update_time_string(str, len);
1221 tv_add(now, &delay, &pt->next_update);
1229 * The main function of para_play.
1231 * \param argc Standard.
1232 * \param argv Standard.
1234 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1236 int main(int argc, char *argv[])
1239 unsigned num_inputs;
1241 sched.default_timeout.tv_sec = 5;
1242 parse_config_or_die(argc, argv);
1244 num_inputs = lls_num_inputs(play_lpr);
1246 pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1247 pt->rq = CRT_FILE_CHANGE;
1248 pt->current_file = num_inputs - 1;
1250 pt->task = task_register(&(struct task_info){
1252 .pre_select = play_pre_select,
1253 .post_select = play_post_select,
1256 ret = schedule(&sched);
1257 sched_shutdown(&sched);
1259 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1260 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;