r8646: support new windaq format
[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$
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$";
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_dont_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 preserving zero point\n";
115   std::cout << "  -m   Do not demean the data (don't 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_dont_demean = true;
141       break;
142     case 'z':
143       g_ignore_zero = true;
144       break;
145     case 'v':
146       g_verbose = true;
147       break;
148     case 'd':
149       g_debug = true;
150       break;
151     case 'p':
152       play = 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 read_float8 (int fd, double& f)
339 {
340   unsigned char buf[8];
341   if (read (fd, &buf, 8) != 8)
342     return false;
343
344 #if WORDS_BIG_ENDIAN
345   unsigned char c;
346   c = buf[0]; buf[0] = buf[7]; buf[7] = c;
347   c = buf[1]; buf[1] = buf[6]; buf[6] = c;
348   c = buf[2]; buf[2] = buf[5]; buf[5] = c;
349   c = buf[3]; buf[3] = buf[4]; buf[4] = c;
350 #endif
351
352   f = *(reinterpret_cast<double*>(buf));
353
354   return true;
355 }
356
357 bool
358 WindaqFile::ReadHeader ()
359 {
360   unsigned short int tmp2;
361
362   m_valid = false;
363   if ((m_fd = open (m_strFile.c_str(), O_RDONLY | O_BINARY)) < 0) {
364     m_error = "Unable to open file";
365     return false;
366   }
367
368   lseek (0, 0, SEEK_SET);
369   if (! read_int2 (m_fd, tmp2))
370     return false;
371   m_format = (tmp2 & 0xFF00) >> 8;
372   printf ("format=%d\n",m_format);
373   printf ("tmp2=%4x\n", tmp2);
374   m_nChannels = tmp2 & 0x1f;
375   m_sr_denom = (tmp2 & 0x7fff) >> 5;
376   m_sr_numer = (tmp2 & 0x8000) << 1;
377   
378   if (! read_int2 (m_fd, tmp2))
379     return false;
380
381   m_sr_numer |= tmp2;
382   if (! read_int2 (m_fd, tmp2))
383     return false;
384
385   m_channel_offset = tmp2 & 0xFF;
386   m_nBytes_channel_header = tmp2 >> 8;
387   
388   if (! read_int2 (m_fd, m_nHeader_bytes))
389     return false;
390
391   m_nMaxChannels = (m_nHeader_bytes - 112) / 36;
392   printf ("m_nMaxChannels = %d\n", m_nMaxChannels);
393
394   if (! read_int4 (m_fd, m_nData_bytes))
395     return false;
396
397   m_nSamples = (m_nData_bytes / m_nChannels) / 2;
398
399   lseek (m_fd, 28, SEEK_SET);
400   if (! read_float8 (m_fd, m_time_between_channel_samples))
401           return false;
402   printf ("time_between_channel_samples=%lf\n", m_time_between_channel_samples);
403
404   if (m_format == 0 || m_format == 1)
405          m_sample_rate = (double) m_nChannels / m_time_between_channel_samples;
406   else          
407           m_sample_rate = (double) m_sr_numer / (double) (m_sr_denom * m_nChannels);
408
409   lseek (m_fd, 36, SEEK_SET);
410   if (! read_int4 (m_fd, m_time_acq_start))
411     return false;
412
413   if (! read_int4 (m_fd, m_time_acq_stop))
414     return false;
415
416   // Verify Windaq signature
417   lseek (m_fd, m_nHeader_bytes - 2, SEEK_SET);
418   if (! read_int2 (m_fd, tmp2))
419     return false;
420
421   if (tmp2 != 0x8001) {
422     std::ostringstream os;
423     m_error = "File is not a valid WinDAQ file";
424     return false;
425   }
426
427   m_valid = true;
428   return true;
429 }
430   
431 WindaqChannel::WindaqChannel (WindaqFile& wdq, const int channel)
432   : r_wdq(wdq), m_data(0), m_slope(0), m_intercept (0), m_channel(channel),
433     m_valid(false)
434 {
435   if (wdq.m_valid) {
436     if (channel >= 1 && channel <= wdq.m_nChannels) {
437       if (read_channel_data())
438         m_valid = true;
439     } else {
440       std::ostringstream os;
441       os << "Channel " << channel << " is invalid, valid range 1-" <<
442         wdq.m_nChannels;
443       error_msg (os.str().c_str());
444     }
445   }
446 }
447
448 WindaqChannel::~WindaqChannel ()
449 {
450   if (m_data)
451     delete m_data;
452 }
453
454 bool
455 WindaqChannel::read_channel_data ()
456 {
457   int fd = r_wdq.m_fd;
458
459   m_data = new signed short int [r_wdq.m_nSamples * 2];
460
461   lseek (fd, r_wdq.m_channel_offset + 8 + 
462          (m_channel - 1) * r_wdq.m_nBytes_channel_header,
463          SEEK_SET);
464   if (! read_float8 (fd, m_slope))
465     return false;
466
467   if (! read_float8 (fd, m_intercept))
468     return false;
469
470   char units[7];
471   units[6] = 0;
472   if (read (fd, units, 6) != 6) {
473     error_msg ("Error reading file");
474     return false;
475   }
476   m_units = units;
477  
478   long int row_bytes = 2 * r_wdq.m_nChannels;
479
480   signed short int *sample_row = new signed short int [row_bytes];
481   
482   signed short int* psample = &sample_row[m_channel - 1];
483
484   lseek (fd, r_wdq.m_nHeader_bytes, SEEK_SET);
485   unsigned long int i;
486   signed short int data_max = 0, data_min = 0;
487   double total_data = 0;
488   for (i = 0; i < r_wdq.m_nSamples; i++) {
489     if (read (fd, sample_row, row_bytes) != row_bytes) {
490       std::ostringstream os;
491       os << "Error reading file at " << i;
492       error_msg (os.str().c_str());
493       delete sample_row;
494       return false;
495     }
496     signed short int v = *psample;
497
498 #if WORDS_BIG_ENDIAN
499     unsigned char* p = reinterpret_cast<unsigned char*>(&v);
500     unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
501 #endif
502
503     signed short int value = v >> 2;
504     m_data[i] = value;
505     total_data += value;
506     
507     if (i == 0) {
508       data_max = value;
509       data_min = value;
510     } else {
511       if (value > data_max)
512         data_max = value;
513       else if (value < data_min)
514         data_min = value;
515     }
516   }
517
518   m_max_raw_data = data_max;
519   m_min_raw_data = data_min;
520   m_max_scaled_data = (m_slope * data_max) + m_intercept;
521   m_min_scaled_data = (m_slope * data_min) + m_intercept;
522
523   if (! g_dont_demean) {
524     double dmean = total_data / static_cast<double>(r_wdq.m_nSamples);
525     int mean = nearest<int>(dmean);
526     std::cout << "Removing mean: " << (dmean * m_slope) + m_intercept <<
527       " " << m_units << std::endl;
528     
529     for (i = 0; i < r_wdq.m_nSamples; i++)
530       m_data[i] -= mean;
531   }
532   
533   delete sample_row;
534   return true;
535 }
536
537
538 WavFile::WavFile (WindaqChannel& wdq_channel, const char* fname)
539   : m_valid(false), m_data(0), m_nSamples(0), m_strFile(fname), m_fd(0)
540 {
541   if (wdq_channel.m_valid) {
542     m_nSamples = wdq_channel.r_wdq.m_nSamples;
543     m_nChannels = 1;
544     m_nBitsPerSample = 16;
545     m_nBytesPerSample = 2;
546     m_rate = wdq_channel.r_wdq.m_sample_rate;
547
548     double data_offset = 0, data_scale = 0;
549     if (g_ignore_zero) {
550       data_offset = -wdq_channel.m_min_scaled_data;
551       if (wdq_channel.m_max_scaled_data != wdq_channel.m_min_scaled_data)
552         data_scale = 65535. / (wdq_channel.m_max_scaled_data -
553                                wdq_channel.m_min_scaled_data);
554     } else {
555       double max_value = fabs(wdq_channel.m_max_scaled_data);
556       if (fabs (wdq_channel.m_min_scaled_data) > max_value)
557         max_value = fabs (wdq_channel.m_min_scaled_data);
558       if (max_value != 0.)
559         data_scale = 32767. / max_value;
560     }
561     
562     if (g_debug) {
563       std::ostringstream os;
564       os << "  Wav data_scale: " << data_scale << ", data_offset: " << data_offset;
565       info_msg (os.str().c_str());
566     }
567     
568     m_nHeaderBytes = 44;
569     m_nDataBytes = m_nSamples * m_nBytesPerSample * m_nChannels;
570     m_nFileBytes = m_nHeaderBytes + m_nDataBytes;
571
572     unsigned int nHeaderShortInts = m_nHeaderBytes / sizeof(signed short int);
573
574     m_data = new signed short int [m_nSamples + nHeaderShortInts];
575     signed short int* input = wdq_channel.m_data;
576     signed short int* output = &m_data[nHeaderShortInts];
577     double slope = wdq_channel.m_slope;
578     double intercept = wdq_channel.m_intercept;
579     
580     if (! fill_header ())
581       return;
582
583     unsigned long int i;
584     for (i = 0; i < m_nSamples; i++) {
585       double value = input[i];
586       value = (slope * value) + intercept;
587       if (g_ignore_zero) {
588         value = (value + data_offset) * data_scale;
589         value += 0.5 - 32768;
590       } else {
591         value = value * data_scale;
592       }
593       
594       signed short int v = static_cast<signed short int>(value);
595 #if WORDS_BIG_ENDIAN
596       unsigned char* p = reinterpret_cast<unsigned char*>(&v);
597       unsigned char c = p[0]; p[0] = p[1]; p[1] = c; 
598 #endif
599       output[i] = v;
600     }
601   }
602
603   m_valid = true;
604 }
605
606
607 WavFile::~WavFile ()
608 {
609   if (m_fd != 0)
610     close (m_fd);
611     
612   if (m_data != NULL)
613     delete m_data;
614 }
615
616 void
617 put_int4 (char* p, unsigned int n)
618 {
619   *p = n & 0xFF;
620   *(p+1) = 0xFF & (n >> 8);
621   *(p+2) = 0xFF & (n >> 16);
622   *(p+3) = 0xFF & (n >> 24);
623 }
624
625 void
626 put_int2 (char* p, unsigned short int n)
627 {
628   *p = n & 0xFF;
629   *(p+1) = 0xFF & (n >> 8);
630 }
631
632 bool
633 WavFile::fill_header ()
634 {
635   char* pData = reinterpret_cast<char*> (m_data);
636
637   strncpy (pData, "RIFF", 4);
638
639   // Length of file after 8 byte header
640   put_int4 (pData + 4, 36 + m_nDataBytes);
641
642   strncpy (pData + 8, "WAVEfmt ", 8);
643
644   // Length of header block
645   put_int4 (pData + 16, 0x10);
646
647   // Always 1
648   put_int2 (pData + 20, 1);
649
650   /* Number of channels */
651   put_int2 (pData + 22, m_nChannels);
652
653   // Sample Rate
654   put_int4 (pData + 24, static_cast<int> (m_rate + 0.5));
655
656   // Bytes per second 
657   put_int4 (pData + 28, static_cast<int> (m_rate * m_nBytesPerSample + 0.5));
658
659   // Bytes per sample
660   put_int2 (pData + 32, m_nBytesPerSample * m_nChannels);
661
662   // Bits per sample 
663   put_int2 (pData + 34, m_nBitsPerSample);
664
665   strncpy (pData + 36, "data", 4);
666
667   put_int4 (pData + 40, m_nDataBytes);
668
669   return true;
670 }
671
672 bool
673 WavFile::WriteFile ()
674 {
675   if (! m_valid)
676     return false;
677
678   if (m_fd == 0)
679     if ((m_fd = open (m_strFile.c_str(), O_WRONLY | O_BINARY | O_TRUNC | O_CREAT, g_fileMode)) == 0) {
680       std::ostringstream os;
681       os << "Error opening output file " << m_strFile.c_str();
682       error_msg (os.str().c_str());
683       return false;
684     }
685
686   lseek (m_fd, 0, SEEK_SET);
687   if (write (m_fd, m_data, m_nFileBytes) != m_nFileBytes) {
688     error_msg ("Error writing file");
689     return false;
690   }
691
692   if (close (m_fd) < 0)
693     error_msg ("Error closing output file");
694   
695   m_fd = 0;
696   return true;
697 }
698
699 #ifdef WIN32
700 #include <windows.h>
701 #include <mmsystem.h>
702 #elif defined(LINUX)
703 #include <sys/ioctl.h>
704 #include <sys/soundcard.h>
705 #endif
706
707 bool
708 WavFile::Play ()
709 {
710 #ifdef WIN32
711   if (PlaySound ((LPCSTR) m_data, 0, SND_MEMORY | SND_NODEFAULT))
712     return true;
713 #elif defined(LINUX)
714   int fd;
715   if ((fd = open ("/dev/dsp",O_WRONLY)) == -1) {
716     error_msg ("Error opening /dev/dsp");
717     return false;
718   }
719   
720   int format = AFMT_S16_LE;
721   if (ioctl (fd, SNDCTL_DSP_SETFMT, &format) == -1) {
722     error_msg ("Error setting DSP format");
723     close(fd); return false;
724   }
725   if (format != AFMT_S16_LE) {
726     error_msg ("DSP Format not set");
727     close(fd); return false;
728   }
729   
730   unsigned int channels = m_nChannels;
731   if (ioctl (fd, SNDCTL_DSP_CHANNELS, &format) == -1) {
732     error_msg ("Error setting number of channels");
733     close(fd); return false;
734   }
735   if (channels != m_nChannels) {
736     error_msg ("Number of channels not set");
737     close(fd); return false;
738   }
739
740   unsigned int speed = static_cast<int>(m_rate + 0.5);
741   if (ioctl (fd, SNDCTL_DSP_SPEED, &speed) == -1) {
742     error_msg ("Error setting sample rate");
743     close(fd); return false;
744   }
745   if (speed != m_rate && ! g_quiet) {
746     std::ostringstream os;
747     os << "Warning: Sample rate set to " << speed << ", not " << m_rate;
748     error_msg (os.str().c_str());
749   }
750     
751   if (write (fd, reinterpret_cast<char*>(m_data) + m_nHeaderBytes, m_nDataBytes) !=
752       m_nDataBytes) {
753     error_msg ("Error writing audio samples");
754     close(fd); return false;
755   }
756
757   close (fd);
758   return true;
759 #else
760 #endif
761   
762   return false;
763 }
764
765