r4121: 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.21 2003/02/25 18:14:10 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.21 2003/02/25 18:14:10 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 inline T nearest (double x)
443 { return (x > 0 ? static_cast<T>(x+0.5) : static_cast<T>(x-0.5)); }
444
445 bool
446 WindaqChannel::read_channel_data ()
447 {
448   int fd = r_wdq.m_fd;
449
450   m_data = new signed short int [r_wdq.m_nSamples * 2];
451
452   lseek (fd, r_wdq.m_channel_offset + 8 + 
453          (m_channel - 1) * r_wdq.m_nBytes_channel_header,
454          SEEK_SET);
455   if (! get_float8 (fd, m_slope))
456     return false;
457
458   if (! get_float8 (fd, m_intercept))
459     return false;
460
461   char units[7];
462   units[6] = 0;
463   if (read (fd, units, 6) != 6) {
464     error_msg ("Error reading file");
465     return false;
466   }
467   m_units = units;
468  
469   long int row_bytes = 2 * r_wdq.m_nChannels;
470   signed short int *sample_row = new signed short int [row_bytes];
471   
472   signed short int* psample = &sample_row[m_channel - 1];
473
474   lseek (fd, r_wdq.m_nHeader_bytes, SEEK_SET);
475   unsigned long int i;
476   signed short int data_max = 0, data_min = 0;
477   double total_data = 0;
478   for (i = 0; i < r_wdq.m_nSamples; i++) {
479     if (read (fd, sample_row, row_bytes) != row_bytes) {
480       std::ostringstream os;
481       os << "Error reading file at " << i;
482       error_msg (os.str().c_str());
483       delete sample_row;
484       return false;
485     }
486     signed short int v = *psample;
487
488 #if WORDS_BIG_ENDIAN
489     unsigned char* p = reinterpret_cast<unsigned char*>(&v);
490     unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
491 #endif
492
493     signed short int value = v >> 2;
494     m_data[i] = value;
495     total_data += value;
496     
497     if (i == 0) {
498       data_max = value;
499       data_min = value;
500     } else {
501       if (value > data_max)
502         data_max = value;
503       else if (value < data_min)
504         data_min = value;
505     }
506   }
507
508   m_max_raw_data = data_max;
509   m_min_raw_data = data_min;
510   m_max_scaled_data = (m_slope * data_max) + m_intercept;
511   m_min_scaled_data = (m_slope * data_min) + m_intercept;
512
513   if (g_demean) {
514     double dmean = total_data / static_cast<double> wdq.m_nSamples;
515     int mean = nearest<int>(dmean);
516     for (i = 0; i < r_wdq.m_nSamples; i++)
517       m_data[i] -= mean;
518   }
519   
520   delete sample_row;
521   return true;
522 }
523
524
525 WavFile::WavFile (WindaqChannel& wdq_channel, const char* fname)
526   : m_valid(false), m_data(0), m_nSamples(0), m_strFile(fname), m_fd(0)
527 {
528   if (wdq_channel.m_valid) {
529     m_nSamples = wdq_channel.r_wdq.m_nSamples;
530     m_nChannels = 1;
531     m_nBitsPerSample = 16;
532     m_nBytesPerSample = 2;
533     m_rate = wdq_channel.r_wdq.m_sample_rate;
534
535     double data_offset = 0, data_scale = 0;
536     if (g_ignore_zero) {
537       data_offset = -wdq_channel.m_min_scaled_data;
538       if (wdq_channel.m_max_scaled_data != wdq_channel.m_min_scaled_data)
539         data_scale = 65535. / (wdq_channel.m_max_scaled_data -
540                                wdq_channel.m_min_scaled_data);
541     } else {
542       double max_value = fabs(wdq_channel.m_max_scaled_data);
543       if (fabs (wdq_channel.m_min_scaled_data) > max_value)
544         max_value = fabs (wdq_channel.m_min_scaled_data);
545       if (max_value != 0.)
546         data_scale = 32767. / max_value;
547     }
548     
549     if (g_debug) {
550       std::ostringstream os;
551       os << "  Wav data_scale: " << data_scale << ", data_offset: " << data_offset;
552       info_msg (os.str().c_str());
553     }
554     
555     m_nHeaderBytes = 44;
556     m_nDataBytes = m_nSamples * m_nBytesPerSample * m_nChannels;
557     m_nFileBytes = m_nHeaderBytes + m_nDataBytes;
558
559     unsigned int nHeaderShortInts = m_nHeaderBytes / sizeof(signed short int);
560
561     m_data = new signed short int [m_nSamples + nHeaderShortInts];
562     signed short int* input = wdq_channel.m_data;
563     signed short int* output = &m_data[nHeaderShortInts];
564     double slope = wdq_channel.m_slope;
565     double intercept = wdq_channel.m_intercept;
566     
567     if (! fill_header ())
568       return;
569
570     unsigned long int i;
571     for (i = 0; i < m_nSamples; i++) {
572       double value = input[i];
573       value = (slope * value) + intercept;
574       if (g_ignore_zero) {
575         value = (value + data_offset) * data_scale;
576         value += 0.5 - 32768;
577       } else
578         value = value * data_scale;
579       
580       signed short int v = static_cast<signed short int>(value);
581 #if WORDS_BIG_ENDIAN
582       unsigned char* p = reinterpret_cast<unsigned char*>(&v);
583       unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
584 #endif
585       output[i] = v;
586     }
587   }
588
589   m_valid = true;
590 }
591
592
593 WavFile::~WavFile ()
594 {
595   if (m_fd != 0)
596     close (m_fd);
597     
598   if (m_data != NULL)
599     delete m_data;
600 }
601
602 void
603 put_int4 (char* p, unsigned int n)
604 {
605   *p = n & 0xFF;
606   *(p+1) = 0xFF & (n >> 8);
607   *(p+2) = 0xFF & (n >> 16);
608   *(p+3) = 0xFF & (n >> 24);
609 }
610
611 void
612 put_int2 (char* p, unsigned short int n)
613 {
614   *p = n & 0xFF;
615   *(p+1) = 0xFF & (n >> 8);
616 }
617
618 bool
619 WavFile::fill_header ()
620 {
621   char* pData = reinterpret_cast<char*> (m_data);
622
623   strncpy (pData, "RIFF", 4);
624
625   // Length of file after 8 byte header
626   put_int4 (pData + 4, 36 + m_nDataBytes);
627
628   strncpy (pData + 8, "WAVEfmt ", 8);
629
630   // Length of header block
631   put_int4 (pData + 16, 0x10);
632
633   // Always 1
634   put_int2 (pData + 20, 1);
635
636   /* Number of channels */
637   put_int2 (pData + 22, m_nChannels);
638
639   // Sample Rate
640   put_int4 (pData + 24, static_cast<int> (m_rate + 0.5));
641
642   // Bytes per second 
643   put_int4 (pData + 28, static_cast<int> (m_rate * m_nBytesPerSample + 0.5));
644
645   // Bytes per sample
646   put_int2 (pData + 32, m_nBytesPerSample * m_nChannels);
647
648   // Bits per sample 
649   put_int2 (pData + 34, m_nBitsPerSample);
650
651   strncpy (pData + 36, "data", 4);
652
653   put_int4 (pData + 40, m_nDataBytes);
654
655   return true;
656 }
657
658 bool
659 WavFile::WriteFile ()
660 {
661   if (! m_valid)
662     return false;
663
664   if (m_fd == 0)
665     if ((m_fd = open (m_strFile.c_str(), O_WRONLY | O_BINARY | O_TRUNC | O_CREAT, g_fileMode)) == 0) {
666       std::ostringstream os;
667       os << "Error opening output file " << m_strFile.c_str();
668       error_msg (os.str().c_str());
669       return false;
670     }
671
672   lseek (m_fd, 0, SEEK_SET);
673   if (write (m_fd, m_data, m_nFileBytes) != m_nFileBytes) {
674     error_msg ("Error writing file");
675     return false;
676   }
677
678   if (close (m_fd) < 0)
679     error_msg ("Error closing output file");
680   
681   m_fd = 0;
682   return true;
683 }
684
685 #ifdef WIN32
686 #include <windows.h>
687 #include <mmsystem.h>
688 #elif defined(LINUX)
689 #include <sys/ioctl.h>
690 #include <sys/soundcard.h>
691 #endif
692
693 bool
694 WavFile::Play ()
695 {
696 #ifdef WIN32
697   if (PlaySound ((LPCSTR) m_data, 0, SND_MEMORY | SND_NODEFAULT))
698     return true;
699 #elif defined(LINUX)
700   int fd;
701   if ((fd = open ("/dev/dsp",O_WRONLY)) == -1) {
702     error_msg ("Error opening /dev/dsp");
703     return false;
704   }
705   
706   int format = AFMT_S16_LE;
707   if (ioctl (fd, SNDCTL_DSP_SETFMT, &format) == -1) {
708     error_msg ("Error setting DSP format");
709     close(fd); return false;
710   }
711   if (format != AFMT_S16_LE) {
712     error_msg ("DSP Format not set");
713     close(fd); return false;
714   }
715   
716   unsigned int channels = m_nChannels;
717   if (ioctl (fd, SNDCTL_DSP_CHANNELS, &format) == -1) {
718     error_msg ("Error setting number of channels");
719     close(fd); return false;
720   }
721   if (channels != m_nChannels) {
722     error_msg ("Number of channels not set");
723     close(fd); return false;
724   }
725
726   unsigned int speed = static_cast<int>(m_rate + 0.5);
727   if (ioctl (fd, SNDCTL_DSP_SPEED, &speed) == -1) {
728     error_msg ("Error setting sample rate");
729     close(fd); return false;
730   }
731   if (speed != m_rate && ! g_quiet) {
732     std::ostringstream os;
733     os << "Warning: Sample rate set to " << speed << ", not " << m_rate;
734     error_msg (os.str().c_str());
735   }
736     
737   if (write (fd, reinterpret_cast<char*>(m_data) + m_nHeaderBytes, m_nDataBytes) !=
738       m_nDataBytes) {
739     error_msg ("Error writing audio samples");
740     close(fd); return false;
741   }
742
743   close (fd);
744   return true;
745 #else
746 #endif
747   
748   return false;
749 }
750
751