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