]> git.tuebingen.mpg.de Git - paraslash.git/blob - play.c
Merge topic branch t/sf_float into pu
[paraslash.git] / play.c
1 /* Copyright (C) 2012 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file play.c Paraslash's standalone player. */
4
5 #include <regex.h>
6 #include <signal.h>
7 #include <lopsub.h>
8
9 #include "recv_cmd.lsg.h"
10 #include "filter_cmd.lsg.h"
11 #include "play_cmd.lsg.h"
12 #include "write_cmd.lsg.h"
13 #include "play.lsg.h"
14 #include "para.h"
15 #include "lsu.h"
16 #include "list.h"
17 #include "error.h"
18 #include "buffer_tree.h"
19 #include "version.h"
20 #include "string.h"
21 #include "sched.h"
22 #include "filter.h"
23 #include "afh.h"
24 #include "recv.h"
25 #include "write.h"
26 #include "fd.h"
27 #include "interactive.h"
28
29 /** Array of error strings. */
30 DEFINE_PARA_ERRLIST;
31
32 static struct lls_parse_result *play_lpr;
33
34 #define CMD_PTR (lls_cmd(0, play_suite))
35 #define OPT_RESULT(_name) \
36         (lls_opt_result(LSG_PLAY_PARA_PLAY_OPT_ ## _name, play_lpr))
37 #define OPT_GIVEN(_name) (lls_opt_given(OPT_RESULT(_name)))
38 #define OPT_UINT32_VAL(_name) (lls_uint32_val(0, OPT_RESULT(_name)))
39 #define OPT_STRING_VAL(_name) (lls_string_val(0, OPT_RESULT(_name)))
40
41 /**
42  * Describes a request to change the state of para_play.
43  *
44  * There is only one variable of this type: \a rq of the global play task
45  * structure. Command handlers only set this variable and the post_monitor()
46  * function of the play task investigates its value during each iteration of
47  * the scheduler run and performs the actual work.
48  */
49 enum state_change_request_type {
50         /** Everybody is happy. */
51         CRT_NONE,
52         /** Stream must be repositioned (com_jmp(), com_ff()). */
53         CRT_REPOS,
54         /** New file should be loaded (com_next()). */
55         CRT_FILE_CHANGE,
56         /** Someone wants us for dead (com_quit()). */
57         CRT_TERM_RQ
58 };
59
60 struct play_task {
61         struct task *task;
62         /* A bit array of invalid files (those will be skipped). */
63         bool *invalid;
64         /* The file which is currently open. */
65         unsigned current_file;
66         /* When to update the status again. */
67         struct timeval next_update;
68
69         /* Root of the buffer tree for command and status output. */
70         struct btr_node *btrn;
71
72         /* The decoding machinery.  */
73         struct receiver_node rn;
74         struct filter_node fn;
75         struct writer_node wn;
76
77         /* See comment to enum \ref state_change_request_type above. */
78         enum state_change_request_type rq;
79         /* only relevant if rq == CRT_FILE_CHANGE */
80         unsigned next_file;
81         /*
82                 bg: read lines at prompt, fg: display status and wait
83                 for keystroke.
84         */
85         bool background;
86
87         /* We have the *intention* to play. Set by com_play(). */
88         bool playing;
89
90         /* as returned by afh_recv->open() */
91         int audio_format_num;
92
93         /* retrieved via the btr exec mechanism */
94         long unsigned start_chunk;
95         long unsigned seconds;
96         long unsigned num_chunks;
97         char *afhi_txt;
98 };
99
100 typedef int (*play_cmd_handler_t)(struct lls_parse_result *lpr);
101 struct play_command_info {
102         play_cmd_handler_t handler;
103 };
104
105 static int loglevel = LL_WARNING;
106
107 /** The log function which writes log messages to stderr. */
108 INIT_STDERR_LOGGING(loglevel);
109
110 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
111
112 static struct sched sched;
113 static struct play_task play_task, *pt = &play_task;
114
115 #define AFH_RECV_CMD (lls_cmd(LSG_RECV_CMD_CMD_AFH, recv_cmd_suite))
116 #define AFH_RECV ((struct receiver *)lls_user_data(AFH_RECV_CMD))
117
118 static unsigned *shuffle_map;
119
120 static const char *get_playlist_file(unsigned idx)
121 {
122         return lls_input(shuffle_map[idx], play_lpr);
123 }
124
125 static void handle_help_flags(void)
126 {
127         char *help;
128
129         if (OPT_GIVEN(DETAILED_HELP))
130                 help = lls_long_help(CMD_PTR);
131         else if (OPT_GIVEN(HELP) || lls_num_inputs(play_lpr) == 0)
132                 help = lls_short_help(CMD_PTR);
133         else
134                 return;
135         printf("%s\n", help);
136         free(help);
137         exit(EXIT_SUCCESS);
138 }
139
140 static void parse_config_or_die(int argc, char *argv[])
141 {
142         int i, ret;
143         unsigned num_kmas;
144         char *errctx;
145
146         ret = lls(lls_parse(argc, argv, CMD_PTR, &play_lpr, &errctx));
147         if (ret < 0) {
148                 if (errctx)
149                         PARA_EMERG_LOG("%s\n", errctx);
150                 free(errctx);
151                 PARA_EMERG_LOG("failed to parse command line options: %s\n",
152                         para_strerror(-ret));
153                 exit(EXIT_FAILURE);
154         }
155         loglevel = OPT_UINT32_VAL(LOGLEVEL);
156         version_handle_flag("play", OPT_GIVEN(VERSION));
157         handle_help_flags(); /* also handles the zero-arg case */
158         ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
159                 "play.conf", &play_lpr, CMD_PTR, play_suite, 0 /* flags */);
160         if (ret < 0) {
161                 PARA_EMERG_LOG("failed to parse config file: %s\n",
162                         para_strerror(-ret));
163                 exit(EXIT_FAILURE);
164         }
165         loglevel = OPT_UINT32_VAL(LOGLEVEL);
166         num_kmas = OPT_GIVEN(KEY_MAP);
167         for (i = 0; i < num_kmas; i++) {
168                 const char *kma = lls_string_val(i, OPT_RESULT(KEY_MAP));
169                 if (*kma && strchr(kma + 1, ':'))
170                         continue;
171                 PARA_EMERG_LOG("invalid key map arg: %s\n", kma);
172                 exit(EXIT_FAILURE);
173         }
174 }
175
176 static char get_playback_state(void)
177 {
178         switch (pt->rq) {
179         case CRT_NONE: return pt->playing? 'P' : 'U';
180         case CRT_REPOS: return 'R';
181         case CRT_FILE_CHANGE: return 'F';
182         case CRT_TERM_RQ: return 'X';
183         }
184         assert(false);
185 };
186
187 /* returns number of milliseconds */
188 static long unsigned get_play_time(void)
189 {
190         char state = get_playback_state();
191         long unsigned result;
192
193         if (state != 'P' && state != 'U')
194                 return 0;
195         if (pt->num_chunks == 0 || pt->seconds == 0)
196                 return 0;
197         /* where the stream started (in milliseconds) */
198         result = 1000ULL * pt->start_chunk * pt->seconds / pt->num_chunks;
199         if (pt->wn.btrn) { /* Add the uptime of the writer node */
200                 struct timeval diff = {.tv_sec = 0}, wstime;
201                 btr_get_node_start(pt->wn.btrn, &wstime);
202                 if (wstime.tv_sec > 0)
203                         tv_diff(now, &wstime, &diff);
204                 result += tv2ms(&diff);
205         }
206         result = PARA_MIN(result, pt->seconds * 1000);
207         result = PARA_MAX(result, 0UL);
208         return result;
209 }
210
211 static void wipe_receiver_node(void)
212 {
213         PARA_NOTICE_LOG("cleaning up receiver node\n");
214         btr_remove_node(&pt->rn.btrn);
215         AFH_RECV->close(&pt->rn);
216         lls_free_parse_result(pt->rn.lpr, AFH_RECV_CMD);
217         memset(&pt->rn, 0, sizeof(struct receiver_node));
218 }
219
220 /* returns: 0 not eof, 1: eof, < 0: fatal error.  */
221 static int get_playback_error(void)
222 {
223         int err;
224
225         if (!pt->wn.task)
226                 return 1;
227         err = task_status(pt->wn.task);
228         if (err >= 0)
229                 return 0;
230         if (task_status(pt->fn.task) >= 0)
231                 return 0;
232         if (task_status(pt->rn.task) >= 0)
233                 return 0;
234         if (err == -E_EOF)
235                 return 1;
236         return err;
237 }
238
239 static int eof_cleanup(void)
240 {
241         const struct filter *decoder;
242         const struct writer *w = writer_get(-1); /* default writer */
243         int ret;
244
245         ret = get_playback_error();
246         if (ret == 0)
247                 return ret;
248         PARA_NOTICE_LOG("cleaning up wn/fn nodes\n");
249         task_reap(&pt->wn.task);
250         w->close(&pt->wn);
251         btr_remove_node(&pt->wn.btrn);
252         lls_free_parse_result(pt->wn.lpr, WRITE_CMD(pt->wn.wid));
253         memset(&pt->wn, 0, sizeof(struct writer_node));
254
255         decoder = filter_get(pt->fn.filter_num);
256         task_reap(&pt->fn.task);
257         if (decoder && decoder->close)
258                 decoder->close(&pt->fn);
259         btr_remove_node(&pt->fn.btrn);
260         lls_free_parse_result(pt->fn.lpr, FILTER_CMD(pt->fn.filter_num));
261         free(pt->fn.conf);
262         memset(&pt->fn, 0, sizeof(struct filter_node));
263
264         task_reap(&pt->rn.task);
265         btr_remove_node(&pt->rn.btrn);
266         /*
267          * On eof (ret > 0), we do not wipe the receiver node struct until a
268          * new file is loaded because we still need it for jumping around when
269          * paused.
270          */
271         if (ret < 0)
272                 wipe_receiver_node();
273         return ret;
274 }
275
276 static int shuffle_compare(__a_unused const void *a, __a_unused const void *b)
277 {
278         return para_random(100) - 50;
279 }
280
281 static void init_shuffle_map(void)
282 {
283         unsigned n, num_inputs = lls_num_inputs(play_lpr);
284         shuffle_map = arr_alloc(num_inputs, sizeof(unsigned));
285         for (n = 0; n < num_inputs; n++)
286                 shuffle_map[n] = n;
287         if (!OPT_GIVEN(RANDOMIZE))
288                 return;
289         srandom(time(NULL));
290         qsort(shuffle_map, num_inputs, sizeof(unsigned), shuffle_compare);
291 }
292
293 static struct btr_node *new_recv_btrn(struct receiver_node *rn)
294 {
295         return btr_new_node(&(struct btr_node_description)
296                 EMBRACE(.name = lls_command_name(AFH_RECV_CMD), .context = rn,
297                         .handler = AFH_RECV->execute));
298 }
299
300 static int open_new_file(void)
301 {
302         int ret;
303         const char *path = get_playlist_file(pt->next_file);
304         char *tmp = para_strdup(path), *errctx;
305         char *argv[] = {"play", "-f", tmp, "-b", "0", NULL};
306
307         PARA_NOTICE_LOG("next file: %s\n", path);
308         wipe_receiver_node();
309         pt->start_chunk = 0;
310         pt->rn.btrn = new_recv_btrn(&pt->rn);
311         ret = lls(lls_parse(ARRAY_SIZE(argv) - 1, argv, AFH_RECV_CMD,
312                 &pt->rn.lpr, &errctx));
313         free(tmp);
314         assert(ret >= 0);
315         pt->rn.receiver = AFH_RECV;
316         ret = AFH_RECV->open(&pt->rn);
317         if (ret < 0) {
318                 PARA_ERROR_LOG("could not open %s\n", path);
319                 goto fail;
320         }
321         pt->audio_format_num = ret;
322         free(pt->afhi_txt);
323         ret = btr_exec_up(pt->rn.btrn, "afhi", &pt->afhi_txt);
324         if (ret < 0)
325                 pt->afhi_txt = make_message("[afhi command failed]\n");
326         ret = btr_exec_up(pt->rn.btrn, "seconds_total", &tmp);
327         if (ret < 0)
328                 pt->seconds = 1;
329         else {
330                 int32_t x;
331                 ret = para_atoi32(tmp, &x);
332                 pt->seconds = ret < 0? 1 : x;
333                 free(tmp);
334                 tmp = NULL;
335         }
336         ret = btr_exec_up(pt->rn.btrn, "chunks_total", &tmp);
337         if (ret < 0)
338                 pt->num_chunks = 1;
339         else {
340                 int32_t x;
341                 ret = para_atoi32(tmp, &x);
342                 pt->num_chunks = ret < 0? 1 : x;
343                 free(tmp);
344                 tmp = NULL;
345         }
346         return 1;
347 fail:
348         wipe_receiver_node();
349         return ret;
350 }
351
352 static int load_file(void)
353 {
354         const char *af;
355         char *tmp, buf[20];
356         int ret;
357         const struct filter *decoder;
358         static struct lls_parse_result *filter_lpr, *writer_lpr;
359
360         btr_remove_node(&pt->rn.btrn);
361         if (!pt->rn.receiver || pt->next_file != pt->current_file) {
362                 ret = open_new_file();
363                 if (ret < 0)
364                         return ret;
365         } else {
366                 pt->rn.btrn = new_recv_btrn(&pt->rn);
367                 sprintf(buf, "repos %lu", pt->start_chunk);
368                 ret = btr_exec_up(pt->rn.btrn, buf, &tmp);
369                 if (ret < 0)
370                         PARA_CRIT_LOG("repos failed: %s\n", para_strerror(-ret));
371                 freep(&tmp);
372         }
373         if (!pt->playing)
374                 return 0;
375         /* set up decoding filter */
376         af = audio_format_name(pt->audio_format_num);
377         tmp = make_message("%sdec", af);
378         ret = filter_setup(tmp, &pt->fn.conf, &filter_lpr);
379         freep(&tmp);
380         if (ret < 0)
381                 goto fail;
382         pt->fn.filter_num = ret;
383         pt->fn.lpr = filter_lpr;
384         decoder = filter_get(ret);
385         pt->fn.btrn = btr_new_node(&(struct btr_node_description)
386                 EMBRACE(.name = filter_name(pt->fn.filter_num),
387                         .parent = pt->rn.btrn, .handler = decoder->execute,
388                         .context = &pt->fn));
389         if (decoder->open)
390                 decoder->open(&pt->fn);
391         PARA_INFO_LOG("buffer tree:\n");
392         btr_log_tree(pt->rn.btrn, LL_INFO);
393
394         /* setup default writer */
395         pt->wn.wid = check_writer_arg_or_die(NULL, &writer_lpr);
396         pt->wn.lpr = writer_lpr;
397         /* success, register tasks */
398         pt->rn.task = task_register(
399                 &(struct task_info) {
400                         .name = lls_command_name(AFH_RECV_CMD),
401                         .pre_monitor = AFH_RECV->pre_monitor,
402                         .post_monitor = AFH_RECV->post_monitor,
403                         .context = &pt->rn
404                 }, &sched);
405         sprintf(buf, "%s decoder", af);
406         pt->fn.task = task_register(
407                 &(struct task_info) {
408                         .name = buf,
409                         .pre_monitor = decoder->pre_monitor,
410                         .post_monitor = decoder->post_monitor,
411                         .context = &pt->fn
412                 }, &sched);
413         register_writer_node(&pt->wn, pt->fn.btrn, &sched);
414         return 1;
415 fail:
416         wipe_receiver_node();
417         return ret;
418 }
419
420 static int next_valid_file(void)
421 {
422         int i, j = pt->current_file;
423         unsigned num_inputs = lls_num_inputs(play_lpr);
424
425         if (j == num_inputs - 1) {
426                 switch (OPT_UINT32_VAL(END_OF_PLAYLIST)) {
427                 case EOP_LOOP: break;
428                 case EOP_STOP:
429                         pt->playing = false;
430                         return 0;
431                 case EOP_QUIT: return -E_EOP;
432                 }
433         }
434         for (i = 0; i < num_inputs; i++) {
435                 j = (j + 1) % num_inputs;
436                 if (!pt->invalid[j])
437                         return j;
438         }
439         return -E_NO_VALID_FILES;
440 }
441
442 static int load_next_file(void)
443 {
444         int ret;
445
446 again:
447         if (pt->rq == CRT_NONE) {
448                 pt->start_chunk = 0;
449                 ret = next_valid_file();
450                 if (ret < 0)
451                         return ret;
452                 pt->next_file = ret;
453         } else if (pt->rq == CRT_REPOS)
454                 pt->next_file = pt->current_file;
455         ret = load_file();
456         if (ret < 0) {
457                 PARA_ERROR_LOG("%s: marking file as invalid\n",
458                         para_strerror(-ret));
459                 pt->invalid[pt->next_file] = true;
460                 pt->rq = CRT_NONE;
461                 goto again;
462         }
463         pt->current_file = pt->next_file;
464         pt->rq = CRT_NONE;
465         return ret;
466 }
467
468 static void kill_stream(void)
469 {
470         if (pt->wn.task)
471                 task_notify(pt->wn.task, E_EOF);
472 }
473
474 /* only called from com_prev(), nec. only if we have readline */
475 static int previous_valid_file(void)
476 {
477         int i, j = pt->current_file;
478         unsigned num_inputs = lls_num_inputs(play_lpr);
479
480         for (i = 0; i < num_inputs; i++) {
481                 j--;
482                 if (j < 0)
483                         j = num_inputs - 1;
484                 if (!pt->invalid[j])
485                         return j;
486         }
487         return -E_NO_VALID_FILES;
488 }
489
490 /*
491  * Define the default (internal) key mappings and helper functions to get the
492  * key sequence or the command from a key id, which is what we obtain from
493  * i9e/readline when the key is pressed.
494  *
495  * In some of these helper functions we could return pointers to the constant
496  * arrays defined below. However, for others we can not, so let's better be
497  * consistent and allocate all returned strings on the heap.
498  */
499
500 #define INTERNAL_KEYMAP_ENTRIES \
501         KEYMAP_ENTRY("^", "jmp 0"), \
502         KEYMAP_ENTRY("1", "jmp 10"), \
503         KEYMAP_ENTRY("2", "jmp 21"), \
504         KEYMAP_ENTRY("3", "jmp 32"), \
505         KEYMAP_ENTRY("4", "jmp 43"), \
506         KEYMAP_ENTRY("5", "jmp 54"), \
507         KEYMAP_ENTRY("6", "jmp 65"), \
508         KEYMAP_ENTRY("7", "jmp 76"), \
509         KEYMAP_ENTRY("8", "jmp 87"), \
510         KEYMAP_ENTRY("9", "jmp 98"), \
511         KEYMAP_ENTRY("+", "next"), \
512         KEYMAP_ENTRY("-", "prev"), \
513         KEYMAP_ENTRY(":", "bg"), \
514         KEYMAP_ENTRY("i", "info"), \
515         KEYMAP_ENTRY("l", "ls"), \
516         KEYMAP_ENTRY("s", "play"), \
517         KEYMAP_ENTRY("p", "pause"), \
518         KEYMAP_ENTRY("q", "quit"), \
519         KEYMAP_ENTRY("?", "help"), \
520         KEYMAP_ENTRY("\033[D", "ff -10"), \
521         KEYMAP_ENTRY("\033[C", "ff 10"), \
522         KEYMAP_ENTRY("\033[A", "ff 60"), \
523         KEYMAP_ENTRY("\033[B", "ff -60"), \
524
525 #define KEYMAP_ENTRY(a, b) a
526 static const char *default_keyseqs[] = {INTERNAL_KEYMAP_ENTRIES};
527 #undef KEYMAP_ENTRY
528 #define KEYMAP_ENTRY(a, b) b
529 static const char *default_commands[] = {INTERNAL_KEYMAP_ENTRIES};
530 #undef KEYMAP_ENTRY
531 #define NUM_INTERNALLY_MAPPED_KEYS ARRAY_SIZE(default_commands)
532 #define NUM_MAPPED_KEYS (NUM_INTERNALLY_MAPPED_KEYS + OPT_GIVEN(KEY_MAP))
533 #define FOR_EACH_MAPPED_KEY(i) for (i = 0; i < NUM_MAPPED_KEYS; i++)
534
535 static inline bool is_internal_key(int key)
536 {
537         return key < NUM_INTERNALLY_MAPPED_KEYS;
538 }
539
540 /* for internal keys, the key id is just the array index. */
541 static inline int get_internal_key_map_idx(int key)
542 {
543         assert(is_internal_key(key));
544         return key;
545 }
546
547 /*
548  * For user-defined keys, we have to subtract NUM_INTERNALLY_MAPPED_KEYS. The
549  * difference is the index to the array of user defined key maps.
550  */
551 static inline int get_user_key_map_idx(int key)
552 {
553         assert(!is_internal_key(key));
554         return key - NUM_INTERNALLY_MAPPED_KEYS;
555 }
556
557 static inline int get_key_map_idx(int key)
558 {
559         return is_internal_key(key)?
560                 get_internal_key_map_idx(key) : get_user_key_map_idx(key);
561 }
562
563 static inline const char *get_user_key_map_arg(int key)
564 {
565         return lls_string_val(get_user_key_map_idx(key), OPT_RESULT(KEY_MAP));
566 }
567
568 static inline char *get_internal_key_map_seq(int key)
569 {
570         return para_strdup(default_keyseqs[get_internal_key_map_idx(key)]);
571 }
572
573 static char *get_key_map_seq(int key)
574 {
575         const char *kma, *p;
576         char *result;
577         int len;
578
579         if (is_internal_key(key))
580                 return get_internal_key_map_seq(key);
581         kma = get_user_key_map_arg(key);
582         p = strchr(kma + 1, ':');
583         assert(p); /* We checked earlier that kma contains a colon */
584         len = p - kma;
585         result = alloc(len + 1);
586         memcpy(result, kma, len);
587         result[len] = '\0';
588         return result;
589 }
590
591 static char *get_key_map_seq_safe(int key)
592 {
593         const char hex[] = "0123456789abcdef";
594         char *seq = get_key_map_seq(key), *sseq;
595         size_t n, len = strlen(seq);
596
597         if (len == 1 && isprint(*seq))
598                 return seq;
599         sseq = alloc(2 + 2 * len + 1);
600         sseq[0] = '0';
601         sseq[1] = 'x';
602         for (n = 0; n < len; n++) {
603                 uint8_t val = (seq[n] & 0xf0) >> 4;
604                 sseq[2 + 2 * n] = hex[val];
605                 val = seq[n] & 0xf;
606                 sseq[2 + 2 * n + 1] = hex[val];
607         }
608         free(seq);
609         sseq[2 + 2 * n] = '\0';
610         return sseq;
611 }
612
613 static inline char *get_internal_key_map_cmd(int key)
614 {
615         return para_strdup(default_commands[get_internal_key_map_idx(key)]);
616 }
617
618 static char *get_user_key_map_cmd(int key)
619 {
620         const char *kma = get_user_key_map_arg(key);
621         const char *p = strchr(kma + 1, ':');
622
623         if (!p)
624                 return NULL;
625         return para_strdup(p + 1);
626 }
627
628 static char *get_key_map_cmd(int key)
629 {
630         return is_internal_key(key)?
631                 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
632 }
633
634 static char **get_mapped_keyseqs(void)
635 {
636         char **result;
637         int i;
638
639         result = arr_alloc(NUM_MAPPED_KEYS + 1, sizeof(char *));
640         FOR_EACH_MAPPED_KEY(i) {
641                 char *seq = get_key_map_seq(i);
642                 result[i] = seq;
643         }
644         result[i] = NULL;
645         return result;
646 }
647
648 static struct i9e_completer pp_completers[];
649
650 I9E_DUMMY_COMPLETER(jmp);
651 I9E_DUMMY_COMPLETER(next);
652 I9E_DUMMY_COMPLETER(prev);
653 I9E_DUMMY_COMPLETER(fg);
654 I9E_DUMMY_COMPLETER(bg);
655 I9E_DUMMY_COMPLETER(ls);
656 I9E_DUMMY_COMPLETER(info);
657 I9E_DUMMY_COMPLETER(play);
658 I9E_DUMMY_COMPLETER(pause);
659 I9E_DUMMY_COMPLETER(tasks);
660 I9E_DUMMY_COMPLETER(quit);
661 I9E_DUMMY_COMPLETER(ff);
662
663 static void help_completer(struct i9e_completion_info *ci,
664                 struct i9e_completion_result *cr)
665 {
666         char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
667
668         if (ci->word[0] == '-') {
669                 i9e_complete_option(opts, ci, cr);
670                 return;
671         }
672         cr->matches = i9e_complete_commands(ci->word, pp_completers);
673 }
674
675 static struct i9e_completer pp_completers[] = {
676 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
677         .completer = _name ## _completer}
678         LSG_PLAY_CMD_SUBCOMMANDS
679 #undef LSG_PLAY_CMD_CMD
680         {.name = NULL}
681 };
682
683 static void attach_stdout(const char *name)
684 {
685         if (pt->btrn)
686                 return;
687         pt->btrn = btr_new_node(&(struct btr_node_description)
688                 EMBRACE(.name = name));
689         i9e_attach_to_stdout(pt->btrn);
690 }
691
692 static void detach_stdout(void)
693 {
694         btr_remove_node(&pt->btrn);
695 }
696
697 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
698         const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
699                 .handler = com_ ## _cmd \
700         };
701
702 static int com_quit(__a_unused struct lls_parse_result *lpr)
703 {
704         pt->rq = CRT_TERM_RQ;
705         return 0;
706 }
707 EXPORT_PLAY_CMD_HANDLER(quit);
708
709 static int com_help(struct lls_parse_result *lpr)
710 {
711         int i;
712         char *buf;
713         size_t sz;
714         unsigned n;
715         const struct lls_opt_result *r =
716                 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
717         bool long_help = lls_opt_given(r);
718
719         if (!pt->background) {
720                 FOR_EACH_MAPPED_KEY(i) {
721                         bool internal = is_internal_key(i);
722                         int idx = get_key_map_idx(i);
723                         char *seq = get_key_map_seq_safe(i);
724                         char *kmc = get_key_map_cmd(i);
725                         sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
726                                 internal? "internal" : "user-defined",
727                                 idx, seq, kmc);
728                         btr_add_output(buf, sz, pt->btrn);
729                         free(seq);
730                         free(kmc);
731                 }
732                 return 0;
733         }
734         lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
735         btr_add_output(buf, n, pt->btrn);
736         return 0;
737 }
738 EXPORT_PLAY_CMD_HANDLER(help);
739
740 static int com_info(__a_unused struct lls_parse_result *lpr)
741 {
742         char *buf;
743         size_t sz;
744         static char dflt[] = "[no information available]";
745
746         sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
747                 pt->current_file, get_playlist_file(pt->current_file));
748         btr_add_output(buf, sz, pt->btrn);
749         buf = pt->afhi_txt? pt->afhi_txt : dflt;
750         btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
751         return 0;
752 }
753 EXPORT_PLAY_CMD_HANDLER(info);
754
755 static void list_file(int num)
756 {
757         char *buf;
758         size_t sz;
759
760         sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
761                 "*" : " ", num, get_playlist_file(num));
762         btr_add_output(buf, sz, pt->btrn);
763 }
764
765 static int com_tasks(__a_unused struct lls_parse_result *lpr)
766 {
767         static char state;
768         char *buf;
769         size_t sz;
770
771         buf = get_task_list(&sched);
772         btr_add_output(buf, strlen(buf), pt->btrn);
773         state = get_playback_state();
774         sz = xasprintf(&buf, "state: %c\n", state);
775         btr_add_output(buf, sz, pt->btrn);
776         return 0;
777 }
778 EXPORT_PLAY_CMD_HANDLER(tasks);
779
780 static int com_ls(__a_unused struct lls_parse_result *lpr)
781 {
782         int i;
783         unsigned num_inputs = lls_num_inputs(play_lpr);
784
785         for (i = 0; i < num_inputs; i++)
786                 list_file(i);
787         return 0;
788 }
789 EXPORT_PLAY_CMD_HANDLER(ls);
790
791 static int com_play(struct lls_parse_result *lpr)
792 {
793         int32_t x;
794         int ret;
795         char state, *errctx;
796
797         ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
798         if (ret < 0) {
799                 if (errctx)
800                         PARA_ERROR_LOG("%s\n", errctx);
801                 free(errctx);
802                 return ret;
803         }
804         state = get_playback_state();
805         if (lls_num_inputs(lpr) == 0) {
806                 if (state == 'P')
807                         return 0;
808                 pt->next_file = pt->current_file;
809                 pt->rq = CRT_REPOS;
810                 pt->playing = true;
811                 return 0;
812         }
813         ret = para_atoi32(lls_input(0, lpr), &x);
814         if (ret < 0)
815                 return ret;
816         if (x < 0 || x >= lls_num_inputs(play_lpr))
817                 return -ERRNO_TO_PARA_ERROR(EINVAL);
818         kill_stream();
819         pt->next_file = x;
820         pt->rq = CRT_FILE_CHANGE;
821         return 0;
822 }
823 EXPORT_PLAY_CMD_HANDLER(play);
824
825 static int com_pause(__a_unused struct lls_parse_result *lpr)
826 {
827         char state;
828         uint64_t ms;
829         unsigned long cn; /* chunk num */
830
831         state = get_playback_state();
832         pt->playing = false;
833         if (state != 'P')
834                 return 0;
835         ms = get_play_time();
836         pt->playing = false;
837         cn = 0;
838         if (pt->seconds > 0)
839                 cn = ms * pt->num_chunks / pt->seconds / 1000 + 1;
840         cn = PARA_MIN(cn, pt->num_chunks);
841         pt->start_chunk = cn;
842         pt->rq = CRT_REPOS;
843         kill_stream();
844         return 0;
845 }
846 EXPORT_PLAY_CMD_HANDLER(pause);
847
848 static int com_prev(__a_unused struct lls_parse_result *lpr)
849 {
850         int ret;
851
852         ret = previous_valid_file();
853         if (ret < 0)
854                 return ret;
855         kill_stream();
856         pt->next_file = ret;
857         pt->rq = CRT_FILE_CHANGE;
858         pt->start_chunk = 0;
859         return 0;
860 }
861 EXPORT_PLAY_CMD_HANDLER(prev);
862
863 static int com_next(__a_unused struct lls_parse_result *lpr)
864 {
865         int ret;
866
867         ret = next_valid_file();
868         if (ret < 0)
869                 return ret;
870         kill_stream();
871         pt->next_file = ret;
872         pt->rq = CRT_FILE_CHANGE;
873         pt->start_chunk = 0;
874         return 0;
875 }
876 EXPORT_PLAY_CMD_HANDLER(next);
877
878 static int com_fg(__a_unused struct lls_parse_result *lpr)
879 {
880         pt->background = false;
881         return 0;
882 }
883 EXPORT_PLAY_CMD_HANDLER(fg);
884
885 static int com_bg(__a_unused struct lls_parse_result *lpr)
886 {
887         pt->background = true;
888         return 0;
889 }
890 EXPORT_PLAY_CMD_HANDLER(bg);
891
892 static int com_jmp(struct lls_parse_result *lpr)
893 {
894         int32_t percent;
895         int ret;
896         char *errctx;
897
898         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
899         if (ret < 0) {
900                 if (errctx)
901                         PARA_ERROR_LOG("%s\n", errctx);
902                 free(errctx);
903                 return ret;
904         }
905         ret = para_atoi32(lls_input(0, lpr), &percent);
906         if (ret < 0)
907                 return ret;
908         if (percent < 0 || percent > 100)
909                 return -ERRNO_TO_PARA_ERROR(EINVAL);
910         if (percent == 100)
911                 return com_next(NULL);
912         if (pt->playing && !pt->fn.btrn)
913                 return 0;
914         pt->start_chunk = percent * pt->num_chunks / 100;
915         if (!pt->playing)
916                 return 0;
917         pt->rq = CRT_REPOS;
918         kill_stream();
919         return 0;
920 }
921 EXPORT_PLAY_CMD_HANDLER(jmp);
922
923 static int com_ff(struct lls_parse_result *lpr)
924 {
925         int32_t seconds;
926         char *errctx;
927         int ret;
928
929         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
930         if (ret < 0) {
931                 if (errctx)
932                         PARA_ERROR_LOG("%s\n", errctx);
933                 free(errctx);
934                 return ret;
935         }
936         ret = para_atoi32(lls_input(0, lpr), &seconds);
937         if (ret < 0)
938                 return ret;
939         if (pt->playing && !pt->fn.btrn)
940                 return 0;
941         seconds += (get_play_time() + 500) / 1000;
942         seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
943         seconds = PARA_MAX(seconds, 0);
944         pt->start_chunk = (uint64_t)pt->num_chunks * seconds / pt->seconds;
945         pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
946         pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
947         if (!pt->playing)
948                 return 0;
949         pt->rq = CRT_REPOS;
950         kill_stream();
951         return 0;
952 }
953 EXPORT_PLAY_CMD_HANDLER(ff);
954
955 static int run_command(char *line)
956 {
957         int ret, argc;
958         char **argv = NULL;
959         char *errctx = NULL;
960         const struct play_command_info *pci;
961         struct lls_parse_result *lpr;
962         const struct lls_command *cmd;
963
964         attach_stdout(__FUNCTION__);
965         ret = create_argv(line, " ", &argv);
966         if (ret < 0)
967                 goto out;
968         if (ret == 0)
969                 goto out;
970         argc = ret;
971         ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
972         if (ret < 0)
973                 goto out;
974         cmd = lls_cmd(ret, play_cmd_suite);
975         ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
976         if (ret < 0)
977                 goto out;
978         pci = lls_user_data(cmd);
979         ret = pci->handler(lpr);
980         lls_free_parse_result(lpr, cmd);
981 out:
982         if (errctx)
983                 PARA_ERROR_LOG("%s\n", errctx);
984         free(errctx);
985         free_argv(argv);
986         return ret;
987 }
988
989 static int play_i9e_line_handler(char *line)
990 {
991         return run_command(line);
992 }
993
994 static int play_i9e_key_handler(int key)
995 {
996         int idx = get_key_map_idx(key);
997         char *seq = get_key_map_seq(key);
998         char *cmd = get_key_map_cmd(key);
999         bool internal = is_internal_key(key);
1000
1001         PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1002                 key, internal? "internal" : "user-defined",
1003                 idx, seq, cmd);
1004         run_command(cmd);
1005         free(seq);
1006         free(cmd);
1007         pt->next_update = *now;
1008         return 0;
1009 }
1010
1011 static struct i9e_client_info ici = {
1012         .fds = {0, 1, 2},
1013         .prompt = "para_play> ",
1014         .line_handler = play_i9e_line_handler,
1015         .key_handler = play_i9e_key_handler,
1016         .completers = pp_completers,
1017 };
1018
1019 static void sigint_handler(int sig)
1020 {
1021         pt->background = true;
1022         i9e_signal_dispatch(sig);
1023 }
1024
1025 /*
1026  * We start with para_log() set to the standard log function which writes to
1027  * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1028  * log facility.
1029  */
1030 static void session_open(void)
1031 {
1032         int ret;
1033         char *history_file;
1034         struct sigaction act;
1035
1036         PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1037         if (OPT_GIVEN(HISTORY_FILE))
1038                 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1039         else {
1040                 const char *confdir = get_confdir();
1041
1042                 ret = para_mkdir(confdir);
1043                 /* warn, but otherwise ignore mkdir error */
1044                 if (ret < 0)
1045                         PARA_WARNING_LOG("Can not create %s: %s\n", confdir,
1046                                 para_strerror(-ret));
1047                 history_file = make_message("%s/play.history", confdir);
1048         }
1049         ici.history_file = history_file;
1050         ici.loglevel = loglevel;
1051
1052         act.sa_handler = sigint_handler;
1053         sigemptyset(&act.sa_mask);
1054         act.sa_flags = 0;
1055         sigaction(SIGINT, &act, NULL);
1056         act.sa_handler = i9e_signal_dispatch;
1057         sigemptyset(&act.sa_mask);
1058         act.sa_flags = 0;
1059         sigaction(SIGWINCH, &act, NULL);
1060         sched.poll_function = i9e_poll;
1061
1062         ici.bound_keyseqs = get_mapped_keyseqs();
1063         pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1064                 EMBRACE(.name = __FUNCTION__));
1065         ret = i9e_open(&ici, &sched);
1066         if (ret < 0)
1067                 goto out;
1068         para_log = i9e_log;
1069         return;
1070 out:
1071         free(history_file);
1072         if (ret >= 0)
1073                 return;
1074         PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1075         exit(EXIT_FAILURE);
1076 }
1077
1078 static void session_update_time_string(char *str, unsigned len)
1079 {
1080         if (pt->background)
1081                 return;
1082         if (pt->btrn) {
1083                 if (btr_get_output_queue_size(pt->btrn) > 0)
1084                         return;
1085                 if (btr_get_input_queue_size(pt->btrn) > 0)
1086                         return;
1087         }
1088         i9e_print_status_bar(str, len);
1089 }
1090
1091 static void play_pre_monitor(struct sched *s, __a_unused void *context)
1092 {
1093         char state;
1094
1095         sched_monitor_readfd(STDIN_FILENO, s);
1096         state = get_playback_state();
1097         if (state == 'R' || state == 'F' || state == 'X')
1098                 return sched_min_delay(s);
1099         sched_request_barrier_or_min_delay(&pt->next_update, s);
1100 }
1101
1102 static unsigned get_time_string(char **result)
1103 {
1104         int seconds, length;
1105         char state = get_playback_state();
1106
1107         /* do not return anything if things are about to change */
1108         if (state != 'P' && state != 'U') {
1109                 *result = NULL;
1110                 return 0;
1111         }
1112         length = pt->seconds;
1113         if (length == 0)
1114                 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1115         seconds = (get_play_time() + 500) / 1000;
1116         return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1117                 pt->current_file,
1118                 seconds / 60,
1119                 seconds % 60,
1120                 (length - seconds) / 60,
1121                 (length - seconds) % 60,
1122                 length? (seconds * 100 + length / 2) / length : 0,
1123                 length / 60,
1124                 length % 60,
1125                 get_playlist_file(pt->current_file)
1126         );
1127 }
1128
1129 static int play_post_monitor(__a_unused struct sched *s, __a_unused void *context)
1130 {
1131         int ret, i9e_error;
1132
1133         if (pt->background)
1134                 detach_stdout();
1135         else
1136                 attach_stdout(__FUNCTION__);
1137         i9e_error = i9e_get_error();
1138         ret = eof_cleanup();
1139         if (pt->rq == CRT_TERM_RQ || i9e_error < 0) /* com_quit() or CTRL+D */
1140                 kill_stream(); /* terminate receiver/filter/writer */
1141         if ((ret < 0 || pt->rq == CRT_TERM_RQ) && i9e_error >= 0)
1142                 i9e_signal_dispatch(SIGTERM); /* terminate the i9e task */
1143         if (ret < 0) /* unexpected error from the writer node */
1144                 return ret;
1145         if (ret != 0 && i9e_error < 0) /* eof, and i9e has died */
1146                 return i9e_error;
1147         if (!pt->wn.btrn && !pt->fn.btrn) {
1148                 char state = get_playback_state();
1149                 if (state == 'P' || state == 'R' || state == 'F') {
1150                         PARA_NOTICE_LOG("state: %c\n", state);
1151                         ret = load_next_file();
1152                         if (ret < 0) {
1153                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1154                                 pt->rq = CRT_TERM_RQ;
1155                                 return 1;
1156                         }
1157                         pt->next_update = *now;
1158                 }
1159         }
1160         if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1161                 char *str;
1162                 unsigned len = get_time_string(&str);
1163                 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1164                 if (str && len > 0)
1165                         session_update_time_string(str, len);
1166                 free(str);
1167                 tv_add(now, &delay, &pt->next_update);
1168         }
1169         return 1;
1170 }
1171
1172 /**
1173  * The main function of para_play.
1174  *
1175  * \param argc See man page.
1176  * \param argv See man page.
1177  *
1178  * para_play distributes its work by submitting various tasks to the paraslash
1179  * scheduler. The receiver, filter and writer tasks, which are used to play an
1180  * audio file, require one task each to maintain their underlying buffer tree
1181  * node. These tasks only exist when an audio file is playing.
1182  *
1183  * The i9 task, which is submitted and maintained by the i9e subsystem, reads
1184  * an input line and calls the corresponding command handler such as com_stop()
1185  * which is implemented in this file. The command handlers typically write a
1186  * request to the global play_task structure, whose contents are read and acted
1187  * upon by another task, the play task.
1188  *
1189  * As a rule, playlist handling is performed exclusively in play context, i.e.
1190  * in the post-monitor step of the play task, while command handlers are only
1191  * called in i9e context.
1192  *
1193  * \return EXIT_FAILURE or EXIT_SUCCESS.
1194  */
1195 int main(int argc, char *argv[])
1196 {
1197         int ret;
1198         unsigned num_inputs;
1199
1200         sched.default_timeout = 5000;
1201         parse_config_or_die(argc, argv);
1202         session_open();
1203         num_inputs = lls_num_inputs(play_lpr);
1204         init_shuffle_map();
1205         pt->invalid = arr_zalloc(num_inputs, sizeof(*pt->invalid));
1206         pt->rq = CRT_FILE_CHANGE;
1207         pt->playing = true;
1208         pt->task = task_register(&(struct task_info){
1209                 .name = "play",
1210                 .pre_monitor = play_pre_monitor,
1211                 .post_monitor = play_post_monitor,
1212                 .context = pt,
1213         }, &sched);
1214         ret = schedule(&sched);
1215         sched_shutdown(&sched);
1216         i9e_close();
1217         wipe_receiver_node();
1218         para_log = stderr_log;
1219         free(ici.history_file);
1220         if (ret < 0)
1221                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1222         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1223 }