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