File: ExportMP3.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 (1043 lines) | stat: -rw-r--r-- 32,736 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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
/**********************************************************************

  Audacity: A Digital Audio Editor

  ExportMP3.cpp

  Joshua Haberman

  This just acts as an interface to LAME. A Lame dynamic library must
  be present

  The difficulty in our approach is that we are attempting to use LAME
  in a way it was not designed to be used. LAME's API is reasonably
  consistant, so if we were linking directly against it we could expect
  this code to work with a variety of different LAME versions. However,
  the data structures change from version to version, and so linking
  with one version of the header and dynamically linking against a
  different version of the dynamic library will not work correctly.

  The solution is to find the lowest common denominator between versions.
  The bare minimum of functionality we must use is this:
      1. Initialize the library.
      2. Set, at minimum, the following global options:
          i.  input sample rate
          ii. input channels
      3. Encode the stream
      4. Call the finishing routine

  Just so that it's clear that we're NOT free to use whatever features
  of LAME we like, I'm not including lame.h, but instead enumerating
  here the extent of functions and structures that we can rely on being
  able to import and use from a dynamic library.

  For the record, we aim to support LAME 3.70 on. Since LAME 3.70 was
  released in April of 2000, that should be plenty.

  UPDATE: Linux now uses the stable, function-based interface for
  getting and settting parameters, so it should be forward compatible.
  However, it requires LAME 3.89 or greater.

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

#ifdef __WXMAC__
#include <Files.h>
void wxMacFilename2FSSpec( const char *path , FSSpec *spec ) ;
#endif

#include <wx/dynlib.h>
#include <wx/msgdlg.h>
#include <wx/utils.h>
#include <wx/progdlg.h>
#include <wx/timer.h>
#include <wx/window.h>
#include <wx/ffile.h>
#include <wx/log.h>
#include <wx/filedlg.h>

#include "ExportMP3.h"
#include "Mix.h"
#include "Prefs.h"
#include "Project.h"
#include "Tags.h"
#include "WaveTrack.h"


MP3Exporter::MP3Exporter()
{
   if (gPrefs)
      mLibPath = gPrefs->Read("/MP3/MP3LibPath", "");
}

bool MP3Exporter::FindLibrary(wxWindow *parent)
{
   mLibPath = gPrefs->Read("/MP3/MP3LibPath", "");

   if (mLibPath=="" || !::wxFileExists(mLibPath)) {
   
      int action = wxMessageBox(GetLibraryMessage(),
                                "Export MP3",
                                wxYES_NO | wxICON_EXCLAMATION,
                                parent);

      if (action == wxYES) {
         wxString question;
         question.Printf("Where is %s?", (const char *)GetLibraryName());
         mLibPath = wxFileSelector(question, NULL,
                                   GetLibraryName(),        // Name
                                   "",      // Extension
                                   GetLibraryTypeString(),
                                   wxOPEN, parent);
         
         if (mLibPath == "") {
            mLibPath = "";
            gPrefs->Write("/MP3/MP3LibPath", mLibPath);
         
            return false;
         }
         
         wxString path, baseName, extension;
         ::wxSplitPath(mLibPath, &path, &baseName, &extension);
         
         if (extension != "")
            baseName += "." + extension;
         
         if (baseName != GetLibraryName()) {
         
            wxString question;
            question.Printf("Audacity was expecting a library named \"%s\".  "
                            "Are you sure you want to attempt to export MP3 "
                            "files using \"%s\"?",
                            (const char *)GetLibraryName(),
                            (const char *)baseName);

            int action = wxMessageBox(question,
                                      "Export MP3",
                                      wxYES_NO | wxICON_EXCLAMATION,
                                      parent);
            
            if (action != wxYES) {
               mLibPath = "";
               gPrefs->Write("/MP3/MP3LibPath", mLibPath);
            
               return false;
            }
         }
      }
      else {
         mLibPath = "";
         gPrefs->Write("/MP3/MP3LibPath", mLibPath);
            
         return false;
      }
      
      gPrefs->Write("/MP3/MP3LibPath", mLibPath);
   }
   
   return true;
}

#ifdef __WXGTK__

   /* --------------------------------------------------------------------------*/

   struct lame_global_flags;
   typedef lame_global_flags *lame_init_t(void);
   typedef int lame_init_params_t(lame_global_flags*);
   typedef const char* get_lame_version_t(void);

   typedef int lame_encode_buffer_t (
         lame_global_flags* gf,
         const short int    buffer_l [],
         const short int    buffer_r [],
         const int          nsamples,
         unsigned char *    mp3buf,
         const int          mp3buf_size );

   typedef int lame_encode_buffer_interleaved_t(
         lame_global_flags* gf,
         short int          pcm[],
         int                num_samples,   /* per channel */
         unsigned char*     mp3buf,
         int                mp3buf_size );

   typedef int lame_encode_flush_t(
         lame_global_flags *gf,
         unsigned char*     mp3buf,
         int                size );

   typedef int lame_close_t(lame_global_flags*);
   
   typedef int lame_set_in_samplerate_t(lame_global_flags*, int);
   typedef int lame_set_num_channels_t(lame_global_flags*, int );
   typedef int lame_set_quality_t(lame_global_flags*, int);
   typedef int lame_get_quality_t(lame_global_flags*);
   typedef int lame_set_brate_t(lame_global_flags*, int);
   typedef int lame_get_brate_t(lame_global_flags*);
   

   /* --------------------------------------------------------------------------*/

   class LinuxLAMEExporter : public MP3Exporter {
      private:
         /* function pointers to the symbols we get from the library */
         lame_init_t* lame_init;
         lame_init_params_t* lame_init_params;
         lame_encode_buffer_interleaved_t* lame_encode_buffer_interleaved;
         lame_encode_flush_t* lame_encode_flush;
         lame_close_t* lame_close;
         get_lame_version_t* get_lame_version;
         
         lame_set_in_samplerate_t* lame_set_in_samplerate;
         lame_set_num_channels_t* lame_set_num_channels;
         lame_set_quality_t* lame_set_quality;
         lame_get_quality_t* lame_get_quality;
         lame_set_brate_t* lame_set_brate;
         lame_get_brate_t* lame_get_brate;

         lame_global_flags *mGF;
         
         bool mLibraryLoaded, mEncoding;
         char mVersion[20];

         static const int mSamplesPerChunk = 220500;
         static const int mOutBufferSize = int(1.25 * mSamplesPerChunk + 7200);
      public:
         
         LinuxLAMEExporter() {
            mLibraryLoaded = false;
            mEncoding = false;
            mGF = NULL;
         }
         
         wxString GetLibraryName()
         {
            return "libmp3lame.so";
         }
         
         wxString GetLibraryTypeString()
         {
            return wxString("Shared Object files (*.so)|*.so");
         }
         
         wxString GetLibraryMessage()
         {
            return "Audacity does not export MP3 files directly, but instead uses the \n"
                   "freely available LAME library to handle MP3 file encoding.  You must \n"
                   "obtain libmp3lame.so separately, either by downloading it or building \n"
                   "it from the sources, and then locate the file for Audacity.  You only \n"
                   "need to do this once.\n\n"
                   "Would you like to locate libmp3lame.so now?";
         }

         bool  LoadLibrary() {
            wxLogNull logNo;

            wxDllType libHandle = NULL;

            if (wxFileExists(mLibPath))
               libHandle = wxDllLoader::LoadLibrary(mLibPath);
            else
               return false;

            /* get function pointers from the shared library */

            lame_init = (lame_init_t *)wxDllLoader::GetSymbol(libHandle, "lame_init");
            get_lame_version = (get_lame_version_t *)wxDllLoader::GetSymbol(libHandle,
                                                                         "get_lame_version");
            lame_init_params = 
               (lame_init_params_t *) wxDllLoader::GetSymbol(libHandle, "lame_init_params");
            lame_encode_buffer_interleaved =
                (lame_encode_buffer_interleaved_t *) wxDllLoader::GetSymbol(libHandle,
                                                          "lame_encode_buffer_interleaved");
            lame_encode_flush =
                (lame_encode_flush_t *) wxDllLoader::GetSymbol(libHandle, "lame_encode_flush");
            lame_close =
                (lame_close_t *) wxDllLoader::GetSymbol(libHandle, "lame_close");

            lame_close =
                (lame_close_t *) wxDllLoader::GetSymbol(libHandle, "lame_close");

            lame_set_in_samplerate =
                (lame_set_in_samplerate_t *) wxDllLoader::GetSymbol(libHandle,
                                                              "lame_set_in_samplerate");
            lame_set_num_channels =
                (lame_set_num_channels_t *) wxDllLoader::GetSymbol(libHandle,
                                                              "lame_set_num_channels");
            lame_set_quality =
                (lame_set_quality_t *) wxDllLoader::GetSymbol(libHandle,
                                                              "lame_set_quality");
            lame_get_quality =
                (lame_get_quality_t *) wxDllLoader::GetSymbol(libHandle,
                                                              "lame_get_quality");
            lame_set_brate =
                (lame_set_brate_t *) wxDllLoader::GetSymbol(libHandle,
                                                              "lame_set_brate");
            lame_get_brate =
                (lame_get_brate_t *) wxDllLoader::GetSymbol(libHandle,
                                                              "lame_get_brate");

            /* we assume that if all the symbols are found, it's a valid library */

            if (!lame_init ||
                !get_lame_version ||
                !lame_init_params ||
                !lame_encode_buffer_interleaved ||
                !lame_encode_flush ||
                !lame_close ||
                !lame_set_in_samplerate ||
                !lame_set_num_channels ||
                !lame_set_quality ||
                !lame_set_brate) {
               return false;
            }

            mGF = lame_init();
            mLibraryLoaded = true;
            return true;
         }

      bool ValidLibraryLoaded() { return mLibraryLoaded; }

      const char *GetLibraryVersion() {
         if(!mLibraryLoaded) return "";

         return wxString::Format("LAME %s", get_lame_version()).c_str();
      }

      int InitializeStream(int channels, int sampleRate) {
         if(!mLibraryLoaded) return -1;

         lame_set_num_channels(mGF, channels);
         lame_set_in_samplerate(mGF, sampleRate);

         lame_init_params(mGF);

         mEncoding = true;
         return mSamplesPerChunk;
      }

      int GetOutBufferSize() {
         return mOutBufferSize;
      }

      int EncodeBuffer(short int inbuffer[], unsigned char outbuffer[]) {
         if(!mEncoding) return -1;

         return lame_encode_buffer_interleaved(mGF, inbuffer, mSamplesPerChunk,
            outbuffer, mOutBufferSize);
      }

      int EncodeRemainder(short int inbuffer[], int nSamples,
                        unsigned char outbuffer[]) {
         return lame_encode_buffer_interleaved(mGF, inbuffer, nSamples, outbuffer,
            mOutBufferSize);
      }

      int FinishStream(unsigned char outbuffer[]) {
         mEncoding = false;
         lame_encode_flush(mGF, outbuffer, mOutBufferSize);
         lame_close(mGF);
      }

      void CancelEncoding() { mEncoding = false; }

      int GetConfigurationCaps() { return MP3CONFIG_BITRATE|MP3CONFIG_QUALITY; }

      int GetQualityVariance() { return 10; }

      void SetBitrate(int rate) { lame_set_brate(mGF, rate); }
      int GetBitrate() { return lame_get_quality(mGF); }

      /* lame specifies 0: highest and 9: lowest. We want 1: lowest and 10: highest */
      void SetQuality(int quality) { lame_set_quality(mGF, 10 - quality); }
      int GetQuality() {
         int quality = (10 - lame_get_quality(mGF)); 
         printf(" quality: %d\n", quality);
         printf(" lame's returning: %d\n", lame_get_quality(mGF));
         return quality;
      }
   };

