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