Ejemplo n.º 1
0
int handle_decode(char **argv, Images &images, int quality, int scale) {
    char *ext = strrchr(argv[1],'.');
    if (!check_compatible_extension(ext)) {
        e_printf("Error: expected \".png\", \".pnm\" or \".pam\" file name extension for output file\n");
        return 1;
    }
    if (!decode_flif(argv, images, quality, scale)) {e_printf("Error: could not decode FLIF file\n"); return 3; }
    if (scale>1)
        v_printf(3,"Downscaling output: %ux%u -> %ux%u\n",images[0].cols(),images[0].rows(),images[0].cols()/scale,images[0].rows()/scale);
    if (images.size() == 1) {
        if (!images[0].save(argv[1],scale)) return 2;
    } else {
        int counter=0;
        std::vector<char> vfilename(strlen(argv[1])+6);
        char *filename = &vfilename[0];
        strcpy(filename,argv[1]);
        char *a_ext = strrchr(filename,'.');
        for (Image& image : images) {
            sprintf(a_ext,"-%03d%s",counter++,ext);
            if (!image.save(filename,scale)) return 2;
            v_printf(2,"    (%i/%i)         \r",counter,(int)images.size()); v_printf(4,"\n");
        }
    }
    v_printf(2,"\n");
    return 0;
}
Ejemplo n.º 2
0
/*
 * Return address of the stub function is passed into eip
 */
static int m_munprotect(unsigned int addr, unsigned int len, unsigned char *eip)
{
	if (debug_level('e')>3) e_printf("\tM_MUNPROT %08x:%p [%08x]\n",
		addr,eip,*((int *)(eip-3)));
	/* verify that data, not code, has been hit */
	if (!e_querymark(addr, len))
	    return e_check_munprotect(addr, len);
	/* Oops.. we hit code, maybe the stub was set up before that
	 * code was parsed. Ok, undo the patch and clear that code */
	if (debug_level('e')>1)
	    e_printf("CODE %08x hit in DATA %p patch\n",addr,eip);
/*	if (UnCpatch((void *)(eip-3))) leavedos_main(0); */
	InvalidateNodePage(addr,len,eip,NULL);
	return e_check_munprotect(addr, len);
}
Ejemplo n.º 3
0
    bool read_subtree(int pos, Ranges &subrange, Tree &tree) {
        PropertyDecisionNode &n = tree[pos];
        int p = n.property = coder.read_int(0,nb_properties)-1;

        if (p != -1) {
            int oldmin = subrange[p].first;
            int oldmax = subrange[p].second;
            if (oldmin >= oldmax) {
              e_printf( "Invalid tree. Aborting tree decoding.\n");
              return false;
            }
            n.count = coder.read_int(CONTEXT_TREE_MIN_COUNT, CONTEXT_TREE_MAX_COUNT); // * CONTEXT_TREE_COUNT_QUANTIZATION;
            assert(oldmin < oldmax);
            int splitval = n.splitval = coder.read_int(oldmin, oldmax-1);
            int childID = n.childID = tree.size();
//            e_printf( "Pos %i: prop %i splitval %i in [%i..%i]\n", pos, n.property, splitval, oldmin, oldmax-1);
            tree.push_back(PropertyDecisionNode());
            tree.push_back(PropertyDecisionNode());
            // > splitval
            subrange[p].first = splitval+1;
            if (!read_subtree(childID, subrange, tree)) return false;

            // <= splitval
            subrange[p].first = oldmin;
            subrange[p].second = splitval;
            if (!read_subtree(childID+1, subrange, tree)) return false;

            subrange[p].second = oldmax;
        }
        return true;
    }
Ejemplo n.º 4
0
 void snap(const int p, const prevPlanes &pp, ColorVal &minv, ColorVal &maxv, ColorVal &v) const {
     const ColorBucket& b = bucket(p,pp);
     minv=b.min;
     maxv=b.max;
     if (b.min > b.max) { assert(false); e_printf("Corruption detected!\n"); exit(4); } // this should only happen on malicious input files
     v=b.snapColor(v);
 }
Ejemplo n.º 5
0
void e_priv_iopl(int pl)
{
    pl &= 3;
    TheCPU.eflags = (TheCPU.eflags & ~EFLAGS_IOPL) |
	(pl << 12);
    e_printf("eIOPL: set IOPL to %d, flags=%#x\n",pl,TheCPU.eflags);
}
Ejemplo n.º 6
0
bool Image::load(const char *filename)
{
    const char *f = strrchr(filename,'/');
    const char *ext = f ? strrchr(f,'.') : strrchr(filename,'.');
    v_printf(2,"Loading input file: %s  ",filename);
    if (ext && !strcasecmp(ext,".png")) {
        return !image_load_png(filename,*this);
    }
    if (ext && !strcasecmp(ext,".pnm")) {
        return image_load_pnm(filename,*this);
    }
    if (ext && !strcasecmp(ext,".pbm")) {
        return image_load_pnm(filename,*this);
    }
    if (ext && !strcasecmp(ext,".pgm")) {
        return image_load_pnm(filename,*this);
    }
    if (ext && !strcasecmp(ext,".ppm")) {
        return image_load_pnm(filename,*this);
    }
    if (ext && !strcasecmp(ext,".pam")) {
        return image_load_pam(filename,*this);
    }
    if (ext && !strcasecmp(ext,".rggb")) {
        return image_load_rggb(filename,*this);
    }
    if (image_load_pnm(filename,*this) || !image_load_png(filename,*this)) return true;
    e_printf("ERROR: Unknown input file type to read from: %s\n",ext ? ext : "(none)");
    return false;
}
Ejemplo n.º 7
0
bool Image::save(const char *filename) const
{
    const char *f = strrchr(filename,'/');
    const char *ext = f ? strrchr(f,'.') : strrchr(filename,'.');
    v_printf(2,"Saving output file: %s  ",filename);
    if (ext && !strcasecmp(ext,".png")) {
        return !image_save_png(filename,*this);
    }
    if (ext && !strcasecmp(ext,".pnm")) {
        return image_save_pnm(filename,*this);
    }
    if (ext && !strcasecmp(ext,".pgm")) {
        return image_save_pnm(filename,*this);
    }
    if (ext && !strcasecmp(ext,".ppm")) {
        return image_save_pnm(filename,*this);
    }
    if (ext && !strcasecmp(ext,".pam")) {
        return image_save_pam(filename,*this);
    }
    if (ext && !strcasecmp(ext,".rggb")) {
        return image_save_rggb(filename,*this);
    }
    e_printf("ERROR: Unknown extension to write to: %s\n",ext ? ext : "(none)");
    return false;
}
Ejemplo n.º 8
0
Archivo: pipe_hd.c Proyecto: emon/emon
static ssize_t
pipe_blocked_read_header(int fd, void *hd)
{
	if (fd_read_ignoreEOF(fd, hd, PIPE_HEADER_LEN) != PIPE_HEADER_LEN) {
		e_printf("Can't read EMON message header.\n");
		return PIPE_ERROR;
	}
	if(pipe_get_version(hd)!=1) {
		e_printf("Unavailable EMON message version %d.\n",pipe_get_version(hd));
		return PIPE_ERROR;
	}
	if(pipe_get_length(hd)==END_FLAG) {
		return PIPE_END;
	}
	return PIPE_HEADER_LEN;
}
Ejemplo n.º 9
0
/*
 * Return address of the stub function is passed into eip
 */
static void m_munprotect(unsigned int addr, unsigned int len, unsigned char *eip)
{
	if (debug_level('e')>3) e_printf("\tM_MUNPROT %08x:%p [%08x]\n",
		addr,eip,*((int *)(eip-3)));
	/* if only data in aliased low memory is hit, nothing to do */
	if (LINEAR2UNIX(addr) != MEM_BASE32(addr) && !e_querymark(addr, len))
		return;
	/* Always unprotect and clear all code in the pages
	 * for either DPMI data or code.
	 * Maybe the stub was set up before that code was parsed.
	 * Clear that code */
	if (debug_level('e')>1 && e_querymark(addr, len))
	    e_printf("CODE %08x hit in DATA %p patch\n",addr,eip);
/*	if (UnCpatch((void *)(eip-3))) leavedos_main(0); */
	InvalidateNodePage(addr,len,eip,NULL);
	e_resetpagemarks(addr,len);
	e_munprotect(addr,len);
}
Ejemplo n.º 10
0
bool ioget_int_8bit (IO& io, int* result)
{
    int c = io.getc();
    if (c == io.EOS) {
        e_printf ("Unexpected EOS");
        return false;
    }

    *result = c;
    return true;
}
Ejemplo n.º 11
0
 const ColorRanges *meta(Images& images, const ColorRanges *srcRanges) {
     if (max_lookback >= (int)images.size()) { e_printf("Bad value for FRA lookback\n"); exit(4);}
     was_grayscale = srcRanges->numPlanes() < 2;
     was_flat = srcRanges->numPlanes() < 4;
     for (unsigned int fr=0; fr<images.size(); fr++) {
         Image& image = images[fr];
         image.ensure_frame_lookbacks();
     }
     int lookback = (int)images.size()-1;
     if (lookback > max_lookback) lookback=max_lookback;
     return new ColorRangesFC(lookback, (srcRanges->numPlanes() == 4 ? srcRanges->min(3) : 255), (srcRanges->numPlanes() == 4 ? srcRanges->max(3) : 255), srcRanges);
 }
