File: ImportPCM.cpp

package info (click to toggle)
audacity 0.98-3
  • links: PTS
  • area: main
  • in suites: woody
  • size: 2,896 kB
  • ctags: 4,089
  • sloc: cpp: 26,099; ansic: 4,961; sh: 2,465; makefile: 156; perl: 23
file content (495 lines) | stat: -rw-r--r-- 12,295 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/**********************************************************************

  Audacity: A Digital Audio Editor

  ImportPCM.cpp

  Dominic Mazzoni

**********************************************************************/

#include <wx/file.h>
#include <wx/string.h>
#include <wx/thread.h>
#include <wx/timer.h>
#include <wx/msgdlg.h>
#include <wx/progdlg.h>

#include "Import.h"
#include "ImportPCM.h"
#include "WaveTrack.h"
#include "DirManager.h"
#include "Prefs.h"

#include "snd/snd.h"

bool IsPCM(wxString fName)
{
   wxFile testFile;
   testFile.Open(fName);
   if (!testFile.IsOpened())
      return false;

   snd_node sndfile;

   sndfile.device = SND_DEVICE_FILE;
   sndfile.write_flag = SND_READ;
   strcpy(sndfile.u.file.filename, (const char *) fName);
   sndfile.u.file.file = 0;

   int err;
   long flags = 0;

   err = snd_open(&sndfile, &flags);
   if (err)
      return false;

   int channels = sndfile.format.channels;
   if (channels < 1 || channels > 128) {
      snd_close(&sndfile);
      return false;
   }

   if (sndfile.u.file.header == SND_HEAD_WAVE) {
      snd_close(&sndfile);
      return true;
   }

   int len = sndfile.u.file.end_offset - sndfile.u.file.byte_offset;
   if (len <= 0) {
      snd_close(&sndfile);
      return false;
   }

   snd_close(&sndfile);
   return true;
}

