Implemented J2K desc to/from MD
[asdcplib.git] / src / pinkwave.cpp
1 /*
2 Copyright (c) 2015, John Hurst
3 All rights reserved.
4
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions
7 are met:
8 1. Redistributions of source code must retain the above copyright
9    notice, this list of conditions and the following disclaimer.
10 2. Redistributions in binary form must reproduce the above copyright
11    notice, this list of conditions and the following disclaimer in the
12    documentation and/or other materials provided with the distribution.
13 3. The name of the author may not be used to endorse or promote products
14    derived from this software without specific prior written permission.
15
16 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27 /*! \file    wavsplit.cpp
28     \version $Id$
29     \brief   Black WAV file generator
30 */
31
32 #include "Wav.h"
33 #include "ST2095_PinkNoise.h"
34 #include <assert.h>
35
36 using namespace ASDCP;
37
38 //------------------------------------------------------------------------------------------
39 //
40 // command line option parser class
41
42 static const char* PROGRAM_NAME = "pinkwave";    // program name for messages
43
44 // Macros used to test command option data state.
45
46 // Increment the iterator, test for an additional non-option command line argument.
47 // Causes the caller to return if there are no remaining arguments or if the next
48 // argument begins with '-'.
49 #define TEST_EXTRA_ARG(i,c)    if ( ++i >= argc || argv[(i)][0] == '-' ) \
50                                  { \
51                                    fprintf(stderr, "Argument not found for option %c.\n", (c)); \
52                                    return; \
53                                  }
54 //
55 void
56 banner(FILE* stream = stderr)
57 {
58   fprintf(stream, "\n\
59 %s (asdcplib %s)\n\n\
60 Copyright (c) 2015 John Hurst\n\n\
61 %s is part of asdcplib.\n\
62 asdcplib may be copied only under the terms of the license found at\n\
63 the top of every file in the asdcplib distribution kit.\n\n\
64 Specify the -h (help) option for further information about %s\n\n",
65           PROGRAM_NAME, ASDCP::Version(), PROGRAM_NAME, PROGRAM_NAME);
66 }
67
68 //
69 void
70 usage(FILE* stream = stderr)
71 {
72   fprintf(stream, "\
73 USAGE: %s [-v|-h[-d]] <filename>\n\
74 \n\
75   -V              - Show version\n\
76   -h              - Show help\n\
77   -d <duration>   - Number of edit units to process, default 1440\n\
78   -9              - Make a 96 kHz file (default 48 kHz)\n\
79 \n\
80 Other Options:\n\
81   -v              - Verbose, show extra detail during run\n\
82 \n\
83   NOTES: o There is no option grouping, all options must be distinct arguments.\n\
84          o All option arguments must be separated from the option by whitespace.\n\
85 \n", PROGRAM_NAME);
86 }
87
88 //
89 //
90 class CommandOptions
91 {
92   CommandOptions();
93
94 public:
95   bool   error_flag;     // true if the given options are in error or not complete
96   bool   verbose_flag;   // true if the verbose option was selected
97   bool   version_flag;   // true if the version display option was selected
98   bool   help_flag;      // true if the help display option was selected
99   bool   s96_flag;       // true if the samples should be at 96 kHz
100   ui32_t duration;       // number of frames to be processed
101   float  HpFc;           // Highpass filter cutoff frequency in Hz
102   float  LpFc;           // Lowpass filter cutoff frequency in Hz
103   const char* filename;  //
104
105   CommandOptions(int argc, const char** argv) :
106     error_flag(true), verbose_flag(false), version_flag(false), help_flag(false), s96_flag(false),
107     duration(1440), HpFc(PinkFilterHighPassConstant), LpFc(PinkFilterLowPassConstant), filename(0)
108   {
109     for ( int i = 1; i < argc; i++ )
110       {
111         if ( argv[i][0] == '-' && ( isalpha(argv[i][1]) || isdigit(argv[i][1]) ) && argv[i][2] == 0 )
112           {
113             switch ( argv[i][1] )
114               {
115               case 'V': version_flag = true; break;
116               case 'h': help_flag = true; break;
117               case 'v': verbose_flag = true; break;
118
119               case 'd':
120                 TEST_EXTRA_ARG(i, 'd');
121                 duration = Kumu::xabs(strtol(argv[i], 0, 10));
122                 break;
123
124               case '9':
125                 s96_flag = true;
126                 break;
127
128               default:
129                 fprintf(stderr, "Unrecognized option: %c\n", argv[i][1]);
130                 return;
131               }
132           }
133         else
134           {
135             if ( filename )
136               {
137                 fprintf(stderr, "Unexpected extra filename.\n");
138                 return;
139               }
140
141             filename = argv[i];
142           }
143       }
144
145     if ( filename == 0 )
146       {
147         fputs("Output filename required.\n", stderr);
148         return;
149       }
150
151     error_flag = false;
152   }
153 };
154
155 // 
156 //
157 Result_t
158 make_pink_wav_file(CommandOptions& Options)
159 {
160   PCM::FrameBuffer FrameBuffer;
161   PCM::AudioDescriptor ADesc;
162
163   ADesc.EditRate = Rational(24,1);
164   ADesc.AudioSamplingRate = Options.s96_flag ? ASDCP::SampleRate_96k : ASDCP::SampleRate_48k;
165   ADesc.Locked = 0;
166   ADesc.ChannelCount = 1;
167   ADesc.QuantizationBits = 24;
168   ADesc.BlockAlign = 3;
169   ADesc.AvgBps = ADesc.BlockAlign * ADesc.AudioSamplingRate.Quotient();
170   ADesc.LinkedTrackID = 1;
171   ADesc.ContainerDuration = Options.duration;
172
173   // set up LCG and pink filter
174   PinkFilter pink_filter(Options.s96_flag ? ASDCP::SampleRate_96k.Numerator : ASDCP::SampleRate_48k.Numerator,
175                          Options.HpFc, Options.LpFc);
176
177   LinearCongruentialGenerator lcg(Options.s96_flag ? ASDCP::SampleRate_96k.Numerator : ASDCP::SampleRate_48k.Numerator);
178
179
180   FrameBuffer.Capacity(PCM::CalcFrameBufferSize(ADesc));
181   FrameBuffer.Size(FrameBuffer.Capacity());
182   ui32_t samples_per_frame = PCM::CalcSamplesPerFrame(ADesc);
183
184   if ( Options.verbose_flag )
185     {
186       fprintf(stderr, "%s kHz PCM Audio, 24 fps (%u spf)\n",
187               (Options.s96_flag?"96":"48"), samples_per_frame);
188       fputs("AudioDescriptor:\n", stderr);
189       PCM::AudioDescriptorDump(ADesc);
190     }
191
192   // set up output file
193   Kumu::FileWriter OutFile;
194   Result_t result = OutFile.OpenWrite(Options.filename);
195
196   if ( ASDCP_SUCCESS(result) )
197     {
198        RF64::SimpleRF64Header WavHeader(ADesc);
199        result = WavHeader.WriteToFile(OutFile);
200     }
201
202   if ( ASDCP_SUCCESS(result) )
203     {
204       ui32_t write_count = 0;
205       ui32_t duration = 0;
206       byte_t scaled_pink[sizeof(ui32_t)];
207
208       while ( ASDCP_SUCCESS(result) && (duration++ < Options.duration) )
209         {
210           // fill the frame buffer with a frame of pink noise
211           byte_t *p = FrameBuffer.Data();
212
213           for ( int i = 0; i < samples_per_frame; ++i )
214             {
215               float pink_sample = pink_filter.GetNextSample(lcg.GetNextSample());
216               ScalePackSample(pink_sample, p, ADesc.BlockAlign);
217               p += ADesc.BlockAlign;
218             }
219
220           result = OutFile.Write(FrameBuffer.RoData(), FrameBuffer.Size(), &write_count);
221         }
222     }
223
224   return result;
225 }
226
227
228 //
229 int
230 main(int argc, const char** argv)
231 {
232   Result_t result = RESULT_OK;
233   CommandOptions Options(argc, argv);
234
235   if ( Options.help_flag )
236     {
237       usage();
238       return 0;
239     }
240
241   if ( Options.error_flag )
242     return 3;
243
244   if ( Options.version_flag )
245     banner();
246
247   else
248     result = make_pink_wav_file(Options);
249
250   if ( result != RESULT_OK )
251     {
252       fputs("Program stopped on error.\n", stderr);
253
254       if ( result != RESULT_FAIL )
255         {
256           fputs(result, stderr);
257           fputc('\n', stderr);
258         }
259
260       return 1;
261     }
262
263   return 0;
264 }
265
266
267 //
268 // end pinkwave.cpp
269 //