]> git.tuebingen.mpg.de Git - paraslash.git/blob - play.c
4f734a3f729c526b8b319edbf2a477c636e2abe6
[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_user_key_map_seq(int key)
574 {
575         const char *kma = get_user_key_map_arg(key);
576         const char *p = strchr(kma + 1, ':');
577         char *result;
578         int len;
579
580         if (!p)
581                 return NULL;
582         len = p - kma;
583         result = alloc(len + 1);
584         memcpy(result, kma, len);
585         result[len] = '\0';
586         return result;
587 }
588
589 static char *get_key_map_seq(int key)
590 {
591         return is_internal_key(key)?
592                 get_internal_key_map_seq(key) : get_user_key_map_seq(key);
593 }
594
595 static char *get_key_map_seq_safe(int key)
596 {
597         const char hex[] = "0123456789abcdef";
598         char *seq = get_key_map_seq(key), *sseq;
599         size_t n, len = strlen(seq);
600
601         if (len == 1 && isprint(*seq))
602                 return seq;
603         sseq = alloc(2 + 2 * len + 1);
604         sseq[0] = '0';
605         sseq[1] = 'x';
606         for (n = 0; n < len; n++) {
607                 uint8_t val = (seq[n] & 0xf0) >> 4;
608                 sseq[2 + 2 * n] = hex[val];
609                 val = seq[n] & 0xf;
610                 sseq[2 + 2 * n + 1] = hex[val];
611         }
612         free(seq);
613         sseq[2 + 2 * n] = '\0';
614         return sseq;
615 }
616
617 static inline char *get_internal_key_map_cmd(int key)
618 {
619         return para_strdup(default_commands[get_internal_key_map_idx(key)]);
620 }
621
622 static char *get_user_key_map_cmd(int key)
623 {
624         const char *kma = get_user_key_map_arg(key);
625         const char *p = strchr(kma + 1, ':');
626
627         if (!p)
628                 return NULL;
629         return para_strdup(p + 1);
630 }
631
632 static char *get_key_map_cmd(int key)
633 {
634         return is_internal_key(key)?
635                 get_internal_key_map_cmd(key) : get_user_key_map_cmd(key);
636 }
637
638 static char **get_mapped_keyseqs(void)
639 {
640         char **result;
641         int i;
642
643         result = arr_alloc(NUM_MAPPED_KEYS + 1, sizeof(char *));
644         FOR_EACH_MAPPED_KEY(i) {
645                 char *seq = get_key_map_seq(i);
646                 result[i] = seq;
647         }
648         result[i] = NULL;
649         return result;
650 }
651
652 static struct i9e_completer pp_completers[];
653
654 I9E_DUMMY_COMPLETER(jmp);
655 I9E_DUMMY_COMPLETER(next);
656 I9E_DUMMY_COMPLETER(prev);
657 I9E_DUMMY_COMPLETER(fg);
658 I9E_DUMMY_COMPLETER(bg);
659 I9E_DUMMY_COMPLETER(ls);
660 I9E_DUMMY_COMPLETER(info);
661 I9E_DUMMY_COMPLETER(play);
662 I9E_DUMMY_COMPLETER(pause);
663 I9E_DUMMY_COMPLETER(tasks);
664 I9E_DUMMY_COMPLETER(quit);
665 I9E_DUMMY_COMPLETER(ff);
666
667 static void help_completer(struct i9e_completion_info *ci,
668                 struct i9e_completion_result *cr)
669 {
670         char *opts[] = {LSG_PLAY_CMD_HELP_OPTS, NULL};
671
672         if (ci->word[0] == '-') {
673                 i9e_complete_option(opts, ci, cr);
674                 return;
675         }
676         cr->matches = i9e_complete_commands(ci->word, pp_completers);
677 }
678
679 static struct i9e_completer pp_completers[] = {
680 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
681         .completer = _name ## _completer}
682         LSG_PLAY_CMD_SUBCOMMANDS
683 #undef LSG_PLAY_CMD_CMD
684         {.name = NULL}
685 };
686
687 static void attach_stdout(const char *name)
688 {
689         if (pt->btrn)
690                 return;
691         pt->btrn = btr_new_node(&(struct btr_node_description)
692                 EMBRACE(.name = name));
693         i9e_attach_to_stdout(pt->btrn);
694 }
695
696 static void detach_stdout(void)
697 {
698         btr_remove_node(&pt->btrn);
699 }
700
701 #define EXPORT_PLAY_CMD_HANDLER(_cmd) \
702         const struct play_command_info lsg_play_cmd_com_ ## _cmd ## _user_data = { \
703                 .handler = com_ ## _cmd \
704         };
705
706 static int com_quit(__a_unused struct lls_parse_result *lpr)
707 {
708         pt->rq = CRT_TERM_RQ;
709         return 0;
710 }
711 EXPORT_PLAY_CMD_HANDLER(quit);
712
713 static int com_help(struct lls_parse_result *lpr)
714 {
715         int i;
716         char *buf;
717         size_t sz;
718         unsigned n;
719         const struct lls_opt_result *r =
720                 lls_opt_result(LSG_PLAY_CMD_HELP_OPT_LONG, lpr);
721         bool long_help = lls_opt_given(r);
722
723         if (!pt->background) {
724                 FOR_EACH_MAPPED_KEY(i) {
725                         bool internal = is_internal_key(i);
726                         int idx = get_key_map_idx(i);
727                         char *seq = get_key_map_seq_safe(i);
728                         char *kmc = get_key_map_cmd(i);
729                         sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
730                                 internal? "internal" : "user-defined",
731                                 idx, seq, kmc);
732                         btr_add_output(buf, sz, pt->btrn);
733                         free(seq);
734                         free(kmc);
735                 }
736                 return 0;
737         }
738         lsu_com_help(long_help, lpr, play_cmd_suite, NULL, &buf, &n);
739         btr_add_output(buf, n, pt->btrn);
740         return 0;
741 }
742 EXPORT_PLAY_CMD_HANDLER(help);
743
744 static int com_info(__a_unused struct lls_parse_result *lpr)
745 {
746         char *buf;
747         size_t sz;
748         static char dflt[] = "[no information available]";
749
750         sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
751                 pt->current_file, get_playlist_file(pt->current_file));
752         btr_add_output(buf, sz, pt->btrn);
753         buf = pt->afhi_txt? pt->afhi_txt : dflt;
754         btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
755         return 0;
756 }
757 EXPORT_PLAY_CMD_HANDLER(info);
758
759 static void list_file(int num)
760 {
761         char *buf;
762         size_t sz;
763
764         sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
765                 "*" : " ", num, get_playlist_file(num));
766         btr_add_output(buf, sz, pt->btrn);
767 }
768
769 static int com_tasks(__a_unused struct lls_parse_result *lpr)
770 {
771         static char state;
772         char *buf;
773         size_t sz;
774
775         buf = get_task_list(&sched);
776         btr_add_output(buf, strlen(buf), pt->btrn);
777         state = get_playback_state();
778         sz = xasprintf(&buf, "state: %c\n", state);
779         btr_add_output(buf, sz, pt->btrn);
780         return 0;
781 }
782 EXPORT_PLAY_CMD_HANDLER(tasks);
783
784 static int com_ls(__a_unused struct lls_parse_result *lpr)
785 {
786         int i;
787         unsigned num_inputs = lls_num_inputs(play_lpr);
788
789         for (i = 0; i < num_inputs; i++)
790                 list_file(i);
791         return 0;
792 }
793 EXPORT_PLAY_CMD_HANDLER(ls);
794
795 static int com_play(struct lls_parse_result *lpr)
796 {
797         int32_t x;
798         int ret;
799         char state, *errctx;
800
801         ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
802         if (ret < 0) {
803                 if (errctx)
804                         PARA_ERROR_LOG("%s\n", errctx);
805                 free(errctx);
806                 return ret;
807         }
808         state = get_playback_state();
809         if (lls_num_inputs(lpr) == 0) {
810                 if (state == 'P')
811                         return 0;
812                 pt->next_file = pt->current_file;
813                 pt->rq = CRT_REPOS;
814                 pt->playing = true;
815                 return 0;
816         }
817         ret = para_atoi32(lls_input(0, lpr), &x);
818         if (ret < 0)
819                 return ret;
820         if (x < 0 || x >= lls_num_inputs(play_lpr))
821                 return -ERRNO_TO_PARA_ERROR(EINVAL);
822         kill_stream();
823         pt->next_file = x;
824         pt->rq = CRT_FILE_CHANGE;
825         return 0;
826 }
827 EXPORT_PLAY_CMD_HANDLER(play);
828
829 static int com_pause(__a_unused struct lls_parse_result *lpr)
830 {
831         char state;
832         uint64_t ms;
833         unsigned long cn; /* chunk num */
834
835         state = get_playback_state();
836         pt->playing = false;
837         if (state != 'P')
838                 return 0;
839         ms = get_play_time();
840         pt->playing = false;
841         cn = 0;
842         if (pt->seconds > 0)
843                 cn = ms * pt->num_chunks / pt->seconds / 1000 + 1;
844         cn = PARA_MIN(cn, pt->num_chunks);
845         pt->start_chunk = cn;
846         pt->rq = CRT_REPOS;
847         kill_stream();
848         return 0;
849 }
850 EXPORT_PLAY_CMD_HANDLER(pause);
851
852 static int com_prev(__a_unused struct lls_parse_result *lpr)
853 {
854         int ret;
855
856         ret = previous_valid_file();
857         if (ret < 0)
858                 return ret;
859         kill_stream();
860         pt->next_file = ret;
861         pt->rq = CRT_FILE_CHANGE;
862         pt->start_chunk = 0;
863         return 0;
864 }
865 EXPORT_PLAY_CMD_HANDLER(prev);
866
867 static int com_next(__a_unused struct lls_parse_result *lpr)
868 {
869         int ret;
870
871         ret = next_valid_file();
872         if (ret < 0)
873                 return ret;
874         kill_stream();
875         pt->next_file = ret;
876         pt->rq = CRT_FILE_CHANGE;
877         pt->start_chunk = 0;
878         return 0;
879 }
880 EXPORT_PLAY_CMD_HANDLER(next);
881
882 static int com_fg(__a_unused struct lls_parse_result *lpr)
883 {
884         pt->background = false;
885         return 0;
886 }
887 EXPORT_PLAY_CMD_HANDLER(fg);
888
889 static int com_bg(__a_unused struct lls_parse_result *lpr)
890 {
891         pt->background = true;
892         return 0;
893 }
894 EXPORT_PLAY_CMD_HANDLER(bg);
895
896 static int com_jmp(struct lls_parse_result *lpr)
897 {
898         int32_t percent;
899         int ret;
900         char *errctx;
901
902         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
903         if (ret < 0) {
904                 if (errctx)
905                         PARA_ERROR_LOG("%s\n", errctx);
906                 free(errctx);
907                 return ret;
908         }
909         ret = para_atoi32(lls_input(0, lpr), &percent);
910         if (ret < 0)
911                 return ret;
912         if (percent < 0 || percent > 100)
913                 return -ERRNO_TO_PARA_ERROR(EINVAL);
914         if (percent == 100)
915                 return com_next(NULL);
916         if (pt->playing && !pt->fn.btrn)
917                 return 0;
918         pt->start_chunk = percent * pt->num_chunks / 100;
919         if (!pt->playing)
920                 return 0;
921         pt->rq = CRT_REPOS;
922         kill_stream();
923         return 0;
924 }
925 EXPORT_PLAY_CMD_HANDLER(jmp);
926
927 static int com_ff(struct lls_parse_result *lpr)
928 {
929         int32_t seconds;
930         char *errctx;
931         int ret;
932
933         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
934         if (ret < 0) {
935                 if (errctx)
936                         PARA_ERROR_LOG("%s\n", errctx);
937                 free(errctx);
938                 return ret;
939         }
940         ret = para_atoi32(lls_input(0, lpr), &seconds);
941         if (ret < 0)
942                 return ret;
943         if (pt->playing && !pt->fn.btrn)
944                 return 0;
945         seconds += (get_play_time() + 500) / 1000;
946         seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
947         seconds = PARA_MAX(seconds, 0);
948         pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
949         pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
950         pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
951         if (!pt->playing)
952                 return 0;
953         pt->rq = CRT_REPOS;
954         kill_stream();
955         return 0;
956 }
957 EXPORT_PLAY_CMD_HANDLER(ff);
958
959 static int run_command(char *line)
960 {
961         int ret, argc;
962         char **argv = NULL;
963         char *errctx = NULL;
964         const struct play_command_info *pci;
965         struct lls_parse_result *lpr;
966         const struct lls_command *cmd;
967
968         attach_stdout(__FUNCTION__);
969         ret = create_argv(line, " ", &argv);
970         if (ret < 0)
971                 goto out;
972         if (ret == 0)
973                 goto out;
974         argc = ret;
975         ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
976         if (ret < 0)
977                 goto out;
978         cmd = lls_cmd(ret, play_cmd_suite);
979         ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
980         if (ret < 0)
981                 goto out;
982         pci = lls_user_data(cmd);
983         ret = pci->handler(lpr);
984         lls_free_parse_result(lpr, cmd);
985 out:
986         if (errctx)
987                 PARA_ERROR_LOG("%s\n", errctx);
988         free(errctx);
989         free_argv(argv);
990         return ret;
991 }
992
993 static int play_i9e_line_handler(char *line)
994 {
995         return run_command(line);
996 }
997
998 static int play_i9e_key_handler(int key)
999 {
1000         int idx = get_key_map_idx(key);
1001         char *seq = get_key_map_seq(key);
1002         char *cmd = get_key_map_cmd(key);
1003         bool internal = is_internal_key(key);
1004
1005         PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1006                 key, internal? "internal" : "user-defined",
1007                 idx, seq, cmd);
1008         run_command(cmd);
1009         free(seq);
1010         free(cmd);
1011         pt->next_update = *now;
1012         return 0;
1013 }
1014
1015 static struct i9e_client_info ici = {
1016         .fds = {0, 1, 2},
1017         .prompt = "para_play> ",
1018         .line_handler = play_i9e_line_handler,
1019         .key_handler = play_i9e_key_handler,
1020         .completers = pp_completers,
1021 };
1022
1023 static void sigint_handler(int sig)
1024 {
1025         pt->background = true;
1026         i9e_signal_dispatch(sig);
1027 }
1028
1029 /*
1030  * We start with para_log() set to the standard log function which writes to
1031  * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1032  * log facility.
1033  */
1034 static void session_open(void)
1035 {
1036         int ret;
1037         char *history_file;
1038         struct sigaction act;
1039
1040         PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1041         if (OPT_GIVEN(HISTORY_FILE))
1042                 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1043         else {
1044                 char *home = para_homedir();
1045                 char *dot_para = make_message("%s/.paraslash", home);
1046
1047                 free(home);
1048                 ret = para_mkdir(dot_para);
1049                 /* warn, but otherwise ignore mkdir error */
1050                 if (ret < 0)
1051                         PARA_WARNING_LOG("Can not create %s: %s\n", dot_para,
1052                                 para_strerror(-ret));
1053                 history_file = make_message("%s/play.history", dot_para);
1054                 free(dot_para);
1055         }
1056         ici.history_file = history_file;
1057         ici.loglevel = loglevel;
1058
1059         act.sa_handler = sigint_handler;
1060         sigemptyset(&act.sa_mask);
1061         act.sa_flags = 0;
1062         sigaction(SIGINT, &act, NULL);
1063         act.sa_handler = i9e_signal_dispatch;
1064         sigemptyset(&act.sa_mask);
1065         act.sa_flags = 0;
1066         sigaction(SIGWINCH, &act, NULL);
1067         sched.poll_function = i9e_poll;
1068
1069         ici.bound_keyseqs = get_mapped_keyseqs();
1070         pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1071                 EMBRACE(.name = __FUNCTION__));
1072         ret = i9e_open(&ici, &sched);
1073         if (ret < 0)
1074                 goto out;
1075         para_log = i9e_log;
1076         return;
1077 out:
1078         free(history_file);
1079         if (ret >= 0)
1080                 return;
1081         PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1082         exit(EXIT_FAILURE);
1083 }
1084
1085 static void session_update_time_string(char *str, unsigned len)
1086 {
1087         if (pt->background)
1088                 return;
1089         if (pt->btrn) {
1090                 if (btr_get_output_queue_size(pt->btrn) > 0)
1091                         return;
1092                 if (btr_get_input_queue_size(pt->btrn) > 0)
1093                         return;
1094         }
1095         i9e_print_status_bar(str, len);
1096 }
1097
1098 /*
1099  * If we are about to die we must call i9e_close() to reset the terminal.
1100  * However, i9e_close() must be called in *this* context, i.e. from
1101  * play_task.post_monitor() rather than from i9e_post_monitor(), because
1102  * otherwise i9e would access freed memory upon return. So the play task must
1103  * stay alive until the i9e task terminates.
1104  *
1105  * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1106  * and reschedule. In the next iteration, i9e->post_monitor returns an error and
1107  * terminates. Subsequent calls to i9e_get_error() then return negative and we
1108  * are allowed to call i9e_close() and terminate as well.
1109  */
1110 static int session_post_monitor(__a_unused struct sched *s)
1111 {
1112         int ret;
1113
1114         if (pt->background)
1115                 detach_stdout();
1116         else
1117                 attach_stdout(__FUNCTION__);
1118         ret = i9e_get_error();
1119         if (ret < 0) {
1120                 kill_stream();
1121                 i9e_close();
1122                 para_log = stderr_log;
1123                 free(ici.history_file);
1124                 return ret;
1125         }
1126         if (get_playback_state() == 'X')
1127                 i9e_signal_dispatch(SIGTERM);
1128         return 0;
1129 }
1130
1131 static void play_pre_monitor(struct sched *s, __a_unused void *context)
1132 {
1133         char state;
1134
1135         sched_monitor_readfd(STDIN_FILENO, s);
1136         state = get_playback_state();
1137         if (state == 'R' || state == 'F' || state == 'X')
1138                 return sched_min_delay(s);
1139         sched_request_barrier_or_min_delay(&pt->next_update, s);
1140 }
1141
1142 static unsigned get_time_string(char **result)
1143 {
1144         int seconds, length;
1145         char state = get_playback_state();
1146
1147         /* do not return anything if things are about to change */
1148         if (state != 'P' && state != 'U') {
1149                 *result = NULL;
1150                 return 0;
1151         }
1152         length = pt->seconds;
1153         if (length == 0)
1154                 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1155         seconds = (get_play_time() + 500) / 1000;
1156         return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1157                 pt->current_file,
1158                 seconds / 60,
1159                 seconds % 60,
1160                 (length - seconds) / 60,
1161                 (length - seconds) % 60,
1162                 length? (seconds * 100 + length / 2) / length : 0,
1163                 length / 60,
1164                 length % 60,
1165                 get_playlist_file(pt->current_file)
1166         );
1167 }
1168
1169 static int play_post_monitor(struct sched *s, __a_unused void *context)
1170 {
1171         int ret;
1172
1173         ret = eof_cleanup();
1174         if (ret < 0) {
1175                 pt->rq = CRT_TERM_RQ;
1176                 return 0;
1177         }
1178         ret = session_post_monitor(s);
1179         if (ret < 0)
1180                 goto out;
1181         if (!pt->wn.btrn && !pt->fn.btrn) {
1182                 char state = get_playback_state();
1183                 if (state == 'P' || state == 'R' || state == 'F') {
1184                         PARA_NOTICE_LOG("state: %c\n", state);
1185                         ret = load_next_file();
1186                         if (ret < 0) {
1187                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1188                                 pt->rq = CRT_TERM_RQ;
1189                                 ret = 1;
1190                                 goto out;
1191                         }
1192                         pt->next_update = *now;
1193                 }
1194         }
1195         if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1196                 char *str;
1197                 unsigned len = get_time_string(&str);
1198                 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1199                 if (str && len > 0)
1200                         session_update_time_string(str, len);
1201                 free(str);
1202                 tv_add(now, &delay, &pt->next_update);
1203         }
1204         ret = 1;
1205 out:
1206         return ret;
1207 }
1208
1209 /**
1210  * The main function of para_play.
1211  *
1212  * \param argc See man page.
1213  * \param argv See man page.
1214  *
1215  * para_play distributes its work by submitting various tasks to the paraslash
1216  * scheduler. The receiver, filter and writer tasks, which are used to play an
1217  * audio file, require one task each to maintain their underlying buffer tree
1218  * node. These tasks only exist when an audio file is playing.
1219  *
1220  * The i9 task, which is submitted and maintained by the i9e subsystem, reads
1221  * an input line and calls the corresponding command handler such as com_stop()
1222  * which is implemented in this file. The command handlers typically write a
1223  * request to the global play_task structure, whose contents are read and acted
1224  * upon by another task, the play task.
1225  *
1226  * As a rule, playlist handling is performed exclusively in play context, i.e.
1227  * in the post-monitor step of the play task, while command handlers are only
1228  * called in i9e context.
1229  *
1230  * \return EXIT_FAILURE or EXIT_SUCCESS.
1231  */
1232 int main(int argc, char *argv[])
1233 {
1234         int ret;
1235         unsigned num_inputs;
1236
1237         sched.default_timeout = 5000;
1238         parse_config_or_die(argc, argv);
1239         session_open();
1240         num_inputs = lls_num_inputs(play_lpr);
1241         init_shuffle_map();
1242         pt->invalid = arr_zalloc(num_inputs, sizeof(*pt->invalid));
1243         pt->rq = CRT_FILE_CHANGE;
1244         pt->playing = true;
1245         pt->task = task_register(&(struct task_info){
1246                 .name = "play",
1247                 .pre_monitor = play_pre_monitor,
1248                 .post_monitor = play_post_monitor,
1249                 .context = pt,
1250         }, &sched);
1251         ret = schedule(&sched);
1252         sched_shutdown(&sched);
1253         if (ret < 0)
1254                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1255         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1256 }