MP3Exporter *gMP3Exporter = NULL;

MP3Exporter *GetMP3Exporter()
{
   if (!gMP3Exporter)
      gMP3Exporter = new LinuxLAMEExporter();
   
   return gMP3Exporter;
}

#elif defined(__WXMAC__)

   /* --------------------------------------------------------------------------*/

   /* The following code is intended to work with LAMELib, roughly LAME
      verson 3.87, as distributed by N2MP3. */

   typedef struct {
      /* input file description */
      unsigned long num_samples;  /* number of samples. default=2^32-1    */
      int num_channels;           /* input number of channels. default=2  */
      int in_samplerate;          /* input_samp_rate. default=44.1kHz     */
      int out_samplerate;         /* output_samp_rate. (usually determined automatically)   */ 
      float scale;                /* scale input by this amount */

      /* general control params */
      int gtkflag;                /* run frame analyzer?       */
      int bWriteVbrTag;           /* add Xing VBR tag?         */
      int disable_waveheader;     /* disable writing of .wav header, when *decoding* */
      int decode_only;            /* use lame/mpglib to convert mp3 to wav */
      int ogg;                    /* encode to Vorbis .ogg file */

      int quality;                /* quality setting 0=best,  9=worst  */
      int silent;                 /* disable some status output */
      float update_interval;      /* to use Frank's time status display */
      int brhist_disp;            /* enable VBR bitrate histogram display */
      int mode;                       /* 0,1,2,3 stereo,jstereo,dual channel,mono */
      int mode_fixed;                 /* use specified the mode, do not use lame's opinion of the best mode */
      int force_ms;                   /* force M/S mode.  requires mode=1 */
      int brate;                      /* bitrate */
      float compression_ratio;          /* user specified compression ratio, instead of brate */
      int free_format;                /* use free format? */

      int space[10000];  /* to liberally accomadate for the real size of the struct */
   } lame_global_flags;

   /* All functions types are suffexed with _t because gcc won't let you have a
    * type and a variable of the same name */

   typedef void lame_init_t(lame_global_flags *);

   /* NOTE: Same deal with this one: >= 3.88 changes it to: const char
    * *get_lame_version(), but this time they don't even leave us a
    * compatibility version! aggh! */
   typedef void lame_version_t(lame_global_flags *, char *);
   typedef const char *get_lame_version_t();

   typedef void lame_init_params_t(lame_global_flags*);

   typedef int lame_encode_buffer_t (
         lame_global_flags* gf,
         const short int    buffer_l [],
         const short int    buffer_r [],
         const int          nsamples,
         unsigned char *    mp3buf,
         const int          mp3buf_size );

   typedef int lame_encode_buffer_interleaved_t(
         lame_global_flags* gf,
         short int          pcm[],
         int                num_samples,   /* per channel */
         unsigned char*     mp3buf,
         int                mp3buf_size );

   typedef int lame_encode_finish_t(
         lame_global_flags *gf,
         unsigned char*     mp3buf,
         int                size );

   /* --------------------------------------------------------------------------*/

   class MacLAMEExporter : public MP3Exporter {
      private:
         lame_init_t* lame_init;
         lame_version_t* lame_version;
         get_lame_version_t* get_lame_version;
         lame_init_params_t* lame_init_params;
         lame_encode_buffer_t* lame_encode_buffer;
         lame_encode_finish_t* lame_encode_finish;

         lame_global_flags *mGF;
         
         bool mLibraryLoaded, mEncoding;
         char mVersion[20];

         static const int mSamplesPerChunk = 220500;
         static const int mOutBufferSize = int(1.25 * mSamplesPerChunk + 7200);

         short int *mLeftBuffer;
         short int *mRightBuffer;
         
      public:
         
         MacLAMEExporter() {
            mLibraryLoaded = false;
            mEncoding = false;
            mGF = NULL;
         }

         wxString GetLibraryName()
         {
            return "LAMELib";
         }
         
         wxString GetLibraryTypeString()
         {
            return "Shared Libraries|*";
         }
         
         wxString GetLibraryMessage()
         {
            // Must be <= 255 characters on Mac
            return "Audacity does not export MP3 files directly, but instead uses LAME, "
                   "an MP3 exporting library available separately.  See the documentation "
                   "for more information.\n\n"
                   "Would you like to locate LameLib now?";
         }

         bool  LoadLibrary() {
            wxLogNull logNo;

            wxDllType libHandle = NULL;

            if (wxFileExists(mLibPath))
               libHandle = wxDllLoader::LoadLibrary(mLibPath);
            else
               return false;

            lame_init = (lame_init_t *) wxDllLoader::GetSymbol(libHandle, "lame_init");

            lame_version = (lame_version_t *) wxDllLoader::GetSymbol(libHandle, "lame_version");
            
            get_lame_version =
               (get_lame_version_t *) wxDllLoader::GetSymbol(libHandle, "get_lame_version");

            lame_init_params = 
               (lame_init_params_t *) wxDllLoader::GetSymbol(libHandle, "lame_init_params");

            lame_encode_buffer =
                (lame_encode_buffer_t *) wxDllLoader::GetSymbol(libHandle,
                                                                "lame_encode_buffer");
            lame_encode_finish =
                (lame_encode_finish_t *) wxDllLoader::GetSymbol(libHandle, "lame_encode_finish");

            if (!lame_init ||
                !lame_init_params ||
                !lame_encode_buffer ||
                !(lame_version || get_lame_version) ||
                !lame_encode_finish) {
               return false;
            }

            mGF = new lame_global_flags;
            lame_init(mGF);
            mLibraryLoaded = true;
            return true;
         }

      bool ValidLibraryLoaded() { return mLibraryLoaded; }

      const char *GetLibraryVersion() {
         if(!mLibraryLoaded) return "";

         if(get_lame_version)
            return get_lame_version();
         else {
            lame_version(mGF, mVersion);
            return mVersion;
         }
      }

      int InitializeStream(int channels, int sampleRate) {
         if(!mLibraryLoaded) return -1;

         mGF->num_channels = channels;
         mGF->in_samplerate = sampleRate;
         mGF->out_samplerate = sampleRate;
         mGF->num_samples = 0;
         
         if (channels == 1)
            mGF->mode = 3;  // mono
         else
            mGF->mode = 1;  // joint stereo

         lame_init_params(mGF);
         
         mLeftBuffer = new short[mSamplesPerChunk];
         mRightBuffer = new short[mSamplesPerChunk];

         mEncoding = true;
         return mSamplesPerChunk;
      }

      int GetOutBufferSize() {
         return mOutBufferSize;
      }
      
      int GetConfigurationCaps() {
         return MP3CONFIG_BITRATE;
      }

      int EncodeBuffer(short int inbuffer[], unsigned char outbuffer[]) {
         if(!mEncoding) return -1;
         
         if (mGF->num_channels == 2) {
            for(int i=0; i<mSamplesPerChunk; i++) {
               mLeftBuffer[i] = inbuffer[2*i];
               mRightBuffer[i] = inbuffer[2*i+1];
            }

            return lame_encode_buffer(mGF, mLeftBuffer, mRightBuffer, mSamplesPerChunk,
                                      outbuffer, mOutBufferSize);
         }
         else {
            return lame_encode_buffer(mGF, inbuffer, inbuffer, mSamplesPerChunk,
                       outbuffer, mOutBufferSize);
         }
      }

      int EncodeRemainder(short int inbuffer[], int nSamples,
                        unsigned char outbuffer[]) {

         if (mGF->num_channels == 2) {
            for(int i=0; i<nSamples; i++) {
               mLeftBuffer[i] = inbuffer[2*i];
               mRightBuffer[i] = inbuffer[2*i+1];
            }

            return lame_encode_buffer(mGF, mLeftBuffer, mRightBuffer, nSamples, outbuffer,
               mOutBufferSize);
         }
         else {
            return lame_encode_buffer(mGF, inbuffer, inbuffer, nSamples,
                       outbuffer, mOutBufferSize);
         }
      }

      int FinishStream(unsigned char outbuffer[]) {
         mEncoding = false;
         int result = lame_encode_finish(mGF, outbuffer, mOutBufferSize);
         
         delete[] mLeftBuffer;
         delete[] mRightBuffer;
         
         return result;
      }

      void CancelEncoding() { mEncoding = false; }

      int GetQualityVariance() { return -1; }

      void SetBitrate(int rate) { }
      int GetBitrate() { return -1; }

      void SetQuality(int quality) { }
      int GetQuality() { return -1; }
   };

