2 * SBG (SBaGen) file format decoder
3 * Copyright (c) 2011 Nicolas George
5 * This file is part of FFmpeg.
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.
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.
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
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/log.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/time_internal.h"
32 #define SBG_SCALE (1 << 16)
33 #define DAY (24 * 60 * 60)
34 #define DAY_TS ((int64_t)DAY * AV_TIME_BASE)
55 int8_t in
, out
, slide
;
67 /* bell: freq constant, ampl decreases exponentially, can be approx lin */
69 struct sbg_timestamp
{
71 char type
; /* 0 for relative, 'N' for now, 'T' for absolute */
74 struct sbg_script_definition
{
77 int elements
, nb_elements
;
78 char type
; /* 'S' or 'B' */
81 struct sbg_script_synth
{
85 enum sbg_synth_type type
;
91 struct sbg_script_tseq
{
92 struct sbg_timestamp ts
;
99 struct sbg_script_event
{
101 int64_t ts_int
, ts_trans
, ts_next
;
102 int elements
, nb_elements
;
103 struct sbg_fade fade
;
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
;
118 int64_t opt_fade_time
;
119 int64_t opt_duration
;
122 uint8_t opt_start_at_first
;
123 uint8_t opt_end_at_last
;
130 struct sbg_script scs
;
131 struct sbg_timestamp current_time
;
133 int nb_def_max
, nb_synth_max
, nb_tseq_max
, nb_block_tseq_max
;
138 enum ws_interval_type
{
139 WS_SINE
= MKTAG('S','I','N','E'),
140 WS_NOISE
= MKTAG('N','O','I','S'),
145 enum ws_interval_type type
;
152 struct ws_intervals
{
153 struct ws_interval
*inter
;
158 static void *alloc_array_elem(void **array
, size_t elsize
,
159 int *size
, int *max_size
)
163 if (*size
== *max_size
) {
164 int m
= FFMAX(32, FFMIN(*max_size
, INT_MAX
/ 2) * 2);
167 *array
= av_realloc_f(*array
, m
, elsize
);
172 ret
= (char *)*array
+ elsize
* *size
;
173 memset(ret
, 0, elsize
);
178 static int str_to_time(const char *str
, int64_t *rtime
)
180 const char *cur
= str
;
186 if (*cur
< '0' || *cur
> '9')
188 hours
= strtol(cur
, &end
, 10);
189 if (end
== cur
|| *end
!= ':' || end
[1] < '0' || end
[1] > '9')
192 minutes
= strtol(cur
, &end
, 10);
197 seconds
= strtod(cur
+ 1, &end
);
200 ts
= av_clipd(seconds
* AV_TIME_BASE
, INT64_MIN
/2, INT64_MAX
/2);
202 *rtime
= av_sat_add64((hours
* 3600LL + minutes
* 60LL) * AV_TIME_BASE
, ts
);
206 static inline int is_space(char c
)
208 return c
== ' ' || c
== '\t' || c
== '\r';
211 static inline int scale_double(void *log
, double d
, double m
, int *r
)
214 if (m
< INT_MIN
|| m
>= INT_MAX
) {
216 av_log(log
, AV_LOG_ERROR
, "%g is too large\n", d
);
217 return AVERROR(EDOM
);
223 static int lex_space(struct sbg_parser
*p
)
227 while (p
->cursor
< p
->end
&& is_space(*p
->cursor
))
229 return p
->cursor
> c
;
232 static int lex_char(struct sbg_parser
*p
, char c
)
234 int r
= p
->cursor
< p
->end
&& *p
->cursor
== c
;
240 static int lex_double(struct sbg_parser
*p
, double *r
)
245 if (p
->cursor
== p
->end
|| is_space(*p
->cursor
) || *p
->cursor
== '\n')
247 d
= strtod(p
->cursor
, &end
);
248 if (end
> p
->cursor
) {
256 static int lex_fixed(struct sbg_parser
*p
, const char *t
, int l
)
258 if (p
->end
- p
->cursor
< l
|| memcmp(p
->cursor
, t
, l
))
264 static int lex_line_end(struct sbg_parser
*p
)
266 if (p
->cursor
< p
->end
&& *p
->cursor
== '#') {
268 while (p
->cursor
< p
->end
&& *p
->cursor
!= '\n')
271 if (p
->cursor
== p
->end
)
272 /* simulate final LF for files lacking it */
274 if (*p
->cursor
!= '\n')
282 static int lex_wsword(struct sbg_parser
*p
, struct sbg_string
*rs
)
284 char *s
= p
->cursor
, *c
= s
;
286 if (s
== p
->end
|| *s
== '\n')
288 while (c
< p
->end
&& *c
!= '\n' && !is_space(*c
))
291 rs
->e
= p
->cursor
= c
;
296 static int lex_name(struct sbg_parser
*p
, struct sbg_string
*rs
)
298 char *s
= p
->cursor
, *c
= s
;
300 while (c
< p
->end
&& ((*c
>= 'a' && *c
<= 'z') || (*c
>= 'A' && *c
<= 'Z')
301 || (*c
>= '0' && *c
<= '9') || *c
== '_' || *c
== '-'))
306 rs
->e
= p
->cursor
= c
;
310 static int lex_time(struct sbg_parser
*p
, int64_t *rt
)
312 int r
= str_to_time(p
->cursor
, rt
);
317 #define FORWARD_ERROR(c) \
321 return errcode ? errcode : AVERROR_INVALIDDATA; \
324 static int parse_immediate(struct sbg_parser
*p
)
326 snprintf(p
->err_msg
, sizeof(p
->err_msg
),
327 "immediate sequences not yet implemented");
328 return AVERROR_PATCHWELCOME
;
331 static int parse_preprogrammed(struct sbg_parser
*p
)
333 snprintf(p
->err_msg
, sizeof(p
->err_msg
),
334 "preprogrammed sequences not yet implemented");
335 return AVERROR_PATCHWELCOME
;
338 static int parse_optarg(struct sbg_parser
*p
, char o
, struct sbg_string
*r
)
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
;
348 static int parse_options(struct sbg_parser
*p
)
350 struct sbg_string ostr
, oarg
;
356 if (p
->cursor
== p
->end
|| *p
->cursor
!= '-')
358 while (lex_char(p
, '-') && lex_wsword(p
, &ostr
)) {
359 for (; ostr
.s
< ostr
.e
; ostr
.s
++) {
363 p
->scs
.opt_start_at_first
= 1;
366 p
->scs
.opt_end_at_last
= 1;
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
;
382 p
->scs
.opt_fade_time
= v
* AV_TIME_BASE
/ 1000;
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
|| p
->scs
.opt_duration
< 0) {
388 snprintf(p
->err_msg
, sizeof(p
->err_msg
),
389 "syntax error for option -L");
390 return AVERROR_INVALIDDATA
;
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
;
403 FORWARD_ERROR(parse_optarg(p
, opt
, &oarg
));
404 tptr
= av_malloc(oarg
.e
- oarg
.s
+ 1);
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
;
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
;
421 snprintf(p
->err_msg
, sizeof(p
->err_msg
),
422 "speed factor other than 1 not supported");
423 return AVERROR_PATCHWELCOME
;
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
;
435 snprintf(p
->err_msg
, sizeof(p
->err_msg
),
436 "invalid sample rate");
437 return AVERROR_PATCHWELCOME
;
439 p
->scs
.sample_rate
= r
;
442 snprintf(p
->err_msg
, sizeof(p
->err_msg
),
443 "unknown option: '%c'", *ostr
.s
);
444 return AVERROR_INVALIDDATA
;
450 return parse_immediate(p
);
452 return parse_preprogrammed(p
);
454 if (!lex_line_end(p
))
455 return AVERROR_INVALIDDATA
;
461 static int parse_timestamp(struct sbg_parser
*p
,
462 struct sbg_timestamp
*rts
, int64_t *rrel
)
464 int64_t abs
= 0, rel
= 0, dt
;
468 if (lex_fixed(p
, "NOW", 3)) {
472 r
= lex_time(p
, &abs
);
476 while (lex_char(p
, '+')) {
477 if (!lex_time(p
, &dt
))
478 return AVERROR_INVALIDDATA
;
484 return AVERROR_INVALIDDATA
;
492 static int parse_fade(struct sbg_parser
*p
, struct sbg_fade
*fr
)
494 struct sbg_fade f
= {0};
496 if (lex_char(p
, '<'))
497 f
.in
= SBG_FADE_SILENCE
;
498 else if (lex_char(p
, '-'))
499 f
.in
= SBG_FADE_SAME
;
500 else if (lex_char(p
, '='))
501 f
.in
= SBG_FADE_ADAPT
;
504 if (lex_char(p
, '>'))
505 f
.out
= SBG_FADE_SILENCE
;
506 else if (lex_char(p
, '-'))
507 f
.out
= SBG_FADE_SAME
;
508 else if (lex_char(p
, '='))
509 f
.out
= SBG_FADE_ADAPT
;
511 return AVERROR_INVALIDDATA
;
516 static int parse_time_sequence(struct sbg_parser
*p
, int inblock
)
518 struct sbg_timestamp ts
;
521 struct sbg_fade fade
= { SBG_FADE_SAME
, SBG_FADE_SAME
, 0 };
522 struct sbg_string name
;
523 struct sbg_script_tseq
*tseq
;
525 r
= parse_timestamp(p
, &ts
, &rel_ts
);
532 return AVERROR_INVALIDDATA
;
533 p
->current_time
.type
= ts
.type
;
534 p
->current_time
.t
= ts
.t
;
535 } else if(!inblock
&& !p
->current_time
.type
) {
536 snprintf(p
->err_msg
, sizeof(p
->err_msg
),
537 "relative time without previous absolute time");
538 return AVERROR_INVALIDDATA
;
540 ts
.type
= p
->current_time
.type
;
542 if (av_sat_add64(p
->current_time
.t
, rel_ts
) != p
->current_time
.t
+ (uint64_t)rel_ts
)
543 return AVERROR_INVALIDDATA
;
544 ts
.t
= p
->current_time
.t
+ rel_ts
;
545 r
= parse_fade(p
, &fade
);
549 if (!lex_name(p
, &name
))
550 return AVERROR_INVALIDDATA
;
552 if (lex_fixed(p
, "->", 2)) {
553 fade
.slide
= SBG_FADE_ADAPT
;
556 if (!lex_line_end(p
))
557 return AVERROR_INVALIDDATA
;
559 alloc_array_elem((void **)&p
->scs
.block_tseq
, sizeof(*tseq
),
560 &p
->nb_block_tseq
, &p
->nb_block_tseq_max
) :
561 alloc_array_elem((void **)&p
->scs
.tseq
, sizeof(*tseq
),
562 &p
->scs
.nb_tseq
, &p
->nb_tseq_max
);
564 return AVERROR(ENOMEM
);
567 tseq
->name_len
= name
.e
- name
.s
;
572 static int parse_wave_def(struct sbg_parser
*p
, int wavenum
)
574 snprintf(p
->err_msg
, sizeof(p
->err_msg
),
575 "waveform definitions not yet implemented");
576 return AVERROR_PATCHWELCOME
;
579 static int parse_block_def(struct sbg_parser
*p
,
580 struct sbg_script_definition
*def
)
585 if (!lex_line_end(p
))
586 return AVERROR_INVALIDDATA
;
587 tseq
= p
->nb_block_tseq
;
589 r
= parse_time_sequence(p
, 1);
595 if (!lex_char(p
, '}'))
596 return AVERROR_INVALIDDATA
;
598 if (!lex_line_end(p
))
599 return AVERROR_INVALIDDATA
;
601 def
->elements
= tseq
;
602 def
->nb_elements
= p
->nb_block_tseq
- tseq
;
603 if (!def
->nb_elements
)
604 return AVERROR_INVALIDDATA
;
608 static int parse_volume(struct sbg_parser
*p
, int *vol
)
612 if (!lex_char(p
, '/'))
614 if (!lex_double(p
, &v
))
615 return AVERROR_INVALIDDATA
;
616 if (scale_double(p
->log
, v
, 0.01, vol
))
617 return AVERROR(ERANGE
);
621 static int parse_synth_channel_sine(struct sbg_parser
*p
,
622 struct sbg_script_synth
*synth
)
624 double carrierf
, beatf
;
625 int carrier
, beat
, vol
;
627 if (!lex_double(p
, &carrierf
))
629 if (!lex_double(p
, &beatf
))
631 FORWARD_ERROR(parse_volume(p
, &vol
));
632 if (scale_double(p
->log
, carrierf
, 1, &carrier
) < 0 ||
633 scale_double(p
->log
, beatf
, 1, &beat
) < 0)
634 return AVERROR(EDOM
);
635 synth
->type
= SBG_TYPE_SINE
;
636 synth
->carrier
= carrier
;
642 static int parse_synth_channel_pink(struct sbg_parser
*p
,
643 struct sbg_script_synth
*synth
)
647 if (!lex_fixed(p
, "pink", 4))
649 FORWARD_ERROR(parse_volume(p
, &vol
));
650 synth
->type
= SBG_TYPE_NOISE
;
655 static int parse_synth_channel_bell(struct sbg_parser
*p
,
656 struct sbg_script_synth
*synth
)
661 if (!lex_fixed(p
, "bell", 4))
663 if (!lex_double(p
, &carrierf
))
664 return AVERROR_INVALIDDATA
;
665 FORWARD_ERROR(parse_volume(p
, &vol
));
666 if (scale_double(p
->log
, carrierf
, 1, &carrier
) < 0)
667 return AVERROR(EDOM
);
668 synth
->type
= SBG_TYPE_BELL
;
669 synth
->carrier
= carrier
;
674 static int parse_synth_channel_mix(struct sbg_parser
*p
,
675 struct sbg_script_synth
*synth
)
679 if (!lex_fixed(p
, "mix", 3))
681 FORWARD_ERROR(parse_volume(p
, &vol
));
682 synth
->type
= SBG_TYPE_MIX
;
687 static int parse_synth_channel_spin(struct sbg_parser
*p
,
688 struct sbg_script_synth
*synth
)
690 double carrierf
, beatf
;
691 int carrier
, beat
, vol
;
693 if (!lex_fixed(p
, "spin:", 5))
695 if (!lex_double(p
, &carrierf
))
696 return AVERROR_INVALIDDATA
;
697 if (!lex_double(p
, &beatf
))
698 return AVERROR_INVALIDDATA
;
699 FORWARD_ERROR(parse_volume(p
, &vol
));
700 if (scale_double(p
->log
, carrierf
, 1, &carrier
) < 0 ||
701 scale_double(p
->log
, beatf
, 1, &beat
) < 0)
702 return AVERROR(EDOM
);
703 synth
->type
= SBG_TYPE_SPIN
;
704 synth
->carrier
= carrier
;
710 static int parse_synth_channel(struct sbg_parser
*p
)
713 struct sbg_script_synth
*synth
;
715 synth
= alloc_array_elem((void **)&p
->scs
.synth
, sizeof(*synth
),
716 &p
->scs
.nb_synth
, &p
->nb_synth_max
);
718 return AVERROR(ENOMEM
);
719 r
= lex_char(p
, '-');
721 r
= parse_synth_channel_pink(p
, synth
);
723 r
= parse_synth_channel_bell(p
, synth
);
725 r
= parse_synth_channel_mix(p
, synth
);
727 r
= parse_synth_channel_spin(p
, synth
);
728 /* Unimplemented: wave%d:%f%f/vol (carrier, beat) */
730 r
= parse_synth_channel_sine(p
, synth
);
736 static int parse_synth_def(struct sbg_parser
*p
,
737 struct sbg_script_definition
*def
)
741 synth
= p
->scs
.nb_synth
;
743 r
= parse_synth_channel(p
);
746 if (!r
|| !lex_space(p
))
750 if (synth
== p
->scs
.nb_synth
)
751 return AVERROR_INVALIDDATA
;
752 if (!lex_line_end(p
))
753 return AVERROR_INVALIDDATA
;
755 def
->elements
= synth
;
756 def
->nb_elements
= p
->scs
.nb_synth
- synth
;
760 static int parse_named_def(struct sbg_parser
*p
)
762 char *cursor_save
= p
->cursor
;
763 struct sbg_string name
;
764 struct sbg_script_definition
*def
;
766 if (!lex_name(p
, &name
) || !lex_char(p
, ':') || !lex_space(p
)) {
767 p
->cursor
= cursor_save
;
770 if (name
.e
- name
.s
== 6 && !memcmp(name
.s
, "wave", 4) &&
771 name
.s
[4] >= '0' && name
.s
[4] <= '9' &&
772 name
.s
[5] >= '0' && name
.s
[5] <= '9') {
773 int wavenum
= (name
.s
[4] - '0') * 10 + (name
.s
[5] - '0');
774 return parse_wave_def(p
, wavenum
);
776 def
= alloc_array_elem((void **)&p
->scs
.def
, sizeof(*def
),
777 &p
->scs
.nb_def
, &p
->nb_def_max
);
779 return AVERROR(ENOMEM
);
781 def
->name_len
= name
.e
- name
.s
;
782 if (lex_char(p
, '{'))
783 return parse_block_def(p
, def
);
784 return parse_synth_def(p
, def
);
787 static void free_script(struct sbg_script
*s
)
792 av_freep(&s
->block_tseq
);
793 av_freep(&s
->events
);
794 av_freep(&s
->opt_mix
);
797 static int parse_script(void *log
, char *script
, int script_len
,
798 struct sbg_script
*rscript
)
800 struct sbg_parser sp
= {
803 .end
= script
+ script_len
,
809 .start_ts
= AV_NOPTS_VALUE
,
810 .sample_rate
= 44100,
811 .opt_fade_time
= 60 * AV_TIME_BASE
,
817 while (sp
.cursor
< sp
.end
) {
818 r
= parse_options(&sp
);
821 if (!r
&& !lex_line_end(&sp
))
824 while (sp
.cursor
< sp
.end
) {
825 r
= parse_named_def(&sp
);
827 r
= parse_time_sequence(&sp
, 0);
829 r
= lex_line_end(&sp
) ? 1 : AVERROR_INVALIDDATA
;
836 free_script(&sp
.scs
);
838 if (r
== AVERROR_INVALIDDATA
)
839 snprintf(sp
.err_msg
, sizeof(sp
.err_msg
), "syntax error");
840 if (log
&& *sp
.err_msg
) {
841 const char *ctx
= sp
.cursor
;
842 const char *ectx
= av_x_if_null(memchr(ctx
, '\n', sp
.end
- sp
.cursor
),
844 int lctx
= ectx
- ctx
;
845 const char *quote
= "\"";
846 if (lctx
> 0 && ctx
[lctx
- 1] == '\r')
849 ctx
= "the end of line";
853 av_log(log
, AV_LOG_ERROR
, "Error line %d: %s near %s%.*s%s.\n",
854 sp
.line_no
, sp
.err_msg
, quote
, lctx
, ctx
, quote
);
859 static int read_whole_file(AVIOContext
*io
, int max_size
, char **rbuf
)
862 int size
= 0, bufsize
= 0, r
;
865 if (bufsize
- size
< 1024) {
866 bufsize
= FFMIN(FFMAX(2 * bufsize
, 8192), max_size
);
867 if (bufsize
- size
< 2) {
868 size
= AVERROR(EFBIG
);
871 buf
= av_realloc_f(buf
, bufsize
, 1);
873 size
= AVERROR(ENOMEM
);
877 r
= avio_read(io
, buf
, bufsize
- size
- 1);
878 if (r
== AVERROR_EOF
)
892 static int expand_timestamps(void *log
, struct sbg_script
*s
)
895 int64_t now
, cur_ts
, delta
= 0;
897 for (i
= 0; i
< s
->nb_tseq
; i
++)
898 nb_rel
+= s
->tseq
[i
].ts
.type
== 'N';
899 if (nb_rel
== s
->nb_tseq
) {
900 /* All ts are relative to NOW: consider NOW = 0 */
902 if (s
->start_ts
!= AV_NOPTS_VALUE
)
903 av_log(log
, AV_LOG_WARNING
,
904 "Start time ignored in a purely relative script.\n");
905 } else if (nb_rel
== 0 && s
->start_ts
!= AV_NOPTS_VALUE
||
906 s
->opt_start_at_first
) {
907 /* All ts are absolute and start time is specified */
908 if (s
->start_ts
== AV_NOPTS_VALUE
)
909 s
->start_ts
= s
->tseq
[0].ts
.t
;
912 /* Mixed relative/absolute ts: expand */
914 struct tm
*tm
, tmpbuf
;
916 av_log(log
, AV_LOG_WARNING
,
917 "Scripts with mixed absolute and relative timestamps can give "
918 "unexpected results (pause, seeking, time zone change).\n");
921 tm
= localtime_r(&now0
, &tmpbuf
);
922 now
= tm
? tm
->tm_hour
* 3600 + tm
->tm_min
* 60 + tm
->tm_sec
:
924 av_log(log
, AV_LOG_INFO
, "Using %02d:%02d:%02d as NOW.\n",
925 (int)(now
/ 3600), (int)(now
/ 60) % 60, (int)now
% 60);
927 for (i
= 0; i
< s
->nb_tseq
; i
++) {
928 if (s
->tseq
[i
].ts
.type
== 'N') {
929 s
->tseq
[i
].ts
.t
+= now
;
930 s
->tseq
[i
].ts
.type
= 'T'; /* not necessary */
934 if (s
->start_ts
== AV_NOPTS_VALUE
)
935 s
->start_ts
= (s
->opt_start_at_first
&& s
->tseq
) ? s
->tseq
[0].ts
.t
: now
;
936 if (s
->start_ts
> INT64_MAX
- s
->opt_duration
)
937 return AVERROR_INVALIDDATA
;
939 s
->end_ts
= s
->opt_duration
? s
->start_ts
+ s
->opt_duration
:
940 AV_NOPTS_VALUE
; /* may be overridden later by -E option */
942 for (i
= 0; i
< s
->nb_tseq
; i
++) {
943 if (av_sat_add64(s
->tseq
[i
].ts
.t
, delta
) != s
->tseq
[i
].ts
.t
+ (uint64_t)delta
)
944 return AVERROR_INVALIDDATA
;
945 if (s
->tseq
[i
].ts
.t
+ delta
< cur_ts
)
947 cur_ts
= s
->tseq
[i
].ts
.t
+= delta
;
952 static int expand_tseq(void *log
, struct sbg_script
*s
, int *nb_ev_max
,
953 int64_t t0
, struct sbg_script_tseq
*tseq
)
956 struct sbg_script_definition
*def
;
957 struct sbg_script_tseq
*be
;
958 struct sbg_script_event
*ev
;
961 av_log(log
, AV_LOG_ERROR
, "Recursion loop on \"%.*s\"\n",
962 tseq
->name_len
, tseq
->name
);
963 return AVERROR(EINVAL
);
965 if (t0
+ (uint64_t)tseq
->ts
.t
!= av_sat_add64(t0
, tseq
->ts
.t
))
966 return AVERROR(EINVAL
);
969 for (i
= 0; i
< s
->nb_def
; i
++) {
970 if (s
->def
[i
].name_len
== tseq
->name_len
&&
971 !memcmp(s
->def
[i
].name
, tseq
->name
, tseq
->name_len
))
974 if (i
>= s
->nb_def
) {
975 av_log(log
, AV_LOG_ERROR
, "Tone-set \"%.*s\" not defined\n",
976 tseq
->name_len
, tseq
->name
);
977 return AVERROR(EINVAL
);
980 if (def
->type
== 'B') {
981 be
= s
->block_tseq
+ def
->elements
;
982 for (i
= 0; i
< def
->nb_elements
; i
++) {
983 r
= expand_tseq(log
, s
, nb_ev_max
, t0
, &be
[i
]);
988 ev
= alloc_array_elem((void **)&s
->events
, sizeof(*ev
),
989 &s
->nb_events
, nb_ev_max
);
991 return AVERROR(ENOMEM
);
993 ev
->elements
= def
->elements
;
994 ev
->nb_elements
= def
->nb_elements
;
995 ev
->fade
= tseq
->fade
;
1001 static int expand_script(void *log
, struct sbg_script
*s
)
1003 int i
, r
, nb_events_max
= 0;
1005 r
= expand_timestamps(log
, s
);
1008 for (i
= 0; i
< s
->nb_tseq
; i
++) {
1009 r
= expand_tseq(log
, s
, &nb_events_max
, 0, &s
->tseq
[i
]);
1013 if (!s
->nb_events
) {
1014 av_log(log
, AV_LOG_ERROR
, "No events in script\n");
1015 return AVERROR_INVALIDDATA
;
1017 if (s
->opt_end_at_last
)
1018 s
->end_ts
= s
->events
[s
->nb_events
- 1].ts
;
1022 static int add_interval(struct ws_intervals
*inter
,
1023 enum ws_interval_type type
, uint32_t channels
, int ref
,
1024 int64_t ts1
, int32_t f1
, int32_t a1
,
1025 int64_t ts2
, int32_t f2
, int32_t a2
)
1027 struct ws_interval
*i
, *ri
;
1030 ri
= &inter
->inter
[ref
];
1031 /* ref and new intervals are constant, identical and adjacent */
1032 if (ri
->type
== type
&& ri
->channels
== channels
&&
1033 ri
->f1
== ri
->f2
&& ri
->f2
== f1
&& f1
== f2
&&
1034 ri
->a1
== ri
->a2
&& ri
->a2
== a1
&& a1
== a2
&&
1040 i
= alloc_array_elem((void **)&inter
->inter
, sizeof(*i
),
1041 &inter
->nb_inter
, &inter
->max_inter
);
1043 return AVERROR(ENOMEM
);
1047 i
->channels
= channels
;
1052 i
->phi
= ref
>= 0 ? ref
| 0x80000000 : 0;
1053 return i
- inter
->inter
;
1056 static int add_bell(struct ws_intervals
*inter
, struct sbg_script
*s
,
1057 int64_t ts1
, int64_t ts2
, int32_t f
, int32_t a
)
1059 /* SBaGen uses an exponential decrease every 50ms.
1060 We approximate it with piecewise affine segments. */
1061 int32_t cpoints
[][2] = {
1071 int64_t dt
= s
->sample_rate
/ 20, ts3
= ts1
, ts4
;
1072 for (i
= 0; i
< FF_ARRAY_ELEMS(cpoints
); i
++) {
1073 ts4
= FFMIN(ts2
, ts1
+ cpoints
[i
][0] * dt
);
1074 r
= add_interval(inter
, WS_SINE
, 3, -1,
1075 ts3
, f
, a
, ts4
, f
, cpoints
[i
][1]);
1084 static int generate_interval(void *log
, struct sbg_script
*s
,
1085 struct ws_intervals
*inter
,
1086 int64_t ts1
, int64_t ts2
,
1087 struct sbg_script_synth
*s1
,
1088 struct sbg_script_synth
*s2
,
1093 if (ts2
<= ts1
|| (s1
->vol
== 0 && s2
->vol
== 0))
1099 if (s1
->beat
== 0 && s2
->beat
== 0) {
1100 r
= add_interval(inter
, WS_SINE
, 3, s1
->ref
.l
,
1101 ts1
, s1
->carrier
, s1
->vol
,
1102 ts2
, s2
->carrier
, s2
->vol
);
1105 s2
->ref
.l
= s2
->ref
.r
= r
;
1107 r
= add_interval(inter
, WS_SINE
, 1, s1
->ref
.l
,
1108 ts1
, s1
->carrier
+ s1
->beat
/ 2, s1
->vol
,
1109 ts2
, s2
->carrier
+ s2
->beat
/ 2, s2
->vol
);
1113 r
= add_interval(inter
, WS_SINE
, 2, s1
->ref
.r
,
1114 ts1
, s1
->carrier
- s1
->beat
/ 2, s1
->vol
,
1115 ts2
, s2
->carrier
- s2
->beat
/ 2, s2
->vol
);
1123 if (transition
== 2) {
1124 r
= add_bell(inter
, s
, ts1
, ts2
, s1
->carrier
, s2
->vol
);
1131 av_log(log
, AV_LOG_WARNING
, "Spinning noise not implemented, "
1132 "using pink noise instead.\n");
1134 case SBG_TYPE_NOISE
:
1135 /* SBaGen's pink noise generator uses:
1136 - 1 band of white noise, mean square: 1/3;
1137 - 9 bands of subsampled white noise with linear
1138 interpolation, mean square: 2/3 each;
1139 with 1/10 weight each: the total mean square is 7/300.
1140 Our pink noise generator uses 8 bands of white noise with
1141 rectangular subsampling: the total mean square is 1/24.
1142 Therefore, to match SBaGen's volume, we must multiply vol by
1143 sqrt((7/300) / (1/24)) = sqrt(14/25) =~ 0.748
1145 r
= add_interval(inter
, WS_NOISE
, 3, s1
->ref
.l
,
1146 ts1
, 0, s1
->vol
- s1
->vol
/ 4,
1147 ts2
, 0, s2
->vol
- s2
->vol
/ 4);
1150 s2
->ref
.l
= s2
->ref
.r
= r
;
1154 /* Unimplemented: silence; warning present elsewhere */
1156 av_log(log
, AV_LOG_ERROR
,
1157 "Type %d is not implemented\n", s1
->type
);
1158 return AVERROR_PATCHWELCOME
;
1163 static int generate_plateau(void *log
, struct sbg_script
*s
,
1164 struct ws_intervals
*inter
,
1165 struct sbg_script_event
*ev1
)
1167 int64_t ts1
= ev1
->ts_int
, ts2
= ev1
->ts_trans
;
1169 struct sbg_script_synth
*s1
;
1171 for (i
= 0; i
< ev1
->nb_elements
; i
++) {
1172 s1
= &s
->synth
[ev1
->elements
+ i
];
1173 r
= generate_interval(log
, s
, inter
, ts1
, ts2
, s1
, s1
, 0);
1182 ts1 ts2 ts1 tsmid ts2
1187 ''''....____ ''....''
1189 compatible transition incompatible transition
1192 static int generate_transition(void *log
, struct sbg_script
*s
,
1193 struct ws_intervals
*inter
,
1194 struct sbg_script_event
*ev1
,
1195 struct sbg_script_event
*ev2
)
1197 int64_t ts1
= ev1
->ts_trans
, ts2
= ev1
->ts_next
;
1198 /* (ts1 + ts2) / 2 without overflow */
1199 int64_t tsmid
= (ts1
>> 1) + (ts2
>> 1) + (ts1
& ts2
& 1);
1200 enum sbg_fade_type type
= ev1
->fade
.slide
| (ev1
->fade
.out
& ev2
->fade
.in
);
1201 int nb_elements
= FFMAX(ev1
->nb_elements
, ev2
->nb_elements
);
1202 struct sbg_script_synth
*s1
, *s2
, s1mod
, s2mod
, smid
;
1205 for (pass
= 0; pass
< 2; pass
++) {
1206 /* pass = 0 -> compatible and first half of incompatible
1207 pass = 1 -> second half of incompatible
1208 Using two passes like that ensures that the intervals are generated
1209 in increasing order according to their start timestamp.
1210 Otherwise it would be necessary to sort them
1211 while keeping the mutual references.
1213 for (i
= 0; i
< nb_elements
; i
++) {
1214 s1
= i
< ev1
->nb_elements
? &s
->synth
[ev1
->elements
+ i
] : &s1mod
;
1215 s2
= i
< ev2
->nb_elements
? &s
->synth
[ev2
->elements
+ i
] : &s2mod
;
1216 s1mod
= s1
!= &s1mod
? *s1
: (struct sbg_script_synth
){ 0 };
1217 s2mod
= s2
!= &s2mod
? *s2
: (struct sbg_script_synth
){ 0 };
1218 if (ev1
->fade
.slide
) {
1219 /* for slides, and only for slides, silence ("-") is equivalent
1220 to anything with volume 0 */
1221 if (s1mod
.type
== SBG_TYPE_NONE
) {
1224 } else if (s2mod
.type
== SBG_TYPE_NONE
) {
1229 if (s1mod
.type
== s2mod
.type
&&
1230 s1mod
.type
!= SBG_TYPE_BELL
&&
1231 (type
== SBG_FADE_ADAPT
||
1232 (s1mod
.carrier
== s2mod
.carrier
&&
1233 s1mod
.beat
== s2mod
.beat
))) {
1234 /* compatible: single transition */
1236 r
= generate_interval(log
, s
, inter
,
1237 ts1
, ts2
, &s1mod
, &s2mod
, 3);
1240 s2
->ref
= s2mod
.ref
;
1243 /* incompatible: silence at midpoint */
1247 r
= generate_interval(log
, s
, inter
,
1248 ts1
, tsmid
, &s1mod
, &smid
, 1);
1254 r
= generate_interval(log
, s
, inter
,
1255 tsmid
, ts2
, &smid
, &s2mod
, 2);
1258 s2
->ref
= s2mod
.ref
;
1267 ev1 trats ev2 intts endts ev3
1272 '''....________________....''' '''...._______________
1274 \_________/\______________/\_________/\______________/\_________/\_____________/
1275 tr x->1 int1 tr 1->2 int2 tr 2->3 int3
1278 static int generate_intervals(void *log
, struct sbg_script
*s
, int sample_rate
,
1279 struct ws_intervals
*inter
)
1281 int64_t trans_time
= s
->opt_fade_time
/ 2;
1282 struct sbg_script_event ev0
, *ev1
, *ev2
;
1286 /* SBaGen handles the time before and after the extremal events,
1287 and the corresponding transitions, as if the sequence were cyclic
1288 with a 24-hours period. */
1289 period
= s
->events
[s
->nb_events
- 1].ts
- (uint64_t)s
->events
[0].ts
;
1291 return AVERROR_INVALIDDATA
;
1293 period
= (period
+ (DAY_TS
- 1)) / DAY_TS
* DAY_TS
;
1294 period
= FFMAX(period
, DAY_TS
);
1296 /* Prepare timestamps for transitions */
1297 for (i
= 0; i
< s
->nb_events
; i
++) {
1298 ev1
= &s
->events
[i
];
1299 ev2
= &s
->events
[(i
+ 1) % s
->nb_events
];
1300 ev1
->ts_int
= ev1
->ts
;
1302 if (!ev1
->fade
.slide
&& ev1
>= ev2
&& ev2
->ts
> INT64_MAX
- period
)
1303 return AVERROR_INVALIDDATA
;
1305 ev1
->ts_trans
= ev1
->fade
.slide
? ev1
->ts
1306 : ev2
->ts
+ (ev1
< ev2
? 0 : period
);
1308 for (i
= 0; i
< s
->nb_events
; i
++) {
1309 ev1
= &s
->events
[i
];
1310 ev2
= &s
->events
[(i
+ 1) % s
->nb_events
];
1311 if (!ev1
->fade
.slide
) {
1312 ev1
->ts_trans
= FFMAX(ev1
->ts_int
, ev1
->ts_trans
- trans_time
);
1313 ev2
->ts_int
= FFMIN(ev2
->ts_trans
, ev2
->ts_int
+ trans_time
);
1315 ev1
->ts_next
= ev2
->ts_int
+ (ev1
< ev2
? 0 : period
);
1318 /* Pseudo event before the first one */
1319 ev0
= s
->events
[s
->nb_events
- 1];
1320 if (av_sat_sub64(ev0
.ts_int
, period
) != (uint64_t)ev0
.ts_int
- period
)
1321 return AVERROR_INVALIDDATA
;
1322 ev0
.ts_int
-= period
;
1323 ev0
.ts_trans
-= period
;
1324 ev0
.ts_next
-= period
;
1326 /* Convert timestamps */
1327 for (i
= -1; i
< s
->nb_events
; i
++) {
1328 ev1
= i
< 0 ? &ev0
: &s
->events
[i
];
1329 ev1
->ts_int
= av_rescale(ev1
->ts_int
, sample_rate
, AV_TIME_BASE
);
1330 ev1
->ts_trans
= av_rescale(ev1
->ts_trans
, sample_rate
, AV_TIME_BASE
);
1331 ev1
->ts_next
= av_rescale(ev1
->ts_next
, sample_rate
, AV_TIME_BASE
);
1334 /* Generate intervals */
1335 for (i
= 0; i
< s
->nb_synth
; i
++)
1336 s
->synth
[i
].ref
.l
= s
->synth
[i
].ref
.r
= -1;
1337 for (i
= -1; i
< s
->nb_events
; i
++) {
1338 ev1
= i
< 0 ? &ev0
: &s
->events
[i
];
1339 ev2
= &s
->events
[(i
+ 1) % s
->nb_events
];
1340 r
= generate_plateau(log
, s
, inter
, ev1
);
1343 r
= generate_transition(log
, s
, inter
, ev1
, ev2
);
1347 if (!inter
->nb_inter
)
1348 av_log(log
, AV_LOG_WARNING
, "Completely silent script.\n");
1352 static int encode_intervals(struct sbg_script
*s
, AVCodecParameters
*par
,
1353 struct ws_intervals
*inter
)
1355 int i
, edata_size
= 4, ret
;
1358 for (i
= 0; i
< inter
->nb_inter
; i
++) {
1359 edata_size
+= inter
->inter
[i
].type
== WS_SINE
? 44 :
1360 inter
->inter
[i
].type
== WS_NOISE
? 32 : 0;
1362 return AVERROR(ENOMEM
);
1364 if ((ret
= ff_alloc_extradata(par
, edata_size
)) < 0)
1366 edata
= par
->extradata
;
1368 #define ADD_EDATA32(v) do { AV_WL32(edata, (v)); edata += 4; } while(0)
1369 #define ADD_EDATA64(v) do { AV_WL64(edata, (v)); edata += 8; } while(0)
1370 ADD_EDATA32(inter
->nb_inter
);
1371 for (i
= 0; i
< inter
->nb_inter
; i
++) {
1372 ADD_EDATA64(inter
->inter
[i
].ts1
);
1373 ADD_EDATA64(inter
->inter
[i
].ts2
);
1374 ADD_EDATA32(inter
->inter
[i
].type
);
1375 ADD_EDATA32(inter
->inter
[i
].channels
);
1376 switch (inter
->inter
[i
].type
) {
1378 ADD_EDATA32(inter
->inter
[i
].f1
);
1379 ADD_EDATA32(inter
->inter
[i
].f2
);
1380 ADD_EDATA32(inter
->inter
[i
].a1
);
1381 ADD_EDATA32(inter
->inter
[i
].a2
);
1382 ADD_EDATA32(inter
->inter
[i
].phi
);
1385 ADD_EDATA32(inter
->inter
[i
].a1
);
1386 ADD_EDATA32(inter
->inter
[i
].a2
);
1390 if (edata
!= par
->extradata
+ edata_size
)
1395 static av_cold
int sbg_read_probe(const AVProbeData
*p
)
1398 struct sbg_script script
= { 0 };
1400 r
= parse_script(NULL
, p
->buf
, p
->buf_size
, &script
);
1401 score
= r
< 0 || !script
.nb_def
|| !script
.nb_tseq
? 0 :
1402 AVPROBE_SCORE_MAX
/ 3;
1403 free_script(&script
);
1407 static av_cold
int sbg_read_header(AVFormatContext
*avf
)
1409 struct sbg_demuxer
*sbg
= avf
->priv_data
;
1412 struct sbg_script script
= { 0 };
1414 struct ws_intervals inter
= { 0 };
1416 r
= read_whole_file(avf
->pb
, sbg
->max_file_size
, &buf
);
1419 r
= parse_script(avf
, buf
, r
, &script
);
1422 if (!sbg
->sample_rate
)
1423 sbg
->sample_rate
= script
.sample_rate
;
1425 script
.sample_rate
= sbg
->sample_rate
;
1426 if (!sbg
->frame_size
)
1427 sbg
->frame_size
= FFMAX(1, sbg
->sample_rate
/ 10);
1429 av_log(avf
, AV_LOG_WARNING
, "Mix feature not implemented: "
1430 "-m is ignored and mix channels will be silent.\n");
1431 r
= expand_script(avf
, &script
);
1435 r
= generate_intervals(avf
, &script
, sbg
->sample_rate
, &inter
);
1439 if (script
.end_ts
!= AV_NOPTS_VALUE
&& script
.end_ts
< script
.start_ts
) {
1440 r
= AVERROR_INVALIDDATA
;
1444 st
= avformat_new_stream(avf
, NULL
);
1446 return AVERROR(ENOMEM
);
1447 st
->codecpar
->codec_type
= AVMEDIA_TYPE_AUDIO
;
1448 st
->codecpar
->codec_id
= AV_CODEC_ID_FFWAVESYNTH
;
1449 st
->codecpar
->channels
= 2;
1450 st
->codecpar
->channel_layout
= AV_CH_LAYOUT_STEREO
;
1451 st
->codecpar
->sample_rate
= sbg
->sample_rate
;
1452 st
->codecpar
->frame_size
= sbg
->frame_size
;
1453 avpriv_set_pts_info(st
, 64, 1, st
->codecpar
->sample_rate
);
1454 st
->probe_packets
= 0;
1455 st
->start_time
= av_rescale(script
.start_ts
,
1456 sbg
->sample_rate
, AV_TIME_BASE
);
1457 st
->duration
= script
.end_ts
== AV_NOPTS_VALUE
? AV_NOPTS_VALUE
:
1458 av_rescale(script
.end_ts
- script
.start_ts
,
1459 sbg
->sample_rate
, AV_TIME_BASE
);
1460 st
->cur_dts
= st
->start_time
;
1461 r
= encode_intervals(&script
, st
->codecpar
, &inter
);
1465 av_free(inter
.inter
);
1466 free_script(&script
);
1470 av_free(inter
.inter
);
1471 free_script(&script
);
1476 static int sbg_read_packet(AVFormatContext
*avf
, AVPacket
*packet
)
1481 ts
= avf
->streams
[0]->cur_dts
;
1482 end_ts
= ts
+ avf
->streams
[0]->codecpar
->frame_size
;
1483 if (avf
->streams
[0]->duration
!= AV_NOPTS_VALUE
)
1484 end_ts
= FFMIN(avf
->streams
[0]->start_time
+ avf
->streams
[0]->duration
,
1488 if ((ret
= av_new_packet(packet
, 12)) < 0)
1490 packet
->dts
= packet
->pts
= ts
;
1491 packet
->duration
= end_ts
- ts
;
1492 AV_WL64(packet
->data
+ 0, ts
);
1493 AV_WL32(packet
->data
+ 8, packet
->duration
);
1494 return packet
->size
;
1497 static int sbg_read_seek2(AVFormatContext
*avf
, int stream_index
,
1498 int64_t min_ts
, int64_t ts
, int64_t max_ts
, int flags
)
1500 if (flags
|| stream_index
> 0)
1501 return AVERROR(EINVAL
);
1502 if (stream_index
< 0)
1503 ts
= av_rescale_q(ts
, AV_TIME_BASE_Q
, avf
->streams
[0]->time_base
);
1504 avf
->streams
[0]->cur_dts
= ts
;
1508 static int sbg_read_seek(AVFormatContext
*avf
, int stream_index
,
1509 int64_t ts
, int flags
)
1511 return sbg_read_seek2(avf
, stream_index
, ts
, ts
, ts
, 0);
1514 static const AVOption sbg_options
[] = {
1515 { "sample_rate", "", offsetof(struct sbg_demuxer
, sample_rate
),
1516 AV_OPT_TYPE_INT
, { .i64
= 0 }, 0, INT_MAX
,
1517 AV_OPT_FLAG_DECODING_PARAM
},
1518 { "frame_size", "", offsetof(struct sbg_demuxer
, frame_size
),
1519 AV_OPT_TYPE_INT
, { .i64
= 0 }, 0, INT_MAX
,
1520 AV_OPT_FLAG_DECODING_PARAM
},
1521 { "max_file_size", "", offsetof(struct sbg_demuxer
, max_file_size
),
1522 AV_OPT_TYPE_INT
, { .i64
= 5000000 }, 0, INT_MAX
,
1523 AV_OPT_FLAG_DECODING_PARAM
},
1527 static const AVClass sbg_demuxer_class
= {
1528 .class_name
= "sbg_demuxer",
1529 .item_name
= av_default_item_name
,
1530 .option
= sbg_options
,
1531 .version
= LIBAVUTIL_VERSION_INT
,
1534 AVInputFormat ff_sbg_demuxer
= {
1536 .long_name
= NULL_IF_CONFIG_SMALL("SBaGen binaural beats script"),
1537 .priv_data_size
= sizeof(struct sbg_demuxer
),
1538 .read_probe
= sbg_read_probe
,
1539 .read_header
= sbg_read_header
,
1540 .read_packet
= sbg_read_packet
,
1541 .read_seek
= sbg_read_seek
,
1542 .read_seek2
= sbg_read_seek2
,
1543 .extensions
= "sbg",
1544 .priv_class
= &sbg_demuxer_class
,