build: Don't create phony targets for dependencies.
[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 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(stop);
714 I9E_DUMMY_COMPLETER(tasks);
715 I9E_DUMMY_COMPLETER(quit);
716 I9E_DUMMY_COMPLETER(ff);
717
718 static void help_completer(struct i9e_completion_info *ci,
719                 struct i9e_completion_result *result)
720 {
721         result->matches = i9e_complete_commands(ci->word, pp_completers);
722 }
723
724 I9E_DUMMY_COMPLETER(SUPERCOMMAND_UNAVAILABLE);
725 static struct i9e_completer pp_completers[] = {
726 #define LSG_PLAY_CMD_CMD(_name) {.name = #_name, \
727         .completer = _name ## _completer}
728         LSG_PLAY_CMD_SUBCOMMANDS
729 #undef LSG_PLAY_CMD_CMD
730         {.name = NULL}
731 };
732
733 static void attach_stdout(struct play_task *pt, const char *name)
734 {
735         if (pt->btrn)
736                 return;
737         pt->btrn = btr_new_node(&(struct btr_node_description)
738                 EMBRACE(.name = name));
739         i9e_attach_to_stdout(pt->btrn);
740 }
741
742 static void detach_stdout(struct play_task *pt)
743 {
744         btr_remove_node(&pt->btrn);
745 }
746
747 static int com_quit(struct play_task *pt,
748                 __a_unused struct lls_parse_result *lpr)
749 {
750         pt->rq = CRT_TERM_RQ;
751         return 0;
752 }
753 EXPORT_PLAY_CMD_HANDLER(quit);
754
755 static int com_help(struct play_task *pt, struct lls_parse_result *lpr)
756 {
757         int i, ret;
758         char *buf, *errctx;
759         size_t sz;
760         const struct lls_command *cmd;
761
762         ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
763         if (ret < 0) {
764                 if (errctx)
765                         PARA_ERROR_LOG("%s\n", errctx);
766                 free(errctx);
767                 return ret;
768         }
769         if (lls_num_inputs(lpr) == 0) {
770                 if (pt->background) {
771                         for (i = 1; (cmd = lls_cmd(i, play_cmd_suite)); i++) {
772                                 sz = xasprintf(&buf, "%s\t%s\n",
773                                         lls_command_name(cmd), lls_purpose(cmd));
774                                 btr_add_output(buf, sz, pt->btrn);
775                         }
776                         return 0;
777                 }
778                 FOR_EACH_MAPPED_KEY(i) {
779                         bool internal = is_internal_key(i);
780                         int idx = get_key_map_idx(i);
781                         char *seq = get_key_map_seq_safe(i);
782                         char *kmc = get_key_map_cmd(i);
783                         sz = xasprintf(&buf, "%s key #%d: %s -> %s\n",
784                                 internal? "internal" : "user-defined",
785                                 idx, seq, kmc);
786                         btr_add_output(buf, sz, pt->btrn);
787                         free(seq);
788                         free(kmc);
789                 }
790                 return 0;
791         }
792         ret = lls(lls_lookup_subcmd(lls_input(0, lpr), play_cmd_suite,
793                 &errctx));
794         if (ret < 0) {
795                 if (errctx)
796                         PARA_ERROR_LOG("%s\n", errctx);
797                 free(errctx);
798                 return ret;
799         }
800         cmd = lls_cmd(ret, play_cmd_suite);
801         buf = lls_long_help(cmd);
802         assert(buf);
803         btr_add_output(buf, strlen(buf), pt->btrn);
804         return 0;
805 }
806 EXPORT_PLAY_CMD_HANDLER(help);
807
808 static int com_info(struct play_task *pt,
809                 __a_unused struct lls_parse_result *lpr)
810 {
811         char *buf;
812         size_t sz;
813         static char dflt[] = "[no information available]";
814
815         sz = xasprintf(&buf, "playlist_pos: %u\npath: %s\n",
816                 pt->current_file, get_playlist_file(pt->current_file));
817         btr_add_output(buf, sz, pt->btrn);
818         buf = pt->afhi_txt? pt->afhi_txt : dflt;
819         btr_add_output_dont_free(buf, strlen(buf), pt->btrn);
820         return 0;
821 }
822 EXPORT_PLAY_CMD_HANDLER(info);
823
824 static void list_file(struct play_task *pt, int num)
825 {
826         char *buf;
827         size_t sz;
828
829         sz = xasprintf(&buf, "%s %4d %s\n", num == pt->current_file?
830                 "*" : " ", num, get_playlist_file(num));
831         btr_add_output(buf, sz, pt->btrn);
832 }
833
834 static int com_tasks(struct play_task *pt,
835                 __a_unused struct lls_parse_result *lpr)
836 {
837         static char state;
838         char *buf;
839         size_t sz;
840
841         buf = get_task_list(&sched);
842         btr_add_output(buf, strlen(buf), pt->btrn);
843         state = get_playback_state(pt);
844         sz = xasprintf(&buf, "state: %c\n", state);
845         btr_add_output(buf, sz, pt->btrn);
846         return 0;
847 }
848 EXPORT_PLAY_CMD_HANDLER(tasks);
849
850 static int com_ls(struct play_task *pt,
851         __a_unused struct lls_parse_result *lpr)
852 {
853         int i;
854         unsigned num_inputs = lls_num_inputs(play_lpr);
855
856         for (i = 0; i < num_inputs; i++)
857                 list_file(pt, i);
858         return 0;
859 }
860 EXPORT_PLAY_CMD_HANDLER(ls);
861
862 static int com_play(struct play_task *pt, struct lls_parse_result *lpr)
863 {
864         int32_t x;
865         int ret;
866         char state, *errctx;
867
868         ret = lls(lls_check_arg_count(lpr, 0, 1, &errctx));
869         if (ret < 0) {
870                 if (errctx)
871                         PARA_ERROR_LOG("%s\n", errctx);
872                 free(errctx);
873                 return ret;
874         }
875         state = get_playback_state(pt);
876         if (lls_num_inputs(lpr) == 0) {
877                 if (state == 'P')
878                         return 0;
879                 pt->next_file = pt->current_file;
880                 pt->rq = CRT_REPOS;
881                 pt->playing = true;
882                 return 0;
883         }
884         ret = para_atoi32(lls_input(0, lpr), &x);
885         if (ret < 0)
886                 return ret;
887         if (x < 0 || x >= lls_num_inputs(play_lpr))
888                 return -ERRNO_TO_PARA_ERROR(EINVAL);
889         kill_stream(pt);
890         pt->next_file = x;
891         pt->rq = CRT_FILE_CHANGE;
892         return 0;
893 }
894 EXPORT_PLAY_CMD_HANDLER(play);
895
896 static int com_pause(struct play_task *pt,
897                 __a_unused struct lls_parse_result *lpr)
898 {
899         char state;
900         long unsigned seconds, ss;
901
902         state = get_playback_state(pt);
903         pt->playing = false;
904         if (state != 'P')
905                 return 0;
906         seconds = get_play_time(pt);
907         pt->playing = false;
908         ss = 0;
909         if (pt->seconds > 0)
910                 ss = seconds * pt->num_chunks / pt->seconds + 1;
911         ss = PARA_MAX(ss, 0UL);
912         ss = PARA_MIN(ss, pt->num_chunks);
913         pt->start_chunk = ss;
914         kill_stream(pt);
915         return 0;
916 }
917 EXPORT_PLAY_CMD_HANDLER(pause);
918
919 static int com_prev(struct play_task *pt,
920         __a_unused struct lls_parse_result *lpr)
921 {
922         int ret;
923
924         ret = previous_valid_file(pt);
925         if (ret < 0)
926                 return ret;
927         kill_stream(pt);
928         pt->next_file = ret;
929         pt->rq = CRT_FILE_CHANGE;
930         pt->start_chunk = 0;
931         return 0;
932 }
933 EXPORT_PLAY_CMD_HANDLER(prev);
934
935 static int com_next(struct play_task *pt,
936                 __a_unused struct lls_parse_result *lpr)
937 {
938         int ret;
939
940         ret = next_valid_file(pt);
941         if (ret < 0)
942                 return ret;
943         kill_stream(pt);
944         pt->next_file = ret;
945         pt->rq = CRT_FILE_CHANGE;
946         pt->start_chunk = 0;
947         return 0;
948 }
949 EXPORT_PLAY_CMD_HANDLER(next);
950
951 static int com_fg(struct play_task *pt,
952                 __a_unused struct lls_parse_result *lpr)
953 {
954         pt->background = false;
955         return 0;
956 }
957 EXPORT_PLAY_CMD_HANDLER(fg);
958
959 static int com_bg(struct play_task *pt,
960         __a_unused struct lls_parse_result *lpr)
961 {
962         pt->background = true;
963         return 0;
964 }
965 EXPORT_PLAY_CMD_HANDLER(bg);
966
967 static int com_jmp(struct play_task *pt, struct lls_parse_result *lpr)
968 {
969         int32_t percent;
970         int ret;
971         char *errctx;
972
973         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
974         if (ret < 0) {
975                 if (errctx)
976                         PARA_ERROR_LOG("%s\n", errctx);
977                 free(errctx);
978                 return ret;
979         }
980         ret = para_atoi32(lls_input(0, lpr), &percent);
981         if (ret < 0)
982                 return ret;
983         if (percent < 0 || percent > 100)
984                 return -ERRNO_TO_PARA_ERROR(EINVAL);
985         if (percent == 100)
986                 return com_next(pt, NULL);
987         if (pt->playing && !pt->fn.btrn)
988                 return 0;
989         pt->start_chunk = percent * pt->num_chunks / 100;
990         if (!pt->playing)
991                 return 0;
992         pt->rq = CRT_REPOS;
993         kill_stream(pt);
994         return 0;
995 }
996 EXPORT_PLAY_CMD_HANDLER(jmp);
997
998 static int com_ff(struct play_task *pt, struct lls_parse_result *lpr)
999 {
1000         int32_t seconds;
1001         char *errctx;
1002         int ret;
1003
1004         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
1005         if (ret < 0) {
1006                 if (errctx)
1007                         PARA_ERROR_LOG("%s\n", errctx);
1008                 free(errctx);
1009                 return ret;
1010         }
1011         ret = para_atoi32(lls_input(0, lpr), &seconds);
1012         if (ret < 0)
1013                 return ret;
1014         if (pt->playing && !pt->fn.btrn)
1015                 return 0;
1016         seconds += get_play_time(pt);
1017         seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
1018         seconds = PARA_MAX(seconds, 0);
1019         pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
1020         pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
1021         pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1022         if (!pt->playing)
1023                 return 0;
1024         pt->rq = CRT_REPOS;
1025         kill_stream(pt);
1026         return 0;
1027 }
1028 EXPORT_PLAY_CMD_HANDLER(ff);
1029
1030 static int run_command(char *line, struct play_task *pt)
1031 {
1032         int ret, argc;
1033         char **argv = NULL;
1034         char *errctx = NULL;
1035         const struct play_command_info *pci;
1036         struct lls_parse_result *lpr;
1037         const struct lls_command *cmd;
1038
1039         attach_stdout(pt, __FUNCTION__);
1040         ret = create_argv(line, " ", &argv);
1041         if (ret < 0)
1042                 goto out;
1043         if (ret == 0)
1044                 goto out;
1045         argc = ret;
1046         ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1047         if (ret < 0)
1048                 goto out;
1049         cmd = lls_cmd(ret, play_cmd_suite);
1050         ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1051         if (ret < 0)
1052                 goto out;
1053         pci = lls_user_data(cmd);
1054         ret = pci->handler(pt, lpr);
1055         lls_free_parse_result(lpr, cmd);
1056 out:
1057         if (errctx)
1058                 PARA_ERROR_LOG("%s\n", errctx);
1059         free(errctx);
1060         free_argv(argv);
1061         return ret;
1062 }
1063
1064 static int play_i9e_line_handler(char *line)
1065 {
1066         return run_command(line, &play_task);
1067 }
1068
1069 static int play_i9e_key_handler(int key)
1070 {
1071         struct play_task *pt = &play_task;
1072         int idx = get_key_map_idx(key);
1073         char *seq = get_key_map_seq(key);
1074         char *cmd = get_key_map_cmd(key);
1075         bool internal = is_internal_key(key);
1076
1077         PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1078                 key, internal? "internal" : "user-defined",
1079                 idx, seq, cmd);
1080         run_command(cmd, pt);
1081         free(seq);
1082         free(cmd);
1083         pt->next_update = *now;
1084         return 0;
1085 }
1086
1087 static struct i9e_client_info ici = {
1088         .fds = {0, 1, 2},
1089         .prompt = "para_play> ",
1090         .line_handler = play_i9e_line_handler,
1091         .key_handler = play_i9e_key_handler,
1092         .completers = pp_completers,
1093 };
1094
1095 static void sigint_handler(int sig)
1096 {
1097         play_task.background = true;
1098         i9e_signal_dispatch(sig);
1099 }
1100
1101 /*
1102  * We start with para_log() set to the standard log function which writes to
1103  * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1104  * log facility.
1105  */
1106 static void session_open(struct play_task *pt)
1107 {
1108         int ret;
1109         char *history_file;
1110         struct sigaction act;
1111
1112         PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1113         if (OPT_GIVEN(HISTORY_FILE))
1114                 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1115         else {
1116                 char *home = para_homedir();
1117                 history_file = make_message("%s/.paraslash/play.history",
1118                         home);
1119                 free(home);
1120         }
1121         ici.history_file = history_file;
1122         ici.loglevel = loglevel;
1123
1124         act.sa_handler = sigint_handler;
1125         sigemptyset(&act.sa_mask);
1126         act.sa_flags = 0;
1127         sigaction(SIGINT, &act, NULL);
1128         act.sa_handler = i9e_signal_dispatch;
1129         sigemptyset(&act.sa_mask);
1130         act.sa_flags = 0;
1131         sigaction(SIGWINCH, &act, NULL);
1132         sched.select_function = i9e_select;
1133
1134         ici.bound_keyseqs = get_mapped_keyseqs();
1135         pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1136                 EMBRACE(.name = __FUNCTION__));
1137         ret = i9e_open(&ici, &sched);
1138         if (ret < 0)
1139                 goto out;
1140         para_log = i9e_log;
1141         return;
1142 out:
1143         free(history_file);
1144         if (ret >= 0)
1145                 return;
1146         PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1147         exit(EXIT_FAILURE);
1148 }
1149
1150 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1151 {
1152         if (pt->background)
1153                 return;
1154         if (pt->btrn) {
1155                 if (btr_get_output_queue_size(pt->btrn) > 0)
1156                         return;
1157                 if (btr_get_input_queue_size(pt->btrn) > 0)
1158                         return;
1159         }
1160         ie9_print_status_bar(str, len);
1161 }
1162
1163 /*
1164  * If we are about to die we must call i9e_close() to reset the terminal.
1165  * However, i9e_close() must be called in *this* context, i.e. from
1166  * play_task.post_select() rather than from i9e_post_select(), because
1167  * otherwise i9e would access freed memory upon return. So the play task must
1168  * stay alive until the i9e task terminates.
1169  *
1170  * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1171  * and reschedule. In the next iteration, i9e->post_select returns an error and
1172  * terminates. Subsequent calls to i9e_get_error() then return negative and we
1173  * are allowed to call i9e_close() and terminate as well.
1174  */
1175 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1176 {
1177         int ret;
1178
1179         if (pt->background)
1180                 detach_stdout(pt);
1181         else
1182                 attach_stdout(pt, __FUNCTION__);
1183         ret = i9e_get_error();
1184         if (ret < 0) {
1185                 kill_stream(pt);
1186                 i9e_close();
1187                 para_log = stderr_log;
1188                 free(ici.history_file);
1189                 return ret;
1190         }
1191         if (get_playback_state(pt) == 'X')
1192                 i9e_signal_dispatch(SIGTERM);
1193         return 0;
1194 }
1195
1196 #else /* HAVE_READLINE */
1197
1198 static int session_post_select(struct sched *s, struct play_task *pt)
1199 {
1200         char c;
1201
1202         if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1203                 return 0;
1204         if (read(STDIN_FILENO, &c, 1))
1205                 do_nothing;
1206         kill_stream(pt);
1207         return 1;
1208 }
1209
1210 static void session_open(__a_unused struct play_task *pt)
1211 {
1212 }
1213
1214 static void session_update_time_string(__a_unused struct play_task *pt,
1215                 char *str, __a_unused unsigned len)
1216 {
1217         printf("\r%s     ", str);
1218         fflush(stdout);
1219 }
1220 #endif /* HAVE_READLINE */
1221
1222 static void play_pre_select(struct sched *s, void *context)
1223 {
1224         struct play_task *pt = context;
1225         char state;
1226
1227         para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1228         state = get_playback_state(pt);
1229         if (state == 'R' || state == 'F' || state == 'X')
1230                 return sched_min_delay(s);
1231         sched_request_barrier_or_min_delay(&pt->next_update, s);
1232 }
1233
1234 static unsigned get_time_string(struct play_task *pt, char **result)
1235 {
1236         int seconds, length;
1237         char state = get_playback_state(pt);
1238
1239         /* do not return anything if things are about to change */
1240         if (state != 'P' && state != 'U') {
1241                 *result = NULL;
1242                 return 0;
1243         }
1244         length = pt->seconds;
1245         if (length == 0)
1246                 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1247         seconds = get_play_time(pt);
1248         return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1249                 pt->current_file,
1250                 seconds / 60,
1251                 seconds % 60,
1252                 (length - seconds) / 60,
1253                 (length - seconds) % 60,
1254                 length? (seconds * 100 + length / 2) / length : 0,
1255                 length / 60,
1256                 length % 60,
1257                 get_playlist_file(pt->current_file)
1258         );
1259 }
1260
1261 static int play_post_select(struct sched *s, void *context)
1262 {
1263         struct play_task *pt = context;
1264         int ret;
1265
1266         ret = eof_cleanup(pt);
1267         if (ret < 0) {
1268                 pt->rq = CRT_TERM_RQ;
1269                 return 0;
1270         }
1271         ret = session_post_select(s, pt);
1272         if (ret < 0)
1273                 goto out;
1274         if (!pt->wn.btrn && !pt->fn.btrn) {
1275                 char state = get_playback_state(pt);
1276                 if (state == 'P' || state == 'R' || state == 'F') {
1277                         PARA_NOTICE_LOG("state: %c\n", state);
1278                         ret = load_next_file(pt);
1279                         if (ret < 0) {
1280                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1281                                 pt->rq = CRT_TERM_RQ;
1282                                 ret = 1;
1283                                 goto out;
1284                         }
1285                         pt->next_update = *now;
1286                 }
1287         }
1288         if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1289                 char *str;
1290                 unsigned len = get_time_string(pt, &str);
1291                 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1292                 if (str && len > 0)
1293                         session_update_time_string(pt, str, len);
1294                 free(str);
1295                 tv_add(now, &delay, &pt->next_update);
1296         }
1297         ret = 1;
1298 out:
1299         return ret;
1300 }
1301
1302 /**
1303  * The main function of para_play.
1304  *
1305  * \param argc Standard.
1306  * \param argv Standard.
1307  *
1308  * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1309  */
1310 int main(int argc, char *argv[])
1311 {
1312         int ret;
1313         struct play_task *pt = &play_task;
1314         unsigned num_inputs;
1315
1316         /* needed this early to make help work */
1317         recv_init();
1318
1319         sched.default_timeout.tv_sec = 5;
1320         parse_config_or_die(argc, argv);
1321         AFH_RECV->init();
1322         session_open(pt);
1323         num_inputs = lls_num_inputs(play_lpr);
1324         init_shuffle_map();
1325         pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1326         pt->rq = CRT_FILE_CHANGE;
1327         pt->current_file = num_inputs - 1;
1328         pt->playing = true;
1329         pt->task = task_register(&(struct task_info){
1330                 .name = "play",
1331                 .pre_select = play_pre_select,
1332                 .post_select = play_post_select,
1333                 .context = pt,
1334         }, &sched);
1335         ret = schedule(&sched);
1336         sched_shutdown(&sched);
1337         if (ret < 0)
1338                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1339         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1340 }