MP3Exporter *gMP3Exporter = NULL;

MP3Exporter *GetMP3Exporter()
{
   if (!gMP3Exporter)
      gMP3Exporter = new MacLAMEExporter();
   
   return gMP3Exporter;
}

#elif defined(__WXMSW__)

#include "BladeMP3EncDLL.h"

class BladeEncExporter : public MP3Exporter {
private:
   BE_CONFIG mConf;
   BE_VERSION mVersion;
   HBE_STREAM mStreamHandle;
   bool mLibraryLoaded, mEncoding,mStereo;
   unsigned long mOutBufferSize, mInSampleNum;
   int mDefaultRate;


   BEINITSTREAM beInitStream;
   BEENCODECHUNK beEncodeChunk;
   BEDEINITSTREAM beDeinitStream;
   BECLOSESTREAM beCloseStream;
   BEVERSION beVersion;


public:
   BladeEncExporter() {
      mLibraryLoaded = false;
      mEncoding = false;

      /* Set all the config defaults to sane values */

      memset(&mConf, 0, sizeof(BE_CONFIG));
//      mConf.dwConfig = BE_CONFIG_LAME;
//      mConf.format.LHV1.dwStructVersion = 1;
//      mConf.format.LHV1.dwStructSize = sizeof(BE_CONFIG);
//      mConf.format.LHV1.dwReSampleRate = 0;
//      mConf.format.LHV1.dwBitrate = 128;
      //mConf.format.LHV1.dwMaxBitrate = 128;
//      mConf.format.LHV1.nPreset = LQP_HIGH_QUALITY;
//	  mConf.format.LHV1.dwMpegVersion = MPEG1;
//      mConf.format.LHV1.bCopyright = false;
//      mConf.format.LHV1.bCRC = true;
//      mConf.format.LHV1.bOriginal = false;
//      mConf.format.LHV1.bPrivate = false;
//      mConf.format.LHV1.bWriteVBRHeader = false;
//      mConf.format.LHV1.bEnableVBR = true;
//      mConf.format.LHV1.nVBRQuality = 2;
//      mConf.format.LHV1.dwVbrAbr_bps = -1;
//      mConf.format.LHV1.bNoRes = true;
      mConf.dwConfig = BE_CONFIG_MP3;
      mConf.format.mp3.wBitrate = 128;
      mConf.format.mp3.bCopyright = false;
      mConf.format.mp3.bCRC = true;
      mConf.format.mp3.bOriginal = false;
      mConf.format.mp3.bPrivate = false;
      
      mDefaultRate = 128;
   }

