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