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