   wxString GetLibraryName()
   {
      return "lame_enc.dll";
   }
   
   wxString GetLibraryTypeString()
   {
      return "Dynamically Linked Libraries (*.dll)|*.dll";
   }
   
   wxString GetLibraryMessage()
   {
      return "Audacity does not export MP3 files directly, but instead uses the\n"
             "freely available LAME library to handle MP3 file encoding.  You must\n"
             "obtain lame_enc.dll separately, by downloading the LAME MP3 encoder,\n"
             "and then locate this file for Audacity.  You only need to do this once.\n\n"
             "Would you like to locate lame_enc.dll now?";
   }


   bool  LoadLibrary() {
      wxLogNull logNo;

      wxDllType libHandle = NULL;

      if (wxFileExists(mLibPath))
         libHandle = wxDllLoader::LoadLibrary(mLibPath);
      else
         return false;

      beInitStream = (BEINITSTREAM)wxDllLoader::GetSymbol(libHandle, "beInitStream");
      beEncodeChunk = (BEENCODECHUNK)wxDllLoader::GetSymbol(libHandle, "beEncodeChunk");
      beDeinitStream = (BEDEINITSTREAM)wxDllLoader::GetSymbol(libHandle, "beDeinitStream");
      beCloseStream = (BECLOSESTREAM)wxDllLoader::GetSymbol(libHandle, "beCloseStream");
      beVersion = (BEVERSION)wxDllLoader::GetSymbol(libHandle, "beVersion");

      if(!beInitStream ||
         !beEncodeChunk ||
         !beDeinitStream ||
         !beCloseStream ||
         !beVersion)
         return false;

      beVersion(&mVersion);
      mLibraryLoaded = true;
      return true;
   }

