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