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_monitor()
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;
113 static int loglevel = LL_WARNING;
115 /** The log function which writes log messages to stderr. */
116 INIT_STDERR_LOGGING(loglevel);
118 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
120 static struct sched sched;
121 static struct play_task play_task, *pt = &play_task;
123 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
124 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
126 static unsigned *shuffle_map;
128 static const char *get_playlist_file(unsigned idx)
130 return lls_input(shuffle_map[idx], play_lpr);
133 static void handle_help_flags(void)
137 if (OPT_GIVEN(DETAILED_HELP))
138 help = lls_long_help(CMD_PTR);
139 else if (OPT_GIVEN(HELP) || lls_num_inputs(play_lpr) == 0)
140 help = lls_short_help(CMD_PTR);
143 printf("%s\n", help);
148 static void parse_config_or_die(int argc, char *argv[])
154 ret = lls(lls_parse(argc, argv, CMD_PTR, &play_lpr, &errctx));
157 PARA_EMERG_LOG("%s\n", errctx);
159 PARA_EMERG_LOG("failed to parse command line options: %s\n",
160 para_strerror(-ret));
163 loglevel = OPT_UINT32_VAL(LOGLEVEL);
164 version_handle_flag("play", OPT_GIVEN(VERSION));
165 handle_help_flags(); /* also handles the zero-arg case */
166 ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
167 "play.conf", &play_lpr, CMD_PTR, play_suite, 0 /* flags */);
169 PARA_EMERG_LOG("failed to parse config file: %s\n",
170 para_strerror(-ret));
173 loglevel = OPT_UINT32_VAL(LOGLEVEL);
174 num_kmas = OPT_GIVEN(KEY_MAP);
175 for (i = 0; i < num_kmas; i++) {
176 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
177 if (*kma && strchr(kma + 1, ':'))
179 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
184 static char get_playback_state(void)
187 case CRT_NONE: return pt->playing? 'P' : 'U';
188 case CRT_REPOS: return 'R';
189 case CRT_FILE_CHANGE: return 'F';
190 case CRT_TERM_RQ: return 'X';
195 /* returns number of milliseconds */
196 static long unsigned get_play_time(void)
198 char state = get_playback_state();
199 long unsigned result;
201 if (state != 'P' && state != 'U')
203 if (pt->num_chunks == 0 || pt->seconds == 0)
205 /* where the stream started (in milliseconds) */
206 result = 1000ULL * pt->start_chunk * pt->seconds / pt->num_chunks;
207 if (pt->wn.btrn) { /* Add the uptime of the writer node */
208 struct timeval diff = {.tv_sec = 0}, wstime;
209 btr_get_node_start(pt->wn.btrn, &wstime);
210 if (wstime.tv_sec > 0)
211 tv_diff(now, &wstime, &diff);
212 result += tv2ms(&diff);
214 result = PARA_MIN(result, pt->seconds * 1000);
215 result = PARA_MAX(result, 0UL);
219 static void wipe_receiver_node(void)
221 PARA_NOTICE_LOG("cleaning up receiver node\n");
222 btr_remove_node(&pt->rn.btrn);
223 AFH_RECV->close(&pt->rn);
224 lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
225 memset(&pt->rn, 0, sizeof(struct receiver_node));
228 /* returns: 0 not eof, 1: eof, < 0: fatal error. */
229 static int get_playback_error(void)
235 err = task_status(pt->wn.task);
238 if (task_status(pt->fn.task) >= 0)
240 if (task_status(pt->rn.task) >= 0)
242 if (err == -E_BTR_EOF || err == -E_RECV_EOF || err == -E_EOF
243 || err == -E_WRITE_COMMON_EOF)
248 static int eof_cleanup(void)
250 const struct filter *decoder;
251 const struct writer *w = writer_get(-1); /* default writer */
254 ret = get_playback_error();
257 PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
258 task_reap(&pt->wn.task);
260 btr_remove_node(&pt->wn.btrn);
261 lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
262 memset(&pt->wn, 0, sizeof(struct writer_node));
264 decoder = filter_get(pt->fn.filter_num);
265 task_reap(&pt->fn.task);
267 decoder->close(&pt->fn);
268 btr_remove_node(&pt->fn.btrn);
270 memset(&pt->fn, 0, sizeof(struct filter_node));
272 task_reap(&pt->rn.task);
273 btr_remove_node(&pt->rn.btrn);
275 * On eof (ret > 0), we do not wipe the receiver node struct until a
276 * new file is loaded because we still need it for jumping around when
280 wipe_receiver_node();
284 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
286 return para_random(100) - 50;
289 static void init_shuffle_map(void)
291 unsigned n, num_inputs = lls_num_inputs(play_lpr);
292 shuffle_map = arr_alloc(num_inputs, sizeof(unsigned));
293 for (n = 0; n < num_inputs; n++)
295 if (!OPT_GIVEN(RANDOMIZE))
298 qsort(shuffle_map, num_inputs, sizeof(unsigned), 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(void)
311 const char *path = get_playlist_file(pt->next_file);
312 char *tmp = para_strdup(path), *errctx;
313 char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
315 PARA_NOTICE_LOG("next file: %s\n", path);
316 wipe_receiver_node();
318 pt->rn.btrn = new_recv_btrn(&pt->rn);
319 ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
320 &pt->rn.lpr, &errctx));
323 pt->rn.receiver = AFH_RECV;
324 ret = AFH_RECV->open(&pt->rn);
326 PARA_ERROR_LOG("could not open %s\n", path);
329 pt->audio_format_num = ret;
331 ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
333 pt->afhi_txt = make_message("[afhi command failed]\n");
334 ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
339 ret = para_atoi32(tmp, &x);
340 pt->seconds = ret < 0? 1 : x;
344 ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
349 ret = para_atoi32(tmp, &x);
350 pt->num_chunks = ret < 0? 1 : x;
356 wipe_receiver_node();
360 static int load_file(void)
365 const struct filter *decoder;
366 static struct lls_parse_result *filter_lpr, *writer_lpr;
368 btr_remove_node(&pt->rn.btrn);
369 if (!pt->rn.receiver || pt->next_file != pt->current_file) {
370 ret = open_new_file();
374 pt->rn.btrn = new_recv_btrn(&pt->rn);
375 sprintf(buf, "repos %lu", pt->start_chunk);
376 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
378 PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
383 /* set up decoding filter */
384 af = audio_format_name(pt->audio_format_num);
385 tmp = make_message("%sdec", af);
386 ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
390 pt->fn.filter_num = ret;
391 pt->fn.lpr = filter_lpr;
392 decoder = filter_get(ret);
393 pt->fn.btrn = btr_new_node(&(struct btr_node_description)
394 EMBRACE(.name = filter_name(pt->fn.filter_num),
395 .parent = pt->rn.btrn, .handler = decoder->execute,
396 .context = &pt->fn));
398 decoder->open(&pt->fn);
399 PARA_INFO_LOG("buffer tree:\n");
400 btr_log_tree(pt->rn.btrn, LL_INFO);
402 /* setup default writer */
403 pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
404 pt->wn.lpr = writer_lpr;
405 /* success, register tasks */
406 pt->rn.task = task_register(
407 &(struct task_info) {
408 .name = lls_command_name(AFH_RECV_CMD),
409 .pre_monitor = AFH_RECV->pre_monitor,
410 .post_monitor = AFH_RECV->post_monitor,
413 sprintf(buf, "%s decoder", af);
414 pt->fn.task = task_register(
415 &(struct task_info) {
417 .pre_monitor = decoder->pre_monitor,
418 .post_monitor = decoder->post_monitor,
421 register_writer_node(&pt->wn, pt->fn.btrn, &sched);
424 wipe_receiver_node();
428 static int next_valid_file(void)
430 int i, j = pt->current_file;
431 unsigned num_inputs = lls_num_inputs(play_lpr);
433 if (j == num_inputs - 1) {
434 switch (OPT_UINT32_VAL(END_OF_PLAYLIST)) {
435 case EOP_LOOP: break;
439 case EOP_QUIT: return -E_EOP;
442 for (i = 0; i < num_inputs; i++) {
443 j = (j + 1) % num_inputs;
447 return -E_NO_VALID_FILES;
450 static int load_next_file(void)
455 if (pt->rq == CRT_NONE) {
457 ret = next_valid_file();
461 } else if (pt->rq == CRT_REPOS)
462 pt->next_file = pt->current_file;
465 PARA_ERROR_LOG("%s: marking file as invalid\n",
466 para_strerror(-ret));
467 pt->invalid[pt->next_file] = true;
471 pt->current_file = pt->next_file;
476 static void kill_stream(void)
479 task_notify(pt->wn.task, E_EOF);
484 /* only called from com_prev(), nec. only if we have readline */
485 static int previous_valid_file(void)
487 int i, j = pt->current_file;
488 unsigned num_inputs = lls_num_inputs(play_lpr);
490 for (i = 0; i < num_inputs; i++) {
497 return -E_NO_VALID_FILES;
500 #include "interactive.h"
503 * Define the default (internal) key mappings and helper functions to get the
504 * key sequence or the command from a key id, which is what we obtain from
505 * i9e/readline when the key is pressed.
507 * In some of these helper functions we could return pointers to the constant
508 * arrays defined below. However, for others we can not, so let's better be
509 * consistent and allocate all returned strings on the heap.
512 #define INTERNAL_KEYMAP_ENTRIES \
513 KEYMAP_ENTRY("^", "jmp 0"), \
514 KEYMAP_ENTRY("1", "jmp 10"), \
515 KEYMAP_ENTRY("2", "jmp 21"), \
516 KEYMAP_ENTRY("3", "jmp 32"), \
517 KEYMAP_ENTRY("4", "jmp 43"), \
518 KEYMAP_ENTRY("5", "jmp 54"), \
519 KEYMAP_ENTRY("6", "jmp 65"), \
520 KEYMAP_ENTRY("7", "jmp 76"), \
521 KEYMAP_ENTRY("8", "jmp 87"), \
522 KEYMAP_ENTRY("9", "jmp 98"), \
523 KEYMAP_ENTRY("+", "next"), \
524 KEYMAP_ENTRY("-", "prev"), \
525 KEYMAP_ENTRY(":", "bg"), \
526 KEYMAP_ENTRY("i", "info"), \
527 KEYMAP_ENTRY("l", "ls"), \
528 KEYMAP_ENTRY("s", "play"), \
529 KEYMAP_ENTRY("p", "pause"), \
530 KEYMAP_ENTRY("q", "quit"), \
531 KEYMAP_ENTRY("?", "help"), \
532 KEYMAP_ENTRY("\033[D", "ff -10"), \
533 KEYMAP_ENTRY("\033[C", "ff 10"), \
534 KEYMAP_ENTRY("\033[A", "ff 60"), \
535 KEYMAP_ENTRY("\033[B", "ff -60"), \
537 #define KEYMAP_ENTRY(a, b) a
538 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
540 #define KEYMAP_ENTRY(a, b) b
541 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
543 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
544 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
545 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
547 static inline bool is_internal_key(int key)
549 return key < NUM_INTERNALLY_MAPPED_KEYS;
552 /* for internal keys, the key id is just the array index. */
553 static inline int get_internal_key_map_idx(int key)
555 assert(is_internal_key(key));
560 * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
561 * difference is the index to the array of user defined key maps.
563 static inline int get_user_key_map_idx(int key)
565 assert(!is_internal_key(key));
566 return key - NUM_INTERNALLY_MAPPED_KEYS;
569 static inline int get_key_map_idx(int key)
571 return is_internal_key(key)?
572 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
575 static inline const char *get_user_key_map_arg(int key)
577 return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
580 static inline char *get_internal_key_map_seq(int key)
582 return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
585 static char *get_user_key_map_seq(int key)
587 const char *kma = get_user_key_map_arg(key);
588 const char *p = strchr(kma + 1, ':');
595 result = alloc(len + 1);
596 memcpy(result, kma, len);
601 static char *get_key_map_seq(int key)
603 return is_internal_key(key)?
604 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
607 static char *get_key_map_seq_safe(int key)
609 const char hex[] = "0123456789abcdef";
610 char *seq = get_key_map_seq(key), *sseq;
611 size_t n, len = strlen(seq);
613 if (len == 1 && isprint(*seq))
615 sseq = alloc(2 + 2 * len + 1);
618 for (n = 0; n < len; n++) {
619 uint8_t val = (seq[n] & 0xf0) >> 4;
620 sseq[2 + 2 * n] = hex[val];
622 sseq[2 + 2 * n + 1] = hex[val];
625 sseq[2 + 2 * n] = '\0';
629 static inline char *get_internal_key_map_cmd(int key)
631 return para_strdup(default_commands[get_internal_key_map_idx(key)]);
634 static char *get_user_key_map_cmd(int key)
636 const char *kma = get_user_key_map_arg(key);
637 const char *p = strchr(kma + 1, ':');
641 return para_strdup(p + 1);
644 static char *get_key_map_cmd(int key)
646 return is_internal_key(key)?
647 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
650 static char **get_mapped_keyseqs(void)
655 result = arr_alloc(NUM_MAPPED_KEYS + 1, sizeof(char *));
656 FOR_EACH_MAPPED_KEY(i) {
657 char *seq = get_key_map_seq(i);
664 static struct i9e_completer pp_completers[];
666 I9E_DUMMY_COMPLETER(jmp);
667 I9E_DUMMY_COMPLETER(next);
668 I9E_DUMMY_COMPLETER(prev);
669 I9E_DUMMY_COMPLETER(fg);
670 I9E_DUMMY_COMPLETER(bg);
671 I9E_DUMMY_COMPLETER(ls);
672 I9E_DUMMY_COMPLETER(info);
673 I9E_DUMMY_COMPLETER(play);
674 I9E_DUMMY_COMPLETER(pause);
675 I9E_DUMMY_COMPLETER(tasks);
676 I9E_DUMMY_COMPLETER(quit);
677 I9E_DUMMY_COMPLETER(ff);
679 static void help_completer(struct i9e_completion_info *ci,
680 struct i9e_completion_result *cr)
682 char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
684 if (ci->word[0] == '-') {
685 i9e_complete_option(opts, ci, cr);
688 cr->matches = i9e_complete_commands(ci->word, pp_completers);
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(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(void)
710 btr_remove_node(&pt->btrn);
713 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
714 const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
715 .handler = com_ ## _cmd \
718 static int com_quit(__a_unused struct lls_parse_result *lpr)
720 pt->rq = CRT_TERM_RQ;
723 EXPORT_PLAY_CMD_HANDLER(quit);
725 static int com_help(struct lls_parse_result *lpr)
731 const struct lls_opt_result *r =
732 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
733 bool long_help = lls_opt_given(r);
735 if (!pt->background) {
736 FOR_EACH_MAPPED_KEY(i) {
737 bool internal = is_internal_key(i);
738 int idx = get_key_map_idx(i);
739 char *seq = get_key_map_seq_safe(i);
740 char *kmc = get_key_map_cmd(i);
741 sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
742 internal? "internal" : "user-defined",
744 btr_add_output(buf, sz, pt->btrn);
750 lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
751 btr_add_output(buf, n, pt->btrn);
754 EXPORT_PLAY_CMD_HANDLER(help);
756 static int com_info(__a_unused struct lls_parse_result *lpr)
760 static char dflt[] = "[no information available]";
762 sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
763 pt->current_file, get_playlist_file(pt->current_file));
764 btr_add_output(buf, sz, pt->btrn);
765 buf = pt->afhi_txt? pt->afhi_txt : dflt;
766 btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
769 EXPORT_PLAY_CMD_HANDLER(info);
771 static void list_file(int num)
776 sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
777 "*" : " ", num, get_playlist_file(num));
778 btr_add_output(buf, sz, pt->btrn);
781 static int com_tasks(__a_unused struct lls_parse_result *lpr)
787 buf = get_task_list(&sched);
788 btr_add_output(buf, strlen(buf), pt->btrn);
789 state = get_playback_state();
790 sz = xasprintf(&buf, "state: %c\n", state);
791 btr_add_output(buf, sz, pt->btrn);
794 EXPORT_PLAY_CMD_HANDLER(tasks);
796 static int com_ls(__a_unused struct lls_parse_result *lpr)
799 unsigned num_inputs = lls_num_inputs(play_lpr);
801 for (i = 0; i < num_inputs; i++)
805 EXPORT_PLAY_CMD_HANDLER(ls);
807 static int com_play(struct lls_parse_result *lpr)
813 ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
816 PARA_ERROR_LOG("%s\n", errctx);
820 state = get_playback_state();
821 if (lls_num_inputs(lpr) == 0) {
824 pt->next_file = pt->current_file;
829 ret = para_atoi32(lls_input(0, lpr), &x);
832 if (x < 0 || x >= lls_num_inputs(play_lpr))
833 return -ERRNO_TO_PARA_ERROR(EINVAL);
836 pt->rq = CRT_FILE_CHANGE;
839 EXPORT_PLAY_CMD_HANDLER(play);
841 static int com_pause(__a_unused struct lls_parse_result *lpr)
845 unsigned long cn; /* chunk num */
847 state = get_playback_state();
851 ms = get_play_time();
855 cn = ms * pt->num_chunks / pt->seconds / 1000 + 1;
856 cn = PARA_MIN(cn, pt->num_chunks);
857 pt->start_chunk = cn;
862 EXPORT_PLAY_CMD_HANDLER(pause);
864 static int com_prev(__a_unused struct lls_parse_result *lpr)
868 ret = previous_valid_file();
873 pt->rq = CRT_FILE_CHANGE;
877 EXPORT_PLAY_CMD_HANDLER(prev);
879 static int com_next(__a_unused struct lls_parse_result *lpr)
883 ret = next_valid_file();
888 pt->rq = CRT_FILE_CHANGE;
892 EXPORT_PLAY_CMD_HANDLER(next);
894 static int com_fg(__a_unused struct lls_parse_result *lpr)
896 pt->background = false;
899 EXPORT_PLAY_CMD_HANDLER(fg);
901 static int com_bg(__a_unused struct lls_parse_result *lpr)
903 pt->background = true;
906 EXPORT_PLAY_CMD_HANDLER(bg);
908 static int com_jmp(struct lls_parse_result *lpr)
914 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
917 PARA_ERROR_LOG("%s\n", errctx);
921 ret = para_atoi32(lls_input(0, lpr), &percent);
924 if (percent < 0 || percent > 100)
925 return -ERRNO_TO_PARA_ERROR(EINVAL);
927 return com_next(NULL);
928 if (pt->playing && !pt->fn.btrn)
930 pt->start_chunk = percent * pt->num_chunks / 100;
937 EXPORT_PLAY_CMD_HANDLER(jmp);
939 static int com_ff(struct lls_parse_result *lpr)
945 ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
948 PARA_ERROR_LOG("%s\n", errctx);
952 ret = para_atoi32(lls_input(0, lpr), &seconds);
955 if (pt->playing && !pt->fn.btrn)
957 seconds += (get_play_time() + 500) / 1000;
958 seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
959 seconds = PARA_MAX(seconds, 0);
960 pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
961 pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
962 pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
969 EXPORT_PLAY_CMD_HANDLER(ff);
971 static int run_command(char *line)
976 const struct play_command_info *pci;
977 struct lls_parse_result *lpr;
978 const struct lls_command *cmd;
980 attach_stdout(__FUNCTION__);
981 ret = create_argv(line, " ", &argv);
987 ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
990 cmd = lls_cmd(ret, play_cmd_suite);
991 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
994 pci = lls_user_data(cmd);
995 ret = pci->handler(lpr);
996 lls_free_parse_result(lpr, cmd);
999 PARA_ERROR_LOG("%s\n", errctx);
1005 static int play_i9e_line_handler(char *line)
1007 return run_command(line);
1010 static int play_i9e_key_handler(int key)
1012 int idx = get_key_map_idx(key);
1013 char *seq = get_key_map_seq(key);
1014 char *cmd = get_key_map_cmd(key);
1015 bool internal = is_internal_key(key);
1017 PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1018 key, internal? "internal" : "user-defined",
1023 pt->next_update = *now;
1027 static struct i9e_client_info ici = {
1029 .prompt = "para_play> ",
1030 .line_handler = play_i9e_line_handler,
1031 .key_handler = play_i9e_key_handler,
1032 .completers = pp_completers,
1035 static void sigint_handler(int sig)
1037 pt->background = true;
1038 i9e_signal_dispatch(sig);
1042 * We start with para_log() set to the standard log function which writes to
1043 * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1046 static void session_open(void)
1050 struct sigaction act;
1052 PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1053 if (OPT_GIVEN(HISTORY_FILE))
1054 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1056 char *home = para_homedir();
1057 char *dot_para = make_message("%s/.paraslash", home);
1060 ret = para_mkdir(dot_para, 0777);
1061 /* warn, but otherwise ignore mkdir error */
1062 if (ret < 0 && ret != -ERRNO_TO_PARA_ERROR(EEXIST))
1063 PARA_WARNING_LOG("Can not create %s: %s\n", dot_para,
1064 para_strerror(-ret));
1065 history_file = make_message("%s/play.history", dot_para);
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.poll_function = i9e_poll;
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(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 i9e_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_monitor() rather than from i9e_post_monitor(), 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_monitor 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_monitor(__a_unused struct sched *s)
1129 attach_stdout(__FUNCTION__);
1130 ret = i9e_get_error();
1134 para_log = stderr_log;
1135 free(ici.history_file);
1138 if (get_playback_state() == 'X')
1139 i9e_signal_dispatch(SIGTERM);
1143 #else /* HAVE_READLINE */
1145 static int session_post_monitor(struct sched *s)
1149 if (!sched_read_ok(STDIN_FILENO, s))
1151 if (read(STDIN_FILENO, &c, 1))
1157 static void session_open(void)
1161 static void session_update_time_string(char *str, __a_unused unsigned len)
1163 printf("\r%s ", str);
1166 #endif /* HAVE_READLINE */
1168 static void play_pre_monitor(struct sched *s, __a_unused void *context)
1172 sched_monitor_readfd(STDIN_FILENO, s);
1173 state = get_playback_state();
1174 if (state == 'R' || state == 'F' || state == 'X')
1175 return sched_min_delay(s);
1176 sched_request_barrier_or_min_delay(&pt->next_update, s);
1179 static unsigned get_time_string(char **result)
1181 int seconds, length;
1182 char state = get_playback_state();
1184 /* do not return anything if things are about to change */
1185 if (state != 'P' && state != 'U') {
1189 length = pt->seconds;
1191 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1192 seconds = (get_play_time() + 500) / 1000;
1193 return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1197 (length - seconds) / 60,
1198 (length - seconds) % 60,
1199 length? (seconds * 100 + length / 2) / length : 0,
1202 get_playlist_file(pt->current_file)
1206 static int play_post_monitor(struct sched *s, __a_unused void *context)
1210 ret = eof_cleanup();
1212 pt->rq = CRT_TERM_RQ;
1215 ret = session_post_monitor(s);
1218 if (!pt->wn.btrn && !pt->fn.btrn) {
1219 char state = get_playback_state();
1220 if (state == 'P' || state == 'R' || state == 'F') {
1221 PARA_NOTICE_LOG("state: %c\n", state);
1222 ret = load_next_file();
1224 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1225 pt->rq = CRT_TERM_RQ;
1229 pt->next_update = *now;
1232 if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1234 unsigned len = get_time_string(&str);
1235 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1237 session_update_time_string(str, len);
1239 tv_add(now, &delay, &pt->next_update);
1247 * The main function of para_play.
1249 * \param argc Standard.
1250 * \param argv Standard.
1252 * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1254 int main(int argc, char *argv[])
1257 unsigned num_inputs;
1259 sched.default_timeout = 5000;
1260 parse_config_or_die(argc, argv);
1262 num_inputs = lls_num_inputs(play_lpr);
1264 pt->invalid = arr_zalloc(num_inputs, sizeof(*pt->invalid));
1265 pt->rq = CRT_FILE_CHANGE;
1267 pt->task = task_register(&(struct task_info){
1269 .pre_monitor = play_pre_monitor,
1270 .post_monitor = play_post_monitor,
1273 ret = schedule(&sched);
1274 sched_shutdown(&sched);
1276 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1277 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;