forked from dj1yfk/ebook2cw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ebook2cw.c
2137 lines (1809 loc) · 51.9 KB
/
ebook2cw.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
ebook2cw - converts an ebook to Morse MP3/OGG-files
Copyright (C) 2007 - 2023 Fabian Kurz, DJ5CW
https://fkurz.net/ham/ebook2cw.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
Street, Fifth Floor, Boston, MA 02110-1301, USA.
source code looks properly indented with ts=4
*/
#ifdef LAME
#include <lame/lame.h>
#endif
#ifdef OGGV
#include <vorbis/vorbisenc.h>
#endif
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <time.h>
#if !__MINGW32__
#include <locale.h> /* For GNU gettext */
#include <libintl.h>
#define _(String) gettext (String)
#define gettext_noop(String) String
#define N_(String) gettext_noop (String)
#else
#define _(String) (String)
#endif
#ifndef CGI
#include <signal.h> /* Ctrl-C handling with signalhandler() */
#include <setjmp.h> /* longjmp */
#endif
/* for mkdir, not used on Windows */
#if !__MINGW32__
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#endif
#include <limits.h> /* PATH_MAX */
#ifndef PATH_MAX /* Not defined e.g. on GNU/hurd */
#define PATH_MAX 4096
#endif
#include "codetables.h"
#ifndef VERSION
#define VERSION "0.0.0"
#endif
#define PCMBUFFER 1048576 /* 90 seconds at 11kHz, for one word. plenty. */
#define NOISEBUFFER 1048576 /* 90 seconds at 11kHz, for one word. plenty. */
#define MP3BUFFER 1310720 /* abt 1.25*PCMBUFFER + 7200, as recommended */
#define ISO8859 0
#define UTF8 1
#define MP3 0
#define OGG 1
#define NOENC 2
#define SINE 0
#define SAWTOOTH 1
#define SQUARE 2
#define NOISEAMPLITUDE (10000.0)
#define CWAMPLITUDE (20000.0)
#ifdef LAME
/* Global for LAME */
lame_global_flags *gfp;
#endif
#ifdef OGGV
/* Globals for OGG/Vorbis */
ogg_stream_state os;
ogg_page og;
ogg_packet op;
vorbis_info vi;
vorbis_comment vc;
vorbis_dsp_state vd;
vorbis_block vb;
#endif
#ifndef CGI
/* Globals for longjmp */
static jmp_buf jmp;
#endif
/* Struct CWP to keep all CW parameters */
typedef struct {
/* CW parameters */
int wpm, /* speed, words per minute */
freq, /* audio frequency in Hz */
rt, /* risetime, in samples */
ft, /* falltime, in samples */
qrq, /* increase speed each qrq minutes */
reset, /* reset qrq each chapter? */
farnsworth, /* effective, farnsworth speed */
pBT, /* sent <BT> for each paragraph? */
waveform, /* waveform, sine(1), sawtooth(2), square(3) */
original_wpm, /* starting speed; if qrq is used */
wordspace, /* wordspace in samples, depends on Farnsworth*/
letterspace; /* inter-letter space */
float ews; /* extra word space */
/* Noise parameters */
int bandpassbw, /* Noise filter bandwidth */
bandpassfc, /* f_center of the bandpass */
addnoise, /* 1 if noise should be added, 0 if not */
snr; /* SNR of the CW with the noise */
/* mp3/ogg encoder parameters, buffers */
int encoder;
int samplerate,
brate,
quality;
int inpcm_size,
mp3buffer_size,
noisebuf_size,
ditlen, /* normal dit length in samples */
fditlen, /* farnsworth ditlen in samples */
maxbytes; /* max bytes of a 'dah' */
short int *dit_buf,
*dah_buf,
*inpcm,
*noisebuf;
unsigned char *mp3buffer;
/* Chapter splitting */
char chapterstr[80], /* split chapters by this string */
chapterfilename[PATH_MAX-8], /* Prefix, e.g. "Chapter-" */
outfilename[PATH_MAX]; /* Full name of current outputfile */
/* time based splitting, seconds */
int chaptertime;
/* word based splitting */
int chapterwords;
/* encoding and mapping */
int encoding, /* ISO8859 or UTF8 */
use_isomapping,
use_utf8mapping;
char isomapindex[256]; /* contains the chars to be mapped */
int utf8mapindex[256]; /* for utf8 as decimal code */
char isomap[256][4]; /* by these strings */
char utf8map[256][8];
int didahinput;
int comment; /* status for comments (which will not
be translated to CW), 0 = off, 1 = on,
2 = off after next word */
/* Line of input file; position (byte) within the line */
int linecount;
int linepos;
char configfile[2048];
char id3_author[80],
id3_title[80],
id3_comment[80],
id3_year[5];
FILE *outfile;
unsigned int outfile_length;
} CWP;
/* functions */
void init_cw (CWP *cw);
void init_cwp (CWP *cw);
void init_encoder (CWP *cw);
void encode_buffer (int length, CWP *cw);
void ogg_encode_and_write (CWP *cw);
void flush_ogg (CWP *cw);
void help (void);
void showcodes (int i);
int makeword(char * text, CWP *cw);
void closefile (int letter, int chw, int chms, CWP *cw);
void openfile (int chapter, CWP *cw);
void buf_alloc (CWP *cw);
void buf_check (int j, CWP *cw);
void command (char * cmd, CWP *cw);
void readconfig (CWP *cw);
int install_config_files (char *homedir, CWP *cw);
void setparameter (char p, char * value, CWP *cw);
void loadmapping(char *filename, int enc, CWP *cw);
char *mapstring (char *string, CWP *cw);
void addnoise (int length, CWP *cw);
float snramplitude (int snr);
void fillnoisebuffer (short int *buf, int size, float amplitude);
void filterloop (short int *buf, int l, int b);
void scalebuffer(short int *buf, int length, float factor);
void addbuffer (short int *b1, short int *b2, int l);
char *timestring (int ms);
void guessencoding (char *filename);
void add_silence (int ms, CWP *cw);
#ifndef CGI
void signalhandler(int signal);
#endif
#ifdef CGI
int hexit (char c);
void urldecode(char *buf);
#endif
/* main */
int main (int argc, char** argv) {
int pos, i, c, tmp;
char word[1024]=""; /* will be cut when > 1024 chars long */
int chapter = 0;
int download = 0; /* CGI: Send content-disposition header? */
int chw = 0, tw = 0; /* chapter words, total words */
int chms = 0, tms = 0, qms = 0; /* millisec: chapter, total, since qrq */
time_t start_time, end_time; /* conversion time */
int finishchapter = 0; /* finish chapter after this sentence */
int interactive = 0; /* 0 for pipe/file input, 1 for tty */
FILE *infile;
#ifdef CGI
char *querystring;
static char text[10000];
static char cgi_outfilename[1024];
#endif
#ifdef CGIBUFFERED
char *cgibuf;
#endif
/* initializing the CW parameter struct with standard values */
CWP cw;
init_cwp(&cw);
infile = stdin;
start_time = time(NULL);
srand((unsigned int) start_time);
#if !__MINGW32__
/* Native Language Support by GNU gettext */
setlocale(LC_ALL, "" );
bindtextdomain( "ebook2cw", "/usr/share/locale" );
textdomain("ebook2cw");
#endif
#ifndef CGI
/* Signal handling for Ctrl-C -- Does not work on Win32 because
* SIGINT is not supported on that platform. There, the signal
* handler will be called but then the program terminates. */
if (signal(SIGINT, signalhandler) == SIG_ERR) {
fprintf(stderr, _("Failed to set up signal handler for SIGINT\n"));
return EXIT_FAILURE;
}
printf(_("ebook2cw %s - (c) 2007 - 2023 by Fabian Kurz, DJ5CW\n\n"), VERSION);
/*
* Find and read ebook2cw.conf
*/
readconfig(&cw);
while((i=getopt(argc,argv, "XOo:w:W:e:f:uc:k:Q:R:pF:s:b:q:a:t:y:S:hnT:N:B:C:g:d:l:E:m"))!= -1){
setparameter(i, optarg, &cw);
}
if (optind < argc) { /* something left? if so, use as infile */
if ((argv[optind][0] != '-') && (argv[optind][0] != '\0')) {
if ((infile = fopen(argv[optind], "r")) == NULL) {
fprintf(stderr, _("Error: Cannot open file %s. Exit.\n"),
argv[optind]);
exit(EXIT_FAILURE);
}
}
}
/* If we are getting data from a tty, check what the actual encoding is.
* Historically, the default encoding of ebook2cw is ISO 8859-1, but
* nowadays most terminals should use UTF-8. */
if (isatty(fileno(infile))) {
interactive = 1;
#if !__MINGW32__
if (getenv("LANG") != NULL) {
if (strstr(getenv("LANG"), "utf") ||
strstr(getenv("LANG"), "UTF")) {
cw.encoding = UTF8;
}
}
#else
/* Assume Windows terminal to be UTF8 */
cw.encoding = UTF8;
#endif
}
#endif /* ifndef CGI */
/* init encoder (LAME or OGG/Vorbis) */
init_encoder(&cw);
/* Initially allocate inpcm, noisebuffer, mp3buffer, dit_buf, dah_buf */
buf_alloc(&cw);
#ifndef CGI
printf(_("Speed: %dwpm, Freq: %dHz, Chapter: >%s<, Encoding: %s\n"),cw.wpm,
cw.freq, cw.chapterstr, cw.encoding == UTF8 ? "UTF-8" : "ISO 8859-1");
printf(_("Effective speed: %dwpm, "), cw.farnsworth ? cw.farnsworth : cw.wpm);
printf(_("Extra word spaces: %1.1f, "), cw.ews);
printf(_("QRQ: %dmin, reset QRQ: %s\n"), cw.qrq, cw.reset ? _("yes") : _("no"));
if (cw.chapterwords) {
printf(_("Chapter limit: %d words, "), cw.chapterwords);
}
if (cw.chaptertime) {
printf(_("Chapter limit: %d seconds, "), cw.chaptertime);
}
printf(_("Encoder: %s\n\n"), (cw.encoder == OGG) ? "OGG" : "MP3");
if (interactive) {
printf(_("Interactive mode. Type in text and finish with Ctrl-D.\n\n"));
}
#endif
#ifdef CGI
/* CGI: utf8 input by default */
cw.encoding = UTF8;
/* CGI standard: write directly to stdout ==> no Content-Length possible
* CGI buffered: write to file /tmp/$time-$rnd and later generate output */
#ifndef CGIBUFFERED
cw.outfile = stdout;
#else
/* we need to generate a good random number for the file name;
* just using rand(time) won't do if two requests come in the
* same second. temporarily use cw.outfile FD to open urand */
if ((cw.outfile = fopen("/dev/urandom", "r")) == NULL) {
fprintf(stderr, _("Error: Failed to open /dev/urandom.\n"));
exit(EXIT_FAILURE);
}
fread(&i, sizeof(i), 1, cw.outfile);
srand(i);
i = rand();
fclose(cw.outfile);
snprintf(cgi_outfilename, 80, "/tmp/%d-%d", (int)start_time, i);
if ((cw.outfile = fopen(cgi_outfilename, "wb+")) == NULL) {
fprintf(stderr, _("Error: Failed to open %s\n"), cgi_outfilename);
exit(EXIT_FAILURE);
}
#endif
switch (cw.encoder) {
case MP3:
printf("Content-Type: audio/mpeg\n");
break;
case OGG:
printf("Content-Type: audio/ogg\n");
break;
}
#ifndef CGIBUFFERED /* header is finished */
printf("\n");
#endif
querystring = getenv("QUERY_STRING");
if ((querystring == NULL) || strlen(querystring) > 9000) {
exit(1);
}
/* the query parameters may look like:
* d=001&s=25&e=20&f=600&t=text => download, offer as filename "lcwo-001.mp3"
* s=25&e=20&f=600&t=text => return normal file
*/
if (querystring[0] == 'd') {
sscanf(querystring, "d=%d&s=%d&e=%d&f=%d&t=%9000s", &download, &cw.wpm, &cw.farnsworth, &cw.freq, text);
}
else {
sscanf(querystring, "s=%d&e=%d&f=%d&t=%9000s", &cw.wpm, &cw.farnsworth, &cw.freq, text);
}
strcat(text, " ");
urldecode(text);
if (cw.wpm == 0 || cw.freq == 0) {
exit(1);
}
flush_ogg(&cw);
#endif
init_cw(&cw); /* generate raw dit, dah */
if (strlen(cw.chapterstr)) {
strcat(cw.chapterstr, " ");
}
cw.original_wpm = cw.wpm; /* may be changed by QRQing */
chapter = 0;
#ifndef CGI
openfile(chapter, &cw);
/* Entry point for handling SIGINT; we jump back here from
* the signalhandler() function */
if (setjmp(jmp)) {
goto cleanup;
}
#endif
i=0;
pos=0;
/* 100ms of silence at the start; some decoders otherwise produce
* crackling noises */
add_silence(100, &cw);
/* read input, assemble full words (anything ending in ' ') to 'word' and
* generate CW, write to file by 'makeword'. words with > 1024 characters
* will be split */
#ifndef CGI
while ((c = getc(infile)) != EOF) {
#else
while ((c = text[i++]) != '\0') {
#endif
if (c == '\r') /* DOS linebreaks */
continue;
#if __MINGW32__
if (c == 0x04) /* EOT; Win32 console produces this for Ctl-D */
break;
#endif
if (c == '#')
cw.comment = 1;
if (cw.comment) {
if (c == '\n') {
cw.comment = 2;
}
else {
continue;
}
}
word[pos++] = c;
if ((c == ' ') || (c == '\n') || (pos == 1024)) {
word[pos] = '\0';
#ifndef CGI
/* new chapter */
if ((strcmp(cw.chapterstr, word) == 0) || /* regular */
finishchapter == 2 /* timeout/max. words */
) {
closefile(chapter, chw, chms, &cw);
tw += chw;
tms += chms;
chw = 0;
chms = 0;
chapter++;
if (cw.qrq && cw.reset) {
cw.wpm = cw.original_wpm;
init_cw(&cw);
}
finishchapter = 0;
openfile(chapter, &cw);
}
#endif
/* check for commands: |f or |w */
if (word[0] == '|') {
command(word, &cw);
}
else {
tmp = makeword(mapstring(word, &cw), &cw);
chms += tmp;
qms += tmp;
chw++;
if (cw.comment == 2)
cw.comment = 0;
}
/* Every 'cw.qrq' minutes speed up 1 WpM */
if (cw.qrq && ((qms/60000.0) > cw.qrq)) {
cw.wpm += 1;
init_cw(&cw);
printf("QRQ: %dwpm\n", cw.wpm);
qms = 0;
}
/* word finished; reached word- or time-limit? */
if (finishchapter || (cw.chaptertime && chms/1000 >= cw.chaptertime) ||
(cw.chapterwords && chw == cw.chapterwords)) {
/* Yes! Finish sentence (i.e. until next '.', '!' or '?')
* and then start a new chapter */
finishchapter = 1;
/* End of sentence? */
if (word[pos-2] == '.' ||
word[pos-2] == '!' ||
word[pos-2] == '?') {
finishchapter = 2;
}
}
word[0] = '\0';
pos = 0;
} /* word */
} /* eof */
/* If the file ends without newline or space, but directly with EOF after
* the last word, this one is lost, so we need to add it... */
if (strlen(word) && word[0] != '|' && word[0] != '#') {
makeword(mapstring(word, &cw), &cw);
chw++;
}
/* CGI: Add some silence (500ms) to the end of the file */
#ifdef CGI
add_silence(500, &cw);
#endif
#ifndef CGI
closefile(chapter, chw, chms, &cw);
end_time = time(NULL);
printf(_("Total words: %d, total time: %s\n"), tw+chw, timestring(tms+chms));
printf(_("Conversion time: %s (Speedup: %.1fx)\n"),
timestring(1000.0 * difftime(end_time, start_time)),
((tms+chms)/(1000.0 * difftime(end_time,start_time)))
);
#else /* in CGI mode, we need to do this to close the file properly */
if (cw.encoder == OGG) { /* (otherwise done in closefile() */
#ifdef OGGV
vorbis_analysis_wrote(&vd,0);
ogg_encode_and_write(&cw);
#endif
}
#endif
if (cw.encoder == MP3) {
#ifdef LAME
lame_close(gfp);
#endif
}
else {
#ifdef OGGV
ogg_stream_clear(&os);
vorbis_block_clear(&vb);
vorbis_dsp_clear(&vd);
vorbis_comment_clear(&vc);
vorbis_info_clear(&vi);
#endif
}
free(cw.mp3buffer);
free(cw.inpcm);
free(cw.noisebuf);
free(cw.dah_buf);
free(cw.dit_buf);
if (download) {
printf("Content-Disposition: attachment; filename=\"lcwo-%03d.mp3\"\n", download);
}
#ifdef CGIBUFFERED
/* File is completed, so we know the length and can send the
* content length header, and then the whole file */
printf("Content-Length: %d\n", cw.outfile_length);
printf("\n");
i = (int) ftell(cw.outfile);
rewind(cw.outfile);
/* maybe one day sendfile(2) will support writing to a
* file descriptor, not just a socket, to make this
* easier and faster... */
cgibuf = malloc((size_t) i+1);
if (cgibuf == NULL) {
fprintf(stderr, _("malloc() for cgibuf failed!\n"));
exit(EXIT_FAILURE);
}
fread(cgibuf, sizeof(char), (size_t) i, cw.outfile);
fclose(cw.outfile);
fwrite(cgibuf, sizeof(char), (size_t) i, stdout);
free(cgibuf);
unlink(cgi_outfilename);
#endif
/* NON-CGI operation: If we produced no output, remove the
* empty file */
#ifndef CGI
cleanup:
if (!chw) {
printf(_("Deleting empty file: %s\n"), cw.outfilename);
unlink(cw.outfilename);
}
#endif
return (EXIT_SUCCESS);
}
/* init_cw - generates a dit and a dah to dit_buf and dah_buf */
void init_cw (CWP *cw) {
int samples_per_minute;
int x, len;
double val, val1, val2;
samples_per_minute = 60*cw->samplerate;
len = (int) (samples_per_minute/(50.0*cw->wpm));
/* size of dit_buf, dah_buf may have to be increased, when speed decreased */
if (len > cw->ditlen) {
if ((cw->dah_buf = realloc(cw->dah_buf, 3*len * sizeof(short int))) == NULL) {
fprintf(stderr, _("Error: Can't reallocate dah_buf[%d]\n"), 3*len);
exit(EXIT_FAILURE);
}
if ((cw->dit_buf = realloc(cw->dit_buf, len * sizeof(short int))) == NULL) {
fprintf(stderr, _("Error: Can't allocate dit_buf[%d]\n"), len);
exit(EXIT_FAILURE);
}
}
/* both dah_buf and dit_buf are filled in this loop */
for (x=0; x < 3*len; x++) {
switch (cw->waveform) {
case SINE:
val = sin(2*M_PI*cw->freq*x/cw->samplerate);
break;
case SAWTOOTH:
val = ((1.0*cw->freq*x/cw->samplerate)-
floor(1.0*cw->freq*x/cw->samplerate))-0.5;
break;
case SQUARE:
val = ceil(sin(2*M_PI*cw->freq*x/cw->samplerate))-0.5;
break;
}
/* Shaping rising edge, same for dit and dah */
if (x < cw->rt)
val *= pow(sin(M_PI*x/(2.0*cw->rt)),2);
val1 = val2 = val;
/* Shaping falling edge, dit */
if (x < len) {
if (x > (len-cw->ft)) {
val1 *= pow((sin(2*M_PI*(x-(len-cw->ft)+cw->ft)/(4*cw->ft))), 2);
}
cw->dit_buf[x] = (short int) (val1 * CWAMPLITUDE);
}
/* Shaping falling edge, dah */
if (x > (3*len-cw->ft)) {
val2 *= pow((sin(2*M_PI*(x-(3*len-cw->ft)+cw->ft)/(4*cw->ft))), 2);
}
cw->dah_buf[x] = (short int) (val2 * CWAMPLITUDE);
} /* for */
cw->ditlen = len;
/* calculate farnsworth length samples */
if (cw->farnsworth) {
if (cw->farnsworth > cw->wpm) {
fprintf(stderr, _("Warning: Effective speed (-e %d) must be lower "
"than character speed (-w %d)! Speed adjusted to %d.\n"),
cw->farnsworth, cw->wpm, cw->wpm);
cw->farnsworth = cw->wpm;
}
/* by convention, wpm is measured using the word "Paris". With a dah
being 3 dits, and a spacing of one dit between sigs, this word
has a total length of
1+3+3+1 +3 +3 +1+3 +1 +3 +1+3+1 +2 +3 +1+1 +1 +3 +1+1+1 +2 = 43 dit lengths
Together with an additional word break of 7 dits this makes 50
dit lengths.
Actually, the total duration of only the sigs themselves is only
1+3+3+1 +3 +1+3 +1 +1+3+1 +2 +1+1 +1 +1+1+1 +2 = 31 dit lengths
and the other 12 dits are inter-sig pauses.
The definition of n "words per minute" speed means that this is
the speed where the operator gives the word "Paris" n times per
minute.
The sigs at a speed of cw->wpm have a total length of
cw->farnsworth * 31 dits
The total length of pauses is
cw->farnsworth * (12+7) dits
Note that the the effective wpm is relevant for the count here.
According to the farnsworth method, the inter-sig and inter-word
pauses are elongated such that the operator gives "Paris" only
cw->farnsworth times.
The total length of the sigs in samples is
*/
int total_sigs_samples = cw->farnsworth * 31 * cw->ditlen;
/*
This allows to determine the length of a ditlength during a
farnsworth break.*/
cw->fditlen = (samples_per_minute - total_sigs_samples) / (cw->farnsworth * (12+7));
}
/* Calculate maximum number of bytes per 'dah' for the PCM stream,
* this will be used later to check if the buffer runs full
* (10000 margin) */
if (cw->farnsworth) {
cw->maxbytes = (int) ((4+7.0*cw->ews)*(cw->fditlen)) + 10000;
}
else {
cw->maxbytes = (int) ((6+7.0*cw->ews) * len) + 10000;
}
/* Calculate word space, letter space, considering EWS and farnsworth */
cw->wordspace =(int)(1+7*cw->ews)*(cw->farnsworth ? cw->fditlen : cw->ditlen);
cw->letterspace = (cw->farnsworth ? 3*cw->fditlen - cw->ditlen : 2*cw->ditlen);
return;
}
/* makeword -- converts 'text' to CW by concatenating dit_buf amd dah_bufs,
* encodes this to MP3 and writes to open filehandle outfile */
int makeword(char * text, CWP *cw) {
const char *code; /* CW code as . and - */
int c, i, j, u, w;
int prosign = 0;
unsigned char last=0; /* for utf8 2-byte characters */
j = 0; /* position in 'inpcm' buffer */
int maxloop = strlen(text);
if (cw->didahinput == 1)
{
maxloop = 1;
}
for (i = 0; i < maxloop; i++) {
c = (unsigned char) text[i];
code = NULL;
cw->linepos++;
if (c == '\n') { /* Same for UTF8 and ISO8859 */
if (cw->comment == 0 && strlen(text) == 1 && cw->pBT) /* paragraph */
code = " -...- ";
else if (cw->comment) { /* No spaces after comment line */
code = " ";
}
else { /* Space instead of newline */
code = " ";
}
cw->linepos = 0;
cw->linecount++;
}
else if (c == '<') { /* prosign on */
prosign = 1;
continue;
}
else if ((c == '>') && prosign) { /* prosign off */
prosign = 0;
code = ""; /* only inserts letter space */
}
else if (cw->encoding == ISO8859) {
code = iso8859[c];
}
else if (cw->encoding == UTF8) {
/* Character may be 1-byte ASCII or 2-byte UTF8 */
if (!(c & 128)) { /* MSB = 0 -> 7bit ASCII */
code = iso8859[c]; /* subset of iso8859 */
}
else {
if (last && (c < 192) ) { /* this is the 2nd byte */
/* 110yyyyy 10zzzzzz -> 00000yyy yyzzzzzz */
c = ((last & 31) << 6) | (c & 63);
code = utf8table[c];
last = 0;
}
else { /* this is the first byte */
last = c;
}
}
}
if (last) continue; /* first of two-byte character read */
/* Not found anything, produce warning message */
if (code == NULL) {
#ifndef CGI
if (c < 128) {
fprintf(stderr, _("Warning: Don't know CW for '%c'. "), c);
}
else if (cw->encoding == ISO8859) {
fprintf(stderr, _("Warning: Don't know CW for '%c' (0x%01X) (try the -u switch to enable UTF-8). "), c, c);
}
else {
/* TODO: Consider using libunistring's unicode_character_name()
* function to provide the name of the character */
fprintf(stderr, _("Warning: Don't know CW for unicode code point U+%04X. "), c);
}
fprintf(stderr, _("[Line %d, Byte %d]\n"), cw->linecount, cw->linepos);
#endif
code = " ";
}
if (cw->didahinput == 1) {
code = text;
}
//printf ("%s %s", text, code);
/* code contains letter as ./-, now assemble pcm buffer */
for (w = 0; w < strlen(code) ; w++) {
/* make sure the inpcm buffer doesn't run full,
* with a conservative margin. reallocate memory if neccesary */
buf_check(j, cw);
c = code[w];
if (c == '.') {
for (u=0; u < cw->ditlen; u++) {
cw->inpcm[++j] = cw->dit_buf[u];
}
}
else if (c == '-') {
for (u=0; u < (3*cw->ditlen); u++) {
cw->inpcm[++j] = cw->dah_buf[u];
}
}
else { /* word space */
for (u=0;u < cw->wordspace; u++)
cw->inpcm[++j] = 0;
}
for (u=0; u < cw->ditlen; u++) {
cw->inpcm[++j] = 0;
}
} /* foreach dot/dash */
if (prosign == 0) {
for (u=0; u < cw->letterspace; u++)
cw->inpcm[++j] = 0;
}
} /* foreach letter */
/* j = total length of samples in 'inpcm' */
if (cw->addnoise) {
addnoise(j, cw);
}
encode_buffer(j, cw);
return (int) (1000.0*j/cw->samplerate); /* encoded length in ms */
}
/* closefile -- finishes writing the current file, flushes the encoder buffer */
void closefile (int chapter, int chw, int chms, CWP *cw) {
int outbytes = 0;
printf(_("words: %d, time: %s\n"), chw, timestring(chms));
printf(_("Finishing %s\n\n"), cw->outfilename);
switch (cw->encoder) {
case MP3:
#ifdef LAME
outbytes = lame_encode_flush(gfp,cw->mp3buffer, cw->mp3buffer_size);
if (outbytes < 0) {
fprintf(stderr, "Error: lame_encode_buffer returned %d.\n",
outbytes);
exit(EXIT_FAILURE);
}
if (fwrite(cw->mp3buffer, sizeof(char), outbytes, cw->outfile) !=
outbytes) {
fprintf(stderr, "Error: Writing %db to file failed. Exit.\n",
outbytes);
exit(EXIT_FAILURE);
}
cw->outfile_length += outbytes;
#endif
break;
case OGG:
#ifdef OGGV
vorbis_analysis_wrote(&vd,0);
ogg_encode_and_write(cw);
#endif
break;
case NOENC:
/* Do nothing */
break;
}
if (cw->encoder != NOENC)
fclose(cw->outfile);
}
/* openfile -- starts a new chapter by opening a new file as outfile */
void openfile (int chapter, CWP *cw) {
#ifdef LAME
static char tmp[80] = "";
#endif
#ifdef OGGV
ogg_packet hdr;
ogg_packet hdr_comm;
ogg_packet hdr_code;
#endif
/* If we have a chapter separator string, use format Chapter0001.mp3 */
if (strlen(cw->chapterstr) && cw->chapterstr[0] != '-') {
snprintf(cw->outfilename, PATH_MAX, "%s%04d.%s", cw->chapterfilename,
chapter, (cw->encoder == MP3) ? "mp3" : "ogg");
}
else { /* otherwise just Chapter.mp3 */
snprintf(cw->outfilename, PATH_MAX, "%s.%s", cw->chapterfilename,
(cw->encoder == MP3) ? "mp3" : "ogg");
}
printf(_("Starting %s\n"), cw->outfilename);
if ((cw->encoder != NOENC) &&
(cw->outfile = fopen(cw->outfilename, "wb")) == NULL) {
fprintf(stderr, _("Error: Failed to open %s\n"), cw->outfilename);
exit(EXIT_FAILURE);
}
switch (cw->encoder) {
case MP3:
#ifdef LAME
snprintf(tmp, 79, "%s - %d", cw->id3_title, chapter); /* title */
id3tag_init(gfp);
id3tag_set_artist(gfp, cw->id3_author);
id3tag_set_year(gfp, cw->id3_year);
id3tag_set_title(gfp, tmp);
id3tag_set_comment(gfp, cw->id3_comment);
#endif
break;
case OGG:
#ifdef OGGV
vorbis_comment_init(&vc);
vorbis_comment_add_tag(&vc,"ENCODER","ebook2cw");
vorbis_analysis_init(&vd, &vi);
vorbis_block_init(&vd, &vb);
ogg_stream_init(&os,rand());
vorbis_analysis_headerout(&vd,&vc,&hdr,&hdr_comm,&hdr_code);
ogg_stream_packetin(&os,&hdr);
ogg_stream_packetin(&os,&hdr_comm);
ogg_stream_packetin(&os,&hdr_code);
flush_ogg(cw);
#endif
break;
case NOENC:
/* Do nothing */
break;
}
}
void help (void) {