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