-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathread_dat.c
2283 lines (2127 loc) · 111 KB
/
read_dat.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
/*
SYNOPSIS
read_dat [-m minimum_track_length] [-p filename-prefix] [-q] [-v verbosity-level] input-device-or-file
DESCRIPTION
read_dat reads data from a DAT in an audio-capable DDS drive
and produces a series of WAV files containing the audio data. It also
produces a series of ".details" files containing information about each
".wav" file, including the date/time from the subcode data.
See http://www.cse.unsw.edu.au/~andrewt/read_dat/ for the latest version
of this program.
See http://www.btinternet.com/~big.bubbles/personal/ade/dat-dds/drives.html
and http://www.zianet.com/jgray/dat/index.html for more information about
audio-capable DDS drives.
OPTIONS
-a --max_nonaudio_tape
Maximum number of consecutive non-audio frames before program exits.
Default is 10.
-A --max_nonaudio_track
Maximum number of consecutive non-audio frames before track closed
Default is 0.
-d --ignore_date_time
Don't start a new track if the date/time jumps.
-m seconds --minimum_track_length seconds
Tracks less than this length will be ignored. The value is a double.
Default is 1.0 seconds.
-M seconds --maximum_track_length seconds
Do not create tracks longer than this number of seconds. The value is a double.
A new track will be started if this limit is reached. Default is 360000.0 seconds.
-n --ignore_program_number
Don't start a new track if the program number changes.
-p filename-prefix --prefix filename-prefix
Create WAV files named filename-prefix0.wav, filename-prefix1.wav ...
Default is ""
-q --quiet
Turn off warnings.
-r seconds --read_n_seconds seconds
Read at most this number of seconds of audio.
Default is 360000.0 seconds.
-s frames --skip_n_frames
Skip n frames on segment change.
Default is 0.
-S frames --seek_n_frames
Skip (seek) oever the first n frames of the tape
Default is 0.
-v verbosity-level --verbose verbosity-level
Print extra information. The higher the level specified the more
information printed. Verbosity-level should be in the range 1..5
-V --version
Print the program version number
EXAMPLE
If /dev/st0 is an audio-capable DDS drive with a DAT inserted
read_dat /dev/st0
should create a series of ".wav" files containing the audio data
from the tape. An accompany series of ".details" files will
also be created.
AUTHOR
Andrew Taylor ([email protected])
with additions by (Torsten Lang, [email protected] (use read_dat in subject line))
DATE
February 2001
COPYRIGHT
This software is copyright Andrew Taylor ([email protected]).
It is released under the GNU General Public License. See the
terms and condions appended at end of this file.
BUGS
sometimes bad data at start of track encoded with 12-bit non-linear encoding (LP mode)
Untested on big-endian machines.
4-channel DATs untested.
Warning messages confusing.
Handling of bogus tracks of a small number of frames poor.
DISCUSSION
See ftp://ftp.informatik.uni-erlangen.de/pub/DATlib/ for a more
comprehensive library for manipulating DAT-tapes and
http://www.hoxnet.com/dat-tools/datlib/ for a version modified for Linux.
No code from DATlib has been incorporated in this program but DATlib
provided invaluable information about the format of DAT tapes.
See http://www.zianet.com/jgray/dat/notes.html for some explanation of
the DAT data format.
I have not had access to a complete specification of the Audio DAT format.
This is what I've been able to infer:
Data on in an audio DAT tape is laid out in 5822 byte frames.
The first 5760 bytes of each frame are used for sound.
The last 62 bytes of the frame, i.e. frame[5760..5821] contain information
about the recording rather than sound.
The sound data on a DAT tape is either encoded as PCM 16-bit little-endian
samples or as 12-bit non-linear samples.
The follow applies only to 2 channel (stereo) tapes - I don't know
how what format is used if there are more channels.
There are three sampling rates used for 16-bit samples: 48khz, 44.1khz
and 32khz.
At 48khz frame[0..5759] contains are 1440 pairs of left & right 16-bit samples
At 44.1khz frame[0..5291] contains are 1323 pairs of left & right 16-bit samples
At 32khz frame[0..3840] contains are 960 pairs of left & right 16-bit samples
12-bit non-linear encoding is used with a 32khz sample-rate and half tape speed -
frame[0..5759] contains 1920 pairs of left & right 12-bit samples
I don't know how the non-linear encoding is done or how it is laid out
within the frame.
frame[5760..5815] is used for an array of 7 regions, each of 8 bytes.
The most significant 4 bits of the first byte in each 8 byte region
specifies the type of information it contains.
frame[5816..5819] contains the "sub-id".
frame[5820..5821] contains the "main-id".
A description of the encoding of the last 62 bytes should go here but
see the functions parse_frame, parse_subcodepack
for an operational description of the format of the last 62 bytes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <getopt.h>
#include <utime.h>
#include <errno.h>
#include <stdarg.h>
#define FRAME_SIZE 5822
#define DATA_SIZE 5760
#define SOUND_DATA_SIZE_48KHZ DATA_SIZE
#define SOUND_DATA_SIZE_44_1KHZ 5292
#define SOUND_DATA_SIZE_32KHZ_PCM 3840
#define SOUND_DATA_SIZE_32KHZ_NONLINEAR_PACKED DATA_SIZE
#define SOUND_DATA_SIZE_32KHZ_NONLINEAR_UNPACKED 7680
#define PACKS_OFFSET 5760
#define N_PACKS 7
#define PACK_SIZE 8
#define SUBID_OFFSET (PACKS_OFFSET + (N_PACKS*PACK_SIZE))
#define MAINID_OFFSET (SUBID_OFFSET + 4)
#define MAX_FILENAME 8192
#define WAV_HEADER_LENGTH 44
#define CTRL_PRIO 8
#define CTRL_START 4
#define CTRL_SKIP 2
#define CTRL_TOC 1
typedef struct frame_info {
int invalid; // 0 == valid, 1 == invalid fields, 2 = non-audio
int nChannels;
int sampling_frequency;
int encoding;
int emphasis;
time_t date_time;
int program_number;
int hex_pno;
int interpolate_flags;
int frame_number;
} frame_info_t;
void usage(void);
void process_file(char *filename);
void parse_frame(unsigned char *frame, frame_info_t *info);
int process_frame(unsigned char *frame, frame_info_t *previous_info, frame_info_t *info);
void parse_subcodepack(unsigned char *frame, int pack_index, frame_info_t *next_info);
void write_frame_audio(unsigned char *frame, frame_info_t *info);
void write_frame_nonlinear_audio(unsigned char *frame, frame_info_t *info);
void open_track(frame_info_t *info);
void close_track();
void write_track_details();
void print_frame_time(int frame_number, FILE *fp);
void warn(char *);
void die(char *format, ...);
int dp(int level, char *format, ...);
char *get_16bit_WAV_header(int samples, int channels, int frequency);
void intcpy(char *b, int i);
void shortcpy(char *b, int i);
int unBCD(unsigned int i);
char *decode_sampfreq[] = {"48kHz","44.1kHz","32kHz","reserved"};
char *decode_numchans[] = {"2 channels","4 channels","reserved","reserved"};
char *decode_quantization[] = {"16-bit linear","12-bit non-linear","reserved","reserved"};
char *decode_emphasis[] = {"none", "pre-emphasis"};
char *decode_subcodeid[] = {"Unused", "Program time","Absolute time","Running Time","Table of Contents","Date","Catalog","Catalog Number","International Standard Recording Code","Pro Binary"};
char *decode_weekday[] = {"Sun", "Mon","Tue","Wed","Thu","Fri","Sat"};
extern short decode_lp_sample[];
extern short translate_lp_frame_index[];
extern short decode_lp_sample[4096];
static int option_print_warnings = 1;
static int option_segment_on_datetime = 1;
static int option_segment_on_program_number = 1;
static int skip_frames_on_segment_change = 0;
static int verbosity = 1;
static FILE *debug_stream;
static off_t seek_n_frames = 0;
static double min_track_seconds = 1.0;
static double max_track_seconds = 360000.0; /* 100 hours should be longer than any track or tape */
static double max_audio_seconds_read = 360000.0;
static int max_consecutive_nonaudio_frames_track = 0;
static int max_consecutive_nonaudio_frames_tape = 10;
static char *filename_prefix = "";
static char *myname;
static char *version = "0.9";
static int little_endian;
static int skip_n_frames = 0;
static double audio_seconds_read = 0;
static int consecutive_nonaudio_frames = 0;
static int track_number = 0;
static int track_frame_count = -1;
static int track_fd = -1;
static FILE *track_invalid_frames_fp = NULL;
char track_filename[MAX_FILENAME];
char track_invalid_frames_filename[MAX_FILENAME];
static int track_nSamples;
static int track_first_frame = -1;
static time_t track_first_date_time = -1;
static int track_first_invalid_frame = -1;
static int track_last_invalid_frame = -1;
static int track_invalid_frames = 0;
static frame_info_t track_info;
static struct option long_options[] = {
{"max_nonaudio_tape", 1, 0, 'a'},
{"max_nonaudio_track", 1, 0, 'a'},
{"ignore_date_time", 0, 0, 'd'},
{"minimum_track_length", 1, 0, 'm'},
{"maximum_track_length", 1, 0, 'M'},
{"ignore_program_number", 0, 0, 'n'},
{"prefix", 1, 0, 'p'},
{"quiet", 0, 0, 'q'},
{"read_n_seconds", 1, 0, 'r'},
{"skip_n_frames", 1, 0, 's'},
{"seek_n_frames", 1, 0, 'S'},
{"verbose", 1, 0, 'v'},
{"version", 0, 0, 'V'},
{0, 0, 0, 0}
};
void
usage(void) {
fprintf(stderr, "Usage: %s [-a frame_count] [-A frame_count] [-d] [-m minimum_track_length] [-M maximum_track_length] [-n] [-p filename-prefix] [-r tape_seconds] [-s frames] [-S frames] [-q] [-v verbosity-level] input-device-or-file\n", myname);
exit(1);
}
int
main(int argc, char *argv[]) {
int n;
myname = strrchr(argv[0], '/');
if (myname == NULL)
myname = argv[0];
else
myname++;
n = 1;
little_endian = (*(char *)&n == 1);
if (!little_endian) {
int i;
for (i = 0; i < sizeof(decode_lp_sample)>>1; i++)
decode_lp_sample[i] = (short)((unsigned char)(decode_lp_sample[i] >> 8) | (decode_lp_sample[i] << 8));
}
while (1) {
int option_index;
int c = getopt_long (argc, argv, "a:A:dm:M:np:qr:s:S:v:V", long_options, &option_index);
if (c == -1)
break;
switch (c) {
case 'a':
max_consecutive_nonaudio_frames_tape = atoi(optarg);
break;
case 'A':
max_consecutive_nonaudio_frames_track = atoi(optarg);
if (max_consecutive_nonaudio_frames_tape < max_consecutive_nonaudio_frames_track)
max_consecutive_nonaudio_frames_tape = max_consecutive_nonaudio_frames_track;
break;
case 'd':
option_segment_on_datetime = 0;
break;
case 'm':
min_track_seconds = atof(optarg);
break;
case 'M':
max_track_seconds = atof(optarg);
break;
case 'n':
option_segment_on_program_number = 0;
break;
case 'p':
filename_prefix = optarg;
break;
case 'q':
option_print_warnings = 0;
verbosity = 0;
break;
case 'r':
max_audio_seconds_read = atof(optarg);
break;
case 's':
skip_frames_on_segment_change = atoi(optarg);
if (skip_frames_on_segment_change < 0)
usage();
break;
case 'S':
seek_n_frames = atoi(optarg);
if (seek_n_frames < 0)
usage();
break;
case 'v':
verbosity = atoi(optarg);
break;
case 'V':
printf("%s v%s - see http://www.cse.unsw.edu.au/~andrewt/read_dat/\n",myname, version);
break;
default:
usage();
}
}
if (optind == argc)
usage();
for (;optind < argc;optind++) {
process_file(argv[optind]);
}
return 0;
}
void
process_file(char *filename) {
int fd, n;
unsigned char buffer[FRAME_SIZE], next_buffer[FRAME_SIZE];
frame_info_t info, next_info;
int frame_number = 0;
if ((fd = open(filename, O_RDONLY)) < 0)
die("Can not open input");
if (seek_n_frames) {
dp(1, "Seeking %d frames\n", (int)seek_n_frames);
off_t seek_bytes = seek_n_frames*FRAME_SIZE;
off_t seek_result = lseek(fd, seek_bytes, SEEK_SET);
if (seek_result == seek_bytes) {
dp(2, "Seek succeeded\n");
frame_number = seek_n_frames;
} else if (seek_result <= 0) {
dp(1, "Seeking not possible reading %d frames\n", (int)seek_n_frames);
for (;frame_number < seek_n_frames;frame_number++) {
if (read(fd, buffer, FRAME_SIZE) != FRAME_SIZE)
die("read failed");
}
} else
die("can not recover from partial seek");
}
if ((n = read(fd, buffer, FRAME_SIZE)) != FRAME_SIZE)
die("read of first frame failed");
info.frame_number = frame_number++;
parse_frame(buffer, &info);
for (;;frame_number++) {
if ((n = read(fd, next_buffer, FRAME_SIZE)) != FRAME_SIZE) {
switch (n) {
case -1:
close_track();
die("read failed");
case 0:
process_frame(buffer, &info, &info);// hack to handle last frame
close_track();
exit(0);
default:
close_track();
die("read returned only a partial frame (%d bytes) - %d frames previously read", n, frame_number);
}
break;
}
next_info.frame_number = frame_number;
parse_frame(next_buffer, &next_info);
if (next_info.hex_pno == 0xbb && frame_number < 4) {
// hack so we number frames from first non lead in frame
frame_number = -1;
next_info.frame_number = -1;
}
if (!process_frame(buffer, &info, &next_info))
return;
memcpy(buffer, next_buffer, sizeof buffer);
info = next_info;
}
}
/*
* process one frame (5822 bytes) of data,
* return 0 if no more input should be read
*/
void
parse_frame(unsigned char *frame, frame_info_t *info) {
unsigned char *scode = frame+DATA_SIZE;
unsigned char *subid = scode+7*8;
unsigned char *mainid = subid+4;
int channels = (mainid[0] >> 0) & 0x3;
int samplerate = (mainid[0] >> 2) & 0x3;
int emphasis = (mainid[0] >> 4) & 0x3;
int fmtid = (mainid[0] >> 6) & 0x3;
int datapacket = (mainid[1] >> 0) & 0x3;
int scms = (mainid[1] >> 2) & 0x3;
int width = (mainid[1] >> 4) & 0x3;
int encoding = (mainid[1] >> 6) & 0x3;
int dataid = (subid[0] >> 0) & 0xf;
int ctrlid = (subid[0] >> 4) & 0xf;
int numpacks = (subid[1] >> 0) & 0xf;
int pno1 = (subid[1] >> 4) & 0xf;
int pno2 = (subid[2] >> 4) & 0xf;
int pno3 = (subid[2] >> 0) & 0xf;
int interpolate_flags = subid[3];
int hex_pno = (pno1 << 8) | (pno2 << 4) | (pno3 << 0);
int bcd_pno = pno1 * 100 + pno2 * 10 + pno3 * 1;
int pack_index;
info->invalid = 0;
info->nChannels = 2;
info->sampling_frequency = 48000;
info->encoding = encoding;
info->emphasis = emphasis;
info->date_time = -1;
info->program_number = -1;
info->hex_pno = hex_pno;
info->interpolate_flags = interpolate_flags;
if (dataid) {
dp(5, "Frame %d non audio dataid(%d)\n", info->frame_number, dataid);
info->invalid = 2;
return;
}
if ((ctrlid != 0 && verbosity >= 3) || verbosity >= 4)
printf("Frame %d cntrlid=%d channels=%d samplerate=%d emphasis=%d fmtid=%d datapacket=%d scms=%d width=%d encoding=%d numpacks=%d id=%x pno=%x%x%x\n", info->frame_number, ctrlid, channels, samplerate, emphasis, fmtid, datapacket, scms, width, encoding, numpacks, subid[0], pno1,pno2, pno3);
if (verbosity >= 4) {
short *s;
int i;
printf("Frame %d data:", info->frame_number);
s = (short *)&frame[0];
for (i = 0; i < 10; i+=2)
printf(" %4d", s[i]);
printf(" ....");
s = (short *)&frame[DATA_SIZE-60];
for (i = 0; i < 10; i+=2)
printf(" %4d", s[i]);
printf("\n");
}
/* check for start id */
if ((ctrlid & CTRL_START) && (ctrlid & CTRL_PRIO) && pno1 < 10 && pno2 < 10 && pno3 < 10)
info->program_number = bcd_pno;
for (pack_index = 0; pack_index < N_PACKS; pack_index++)
parse_subcodepack(frame, pack_index, info);
switch (channels) {
case 0:
info->nChannels = 2;
break;
case 1:
info->nChannels = 4;
break;
default:
info->invalid = 1;
dp(1, "Frame %d invalid value for channels(%d)\n", info->frame_number, channels);
}
switch (samplerate) {
case 0:
info->sampling_frequency = 48000;
break;
case 1:
info->sampling_frequency = 44100;
break;
case 2:
info->sampling_frequency = 32000;
break;
default:
dp(1, "Frame %d invalid value for sampling_frequency (%d)\n", info->frame_number, samplerate);
info->invalid = 1;
}
}
char *
frame_info_inconsistent(frame_info_t *i1, frame_info_t *i2) {
if (option_segment_on_datetime && i1->date_time != -1 && i2->date_time != -1 && i1->date_time != i2->date_time && i1->date_time != i2->date_time + 1 && i1->date_time != i2->date_time - 1)
return "jump in subcode date/time";
else if (i1->nChannels != i1->nChannels)
return "change in number of channels";
else if (i1->sampling_frequency != i2->sampling_frequency)
return "change in sampling frequency";
else if (option_segment_on_program_number && i1->program_number != -1 && i2->program_number != -1 && i1->program_number != i2->program_number)
return "change in program number";
else if (i1->encoding != i2->encoding)
return "change in encoding";
else if (i1->emphasis != i2->emphasis)
return "change in emphasis";
else
return NULL;
}
/*
* process one frame (5822 bytes) of data,
* return 0 if no more input should be read
*
* this function should never skip a frame in the middle of a track
* if their problems with a frame they can either be ignored
* or the track closed and the frame skipped
*/
int
process_frame(unsigned char *frame, frame_info_t *info, frame_info_t *next_info) {
int invalid_frame = info->invalid != 0;
if (info->hex_pno == 0x0ee) {
dp(2, "Frame %d end of tape reached (0x0EE pno found)\n", info->frame_number);
close_track();
return 0;
} else if (info->hex_pno == 0x0bb) {
if (track_fd != -1) {
close_track();
dp(1, "Frame %d closing track 0x0BB pno seen\n", info->frame_number);
} else {
dp(2, "Ignoring frame %d - 0x0BB pno\n", info->frame_number);
}
return 1;
}
if (info->invalid != 2)
consecutive_nonaudio_frames = 0;
else {
if (consecutive_nonaudio_frames++ >= max_consecutive_nonaudio_frames_tape) {
close_track();
dp(1, "Exiting because because %d consecutive frames of non-audio data encountered\n", consecutive_nonaudio_frames);
return 0;
} else {
if (track_fd == -1) {
dp(1, "Skipping frame %d because of non-audio dataid and not in track\n", info->frame_number);
return 1;
}
if (next_info->invalid != 2 && !frame_info_inconsistent(&track_info, next_info)) {
dp(1, "Frame %d ignoring non audio dataid because next frame is audio and its frame info is consistent with previous frame\n", info->frame_number);
} else if (consecutive_nonaudio_frames >= max_consecutive_nonaudio_frames_track) {
dp(1, "Skipping frame %d because of non-audio dataid\n", info->frame_number);
dp(1, "Closing track %d because %d frames of non-audio data encountered\n", track_number, consecutive_nonaudio_frames);
close_track();
} else {
dp(1, "Ignoring non audio dataid on frame %d\n", info->frame_number);
}
}
}
if (info->interpolate_flags & (0x40|0x20)) {
dp(2, "Frame %d warning interpolate flags set indicating audio contains errors\n", info->frame_number);
invalid_frame = 1;
}
if (track_fd != -1) {
char *reason = frame_info_inconsistent(&track_info, info);
if (reason != NULL && !frame_info_inconsistent(&track_info, next_info)) {
dp(1, "Frame %d ignoring %s because previous & next frame consistent\n", info->frame_number, reason);
info->nChannels = next_info->nChannels;
info->sampling_frequency = next_info->sampling_frequency;
info->encoding = next_info->encoding;
info->emphasis = next_info->emphasis;
info->program_number = next_info->program_number;
info->date_time = next_info->date_time;
invalid_frame = 1;
reason = NULL;
}
if (reason != NULL) {
close_track();
skip_n_frames = skip_frames_on_segment_change;
dp(2, "Closing track %d because %s\n", track_number, reason);
}
}
if (skip_n_frames > 0) {
skip_n_frames--;
return 1;
}
if (track_fd == -1)
open_track(info);
if (track_first_frame == -1)
track_first_frame = info->frame_number;
track_info.frame_number = info->frame_number;
if (info->date_time != -1) {
track_info.date_time = info->date_time;
if (track_first_date_time == -1)
track_first_date_time = info->date_time;
}
if (info->program_number != -1 && track_info.program_number == -1)
track_info.program_number = info->program_number;
if (invalid_frame) {
track_invalid_frames++;
if (track_first_invalid_frame == -1)
track_first_invalid_frame = info->frame_number;
track_last_invalid_frame = info->frame_number;
} else if (track_first_invalid_frame != -1) {
if (track_first_invalid_frame == track_last_invalid_frame)
fprintf(track_invalid_frames_fp, "Frame %d (", track_first_invalid_frame);
else
fprintf(track_invalid_frames_fp, "Frames %d-%d (", track_first_invalid_frame, track_last_invalid_frame);
print_frame_time(track_first_invalid_frame, track_invalid_frames_fp);
fprintf(track_invalid_frames_fp, "-");
print_frame_time(track_last_invalid_frame+1, track_invalid_frames_fp);
fprintf(track_invalid_frames_fp, ") invalid\n");
track_first_invalid_frame = -1;
track_last_invalid_frame = -1;
}
write_frame_audio(frame, info);
if (audio_seconds_read >= max_audio_seconds_read) {
dp(1, "Closing track %d and exiting, limit of %.2f seconds reached\n", track_number, max_audio_seconds_read);
close_track();
return 0;
}
if (track_nSamples/(double)info->sampling_frequency >= max_track_seconds) {
dp(1, "Closing track %d and exiting, limit of %.2f seconds reached\n", track_number, max_track_seconds);
close_track();
}
return 1;
}
/*
* process one subcode pack (8 bytes of data)
*/
void
parse_subcodepack(unsigned char *frame, int pack_index, frame_info_t *info) {
struct tm t;
int j, weekday;
int parity = 0;
unsigned char *pack = frame + PACKS_OFFSET + pack_index * PACK_SIZE;
int id = (pack[0] >> 4) & 0x0f;
if (id == 0)
return;
for (j=0; j < 7; j++)
parity ^= pack[j];
if (parity != pack[7]) {
dp(2, "Frame %d Subcode[%d] %s: Incorrect parity %x != %x\n", info->frame_number, pack_index, decode_subcodeid[id], parity, pack[7]);
return;
}
switch (id) {
case 1:
case 2:
case 3:
if ((pack[3] != 0xAA && verbosity > 3) || verbosity > 4)
printf("Frame %d Subcode[%d] %s: indexnr=%d %d:%d:%d frame=%d\n", info->frame_number, pack_index, decode_subcodeid[id], unBCD(pack[2]), unBCD(pack[3]), unBCD(pack[4]), unBCD(pack[5]), unBCD(pack[6]));
break;
case 5:
weekday = pack[0]&0xf;
if (weekday > 7) {
dp(4, "Frame %d Subcode[%d] %s: invalid date\n", info->frame_number, pack_index, decode_subcodeid[id]);
break;
}
t.tm_year = unBCD(pack[1]);
if (t.tm_year < 50)
t.tm_year += 100;
t.tm_mon = unBCD(pack[2]) - 1;
t.tm_mday = unBCD(pack[3]);
t.tm_hour = unBCD(pack[4]) - 1; /* maybe be incorrect - but seems necessary for my Sony TCD-D8 */
t.tm_min = unBCD(pack[5]);
t.tm_sec = unBCD(pack[6]);
t.tm_wday = 0;
t.tm_yday = 0;
t.tm_isdst = 0;
if ((info->date_time = mktime(&t)) == (time_t)(-1)) {
dp(1, "Frame %d can not convert time\n");
warn("can not convert time");
break;
}
dp(3, "Frame %d Subcode[%d] %s", info->frame_number, pack_index,ctime(&info->date_time));
if (weekday - 1 != t.tm_wday)
warn("Day of week apparently set incorrectly on recording - using correct day of week");
break;
default:
dp(4, "Frame %d Subcode[%d] %s\n", info->frame_number, pack_index, decode_subcodeid[id]);
}
}
/*
* process the audio data from a signal frame
*/
void
write_frame_audio(unsigned char *frame, frame_info_t *info) {
int n = 0;
if (track_fd == -1)
return;
if (track_info.encoding != 0) {
write_frame_nonlinear_audio(frame, info);
return;
}
switch (track_info.sampling_frequency) {
case 48000:
n = SOUND_DATA_SIZE_48KHZ;
break;
case 44100:
n = SOUND_DATA_SIZE_44_1KHZ;
break;
case 32000:
n = SOUND_DATA_SIZE_32KHZ_PCM;
break;
default:
close_track();
die("internal error invalid track_sampling_frequency in write_frame_audio");
}
if (write(track_fd, frame, n) != n)
die("write");
track_nSamples += n / (2 * track_info.nChannels);
audio_seconds_read += ((double)(n / (2 * track_info.nChannels)))/track_info.sampling_frequency;
return;
}
void
write_frame_nonlinear_audio(unsigned char *frame, frame_info_t *info) {
short buffer[SOUND_DATA_SIZE_32KHZ_NONLINEAR_UNPACKED/2];
int i, j;
j = 0;
for (i = 0; i < SOUND_DATA_SIZE_32KHZ_NONLINEAR_PACKED; i += 3) {
int x0 = frame[translate_lp_frame_index[i]];
int x1 = frame[translate_lp_frame_index[i+1]];
int x2 = frame[translate_lp_frame_index[i+2]];
buffer[j++] = decode_lp_sample[(x0 << 4) | ((x1 >> 4) & 0x0f)];
buffer[j++] = decode_lp_sample[(x2 << 4) | (x1 & 0x0f)];
}
if (write(track_fd, buffer, SOUND_DATA_SIZE_32KHZ_NONLINEAR_UNPACKED) != SOUND_DATA_SIZE_32KHZ_NONLINEAR_UNPACKED)
die("write");
track_nSamples += SOUND_DATA_SIZE_32KHZ_NONLINEAR_UNPACKED / (2 * track_info.nChannels);
audio_seconds_read += ((double)(SOUND_DATA_SIZE_32KHZ_NONLINEAR_UNPACKED / (2 * track_info.nChannels)))/track_info.sampling_frequency;
}
void
create_filename(char *suffix, char *filename) {
if (track_first_date_time > 0) {
struct tm *t = localtime(&track_first_date_time);
if (snprintf(filename, MAX_FILENAME, "%s%4d-%02d-%02d-%02d-%02d-%02d.%s", filename_prefix, t->tm_year+1900, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec, suffix) == -1)
die("filename too long");
} else {
if (snprintf(filename, MAX_FILENAME, "%s%d.%s", filename_prefix, track_number, suffix) == -1)
die("filename too long");
}
}
/*
* start a new track
*/
void
open_track(frame_info_t *info) {
if (track_fd != -1)
die("internal error open_track previous track not closed");
track_nSamples = 0;
track_invalid_frames = 0;
track_info = *info;
track_first_frame = info->frame_number;
track_first_date_time = info->date_time;
create_filename("wav", track_filename);
dp(1, "Creating %s\n", track_filename);
if ((track_fd = open(track_filename, O_CREAT|O_WRONLY|O_TRUNC, 0600)) < 0)
die("Can not create file %s", track_filename);
create_filename("invalid_frames", track_invalid_frames_filename);
dp(1, "Creating %s\n", track_invalid_frames_filename);
if ((track_invalid_frames_fp = fopen(track_invalid_frames_filename, "w")) == NULL)
die("Can not create file", track_invalid_frames_filename);
/*
* header will be re-written when track is finished to add correct number of samples
*/
if (write(track_fd, get_16bit_WAV_header(track_nSamples, info->nChannels, info->sampling_frequency), WAV_HEADER_LENGTH) != WAV_HEADER_LENGTH)
die("Can not write to file");
}
void
adjust_creation_time(char *filename) {
struct utimbuf u;
if (track_first_date_time > 0) {
u.actime = track_first_date_time;
u.modtime = track_first_date_time;
utime(filename, &u);
}
}
/*
* finish a track
*/
void
close_track() {
char new_track_filename[MAX_FILENAME];
char new_track_invalid_frames_filename[MAX_FILENAME];
double track_length = track_nSamples/(double)track_info.sampling_frequency;
if (track_fd == -1)
return;
if (track_length < min_track_seconds) {
if (verbosity >= 1) {
if (track_nSamples == 0)
dp(1, "Deleting %s - no data\n", track_filename);
else
dp(1, "Deleting %s because %.2fs long - minimum track length %.2fs\n", track_filename, track_length, min_track_seconds);
}
/*
* This is inefficient but simpler than buffering writes
*/
close(track_fd);
if (unlink(track_filename) < 0)
die("unlink file");
if (track_invalid_frames_fp) {
fclose(track_invalid_frames_fp);
track_invalid_frames_fp = NULL;
}
unlink(track_invalid_frames_filename);
} else {
if (lseek(track_fd, SEEK_SET, 0) < 0)
die("Can not lseek track");
dp(2, "Re-writing header to %s: %d channels of %d samples at %dhz\n", track_filename, track_info.nChannels, track_nSamples, track_info.sampling_frequency);
/*
* Re-write header as we now know how many samples to include
*/
if (write(track_fd, get_16bit_WAV_header(track_nSamples, track_info.nChannels, track_info.sampling_frequency), WAV_HEADER_LENGTH) != WAV_HEADER_LENGTH)
die("Can not write to file");
close(track_fd);
adjust_creation_time(track_filename);
create_filename("wav", new_track_filename);
if (strcmp(track_filename, new_track_filename) != 0) {
dp(1, "Renaming %s to %s\n", track_filename, new_track_filename);
if (rename(track_filename, new_track_filename) != 0)
die("can not rename track filename");
}
write_track_details();
if (track_invalid_frames_fp) {
if (track_first_invalid_frame != -1) {
if (track_first_invalid_frame == track_last_invalid_frame)
fprintf(track_invalid_frames_fp, "Frame %d (", track_first_invalid_frame);
else
fprintf(track_invalid_frames_fp, "Frames %d-%d (", track_first_invalid_frame, track_last_invalid_frame);
print_frame_time(track_first_invalid_frame, track_invalid_frames_fp);
fprintf(track_invalid_frames_fp, "-");
print_frame_time(track_last_invalid_frame+1, track_invalid_frames_fp);
fprintf(track_invalid_frames_fp, ") invalid\n");
track_first_invalid_frame = -1;
track_last_invalid_frame = -1;
}
fclose(track_invalid_frames_fp);
track_invalid_frames_fp = NULL;
if (!track_invalid_frames) {
unlink(track_invalid_frames_filename);
} else {
adjust_creation_time(track_invalid_frames_filename);
create_filename("invalid_frames", new_track_invalid_frames_filename);
if (strcmp(track_invalid_frames_filename, new_track_invalid_frames_filename) != 0) {
dp(1, "Renaming %s to %s\n", track_invalid_frames_filename, new_track_invalid_frames_filename);
if (rename(track_invalid_frames_filename, new_track_invalid_frames_filename) != 0)
die("can not rename track invalid frames filename");
}
}
}
track_number++;
}
track_fd = -1;
track_frame_count = -1;
track_first_date_time = -1;
track_first_invalid_frame = -1;
track_last_invalid_frame = -1;
}
/*
* create a ".details" file for a track
*/
void
write_track_details() {
FILE *details_fp;
char details_filename[MAX_FILENAME];
create_filename("details", details_filename);
dp(1, "Creating %s\n", details_filename);
if ((details_fp = fopen(details_filename, "w")) == NULL)
die("Can not open details file");
fprintf(details_fp, "Sampling frequency: %d\n", track_info.sampling_frequency);
fprintf(details_fp, "Channels: %d\n", track_info.nChannels);
fprintf(details_fp, "Samples: %d\n", track_nSamples);
fprintf(details_fp, "Quantization: %s\n", decode_quantization[track_info.encoding]);
fprintf(details_fp, "Emphasis: %s\n", decode_emphasis[track_info.emphasis]);
if (track_info.program_number < 0)
fprintf(details_fp, "Program_number: --\n");
else if (track_info.program_number != -1)
fprintf(details_fp, "Program_number: %d\n", track_info.program_number);
fprintf(details_fp, "First date: %s", ctime(&track_first_date_time));
fprintf(details_fp, "Last date: %s", ctime(&(track_info.date_time)));
fprintf(details_fp, "First frame: %d\n", track_first_frame);
fprintf(details_fp, "Last frame: %d\n", track_info.frame_number);
fprintf(details_fp, "Invalid frames: %d\n", track_invalid_frames);
fclose(details_fp);
adjust_creation_time(details_filename);
}
void
print_frame_time(int frame_number, FILE *fp) {
int n=0,hours, minutes;
double seconds;
switch (track_info.sampling_frequency) {
case 48000:
n = SOUND_DATA_SIZE_48KHZ;
break;
case 44100:
n = SOUND_DATA_SIZE_44_1KHZ;
break;
case 32000:
n = SOUND_DATA_SIZE_32KHZ_PCM;
break;
default:
die("internal error invalid track_sampling_frequency in write_frame_audio");
}
seconds = (frame_number-track_first_frame)*((double)(n / (2 * track_info.nChannels)))/track_info.sampling_frequency;
hours = (int)seconds/3600;
seconds -= hours*3600;
minutes = (int)seconds/60;
seconds -= minutes*60;
fprintf(fp, "%d:%02d:%05.3f", hours, minutes, seconds);
}
/*
* convert a BCD-encoded byte to decimal
*/
int
unBCD(unsigned int i) {
return ((i >> 4) & 0x0f) * 10 + (i & 0x0f);
}
/*
* create a suitable header for a WAV file
*/
char *
get_16bit_WAV_header(int samples, int channels, int frequency) {
static char h[44];
int bytesPerSample = 2;
int bitsPerSample = 16;
strcpy(h, "RIFF WAVEfmt ");
intcpy(h + 4, 36 + samples*channels*bytesPerSample);
intcpy(h + 16, 16);
shortcpy(h + 20, 1);
shortcpy(h + 22, channels);
intcpy(h + 24, frequency);
intcpy(h + 28, frequency*channels*bytesPerSample);