r4123: Auto commit for Debian build
[wdq2wav.git] / wdq2wav.cpp
1 /*****************************************************************************
2 ** FILE IDENTIFICATION
3 **
4 **   Name:          wdq2wav.cpp
5 **   Purpose:       Converts a channel of WinDAQ file to .WAV format
6 **   Programmer:    Kevin Rosenberg <kevin@rosenberg.net>
7 **   Date Started:  Jan 2003
8 **
9 **  Copyright (c) 2003 Kevin Rosenberg
10 **
11 **  $Id: wdq2wav.cpp,v 1.23 2003/02/25 18:18:45 kevin Exp $
12 **
13 **  This program is free software; you can redistribute it and/or modify
14 **  it under the terms of the GNU General Public License (version 2) as
15 **  published by the Free Software Foundation.
16 **
17 **  This program is distributed in the hope that it will be useful,
18 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
19 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 **  GNU General Public License for more details.
21 **
22 **  You should have received a copy of the GNU General Public License
23 **  along with this program; if not, write to the Free Software
24 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25 ******************************************************************************/
26
27 #include <wdq2wav.h>
28
29 const char* g_szIdStr = "$Id: wdq2wav.cpp,v 1.23 2003/02/25 18:18:45 kevin Exp $";
30
31 bool g_quiet = false;
32 bool g_verbose = false;
33 bool g_debug = false;
34 bool g_ignore_zero = false;
35 bool g_demean = false;
36
37
38 #ifdef WIN32
39 #define lseek _lseek
40 #define close _close
41 #define open _open
42 #define read _read
43 #define write _write
44 #define O_BINARY _O_BINARY
45 #define O_RDONLY _O_RDONLY
46 #define O_WRONLY _O_WRONLY
47 #define O_RDWR _O_RDRW
48 #define O_TRUNC _O_TRUNC
49 #define O_CREAT _O_CREAT
50 const int g_fileMode = _S_IWRITE | _S_IREAD;
51 struct fpos_t std::_Fpz = {0,0};
52 #else
53 const int g_fileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
54 // Define as NULL for non-Windows platforms
55 #ifndef O_BINARY
56 #define O_BINARY 0
57 #endif
58 #endif
59  
60
61 void
62 error_msg (const char *msg)
63 {
64   std::cerr << msg << "\n";
65 }
66
67 void
68 info_msg (const char* msg)
69 {
70   std::cout << msg << "\n";
71 }
72
73 void
74 info_msg_sans_newline (const char* msg)
75 {
76   std::cout << msg;
77 }
78
79 const char*
80 fileBasename (const char* filename)
81 {
82   const char* p = strrchr (filename, '/');
83   return (p ? p + 1 : filename);
84 }
85
86 char *
87 str_rm_tail (char *str, const char* const charlist)
88 {
89   size_t i;
90
91   for (i = strlen(str) - 1; i >= 0; i--)
92     if (strchr (charlist, str[i]) != NULL)
93       str[i] = 0;
94     else
95       break;            /* found non-specified char, all done */
96
97   return (str);
98 }
99
100 char *
101 str_wrm_tail (char *str)
102 {
103   return (str_rm_tail(str, "\b\t\n\r"));
104 }
105
106
107 void
108 usage (const char* progname)
109 {
110   std::cout << "usage: " << fileBasename (progname) << " [OPTIONS] <wdq-file> <channel-number> <wav-file>\n";
111   std::cout << "OPTIONS\n";
112   std::cout << "  -p   Play channel through audio system\n";
113   std::cout << "  -q   Supress all messages\n";
114   std::cout << "  -z   Scale output without regard for windaq zero point\n";
115   std::cout << "  -m   Demean the data (subtract the mean value from each sample)\n";
116   std::cout << "  -v   Verbose mode\n";
117   std::cout << "  -d   Debug mode\n";
118   std::cout << "  -r   Print program version\n";
119   std::cout << "  -h   Print this help message\n";
120 }
121
122
123 int
124 main (int argc, char *argv[])
125 {
126   int c;
127   bool play = false;
128
129   const char* progname = argv[0];
130   
131   while ((c = getopt (argc, argv, "rqvzmdph")) != -1) {
132     switch (c) {
133     case 'r':
134         std::cout << "Version " << g_szIdStr << std::endl;
135         break;
136     case 'q':
137       g_quiet = true;
138       break;
139     case 'm':
140       g_demean = true;
141       break;
142     case 'v':
143       g_verbose = true;
144       break;
145     case 'd':
146       g_debug = true;
147       break;
148     case 'p':
149       play = true;
150       break;
151     case 'z':
152       g_ignore_zero = true;
153       break;
154     case 'h':
155       usage (progname);
156       return (0);
157     case '?':
158     default:
159         usage (progname);
160         return (1);
161       }
162     }
163   argc -= optind;
164   argv += optind;
165   if (argc > 3) {
166       std::cerr << "Too many parameters\n";
167       usage (progname);
168       return (1);
169     }
170
171   char wdq_fname[MAX_INPUT_STR];
172   if (argc >= 1)
173       strncpy (wdq_fname, argv [0], MAX_INPUT_STR);
174   else {
175     std::cout << "Enter input WinDAQ filename: ";
176       std::cin.getline (wdq_fname, MAX_INPUT_STR);
177     }
178
179     char channel_buf [MAX_INPUT_STR];
180     if (argc >= 2)
181       strncpy (channel_buf, argv[1], MAX_INPUT_STR);
182     else {
183       std::cout << "Enter channel number: ";
184       std::cin.getline (channel_buf, MAX_INPUT_STR);
185     }
186     
187     char *channel_endptr;
188     int channel = static_cast<int>(strtol (channel_buf, &channel_endptr, 10));
189     if (*channel_endptr != 0) {
190       std::ostringstream os;
191       os << "Error: Channel " << channel_buf << " is not an integer";
192       error_msg (os.str().c_str());
193       usage (progname);
194       return (1);
195     }
196
197     char wav_fname[MAX_INPUT_STR];
198     if (argc >= 3)
199       strncpy (wav_fname, argv[2], MAX_INPUT_STR);
200     else {
201       std::cout << "Enter output wav filename: ";
202       std::cin.getline (wav_fname, MAX_INPUT_STR);
203     }
204       
205     if (! wdq2wav (wdq_fname, channel, wav_fname, play))
206       return 1;
207     
208     return 0;
209 }
210
211 bool
212 wdq2wav (const char* wdq_fname, const int channel, const char *wav_fname, bool play)
213 {
214   WindaqFile wdq (wdq_fname);
215
216   if (! wdq.ReadHeader()) {
217     if (wdq.m_error.size()) {
218       std::ostringstream os;
219       os << "Error reading file " << wdq_fname << ": " << wdq.m_error.c_str();
220       error_msg (os.str().c_str());
221     } else {
222       std::ostringstream os;
223       os << "Error reading file " << wdq_fname;
224       error_msg (os.str().c_str());
225     }
226     return false;
227   }
228   if (! g_quiet || g_verbose || g_debug) {
229     std::ostringstream os1;
230     os1 << "File " << wdq_fname;
231     info_msg (os1.str().c_str());
232     std::ostringstream os2;
233     time_t time = wdq.m_time_acq_start;
234     struct tm* tm = gmtime (&time);
235     os2 << "  Time File Creation: " << asctime(tm);
236     info_msg_sans_newline (os2.str().c_str());
237     std::ostringstream os3;
238     time = wdq.m_time_acq_stop;
239     tm = gmtime (&time);
240     os3 << "  Time File Written: " << asctime(tm);
241     info_msg_sans_newline (os3.str().c_str());
242     std::ostringstream os4;
243     os4 << "  Samples: " << wdq.m_nSamples <<
244       ", Channels: " << wdq.m_nChannels <<
245       ", Sample Rate: " << wdq.m_sample_rate;
246     info_msg (os4.str().c_str());
247   }
248   
249   WindaqChannel wdq_channel (wdq, channel);
250   if (! wdq_channel.m_valid) {
251     error_msg ("Error reading data from channel");
252     return false;
253   }
254
255   if (! g_quiet || g_verbose || g_debug) {
256     std::ostringstream os1;
257     os1 << "Channel " << channel;
258     info_msg (os1.str().c_str());
259     std::ostringstream os2;
260     os2 << "  Units: " << wdq_channel.m_units.c_str();
261     info_msg (os2.str().c_str());
262     std::ostringstream os3;
263     os3 << "  Raw minimum: " << wdq_channel.m_min_raw_data <<
264       ", maximum: " << wdq_channel.m_max_raw_data;
265     info_msg (os3.str().c_str());
266   }
267   
268   if (g_debug) {
269     std::ostringstream os4;
270     os4 << "  Scaled minimum: " << wdq_channel.m_min_scaled_data <<
271       ", maximum: " << wdq_channel.m_max_scaled_data;
272     info_msg (os4.str().c_str());
273     std::ostringstream os5;
274     os5 << "  Slope " <<  wdq_channel.m_slope <<
275       ", Intercept " <<  wdq_channel.m_intercept;
276     info_msg (os5.str().c_str());
277   }
278
279   WavFile wav (wdq_channel, wav_fname);
280
281   if (! wav.m_valid) {
282     error_msg ("Error extracting wav from channel");
283     return false;
284   }
285
286   if (! wav.WriteFile ()) {
287     error_msg ("Error writing file");
288     return false;
289   }
290
291   if (play)
292     wav.Play();
293   
294   return true;
295 }
296
297
298 WindaqFile::WindaqFile (const char* fname)
299   : m_valid(false), m_fd(0), m_nChannels(0), m_nSamples(0), m_sample_rate(0),
300     m_strFile (fname)
301 {
302 }
303
304 WindaqFile::~WindaqFile ()
305 {
306   if (m_fd != 0)
307     close (m_fd);
308 }
309
310 bool read_int2 (int fd, unsigned short int& n)
311 {
312   unsigned char tmp1;
313   unsigned int tmp2;
314   if (read (fd, &tmp1, 1) != 1)
315     return false;
316   tmp2 = tmp1;
317   if (read (fd, &tmp1, 1) != 1)
318     return false;
319   
320   n = tmp2 + (tmp1 * 256);
321   return true;
322 }
323
324 bool read_int4 (int fd, unsigned int& n)
325 {
326   unsigned int tmp4;
327   unsigned short int tmp2;
328   if (! read_int2 (fd, tmp2))
329     return false;
330   tmp4 = tmp2;
331   if (! read_int2 (fd, tmp2))
332     return false;
333   
334   n = tmp4 + (tmp2 * 65536);
335   return true;
336 }
337
338 bool
339 WindaqFile::ReadHeader ()
340 {
341   unsigned short int tmp2;
342
343   m_valid = false;
344   if ((m_fd = open (m_strFile.c_str(), O_RDONLY | O_BINARY)) < 0) {
345     m_error = "Unable to open file";
346     return false;
347   }
348
349   lseek (0, 0, SEEK_SET);
350   if (! read_int2 (m_fd, tmp2))
351     return false;
352
353   m_nChannels = tmp2 & 0x1f;
354   m_sr_denom = (tmp2 & 0x7fff) >> 5;
355   m_sr_numer = (tmp2 & 0x8000) << 1;
356   
357   if (! read_int2 (m_fd, tmp2))
358     return false;
359
360   m_sr_numer |= tmp2;
361   m_sample_rate = (double) m_sr_numer / (double) (m_sr_denom * m_nChannels);
362
363   if (! read_int2 (m_fd, tmp2))
364     return false;
365
366   m_channel_offset = tmp2 & 0xFF;
367   m_nBytes_channel_header = tmp2 >> 8;
368   
369   if (! read_int2 (m_fd, m_nHeader_bytes))
370     return false;
371   
372   if (! read_int4 (m_fd, m_nData_bytes))
373     return false;
374
375   m_nSamples = (m_nData_bytes / m_nChannels) / 2;
376
377   lseek (m_fd, 36, SEEK_SET);
378   if (! read_int4 (m_fd, m_time_acq_start))
379     return false;
380
381   if (! read_int4 (m_fd, m_time_acq_stop))
382     return false;
383
384   // Verify Windaq signature
385   lseek (m_fd, m_nHeader_bytes - 2, SEEK_SET);
386   if (! read_int2 (m_fd, tmp2))
387     return false;
388
389   if (tmp2 != 0x8001) {
390     std::ostringstream os;
391     m_error = "File is not a valid WinDAQ file";
392     return false;
393   }
394
395   m_valid = true;
396   return true;
397 }
398
399   
400 WindaqChannel::WindaqChannel (WindaqFile& wdq, const int channel)
401   : r_wdq(wdq), m_data(0), m_slope(0), m_intercept (0), m_channel(channel),
402     m_valid(false)
403 {
404   if (wdq.m_valid) {
405     if (channel >= 1 && channel <= wdq.m_nChannels) {
406       if (read_channel_data())
407         m_valid = true;
408     } else {
409       std::ostringstream os;
410       os << "Channel " << channel << " is invalid, valid range 1-" <<
411         wdq.m_nChannels;
412       error_msg (os.str().c_str());
413     }
414   }
415 }
416
417 WindaqChannel::~WindaqChannel ()
418 {
419   if (m_data)
420     delete m_data;
421 }
422
423 bool get_float8 (int fd, double& f)
424 {
425   unsigned char buf[8];
426   if (read (fd, &buf, 8) != 8)
427     return false;
428
429 #if WORDS_BIG_ENDIAN
430   unsigned char c;
431   c = buf[0]; buf[0] = buf[7]; buf[7] = c;
432   c = buf[1]; buf[1] = buf[6]; buf[6] = c;
433   c = buf[2]; buf[2] = buf[5]; buf[5] = c;
434   c = buf[3]; buf[3] = buf[4]; buf[4] = c;
435 #endif
436
437   f = *(reinterpret_cast<double*>(buf));
438
439   return true;
440 }
441
442
443 bool
444 WindaqChannel::read_channel_data ()
445 {
446   int fd = r_wdq.m_fd;
447
448   m_data = new signed short int [r_wdq.m_nSamples * 2];
449
450   lseek (fd, r_wdq.m_channel_offset + 8 + 
451          (m_channel - 1) * r_wdq.m_nBytes_channel_header,
452          SEEK_SET);
453   if (! get_float8 (fd, m_slope))
454     return false;
455
456   if (! get_float8 (fd, m_intercept))
457     return false;
458
459   char units[7];
460   units[6] = 0;
461   if (read (fd, units, 6) != 6) {
462     error_msg ("Error reading file");
463     return false;
464   }
465   m_units = units;
466  
467   long int row_bytes = 2 * r_wdq.m_nChannels;
468   signed short int *sample_row = new signed short int [row_bytes];
469   
470   signed short int* psample = &sample_row[m_channel - 1];
471
472   lseek (fd, r_wdq.m_nHeader_bytes, SEEK_SET);
473   unsigned long int i;
474   signed short int data_max = 0, data_min = 0;
475   double total_data = 0;
476   for (i = 0; i < r_wdq.m_nSamples; i++) {
477     if (read (fd, sample_row, row_bytes) != row_bytes) {
478       std::ostringstream os;
479       os << "Error reading file at " << i;
480       error_msg (os.str().c_str());
481       delete sample_row;
482       return false;
483     }
484     signed short int v = *psample;
485
486 #if WORDS_BIG_ENDIAN
487     unsigned char* p = reinterpret_cast<unsigned char*>(&v);
488     unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
489 #endif
490
491     signed short int value = v >> 2;
492     m_data[i] = value;
493     total_data += value;
494     
495     if (i == 0) {
496       data_max = value;
497       data_min = value;
498     } else {
499       if (value > data_max)
500         data_max = value;
501       else if (value < data_min)
502         data_min = value;
503     }
504   }
505
506   m_max_raw_data = data_max;
507   m_min_raw_data = data_min;
508   m_max_scaled_data = (m_slope * data_max) + m_intercept;
509   m_min_scaled_data = (m_slope * data_min) + m_intercept;
510
511   if (g_demean) {
512     double dmean = total_data / static_cast<double>(wdq.m_nSamples);
513     int mean = nearest<int>(dmean);
514     for (i = 0; i < r_wdq.m_nSamples; i++)
515       m_data[i] -= mean;
516   }
517   
518   delete sample_row;
519   return true;
520 }
521
522
523 WavFile::WavFile (WindaqChannel& wdq_channel, const char* fname)
524   : m_valid(false), m_data(0), m_nSamples(0), m_strFile(fname), m_fd(0)
525 {
526   if (wdq_channel.m_valid) {
527     m_nSamples = wdq_channel.r_wdq.m_nSamples;
528     m_nChannels = 1;
529     m_nBitsPerSample = 16;
530     m_nBytesPerSample = 2;
531     m_rate = wdq_channel.r_wdq.m_sample_rate;
532
533     double data_offset = 0, data_scale = 0;
534     if (g_ignore_zero) {
535       data_offset = -wdq_channel.m_min_scaled_data;
536       if (wdq_channel.m_max_scaled_data != wdq_channel.m_min_scaled_data)
537         data_scale = 65535. / (wdq_channel.m_max_scaled_data -
538                                wdq_channel.m_min_scaled_data);
539     } else {
540       double max_value = fabs(wdq_channel.m_max_scaled_data);
541       if (fabs (wdq_channel.m_min_scaled_data) > max_value)
542         max_value = fabs (wdq_channel.m_min_scaled_data);
543       if (max_value != 0.)
544         data_scale = 32767. / max_value;
545     }
546     
547     if (g_debug) {
548       std::ostringstream os;
549       os << "  Wav data_scale: " << data_scale << ", data_offset: " << data_offset;
550       info_msg (os.str().c_str());
551     }
552     
553     m_nHeaderBytes = 44;
554     m_nDataBytes = m_nSamples * m_nBytesPerSample * m_nChannels;
555     m_nFileBytes = m_nHeaderBytes + m_nDataBytes;
556
557     unsigned int nHeaderShortInts = m_nHeaderBytes / sizeof(signed short int);
558
559     m_data = new signed short int [m_nSamples + nHeaderShortInts];
560     signed short int* input = wdq_channel.m_data;
561     signed short int* output = &m_data[nHeaderShortInts];
562     double slope = wdq_channel.m_slope;
563     double intercept = wdq_channel.m_intercept;
564     
565     if (! fill_header ())
566       return;
567
568     unsigned long int i;
569     for (i = 0; i < m_nSamples; i++) {
570       double value = input[i];
571       value = (slope * value) + intercept;
572       if (g_ignore_zero) {
573         value = (value + data_offset) * data_scale;
574         value += 0.5 - 32768;
575       } else
576         value = value * data_scale;
577       
578       signed short int v = static_cast<signed short int>(value);
579 #if WORDS_BIG_ENDIAN
580       unsigned char* p = reinterpret_cast<unsigned char*>(&v);
581       unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
582 #endif
583       output[i] = v;
584     }
585   }
586
587   m_valid = true;
588 }
589
590
591 WavFile::~WavFile ()
592 {
593   if (m_fd != 0)
594     close (m_fd);
595     
596   if (m_data != NULL)
597     delete m_data;
598 }
599
600 void
601 put_int4 (char* p, unsigned int n)
602 {
603   *p = n & 0xFF;
604   *(p+1) = 0xFF & (n >> 8);
605   *(p+2) = 0xFF & (n >> 16);
606   *(p+3) = 0xFF & (n >> 24);
607 }
608
609 void
610 put_int2 (char* p, unsigned short int n)
611 {
612   *p = n & 0xFF;
613   *(p+1) = 0xFF & (n >> 8);
614 }
615
616 bool
617 WavFile::fill_header ()
618 {
619   char* pData = reinterpret_cast<char*> (m_data);
620
621   strncpy (pData, "RIFF", 4);
622
623   // Length of file after 8 byte header
624   put_int4 (pData + 4, 36 + m_nDataBytes);
625
626   strncpy (pData + 8, "WAVEfmt ", 8);
627
628   // Length of header block
629   put_int4 (pData + 16, 0x10);
630
631   // Always 1
632   put_int2 (pData + 20, 1);
633
634   /* Number of channels */
635   put_int2 (pData + 22, m_nChannels);
636
637   // Sample Rate
638   put_int4 (pData + 24, static_cast<int> (m_rate + 0.5));
639
640   // Bytes per second 
641   put_int4 (pData + 28, static_cast<int> (m_rate * m_nBytesPerSample + 0.5));
642
643   // Bytes per sample
644   put_int2 (pData + 32, m_nBytesPerSample * m_nChannels);
645
646   // Bits per sample 
647   put_int2 (pData + 34, m_nBitsPerSample);
648
649   strncpy (pData + 36, "data", 4);
650
651   put_int4 (pData + 40, m_nDataBytes);
652
653   return true;
654 }
655
656 bool
657 WavFile::WriteFile ()
658 {
659   if (! m_valid)
660     return false;
661
662   if (m_fd == 0)
663     if ((m_fd = open (m_strFile.c_str(), O_WRONLY | O_BINARY | O_TRUNC | O_CREAT, g_fileMode)) == 0) {
664       std::ostringstream os;
665       os << "Error opening output file " << m_strFile.c_str();
666       error_msg (os.str().c_str());
667       return false;
668     }
669
670   lseek (m_fd, 0, SEEK_SET);
671   if (write (m_fd, m_data, m_nFileBytes) != m_nFileBytes) {
672     error_msg ("Error writing file");
673     return false;
674   }
675
676   if (close (m_fd) < 0)
677     error_msg ("Error closing output file");
678   
679   m_fd = 0;
680   return true;
681 }
682
683 #ifdef WIN32
684 #include <windows.h>
685 #include <mmsystem.h>
686 #elif defined(LINUX)
687 #include <sys/ioctl.h>
688 #include <sys/soundcard.h>
689 #endif
690
691 bool
692 WavFile::Play ()
693 {
694 #ifdef WIN32
695   if (PlaySound ((LPCSTR) m_data, 0, SND_MEMORY | SND_NODEFAULT))
696     return true;
697 #elif defined(LINUX)
698   int fd;
699   if ((fd = open ("/dev/dsp",O_WRONLY)) == -1) {
700     error_msg ("Error opening /dev/dsp");
701     return false;
702   }
703   
704   int format = AFMT_S16_LE;
705   if (ioctl (fd, SNDCTL_DSP_SETFMT, &format) == -1) {
706     error_msg ("Error setting DSP format");
707     close(fd); return false;
708   }
709   if (format != AFMT_S16_LE) {
710     error_msg ("DSP Format not set");
711     close(fd); return false;
712   }
713   
714   unsigned int channels = m_nChannels;
715   if (ioctl (fd, SNDCTL_DSP_CHANNELS, &format) == -1) {
716     error_msg ("Error setting number of channels");
717     close(fd); return false;
718   }
719   if (channels != m_nChannels) {
720     error_msg ("Number of channels not set");
721     close(fd); return false;
722   }
723
724   unsigned int speed = static_cast<int>(m_rate + 0.5);
725   if (ioctl (fd, SNDCTL_DSP_SPEED, &speed) == -1) {
726     error_msg ("Error setting sample rate");
727     close(fd); return false;
728   }
729   if (speed != m_rate && ! g_quiet) {
730     std::ostringstream os;
731     os << "Warning: Sample rate set to " << speed << ", not " << m_rate;
732     error_msg (os.str().c_str());
733   }
734     
735   if (write (fd, reinterpret_cast<char*>(m_data) + m_nHeaderBytes, m_nDataBytes) !=
736       m_nDataBytes) {
737     error_msg ("Error writing audio samples");
738     close(fd); return false;
739   }
740
741   close (fd);
742   return true;
743 #else
744 #endif
745   
746   return false;
747 }
748
749