r4116: Automatic commit for debian_version_0_5_1-1
[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.19 2003/02/24 12:53:46 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.19 2003/02/24 12:53:46 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_valid(false), m_fd(0), m_nChannels(0), m_nSamples(0), m_sample_rate(0),
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   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 = 0, data_min = 0;
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       if (max_value != 0.)
529         data_scale = 32767. / max_value;
530     }
531     
532     if (g_debug) {
533       std::ostringstream os;
534       os << "  Wav data_scale: " << data_scale << ", data_offset: " << data_offset;
535       info_msg (os.str().c_str());
536     }
537     
538     m_nHeaderBytes = 44;
539     m_nDataBytes = m_nSamples * m_nBytesPerSample * m_nChannels;
540     m_nFileBytes = m_nHeaderBytes + m_nDataBytes;
541
542     unsigned int nHeaderShortInts = m_nHeaderBytes / sizeof(signed short int);
543
544     m_data = new signed short int [m_nSamples + nHeaderShortInts];
545     signed short int* input = wdq_channel.m_data;
546     signed short int* output = &m_data[nHeaderShortInts];
547     double slope = wdq_channel.m_slope;
548     double intercept = wdq_channel.m_intercept;
549     
550     if (! fill_header ())
551       return;
552
553     unsigned long int i;
554     for (i = 0; i < m_nSamples; i++) {
555       double value = input[i];
556       value = (slope * value) + intercept;
557       if (g_ignore_zero) {
558         value = (value + data_offset) * data_scale;
559         value += 0.5 - 32768;
560       } else
561         value = value * data_scale;
562       
563       signed short int v = static_cast<signed short int>(value);
564 #if WORDS_BIG_ENDIAN
565       unsigned char* p = reinterpret_cast<unsigned char*>(&v);
566       unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
567 #endif
568       output[i] = v;
569     }
570   }
571
572   m_valid = true;
573 }
574
575
576 WavFile::~WavFile ()
577 {
578   if (m_fd != 0)
579     close (m_fd);
580     
581   if (m_data != NULL)
582     delete m_data;
583 }
584
585 void
586 put_int4 (char* p, unsigned int n)
587 {
588   *p = n & 0xFF;
589   *(p+1) = 0xFF & (n >> 8);
590   *(p+2) = 0xFF & (n >> 16);
591   *(p+3) = 0xFF & (n >> 24);
592 }
593
594 void
595 put_int2 (char* p, unsigned short int n)
596 {
597   *p = n & 0xFF;
598   *(p+1) = 0xFF & (n >> 8);
599 }
600
601 bool
602 WavFile::fill_header ()
603 {
604   char* pData = reinterpret_cast<char*> (m_data);
605
606   strncpy (pData, "RIFF", 4);
607
608   // Length of file after 8 byte header
609   put_int4 (pData + 4, 36 + m_nDataBytes);
610
611   strncpy (pData + 8, "WAVEfmt ", 8);
612
613   // Length of header block
614   put_int4 (pData + 16, 0x10);
615
616   // Always 1
617   put_int2 (pData + 20, 1);
618
619   /* Number of channels */
620   put_int2 (pData + 22, m_nChannels);
621
622   // Sample Rate
623   put_int4 (pData + 24, static_cast<int> (m_rate + 0.5));
624
625   // Bytes per second 
626   put_int4 (pData + 28, static_cast<int> (m_rate * m_nBytesPerSample + 0.5));
627
628   // Bytes per sample
629   put_int2 (pData + 32, m_nBytesPerSample * m_nChannels);
630
631   // Bits per sample 
632   put_int2 (pData + 34, m_nBitsPerSample);
633
634   strncpy (pData + 36, "data", 4);
635
636   put_int4 (pData + 40, m_nDataBytes);
637
638   return true;
639 }
640
641 bool
642 WavFile::WriteFile ()
643 {
644   if (! m_valid)
645     return false;
646
647   if (m_fd == 0)
648     if ((m_fd = open (m_strFile.c_str(), O_WRONLY | O_BINARY | O_TRUNC | O_CREAT, g_fileMode)) == 0) {
649       std::ostringstream os;
650       os << "Error opening output file " << m_strFile.c_str();
651       error_msg (os.str().c_str());
652       return false;
653     }
654
655   lseek (m_fd, 0, SEEK_SET);
656   if (write (m_fd, m_data, m_nFileBytes) != m_nFileBytes) {
657     error_msg ("Error writing file");
658     return false;
659   }
660
661   if (close (m_fd) < 0)
662     error_msg ("Error closing output file");
663   
664   m_fd = 0;
665   return true;
666 }
667
668 #ifdef WIN32
669 #include <windows.h>
670 #include <mmsystem.h>
671 #elif defined(LINUX)
672 #include <sys/ioctl.h>
673 #include <sys/soundcard.h>
674 #endif
675
676 bool
677 WavFile::Play ()
678 {
679 #ifdef WIN32
680   if (PlaySound ((LPCSTR) m_data, 0, SND_MEMORY | SND_NODEFAULT))
681     return true;
682 #elif defined(LINUX)
683   int fd;
684   if ((fd = open ("/dev/dsp",O_WRONLY)) == -1) {
685     error_msg ("Error opening /dev/dsp");
686     return false;
687   }
688   
689   int format = AFMT_S16_LE;
690   if (ioctl (fd, SNDCTL_DSP_SETFMT, &format) == -1) {
691     error_msg ("Error setting DSP format");
692     close(fd); return false;
693   }
694   if (format != AFMT_S16_LE) {
695     error_msg ("DSP Format not set");
696     close(fd); return false;
697   }
698   
699   int channels = m_nChannels;
700   if (ioctl (fd, SNDCTL_DSP_CHANNELS, &format) == -1) {
701     error_msg ("Error setting number of channels");
702     close(fd); return false;
703   }
704   if (channels != m_nChannels) {
705     error_msg ("Number of channels not set");
706     close(fd); return false;
707   }
708
709   unsigned int speed = static_cast<int>(m_rate + 0.5);
710   if (ioctl (fd, SNDCTL_DSP_SPEED, &speed) == -1) {
711     error_msg ("Error setting sample rate");
712     close(fd); return false;
713   }
714   if (speed != m_rate && ! g_quiet) {
715     std::ostringstream os;
716     os << "Warning: Sample rate set to " << speed << ", not " << m_rate;
717     error_msg (os.str().c_str());
718   }
719     
720   if (write (fd, reinterpret_cast<char*>(m_data) + m_nHeaderBytes, m_nDataBytes) !=
721       m_nDataBytes) {
722     error_msg ("Error writing audio samples");
723     close(fd); return false;
724   }
725
726   close (fd);
727   return true;
728 #else
729 #endif
730   
731   return false;
732 }
733
734