2.5.11.
[asdcplib-cth.git] / src / klvwalk.cpp
1 /*
2 Copyright (c) 2005-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    klvwalk.cpp
28     \version $Id: klvwalk.cpp,v 1.23 2015/10/09 23:41:11 jhurst Exp $
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 = "klvwalk";    // 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 [-r|-p] [-v] <input-file> [<input-file2> ...]\n\
82 \n\
83        %s [-h|-help] [-V]\n\
84 \n\
85   -h | -help   - Show help\n\
86   -r           - When KLV data is an MXF OPAtom or OP 1a file, display headers\n\
87   -p           - Display partition headers by walking the RIP\n\
88   -v           - Verbose. Prints informative messages to stderr\n\
89   -V           - Show version information\n\
90 \n\
91   NOTES: o There is no option grouping, all options must be distinct arguments.\n\
92          o All option arguments must be separated from the option by whitespace.\n\
93 \n", PROGRAM_NAME, PROGRAM_NAME);
94 }
95
96 //
97 //
98  class CommandOptions
99  {
100    CommandOptions();
101
102  public:
103    bool   error_flag;               // true if the given options are in error or not complete
104    bool   version_flag;             // true if the version display option was selected
105    bool   help_flag;                // true if the help display option was selected
106    bool   verbose_flag;             // true if the informative messages option was selected
107    bool   read_mxf_flag;            // true if the -r option was selected
108    bool   walk_parts_flag;          // true if the -p option was selected
109    FileList_t inFileList;           // File to operate on
110
111    CommandOptions(int argc, const char** argv) :
112      error_flag(true), version_flag(false), help_flag(false),
113      verbose_flag(false), read_mxf_flag(false), walk_parts_flag(false)
114    {
115      for ( int i = 1; i < argc; i++ )
116        {
117
118          if ( (strcmp( argv[i], "-help") == 0) )
119            {
120              help_flag = true;
121              continue;
122            }
123          
124          if ( argv[i][0] == '-' && isalpha(argv[i][1]) && argv[i][2] == 0 )
125            {
126              switch ( argv[i][1] )
127                {
128                case 'h': help_flag = true; break;
129                case 'r': read_mxf_flag = true; break;
130                case 'p': walk_parts_flag = true; break;
131                case 'V': version_flag = true; break;
132                case 'v': verbose_flag = true; break;
133
134                default:
135                  fprintf(stderr, "Unrecognized option: %s\n", argv[i]);
136                  return;
137                }
138            }
139          else
140            {
141              if ( argv[i][0] != '-' )
142                inFileList.push_back(argv[i]);
143
144              else
145                {
146                  fprintf(stderr, "Unrecognized option: %s\n", argv[i]);
147                  return;
148                }
149            }
150        }
151
152      if ( help_flag || version_flag )
153        return;
154      
155      if ( inFileList.empty() )
156        {
157          fputs("Input filename(s) required.\n", stderr);
158          return;
159        }
160      
161      error_flag = false;
162    }
163  };
164
165
166 //---------------------------------------------------------------------------------------------------
167 //
168
169 int
170 main(int argc, const char** argv)
171 {
172   CommandOptions Options(argc, argv);
173
174   if ( Options.version_flag )
175     banner();
176
177   if ( Options.help_flag )
178     usage();
179
180   if ( Options.version_flag || Options.help_flag )
181     return 0;
182
183   if ( Options.error_flag )
184     {
185       fprintf(stderr, "There was a problem. Type %s -h for help.\n", PROGRAM_NAME);
186       return 3;
187     }
188
189   FileList_t::iterator fi;
190   Result_t result = RESULT_OK;
191
192   for ( fi = Options.inFileList.begin(); ASDCP_SUCCESS(result) && fi != Options.inFileList.end(); fi++ )
193     {
194       if (Options.verbose_flag)
195         fprintf(stderr, "Opening file %s\n", ((*fi).c_str()));
196       
197       if ( Options.read_mxf_flag ) // dump MXF
198         {
199           Kumu::FileReader        Reader;
200           const Dictionary* Dict = &DefaultCompositeDict();
201           ASDCP::MXF::OP1aHeader Header(Dict);
202           ASDCP::MXF::RIP RIP(Dict);
203           
204           result = Reader.OpenRead((*fi).c_str());
205           
206           if ( ASDCP_SUCCESS(result) )
207             result = MXF::SeekToRIP(Reader);
208
209           if ( ASDCP_SUCCESS(result) )
210             {
211               result = RIP.InitFromFile(Reader);
212               ui32_t test_s = RIP.PairArray.size();
213
214               if ( ASDCP_FAILURE(result) )
215                 {
216                   DefaultLogSink().Error("File contains no RIP\n");
217                   result = RESULT_OK;
218                 }
219               else if ( RIP.PairArray.empty() )
220                 {
221                   DefaultLogSink().Error("RIP contains no Pairs.\n");
222                 }
223
224               Reader.Seek(0);
225             }
226           else
227             {
228               DefaultLogSink().Error("read_mxf SeekToRIP failed: %s\n", result.Label());
229             }
230
231           if ( ASDCP_SUCCESS(result) )
232             result = Header.InitFromFile(Reader);
233           
234           if ( ASDCP_SUCCESS(result) )
235             Header.Dump(stdout);
236           
237           if ( ASDCP_SUCCESS(result) && RIP.PairArray.size() > 2 )
238             {
239               MXF::RIP::const_pair_iterator pi = RIP.PairArray.begin();
240
241               for ( pi++; pi != RIP.PairArray.end() && ASDCP_SUCCESS(result); pi++ )
242                 {
243                   result = Reader.Seek((*pi).ByteOffset);
244
245                   if ( ASDCP_SUCCESS(result) )
246                     {
247                       MXF::Partition TmpPart(Dict);
248                       result = TmpPart.InitFromFile(Reader);
249
250                       if ( ASDCP_SUCCESS(result) && TmpPart.BodySID > 0 )
251                         TmpPart.Dump(stdout);
252                     }
253                 }
254             }
255
256           if ( ASDCP_SUCCESS(result) )
257             {
258               ASDCP::MXF::OPAtomIndexFooter Index(Dict);
259               result = Reader.Seek(Header.FooterPartition);
260               
261               if ( ASDCP_SUCCESS(result) )
262                 {
263                   Index.m_Lookup = &Header.m_Primer;
264                   result = Index.InitFromFile(Reader);
265                 }
266               
267               if ( ASDCP_SUCCESS(result) )
268                 Index.Dump(stdout);
269             }
270
271           if ( ASDCP_SUCCESS(result) )
272             RIP.Dump(stdout);
273         }
274       else if ( Options.walk_parts_flag )
275         {
276           Kumu::FileReader        Reader;
277           const Dictionary* Dict = &DefaultCompositeDict();
278           ASDCP::MXF::OP1aHeader Header(Dict);
279           ASDCP::MXF::RIP RIP(Dict);
280           
281           result = Reader.OpenRead((*fi).c_str());
282           
283           if ( ASDCP_SUCCESS(result) )
284             result = MXF::SeekToRIP(Reader);
285
286           if ( ASDCP_SUCCESS(result) )
287             {
288               result = RIP.InitFromFile(Reader);
289               ui32_t test_s = RIP.PairArray.size();
290
291               if ( ASDCP_FAILURE(result) )
292                 {
293                   DefaultLogSink().Error("File contains no RIP\n");
294                   result = RESULT_OK;
295                 }
296               else if ( RIP.PairArray.empty() )
297                 {
298                   DefaultLogSink().Error("RIP contains no Pairs.\n");
299                 }
300
301               Reader.Seek(0);
302             }
303           else
304             {
305               DefaultLogSink().Error("walk_parts SeekToRIP failed: %s\n", result.Label());
306             }
307
308           if ( ASDCP_SUCCESS(result) )
309             {
310               RIP.Dump();
311
312               MXF::RIP::const_pair_iterator i;
313               for ( i = RIP.PairArray.begin(); i != RIP.PairArray.end(); ++i )
314                 {
315                   Reader.Seek(i->ByteOffset);
316                   MXF::Partition plain_part(Dict);
317                   plain_part.InitFromFile(Reader);
318
319                   if ( plain_part.ThisPartition != i->ByteOffset )
320                     {
321                       DefaultLogSink().Error("ThisPartition value error: wanted=%qu, got=%qu\n",
322                                              plain_part.ThisPartition, i->ByteOffset);
323                     }
324
325                   plain_part.Dump();
326                 }
327             }
328         }
329       else // dump klv
330         {
331           Kumu::FileReader Reader;
332           KLVFilePacket KP;
333           ui64_t pos = 0;
334
335           result = Reader.OpenRead((*fi).c_str());
336           
337           if ( ASDCP_SUCCESS(result) )
338             result = KP.InitFromFile(Reader);
339           
340           while ( ASDCP_SUCCESS(result) )
341             {
342               fprintf(stdout, "@0x%08qx: ", pos);
343               KP.Dump(stdout, DefaultCompositeDict(), true);
344               pos = Reader.Tell();
345               result = KP.InitFromFile(Reader);
346             }
347           
348           if( result == RESULT_ENDOFFILE )
349             result = RESULT_OK;
350         }
351     }
352
353   if ( ASDCP_FAILURE(result) )
354     {
355       fputs("Program stopped on error.\n", stderr);
356       
357       if ( result != RESULT_FAIL )
358         {
359           fputs(result, stderr);
360           fputc('\n', stderr);
361         }
362       
363       return 1;
364     }
365   
366   return 0;
367 }
368
369
370 //
371 // end klvwalk.cpp
372 //