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