Ejemplo n.º 12
0
 bool load(const ColorRanges *, RacIn<IO> &rac) {
     SimpleSymbolCoder<FLIFBitChanceMeta, RacIn<IO>, 18> coder(rac);
     for (unsigned int i=0; i<nb; i+=1) {b.push_back(coder.read_int(0,cols));}
     for (unsigned int i=0; i<nb; i+=1) {
         e.push_back(cols-coder.read_int(0,cols-b[i]));
         if (e[i] > cols || e[i] < b[i] || e[i] <= 0) {
             e_printf("\nError: FRS transform: invalid end column\n");
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 13
0
bool encode_load_input_images(int argc, char **argv, Images &images) {
    int nb_input_images = argc-1;
    while(argc>1) {
        Image image;
        v_printf(2,"\r");
        if (!image.load(argv[0])) {
            e_printf("Could not read input file: %s\n", argv[0]);
            return false;
        };
        images.push_back(std::move(image));
        Image& last_image = images.back();
        if (last_image.rows() != images[0].rows() || last_image.cols() != images[0].cols()) {
            e_printf("Dimensions of all input images should be the same!\n");
            e_printf("  First image is %ux%u\n",images[0].cols(),images[0].rows());
            e_printf("  This image is %ux%u: %s\n",last_image.cols(),last_image.rows(),argv[0]);
            return false;
        }
        if (last_image.numPlanes() < images[0].numPlanes()) {
            if (images[0].numPlanes() == 3) last_image.ensure_chroma();
            else if (images[0].numPlanes() == 4) last_image.ensure_alpha();
            else { e_printf("Problem while loading input images, please report this.\n"); return false; }
        } else if (last_image.numPlanes() > images[0].numPlanes()) {
            if (last_image.numPlanes() == 3) { for (Image& i : images) i.ensure_chroma(); }
            else if (last_image.numPlanes() == 4) { for (Image& i : images) i.ensure_alpha(); }
            else { e_printf("Problem while loading input images, please report this.\n"); return false; }
        }
        argc--; argv++;
        if (nb_input_images>1) {v_printf(2,"    (%i/%i)         ",(int)images.size(),nb_input_images); v_printf(4,"\n");}
    }
    v_printf(2,"\n");
    return true;
}
Ejemplo n.º 14
0
int
main(int argc, char *argv[])
{
	opt_t OPT;

	if (opt_etc(argc, argv, &OPT) < 0){
		return -1;
	}
	if ((OPT.clock % OPT.freq) != 0){
		e_printf("Frames per sec(=clock/freq) must be integar.\n");
		return -1;
	}
	if (isatty(STDOUT)) {
		e_printf("Standard output must be binded with pipe.\n");
		return -1;
	}
	capt_init(&OPT);
	capt_capt(&OPT);
	capt_end(&OPT);

	return 0;
}
Ejemplo n.º 15
0
bool encode_load_input_images(int argc, char **argv, Images &images) {
    int nb_input_images = argc-1;
    while(argc>1) {
        Image image;
        v_printf(2,"\r");
        if (!image.load(argv[0])) {
            e_printf("Could not read input file: %s\n", argv[0]);
            return false;
        };
        images.push_back(std::move(image));
        const Image& last_image = images.back();
        if (last_image.rows() != images[0].rows() || last_image.cols() != images[0].cols() || last_image.numPlanes() != images[0].numPlanes()) {
            e_printf("Dimensions of all input images should be the same!\n");
            e_printf("  First image is %ux%u, %i channels.\n",images[0].cols(),images[0].rows(),images[0].numPlanes());
            e_printf("  This image is %ux%u, %i channels: %s\n",last_image.cols(),last_image.rows(),last_image.numPlanes(),argv[0]);
            return false;
        }
        argc--; argv++;
        if (nb_input_images>1) {v_printf(2,"    (%i/%i)         ",(int)images.size(),nb_input_images); v_printf(4,"\n");}
    }
    v_printf(2,"\n");
    return true;
}
Ejemplo n.º 16
0
int handle_decode(int argc, char **argv, Images &images, int quality, int scale, int resize_width, int resize_height) {
    if (scale < 0) {
        // just identify the file(s), don't actually decode
        while (argc>0) {
            decode_flif(argv, images, quality, scale, resize_width, resize_height);
            argv++; argc--;
        }
        return 0;
    }
    char *ext = strrchr(argv[1],'.');
    if (!check_compatible_extension(ext) && strcmp(argv[1],"null:")) {
        e_printf("Error: expected \".png\", \".pnm\" or \".pam\" file name extension for output file\n");
        return 1;
    }
    if (!decode_flif(argv, images, quality, scale, resize_width, resize_height)) {
        e_printf("Error: could not decode FLIF file\n"); return 3;
    }
    if (!strcmp(argv[1],"null:")) return 0;
//    if (scale>1)
//        v_printf(3,"Downscaling output: %ux%u -> %ux%u\n",images[0].cols(),images[0].rows(),images[0].cols()/scale,images[0].rows()/scale);
    if (images.size() == 1) {
        if (!images[0].save(argv[1])) return 2;
    } else {
        int counter=0;
        std::vector<char> vfilename(strlen(argv[1])+6);
        char *filename = &vfilename[0];
        strcpy(filename,argv[1]);
        char *a_ext = strrchr(filename,'.');
        for (Image& image : images) {
            sprintf(a_ext,"-%03d%s",counter++,ext);
            if (!image.save(filename)) return 2;
            v_printf(2,"    (%i/%i)         \r",counter,(int)images.size()); v_printf(4,"\n");
        }
    }
    v_printf(2,"\n");
    return 0;
}
Ejemplo n.º 17
0
Archivo: image.hpp Proyecto: kif/FLIF
    bool init(uint32_t w, uint32_t h, ColorVal min, ColorVal max, int p) {
      width = w;
      height = h;
      minval = min;
      maxval = max;
      col_begin.clear();
      col_begin.resize(height,0);
      col_end.clear();
      col_end.resize(height,width);
      num = p;
      seen_before = -1;
#ifdef SUPPORT_HDR
      if (max < 256) depth=8; else depth=16;
#else
      assert(max<256);
#endif
      frame_delay=0;
      palette=false;
      assert(min == 0);
      assert(max < (1<<depth));
      assert(p <= 4);
      for (int i=0; i<4; i++) constant[i] = false;
      clear();
      try {
      if (depth <= 8) {
        if (p>0) plane_8_1 = make_unique<Plane<ColorVal_intern_8>>(width, height); // R,Y
        if (p>1) plane_16_1 = make_unique<Plane<ColorVal_intern_16>>(width, height); // G,I
        if (p>2) plane_16_2 = make_unique<Plane<ColorVal_intern_16>>(width, height); // B,Q
        if (p>3) plane_8_2 = make_unique<Plane<ColorVal_intern_8>>(width, height); // A
#ifdef SUPPORT_HDR
      } else {
        if (p>0) plane_16_1 = make_unique<Plane<ColorVal_intern_16>>(width, height); // R,Y
        if (p>1) plane_32_1 = make_unique<Plane<ColorVal_intern_32>>(width, height); // G,I
        if (p>2) plane_32_2 = make_unique<Plane<ColorVal_intern_32>>(width, height); // B,Q
        if (p>3) plane_16_2 = make_unique<Plane<ColorVal_intern_16>>(width, height); // A
#endif
      }
      if (p>4) plane_frame_lookbacks = make_unique<Plane<ColorVal_intern_8>>(width, height); // A
      }
      catch (std::bad_alloc& ba) {
        e_printf("Error: could not allocate enough memory for image data.\n");
        return false;
      }
      return true;
    }
Ejemplo n.º 18
0
 bool load(const ColorRanges *srcRanges, RacIn<IO> &rac) override {
     SimpleSymbolCoder<SimpleBitChance, RacIn<IO>, 18> coder(rac);
     subtract = coder.read_int2(0, 1);
     if (subtract) v_printf(4,"Subtract");
     bool from[4] = {false, false, false, false}, to[4] = {false, false, false, false};
     for (int p=0; p<srcRanges->numPlanes(); p++) {
         permutation[p] = coder.read_int2(0, srcRanges->numPlanes()-1);
         v_printf(5,"[%i->%i]",p,permutation[p]);
         from[p] = true;
         to[permutation[p]] = true;
     }
     for (int p=0; p<srcRanges->numPlanes(); p++) {
         if (!from[p] || !to[p]) {
             e_printf("\nNot a valid permutation!\n");
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 19
0
int main(int argc, char **argv)
{
    Images images;
#ifdef HAS_ENCODER
    int mode = 0; // 0 = encode, 1 = decode, 2 = transcode
    flifEncodingOptional method;
    int learn_repeats = -1;
    int acb = -1; // try auto color buckets
    int frame_delay = 100;
    int palette_size = 512;
    int lookback = 1;
#else
    int mode = 1;
#endif
    int quality = 100; // 100 = everything, positive value: partial decode, negative value: only rough data
    int scale = 1;
    if (strcmp(argv[0],"flif") == 0) mode = 0;
    if (strcmp(argv[0],"dflif") == 0) mode = 1;
    if (strcmp(argv[0],"deflif") == 0) mode = 1;
    if (strcmp(argv[0],"decflif") == 0) mode = 1;
    static struct option optlist[] = {
        {"help", 0, NULL, 'h'},
        {"decode", 0, NULL, 'd'},
        {"verbose", 0, NULL, 'v'},
        {"quality", 1, NULL, 'q'},
        {"scale", 1, NULL, 's'},
#ifdef HAS_ENCODER
        {"encode", 0, NULL, 'e'},
        {"transcode", 0, NULL, 't'},
        {"interlace", 0, NULL, 'i'},
        {"no-interlace", 0, NULL, 'n'},
        {"acb", 0, NULL, 'a'},
        {"no-acb", 0, NULL, 'b'},
        {"palette", 1, NULL, 'p'},
        {"repeats", 1, NULL, 'r'},
        {"frame-delay", 1, NULL, 'f'},
        {"lookback", 1, NULL, 'l'},
#endif
        {0, 0, 0, 0}
    };
    int i,c;
#ifdef HAS_ENCODER
    while ((c = getopt_long (argc, argv, "hedtvinabq:s:p:r:f:l:", optlist, &i)) != -1) {
#else
    while ((c = getopt_long (argc, argv, "hdvq:s:", optlist, &i)) != -1) {
#endif
        switch (c) {
        case 'd': mode=1; break;
        case 'v': increase_verbosity(); break;
        case 'q': quality=atoi(optarg);
                  if (quality < 0 || quality > 100) {e_printf("Not a sensible number for option -q\n"); return 1; }
                  break;
        case 's': scale=atoi(optarg);
                  if (scale < 1 || scale > 128) {e_printf("Not a sensible number for option -s\n"); return 1; }
                  break;
#ifdef HAS_ENCODER
        case 'e': mode=0; break;
        case 't': mode=2; break;
        case 'i': method.encoding=flifEncoding::interlaced; break;
        case 'n': method.encoding=flifEncoding::nonInterlaced; break;
        case 'a': acb=1; break;
        case 'b': acb=0; break;
        case 'p': palette_size=atoi(optarg);
                  if (palette_size < -1 || palette_size > 30000) {e_printf("Not a sensible number for option -p\n"); return 1; }
                  if (palette_size == 0) {v_printf(2,"Palette disabled\n"); }
                  break;
        case 'r': learn_repeats=atoi(optarg);
                  if (learn_repeats < 0 || learn_repeats > 1000) {e_printf("Not a sensible number for option -r\n"); return 1; }
                  break;
        case 'f': frame_delay=atoi(optarg);
                  if (frame_delay < 0 || frame_delay > 60000) {e_printf("Not a sensible number for option -f\n"); return 1; }
                  break;
        case 'l': lookback=atoi(optarg);
                  if (lookback < -1 || lookback > 256) {e_printf("Not a sensible number for option -l\n"); return 1; }
                  break;
#endif
        case 'h':
        default: show_help(); return 0;
        }
    }
    argc -= optind;
    argv += optind;

    show_banner();
    if (argc == 0) {
        //e_printf("Input file missing.\n");
        if (get_verbosity() == 1) show_help();
        return 1;
    }

    if (argc == 1) {
        show_help();
        e_printf("\nOutput file missing.\n");
        return 1;
    }

    if (file_exists(argv[0])) {
#ifdef HAS_ENCODER
        if (mode == 0 && file_is_flif(argv[0])) {
            char *f = strrchr(argv[1],'/');
            char *ext = f ? strrchr(f,'.') : strrchr(argv[1],'.');
            if (check_compatible_extension(ext)) {
                v_printf(2,"Input file is a FLIF file, adding implicit -d\n");
                mode = 1;
            } else if ((ext && ( !strcasecmp(ext,".flif")  || ( !strcasecmp(ext,".flf") )))) {
                v_printf(2,"Input and output file are both FLIF file, adding implicit -t\n");
                mode = 2;
            }
        }
#endif
        char *f = strrchr(argv[0],'/');
        char *ext = f ? strrchr(f,'.') : strrchr(argv[0],'.');
        if (mode == 0) {
            if (!check_compatible_extension(ext)) {
                e_printf("Warning: expected \".png\" or \".pnm\" file name extension for input file, trying anyway...\n");
            }
        } else {
            if (!(ext && ( !strcasecmp(ext,".flif")  || ( !strcasecmp(ext,".flf") )))) {
                e_printf("Warning: expected file name extension \".flif\" for input file, trying anyway...\n");
            }
        }
    } else if (argc>0) {
        e_printf("Input file does not exist: %s\n",argv[0]);
        return 1;
    }
    if (mode > 0 && argc > 2) {
        e_printf("Too many arguments.\n");
        return 1;
    }

#ifdef HAS_ENCODER
    if (mode == 0) {
        if (!handle_encode(argc, argv, images, palette_size, acb, method, lookback, learn_repeats, frame_delay)) return 2;
    } else if (mode == 1) {
#endif
        if (!handle_decode(argv, images, quality, scale)) return 2;
#ifdef HAS_ENCODER
    } else if (mode == 2) {
        if (scale > 1) {e_printf("Not yet supported: transcoding downscaled image; use decode + encode!\n");}
        if (!decode_flif(argv, images, quality, scale)) return 2;
        argc--; argv++;
        if (!encode_flif(argc, argv, images, palette_size, acb, method, lookback, learn_repeats, frame_delay)) return 2;
    }
#endif
    return 0;
}
Ejemplo n.º 20
0
Archivo: jpegplay.c Proyecto: emon/emon
static int
opt_etc(int argc, char *argv[], opt_t *opt)
{
	int             ch;
	int             loop_flag = 1;
	char           *temp;
	char           *opts = "r:nD:d:g:T:bs:W:";
	char           *helpmes =
	"usage : %s [-r <framerate>] [-D <debug level>]"
	" [-d <YUV|RGB|GRB>] [-n]  [-T <window title>]"
	" [-g <xsize>x<ysize> (not supported)] [-b]"
	"\n"
	" -n : no display (decode only)\n"
	" -b : if frame loss,fill screen with blue [require -d BRG]\n"
	" -s <n>   : max frame size\n"
	" -W <n>   : max delay # msec\n"
		;
	int             w, h;

	opt->clock = DEF_EMON_CLOCK;
	opt->freq = DEF_EMON_FREQ;
	opt->f_disp = 1;
	opt->exec_opt_p = 0;
	opt->output_width = 0;
	opt->output_height = 0;
	opt->loss_visual = 0;
#if 0
	opt->dformat = DF_YUV;
#else
	opt->dformat = DF_BGR;
#endif
	opt->dsize   =DEF_JPEGPLAY_DSIZE;
	opt->delay_limit=DEF_JPEGPLAY_DELAY_LIMIT;
	strncpy(opt->title, "jpegplay", sizeof(opt->title) - 1);

	if ((temp = getenv("EMON_CLOCK")) != NULL)
		opt->clock = atoi(temp);
	if ((temp = getenv("EMON_FREQ")) != NULL)
		opt->freq = atoi(temp);
	if ((temp = getenv("JPEGPLAY_DSIZE")) != NULL)
		opt->dsize = atoi(temp);
	if ((temp = getenv("JPEGPLAY_DELAY_LIMIT")) != NULL)
		opt->delay_limit = atoi(temp);

	while ((ch = getopt(argc, argv, opts)) != -1 && loop_flag == 1) {
		switch (ch) {
		case 'r':
			opt->frame_rate = atoi(optarg);
			break;
		case 'D':
			debug_level = atoi(optarg);
			break;
		case 'd':	/* display format */
			if (strcasecmp(optarg, "YUV") == 0) {
				opt->dformat = DF_YUV;
			} else if (strcasecmp(optarg, "RGB") == 0) {
				opt->dformat = DF_RGB;
			} else if (strcasecmp(optarg, "BGR") == 0) {
				opt->dformat = DF_BGR;
			} else {
				opt->dformat = DF_YUV;
				fprintf(stderr, "invalid option in -d option");
			}
			break;
		case 'g':	/* geometry () */
			sscanf(optarg, "%dx%d", &w, &h);
			if (!((0 < w && w <= 1280) && (0 < h && h <= 1024))) {
				break;
			}
			opt->output_width = w;
			opt->output_height = h;
			break;
		case 'n':
			opt->f_disp = 0;
			break;
		case 'b':
			opt->loss_visual = 1;
			break;
		case 's':
			opt->dsize = atoi(optarg);
			break;
		case 'W':
			opt->delay_limit = atoi(optarg);
			break;
		case 'T':	/* Window Title */
			strncpy(opt->title, optarg, sizeof(opt->title) - 1);
			break;
		default:
			fprintf(stderr, helpmes, argv[0]);
			return -1;
		}
	}

	if (opt->freq < 0){
		e_printf("freq (-F or EMON_FREQ) value must be over 0\n");
		return -1;
	}
	opt->frame_rate = opt->clock / opt->freq;

	if (opt->frame_rate == 0) {
		opt->frame_rate=30;
		opt->mspf_org = 1000.0 / 30;
	} else {
		opt->mspf_org = 1000.0 / opt->frame_rate;
	}
	opt->mspf = opt->mspf_org;
	return 0;
}
Ejemplo n.º 21
0
Archivo: jpegplay.c Proyecto: emon/emon
int 
jpeg_display_rgb(int argc, char *argv[])
{
	u_int8_t       *rgb_buf;/* RGB data */
	u_int8_t       *jpeg_buf;	/* JPEG data */
	buf_t           jpeg_src_buf;
	size_t          read_size;	/* read size from file */
	int             row_stride;
	int             w, h, d;/* display size and depth(byte) */
	boolean         draw_screen;	/* draw screen surface or another
					 * surface */
	int             screen_status; /* 0=general 1=blue 2=red */
	/* for jpeg library */
	struct jpeg_decompress_struct cinfo;
	struct jpeg_error_mgr jerr;

	/* for SDL */
	SDL_Surface    *screen;
	SDL_Surface    *sdl_image = NULL;
//	SDL_Rect        dstrect;

	/* for visualize packet loss */
	SDL_Surface    *sdl_img_blue = NULL;
	SDL_Surface    *sdl_img_red  = NULL;
	u_int8_t        pixel_blue[]={0,0,0xff};
	u_int8_t        pixel_red[]={0xff,0,0};
	u_int32_t       tick_start, tick_now;
	int             buf_status; /* -1=full */

	/* for realtime play */
	struct timeval  tv_start,tv_now;
	int64_t         ts_display,ts_diff;
	u_int32_t       ts_nowblk,ts_lastblk=0;
	
	/* for debug */
	struct timeval  tv_tmp1, tv_tmp2;
	

	/* SDL init */
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		ComplainAndExit();
	}
	atexit(SDL_Quit);

	/* jpeg library init / get image size and depth */
	cinfo.err = jpeg_std_error(&jerr);
	cinfo.err->error_exit = my_jpeg_abort_decompress;
	jpeg_create_decompress(&cinfo);

#ifdef USE_JPEG_MEM_SRC
	jpeg_buf = jpeg_mem_src_init(&cinfo, JPEG_BUF_MAX);	/* init */
#else
	jpeg_buf = (u_int8_t *) malloc(JPEG_BUF_MAX);
#endif

	decoder_buf_read();
	read_size = decoder_buf_get(jpeg_buf, JPEG_BUF_MAX,&ts_nowblk);

#ifdef USE_JPEG_MEM_SRC
	jpeg_mem_src(&cinfo, jpeg_buf, read_size);	/* read from memory */
#else
	jpeg_src_buf.buf = jpeg_buf;
	jpeg_buf_src(&cinfo, jpeg_buf, read_size);	/* read from memory */
#endif

	jpeg_read_header(&cinfo, TRUE);
	w = cinfo.image_width;
	h = cinfo.image_height;
	d = cinfo.num_components;
	jpeg_abort_decompress(&cinfo);

	d_printf("\nJPEG info: image=(%d,%d), output=(%d,%d), Bpp=%d\n",
		 cinfo.image_width, cinfo.image_height, w, h, d);

	/* SDL setup / cleanup screen-surface */
	screen = SDL_SetVideoMode(w, h, 0, SDL_HWSURFACE);
	if (screen == NULL) {
		ComplainAndExit();
	}
	if (OPT.loss_visual){
		sdl_img_blue = SDL_CreateRGBSurface(
			SDL_HWSURFACE, w, h, 24
			,OPT.sdl_mask_R, OPT.sdl_mask_G
			,OPT.sdl_mask_B, OPT.sdl_mask_A);
		sdl_img_red = SDL_CreateRGBSurface(
			SDL_HWSURFACE, w, h, 24
			,OPT.sdl_mask_R, OPT.sdl_mask_G
			,OPT.sdl_mask_B, OPT.sdl_mask_A);
		jpeg_fillimg1color(sdl_img_red,pixel_red,3);
		jpeg_fillimg1color(sdl_img_blue,pixel_blue,3);
	}
	if (screen->format->BytesPerPixel == RGB_PIXELSIZE &&
	    screen->format->Rmask == OPT.sdl_mask_R &&
	    screen->format->Gmask == OPT.sdl_mask_G &&
	    screen->format->Bmask == OPT.sdl_mask_B) {
		draw_screen = TRUE;
	} else {
		draw_screen = FALSE;
	}

	d1_printf("\nSDL screen  info: bpp=%d, Bpp=%d, "
		  "R/G/B-mask=%06x/%06x/%06x, Direct=%s",
		screen->format->BitsPerPixel, screen->format->BytesPerPixel,
		  screen->format->Rmask, screen->format->Gmask,
		  screen->format->Bmask,
		  draw_screen ? "ON" : "OFF");

	if (draw_screen==TRUE) {
		/* RGB_PIXELSIZE is defined in jmorecfg.h */
		row_stride = screen->pitch;
	        rgb_buf = (u_int8_t *) screen->pixels;
	} else {
		sdl_image = SDL_CreateRGBSurface(
						 SDL_HWSURFACE, w, h, 24,	/* depth (bit per pixel) */
					     OPT.sdl_mask_R, OPT.sdl_mask_G,
					    OPT.sdl_mask_B, OPT.sdl_mask_A);
		row_stride = sdl_image->pitch;
		d1_printf("\nSDL surface info: bpp=%d, Bpp=%d, "
			  "R/G/B-mask=%06x/%06x/%06x\n",
			  sdl_image->format->BitsPerPixel,
			  sdl_image->format->BytesPerPixel,
			  sdl_image->format->Rmask,
			  sdl_image->format->Gmask,
			  sdl_image->format->Bmask
			);
		rgb_buf = (u_int8_t *) sdl_image->pixels;
	}

	STAT.skip_count = 0;
	STAT.wait_count = 0;

	tick_start = SDL_GetTicks();	/* get start time */
	gettimeofday(&STAT.start, NULL);
	gettimeofday(&tv_start, NULL);
	ts_display=0;

	STAT.f_sigint = 0;
	signal(SIGINT, sigint_trap);



	jpeg_fillimg1color(screen,pixel_blue,3);
	screen_status=1;

	for (STAT.frame_count = 1;; STAT.frame_count++) {
		if (STAT.f_sigint)
			sigint_quit();

		jpeg_has_error = 0;	/* reset flag */
		buf_status=decoder_buf_read();
#if 0
		read_size = decoder_buf_get(jpeg_buf, JPEG_BUF_MAX);
#ifdef REALTIME_PLAY
		tick_now = SDL_GetTicks();
		if (tick_now - tick_start > STAT.frame_count * OPT.mspf) {
			/* skip frame because it's too late */
			STAT.skip_count++;
			continue;
		}
#endif
#else
		read_size = decoder_buf_get(jpeg_buf, JPEG_BUF_MAX,&ts_nowblk);
#ifdef REALTIME_PLAY
		if(buf_status==-1){
			/* need more cpu power */
			if(OPT.loss_visual){
				jpeg_blitimg2screen(sdl_img_red,screen);
				screen_status=2;
			}
			d1_printf("INFO:buffer skip\n");
			STAT.skip_count+=decoder_buf_get_datanum()/2;
			STAT.frame_count+=decoder_buf_get_datanum()/2;
			decoder_buf_rm(decoder_buf_get_datanum()/2);
			ts_display=0;
			gettimeofday(&tv_start, NULL);
			continue;
		}
#endif
#endif
		if (read_size == 0) {	/* buffer empty */
			d1_printf("INFO:buffer empty\n");
			STAT.frame_count--;	/* no skip, no display */
			if(OPT.loss_visual && screen_status!=1){
			  jpeg_blitimg2screen(sdl_img_blue,screen);
			  screen_status=1;
			}
			decoder_buf_prebuf();
			ts_display=0;
			gettimeofday(&tv_start, NULL);
			continue;
		} else if (read_size == -2) {
		    break;	/* end of all files */
		}
#ifdef USE_JPEG_MEM_SRC
		jpeg_mem_src(&cinfo, jpeg_buf, read_size);
#else
		jpeg_src_buf.buf = jpeg_buf;
		jpeg_buf_src(&cinfo, jpeg_buf, read_size);
#endif
		jpeg_read_header(&cinfo, TRUE);

		cinfo.output_width = w;
		cinfo.output_height = h;
		cinfo.out_color_space = JCS_RGB;	/* default */
		cinfo.output_components = d;
		/* more fast decompression */
		cinfo.dct_method = JDCT_FASTEST;
		//cinfo.dct_method = JDCT_FLOAT;
		cinfo.do_fancy_upsampling = FALSE;

		jpeg_start_decompress(&cinfo);

		/* screen surface lock */

		if (SDL_MUSTLOCK(screen)) {
			if (SDL_LockSurface(screen) < 0) {
				ComplainAndExit();
			}
		}
		/* JPEG decode start */
		gettimeofday(&tv_tmp1, NULL);
		while (cinfo.output_scanline < cinfo.output_height &&
		       !jpeg_has_error) {
			JSAMPLE        *rgb_scanline;
			rgb_scanline = &(rgb_buf[cinfo.output_scanline *
						 row_stride]);
			jpeg_read_scanlines(&cinfo, &rgb_scanline, 1);
		}
		/* screen surface unlock */
		if (SDL_MUSTLOCK(screen)) {
			SDL_UnlockSurface(screen);
		}
		jpeg_finish_decompress(&cinfo);
		/* JPEG decode finish */
		gettimeofday(&tv_tmp2, NULL);
		STAT.decode_usec += timeval_diff_usec(&tv_tmp2, &tv_tmp1);
#ifdef REALTIME_PLAY
		wait4rtdisplay(&tv_start,ts_display);

		if(ts_display==0){
		  ts_diff=OPT.freq;
		}else{
		  ts_diff=(u_int32_t)(ts_nowblk-ts_lastblk);
		}
		ts_lastblk=ts_nowblk;

		if(ts_diff<OPT.freq){
	 	  e_printf("INFO:reset TS interval\n");
		}
		if(ts_diff>OPT.freq){
		  d2_printf("blue back start for %u TS\n",(u_int32_t)ts_diff-OPT.freq);
		  ts_display+=(ts_diff-OPT.freq);
		  if(OPT.loss_visual && screen_status!=1){
  		    jpeg_blitimg2screen(sdl_img_blue,screen);
		    screen_status=1;
		  }
		  wait4rtdisplay(&tv_start,ts_display);
		  d2_printf("blue back end.\n");
		}else{
		  d3_printf("no blue back .\n");
		}
		ts_display+= OPT.freq;
#endif
		if (draw_screen==TRUE) {
			SDL_UpdateRect(screen, 0, 0, 0, 0);
			screen_status=0;
		} else {
			jpeg_blitimg2screen(sdl_image,screen);
			screen_status=0;
#if 0
			dstrect.x = 0;
			dstrect.y = 0;
			dstrect.w = sdl_image->w;
			dstrect.h = sdl_image->h;
			if (SDL_BlitSurface(sdl_image, NULL, screen, &dstrect) < 0) {
				SDL_FreeSurface(sdl_image);
				ComplainAndExit();
			}
#if 0
			if (SDL_MUSTLOCK(screen)) {
				SDL_UnlockSurface(screen);
			}
#endif
			SDL_UpdateRects(screen, 1, &dstrect);
#endif 
		}
	}			/* loop for all jpeg file */
	STAT.frame_count--;	/* because count from 1 */
	tick_now = SDL_GetTicks();

	if (!draw_screen) {
		SDL_FreeSurface(sdl_image);
	}
	jpeg_destroy_decompress(&cinfo);
	statistics_print(&STAT);
	return 0;
}
Ejemplo n.º 22
0
Archivo: ddlist.c Proyecto: kroody/egui
static eint item_clicked(eHandle hobj, ePointer data)
{
	e_printf(_("%s\n"), data);
	return 0;
}
Ejemplo n.º 23
0
Archivo: rtpenc.c Proyecto: emon/emon
int
main(int argc, char *argv[])
{
#ifndef RTPESND
	char            p_header[PIPE_HEADER_LEN];
#endif RTPSEND
	char            r_header[RTP_HEADER_LEN];
	char           *buffer;
	struct iovec    iov[3];
	ssize_t         length;
	u_int16_t       seq;
	PIPE_CONTEXT    p;
	int             dummy_cnt; /* dummy(very old packet)cnt */
#ifdef RTPSEND
	int             count=0; /* for Debug */
	struct timeval  blk_start_tv;
	int             blk_wait4start=1;
	int             blk_pktcnt = 0;
	u_int32_t       waitperframe;
#endif
	sigset_t        sigset;
	ssize_t         io_ret;
/* 	sigfillset(&sigset); */
/* 	sigdelset(&sigset,SIGINT); */
/* 	sigdelset(&sigset,SIGTSTP); */
	if (sigprocmask(SIG_BLOCK,&sigset,NULL)!=0){
	  e_printf("sigprocmask fail.\n");
	  exit(0);
	}
	signal(SIGINT,cb_sig);
	signal(SIGTSTP,cb_sig);
	signal(SIGPIPE,cb_sig);

	if (opt_etc(argc, argv) == -1) {
		return -1;
	}
	if (isatty(STDIN)) {
		e_printf("Standard input must be binded with pipe.\n");
		return -1;
	}
#ifndef RTPSEND
	if (isatty(STDOUT)) {
		e_printf("Standard output must be binded with pipe.\n");
		return -1;
	}
#endif /* ! RTPSEND */
	if ((buffer = malloc(OPT.plen)) == NULL) {
		e_printf("cannot malloc for buffer\n");
		return -1;
	}
	if (OPT.compatible_mode) {
		seq = 0;
	} else {
		srand(time(NULL));
		seq = rand() & 0xffff;
	}
	d1_printf("first seq/rtp=%u\n",seq);

	rtp_reset(r_header, RTP_HEADER_LEN);
	rtp_set_version(r_header, 1);
	rtp_set_ptype(r_header, OPT.payload_type);

	memset(buffer, 0, OPT.plen);
#ifdef RTPSEND
	switch(OPT.shaping_lev)
	{
	case 0:
	default:
		OPT.shaping_lev=0;
		waitperframe=1;
		d1_printf("shaping_mode : frame\n");
		break;
	case 1:
		waitperframe=OPT.rs_N;
		d1_printf("shaping_mode : packet with dups\n");
		break;
	case 2:
		waitperframe=OPT.rs_N*OPT.send_double;
		d1_printf("shaping_mode : all packet(include dups)\n");
		break;
	}
	iov[0].iov_base = r_header;
	iov[0].iov_len = RTP_HEADER_LEN;
	iov[1].iov_base = buffer;
/*	iov[1].iov_len = OPT.plen;*/
#else /* RTPSEND */
	iov[0].iov_base = p_header;
	iov[0].iov_len = PIPE_HEADER_LEN;
	iov[1].iov_base = r_header;
	iov[1].iov_len = RTP_HEADER_LEN;
	iov[2].iov_base = buffer;
/*	iov[2].iov_len = OPT.plen;*/
#endif /* RTPSEND */
	p=pipe_context_init(STDIN,1 /*OPT.rs_N*/, OPT.plen);
	wclk_ps_tvstart.tv_sec=0;
	while ((length = pipe_blocked_read_packet_ex(p, p_header, buffer))>=0){
#ifdef RTPSEND
		if(wclk_ps_tvstart.tv_sec==0){
				/* recode start time */
				gettimeofday(&wclk_ps_tvstart, NULL);
		}
		count++;
		if(blk_wait4start){
			gettimeofday(&blk_start_tv,NULL);
			blk_wait4start=0;
			blk_pktcnt = 0;
		}else{
			blk_pktcnt++;
		}
		blk_wait4start=pipe_get_marker(p_header);
#endif
#ifdef RTPSEND
		iov[1].iov_len =length;
		pipe_set_length(p_header,length);
#else 
		iov[2].iov_len =length;
		pipe_set_length(p_header,length + RTP_HEADER_LEN);
#endif /* RTPSEND*/
		rtp_set_timestamp(r_header, pipe_get_timestamp(p_header));
		rtp_set_marker(r_header, pipe_get_marker(p_header));
		rtp_set_seqnum(r_header, seq++);
		if(seq>=0x10000) seq-=0x10000;
		d3_printf("rtpenc: marker %d : seq %d\n",pipe_get_marker(p_header),seq-1);
#ifdef RTPSEND
		if (display_time_all_packet) {
			d_printf("\n%d:", seq);
		}
		rtsend_tslimit+=(u_int32_t)(pipe_get_timestamp(p_header) - pkt_tslast);
		pkt_tslast=pipe_get_timestamp(p_header);
#if 0
		wait4rtsend(&wclk_tvstart,blk_pktcnt);
#else

		if(!(OPT.shaping_lev==0 && blk_pktcnt>=1)){
			wait4rtsend(&wclk_tvstart,&rtsend_tslimit,blk_pktcnt,waitperframe);
		}
#endif 
		if (OPT.send_err_rate > 0) {
			if ((rand() % OPT.send_err_rate) == 0) {
				total_drop++;
				continue;
			}
		}
		d2_printf(" write %d bytes", pipe_get_length(p_header));
		if (writev(OPT.sfd, iov, 2) == -1) {
		    total_drop++;
		    d2_printf(" writev-NG(ts/sq=%d/%d)\n", pipe_get_timestamp(p_header), count);
		} else {
		    d2_printf(" writev-OK(ts/sq=%d/%d)\n", pipe_get_timestamp(p_header), count);
		    total_send++;
		}

		if(OPT.dup2dummy){
			rtp_set_seqnum(r_header, (seq+0x10000-0x100)&0xffff);
		}
		for(dummy_cnt=1;dummy_cnt<OPT.send_double;dummy_cnt++){
			if(OPT.shaping_lev==2){
				blk_pktcnt++;
				wait4rtsend(&wclk_tvstart,&rtsend_tslimit,blk_pktcnt,waitperframe);
			}
			d2_printf(" write dup(%d/%d) \n",dummy_cnt,OPT.send_double);
			io_ret=writev(OPT.sfd, iov, 2);
			if ( io_ret == -1) {
			    total_drop++;
			    d2_printf(" writev-NG(ts/sq=%d/%d)\n", pipe_get_timestamp(p_header), count);
			} else {
			    d2_printf(" writev-OK(ts/sq=%d/%d)\n", pipe_get_timestamp(p_header), count);
			    total_send++;
			}
		}
#else /* RTPSEND */
		d2_printf(" write pkt\n");
		writev(STDOUT, iov, 3);
		if(OPT.dup2dummy){
			rtp_set_seqnum(r_header, (seq+0x10000-0x100)&0xffff);
		}
		for(dummy_cnt=1;dummy_cnt<OPT.send_double;dummy_cnt++){
		  d2_printf(" write dup(%d/%d) \n",dummy_cnt,OPT.send_double);
		  io_ret=writev(STDOUT, iov, 3);
		  if(io_ret==-1){
			  exit_req=1;
			  break;
		  }
		}
#endif /* RTPSEND */
		if(exit_req==1){
		  break;
		}
	}
#ifdef RTPSEND
	last_seq=seq-1;
	statistics_display();
	sleep(1);
#endif
	return 0;
}
Ejemplo n.º 24
0
int main(int argc, char **argv)
{
    Images images;
    flif_options options = FLIF_DEFAULT_OPTIONS;
#ifdef HAS_ENCODER
    int mode = -1; // 0 = encode, 1 = decode, 2 = transcode
#else
    int mode = 1;
#endif
    bool showhelp = false;
    if (strcmp(argv[0],"cflif") == 0) mode = 0;
    if (strcmp(argv[0],"dflif") == 0) mode = 1;
    if (strcmp(argv[0],"deflif") == 0) mode = 1;
    if (strcmp(argv[0],"decflif") == 0) mode = 1;
    static struct option optlist[] = {
        {"help", 0, NULL, 'h'},
        {"decode", 0, NULL, 'd'},
        {"verbose", 0, NULL, 'v'},
        {"no-crc", 0, NULL, 'c'},
        {"no-metadata", 0, NULL, 'm'},
        {"no-color-profile", 0, NULL, 'p'},
        {"quality", 1, NULL, 'q'},
        {"scale", 1, NULL, 's'},
        {"resize", 1, NULL, 'r'},
        {"fit", 1, NULL, 'f'},
        {"identify", 0, NULL, 'i'},
        {"version", 0, NULL, 'V'},
        {"overwrite", 0, NULL, 'o'},
        {"breakpoints", 0, NULL, 'b'},
        {"keep-palette", 0, NULL, 'k'},
#ifdef HAS_ENCODER
        {"encode", 0, NULL, 'e'},
        {"transcode", 0, NULL, 't'},
        {"interlace", 0, NULL, 'I'},
        {"no-interlace", 0, NULL, 'N'},
        {"frame-delay", 1, NULL, 'F'},
        {"keep-invisible-rgb", 0, NULL, 'K'},
        {"max-palette-size", 1, NULL, 'P'},
        {"force-color-buckets", 0, NULL, 'A'},
        {"no-color-buckets", 0, NULL, 'B'},
        {"no-ycocg", 0, NULL, 'Y'},
        {"no-channel-compact", 0, NULL, 'C'},
        {"max-frame-lookback", 1, NULL, 'L'},
        {"no-frame-shape", 0, NULL, 'S'},
        {"maniac-repeats", 1, NULL, 'R'},
        {"maniac-divisor", 1, NULL, 'D'},
        {"maniac-min-size", 1, NULL, 'M'},
        {"maniac-threshold", 1, NULL, 'T'},
        {"chance-cutoff", 1, NULL, 'X'},
        {"chance-alpha", 1, NULL, 'Z'},
        {"lossy", 1, NULL, 'Q'},
        {"adaptive", 0, NULL, 'U'},
        {"guess", 1, NULL, 'G'},
        {"invisible-guess", 1, NULL, 'H'},
        {"effort", 1, NULL, 'E'},
        {"chroma-subsample", 0, NULL, 'J'},
        {"no-subtract-green", 0, NULL, 'W'},
#endif
        {0, 0, 0, 0}
    };
    int i,c;
#ifdef HAS_ENCODER
    while ((c = getopt_long (argc, argv, "hdvcmiVq:s:r:f:obketINnF:KP:ABYWCL:SR:D:M:T:X:Z:Q:UG:H:E:J", optlist, &i)) != -1) {
#else
    while ((c = getopt_long (argc, argv, "hdvcmiVq:s:r:f:obk", optlist, &i)) != -1) {
#endif
        switch (c) {
        case 'd': mode=1; break;
        case 'v': increase_verbosity(); break;
        case 'V': increase_verbosity(3); break;
        case 'c': options.crc_check = 0; break;
        case 'm': options.metadata = 0; break;
        case 'p': options.color_profile = 0; break;
        case 'o': options.overwrite = 1; break;
        case 'q': options.quality=atoi(optarg);
                  if (options.quality < 0 || options.quality > 100) {e_printf("Not a sensible number for option -q\n"); return 1; }
                  break;
        case 's': options.scale=atoi(optarg);
                  if (options.scale < 1 || options.scale > 128) {e_printf("Not a sensible number for option -s\n"); return 1; }
                  break;
        case 'r': if (sscanf(optarg,"%ix%i", &options.resize_width, &options.resize_height) < 1) {
                    if (sscanf(optarg,"x%i", &options.resize_height) < 1) {e_printf("Not a sensible value for option -r (expected WxH)\n"); return 1; }
                  }
                  if (!options.resize_height) options.resize_height = options.resize_width;
                  break;
        case 'f': if (sscanf(optarg,"%ix%i", &options.resize_width, &options.resize_height) < 1) {
                    if (sscanf(optarg,"x%i", &options.resize_height) < 1) {e_printf("Not a sensible value for option -f (expected WxH)\n"); return 1; }
                  }
                  options.fit=1;
                  break;
        case 'i': options.scale = -1; break;
        case 'b': options.show_breakpoints = 8; mode=1; break;
        case 'k': options.keep_palette = true; break;
#ifdef HAS_ENCODER
        case 'e': mode=0; break;
        case 't': mode=2; break;
        case 'I': options.method.encoding=flifEncoding::interlaced; break;
        case 'n': // undocumented: lower case -n still works
        case 'N': options.method.encoding=flifEncoding::nonInterlaced; break;
        case 'A': options.acb=1; break;
        case 'B': options.acb=0; break;
        case 'P': options.palette_size=atoi(optarg);
                  if (options.palette_size < -32000 || options.palette_size > 32000) {e_printf("Not a sensible number for option -P\n"); return 1; }
                  if (options.palette_size > 512) {v_printf(1,"Warning: palette size above 512 implies that simple FLIF decoders (8-bit only) cannot decode this file.\n"); }
                  if (options.palette_size == 0) {v_printf(5,"Palette disabled\n"); }
                  break;
        case 'R': options.learn_repeats=atoi(optarg);
                  if (options.learn_repeats < 0 || options.learn_repeats > 20) {e_printf("Not a sensible number for option -R\n"); return 1; }
                  break;
        case 'F': options.frame_delay.clear();
                  while(optarg != 0) {
                    int d=strtol(optarg,&optarg,10);
                    if (d==0) break;
                    if (*optarg == ',' || *optarg == '+' || *optarg == ' ') optarg++;
                    options.frame_delay.push_back(d);
                    if (d < 0 || d > 60000) {e_printf("Not a sensible number for option -F: %i\n",d); return 1; }
                  }
                  if (options.frame_delay.size() < 1) options.frame_delay.push_back(100);
                  break;
        case 'L': options.lookback=atoi(optarg);
                  if (options.lookback < -1 || options.lookback > 256) {e_printf("Not a sensible number for option -L\n"); return 1; }
                  break;
        case 'D': options.divisor=atoi(optarg);
                  if (options.divisor <= 0 || options.divisor > 0xFFFFFFF) {e_printf("Not a sensible number for option -D\n"); return 1; }
                  break;
        case 'M': options.min_size=atoi(optarg);
                  if (options.min_size < 0) {e_printf("Not a sensible number for option -M\n"); return 1; }
                  break;
        case 'T': options.split_threshold=atoi(optarg);
                  if (options.split_threshold <= 3 || options.split_threshold > 100000) {e_printf("Not a sensible number for option -T\n"); return 1; }
                  options.split_threshold *= 5461;
                  break;
        case 'Y': options.ycocg=0; break;
        case 'W': options.ycocg=0; options.subtract_green=0; break;
        case 'C': options.plc=0; break;
        case 'S': options.frs=0; break;
        case 'K': options.alpha_zero_special=0; break;
        case 'X': options.cutoff=atoi(optarg);
                  if (options.cutoff < 1 || options.cutoff > 128) {e_printf("Not a sensible number for option -X (try something between 1 and 128)\n"); return 1; }
                  break;
        case 'Z': options.alpha=atoi(optarg);
                  if (options.alpha < 2 || options.alpha > 128) {e_printf("Not a sensible number for option -Z (try something between 2 and 128)\n"); return 1; }
                  break;
        case 'Q': options.loss=100-atoi(optarg);
                  // can't go above quality 100 = lossless
                  // can go way below 0 if you want
                  if (options.loss < 0) {e_printf("Not a sensible number for option -Q (try something between 0 and 100)\n"); return 1; }
                  break;
        case 'U': options.adaptive=1; break;
        case 'G': {
                  int p=0;
                  while(*optarg != 0) {
                    int d=0;
                    switch (*optarg) {
                        case '?': case 'G': case 'g': case 'H': case 'h': // guess/heuristically choose
                            d = -2; break;
                        case '0': case 'A': case 'a': // average
                            d = 0; break;
                        case '1': case 'M': case 'm': // median of 3 values (avg, grad1, grad2)
                            d = 1; break;
                        case '2': case 'N': case 'n': // median of 3 neighbors
                            d = 2; break;
                        case '3':
                        case 'X': case 'x': // auto/mixed, usually a bad idea
                            d = -1; break;
                        case ' ': case ',': case '+':
                            optarg++; continue;
                        default:
                        e_printf("Not a sensible value for option -G\nValid values are: 0 (avg), 1 (median avg/gradients), 2 (median neighbors), X (auto/mixed), ? (heuristically pick 0-2)\n"); return 1;
                    }
                    if (p>4) {e_printf("Error while parsing option -G: too many planes specified\n"); return 1; }
                    options.predictor[p] = d;
                    p++; optarg++;
                  }
                  for (; p<5; p++) options.predictor[p]=options.predictor[0];
                  }
                  break;
        case 'H': options.invisible_predictor=atoi(optarg);
                  if (options.invisible_predictor < 0 || options.invisible_predictor > 2) {e_printf("Not a sensible value for option -H\nValid values are: 0 (avg), 1 (median avg/gradients), 2 (median neighbors)\n"); return 1; }
                  break;
        case 'J': options.chroma_subsampling = 1;
                  break;
        case 'E': {
                  int effort=atoi(optarg);
                  if (effort < 0 || effort > 100) {e_printf("Not a sensible number for option -E (try something between 0 and 100)\n"); return 1; }
                  // set some parameters automatically
                  if (effort < 10) options.learn_repeats=0;
                  else if (effort <= 50) {options.learn_repeats=1; options.split_threshold=5461*8*5;}
                  else if (effort <= 70) {options.learn_repeats=2;  options.split_threshold=5461*8*8;}
                  else if (effort <= 90) {options.learn_repeats=3; options.split_threshold=5461*8*10;}
                  else if (effort <= 100) {options.learn_repeats=4; options.split_threshold=5461*8*12;}
                  if (effort < 15) { for (int i=0; i<5; i++) options.predictor[i]=0; }
                  else if (effort < 30) { options.predictor[1]=0; options.predictor[2]=0; }
                  if (effort < 5) options.acb=0;
                  if (effort < 8) options.palette_size=0;
                  if (effort < 25) options.plc=0;
                  if (effort < 30) options.lookback=0;
                  if (effort < 5) options.frs=0;
                  v_printf(3,"Encode effort: %i, corresponds to parameters -R%i -T%i%s%s%s%s\n", effort, options.learn_repeats, options.split_threshold/5461,
                                    (effort<15?" -G0":(effort<30?" -G?00":"")), (effort<5?" -B":""), (effort<8?" -P0":""), (effort<25?" -C":""));
                                    // not mentioning animation options since they're usually irrelevant
                  }
                  break;
#endif
        case 'h': showhelp=true; break;
        default: show_help(mode); return 0;
        }
    }
    argc -= optind;
    argv += optind;
    bool last_is_output = (options.scale != -1);
    if (options.show_breakpoints && argc == 1) { last_is_output = false; options.no_full_decode = 1; options.scale = 2; }

    if (!strcmp(argv[argc-1],"-")) {
        // writing output to stdout, so redirecting verbose output to stderr to avoid contaminating the output stream
        redirect_stdout_to_stderr();
    }

    show_banner();
    if (argc == 0 || showhelp) {
        if (get_verbosity() == 1 || showhelp) show_help(mode);
        return 0;
    }

    if (argc == 1 && last_is_output) {
        show_help(mode);
        e_printf("\nOutput file missing.\n");
        return 1;
    }
    if (options.scale == -1) mode = 1;
    if (mode < 0) mode = 0;
    if (file_exists(argv[0])) {
        char *f = strrchr(argv[0],'/');
        char *ext = f ? strrchr(f,'.') : strrchr(argv[0],'.');
#ifdef HAS_ENCODER
        if (mode == 0 && file_is_flif(argv[0])) {
            char *f = strrchr(argv[1],'/');
            char *ext = f ? strrchr(f,'.') : strrchr(argv[1],'.');
            if ((ext && ( !strcasecmp(ext,".flif")  || ( !strcasecmp(ext,".flf") )))) {
                v_printf(3,"Input and output file are both FLIF file, adding implicit -t\n");
                mode = 2;
            } else {
                v_printf(3,"Input file is a FLIF file, adding implicit -d\n");
                mode = 1;
            }
        }
        if (mode == 0) {
            char *f = strrchr(argv[argc-1],'/');
            char *ext = f ? strrchr(f,'.') : strrchr(argv[argc-1],'.');
            if (ext && !options.loss && strcasecmp(ext,".flif") && strcasecmp(ext,".flf") ) {
                e_printf("Warning: expected file name extension \".flif\" for output file.\n");
            } else if (options.loss && check_compatible_extension(ext)) {
                v_printf(2,"Not doing actual lossy encoding to FLIF, just applying loss.\n");
                options.just_add_loss = 1;
            }
        }
        if (mode != 0) {
#endif
            if (!(ext && ( !strcasecmp(ext,".flif")  || ( !strcasecmp(ext,".flf") )))) {
                e_printf("Warning: expected file name extension \".flif\" for input file, trying anyway...\n");
            }
#ifdef HAS_ENCODER
        } else {
            if (!check_compatible_extension(ext)) {
                e_printf("Warning: expected \".png\", \".pnm\" or \".pam\" file name extension for input file, trying anyway...\n");
            }
        }
#endif
    } else if (argc>0) {
        if (!strcmp(argv[0],"-")) {
          v_printf(4,"Taking input from standard input. Mode: %s\n",
             (mode==0?"encode": (mode==1?"decode":"transcode")));
        } else if (!strchr(argv[0],'%')) {
          e_printf("Error: input file does not exist: %s\n",argv[0]);
          return 1;
        }
    }
    if (last_is_output && file_exists(argv[argc-1]) && !options.overwrite) {
        e_printf("Error: output file already exists: %s\nUse --overwrite to force overwrite.\n",argv[argc-1]);
        return 1;
    }
    if (mode > 0 && argc > 2 && options.scale != -1) {
        e_printf("Too many arguments.\n");
        return 1;
    }

#ifdef HAS_ENCODER
    if (options.chroma_subsampling)
        v_printf(1,"Warning: chroma subsampling produces a truncated FLIF file. Image will not be lossless!\n");
    if (options.loss > 0) options.keep_palette = false; // not going to add loss to indexed colors
    if (options.adaptive) options.loss = -options.loss; // use negative loss to indicate we want to do adaptive lossy encoding
    if (mode == 0) {
        if (!handle_encode(argc, argv, images, options)) return 2;
    } else if (mode == 1) {
#endif
        return handle_decode(argc, argv, images, options);
#ifdef HAS_ENCODER
    } else if (mode == 2) {
//        if (scale > 1) {e_printf("Not yet supported: transcoding downscaled image; use decode + encode!\n");}
        if (!decode_flif(argv, images, options)) return 2;
        argc--; argv++;
        if (!encode_flif(argc, argv, images, options)) return 2;
    }
#endif
    return 0;
}
Ejemplo n.º 25
0
bool encode_load_input_images(int argc, char **argv, Images &images, flif_options &options) {
    int nb_input_images = argc-1;
    int nb_actual_images = 0;
    metadata_options md;
    md.icc = options.color_profile;
    md.xmp = options.metadata;
    md.exif = options.metadata;
    while(argc>1) {
      int maxlength = strlen(argv[0])+100;
      std::vector<char> vfilename(maxlength);
      char *filename = argv[0];
      int framecounter = 0;
      int stop_searching = 0;
      bool multiple=false;
      if (!file_exists(argv[0]) && strchr(argv[0],'%')) {
        multiple=true;
        filename = &vfilename[0];
      }
      for ( ; framecounter < 0xFFFFFFF && stop_searching < 1000; framecounter++ ) {
        if (multiple) {
             snprintf(filename,maxlength,argv[0],framecounter);
             if (!file_exists(filename)) {
                stop_searching++;
                continue;
             }
             stop_searching = 0;
        }
        Image image;
        if (options.keep_palette) image.palette = true; // tells the PNG loader to keep palette intact
        v_printf_tty(2,"\r");
        if (!image.load(filename,md)) {
            e_printf("Could not read input file: %s\n", argv[0]);
            return false;
        };
        if (image.numPlanes() > 0) {
          nb_actual_images++;
          images.push_back(std::move(image));
          Image& last_image = images.back();
          if (last_image.rows() != images[0].rows() || last_image.cols() != images[0].cols()) {
            e_printf("Dimensions of all input images should be the same!\n");
            e_printf("  First image is %ux%u\n",images[0].cols(),images[0].rows());
            e_printf("  This image is %ux%u: %s\n",last_image.cols(),last_image.rows(),filename);
            return false;
          }
          if (last_image.numPlanes() < images[0].numPlanes()) {
            if (images[0].numPlanes() == 3) last_image.ensure_chroma();
            else if (images[0].numPlanes() == 4) last_image.ensure_alpha();
            else { e_printf("Problem while loading input images, please report this.\n"); return false; }
          } else if (last_image.numPlanes() > images[0].numPlanes()) {
            if (last_image.numPlanes() == 3) { for (Image& i : images) i.ensure_chroma(); }
            else if (last_image.numPlanes() == 4) { for (Image& i : images) i.ensure_alpha(); }
            else { e_printf("Problem while loading input images, please report this.\n"); return false; }
          }
        } else {
          if (images.size() == 0) {
            e_printf("First specify the actual image(s), then the metadata.\n");
            return false;
          }
          for (size_t i=0; i<image.metadata.size(); i++)
              images[0].metadata.push_back(image.metadata[i]);
        }
        if (nb_input_images>1) {v_printf(2,"    (%i/%i)         ",(int)images.size(),nb_input_images); v_printf(4,"\n");}
        if (!multiple) break;
      }
      argc--; argv++;
    }
    if (nb_actual_images > 0) return true;
    e_printf("Error: no actual input images to be encoded!\n");
    return false;
}
Ejemplo n.º 26
0
int
capt_capt(opt_t *opt)
{
	int frame_size;
	unsigned int frame_num;
	unsigned char *frame_buf_yuv, *frame_buf_rgb, *jpeg_buf;
	struct timeval start;
	const int fps = opt->fps_opt;
	const int wait_flag = (opt->fps_opt < opt->fps_dev);
	const int w = opt->width, h = opt->height;
	int q = 75;		/* jpeg compress quality */
	int len;
	char mh[PIPE_HEADER_LEN]; /* EMON system Message Header */
	unsigned int ts;	/* timestamp in Message Header */

	frame_size = mchip_hsize() * mchip_vsize() * 3;
	frame_buf_yuv = (unsigned char*)malloc(frame_size);
	frame_buf_rgb = (unsigned char*)malloc(frame_size);
	jpeg_buf = (unsigned char*)malloc(frame_size);
		/* allocate enougth memory for jpeg_buf */
	if (frame_buf_yuv == NULL || frame_buf_rgb == NULL ||jpeg_buf == NULL){
		e_printf("cannot malloc for frame_buf or jpeg_buf\n");
		return -1;
	}

	stat_init(&STAT);
	ts = rand() * opt->freq;
	mchip_continuous_start();
	gettimeofday(&start, NULL);
	STAT.start = start;	/* copy struct timeval */

	d2_printf("\njpegcapt: %ld.%06ld: wait_flag=%d",
		  start.tv_sec, start.tv_usec, wait_flag);
	
	for (frame_num = 0; opt->max_frame == 0 || frame_num < opt->max_frame; frame_num++, ts += opt->freq){
		struct timeval c, b, a; /* capture, before(encoding), after */
		int d1, d2;

		if (debug_level > 0 && (frame_num % opt->stat_freq)== 0){
			stat_print(&STAT, frame_num);
		}

		if (wait_proper_time(&start, fps, frame_num, 1) < 0){
			STAT.skip_count++;
			continue; /* skip capture because it's too late */
		}
		STAT.capt_count++;
		gettimeofday(&c, NULL);
		mchip_continuous_read(frame_buf_yuv,
				      mchip_hsize()*mchip_vsize()*2);
		yuv_convert(frame_buf_yuv, frame_buf_rgb,
			    mchip_hsize(), mchip_vsize());
		gettimeofday(&b, NULL);
		len = jpeg_encode(frame_buf_rgb, jpeg_buf, w, h, q);
		gettimeofday(&a, NULL);
		d1 = timeval_diff_usec(&b, &c);
		d2 = timeval_diff_usec(&a, &b);
		timeval_add_usec(&STAT.capt_total, d1);
		timeval_add_usec(&STAT.jpgenc_total, d2);
		d3_printf("\n frame=%d, ts=%d, jpg_len=%d, q=%d"
			  ", t1=%d, t2=%d",
			  frame_num, ts, len, q, d1, d2);

		if (len > opt->dsize ){
			q *= 0.75;
			continue; /* skip this picture */
		}else if (len < opt->dsize * 0.9 && q < 90) {
			q++;
		}
		bzero(&mh, PIPE_HEADER_LEN);
		pipe_set_version(&mh, 1);
		pipe_set_marker(&mh, 1);
		pipe_set_length(&mh, len);
		pipe_set_timestamp(&mh, ts);
		if (pipe_blocked_write_block(STDOUT, &mh, jpeg_buf)
		    ==PIPE_ERROR){
			d1_printf("\npipe_blocked_write_block error!!"
				  "len=%d, ts=%ud", len, ts);
		} else {
			STAT.out_count++;
		}
	}
	if (debug_level > 0){
		stat_print(&STAT, frame_num);
	}
	return 0;
}
Ejemplo n.º 27
0
static int m_mprotect(unsigned int addr, size_t len)
{
	if (debug_level('e')>3)
	    e_printf("\tM_MPROT   %08x\n",addr);
	return e_mprotect(addr, len);
}
Ejemplo n.º 28
0
Archivo: rtpenc.c Proyecto: emon/emon
void cb_sig(int signo){
	pipe_exit_req();
	e_printf("caught signal %d\n",signo);
	exit_req=1;
}
Ejemplo n.º 29
0
int main(int argc, char **argv)
{
    Images images;
#ifdef HAS_ENCODER
    int mode = 0; // 0 = encode, 1 = decode, 2 = transcode
    flifEncodingOptional method;
    int learn_repeats = -1;
    int acb = -1; // try auto color buckets
    std::vector<int> frame_delay;
    frame_delay.push_back(100);
    int palette_size = -1;
    int lookback = 1;
    int divisor=CONTEXT_TREE_COUNT_DIV;
    int min_size=CONTEXT_TREE_MIN_SUBTREE_SIZE;
    int split_threshold=CONTEXT_TREE_SPLIT_THRESHOLD;
    int yiq = 1;
    int plc = 1;
    int frs = 1;
    bool alpha_zero_special = true;
    int alpha=19;
    int cutoff=2;
#else
    int mode = 1;
#endif
    int quality = 100; // 100 = everything, positive value: partial decode, negative value: only rough data
    int scale = 1;
    int resize_width = 0, resize_height = 0;
    bool showhelp = false;
    if (strcmp(argv[0],"flif") == 0) mode = 0;
    if (strcmp(argv[0],"dflif") == 0) mode = 1;
    if (strcmp(argv[0],"deflif") == 0) mode = 1;
    if (strcmp(argv[0],"decflif") == 0) mode = 1;
    static struct option optlist[] = {
        {"help", 0, NULL, 'h'},
        {"decode", 0, NULL, 'd'},
        {"verbose", 0, NULL, 'v'},
        {"quality", 1, NULL, 'q'},
        {"scale", 1, NULL, 's'},
        {"resize", 1, NULL, 'r'},
        {"identify", 0, NULL, 'i'},
        {"version", 0, NULL, 'V'},
#ifdef HAS_ENCODER
        {"encode", 0, NULL, 'e'},
        {"transcode", 0, NULL, 't'},
        {"interlace", 0, NULL, 'I'},
        {"no-interlace", 0, NULL, 'N'},
        {"frame-delay", 1, NULL, 'F'},
        {"keep-invisible-rgb", 0, NULL, 'K'},
        {"max-palette-size", 1, NULL, 'P'},
        {"force-color-buckets", 0, NULL, 'A'},
        {"no-color-buckets", 0, NULL, 'B'},
        {"no-ycocg", 0, NULL, 'Y'},
        {"no-channel-compact", 0, NULL, 'C'},
        {"max-frame-lookback", 1, NULL, 'L'},
        {"no-frame-shape", 0, NULL, 'S'},
        {"maniac-repeats", 1, NULL, 'R'},
        {"maniac-divisor", 1, NULL, 'D'},
        {"maniac-min-size", 1, NULL, 'M'},
        {"maniac-threshold", 1, NULL, 'T'},
        {"chance-cutoff", 1, NULL, 'X'},
        {"chance-alpha", 1, NULL, 'Z'},
#endif
        {0, 0, 0, 0}
    };
    int i,c;
#ifdef HAS_ENCODER
    while ((c = getopt_long (argc, argv, "hdviVq:s:r:etINnF:KP:ABYCL:SR:D:M:T:X:Z:", optlist, &i)) != -1) {
#else
    while ((c = getopt_long (argc, argv, "hdviVq:s:r:", optlist, &i)) != -1) {
#endif
        switch (c) {
        case 'd': mode=1; break;
        case 'v': increase_verbosity(); break;
        case 'V': increase_verbosity(3); break;
        case 'q': quality=atoi(optarg);
                  if (quality < 0 || quality > 100) {e_printf("Not a sensible number for option -q\n"); return 1; }
                  break;
        case 's': scale=atoi(optarg);
                  if (scale < 1 || scale > 128) {e_printf("Not a sensible number for option -s\n"); return 1; }
                  break;
        case 'r': if (sscanf(optarg,"%ix%i", &resize_width, &resize_height) < 1) {e_printf("Not a sensible value for option -r (expected WxH)\n"); return 1; }
                  if (!resize_height) resize_height = resize_width;
                  break;
        case 'i': scale = -1; break;
#ifdef HAS_ENCODER
        case 'e': mode=0; break;
        case 't': mode=2; break;
        case 'I': method.encoding=flifEncoding::interlaced; break;
        case 'n': // undocumented: lower case -n still works
        case 'N': method.encoding=flifEncoding::nonInterlaced; break;
        case 'A': acb=1; break;
        case 'B': acb=0; break;
        case 'P': palette_size=atoi(optarg);
                  if (palette_size < -32000 || palette_size > 32000) {e_printf("Not a sensible number for option -P\n"); return 1; }
                  if (palette_size == 0) {v_printf(5,"Palette disabled\n"); }
                  break;
        case 'R': learn_repeats=atoi(optarg);
                  if (learn_repeats < 0 || learn_repeats > 20) {e_printf("Not a sensible number for option -R\n"); return 1; }
                  break;
        case 'F': frame_delay.clear();
                  while(optarg != 0) {
                    int d=strtol(optarg,&optarg,10);
                    if (d==0) break;
                    if (*optarg == ',' || *optarg == '+') optarg++;
                    frame_delay.push_back(d);
                    if (d < 0 || d > 60000) {e_printf("Not a sensible number for option -F: %i\n",d); return 1; }
                  }
                  if (frame_delay.size() < 1) frame_delay.push_back(100);
                  break;
        case 'L': lookback=atoi(optarg);
                  if (lookback < -1 || lookback > 256) {e_printf("Not a sensible number for option -L\n"); return 1; }
                  break;
        case 'D': divisor=atoi(optarg);
                  if (divisor <= 0 || divisor > 0xFFFFFFF) {e_printf("Not a sensible number for option -D\n"); return 1; }
                  break;
        case 'M': min_size=atoi(optarg);
                  if (min_size < 0) {e_printf("Not a sensible number for option -M\n"); return 1; }
                  break;
        case 'T': split_threshold=atoi(optarg);
                  if (split_threshold <= 3 || split_threshold > 100000) {e_printf("Not a sensible number for option -T\n"); return 1; }
                  split_threshold *= 5461;
                  break;
        case 'Y': yiq=0; break;
        case 'C': plc=0; break;
        case 'S': frs=0; break;
        case 'K': alpha_zero_special=false; break;
        case 'X': cutoff=atoi(optarg);
                  if (cutoff < 1 || cutoff > 128) {e_printf("Not a sensible number for option -X (try something between 1 and 128)\n"); return 1; }
                  break;
        case 'Z': alpha=atoi(optarg);
                  if (alpha < 2 || alpha > 128) {e_printf("Not a sensible number for option -Z (try something between 2 and 128)\n"); return 1; }
                  break;
#endif
        case 'h': showhelp=true; break;
        default: show_help(); return 0;
        }
    }
    argc -= optind;
    argv += optind;

    show_banner();
    if (argc == 0 || showhelp) {
        if (get_verbosity() == 1 || showhelp) show_help();
        return 0;
    }

    if (argc == 1 && scale != -1) {
        show_help();
        e_printf("\nOutput file missing.\n");
        return 1;
    }
    if (scale == -1) mode = 1;
    if (file_exists(argv[0])) {
        char *f = strrchr(argv[0],'/');
        char *ext = f ? strrchr(f,'.') : strrchr(argv[0],'.');
#ifdef HAS_ENCODER
        if (mode == 0 && file_is_flif(argv[0])) {
            char *f = strrchr(argv[1],'/');
            char *ext = f ? strrchr(f,'.') : strrchr(argv[1],'.');
            if ((ext && ( !strcasecmp(ext,".flif")  || ( !strcasecmp(ext,".flf") )))) {
                v_printf(3,"Input and output file are both FLIF file, adding implicit -t\n");
                mode = 2;
            } else {
                v_printf(3,"Input file is a FLIF file, adding implicit -d\n");
                mode = 1;
            }
        }
        if (mode != 0) {
#endif
            if (!(ext && ( !strcasecmp(ext,".flif")  || ( !strcasecmp(ext,".flf") )))) {
                e_printf("Warning: expected file name extension \".flif\" for input file, trying anyway...\n");
            }
#ifdef HAS_ENCODER
        } else {
            if (!check_compatible_extension(ext)) {
                e_printf("Warning: expected \".png\", \".pnm\" or \".pam\" file name extension for input file, trying anyway...\n");
            }
        }
#endif
    } else if (argc>0) {
        e_printf("Input file does not exist: %s\n",argv[0]);
        return 1;
    }
    if (mode > 0 && argc > 2 && scale != -1) {
        e_printf("Too many arguments.\n");
        return 1;
    }

#ifdef HAS_ENCODER
    if (mode == 0) {
        if (!handle_encode(argc, argv, images, palette_size, acb, method, lookback, learn_repeats, frame_delay, divisor, min_size, split_threshold, yiq, plc, alpha_zero_special, frs, cutoff, alpha)) return 2;
    } else if (mode == 1) {
#endif
        return handle_decode(argc, argv, images, quality, scale, resize_width, resize_height);
#ifdef HAS_ENCODER
    } else if (mode == 2) {
//        if (scale > 1) {e_printf("Not yet supported: transcoding downscaled image; use decode + encode!\n");}
        if (!decode_flif(argv, images, quality, scale, resize_width, resize_height)) return 2;
        argc--; argv++;
        if (!encode_flif(argc, argv, images, palette_size, acb, method, lookback, learn_repeats, frame_delay, divisor, min_size, split_threshold, yiq, plc, frs, cutoff, alpha)) return 2;
    }
#endif
    return 0;
}
Ejemplo n.º 30
0
int handle_decode(int argc, char **argv, Images &images, flif_options &options) {
    if (options.scale < 0) {
        // just identify the file(s), don't actually decode
        while (argc>0) {
            decode_flif(argv, images, options);
            argv++; argc--;
        }
        return 0;
    }
    if (argc == 1 && options.show_breakpoints) {
        decode_flif(argv, images, options);
        return 0;
    }
    char *ext = strrchr(argv[1],'.');
    if (check_metadata_extension(ext)) {
        // only requesting metadata, no need to actually decode the file
        options.scale = -2;
        decode_flif(argv, images, options);
        if (!images[0].save(argv[1])) return 2;
        v_printf(2,"\n");
        return 0;
    }
    if (!check_compatible_extension(ext) && strcmp(argv[1],"null:") && strcmp(argv[1],"-")) {
        e_printf("Error: expected \".png\", \".pnm\" or \".pam\" file name extension for output file\n");
        return 1;
    }
    if (!(ext && ( !strcasecmp(ext,".png"))))
        options.keep_palette = false;   // don't try to make a palette PNM

    try {
      if (!decode_flif(argv, images, options)) {
        e_printf("Error: could not decode FLIF file\n"); return 3;
      }
    } catch (std::bad_alloc& ba) {
        e_printf("Error: memory allocation problem (unexpected)\n"); return 3;
    }
    if (!strcmp(argv[1],"null:")) return 0;
//    if (scale>1)
//        v_printf(3,"Downscaling output: %ux%u -> %ux%u\n",images[0].cols(),images[0].rows(),images[0].cols()/scale,images[0].rows()/scale);
    if (images.size() == 1) {
        if (!images[0].save(argv[1])) return 2;
    } else {
        bool to_stdout=false;
        if (!strcmp(argv[1],"-")) {
            to_stdout=true;
            v_printf(1,"Warning: writing animation to standard output as a concatenation of PAM files.\n");
        }
        int counter=0;
        int maxlength = strlen(argv[1])+100;
        std::vector<char> vfilename(maxlength);
        char *filename = &vfilename[0];
        bool use_custom_format = false;
        if (strchr(argv[1],'%')) use_custom_format = true;
        strcpy(filename,argv[1]);
        char *a_ext = strrchr(filename,'.');
        if (!a_ext && !to_stdout) {
            e_printf("Problem saving animation to %s\n",filename);
            return 2;
        }
        for (Image& image : images) {
            if (!to_stdout) {
              if (use_custom_format) snprintf(filename,maxlength,argv[1],counter);
              else if (images.size() < 1000) sprintf(a_ext,"-%03d%s",counter,ext);
              else if (images.size() < 10000) sprintf(a_ext,"-%04d%s",counter,ext);
              else if (images.size() < 100000) sprintf(a_ext,"-%05d%s",counter,ext);
              else sprintf(a_ext,"-%08d%s",counter,ext);
              if (file_exists(filename) && !options.overwrite) {
                e_printf("Error: output file already exists: %s\nUse --overwrite to force overwrite.\n",filename);
                return 4;
              }
              if (!image.save(filename)) return 2;
            } else {
              if (!image.save(argv[1])) return 2;
            }
            counter++;
            v_printf(2,"    (%i/%i)         \r",counter,(int)images.size()); v_printf(4,"\n");
        }
    }
    // get rid of palette (should also do this in the non-standard/error paths, but being lazy here since the tool will exit anyway)
    images[0].clear();
    v_printf(2,"\n");
    return 0;
}