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