   bool ValidLibraryLoaded() { return mLibraryLoaded; }

   const char *GetLibraryVersion() {
      BE_VERSION ver;

      if(!mLibraryLoaded)
         return NULL;

      beVersion(&ver);

      return wxString::Format("LAME v%d.%d", ver.byMajorVersion, ver.byMinorVersion).c_str();
   }

   int InitializeStream(int channels, int sampleRate) {

      if(!mLibraryLoaded)
         return -1;

	  //int modes[] = { 0, BE_MP3_MODE_MONO, BE_MP3_MODE_STEREO };
	  //mConf.format.LHV1.dwSampleRate = sampleRate;
	  //mConf.format.LHV1.nMode = modes[channels];
      int modes[] = { 0, BE_MP3_MODE_MONO, BE_MP3_MODE_STEREO };
      mConf.format.mp3.byMode = modes[channels];
      mConf.format.mp3.dwSampleRate = sampleRate;
      mConf.format.mp3.wBitrate = mDefaultRate;

      beInitStream(&mConf, &mInSampleNum, &mOutBufferSize, &mStreamHandle);

      mEncoding = true;

      if(channels == 2) {
         mStereo = true;
         return(mInSampleNum / 2); /* convert samples_total into samples_per_channel */
      }
      else {
         mStereo = false;
         return (mInSampleNum);
      }

   }

