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