Light modifications
[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   mj2_init_stdmovie(&movie);
45
46   // Decode first video track 
47   tnum = 0;
48   while (movie.tk[tnum].track_type != 0)
49     tnum ++;
50
51   track = &movie.tk[tnum];
52
53   fprintf(stdout,"Extracting %d frames from file...\n",track->num_samples);
54
55   for (snum=0; snum < track->num_samples; snum++)
56   {
57     sample = &track->sample[snum];
58     frame_codestream = (unsigned char*) malloc (sample->sample_size-8); // Skipping JP2C marker
59     fseek(file,sample->offset+8,SEEK_SET);
60     fread(frame_codestream,sample->sample_size-8,1, file);  // Assuming that jp and ftyp markers size do
61
62     sprintf(outfilename,"%s_%d.j2k",argv[2],snum);
63     outfile = fopen(outfilename, "wb");
64     if (!outfile) {
65       fprintf(stderr, "failed to open %s for writing\n",outfilename);
66       return 1;
67     }
68     fwrite(frame_codestream,sample->sample_size-8,1,outfile);
69     fclose(outfile);
70     free(frame_codestream);
71     }
72   fclose(file);
73   fprintf(stdout, "%d frames correctly extracted\n", snum);
74   mj2_memory_free(&movie);
75
76   //MEMORY LEAK
77   #ifdef _DEBUG
78     _CrtDumpMemoryLeaks();
79   #endif
80   //MEM
81
82   return 0;
83 }