6cb90e26102dcd434274ba40877c3336936a2bfc
[asdcplib.git] / src / as-02-unwrap.cpp
1 /*
2 Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, 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    as-02-unwrap.cpp
28     \version $Id$       
29     \brief   AS-02 file manipulation utility
30
31   This program extracts picture and sound from AS-02 files.
32
33   For more information about AS-02, please refer to the header file AS_02.h
34   For more information about asdcplib, please refer to the header file AS_DCP.h
35 */
36
37 #include <KM_fileio.h>
38 #include <AS_02.h>
39 #include <WavFileWriter.h>
40
41 using namespace ASDCP;
42
43 const ui32_t FRAME_BUFFER_SIZE = 4 * Kumu::Megabyte;
44
45 //------------------------------------------------------------------------------------------
46 //
47 // command line option parser class
48
49 static const char* PROGRAM_NAME = "as-02-unwrap";  // program name for messages
50
51 // Increment the iterator, test for an additional non-option command line argument.
52 // Causes the caller to return if there are no remaining arguments or if the next
53 // argument begins with '-'.
54 #define TEST_EXTRA_ARG(i,c)                                             \
55   if ( ++i >= argc || argv[(i)][0] == '-' ) {                           \
56     fprintf(stderr, "Argument not found for option -%c.\n", (c));       \
57     return;                                                             \
58   }
59
60 //
61 void
62 banner(FILE* stream = stdout)
63 {
64   fprintf(stream, "\n\
65 %s (asdcplib %s)\n\n\
66 Copyright (c) 2011-2012, Robert Scheler, Heiko Sparenberg Fraunhofer IIS, John Hurst\n\n\
67 asdcplib may be copied only under the terms of the license found at\n\
68 the top of every file in the asdcplib distribution kit.\n\n\
69 Specify the -h (help) option for further information about %s\n\n",
70           PROGRAM_NAME, ASDCP::Version(), PROGRAM_NAME);
71 }
72
73 //
74 void
75 usage(FILE* stream = stdout)
76 {
77   fprintf(stream, "\
78 USAGE: %s [-h|-help] [-V]\n\
79 \n\
80        %s [-1|-2] [-b <buffer-size>] [-d <duration>]\n\
81        [-f <starting-frame>] [-m] [-p <frame-rate>] [-R] [-s <size>] [-v] [-W]\n\
82        [-w] <input-file> [<file-prefix>]\n\n",
83           PROGRAM_NAME, PROGRAM_NAME, PROGRAM_NAME);
84
85   fprintf(stream, "\
86 Options:\n\
87   -1                - Split Wave essence to mono WAV files during extract.\n\
88                       Default is multichannel WAV\n\
89   -2                - Split Wave essence to stereo WAV files during extract.\n\
90                       Default is multichannel WAV\n\
91   -b <buffer-size>  - Specify size in bytes of picture frame buffer\n\
92                       Defaults to 4,194,304 (4MB)\n\
93   -d <duration>     - Number of frames to process, default all\n\
94   -f <start-frame>  - Starting frame number, default 0\n\
95   -h | -help        - Show help\n\
96   -k <key-string>   - Use key for ciphertext operations\n\
97   -m                - verify HMAC values when reading\n\
98   -s <size>         - Number of bytes to dump to output when -v is given\n\
99   -V                - Show version information\n\
100   -v                - Verbose, prints informative messages to stderr\n\
101   -W                - Read input file only, do not write destination file\n\
102   -w <width>        - Width of numeric element in a series of frame file names\n\
103                       (default 6)\n\
104   -z                - Fail if j2c inputs have unequal parameters (default)\n\
105   -Z                - Ignore unequal parameters in j2c inputs\n\
106 \n\
107   NOTES: o There is no option grouping, all options must be distinct arguments.\n\
108          o All option arguments must be separated from the option by whitespace.\n\n");
109 }
110
111 //
112 class CommandOptions
113 {
114   CommandOptions();
115
116 public:
117   bool   error_flag;     // true if the given options are in error or not complete
118   bool   key_flag;       // true if an encryption key was given
119   bool   read_hmac;      // true if HMAC values are to be validated
120   bool   split_wav;      // true if PCM is to be extracted to stereo WAV files
121   bool   mono_wav;       // true if PCM is to be extracted to mono WAV files
122   bool   verbose_flag;   // true if the verbose option was selected
123   ui32_t fb_dump_size;   // number of bytes of frame buffer to dump
124   bool   no_write_flag;  // true if no output files are to be written
125   bool   version_flag;   // true if the version display option was selected
126   bool   help_flag;      // true if the help display option was selected
127   bool   stereo_image_flag; // if true, expect stereoscopic JP2K input (left eye first)
128   ui32_t number_width;   // number of digits in a serialized filename (for JPEG extract)
129   ui32_t start_frame;    // frame number to begin processing
130   ui32_t duration;       // number of frames to be processed
131   bool   duration_flag;  // true if duration argument given
132   bool   j2c_pedantic;   // passed to JP2K::SequenceParser::OpenRead
133   ui32_t picture_rate;   // fps of picture when wrapping PCM
134   ui32_t fb_size;        // size of picture frame buffer
135   const char* file_prefix; // filename pre for files written by the extract mode
136   byte_t key_value[KeyLen];  // value of given encryption key (when key_flag is true)
137   byte_t key_id_value[UUIDlen];// value of given key ID (when key_id_flag is true)
138   PCM::ChannelFormat_t channel_fmt; // audio channel arrangement
139   const char* input_filename;
140   std::string prefix_buffer;
141
142   //
143   CommandOptions(int argc, const char** argv) :
144     error_flag(true), key_flag(false), read_hmac(false), split_wav(false),
145     mono_wav(false), verbose_flag(false), fb_dump_size(0), no_write_flag(false),
146     version_flag(false), help_flag(false), number_width(6),
147     start_frame(0), duration(0xffffffff), duration_flag(false), j2c_pedantic(true),
148     picture_rate(24), fb_size(FRAME_BUFFER_SIZE), file_prefix(0),
149     input_filename(0)
150   {
151     memset(key_value, 0, KeyLen);
152     memset(key_id_value, 0, UUIDlen);
153
154     for ( int i = 1; i < argc; ++i )
155       {
156
157         if ( (strcmp( argv[i], "-help") == 0) )
158           {
159             help_flag = true;
160             continue;
161           }
162          
163         if ( argv[i][0] == '-'
164              && ( isalpha(argv[i][1]) || isdigit(argv[i][1]) )
165              && argv[i][2] == 0 )
166           {
167             switch ( argv[i][1] )
168               {
169               case '1': mono_wav = true; break;
170               case '2': split_wav = true; break;
171
172               case 'b':
173                 TEST_EXTRA_ARG(i, 'b');
174                 fb_size = abs(atoi(argv[i]));
175
176                 if ( verbose_flag )
177                   fprintf(stderr, "Frame Buffer size: %u bytes.\n", fb_size);
178
179                 break;
180
181               case 'd':
182                 TEST_EXTRA_ARG(i, 'd');
183                 duration_flag = true;
184                 duration = abs(atoi(argv[i]));
185                 break;
186
187               case 'f':
188                 TEST_EXTRA_ARG(i, 'f');
189                 start_frame = abs(atoi(argv[i]));
190                 break;
191
192               case 'h': help_flag = true; break;
193               case 'm': read_hmac = true; break;
194
195               case 'p':
196                 TEST_EXTRA_ARG(i, 'p');
197                 picture_rate = abs(atoi(argv[i]));
198                 break;
199
200               case 's':
201                 TEST_EXTRA_ARG(i, 's');
202                 fb_dump_size = abs(atoi(argv[i]));
203                 break;
204
205               case 'V': version_flag = true; break;
206               case 'v': verbose_flag = true; break;
207               case 'W': no_write_flag = true; break;
208
209               case 'w':
210                 TEST_EXTRA_ARG(i, 'w');
211                 number_width = abs(atoi(argv[i]));
212                 break;
213
214               case 'Z': j2c_pedantic = false; break;
215               case 'z': j2c_pedantic = true; break;
216
217               default:
218                 fprintf(stderr, "Unrecognized option: %s\n", argv[i]);
219                 return;
220               }
221           }
222         else
223           {
224             if ( argv[i][0] != '-' )
225               {
226                 if ( input_filename == 0 )
227                   {
228                     input_filename = argv[i];
229                   }
230                 else if ( file_prefix == 0 )
231                   {
232                     file_prefix = argv[i];
233                   }
234               }
235             else
236               {
237                 fprintf(stderr, "Unrecognized argument: %s\n", argv[i]);
238                 return;
239               }
240           }
241       }
242
243     if ( help_flag || version_flag )
244       return;
245     
246     if ( input_filename == 0 )
247       {
248         fputs("At least one filename argument is required.\n", stderr);
249         return;
250       }
251
252     if ( file_prefix == 0 )
253       {
254         prefix_buffer = Kumu::PathSetExtension(input_filename, "") + "_";
255         file_prefix = prefix_buffer.c_str();
256       }
257
258     error_flag = false;
259   }
260 };
261
262
263 //------------------------------------------------------------------------------------------
264 // JPEG 2000 essence
265
266
267 // Read one or more plaintext JPEG 2000 codestreams from a plaintext ASDCP file
268 // Read one or more plaintext JPEG 2000 codestreams from a ciphertext ASDCP file
269 // Read one or more ciphertext JPEG 2000 codestreams from a ciphertext ASDCP file
270 //
271 Result_t
272 read_JP2K_file(CommandOptions& Options)
273 {
274   AESDecContext*     Context = 0;
275   HMACContext*       HMAC = 0;
276   JP2K::MXFReader    Reader;
277   JP2K::FrameBuffer  FrameBuffer(Options.fb_size);
278   ui32_t             frame_count = 0;
279
280   Result_t result = Reader.OpenRead(Options.input_filename);
281
282   if ( ASDCP_SUCCESS(result) )
283     {
284       JP2K::PictureDescriptor PDesc;
285       Reader.FillPictureDescriptor(PDesc);
286
287       frame_count = PDesc.ContainerDuration;
288
289       if ( Options.verbose_flag )
290         {
291           fprintf(stderr, "Frame Buffer size: %u\n", Options.fb_size);
292           JP2K::PictureDescriptorDump(PDesc);
293         }
294     }
295
296   if ( ASDCP_SUCCESS(result) && Options.key_flag )
297     {
298       Context = new AESDecContext;
299       result = Context->InitKey(Options.key_value);
300
301       if ( ASDCP_SUCCESS(result) && Options.read_hmac )
302         {
303           WriterInfo Info;
304           Reader.FillWriterInfo(Info);
305
306           if ( Info.UsesHMAC )
307             {
308               HMAC = new HMACContext;
309               result = HMAC->InitKey(Options.key_value, Info.LabelSetType);
310             }
311           else
312             {
313               fputs("File does not contain HMAC values, ignoring -m option.\n", stderr);
314             }
315         }
316     }
317
318   ui32_t last_frame = Options.start_frame + ( Options.duration ? Options.duration : frame_count);
319   if ( last_frame > frame_count )
320     last_frame = frame_count;
321
322   char name_format[64];
323   snprintf(name_format,  64, "%%s%%0%du.j2c", Options.number_width);
324
325   for ( ui32_t i = Options.start_frame; ASDCP_SUCCESS(result) && i < last_frame; i++ )
326     {
327       result = Reader.ReadFrame(i, FrameBuffer, Context, HMAC);
328
329       if ( ASDCP_SUCCESS(result) )
330         {
331           Kumu::FileWriter OutFile;
332           char filename[256];
333           ui32_t write_count;
334           snprintf(filename, 256, name_format, Options.file_prefix, i);
335           result = OutFile.OpenWrite(filename);
336
337           if ( ASDCP_SUCCESS(result) )
338             result = OutFile.Write(FrameBuffer.Data(), FrameBuffer.Size(), &write_count);
339
340           if ( Options.verbose_flag )
341             FrameBuffer.Dump(stderr, Options.fb_dump_size);
342         }
343     }
344
345   return result;
346 }
347
348 //------------------------------------------------------------------------------------------
349 // PCM essence
350
351 // Read one or more plaintext PCM audio streams from a plaintext ASDCP file
352 // Read one or more plaintext PCM audio streams from a ciphertext ASDCP file
353 // Read one or more ciphertext PCM audio streams from a ciphertext ASDCP file
354 //
355 Result_t
356 read_PCM_file(CommandOptions& Options)
357 {
358   AESDecContext*     Context = 0;
359   HMACContext*       HMAC = 0;
360   PCM::MXFReader     Reader;
361   PCM::FrameBuffer   FrameBuffer;
362   WavFileWriter      OutWave;
363   PCM::AudioDescriptor ADesc;
364   ui32_t last_frame = 0;
365
366   Result_t result = Reader.OpenRead(Options.input_filename);
367
368   if ( ASDCP_SUCCESS(result) )
369     {
370       Reader.FillAudioDescriptor(ADesc);
371       ADesc.EditRate = Rational(1, 1);
372       FrameBuffer.Capacity(PCM::CalcFrameBufferSize(ADesc));
373
374       if ( Options.verbose_flag )
375         PCM::AudioDescriptorDump(ADesc);
376     }
377
378   if ( ASDCP_SUCCESS(result) )
379     {
380       last_frame = ADesc.ContainerDuration;
381
382       if ( Options.duration > 0 && Options.duration < last_frame )
383         last_frame = Options.duration;
384
385       if ( Options.start_frame > 0 )
386         {
387           if ( Options.start_frame > ADesc.ContainerDuration )
388             {
389               fprintf(stderr, "Start value greater than file duration.\n");
390               return RESULT_FAIL;
391             }
392
393           last_frame = Kumu::xmin(Options.start_frame + last_frame, ADesc.ContainerDuration);
394         }
395
396       ADesc.ContainerDuration = last_frame - Options.start_frame;
397       OutWave.OpenWrite(ADesc, Options.file_prefix,
398                         ( Options.split_wav ? WavFileWriter::ST_STEREO : 
399                           ( Options.mono_wav ? WavFileWriter::ST_MONO : WavFileWriter::ST_NONE ) ));
400     }
401
402   if ( ASDCP_SUCCESS(result) && Options.key_flag )
403     {
404       Context = new AESDecContext;
405       result = Context->InitKey(Options.key_value);
406
407       if ( ASDCP_SUCCESS(result) && Options.read_hmac )
408         {
409           WriterInfo Info;
410           Reader.FillWriterInfo(Info);
411
412           if ( Info.UsesHMAC )
413             {
414               HMAC = new HMACContext;
415               result = HMAC->InitKey(Options.key_value, Info.LabelSetType);
416             }
417           else
418             {
419               fputs("File does not contain HMAC values, ignoring -m option.\n", stderr);
420             }
421         }
422     }
423
424   for ( ui32_t i = Options.start_frame; ASDCP_SUCCESS(result) && i < last_frame; i++ )
425     {
426       result = Reader.ReadFrame(i, FrameBuffer, Context, HMAC);
427
428       if ( ASDCP_SUCCESS(result) )
429         {
430           if ( Options.verbose_flag )
431             FrameBuffer.Dump(stderr, Options.fb_dump_size);
432
433           result = OutWave.WriteFrame(FrameBuffer);
434         }
435     }
436
437   return result;
438 }
439
440
441 //
442 int
443 main(int argc, const char** argv)
444 {
445   char     str_buf[64];
446   CommandOptions Options(argc, argv);
447
448   if ( Options.version_flag )
449     banner();
450
451   if ( Options.help_flag )
452     usage();
453
454   if ( Options.version_flag || Options.help_flag )
455     return 0;
456
457   if ( Options.error_flag )
458     {
459       fprintf(stderr, "There was a problem. Type %s -h for help.\n", PROGRAM_NAME);
460       return 3;
461     }
462
463   EssenceType_t EssenceType;
464   Result_t result = ASDCP::EssenceType(Options.input_filename, EssenceType);
465
466   if ( ASDCP_SUCCESS(result) )
467     {
468       switch ( EssenceType )
469         {
470         case ESS_JPEG_2000:
471           result = read_JP2K_file(Options);
472           break;
473
474         case ESS_PCM_24b_48k:
475         case ESS_PCM_24b_96k:
476           result = read_PCM_file(Options);
477           break;
478
479         default:
480           fprintf(stderr, "%s: Unknown file type, not ASDCP essence.\n", Options.input_filename);
481           return 5;
482         }
483     }
484
485   if ( ASDCP_FAILURE(result) )
486     {
487       fputs("Program stopped on error.\n", stderr);
488
489       if ( result == RESULT_SFORMAT )
490         {
491           fputs("Use option '-3' to force stereoscopic mode.\n", stderr);
492         }
493       else if ( result != RESULT_FAIL )
494         {
495           fputs(result, stderr);
496           fputc('\n', stderr);
497         }
498
499       return 1;
500     }
501
502   return 0;
503 }
504
505
506 //
507 // end as-02-unwrap.cpp
508 //