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