play: Convert com_prev() 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, int argc, __a_unused char **argv)
951 {
952         if (argc != 1)
953                 return -E_PLAY_SYNTAX;
954         pt->background = true;
955         return 0;
956 }
957
958 static int com_jmp(struct play_task *pt, int argc, char **argv)
959 {
960         int32_t percent;
961         int ret;
962
963         if (argc != 2)
964                 return -E_PLAY_SYNTAX;
965         ret = para_atoi32(argv[1], &percent);
966         if (ret < 0)
967                 return ret;
968         if (percent < 0 || percent > 100)
969                 return -ERRNO_TO_PARA_ERROR(EINVAL);
970         if (percent == 100)
971                 return com_next(pt, NULL);
972         if (pt->playing && !pt->fn.btrn)
973                 return 0;
974         pt->start_chunk = percent * pt->num_chunks / 100;
975         if (!pt->playing)
976                 return 0;
977         pt->rq = CRT_REPOS;
978         kill_stream(pt);
979         return 0;
980 }
981
982 static int com_ff(struct play_task *pt, int argc, char **argv)
983 {
984         int32_t seconds;
985         int ret;
986
987         if (argc != 2)
988                 return -E_PLAY_SYNTAX;
989         ret = para_atoi32(argv[1], &seconds);
990         if (ret < 0)
991                 return ret;
992         if (pt->playing && !pt->fn.btrn)
993                 return 0;
994         seconds += get_play_time(pt);
995         seconds = PARA_MIN(seconds, (typeof(seconds))pt->seconds - 4);
996         seconds = PARA_MAX(seconds, 0);
997         pt->start_chunk = pt->num_chunks * seconds / pt->seconds;
998         pt->start_chunk = PARA_MIN(pt->start_chunk, pt->num_chunks - 1);
999         pt->start_chunk = PARA_MAX(pt->start_chunk, 0UL);
1000         if (!pt->playing)
1001                 return 0;
1002         pt->rq = CRT_REPOS;
1003         kill_stream(pt);
1004         return 0;
1005 }
1006
1007 static int run_command(char *line, struct play_task *pt)
1008 {
1009         int i, ret, argc;
1010         char **argv = NULL;
1011         char *errctx = NULL;
1012         const struct play_command_info *pci;
1013         struct lls_parse_result *lpr;
1014         const struct lls_command *cmd;
1015
1016         attach_stdout(pt, __FUNCTION__);
1017         ret = create_argv(line, " ", &argv);
1018         if (ret < 0)
1019                 goto out;
1020         if (ret == 0)
1021                 goto out;
1022         argc = ret;
1023
1024         ret = lls(lls_lookup_subcmd(argv[0], play_cmd_suite, &errctx));
1025         if (ret >= 0) {
1026                 cmd = lls_cmd(ret, play_cmd_suite);
1027                 ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
1028                 if (ret < 0)
1029                         goto out;
1030                 pci = lls_user_data(cmd);
1031                 ret = pci->handler(pt, lpr);
1032                 lls_free_parse_result(lpr, cmd);
1033         } else {
1034                 FOR_EACH_COMMAND(i) {
1035                         if (strcmp(pp_cmds[i].name, argv[0]))
1036                                 continue;
1037                         free(errctx);
1038                         errctx = NULL;
1039                         ret = pp_cmds[i].handler(pt, argc, argv);
1040                         break;
1041                 }
1042         }
1043 out:
1044         if (errctx)
1045                 PARA_ERROR_LOG("%s\n", errctx);
1046         free(errctx);
1047         free_argv(argv);
1048         return ret;
1049 }
1050
1051 static int play_i9e_line_handler(char *line)
1052 {
1053         return run_command(line, &play_task);
1054 }
1055
1056 static int play_i9e_key_handler(int key)
1057 {
1058         struct play_task *pt = &play_task;
1059         int idx = get_key_map_idx(key);
1060         char *seq = get_key_map_seq(key);
1061         char *cmd = get_key_map_cmd(key);
1062         bool internal = is_internal_key(key);
1063
1064         PARA_NOTICE_LOG("pressed %d: %s key #%d (%s -> %s)\n",
1065                 key, internal? "internal" : "user-defined",
1066                 idx, seq, cmd);
1067         run_command(cmd, pt);
1068         free(seq);
1069         free(cmd);
1070         pt->next_update = *now;
1071         return 0;
1072 }
1073
1074 static struct i9e_client_info ici = {
1075         .fds = {0, 1, 2},
1076         .prompt = "para_play> ",
1077         .line_handler = play_i9e_line_handler,
1078         .key_handler = play_i9e_key_handler,
1079         .completers = pp_completers,
1080 };
1081
1082 static void sigint_handler(int sig)
1083 {
1084         play_task.background = true;
1085         i9e_signal_dispatch(sig);
1086 }
1087
1088 /*
1089  * We start with para_log() set to the standard log function which writes to
1090  * stderr. Once the i9e subsystem has been initialized, we switch to the i9e
1091  * log facility.
1092  */
1093 static void session_open(struct play_task *pt)
1094 {
1095         int ret;
1096         char *history_file;
1097         struct sigaction act;
1098
1099         PARA_NOTICE_LOG("\n%s\n", version_text("play"));
1100         if (conf.history_file_given)
1101                 history_file = para_strdup(conf.history_file_arg);
1102         else {
1103                 char *home = para_homedir();
1104                 history_file = make_message("%s/.paraslash/play.history",
1105                         home);
1106                 free(home);
1107         }
1108         ici.history_file = history_file;
1109         ici.loglevel = loglevel;
1110
1111         act.sa_handler = sigint_handler;
1112         sigemptyset(&act.sa_mask);
1113         act.sa_flags = 0;
1114         sigaction(SIGINT, &act, NULL);
1115         act.sa_handler = i9e_signal_dispatch;
1116         sigemptyset(&act.sa_mask);
1117         act.sa_flags = 0;
1118         sigaction(SIGWINCH, &act, NULL);
1119         sched.select_function = i9e_select;
1120
1121         ici.bound_keyseqs = get_mapped_keyseqs();
1122         pt->btrn = ici.producer = btr_new_node(&(struct btr_node_description)
1123                 EMBRACE(.name = __FUNCTION__));
1124         ret = i9e_open(&ici, &sched);
1125         if (ret < 0)
1126                 goto out;
1127         para_log = i9e_log;
1128         return;
1129 out:
1130         free(history_file);
1131         if (ret >= 0)
1132                 return;
1133         PARA_EMERG_LOG("fatal: %s\n", para_strerror(-ret));
1134         exit(EXIT_FAILURE);
1135 }
1136
1137 static void session_update_time_string(struct play_task *pt, char *str, unsigned len)
1138 {
1139         if (pt->background)
1140                 return;
1141         if (pt->btrn) {
1142                 if (btr_get_output_queue_size(pt->btrn) > 0)
1143                         return;
1144                 if (btr_get_input_queue_size(pt->btrn) > 0)
1145                         return;
1146         }
1147         ie9_print_status_bar(str, len);
1148 }
1149
1150 /*
1151  * If we are about to die we must call i9e_close() to reset the terminal.
1152  * However, i9e_close() must be called in *this* context, i.e. from
1153  * play_task.post_select() rather than from i9e_post_select(), because
1154  * otherwise i9e would access freed memory upon return. So the play task must
1155  * stay alive until the i9e task terminates.
1156  *
1157  * We achieve this by sending a fake SIGTERM signal via i9e_signal_dispatch()
1158  * and reschedule. In the next iteration, i9e->post_select returns an error and
1159  * terminates. Subsequent calls to i9e_get_error() then return negative and we
1160  * are allowed to call i9e_close() and terminate as well.
1161  */
1162 static int session_post_select(__a_unused struct sched *s, struct play_task *pt)
1163 {
1164         int ret;
1165
1166         if (pt->background)
1167                 detach_stdout(pt);
1168         else
1169                 attach_stdout(pt, __FUNCTION__);
1170         ret = i9e_get_error();
1171         if (ret < 0) {
1172                 kill_stream(pt);
1173                 i9e_close();
1174                 para_log = stderr_log;
1175                 free(ici.history_file);
1176                 return ret;
1177         }
1178         if (get_playback_state(pt) == 'X')
1179                 i9e_signal_dispatch(SIGTERM);
1180         return 0;
1181 }
1182
1183 #else /* HAVE_READLINE */
1184
1185 static int session_post_select(struct sched *s, struct play_task *pt)
1186 {
1187         char c;
1188
1189         if (!FD_ISSET(STDIN_FILENO, &s->rfds))
1190                 return 0;
1191         if (read(STDIN_FILENO, &c, 1))
1192                 do_nothing;
1193         kill_stream(pt);
1194         return 1;
1195 }
1196
1197 static void session_open(__a_unused struct play_task *pt)
1198 {
1199 }
1200
1201 static void session_update_time_string(__a_unused struct play_task *pt,
1202                 char *str, __a_unused unsigned len)
1203 {
1204         printf("\r%s     ", str);
1205         fflush(stdout);
1206 }
1207 #endif /* HAVE_READLINE */
1208
1209 static void play_pre_select(struct sched *s, void *context)
1210 {
1211         struct play_task *pt = context;
1212         char state;
1213
1214         para_fd_set(STDIN_FILENO, &s->rfds, &s->max_fileno);
1215         state = get_playback_state(pt);
1216         if (state == 'R' || state == 'F' || state == 'X')
1217                 return sched_min_delay(s);
1218         sched_request_barrier_or_min_delay(&pt->next_update, s);
1219 }
1220
1221 static unsigned get_time_string(struct play_task *pt, char **result)
1222 {
1223         int seconds, length;
1224         char state = get_playback_state(pt);
1225
1226         /* do not return anything if things are about to change */
1227         if (state != 'P' && state != 'U') {
1228                 *result = NULL;
1229                 return 0;
1230         }
1231         length = pt->seconds;
1232         if (length == 0)
1233                 return xasprintf(result, "0:00 [0:00] (0%%/0:00)");
1234         seconds = get_play_time(pt);
1235         return xasprintf(result, "#%u: %d:%02d [%d:%02d] (%d%%/%d:%02d) %s",
1236                 pt->current_file,
1237                 seconds / 60,
1238                 seconds % 60,
1239                 (length - seconds) / 60,
1240                 (length - seconds) % 60,
1241                 length? (seconds * 100 + length / 2) / length : 0,
1242                 length / 60,
1243                 length % 60,
1244                 conf.inputs[pt->current_file]
1245         );
1246 }
1247
1248 static int play_post_select(struct sched *s, void *context)
1249 {
1250         struct play_task *pt = context;
1251         int ret;
1252
1253         ret = eof_cleanup(pt);
1254         if (ret < 0) {
1255                 pt->rq = CRT_TERM_RQ;
1256                 return 0;
1257         }
1258         ret = session_post_select(s, pt);
1259         if (ret < 0)
1260                 goto out;
1261         if (!pt->wn.btrn && !pt->fn.btrn) {
1262                 char state = get_playback_state(pt);
1263                 if (state == 'P' || state == 'R' || state == 'F') {
1264                         PARA_NOTICE_LOG("state: %c\n", state);
1265                         ret = load_next_file(pt);
1266                         if (ret < 0) {
1267                                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1268                                 pt->rq = CRT_TERM_RQ;
1269                                 ret = 1;
1270                                 goto out;
1271                         }
1272                         pt->next_update = *now;
1273                 }
1274         }
1275         if (tv_diff(now, &pt->next_update, NULL) >= 0) {
1276                 char *str;
1277                 unsigned len = get_time_string(pt, &str);
1278                 struct timeval delay = {.tv_sec = 0, .tv_usec = 100 * 1000};
1279                 if (str && len > 0)
1280                         session_update_time_string(pt, str, len);
1281                 free(str);
1282                 tv_add(now, &delay, &pt->next_update);
1283         }
1284         ret = 1;
1285 out:
1286         return ret;
1287 }
1288
1289 /**
1290  * The main function of para_play.
1291  *
1292  * \param argc Standard.
1293  * \param argv Standard.
1294  *
1295  * \return \p EXIT_FAILURE or \p EXIT_SUCCESS.
1296  */
1297 int main(int argc, char *argv[])
1298 {
1299         int ret;
1300         struct play_task *pt = &play_task;
1301
1302         /* needed this early to make help work */
1303         recv_init();
1304         filter_init();
1305         writer_init();
1306
1307         sched.default_timeout.tv_sec = 5;
1308
1309         parse_config_or_die(argc, argv);
1310         if (conf.inputs_num == 0)
1311                 print_help_and_die();
1312         check_afh_receiver_or_die();
1313
1314         session_open(pt);
1315         if (conf.randomize_given)
1316                 shuffle(conf.inputs, conf.inputs_num);
1317         pt->invalid = para_calloc(sizeof(*pt->invalid) * conf.inputs_num);
1318         pt->rq = CRT_FILE_CHANGE;
1319         pt->current_file = conf.inputs_num - 1;
1320         pt->playing = true;
1321         pt->task = task_register(&(struct task_info){
1322                 .name = "play",
1323                 .pre_select = play_pre_select,
1324                 .post_select = play_post_select,
1325                 .context = pt,
1326         }, &sched);
1327         ret = schedule(&sched);
1328         sched_shutdown(&sched);
1329         if (ret < 0)
1330                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1331         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1332 }