   int GetOutBufferSize() {
      if (!mEncoding)
         return -1;

      return mOutBufferSize;
   }

   int EncodeBuffer(short int inbuffer[], unsigned char outbuffer[]) {
      if(!mEncoding)
         return -1;
      
      unsigned long bytes;
      beEncodeChunk(mStreamHandle, mInSampleNum, inbuffer, outbuffer, &bytes);

      return bytes;
   }

   int EncodeRemainder(short int inbuffer[], int nSamples, unsigned char outbuffer[]) {
      if(!mEncoding)
         return -1;

      unsigned long bytes;
      beEncodeChunk(mStreamHandle, nSamples, inbuffer, outbuffer, &bytes);

      return bytes;
   }

   int FinishStream(unsigned char outbuffer[]) {
      if(!mEncoding)
         return -1;

      unsigned long bytes;
      beDeinitStream(mStreamHandle, outbuffer, &bytes);
      beCloseStream(mStreamHandle);

      mEncoding = false;
      return bytes;
   }

   void CancelEncoding() {
      beCloseStream(mStreamHandle);
   }

   int GetQualityVariance() { return -1; }

   int GetConfigurationCaps() {
      return MP3CONFIG_BITRATE;
   }
   
   void SetBitrate(int rate) { 
      mDefaultRate = rate;
   }

