]> git.tuebingen.mpg.de Git - paraslash.git/blob - play.c
interactive: Avoid select(2) in input_available().
[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         pt->rq = CRT_REPOS;
858         kill_stream();
859         return 0;
860 }
861 EXPORT_PLAY_CMD_HANDLER(pause);
862
863 static int com_prev(__a_unused struct lls_parse_result *lpr)
864 {
865         int ret;
866
867         ret = previous_valid_file();
868         if (ret < 0)
869                 return ret;
870         kill_stream();
871         pt->next_file = ret;
872         pt->rq = CRT_FILE_CHANGE;
873         pt->start_chunk = 0;
874         return 0;
875 }
876 EXPORT_PLAY_CMD_HANDLER(prev);
877
878 static int com_next(__a_unused struct lls_parse_result *lpr)
879 {
880         int ret;
881
882         ret = next_valid_file();
883         if (ret < 0)
884                 return ret;
885         kill_stream();
886         pt->next_file = ret;
887         pt->rq = CRT_FILE_CHANGE;
888         pt->start_chunk = 0;
889         return 0;
890 }
891 EXPORT_PLAY_CMD_HANDLER(next);
892
893 static int com_fg(__a_unused struct lls_parse_result *lpr)
894 {
895         pt->background = false;
896         return 0;
897 }
898 EXPORT_PLAY_CMD_HANDLER(fg);
899
900 static int com_bg(__a_unused struct lls_parse_result *lpr)
901 {
902         pt->background = true;
903         return 0;
904 }
905 EXPORT_PLAY_CMD_HANDLER(bg);
906
907 static int com_jmp(struct lls_parse_result *lpr)
908 {
909         int32_t percent;
910         int ret;
911         char *errctx;
912
913         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
914         if (ret < 0) {
915                 if (errctx)
916                         PARA_ERROR_LOG("%s\n", errctx);
917                 free(errctx);
918                 return ret;
919         }
920         ret = para_atoi32(lls_input(0, lpr), &percent);
921         if (ret < 0)
922                 return ret;
923         if (percent < 0 || percent > 100)
924                 return -ERRNO_TO_PARA_ERROR(EINVAL);
925         if (percent == 100)
926                 return com_next(NULL);
927         if (pt->playing && !pt->fn.btrn)
928                 return 0;
929         pt->start_chunk = percent * pt->num_chunks / 100;
930         if (!pt->playing)
931                 return 0;
932         pt->rq = CRT_REPOS;
933         kill_stream();
934         return 0;
935 }
936 EXPORT_PLAY_CMD_HANDLER(jmp);
937
938 static int com_ff(struct lls_parse_result *lpr)
939 {
940         int32_t seconds;
941         char *errctx;
942         int ret;
943
944         ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
945         if (ret < 0) {
946                 if (errctx)
947                         PARA_ERROR_LOG("%s\n", errctx);
948                 free(errctx);
949                 return ret;
950         }
951         ret = para_atoi32(lls_input(0, lpr), &seconds);
952         if (ret < 0)
953                 return ret;
954         if (pt->playing && !pt->fn.btrn)
955                 return 0;
956         seconds += get_play_time();
957         seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
958         seconds = PARA_MAX(seconds, 0);
959         pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
960         pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
961         pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
962         if (!pt->playing)
963                 return 0;
964         pt->rq = CRT_REPOS;
965         kill_stream();
966         return 0;
967 }
968 EXPORT_PLAY_CMD_HANDLER(ff);
969
970 static int run_command(char *line)
971 {
972         int ret, argc;
973         char **argv = NULL;
974         char *errctx = NULL;
975         const struct play_command_info *pci;
976         struct lls_parse_result *lpr;
977         const struct lls_command *cmd;
978
979         attach_stdout(__FUNCTION__);
980         ret = create_argv(line, " ", &argv);
981         if (ret < 0)
982                 goto out;
983         if (ret == 0)
984                 goto out;
985         argc = ret;
986         ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
987         if (ret < 0)
988                 goto out;
989         cmd = lls_cmd(ret, play_cmd_suite);
990         ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
991         if (ret < 0)
992                 goto out;
993         pci = lls_user_data(cmd);
994         ret = pci->handler(lpr);
995         lls_free_parse_result(lpr, cmd);
996 out:
997         if (errctx)
998                 PARA_ERROR_LOG("%s\n", errctx);
999         free(errctx);
1000         free_argv(argv);
1001         return ret;
1002 }
1003
1004 static int play_i9e_line_handler(char *line)
1005 {
1006         return run_command(line);
1007 }
1008
1009 static int play_i9e_key_handler(int key)
1010 {
1011         int idx = get_key_map_idx(key);
1012         char *seq = get_key_map_seq(key);
1013         char *cmd = get_key_map_cmd(key);
1014         bool internal = is_internal_key(key);
1015
1016         PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1017                 key, internal? "internal" : "user-defined",
1018                 idx, seq, cmd);
1019         run_command(cmd);
1020         free(seq);
1021         free(cmd);
1022         pt->next_update = *now;
1023         return 0;
1024 }
1025
1026 static struct i9e_client_info ici = {
1027         .fds = {0, 1, 2},
1028         .prompt = "para_play> ",
1029         .line_handler = play_i9e_line_handler,
1030         .key_handler = play_i9e_key_handler,
1031         .completers = pp_completers,
1032 };
1033
1034 static void sigint_handler(int sig)
1035 {
1036         pt->background = true;
1037         i9e_signal_dispatch(sig);
1038 }
1039
1040 /*
1041  * We start with para_log() set to the standard log function which writes to
1042  * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1043  * log facility.
1044  */
1045 static void session_open(void)
1046 {
1047         int ret;
1048         char *history_file;
1049         struct sigaction act;
1050
1051         PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1052         if (OPT_GIVEN(HISTORY_FILE))
1053                 history_file = para_strdup(OPT_STRING_VAL(HISTORY_FILE));
1054         else {
1055                 char *home = para_homedir();
1056                 char *dot_para = make_message("%s/.paraslash", home);
1057
1058                 free(home);
1059                 ret = para_mkdir(dot_para, 0777);
1060                 /* warn, but otherwise ignore mkdir error */
1061                 if (ret < 0 && ret != -ERRNO_TO_PARA_ERROR(EEXIST))
1062                         PARA_WARNING_LOG("Can not create %s: %s\n", dot_para,
1063                                 para_strerror(-ret));
1064                 history_file = make_message("%s/play.history", dot_para);
1065                 free(dot_para);
1066         }
1067         ici.history_file = history_file;
1068         ici.loglevel = loglevel;
1069
1070         act.sa_handler = sigint_handler;
1071         sigemptyset(&act.sa_mask);
1072         act.sa_flags = 0;
1073         sigaction(SIGINT, &act, NULL);
1074         act.sa_handler = i9e_signal_dispatch;
1075         sigemptyset(&act.sa_mask);
1076         act.sa_flags = 0;
1077         sigaction(SIGWINCH, &act, NULL);
1078         sched.select_function = i9e_select;
1079
1080         ici.bound_keyseqs = get_mapped_keyseqs();
1081         pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1082                 EMBRACE(.name = __FUNCTION__));
1083         ret = i9e_open(&ici, &sched);
1084         if (ret < 0)
1085                 goto out;
1086         para_log = i9e_log;
1087         return;
1088 out:
1089         free(history_file);
1090         if (ret >= 0)
1091                 return;
1092         PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1093         exit(EXIT_FAILURE);
1094 }
1095
1096 static void session_update_time_string(char *str, unsigned len)
1097 {
1098         if (pt->background)
1099                 return;
1100         if (pt->btrn) {
1101                 if (btr_get_output_queue_size(pt->btrn) > 0)
1102                         return;
1103                 if (btr_get_input_queue_size(pt->btrn) > 0)
1104                         return;
1105         }
1106         i9e_print_status_bar(str, len);
1107 }
1108
1109 /*
1110  * If we are about to die we must call i9e_close() to reset the terminal.
1111  * However, i9e_close() must be called in *this* context, i.e. from
1112  * play_task.post_select() rather than from i9e_post_select(), because
1113  * otherwise i9e would access freed memory upon return. So the play task must
1114  * stay alive until the i9e task terminates.
1115  *
1116  * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1117  * and reschedule. In the next iteration, i9e->post_select returns an error and
1118  * terminates. Subsequent calls to i9e_get_error() then return negative and we
1119  * are allowed to call i9e_close() and terminate as well.
1120  */
1121 static int session_post_select(__a_unused struct sched *s)
1122 {
1123         int ret;
1124
1125         if (pt->background)
1126                 detach_stdout();
1127         else
1128                 attach_stdout(__FUNCTION__);
1129         ret = i9e_get_error();
1130         if (ret < 0) {
1131                 kill_stream();
1132                 i9e_close();
1133                 para_log = stderr_log;
1134                 free(ici.history_file);
1135                 return ret;
1136         }
1137         if (get_playback_state() == 'X')
1138                 i9e_signal_dispatch(SIGTERM);
1139         return 0;
1140 }
1141
1142 #else /* HAVE_READLINE */
1143
1144 static int session_post_select(struct sched *s)
1145 {
1146         char c;
1147
1148         if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1149                 return 0;
1150         if (read(STDIN_FILENO, &c, 1))
1151                 do_nothing;
1152         kill_stream();
1153         return 1;
1154 }
1155
1156 static void session_open(void)
1157 {
1158 }
1159
1160 static void session_update_time_string(char *str, __a_unused unsigned len)
1161 {
1162         printf("\r%s     ", str);
1163         fflush(stdout);
1164 }
1165 #endif /* HAVE_READLINE */
1166
1167 static void play_pre_select(struct sched *s, __a_unused void *context)
1168 {
1169         char state;
1170
1171         para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1172         state = get_playback_state();
1173         if (state == 'R' || state == 'F' || state == 'X')
1174                 return sched_min_delay(s);
1175         sched_request_barrier_or_min_delay(&pt->next_update, s);
1176 }
1177
1178 static unsigned get_time_string(char **result)
1179 {
1180         int seconds, length;
1181         char state = get_playback_state();
1182
1183         /* do not return anything if things are about to change */
1184         if (state != 'P' && state != 'U') {
1185                 *result = NULL;
1186                 return 0;
1187         }
1188         length = pt->seconds;
1189         if (length == 0)
1190                 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1191         seconds = get_play_time();
1192         return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1193                 pt->current_file,
1194                 seconds / 60,
1195                 seconds % 60,
1196                 (length - seconds) / 60,
1197                 (length - seconds) % 60,
1198                 length? (seconds * 100 + length / 2) / length : 0,
1199                 length / 60,
1200                 length % 60,
1201                 get_playlist_file(pt->current_file)
1202         );
1203 }
1204
1205 static int play_post_select(struct sched *s, __a_unused void *context)
1206 {
1207         int ret;
1208
1209         ret = eof_cleanup();
1210         if (ret < 0) {
1211                 pt->rq = CRT_TERM_RQ;
1212                 return 0;
1213         }
1214         ret = session_post_select(s);
1215         if (ret < 0)
1216                 goto out;
1217         if (!pt->wn.btrn && !pt->fn.btrn) {
1218                 char state = get_playback_state();
1219                 if (state == 'P' || state == 'R' || state == 'F') {
1220                         PARA_NOTICE_LOG("state: %c\n", state);
1221                         ret = load_next_file();
1222                         if (ret < 0) {
1223                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1224                                 pt->rq = CRT_TERM_RQ;
1225                                 ret = 1;
1226                                 goto out;
1227                         }
1228                         pt->next_update = *now;
1229                 }
1230         }
1231         if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1232                 char *str;
1233                 unsigned len = get_time_string(&str);
1234                 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1235                 if (str && len > 0)
1236                         session_update_time_string(str, len);
1237                 free(str);
1238                 tv_add(now, &delay, &pt->next_update);
1239         }
1240         ret = 1;
1241 out:
1242         return ret;
1243 }
1244
1245 /**
1246  * The main function of para_play.
1247  *
1248  * \param argc Standard.
1249  * \param argv Standard.
1250  *
1251  * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1252  */
1253 int main(int argc, char *argv[])
1254 {
1255         int ret;
1256         unsigned num_inputs;
1257
1258         sched.default_timeout = 5000;
1259         parse_config_or_die(argc, argv);
1260         session_open();
1261         num_inputs = lls_num_inputs(play_lpr);
1262         init_shuffle_map();
1263         pt->invalid = para_calloc(sizeof(*pt->invalid) * num_inputs);
1264         pt->rq = CRT_FILE_CHANGE;
1265         pt->playing = true;
1266         pt->task = task_register(&(struct task_info){
1267                 .name = "play",
1268                 .pre_select = play_pre_select,
1269                 .post_select = play_post_select,
1270                 .context = pt,
1271         }, &sched);
1272         ret = schedule(&sched);
1273         sched_shutdown(&sched);
1274         if (ret < 0)
1275                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1276         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1277 }