This tool extracts J2K codestreams from a MJ2 file (designed to
[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   unsigned int tnum, snum;
20   mj2_movie_t movie;
21   mj2_tk_t *track;
22   mj2_sample_t *sample;
23   unsigned char* frame_codestream;
24   FILE *file, *outfile;
25   char outfilename[50];
26
27   if (argc != 3) {
28     printf("Bad syntax: Usage: MJ2_extractor mj2filename output_location\n"); 
29     printf("Example: MJ2_extractor foreman.mj2 output/foreman\n");
30     return 1;
31   }
32   
33   file = fopen(argv[1], "rb");
34   
35   if (!file) {
36     fprintf(stderr, "failed to open %s for reading\n", argv[1]);
37     return 1;
38   }
39
40   if (mj2_read_struct(file, &movie)) // Creating the movie structure
41     return 1;
42
43   // Decode first video track 
44   tnum = 0;
45   while (movie.tk[tnum].track_type != 0)
46     tnum ++;
47
48   track = &movie.tk[tnum];
49
50   fprintf(stdout,"Extracting %d frames from file...\n",track->num_samples);
51
52   for (snum=0; snum < track->num_samples; snum++)
53   {
54     sample = &track->sample[snum];
55     frame_codestream = (unsigned char*) malloc (sample->sample_size-8); // Skipping JP2C marker
56     fseek(file,sample->offset+8,SEEK_SET);
57     fread(frame_codestream,sample->sample_size-8,1, file);  // Assuming that jp and ftyp markers size do
58
59     sprintf(outfilename,"%s_%d.j2k",argv[2],snum);
60     outfile = fopen(outfilename, "wb");
61     if (!outfile) {
62       fprintf(stderr, "failed to open %s for writing\n",outfilename);
63       return 1;
64     }
65     fwrite(frame_codestream,sample->sample_size-8,1,outfile);
66     fclose(outfile);
67     free(frame_codestream);
68     }
69   fclose(file);
70   fprintf(stdout, "%d frames correctly extracted\n", snum);
71   mj2_memory_free(&movie);
72
73   //MEMORY LEAK
74   #ifdef _DEBUG
75     _CrtDumpMemoryLeaks();
76   #endif
77   //MEM
78
79   return 0;
80 }