94199a7f4b71583ca3aadb90aaa9998787a4669b
[asdcplib.git] / src / klvsplit.cpp
1 /*
2 Copyright (c) 2005-2013, 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    klvwalk.cpp
28     \version $Id$
29     \brief   KLV+MXF test
30 */
31
32 #include "AS_DCP.h"
33 #include "MXF.h"
34 #include <KM_log.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <ctype.h>
38 #include <assert.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41
42 using namespace ASDCP;
43 using Kumu::DefaultLogSink;
44
45
46 //------------------------------------------------------------------------------------------
47 //
48 // command line option parser class
49
50 static const char* PROGRAM_NAME = "essence-scraper";    // program name for messages
51 typedef std::list<std::string> FileList_t;
52
53 // Increment the iterator, test for an additional non-option command line argument.
54 // Causes the caller to return if there are no remaining arguments or if the next
55 // argument begins with '-'.
56 #define TEST_EXTRA_ARG(i,c)    if ( ++i >= argc || argv[(i)][0] == '-' ) \
57                                  { \
58                                    fprintf(stderr, "Argument not found for option -%c.\n", (c)); \
59                                    return; \
60                                  }
61
62 //
63 void
64 banner(FILE* stream = stdout)
65 {
66   fprintf(stream, "\n\
67 %s (asdcplib %s)\n\n\
68 Copyright (c) 2005-2013 John Hurst\n\
69 %s is part of the asdcplib DCP tools package.\n\
70 asdcplib may be copied only under the terms of the license found at\n\
71 the top of every file in the asdcplib distribution kit.\n\n\
72 Specify the -h (help) option for further information about %s\n\n",
73           PROGRAM_NAME, ASDCP::Version(), PROGRAM_NAME, PROGRAM_NAME);
74 }
75
76 //
77 void
78 usage(FILE* stream = stdout)
79 {
80   fprintf(stream, "\
81 USAGE: %s [-l <limit>] [-p <prefix>] [-s <suffix>] [-v] (JPEG2000Essence|\n\
82             MPEG2Essence|WAVEssence|CryptEssence|-u <ul-value>)\n\
83 \n\
84        %s [-h|-help] [-V]\n\
85 \n\
86   -h | -help   - Show help\n\
87   -l <limit>   - Stop processing after <limit> matching packets\n\
88   -p <prefix>  - Use <prefix> to start output filenames (default\n\
89                    uses the input filename minus any extension\n\
90   -s <suffix>  - Append <suffix> to output filenames\n\
91   -u           - Use the given UL to select essence packets\n\
92   -v           - Verbose. Prints informative messages to stderr\n\
93   -V           - Show version information\n\
94 \n\
95   NOTES: o There is no option grouping, all options must be distinct arguments.\n\
96          o All option arguments must be separated from the option by whitespace.\n\
97 \n", PROGRAM_NAME, PROGRAM_NAME);
98 }
99
100 //
101 //
102  class CommandOptions
103  {
104    CommandOptions();
105
106  public:
107    bool   error_flag;               // true if the given options are in error or not complete
108    bool   version_flag;             // true if the version display option was selected
109    bool   help_flag;                // true if the help display option was selected
110    bool   verbose_flag;             // true if the informative messages option was selected
111    ASDCP::UL target_ul;             // a UL value identifying the packets to be extracted
112    ui64_t  extract_limit;           // limit extraction to the given number of packets
113    std::string prefix;              // output filename prefix
114    std::string suffix;              // output filename suffix
115    FileList_t inFileList;           // File to operate on
116
117    CommandOptions(int argc, const char** argv, const ASDCP::Dictionary& dict) :
118      error_flag(true), version_flag(false), help_flag(false),
119      verbose_flag(false), extract_limit(ui64_C(-1))
120    {
121      for ( int i = 1; i < argc; ++i )
122        {
123
124          if ( (strcmp( argv[i], "-help") == 0) )
125            {
126              help_flag = true;
127              continue;
128            }
129          
130          if ( argv[i][0] == '-' && isalpha(argv[i][1]) && argv[i][2] == 0 )
131            {
132              switch ( argv[i][1] )
133                {
134                case 'h': help_flag = true; break;
135
136                case 'l':
137                  TEST_EXTRA_ARG(i, 'l');
138                  extract_limit = abs(strtoll(argv[i], 0, 10));
139                  break;
140
141                case 'p':
142                  TEST_EXTRA_ARG(i, 'p');
143                  prefix = argv[i];
144                  break;
145
146                case 's':
147                  TEST_EXTRA_ARG(i, 's');
148                  suffix = argv[i];
149                  break;
150
151                case 'u':
152                  TEST_EXTRA_ARG(i, 'u');
153
154                  if ( ! target_ul.DecodeHex(argv[i]) )
155                    {
156                      fprintf(stderr, "Error decoding UL: %s\n", argv[i]);
157                      return;
158                    }
159
160                  break;
161
162                case 'V': version_flag = true; break;
163                case 'v': verbose_flag = true; break;
164
165                default:
166                  fprintf(stderr, "Unrecognized option: %s\n", argv[i]);
167                  return;
168                }
169            }
170          else if ( argv[i][0] != '-' )
171            {
172              if ( ! target_ul.HasValue() )
173                {
174                  if ( strncmp(argv[i], "JPEG2000Essence", 15) == 0 )
175                    {
176                      target_ul = dict.ul(MDD_JPEG2000Essence);
177                    }
178                  else if ( strncmp(argv[i], "MPEG2Essence", 12) == 0 )
179                    {
180                      target_ul = dict.ul(MDD_MPEG2Essence);
181                    }
182                  else if ( strncmp(argv[i], "WAVEssence", 10) == 0 )
183                    {
184                      target_ul = dict.ul(MDD_WAVEssence);
185                    }
186                  else
187                    {
188                      inFileList.push_back(argv[i]);
189                    }
190                }
191              else
192                {
193                  inFileList.push_back(argv[i]);
194                }
195            }
196          else
197            {
198              fprintf(stderr, "Unrecognized option: %s\n", argv[i]);
199              return;
200            }
201        }
202
203      if ( help_flag || version_flag )
204        return;
205      
206      if ( inFileList.empty() )
207        {
208          fputs("Input filename(s) required.\n", stderr);
209          return;
210        }
211      
212      if ( ! target_ul.HasValue() )
213        {
214          fputs("Packet UL not set.  Use %s -u <ul> or keyword.\n", stderr);
215          return;
216        }
217
218      error_flag = false;
219    }
220  };
221
222
223 //---------------------------------------------------------------------------------------------------
224 //
225
226 int
227 main(int argc, const char** argv)
228 {
229   const Dictionary *dict = &DefaultCompositeDict();
230
231   CommandOptions Options(argc, argv, *dict);
232
233   if ( Options.version_flag )
234     banner();
235
236   if ( Options.help_flag )
237     usage();
238
239   if ( Options.version_flag || Options.help_flag )
240     return 0;
241
242   if ( Options.error_flag )
243     {
244       fprintf(stderr, "There was a problem. Type %s -h for help.\n", PROGRAM_NAME);
245       return 3;
246     }
247
248   Result_t result = RESULT_OK;
249   FileList_t::iterator fi;
250
251   for ( fi = Options.inFileList.begin(); ASDCP_SUCCESS(result) && fi != Options.inFileList.end(); ++fi )
252     {
253       if ( Options.verbose_flag )
254         fprintf(stderr, "Opening file %s\n", (fi->c_str()));
255       
256       std::string this_prefix =  Options.prefix.empty() ? Kumu::PathSetExtension(*fi, "") + "_" : Options.prefix;
257       Kumu::FileReader reader;
258       KLVFilePacket packet;
259       char filename_buf[1024], buf1[64], buf2[64];
260       ui64_t item_counter = 0;
261
262       result = reader.OpenRead(fi->c_str());
263           
264       if ( KM_SUCCESS(result) )
265         result = packet.InitFromFile(reader);
266           
267       while ( KM_SUCCESS(result) && item_counter < Options.extract_limit )
268         {
269           if ( packet.GetUL() == Options.target_ul
270                || packet.GetUL().MatchIgnoreStream(Options.target_ul) )
271             {
272               snprintf(filename_buf, 1024, "%s%010qu%s", this_prefix.c_str(), item_counter, Options.suffix.c_str());
273
274               if ( Options.verbose_flag )
275                 fprintf(stderr, "%s (%d bytes)\n", filename_buf, packet.ValueLength());
276
277               Kumu::FileWriter writer;
278               writer.OpenWrite(filename_buf);
279
280               if ( KM_SUCCESS(result) )
281                 {
282                   result = writer.Write(packet.m_Buffer.RoData() + packet.KLLength(), packet.ValueLength());
283                   ++item_counter;
284                 }
285             }
286
287           if ( KM_SUCCESS(result) )
288             result = packet.InitFromFile(reader);
289         }
290           
291       if ( result == RESULT_ENDOFFILE )
292         result = RESULT_OK;
293     }
294
295   if ( ASDCP_FAILURE(result) )
296     {
297       fputs("Program stopped on error.\n", stderr);
298       
299       if ( result != RESULT_FAIL )
300         {
301           fputs(result, stderr);
302           fputc('\n', stderr);
303         }
304       
305       return 1;
306     }
307   
308   return 0;
309 }
310
311
312 //
313 // end klvwalk.cpp
314 //