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