STYLE: Add a lot of comments for the CMake build system
[openjpeg.git] / mj2 / extract_j2k_from_mj2.c
1 #include <stdio.h>
2 #include <malloc.h>
3 #include <setjmp.h>
4
5 #include "mj2.h"
6
7 //MEMORY LEAK
8 #ifdef _DEBUG
9 #define _CRTDBG_MAP_ALLOC
10 #include <stdlib.h>  // Must be included first
11 #include <crtdbg.h>
12 #endif
13 //MEM
14
15 jmp_buf j2k_error;
16
17 int main(int argc, char *argv[]) {
18
19   int tnum;
20   unsigned int snum;
21   mj2_movie_t movie;
22   mj2_tk_t *track;
23   mj2_sample_t *sample;
24   unsigned char* frame_codestream;
25   FILE *file, *outfile;
26   char outfilename[50];
27
28   if (argc != 3) {
29     printf("Bad syntax: Usage: MJ2_extractor mj2filename output_location\n"); 
30     printf("Example: MJ2_extractor foreman.mj2 output/foreman\n");
31     return 1;
32   }
33   
34   file = fopen(argv[1], "rb");
35   
36   if (!file) {
37     fprintf(stderr, "failed to open %s for reading\n", argv[1]);
38     return 1;
39   }
40
41   if (mj2_read_struct(file, &movie)) // Creating the movie structure
42     return 1;
43
44   // Decode first video track 
45   tnum = 0;
46   while (movie.tk[tnum].track_type != 0)
47     tnum ++;
48
49   track = &movie.tk[tnum];
50
51   fprintf(stdout,"Extracting %d frames from file...\n",track->num_samples);
52
53   for (snum=0; snum < track->num_samples; snum++)
54   {
55     sample = &track->sample[snum];
56     frame_codestream = (unsigned char*) malloc (sample->sample_size-8); // Skipping JP2C marker
57     fseek(file,sample->offset+8,SEEK_SET);
58     fread(frame_codestream,sample->sample_size-8,1, file);  // Assuming that jp and ftyp markers size do
59
60     sprintf(outfilename,"%s_%d.j2k",argv[2],snum);
61     outfile = fopen(outfilename, "wb");
62     if (!outfile) {
63       fprintf(stderr, "failed to open %s for writing\n",outfilename);
64       return 1;
65     }
66     fwrite(frame_codestream,sample->sample_size-8,1,outfile);
67     fclose(outfile);
68     free(frame_codestream);
69     }
70   fclose(file);
71   fprintf(stdout, "%d frames correctly extracted\n", snum);
72   mj2_memory_free(&movie);
73
74   //MEMORY LEAK
75   #ifdef _DEBUG
76     _CrtDumpMemoryLeaks();
77   #endif
78   //MEM
79
80   return 0;
81 }