   int GetBitrate() {
      return mDefaultRate;
   }

   void SetQuality(int quality) { }
   int GetQuality() { return -1; }

};

MP3Exporter *gMP3Exporter = NULL;

MP3Exporter *GetMP3Exporter()
{
   if (!gMP3Exporter)
      gMP3Exporter = new BladeEncExporter();
   
   return gMP3Exporter;
}

#endif      

bool ExportMP3(AudacityProject *project,
               bool stereo, wxString fName,
               bool selectionOnly, double t0, double t1)
{
   double rate = project->GetRate();
   wxWindow *parent = project;
   TrackList *tracks = project->GetTracks();

   wxLogNull logNo;             /* temporarily disable wxWindows error messages */

   bool success = GetMP3Exporter()->FindLibrary(parent);
   
   if (!success)
      return false;

   success = GetMP3Exporter()->LoadLibrary();
   if (!success) {
      wxMessageBox("Could not open MP3 encoding library!");
      gPrefs->Write("/MP3/MP3LibPath", wxString(""));

      return false;
   }

   if(!GetMP3Exporter()->ValidLibraryLoaded()) {
      wxMessageBox("Not a valid or supported MP3 encoding library!");      
      gPrefs->Write("/MP3/MP3LibPath", wxString(""));
      
      return false;
   }
   
   /* Open file for writing */

   wxFFile outFile(fName, "wb");
   if (!outFile.IsOpened()) {
      wxMessageBox("Unable to open target file for writing");
      return false;
   }
   
   /* Put ID3 tags at beginning of file */
   
   Tags *tags = project->GetTags();
   if (!tags->ShowEditDialog(project, "Edit the ID3 tags for the MP3 file"))
      return false;  // used selected "cancel"

   char *id3buffer;
   int id3len;
   bool endOfFile;
   id3len = tags->ExportID3(&id3buffer, &endOfFile);
   if (!endOfFile)
     outFile.Write(id3buffer, id3len);

   /* Export MP3 using DLL */

   long bitrate = gPrefs->Read("/FileFormats/MP3Bitrate", 128);
   GetMP3Exporter()->SetBitrate(bitrate);

   int iRate = int (rate + 0.5);

   sampleCount inSamples = GetMP3Exporter()->InitializeStream(stereo ? 2 : 1, int(rate + 0.5));
   double timeStep =  (double)inSamples / rate;
   double t = t0;

   wxProgressDialog *progress = NULL;
   wxYield();
   wxStartTimer();
   wxBusyCursor busy;
   bool cancelling = false;
   long bytes;


   int bufferSize = GetMP3Exporter()->GetOutBufferSize();
   unsigned char *buffer = new unsigned char[bufferSize];
   wxASSERT(buffer);

   while (t < t1 && !cancelling) {

      double deltat = timeStep;
      bool lastFrame = false;
      sampleCount numSamples = inSamples;

      if (t + deltat > t1) {
         lastFrame = true;
         deltat = t1 - t;
         numSamples = int(deltat * rate + 0.5);
      }


      Mixer *mixer = new Mixer(stereo ? 2 : 1, numSamples, true);
      wxASSERT(mixer);
      mixer->Clear();


      TrackListIterator iter(tracks);
      VTrack *tr = iter.First();
      while (tr) {
         if (tr->GetKind() == VTrack::Wave) {
            if (tr->selected || !selectionOnly) {
               if (tr->channel == VTrack::MonoChannel)
                  mixer->MixMono((WaveTrack *) tr, t, t + deltat);
               if (tr->channel == VTrack::LeftChannel)
                  mixer->MixLeft((WaveTrack *) tr, t, t + deltat);
               if (tr->channel == VTrack::RightChannel)
                  mixer->MixRight((WaveTrack *) tr, t, t + deltat);
            }
         }
         tr = iter.Next();
      }
      
      sampleType *mixed = mixer->GetBuffer();

      if(lastFrame)
         bytes = GetMP3Exporter()->EncodeRemainder(mixed, numSamples, buffer);
      else
         bytes = GetMP3Exporter()->EncodeBuffer(mixed, buffer);

      outFile.Write(buffer, bytes);

      t += deltat;

      if (!progress && wxGetElapsedTime(false) > 500) {

         wxString message;

         if (selectionOnly)
            message =
                wxString::Format("Exporting the selected audio as an mp3");
         else
            message =
                wxString::Format("Exporting the entire project as an mp3");

         progress =
             new wxProgressDialog("Export",
                                  message,
                                  1000,
                                  parent,
                                  wxPD_CAN_ABORT |
                                  wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
      }

      if (progress) {
         cancelling =
             !progress->Update(int (((t - t0) * 1000) / (t1 - t0) + 0.5));
      }

      delete mixer;

   }

   bytes = GetMP3Exporter()->FinishStream(buffer);

   if (bytes)
      outFile.Write(buffer, bytes);
   
   /* Write ID3 tag if it was supposed to be at the end of the file */
   
   if (endOfFile)
      outFile.Write(id3buffer, id3len);
   delete[] id3buffer;

   /* Close file */
   
   outFile.Close();
      
   /* MacOS: set the file type/creator so that the OS knows it's an MP3
      file which was created by Audacity */
      
#ifdef __WXMAC__
   FSSpec spec;
   wxMacFilename2FSSpec(fName, &spec);
   FInfo finfo;
   if (FSpGetFInfo(&spec, &finfo) == noErr) {
      finfo.fdType = 'MP3 ';
      finfo.fdCreator = AUDACITY_CREATOR;

      FSpSetFInfo(&spec, &finfo);
   }
#endif

   if (progress)
      delete progress;

   delete[]buffer;
   
   return true;
}