• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * SBG (SBaGen) file format decoder
3  * Copyright (c) 2011 Nicolas George
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <time.h>
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/log.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/time_internal.h"
29 #include "avformat.h"
30 #include "internal.h"
31 
32 #define SBG_SCALE (1 << 16)
33 #define DAY (24 * 60 * 60)
34 #define DAY_TS ((int64_t)DAY * AV_TIME_BASE)
35 
36 struct sbg_demuxer {
37     AVClass *class;
38     int sample_rate;
39     int frame_size;
40     int max_file_size;
41 };
42 
43 struct sbg_string {
44     char *s;
45     char *e;
46 };
47 
48 enum sbg_fade_type {
49     SBG_FADE_SILENCE = 0,
50     SBG_FADE_SAME    = 1,
51     SBG_FADE_ADAPT   = 3,
52 };
53 
54 struct sbg_fade {
55     int8_t in, out, slide;
56 };
57 
58 enum sbg_synth_type {
59     SBG_TYPE_NONE,
60     SBG_TYPE_SINE,
61     SBG_TYPE_NOISE,
62     SBG_TYPE_BELL,
63     SBG_TYPE_MIX,
64     SBG_TYPE_SPIN,
65 };
66 
67 /* bell: freq constant, ampl decreases exponentially, can be approx lin */
68 
69 struct sbg_timestamp {
70     int64_t t;
71     char type; /* 0 for relative, 'N' for now, 'T' for absolute */
72 };
73 
74 struct sbg_script_definition {
75     char *name;
76     int name_len;
77     int elements, nb_elements;
78     char type; /* 'S' or 'B' */
79 };
80 
81 struct sbg_script_synth {
82     int carrier;
83     int beat;
84     int vol;
85     enum sbg_synth_type type;
86     struct {
87         int l, r;
88     } ref;
89 };
90 
91 struct sbg_script_tseq {
92     struct sbg_timestamp ts;
93     char *name;
94     int name_len;
95     int lock;
96     struct sbg_fade fade;
97 };
98 
99 struct sbg_script_event {
100     int64_t ts;
101     int64_t ts_int, ts_trans, ts_next;
102     int elements, nb_elements;
103     struct sbg_fade fade;
104 };
105 
106 struct sbg_script {
107     struct sbg_script_definition *def;
108     struct sbg_script_synth *synth;
109     struct sbg_script_tseq *tseq;
110     struct sbg_script_tseq *block_tseq;
111     struct sbg_script_event *events;
112     int nb_def;
113     int nb_tseq;
114     int nb_events;
115     int nb_synth;
116     int64_t start_ts;
117     int64_t end_ts;
118     int64_t opt_fade_time;
119     int64_t opt_duration;
120     char *opt_mix;
121     int sample_rate;
122     uint8_t opt_start_at_first;
123     uint8_t opt_end_at_last;
124 };
125 
126 struct sbg_parser {
127     void *log;
128     char *script, *end;
129     char *cursor;
130     struct sbg_script scs;
131     struct sbg_timestamp current_time;
132     int nb_block_tseq;
133     int nb_def_max, nb_synth_max, nb_tseq_max, nb_block_tseq_max;
134     int line_no;
135     char err_msg[128];
136 };
137 
138 enum ws_interval_type {
139     WS_SINE  = MKTAG('S','I','N','E'),
140     WS_NOISE = MKTAG('N','O','I','S'),
141 };
142 
143 struct ws_interval {
144     int64_t ts1, ts2;
145     enum ws_interval_type type;
146     uint32_t channels;
147     int32_t f1, f2;
148     int32_t a1, a2;
149     uint32_t phi;
150 };
151 
152 struct ws_intervals {
153     struct ws_interval *inter;
154     int nb_inter;
155     int max_inter;
156 };
157 
alloc_array_elem(void ** array,size_t elsize,int * size,int * max_size)158 static void *alloc_array_elem(void **array, size_t elsize,
159                               int *size, int *max_size)
160 {
161     void *ret;
162 
163     if (*size == *max_size) {
164         int m = FFMAX(32, FFMIN(*max_size, INT_MAX / 2) * 2);
165         if (*size >= m)
166             return NULL;
167         *array = av_realloc_f(*array, m, elsize);
168         if (!*array)
169             return NULL;
170         *max_size = m;
171     }
172     ret = (char *)*array + elsize * *size;
173     memset(ret, 0, elsize);
174     (*size)++;
175     return ret;
176 }
177 
str_to_time(const char * str,int64_t * rtime)178 static int str_to_time(const char *str, int64_t *rtime)
179 {
180     const char *cur = str;
181     char *end;
182     int hours, minutes;
183     double seconds = 0;
184     int64_t ts = 0;
185 
186     if (*cur < '0' || *cur > '9')
187         return 0;
188     hours = strtol(cur, &end, 10);
189     if (end == cur || *end != ':' || end[1] < '0' || end[1] > '9')
190         return 0;
191     cur = end + 1;
192     minutes = strtol(cur, &end, 10);
193     if (end == cur)
194         return 0;
195     cur = end;
196     if (*end == ':'){
197         seconds = strtod(cur + 1, &end);
198         if (end > cur + 1)
199             cur = end;
200         ts = av_clipd(seconds * AV_TIME_BASE, INT64_MIN/2, INT64_MAX/2);
201     }
202     *rtime = av_sat_add64((hours * 3600LL + minutes * 60LL) * AV_TIME_BASE, ts);
203     return cur - str;
204 }
205 
is_space(char c)206 static inline int is_space(char c)
207 {
208     return c == ' '  || c == '\t' || c == '\r';
209 }
210 
scale_double(void * log,double d,double m,int * r)211 static inline int scale_double(void *log, double d, double m, int *r)
212 {
213     m *= d * SBG_SCALE;
214     if (m < INT_MIN || m >= INT_MAX) {
215         if (log)
216             av_log(log, AV_LOG_ERROR, "%g is too large\n", d);
217         return AVERROR(EDOM);
218     }
219     *r = m;
220     return 0;
221 }
222 
lex_space(struct sbg_parser * p)223 static int lex_space(struct sbg_parser *p)
224 {
225     char *c = p->cursor;
226 
227     while (p->cursor < p->end && is_space(*p->cursor))
228         p->cursor++;
229     return p->cursor > c;
230 }
231 
lex_char(struct sbg_parser * p,char c)232 static int lex_char(struct sbg_parser *p, char c)
233 {
234     int r = p->cursor < p->end && *p->cursor == c;
235 
236     p->cursor += r;
237     return r;
238 }
239 
lex_double(struct sbg_parser * p,double * r)240 static int lex_double(struct sbg_parser *p, double *r)
241 {
242     double d;
243     char *end;
244 
245     if (p->cursor == p->end || is_space(*p->cursor) || *p->cursor == '\n')
246         return 0;
247     d = strtod(p->cursor, &end);
248     if (end > p->cursor) {
249         *r = d;
250         p->cursor = end;
251         return 1;
252     }
253     return 0;
254 }
255 
lex_fixed(struct sbg_parser * p,const char * t,int l)256 static int lex_fixed(struct sbg_parser *p, const char *t, int l)
257 {
258     if (p->end - p->cursor < l || memcmp(p->cursor, t, l))
259         return 0;
260     p->cursor += l;
261     return 1;
262 }
263 
lex_line_end(struct sbg_parser * p)264 static int lex_line_end(struct sbg_parser *p)
265 {
266     if (p->cursor < p->end && *p->cursor == '#') {
267         p->cursor++;
268         while (p->cursor < p->end && *p->cursor != '\n')
269             p->cursor++;
270     }
271     if (p->cursor == p->end)
272         /* simulate final LF for files lacking it */
273         return 1;
274     if (*p->cursor != '\n')
275         return 0;
276     p->cursor++;
277     p->line_no++;
278     lex_space(p);
279     return 1;
280 }
281 
lex_wsword(struct sbg_parser * p,struct sbg_string * rs)282 static int lex_wsword(struct sbg_parser *p, struct sbg_string *rs)
283 {
284     char *s = p->cursor, *c = s;
285 
286     if (s == p->end || *s == '\n')
287         return 0;
288     while (c < p->end && *c != '\n' && !is_space(*c))
289         c++;
290     rs->s = s;
291     rs->e = p->cursor = c;
292     lex_space(p);
293     return 1;
294 }
295 
lex_name(struct sbg_parser * p,struct sbg_string * rs)296 static int lex_name(struct sbg_parser *p, struct sbg_string *rs)
297 {
298     char *s = p->cursor, *c = s;
299 
300     while (c < p->end && ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <= 'Z')
301            || (*c >= '0' && *c <= '9') || *c == '_' || *c == '-'))
302         c++;
303     if (c == s)
304         return 0;
305     rs->s = s;
306     rs->e = p->cursor = c;
307     return 1;
308 }
309 
lex_time(struct sbg_parser * p,int64_t * rt)310 static int lex_time(struct sbg_parser *p, int64_t *rt)
311 {
312     int r = str_to_time(p->cursor, rt);
313     p->cursor += r;
314     return r > 0;
315 }
316 
317 #define FORWARD_ERROR(c) \
318     do { \
319         int errcode = c; \
320         if (errcode <= 0) \
321             return errcode ? errcode : AVERROR_INVALIDDATA; \
322     } while (0)
323 
parse_immediate(struct sbg_parser * p)324 static int parse_immediate(struct sbg_parser *p)
325 {
326     snprintf(p->err_msg, sizeof(p->err_msg),
327              "immediate sequences not yet implemented");
328     return AVERROR_PATCHWELCOME;
329 }
330 
parse_preprogrammed(struct sbg_parser * p)331 static int parse_preprogrammed(struct sbg_parser *p)
332 {
333     snprintf(p->err_msg, sizeof(p->err_msg),
334              "preprogrammed sequences not yet implemented");
335     return AVERROR_PATCHWELCOME;
336 }
337 
parse_optarg(struct sbg_parser * p,char o,struct sbg_string * r)338 static int parse_optarg(struct sbg_parser *p, char o, struct sbg_string *r)
339 {
340     if (!lex_wsword(p, r)) {
341         snprintf(p->err_msg, sizeof(p->err_msg),
342                  "option '%c' requires an argument", o);
343         return AVERROR_INVALIDDATA;
344     }
345     return 1;
346 }
347 
parse_options(struct sbg_parser * p)348 static int parse_options(struct sbg_parser *p)
349 {
350     struct sbg_string ostr, oarg;
351     char mode = 0;
352     int r;
353     char *tptr;
354     double v;
355 
356     if (p->cursor == p->end || *p->cursor != '-')
357         return 0;
358     while (lex_char(p, '-') && lex_wsword(p, &ostr)) {
359         for (; ostr.s < ostr.e; ostr.s++) {
360             char opt = *ostr.s;
361             switch (opt) {
362                 case 'S':
363                     p->scs.opt_start_at_first = 1;
364                     break;
365                 case 'E':
366                     p->scs.opt_end_at_last = 1;
367                     break;
368                 case 'i':
369                     mode = 'i';
370                     break;
371                 case 'p':
372                     mode = 'p';
373                     break;
374                 case 'F':
375                     FORWARD_ERROR(parse_optarg(p, opt, &oarg));
376                     v = strtod(oarg.s, &tptr);
377                     if (oarg.e != tptr) {
378                         snprintf(p->err_msg, sizeof(p->err_msg),
379                                  "syntax error for option -F");
380                         return AVERROR_INVALIDDATA;
381                     }
382                     p->scs.opt_fade_time = v * AV_TIME_BASE / 1000;
383                     break;
384                 case 'L':
385                     FORWARD_ERROR(parse_optarg(p, opt, &oarg));
386                     r = str_to_time(oarg.s, &p->scs.opt_duration);
387                     if (oarg.e != oarg.s + r) {
388                         snprintf(p->err_msg, sizeof(p->err_msg),
389                                  "syntax error for option -L");
390                         return AVERROR_INVALIDDATA;
391                     }
392                     break;
393                 case 'T':
394                     FORWARD_ERROR(parse_optarg(p, opt, &oarg));
395                     r = str_to_time(oarg.s, &p->scs.start_ts);
396                     if (oarg.e != oarg.s + r) {
397                         snprintf(p->err_msg, sizeof(p->err_msg),
398                                  "syntax error for option -T");
399                         return AVERROR_INVALIDDATA;
400                     }
401                     break;
402                 case 'm':
403                     FORWARD_ERROR(parse_optarg(p, opt, &oarg));
404                     tptr = av_malloc(oarg.e - oarg.s + 1);
405                     if (!tptr)
406                         return AVERROR(ENOMEM);
407                     memcpy(tptr, oarg.s, oarg.e - oarg.s);
408                     tptr[oarg.e - oarg.s] = 0;
409                     av_free(p->scs.opt_mix);
410                     p->scs.opt_mix = tptr;
411                     break;
412                 case 'q':
413                     FORWARD_ERROR(parse_optarg(p, opt, &oarg));
414                     v = strtod(oarg.s, &tptr);
415                     if (oarg.e != tptr) {
416                         snprintf(p->err_msg, sizeof(p->err_msg),
417                                  "syntax error for option -q");
418                         return AVERROR_INVALIDDATA;
419                     }
420                     if (v != 1) {
421                         snprintf(p->err_msg, sizeof(p->err_msg),
422                                  "speed factor other than 1 not supported");
423                         return AVERROR_PATCHWELCOME;
424                     }
425                     break;
426                 case 'r':
427                     FORWARD_ERROR(parse_optarg(p, opt, &oarg));
428                     r = strtol(oarg.s, &tptr, 10);
429                     if (oarg.e != tptr) {
430                         snprintf(p->err_msg, sizeof(p->err_msg),
431                                  "syntax error for option -r");
432                         return AVERROR_INVALIDDATA;
433                     }
434                     if (r < 40) {
435                         snprintf(p->err_msg, sizeof(p->err_msg),
436                                  "invalid sample rate");
437                         return AVERROR_PATCHWELCOME;
438                     }
439                     p->scs.sample_rate = r;
440                     break;
441                 default:
442                     snprintf(p->err_msg, sizeof(p->err_msg),
443                              "unknown option: '%c'", *ostr.s);
444                     return AVERROR_INVALIDDATA;
445             }
446         }
447     }
448     switch (mode) {
449         case 'i':
450             return parse_immediate(p);
451         case 'p':
452             return parse_preprogrammed(p);
453         case 0:
454             if (!lex_line_end(p))
455                 return AVERROR_INVALIDDATA;
456             return 1;
457     }
458     return AVERROR_BUG;
459 }
460 
parse_timestamp(struct sbg_parser * p,struct sbg_timestamp * rts,int64_t * rrel)461 static int parse_timestamp(struct sbg_parser *p,
462                                struct sbg_timestamp *rts, int64_t *rrel)
463 {
464     int64_t abs = 0, rel = 0, dt;
465     char type = 0;
466     int r;
467 
468     if (lex_fixed(p, "NOW", 3)) {
469         type = 'N';
470         r = 1;
471     } else {
472         r = lex_time(p, &abs);
473         if (r)
474             type = 'T';
475     }
476     while (lex_char(p, '+')) {
477         if (!lex_time(p, &dt))
478             return AVERROR_INVALIDDATA;
479         if (av_sat_add64(rel, dt) - dt != rel)
480             return AVERROR_INVALIDDATA;
481         rel += dt;
482         r = 1;
483     }
484     if (r) {
485         if (!lex_space(p))
486             return AVERROR_INVALIDDATA;
487         rts->type = type;
488         rts->t    = abs;
489         *rrel     = rel;
490     }
491     return r;
492 }
493 
parse_fade(struct sbg_parser * p,struct sbg_fade * fr)494 static int parse_fade(struct sbg_parser *p, struct sbg_fade *fr)
495 {
496     struct sbg_fade f = {0};
497 
498     if (lex_char(p, '<'))
499         f.in = SBG_FADE_SILENCE;
500     else if (lex_char(p, '-'))
501         f.in = SBG_FADE_SAME;
502     else if (lex_char(p, '='))
503         f.in = SBG_FADE_ADAPT;
504     else
505         return 0;
506     if (lex_char(p, '>'))
507         f.out = SBG_FADE_SILENCE;
508     else if (lex_char(p, '-'))
509         f.out = SBG_FADE_SAME;
510     else if (lex_char(p, '='))
511         f.out = SBG_FADE_ADAPT;
512     else
513         return AVERROR_INVALIDDATA;
514     *fr = f;
515     return 1;
516 }
517 
parse_time_sequence(struct sbg_parser * p,int inblock)518 static int parse_time_sequence(struct sbg_parser *p, int inblock)
519 {
520     struct sbg_timestamp ts;
521     int64_t rel_ts;
522     int r;
523     struct sbg_fade fade = { SBG_FADE_SAME, SBG_FADE_SAME, 0 };
524     struct sbg_string name;
525     struct sbg_script_tseq *tseq;
526 
527     r = parse_timestamp(p, &ts, &rel_ts);
528     if (!r)
529         return 0;
530     if (r < 0)
531         return r;
532     if (ts.type) {
533         if (inblock)
534             return AVERROR_INVALIDDATA;
535         p->current_time.type = ts.type;
536         p->current_time.t    = ts.t;
537     } else if(!inblock && !p->current_time.type) {
538         snprintf(p->err_msg, sizeof(p->err_msg),
539                  "relative time without previous absolute time");
540         return AVERROR_INVALIDDATA;
541     }
542     ts.type = p->current_time.type;
543 
544     if (av_sat_add64(p->current_time.t, rel_ts) != p->current_time.t + (uint64_t)rel_ts)
545         return AVERROR_INVALIDDATA;
546     ts.t    = p->current_time.t + rel_ts;
547     r = parse_fade(p, &fade);
548     if (r < 0)
549         return r;
550     lex_space(p);
551     if (!lex_name(p, &name))
552         return AVERROR_INVALIDDATA;
553     lex_space(p);
554     if (lex_fixed(p, "->", 2)) {
555         fade.slide = SBG_FADE_ADAPT;
556         lex_space(p);
557     }
558     if (!lex_line_end(p))
559         return AVERROR_INVALIDDATA;
560     tseq = inblock ?
561            alloc_array_elem((void **)&p->scs.block_tseq, sizeof(*tseq),
562                             &p->nb_block_tseq, &p->nb_block_tseq_max) :
563            alloc_array_elem((void **)&p->scs.tseq, sizeof(*tseq),
564                             &p->scs.nb_tseq, &p->nb_tseq_max);
565     if (!tseq)
566         return AVERROR(ENOMEM);
567     tseq->ts       = ts;
568     tseq->name     = name.s;
569     tseq->name_len = name.e - name.s;
570     tseq->fade     = fade;
571     return 1;
572 }
573 
parse_wave_def(struct sbg_parser * p,int wavenum)574 static int parse_wave_def(struct sbg_parser *p, int wavenum)
575 {
576     snprintf(p->err_msg, sizeof(p->err_msg),
577              "waveform definitions not yet implemented");
578     return AVERROR_PATCHWELCOME;
579 }
580 
parse_block_def(struct sbg_parser * p,struct sbg_script_definition * def)581 static int parse_block_def(struct sbg_parser *p,
582                            struct sbg_script_definition *def)
583 {
584     int r, tseq;
585 
586     lex_space(p);
587     if (!lex_line_end(p))
588         return AVERROR_INVALIDDATA;
589     tseq = p->nb_block_tseq;
590     while (1) {
591         r = parse_time_sequence(p, 1);
592         if (r < 0)
593             return r;
594         if (!r)
595             break;
596     }
597     if (!lex_char(p, '}'))
598         return AVERROR_INVALIDDATA;
599     lex_space(p);
600     if (!lex_line_end(p))
601         return AVERROR_INVALIDDATA;
602     def->type        = 'B';
603     def->elements    = tseq;
604     def->nb_elements = p->nb_block_tseq - tseq;
605     if (!def->nb_elements)
606         return AVERROR_INVALIDDATA;
607     return 1;
608 }
609 
parse_volume(struct sbg_parser * p,int * vol)610 static int parse_volume(struct sbg_parser *p, int *vol)
611 {
612     double v;
613 
614     if (!lex_char(p, '/'))
615         return 0;
616     if (!lex_double(p, &v))
617         return AVERROR_INVALIDDATA;
618     if (scale_double(p->log, v, 0.01, vol))
619         return AVERROR(ERANGE);
620     return 1;
621 }
622 
parse_synth_channel_sine(struct sbg_parser * p,struct sbg_script_synth * synth)623 static int parse_synth_channel_sine(struct sbg_parser *p,
624                                     struct sbg_script_synth *synth)
625 {
626     double carrierf, beatf;
627     int carrier, beat, vol;
628 
629     if (!lex_double(p, &carrierf))
630         return 0;
631     if (!lex_double(p, &beatf))
632         beatf = 0;
633     FORWARD_ERROR(parse_volume(p, &vol));
634     if (scale_double(p->log, carrierf, 1, &carrier) < 0 ||
635         scale_double(p->log, beatf, 1, &beat) < 0)
636         return AVERROR(EDOM);
637     synth->type    = SBG_TYPE_SINE;
638     synth->carrier = carrier;
639     synth->beat    = beat;
640     synth->vol     = vol;
641     return 1;
642 }
643 
parse_synth_channel_pink(struct sbg_parser * p,struct sbg_script_synth * synth)644 static int parse_synth_channel_pink(struct sbg_parser *p,
645                                     struct sbg_script_synth *synth)
646 {
647     int vol;
648 
649     if (!lex_fixed(p, "pink", 4))
650         return 0;
651     FORWARD_ERROR(parse_volume(p, &vol));
652     synth->type    = SBG_TYPE_NOISE;
653     synth->vol     = vol;
654     return 1;
655 }
656 
parse_synth_channel_bell(struct sbg_parser * p,struct sbg_script_synth * synth)657 static int parse_synth_channel_bell(struct sbg_parser *p,
658                                     struct sbg_script_synth *synth)
659 {
660     double carrierf;
661     int carrier, vol;
662 
663     if (!lex_fixed(p, "bell", 4))
664         return 0;
665     if (!lex_double(p, &carrierf))
666         return AVERROR_INVALIDDATA;
667     FORWARD_ERROR(parse_volume(p, &vol));
668     if (scale_double(p->log, carrierf, 1, &carrier) < 0)
669         return AVERROR(EDOM);
670     synth->type    = SBG_TYPE_BELL;
671     synth->carrier = carrier;
672     synth->vol     = vol;
673     return 1;
674 }
675 
parse_synth_channel_mix(struct sbg_parser * p,struct sbg_script_synth * synth)676 static int parse_synth_channel_mix(struct sbg_parser *p,
677                                    struct sbg_script_synth *synth)
678 {
679     int vol;
680 
681     if (!lex_fixed(p, "mix", 3))
682         return 0;
683     FORWARD_ERROR(parse_volume(p, &vol));
684     synth->type    = SBG_TYPE_MIX;
685     synth->vol     = vol;
686     return 1;
687 }
688 
parse_synth_channel_spin(struct sbg_parser * p,struct sbg_script_synth * synth)689 static int parse_synth_channel_spin(struct sbg_parser *p,
690                                     struct sbg_script_synth *synth)
691 {
692     double carrierf, beatf;
693     int carrier, beat, vol;
694 
695     if (!lex_fixed(p, "spin:", 5))
696         return 0;
697     if (!lex_double(p, &carrierf))
698         return AVERROR_INVALIDDATA;
699     if (!lex_double(p, &beatf))
700         return AVERROR_INVALIDDATA;
701     FORWARD_ERROR(parse_volume(p, &vol));
702     if (scale_double(p->log, carrierf, 1, &carrier) < 0 ||
703         scale_double(p->log, beatf, 1, &beat) < 0)
704         return AVERROR(EDOM);
705     synth->type    = SBG_TYPE_SPIN;
706     synth->carrier = carrier;
707     synth->beat    = beat;
708     synth->vol     = vol;
709     return 1;
710 }
711 
parse_synth_channel(struct sbg_parser * p)712 static int parse_synth_channel(struct sbg_parser *p)
713 {
714     int r;
715     struct sbg_script_synth *synth;
716 
717     synth = alloc_array_elem((void **)&p->scs.synth, sizeof(*synth),
718                              &p->scs.nb_synth, &p->nb_synth_max);
719     if (!synth)
720         return AVERROR(ENOMEM);
721     r = lex_char(p, '-');
722     if (!r)
723         r = parse_synth_channel_pink(p, synth);
724     if (!r)
725         r = parse_synth_channel_bell(p, synth);
726     if (!r)
727         r = parse_synth_channel_mix(p, synth);
728     if (!r)
729         r = parse_synth_channel_spin(p, synth);
730     /* Unimplemented: wave%d:%f%f/vol (carrier, beat) */
731     if (!r)
732         r = parse_synth_channel_sine(p, synth);
733     if (r <= 0)
734         p->scs.nb_synth--;
735     return r;
736 }
737 
parse_synth_def(struct sbg_parser * p,struct sbg_script_definition * def)738 static int parse_synth_def(struct sbg_parser *p,
739                            struct sbg_script_definition *def)
740 {
741     int r, synth;
742 
743     synth = p->scs.nb_synth;
744     while (1) {
745         r = parse_synth_channel(p);
746         if (r < 0)
747             return r;
748         if (!r || !lex_space(p))
749             break;
750     }
751     lex_space(p);
752     if (synth == p->scs.nb_synth)
753         return AVERROR_INVALIDDATA;
754     if (!lex_line_end(p))
755         return AVERROR_INVALIDDATA;
756     def->type        = 'S';
757     def->elements    = synth;
758     def->nb_elements = p->scs.nb_synth - synth;
759     return 1;
760 }
761 
parse_named_def(struct sbg_parser * p)762 static int parse_named_def(struct sbg_parser *p)
763 {
764     char *cursor_save = p->cursor;
765     struct sbg_string name;
766     struct sbg_script_definition *def;
767 
768     if (!lex_name(p, &name) || !lex_char(p, ':') || !lex_space(p)) {
769         p->cursor = cursor_save;
770         return 0;
771     }
772     if (name.e - name.s == 6 && !memcmp(name.s, "wave", 4) &&
773         name.s[4] >= '0' && name.s[4] <= '9' &&
774         name.s[5] >= '0' && name.s[5] <= '9') {
775         int wavenum = (name.s[4] - '0') * 10 + (name.s[5] - '0');
776         return parse_wave_def(p, wavenum);
777     }
778     def = alloc_array_elem((void **)&p->scs.def, sizeof(*def),
779                            &p->scs.nb_def, &p->nb_def_max);
780     if (!def)
781         return AVERROR(ENOMEM);
782     def->name     = name.s;
783     def->name_len = name.e - name.s;
784     if (lex_char(p, '{'))
785         return parse_block_def(p, def);
786     return parse_synth_def(p, def);
787 }
788 
free_script(struct sbg_script * s)789 static void free_script(struct sbg_script *s)
790 {
791     av_freep(&s->def);
792     av_freep(&s->synth);
793     av_freep(&s->tseq);
794     av_freep(&s->block_tseq);
795     av_freep(&s->events);
796     av_freep(&s->opt_mix);
797 }
798 
parse_script(void * log,char * script,int script_len,struct sbg_script * rscript)799 static int parse_script(void *log, char *script, int script_len,
800                             struct sbg_script *rscript)
801 {
802     struct sbg_parser sp = {
803         .log     = log,
804         .script  = script,
805         .end     = script + script_len,
806         .cursor  = script,
807         .line_no = 1,
808         .err_msg = "",
809         .scs = {
810             /* default values */
811             .start_ts      = AV_NOPTS_VALUE,
812             .sample_rate   = 44100,
813             .opt_fade_time = 60 * AV_TIME_BASE,
814         },
815     };
816     int r;
817 
818     lex_space(&sp);
819     while (sp.cursor < sp.end) {
820         r = parse_options(&sp);
821         if (r < 0)
822             goto fail;
823         if (!r && !lex_line_end(&sp))
824             break;
825     }
826     while (sp.cursor < sp.end) {
827         r = parse_named_def(&sp);
828         if (!r)
829             r = parse_time_sequence(&sp, 0);
830         if (!r)
831             r = lex_line_end(&sp) ? 1 : AVERROR_INVALIDDATA;
832         if (r < 0)
833             goto fail;
834     }
835     *rscript = sp.scs;
836     return 1;
837 fail:
838     free_script(&sp.scs);
839     if (!*sp.err_msg)
840         if (r == AVERROR_INVALIDDATA)
841             snprintf(sp.err_msg, sizeof(sp.err_msg), "syntax error");
842     if (log && *sp.err_msg) {
843         const char *ctx = sp.cursor;
844         const char *ectx = av_x_if_null(memchr(ctx, '\n', sp.end - sp.cursor),
845                                         sp.end);
846         int lctx = ectx - ctx;
847         const char *quote = "\"";
848         if (lctx > 0 && ctx[lctx - 1] == '\r')
849             lctx--;
850         if (lctx == 0) {
851             ctx = "the end of line";
852             lctx = strlen(ctx);
853             quote = "";
854         }
855         av_log(log, AV_LOG_ERROR, "Error line %d: %s near %s%.*s%s.\n",
856                sp.line_no, sp.err_msg, quote, lctx, ctx, quote);
857     }
858     return r;
859 }
860 
read_whole_file(AVIOContext * io,int max_size,char ** rbuf)861 static int read_whole_file(AVIOContext *io, int max_size, char **rbuf)
862 {
863     char *buf = NULL;
864     int size = 0, bufsize = 0, r;
865 
866     while (1) {
867         if (bufsize - size < 1024) {
868             bufsize = FFMIN(FFMAX(2 * bufsize, 8192), max_size);
869             if (bufsize - size < 2) {
870                 size = AVERROR(EFBIG);
871                 goto fail;
872             }
873             buf = av_realloc_f(buf, bufsize, 1);
874             if (!buf) {
875                 size = AVERROR(ENOMEM);
876                 goto fail;
877             }
878         }
879         r = avio_read(io, buf, bufsize - size - 1);
880         if (r == AVERROR_EOF)
881             break;
882         if (r < 0)
883             goto fail;
884         size += r;
885     }
886     buf[size] = 0;
887     *rbuf = buf;
888     return size;
889 fail:
890     av_free(buf);
891     return size;
892 }
893 
expand_timestamps(void * log,struct sbg_script * s)894 static int expand_timestamps(void *log, struct sbg_script *s)
895 {
896     int i, nb_rel = 0;
897     int64_t now, cur_ts, delta = 0;
898 
899     for (i = 0; i < s->nb_tseq; i++)
900         nb_rel += s->tseq[i].ts.type == 'N';
901     if (nb_rel == s->nb_tseq) {
902         /* All ts are relative to NOW: consider NOW = 0 */
903         now = 0;
904         if (s->start_ts != AV_NOPTS_VALUE)
905             av_log(log, AV_LOG_WARNING,
906                    "Start time ignored in a purely relative script.\n");
907     } else if (nb_rel == 0 && s->start_ts != AV_NOPTS_VALUE ||
908                s->opt_start_at_first) {
909         /* All ts are absolute and start time is specified */
910         if (s->start_ts == AV_NOPTS_VALUE)
911             s->start_ts = s->tseq[0].ts.t;
912         now = s->start_ts;
913     } else {
914         /* Mixed relative/absolute ts: expand */
915         time_t now0;
916         struct tm *tm, tmpbuf;
917 
918         av_log(log, AV_LOG_WARNING,
919                "Scripts with mixed absolute and relative timestamps can give "
920                "unexpected results (pause, seeking, time zone change).\n");
921 #undef time
922         time(&now0);
923         tm = localtime_r(&now0, &tmpbuf);
924         now = tm ? tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec :
925                    now0 % DAY;
926         av_log(log, AV_LOG_INFO, "Using %02d:%02d:%02d as NOW.\n",
927                (int)(now / 3600), (int)(now / 60) % 60, (int)now % 60);
928         now *= AV_TIME_BASE;
929         for (i = 0; i < s->nb_tseq; i++) {
930             if (s->tseq[i].ts.type == 'N') {
931                 s->tseq[i].ts.t += now;
932                 s->tseq[i].ts.type = 'T'; /* not necessary */
933             }
934         }
935     }
936     if (s->start_ts == AV_NOPTS_VALUE)
937         s->start_ts = (s->opt_start_at_first && s->tseq) ? s->tseq[0].ts.t : now;
938     if (s->start_ts > INT64_MAX - s->opt_duration)
939         return AVERROR_INVALIDDATA;
940 
941     s->end_ts = s->opt_duration ? s->start_ts + s->opt_duration :
942                 AV_NOPTS_VALUE; /* may be overridden later by -E option */
943     cur_ts = now;
944     for (i = 0; i < s->nb_tseq; i++) {
945         if (av_sat_add64(s->tseq[i].ts.t, delta) != s->tseq[i].ts.t + (uint64_t)delta)
946             return AVERROR_INVALIDDATA;
947         if (s->tseq[i].ts.t + delta < cur_ts)
948             delta += DAY_TS;
949         cur_ts = s->tseq[i].ts.t += delta;
950     }
951     return 0;
952 }
953 
expand_tseq(void * log,struct sbg_script * s,int * nb_ev_max,int64_t t0,struct sbg_script_tseq * tseq)954 static int expand_tseq(void *log, struct sbg_script *s, int *nb_ev_max,
955                        int64_t t0, struct sbg_script_tseq *tseq)
956 {
957     int i, r;
958     struct sbg_script_definition *def;
959     struct sbg_script_tseq *be;
960     struct sbg_script_event *ev;
961 
962     if (tseq->lock++) {
963         av_log(log, AV_LOG_ERROR, "Recursion loop on \"%.*s\"\n",
964                tseq->name_len, tseq->name);
965         return AVERROR(EINVAL);
966     }
967     if (t0 + (uint64_t)tseq->ts.t != av_sat_add64(t0, tseq->ts.t))
968         return AVERROR(EINVAL);
969 
970     t0 += tseq->ts.t;
971     for (i = 0; i < s->nb_def; i++) {
972         if (s->def[i].name_len == tseq->name_len &&
973             !memcmp(s->def[i].name, tseq->name, tseq->name_len))
974             break;
975     }
976     if (i >= s->nb_def) {
977         av_log(log, AV_LOG_ERROR, "Tone-set \"%.*s\" not defined\n",
978                tseq->name_len, tseq->name);
979         return AVERROR(EINVAL);
980     }
981     def = &s->def[i];
982     if (def->type == 'B') {
983         be = s->block_tseq + def->elements;
984         for (i = 0; i < def->nb_elements; i++) {
985             r = expand_tseq(log, s, nb_ev_max, t0, &be[i]);
986             if (r < 0)
987                 return r;
988         }
989     } else {
990         ev = alloc_array_elem((void **)&s->events, sizeof(*ev),
991                               &s->nb_events, nb_ev_max);
992         if (!ev)
993             return AVERROR(ENOMEM);
994         ev->ts          = tseq->ts.t;
995         ev->elements    = def->elements;
996         ev->nb_elements = def->nb_elements;
997         ev->fade        = tseq->fade;
998     }
999     tseq->lock--;
1000     return 0;
1001 }
1002 
expand_script(void * log,struct sbg_script * s)1003 static int expand_script(void *log, struct sbg_script *s)
1004 {
1005     int i, r, nb_events_max = 0;
1006 
1007     r = expand_timestamps(log, s);
1008     if (r < 0)
1009         return r;
1010     for (i = 0; i < s->nb_tseq; i++) {
1011         r = expand_tseq(log, s, &nb_events_max, 0, &s->tseq[i]);
1012         if (r < 0)
1013             return r;
1014     }
1015     if (!s->nb_events) {
1016         av_log(log, AV_LOG_ERROR, "No events in script\n");
1017         return AVERROR_INVALIDDATA;
1018     }
1019     if (s->opt_end_at_last)
1020         s->end_ts = s->events[s->nb_events - 1].ts;
1021     return 0;
1022 }
1023 
add_interval(struct ws_intervals * inter,enum ws_interval_type type,uint32_t channels,int ref,int64_t ts1,int32_t f1,int32_t a1,int64_t ts2,int32_t f2,int32_t a2)1024 static int add_interval(struct ws_intervals *inter,
1025                         enum ws_interval_type type, uint32_t channels, int ref,
1026                         int64_t ts1, int32_t f1, int32_t a1,
1027                         int64_t ts2, int32_t f2, int32_t a2)
1028 {
1029     struct ws_interval *i, *ri;
1030 
1031     if (ref >= 0) {
1032         ri = &inter->inter[ref];
1033         /* ref and new intervals are constant, identical and adjacent */
1034         if (ri->type == type && ri->channels == channels &&
1035             ri->f1 == ri->f2 && ri->f2 == f1 && f1 == f2 &&
1036             ri->a1 == ri->a2 && ri->a2 == a1 && a1 == a2 &&
1037             ri->ts2 == ts1) {
1038             ri->ts2 = ts2;
1039             return ref;
1040         }
1041     }
1042     i = alloc_array_elem((void **)&inter->inter, sizeof(*i),
1043                          &inter->nb_inter, &inter->max_inter);
1044     if (!i)
1045         return AVERROR(ENOMEM);
1046     i->ts1      = ts1;
1047     i->ts2      = ts2;
1048     i->type     = type;
1049     i->channels = channels;
1050     i->f1       = f1;
1051     i->f2       = f2;
1052     i->a1       = a1;
1053     i->a2       = a2;
1054     i->phi      = ref >= 0 ? ref | 0x80000000 : 0;
1055     return i - inter->inter;
1056 }
1057 
add_bell(struct ws_intervals * inter,struct sbg_script * s,int64_t ts1,int64_t ts2,int32_t f,int32_t a)1058 static int add_bell(struct ws_intervals *inter, struct sbg_script *s,
1059                     int64_t ts1, int64_t ts2, int32_t f, int32_t a)
1060 {
1061     /* SBaGen uses an exponential decrease every 50ms.
1062        We approximate it with piecewise affine segments. */
1063     int32_t cpoints[][2] = {
1064         {  2, a },
1065         {  4, a - a / 4 },
1066         {  8, a / 2 },
1067         { 16, a / 4 },
1068         { 25, a / 10 },
1069         { 50, a / 80 },
1070         { 75, 0 },
1071     };
1072     int i, r;
1073     int64_t dt = s->sample_rate / 20, ts3 = ts1, ts4;
1074     for (i = 0; i < FF_ARRAY_ELEMS(cpoints); i++) {
1075         ts4 = FFMIN(ts2, ts1 + cpoints[i][0] * dt);
1076         r = add_interval(inter, WS_SINE, 3, -1,
1077                          ts3, f, a, ts4, f, cpoints[i][1]);
1078         if (r < 0)
1079             return r;
1080         ts3 = ts4;
1081         a = cpoints[i][1];
1082     }
1083     return 0;
1084 }
1085 
generate_interval(void * log,struct sbg_script * s,struct ws_intervals * inter,int64_t ts1,int64_t ts2,struct sbg_script_synth * s1,struct sbg_script_synth * s2,int transition)1086 static int generate_interval(void *log, struct sbg_script *s,
1087                              struct ws_intervals *inter,
1088                              int64_t ts1, int64_t ts2,
1089                              struct sbg_script_synth *s1,
1090                              struct sbg_script_synth *s2,
1091                              int transition)
1092 {
1093     int r;
1094 
1095     if (ts2 <= ts1 || (s1->vol == 0 && s2->vol == 0))
1096         return 0;
1097     switch (s1->type) {
1098         case SBG_TYPE_NONE:
1099             break;
1100         case SBG_TYPE_SINE:
1101             if (s1->beat == 0 && s2->beat == 0) {
1102                 r = add_interval(inter, WS_SINE, 3, s1->ref.l,
1103                                  ts1, s1->carrier, s1->vol,
1104                                  ts2, s2->carrier, s2->vol);
1105                 if (r < 0)
1106                     return r;
1107                 s2->ref.l = s2->ref.r = r;
1108             } else {
1109                 r = add_interval(inter, WS_SINE, 1, s1->ref.l,
1110                                  ts1, s1->carrier + s1->beat / 2, s1->vol,
1111                                  ts2, s2->carrier + s2->beat / 2, s2->vol);
1112                 if (r < 0)
1113                     return r;
1114                 s2->ref.l = r;
1115                 r = add_interval(inter, WS_SINE, 2, s1->ref.r,
1116                                  ts1, s1->carrier - s1->beat / 2, s1->vol,
1117                                  ts2, s2->carrier - s2->beat / 2, s2->vol);
1118                 if (r < 0)
1119                     return r;
1120                 s2->ref.r = r;
1121             }
1122             break;
1123 
1124         case SBG_TYPE_BELL:
1125             if (transition == 2) {
1126                 r = add_bell(inter, s, ts1, ts2, s1->carrier, s2->vol);
1127                 if (r < 0)
1128                     return r;
1129             }
1130             break;
1131 
1132         case SBG_TYPE_SPIN:
1133             av_log(log, AV_LOG_WARNING, "Spinning noise not implemented, "
1134                                         "using pink noise instead.\n");
1135             /* fall through */
1136         case SBG_TYPE_NOISE:
1137             /* SBaGen's pink noise generator uses:
1138                - 1 band of white noise, mean square: 1/3;
1139                - 9 bands of subsampled white noise with linear
1140                  interpolation, mean square: 2/3 each;
1141                with 1/10 weight each: the total mean square is 7/300.
1142                Our pink noise generator uses 8 bands of white noise with
1143                rectangular subsampling: the total mean square is 1/24.
1144                Therefore, to match SBaGen's volume, we must multiply vol by
1145                sqrt((7/300) / (1/24)) = sqrt(14/25) =~ 0.748
1146              */
1147             r = add_interval(inter, WS_NOISE, 3, s1->ref.l,
1148                              ts1, 0, s1->vol - s1->vol / 4,
1149                              ts2, 0, s2->vol - s2->vol / 4);
1150             if (r < 0)
1151                 return r;
1152             s2->ref.l = s2->ref.r = r;
1153             break;
1154 
1155         case SBG_TYPE_MIX:
1156             /* Unimplemented: silence; warning present elsewhere */
1157         default:
1158             av_log(log, AV_LOG_ERROR,
1159                    "Type %d is not implemented\n", s1->type);
1160             return AVERROR_PATCHWELCOME;
1161     }
1162     return 0;
1163 }
1164 
generate_plateau(void * log,struct sbg_script * s,struct ws_intervals * inter,struct sbg_script_event * ev1)1165 static int generate_plateau(void *log, struct sbg_script *s,
1166                             struct ws_intervals *inter,
1167                             struct sbg_script_event *ev1)
1168 {
1169     int64_t ts1 = ev1->ts_int, ts2 = ev1->ts_trans;
1170     int i, r;
1171     struct sbg_script_synth *s1;
1172 
1173     for (i = 0; i < ev1->nb_elements; i++) {
1174         s1 = &s->synth[ev1->elements + i];
1175         r = generate_interval(log, s, inter, ts1, ts2, s1, s1, 0);
1176         if (r < 0)
1177             return r;
1178     }
1179     return 0;
1180 }
1181 
1182 /*
1183 
1184    ts1             ts2         ts1    tsmid    ts2
1185     |               |           |       |       |
1186     v               v           v       |       v
1187 ____                        ____        v       ____
1188     ''''....                    ''..        ..''
1189             ''''....____            ''....''
1190 
1191   compatible transition      incompatible transition
1192  */
1193 
generate_transition(void * log,struct sbg_script * s,struct ws_intervals * inter,struct sbg_script_event * ev1,struct sbg_script_event * ev2)1194 static int generate_transition(void *log, struct sbg_script *s,
1195                                struct ws_intervals *inter,
1196                                struct sbg_script_event *ev1,
1197                                struct sbg_script_event *ev2)
1198 {
1199     int64_t ts1 = ev1->ts_trans, ts2 = ev1->ts_next;
1200     /* (ts1 + ts2) / 2 without overflow */
1201     int64_t tsmid = (ts1 >> 1) + (ts2 >> 1) + (ts1 & ts2 & 1);
1202     enum sbg_fade_type type = ev1->fade.slide | (ev1->fade.out & ev2->fade.in);
1203     int nb_elements = FFMAX(ev1->nb_elements, ev2->nb_elements);
1204     struct sbg_script_synth *s1, *s2, s1mod, s2mod, smid;
1205     int pass, i, r;
1206 
1207     for (pass = 0; pass < 2; pass++) {
1208         /* pass = 0 -> compatible and first half of incompatible
1209            pass = 1 -> second half of incompatible
1210            Using two passes like that ensures that the intervals are generated
1211            in increasing order according to their start timestamp.
1212            Otherwise it would be necessary to sort them
1213            while keeping the mutual references.
1214          */
1215         for (i = 0; i < nb_elements; i++) {
1216             s1 = i < ev1->nb_elements ? &s->synth[ev1->elements + i] : &s1mod;
1217             s2 = i < ev2->nb_elements ? &s->synth[ev2->elements + i] : &s2mod;
1218             s1mod = s1 != &s1mod ? *s1 : (struct sbg_script_synth){ 0 };
1219             s2mod = s2 != &s2mod ? *s2 : (struct sbg_script_synth){ 0 };
1220             if (ev1->fade.slide) {
1221                 /* for slides, and only for slides, silence ("-") is equivalent
1222                    to anything with volume 0 */
1223                 if (s1mod.type == SBG_TYPE_NONE) {
1224                     s1mod = s2mod;
1225                     s1mod.vol = 0;
1226                 } else if (s2mod.type == SBG_TYPE_NONE) {
1227                     s2mod = s1mod;
1228                     s2mod.vol = 0;
1229                 }
1230             }
1231             if (s1mod.type == s2mod.type &&
1232                 s1mod.type != SBG_TYPE_BELL &&
1233                 (type == SBG_FADE_ADAPT ||
1234                  (s1mod.carrier == s2mod.carrier &&
1235                   s1mod.beat == s2mod.beat))) {
1236                 /* compatible: single transition */
1237                 if (!pass) {
1238                     r = generate_interval(log, s, inter,
1239                                           ts1, ts2, &s1mod, &s2mod, 3);
1240                     if (r < 0)
1241                         return r;
1242                     s2->ref = s2mod.ref;
1243                 }
1244             } else {
1245                 /* incompatible: silence at midpoint */
1246                 if (!pass) {
1247                     smid = s1mod;
1248                     smid.vol = 0;
1249                     r = generate_interval(log, s, inter,
1250                                           ts1, tsmid, &s1mod, &smid, 1);
1251                     if (r < 0)
1252                         return r;
1253                 } else {
1254                     smid = s2mod;
1255                     smid.vol = 0;
1256                     r = generate_interval(log, s, inter,
1257                                           tsmid, ts2, &smid, &s2mod, 2);
1258                     if (r < 0)
1259                         return r;
1260                     s2->ref = s2mod.ref;
1261                 }
1262             }
1263         }
1264     }
1265     return 0;
1266 }
1267 
1268 /*
1269     ev1                  trats ev2  intts           endts ev3
1270      |                     |    |     |               |    |
1271      v                     v    v     v               v    v
1272                                       ________________
1273 ....                              ....                ....
1274     '''....________________....'''                        '''...._______________
1275 
1276 \_________/\______________/\_________/\______________/\_________/\_____________/
1277   tr x->1        int1        tr 1->2        int2        tr 2->3        int3
1278  */
1279 
generate_intervals(void * log,struct sbg_script * s,int sample_rate,struct ws_intervals * inter)1280 static int generate_intervals(void *log, struct sbg_script *s, int sample_rate,
1281                               struct ws_intervals *inter)
1282 {
1283     int64_t trans_time = s->opt_fade_time / 2;
1284     struct sbg_script_event ev0, *ev1, *ev2;
1285     int64_t period;
1286     int i, r;
1287 
1288     /* SBaGen handles the time before and after the extremal events,
1289        and the corresponding transitions, as if the sequence were cyclic
1290        with a 24-hours period. */
1291     period = s->events[s->nb_events - 1].ts - s->events[0].ts;
1292     period = (period + (DAY_TS - 1)) / DAY_TS * DAY_TS;
1293     period = FFMAX(period, DAY_TS);
1294 
1295     /* Prepare timestamps for transitions */
1296     for (i = 0; i < s->nb_events; i++) {
1297         ev1 = &s->events[i];
1298         ev2 = &s->events[(i + 1) % s->nb_events];
1299         ev1->ts_int   = ev1->ts;
1300 
1301         if (!ev1->fade.slide && ev1 >= ev2 && ev2->ts > INT64_MAX - period)
1302             return AVERROR_INVALIDDATA;
1303 
1304         ev1->ts_trans = ev1->fade.slide ? ev1->ts
1305                                         : ev2->ts + (ev1 < ev2 ? 0 : period);
1306     }
1307     for (i = 0; i < s->nb_events; i++) {
1308         ev1 = &s->events[i];
1309         ev2 = &s->events[(i + 1) % s->nb_events];
1310         if (!ev1->fade.slide) {
1311             ev1->ts_trans = FFMAX(ev1->ts_int,   ev1->ts_trans - trans_time);
1312             ev2->ts_int   = FFMIN(ev2->ts_trans, ev2->ts_int   + trans_time);
1313         }
1314         ev1->ts_next  = ev2->ts_int + (ev1 < ev2 ? 0 : period);
1315     }
1316 
1317     /* Pseudo event before the first one */
1318     ev0 = s->events[s->nb_events - 1];
1319     ev0.ts_int   -= period;
1320     ev0.ts_trans -= period;
1321     ev0.ts_next  -= period;
1322 
1323     /* Convert timestamps */
1324     for (i = -1; i < s->nb_events; i++) {
1325         ev1 = i < 0 ? &ev0 : &s->events[i];
1326         ev1->ts_int   = av_rescale(ev1->ts_int,   sample_rate, AV_TIME_BASE);
1327         ev1->ts_trans = av_rescale(ev1->ts_trans, sample_rate, AV_TIME_BASE);
1328         ev1->ts_next  = av_rescale(ev1->ts_next,  sample_rate, AV_TIME_BASE);
1329     }
1330 
1331     /* Generate intervals */
1332     for (i = 0; i < s->nb_synth; i++)
1333         s->synth[i].ref.l = s->synth[i].ref.r = -1;
1334     for (i = -1; i < s->nb_events; i++) {
1335         ev1 = i < 0 ? &ev0 : &s->events[i];
1336         ev2 = &s->events[(i + 1) % s->nb_events];
1337         r = generate_plateau(log, s, inter, ev1);
1338         if (r < 0)
1339             return r;
1340         r = generate_transition(log, s, inter, ev1, ev2);
1341         if (r < 0)
1342             return r;
1343     }
1344     if (!inter->nb_inter)
1345         av_log(log, AV_LOG_WARNING, "Completely silent script.\n");
1346     return 0;
1347 }
1348 
encode_intervals(struct sbg_script * s,AVCodecParameters * par,struct ws_intervals * inter)1349 static int encode_intervals(struct sbg_script *s, AVCodecParameters *par,
1350                             struct ws_intervals *inter)
1351 {
1352     int i, edata_size = 4, ret;
1353     uint8_t *edata;
1354 
1355     for (i = 0; i < inter->nb_inter; i++) {
1356         edata_size += inter->inter[i].type == WS_SINE  ? 44 :
1357                       inter->inter[i].type == WS_NOISE ? 32 : 0;
1358         if (edata_size < 0)
1359             return AVERROR(ENOMEM);
1360     }
1361     if ((ret = ff_alloc_extradata(par, edata_size)) < 0)
1362         return ret;
1363     edata = par->extradata;
1364 
1365 #define ADD_EDATA32(v) do { AV_WL32(edata, (v)); edata += 4; } while(0)
1366 #define ADD_EDATA64(v) do { AV_WL64(edata, (v)); edata += 8; } while(0)
1367     ADD_EDATA32(inter->nb_inter);
1368     for (i = 0; i < inter->nb_inter; i++) {
1369         ADD_EDATA64(inter->inter[i].ts1);
1370         ADD_EDATA64(inter->inter[i].ts2);
1371         ADD_EDATA32(inter->inter[i].type);
1372         ADD_EDATA32(inter->inter[i].channels);
1373         switch (inter->inter[i].type) {
1374             case WS_SINE:
1375                 ADD_EDATA32(inter->inter[i].f1);
1376                 ADD_EDATA32(inter->inter[i].f2);
1377                 ADD_EDATA32(inter->inter[i].a1);
1378                 ADD_EDATA32(inter->inter[i].a2);
1379                 ADD_EDATA32(inter->inter[i].phi);
1380                 break;
1381             case WS_NOISE:
1382                 ADD_EDATA32(inter->inter[i].a1);
1383                 ADD_EDATA32(inter->inter[i].a2);
1384                 break;
1385         }
1386     }
1387     if (edata != par->extradata + edata_size)
1388         return AVERROR_BUG;
1389     return 0;
1390 }
1391 
sbg_read_probe(const AVProbeData * p)1392 static av_cold int sbg_read_probe(const AVProbeData *p)
1393 {
1394     int r, score;
1395     struct sbg_script script = { 0 };
1396 
1397     r = parse_script(NULL, p->buf, p->buf_size, &script);
1398     score = r < 0 || !script.nb_def || !script.nb_tseq ? 0 :
1399             AVPROBE_SCORE_MAX / 3;
1400     free_script(&script);
1401     return score;
1402 }
1403 
sbg_read_header(AVFormatContext * avf)1404 static av_cold int sbg_read_header(AVFormatContext *avf)
1405 {
1406     struct sbg_demuxer *sbg = avf->priv_data;
1407     int r;
1408     char *buf = NULL;
1409     struct sbg_script script = { 0 };
1410     AVStream *st;
1411     struct ws_intervals inter = { 0 };
1412 
1413     r = read_whole_file(avf->pb, sbg->max_file_size, &buf);
1414     if (r < 0)
1415         goto fail;
1416     r = parse_script(avf, buf, r, &script);
1417     if (r < 0)
1418         goto fail;
1419     if (!sbg->sample_rate)
1420         sbg->sample_rate = script.sample_rate;
1421     else
1422         script.sample_rate = sbg->sample_rate;
1423     if (!sbg->frame_size)
1424         sbg->frame_size = FFMAX(1, sbg->sample_rate / 10);
1425     if (script.opt_mix)
1426         av_log(avf, AV_LOG_WARNING, "Mix feature not implemented: "
1427                "-m is ignored and mix channels will be silent.\n");
1428     r = expand_script(avf, &script);
1429     if (r < 0)
1430         goto fail;
1431     av_freep(&buf);
1432     r = generate_intervals(avf, &script, sbg->sample_rate, &inter);
1433     if (r < 0)
1434         goto fail;
1435 
1436     if (script.end_ts != AV_NOPTS_VALUE && script.end_ts < script.start_ts) {
1437         r = AVERROR_INVALIDDATA;
1438         goto fail;
1439     }
1440 
1441     st = avformat_new_stream(avf, NULL);
1442     if (!st)
1443         return AVERROR(ENOMEM);
1444     st->codecpar->codec_type     = AVMEDIA_TYPE_AUDIO;
1445     st->codecpar->codec_id       = AV_CODEC_ID_FFWAVESYNTH;
1446     st->codecpar->channels       = 2;
1447     st->codecpar->channel_layout = AV_CH_LAYOUT_STEREO;
1448     st->codecpar->sample_rate    = sbg->sample_rate;
1449     st->codecpar->frame_size     = sbg->frame_size;
1450     avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
1451     st->probe_packets = 0;
1452     st->start_time    = av_rescale(script.start_ts,
1453                                    sbg->sample_rate, AV_TIME_BASE);
1454     st->duration      = script.end_ts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE :
1455                         av_rescale(script.end_ts - script.start_ts,
1456                                    sbg->sample_rate, AV_TIME_BASE);
1457     st->cur_dts       = st->start_time;
1458     r = encode_intervals(&script, st->codecpar, &inter);
1459     if (r < 0)
1460         goto fail;
1461 
1462     av_free(inter.inter);
1463     free_script(&script);
1464     return 0;
1465 
1466 fail:
1467     av_free(inter.inter);
1468     free_script(&script);
1469     av_free(buf);
1470     return r;
1471 }
1472 
sbg_read_packet(AVFormatContext * avf,AVPacket * packet)1473 static int sbg_read_packet(AVFormatContext *avf, AVPacket *packet)
1474 {
1475     int64_t ts, end_ts;
1476     int ret;
1477 
1478     ts = avf->streams[0]->cur_dts;
1479     end_ts = ts + avf->streams[0]->codecpar->frame_size;
1480     if (avf->streams[0]->duration != AV_NOPTS_VALUE)
1481         end_ts = FFMIN(avf->streams[0]->start_time + avf->streams[0]->duration,
1482                        end_ts);
1483     if (end_ts <= ts)
1484         return AVERROR_EOF;
1485     if ((ret = av_new_packet(packet, 12)) < 0)
1486         return ret;
1487     packet->dts = packet->pts = ts;
1488     packet->duration = end_ts - ts;
1489     AV_WL64(packet->data + 0, ts);
1490     AV_WL32(packet->data + 8, packet->duration);
1491     return packet->size;
1492 }
1493 
sbg_read_seek2(AVFormatContext * avf,int stream_index,int64_t min_ts,int64_t ts,int64_t max_ts,int flags)1494 static int sbg_read_seek2(AVFormatContext *avf, int stream_index,
1495                           int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
1496 {
1497     if (flags || stream_index > 0)
1498         return AVERROR(EINVAL);
1499     if (stream_index < 0)
1500         ts = av_rescale_q(ts, AV_TIME_BASE_Q, avf->streams[0]->time_base);
1501     avf->streams[0]->cur_dts = ts;
1502     return 0;
1503 }
1504 
sbg_read_seek(AVFormatContext * avf,int stream_index,int64_t ts,int flags)1505 static int sbg_read_seek(AVFormatContext *avf, int stream_index,
1506                          int64_t ts, int flags)
1507 {
1508     return sbg_read_seek2(avf, stream_index, ts, ts, ts, 0);
1509 }
1510 
1511 static const AVOption sbg_options[] = {
1512     { "sample_rate", "", offsetof(struct sbg_demuxer, sample_rate),
1513       AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX,
1514       AV_OPT_FLAG_DECODING_PARAM },
1515     { "frame_size", "", offsetof(struct sbg_demuxer, frame_size),
1516       AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX,
1517       AV_OPT_FLAG_DECODING_PARAM },
1518     { "max_file_size", "", offsetof(struct sbg_demuxer, max_file_size),
1519       AV_OPT_TYPE_INT, { .i64 = 5000000 }, 0, INT_MAX,
1520       AV_OPT_FLAG_DECODING_PARAM },
1521     { NULL },
1522 };
1523 
1524 static const AVClass sbg_demuxer_class = {
1525     .class_name = "sbg_demuxer",
1526     .item_name  = av_default_item_name,
1527     .option     = sbg_options,
1528     .version    = LIBAVUTIL_VERSION_INT,
1529 };
1530 
1531 AVInputFormat ff_sbg_demuxer = {
1532     .name           = "sbg",
1533     .long_name      = NULL_IF_CONFIG_SMALL("SBaGen binaural beats script"),
1534     .priv_data_size = sizeof(struct sbg_demuxer),
1535     .read_probe     = sbg_read_probe,
1536     .read_header    = sbg_read_header,
1537     .read_packet    = sbg_read_packet,
1538     .read_seek      = sbg_read_seek,
1539     .read_seek2     = sbg_read_seek2,
1540     .extensions     = "sbg",
1541     .priv_class     = &sbg_demuxer_class,
1542 };
1543