bool ImportPCM(wxWindow * parent,
               wxString fName, WaveTrack ** dest1, WaveTrack ** dest2,
               DirManager * dirManager)
{
   *dest1 = 0;
   *dest2 = 0;

   // Get actual file len

   int actualFileLen;

   wxFile testFile;
   testFile.Open(fName);
   if (!testFile.IsOpened()) {
      wxMessageBox("Could not open file.");
      return false;
   }
   actualFileLen = testFile.Length();
   testFile.Close();

   // Initialize snd to actually process it

   snd_node sndfile;
   snd_node sndbuffer;

   sndfile.device = SND_DEVICE_FILE;
   sndfile.write_flag = SND_READ;
   strcpy(sndfile.u.file.filename, (const char *) fName);
   sndfile.u.file.file = 0;

   int err;
   long flags = 0;

   err = snd_open(&sndfile, &flags);
   if (err)
      return false;

   int channels = sndfile.format.channels;

   if (channels > 2 && channels <= 128) {
      wxString s;
      s.Printf("Sorry, Audacity does not support importing %d"
               "-channel files (yet).", channels);
      wxMessageBox(s);
      return false;
   }

   if (channels < 1) {
      wxMessageBox("Unknown audio format.");
      return false;
   }

   *dest1 = new WaveTrack(dirManager);
   wxASSERT(*dest1);
   (*dest1)->rate = sndfile.format.srate;
   (*dest1)->name = TrackNameFromFileName(fName);
   (*dest1)->channel = VTrack::MonoChannel;
   if (channels == 2) {
      *dest2 = new WaveTrack(dirManager);
      wxASSERT(*dest1);
      (*dest2)->rate = sndfile.format.srate;
      (*dest2)->name = TrackNameFromFileName(fName);
      (*dest1)->channel = VTrack::LeftChannel;
      (*dest2)->channel = VTrack::RightChannel;
      (*dest1)->linked = true;
   }

   long fileTotalFrames;

   if (sndfile.u.file.header == SND_HEAD_WAVE) {
      // Wave files are notorious for having bad headers, so we
      // use the actual file length to calculate the length of
      // the song, not the length stored in the header
      fileTotalFrames = (actualFileLen - sndfile.u.file.byte_offset) /
          snd_bytes_per_frame(&sndfile);
   } else {
      // For any other format (i.e. AIFF) we trust the value in
      // the header as long as it's plausible
      if ((sndfile.u.file.end_offset - sndfile.u.file.byte_offset) <
          actualFileLen)
         fileTotalFrames = (sndfile.u.file.end_offset -
                            sndfile.u.file.byte_offset) /
             snd_bytes_per_frame(&sndfile);
      else
         fileTotalFrames = (actualFileLen - sndfile.u.file.byte_offset) /
             snd_bytes_per_frame(&sndfile);
   }

   int maxblocksize = WaveTrack::GetIdealBlockSize();

   wxString copyEdit =
       gPrefs->Read("/FileFormats/CopyOrEditUncompressedData", "edit");

   bool doEdit = true;          // Fall back to "edit" if it doesn't match anything else
   if (copyEdit.IsSameAs("copy", false))
      doEdit = false;

   if (doEdit) {

      // If this mode has been selected, we form the tracks as
      // aliases to the files we're editing, i.e. ("foo.wav", 12000-18000)
      // instead of actually making fresh copies of the samples.

      wxProgressDialog *progress = NULL;
      wxYield();
      wxStartTimer();
      wxBusyCursor busy;

      bool cancelling = false;

      for (sampleCount i = 0; i < fileTotalFrames; i += maxblocksize) {
         sampleCount blockLen = maxblocksize;
         if (i + blockLen > fileTotalFrames)
            blockLen = fileTotalFrames - i;

         (*dest1)->AppendAlias(fName, i, blockLen, 0);
         if (channels == 2) {
            (*dest2)->AppendAlias(fName, i, blockLen, 1);
         }

         if (!progress && wxGetElapsedTime(false) > 500) {
            progress =
                new wxProgressDialog("Import", "Importing audio file...",
                                     1000,
                                     parent,
                                     wxPD_CAN_ABORT |
                                     wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
         }
         if (progress) {
            cancelling = !progress->Update((i * 1000.0) / fileTotalFrames);

            if (cancelling)
               i = fileTotalFrames;
         }
      }

      //printf("Time elapsed: %d\n", wxGetElapsedTime());

      if (progress)
         delete progress;

      if (cancelling) {
         if (*dest1) {
            delete *dest1;
            *dest1 = NULL;
         }
         if (*dest2) {
            delete *dest2;
            *dest2 = NULL;
         }

         return false;
      }

      return true;
   }
   // Otherwise, we're in the "copy" mode, where we read in the actual
   // samples from the file and store our own local copy of the
   // samples in the tracks.

   sndbuffer.device = SND_DEVICE_MEM;
   sndbuffer.write_flag = SND_WRITE;
   sndbuffer.u.mem.buffer_max = 0;
   sndbuffer.u.mem.buffer = 0;
   sndbuffer.u.mem.buffer_len = 0;
   sndbuffer.u.mem.buffer_pos = 0;
   sndbuffer.format.channels = channels;
   sndbuffer.format.mode = SND_MODE_PCM;        // SND_MODE_FLOAT
   sndbuffer.format.bits = 16;
   sndbuffer.format.srate = sndfile.format.srate;

   char *srcbuffer = new char[maxblocksize * 2 * channels];
   char *dstbuffer = new char[maxblocksize * 2 * channels];
   char *leftbuffer = new char[maxblocksize * 2];
   char *rightbuffer = new char[maxblocksize * 2];

   long framescompleted = 0;

   wxProgressDialog *progress = NULL;
   wxYield();
   wxStartTimer();
   wxBusyCursor busy;

   bool cancelling = false;

   long block;
   do {
      block = maxblocksize;
      block = snd_read(&sndfile, srcbuffer, block);
      if (block > 0) {
         long b2 = snd_convert(&sndbuffer, dstbuffer,   // to
                               &sndfile, srcbuffer, block);     // from
         if (channels == 1)
            (*dest1)->Append((sampleType *) dstbuffer, b2);
         else {
            for (int i = 0; i < b2; i++) {
               ((sampleType *) leftbuffer)[i] =
                   ((sampleType *) dstbuffer)[2 * i];
               ((sampleType *) rightbuffer)[i] =
                   ((sampleType *) dstbuffer)[2 * i + 1];
            }
            (*dest1)->Append((sampleType *) leftbuffer, (sampleCount) b2);
            (*dest2)->Append((sampleType *) rightbuffer, (sampleCount) b2);
         }

         framescompleted += block;

      }

      if (!progress && wxGetElapsedTime(false) > 500) {
         progress =
             new wxProgressDialog("Import", "Importing audio file...",
                                  1000,
                                  parent,
                                  wxPD_CAN_ABORT |
                                  wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
      }
      if (progress) {
         int progressvalue = (framescompleted > fileTotalFrames) ?
             fileTotalFrames : framescompleted;

         cancelling =
             !progress->Update((progressvalue * 1000.0) / fileTotalFrames);

         if (cancelling)
            block = 0;
      }
   } while (block > 0);

   snd_close(&sndfile);

   //printf("Time elapsed: %d\n", wxGetElapsedTime());

   if (progress)
      delete progress;

   delete[]srcbuffer;
   delete[]dstbuffer;
   delete[]leftbuffer;
   delete[]rightbuffer;

   if (cancelling) {
      if (*dest1) {
         delete *dest1;
         *dest1 = NULL;
      }
      if (*dest2) {
         delete *dest2;
         *dest2 = NULL;
      }

      return false;
   }

   return true;
}

/*

 *
 * This old code isn't used anymore, but is a handy reference.
 * It parses a standard WAV file header and imports it into
 * the project.  Not needed because the snd library handles
 * WAV and many other formats.
 *


bool ImportWAV(wxString fName, WaveTrack **dest1, WaveTrack **dest2,
               DirManager *dirManager)
{
  *dest1 = 0;
  *dest2 = 0;

  wxFile inf;

  inf.Open(fName, wxFile::read);

  if (!inf.IsOpened()) {
    wxMessageBox("Could not open "+fName);
    return false;
  }

  char tag[5];
  int intRate=0;
  short channels=0;
  short bytesPerSample=0;
  
  inf.Read((void *)tag, 4);
  tag[4] = 0;
  if (strcmp(tag, "RIFF"))
  {
    wxMessageBox("Missing RIFF: Not a WAV file.");
    return false;
  } 

  inf.Seek(4, wxFromCurrent);

  inf.Read((void *)tag, 4);
  tag[4] = 0;
  if (strcmp(tag, "WAVE"))
  {
    wxMessageBox("Missing WAVE: Not a WAV file.");
    return false;
  } 

  inf.Read((void *)tag, 4);
  tag[4] = 0;
  if (strcmp(tag, "fmt "))
  {
    wxMessageBox("Missing fmt : Not a WAV file.");
    return false;
  } 

  inf.Seek(6, wxFromCurrent);

  inf.Read((short *)&channels, 2);
  channels = wxUINT16_SWAP_ON_BE(channels);

#ifdef VERBOSE
  printf("channels: %d\n",(int)channels);
#endif

  inf.Read((int *)&intRate, 4);
  intRate = wxUINT32_SWAP_ON_BE(intRate);

#ifdef VERBOSE
  printf("rate: %d\n", intRate);
#endif

  *dest1 = new WaveTrack(dirManager);
  wxASSERT(*dest1);
  (*dest1)->rate = (double)intRate;
  if (channels == 2) {
    *dest2 = new WaveTrack(dirManager);
    wxASSERT(*dest1);
    (*dest2)->rate = (double)intRate;
  }

  inf.Seek(4, wxFromCurrent);

  inf.Read((short *)&bytesPerSample, 2);
  bytesPerSample = wxUINT16_SWAP_ON_BE(bytesPerSample);
  bytesPerSample /= channels;

#ifdef VERBOSE
  printf("bps: %d\n", (int)bytesPerSample);
#endif

  inf.Seek(2, wxFromCurrent);
    
  inf.Read((void *)tag, 4);
  tag[4] = 0;
  if (strcmp(tag, "data"))
  {
    wxMessageBox("Missing data: Not a WAV file.");
    return false;
  }

  int len=0;

  inf.Read((int *)&len, 4);
  len = wxUINT32_SWAP_ON_BE(len);

#ifdef VERBOSE
  printf("Len: %d\n",len);
#endif

  int blockSize = WaveTrack::GetIdealBlockSize();

  wxProgressDialog *progress = NULL;
  
  wxYield();

  wxStartTimer();

  switch(bytesPerSample) {
  case 2: {
    sampleType *buffer = new sampleType[blockSize];
    sampleType *buffer2 = new sampleType[blockSize/2];
    wxASSERT(buffer);
    wxASSERT(buffer2);
    int numSamples = len / 2;
    int block;
    while(numSamples) {
      int block = (numSamples < blockSize? numSamples : blockSize);
      int actual = inf.Read((void *)buffer, sizeof(sampleType) * block);
      int i;
      for(i=0; i<actual/2; i++) {
          buffer[i] = wxUINT16_SWAP_ON_BE(buffer[i]);
        }
      if (channels==1)
        (*dest1)->Append(buffer, actual/2);
      else {
        for(i=0; i<actual/4; i++)
          buffer2[i] = buffer[i*2];
        (*dest1)->Append(buffer2, actual/4);
        for(i=0; i<actual/4; i++)
          buffer2[i] = buffer[i*2+1];
        (*dest2)->Append(buffer2, actual/4);        
      }
      numSamples -= (actual/2);
      if (!progress && wxGetElapsedTime(false) > 500) {
        progress =
          new wxProgressDialog("Import","Importing WAV file",
                               len/2);
      }

      if (progress)
        progress->Update(len/2 - numSamples);
    }
    delete[] buffer;
    delete[] buffer2;
  }
  break;
  default:
    wxMessageBox("Sorry, WAV file not 16-bit");
    return false;
  }

  if (progress)
    delete progress;

  inf.Close();

  return true;
}

*/