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