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