Exemple #1
0
int main(int argc, char **argv)
{
	if (argc != 3)
		abort_("Usage: program_name <file1> <file2>");

	png_bytep * row_pointers;
	png_bytep * row_pointers2;
	row_pointers = read_png_file(argv[1]);
	row_pointers2 = read_png_file(argv[2]);
	process_file(row_pointers, row_pointers2);

        return 0;
}
Exemple #2
0
int main(int argc, char **argv)
{
	if (argc != 3)
		abort_("Usage: program_name <file_in> <file_out>");

	// Read file + setup logic
	png_info_t* png_info = malloc(sizeof(png_info_t));
	FILE *fp = read_png_file_stats(argv[1], png_info);
	row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * png_info->height);
	for (int y=0; y < png_info->height; y++)
		row_pointers[y] = (png_byte*) malloc(png_get_rowbytes(png_info->png_ptr,png_info->info_ptr));
	row_pointers_post_bh = (png_bytep*) malloc(sizeof(png_bytep) * png_info->height);
	for (int y=0; y < png_info->height; y++)
		row_pointers_post_bh[y] = (png_byte*) malloc(png_get_rowbytes(png_info->png_ptr,png_info->info_ptr));
	row_pointers_post_bv = (png_bytep*) malloc(sizeof(png_bytep) * png_info->height);
	for (int y=0; y < png_info->height; y++)
		row_pointers_post_bv[y] = (png_byte*) malloc(png_get_rowbytes(png_info->png_ptr,png_info->info_ptr));
	read_png_file(&row_pointers, png_info, fp);
	// Distributed preparation logic
	// Distribute chunks of png
	int global_height = png_info->height;
	int global_width  = png_info->width;
	int local_min_height;
	int local_max_height;
	int local_min_width;
	int local_max_width;	
	if (world_rank < world_size) {
		local_min_height = global_height / world_size * (world_rank);
		local_max_height = (global_height / world_size * (world_rank + 1));
	} else { // last rank - takes extra
		local_min_height = global_height / world_size * (world_rank);
		local_max_height = global_height;
	}
	local_min_width = 0;
	local_max_width = global_width;

	distributed_info_t *distributed_info = malloc(sizeof(distributed_info_t));
	distributed_info->local_min_height = local_min_height;
	distributed_info->local_max_height = local_max_height;
	distributed_info->local_min_width = local_min_width;
	distributed_info->local_max_width = local_max_width;
	// Define Need and Have regions (N and H)
	// Blur logic
	blur(png_info, distributed_info); // region goes from local_min_height to local_max_height - 1
	// Write file + cleanup logic
	write_png_file(argv[2], &row_pointers_post_bv, png_info);

	free(distributed_info);
	for (int y = 0; y < png_info->height; y++) {
		free(row_pointers[y]);
		free(row_pointers_post_bh[y]);
		free(row_pointers_post_bv[y]);
	}
	free(row_pointers);
	free(row_pointers_post_bh);
	free(row_pointers_post_bv);
	free(png_info);

	return 0;
}
static void run( const char *input, const char *output )
{
    Huint   i;
    Huint   j;
    image   *img;
    clock_t start;
    clock_t end;
    double  ela;
    double  bytes;
    double  bandw;

    img = read_png_file( input );
    start = clock();
        send_image( img );
        recv_image( img );
    end = clock();
    write_png_file( output, img );
    
    ela = (double)(end - start);
    ela /= 2405516000.0;

    bytes = LOOPS * DATA * 8.0;
    bandw = bytes / ela;
    
    printf( "Processed %.2f bytes of data in %.2f seconds\n", bytes, ela );
    printf( "Bandwidth: %.2f bytes/sec\n", bandw );
}
Exemple #4
0
int main(int argc, char *argv[]) {

  read_png_file(argv[1]);
  process_png_file();
//  write_png_file(argv[2]);

  return 0;
}
Exemple #5
0
/*************************************************************************************************
 * roadmap_canvas_load_png_buffer()
 * Loads and returns the buffer of the png image ( RGBA 32 )
 */
static unsigned char* roadmap_canvas_load_png_buffer( const char *full_path, int *width, int *height, int *stride )
{

   unsigned char *buf = read_png_file( full_path, width, height, stride );

   if ( !buf ) return NULL;

   return buf;
}
Exemple #6
0
int main(int argc, char **argv)
{
	if (argc != 4)
		abort_("Usage: program_name <file_in> <file_out> <shift>");

	read_png_file(argv[1]);
	process_file(argv[3]);
	write_png_file(argv[2]);
}
bool loadThemeImage(char * path, char * description, int expectedWidth, int expectedHeight, u8 * alphaMask, int imageID, themeImage images[]) {
    themeImage * aThemeImage = &(images[imageID]);
    aThemeImage->exists = false;

    if (aThemeImage->spriteData) {
        free(aThemeImage->spriteData);
    }

    aThemeImage->spriteData = NULL;

//    free(aThemeImage->spriteData);

    if (!fileExists(path, &sdmcArchive)) {
        return false;
    }

    bool success = read_png_file(path);

    if (success) {
        if (pngWidth != expectedWidth || pngHeight != expectedHeight) {
            char error[256];
            sprintf(error, "%s must be %dx%d pixels", description, expectedWidth, expectedHeight);
            logText(error);
            return false;
        }
        else {
            u8 * out = process_png_file();

            if (out) {
                if (alphaMask) {
                    u8 * masked = malloc(expectedWidth*expectedHeight*4);
                    MAGFXApplyAlphaMask(out, alphaMask, masked, expectedWidth, expectedHeight, (bytesPerPixel==4));
                    aThemeImage->spriteData = masked;
                    free(out);
                    aThemeImage->hasAlpha = true;
                }
                else {
                    aThemeImage->spriteData = out;
                    aThemeImage->hasAlpha = (bytesPerPixel==4);
                }


                aThemeImage->exists = true;
                aThemeImage->w = expectedWidth;
                aThemeImage->h = expectedHeight;

                return true;
            }
            else {
                return false;
            }
        }
    }
    else {
        return false;
    }
}
static pngimage_t * getTheImage(void)
{
  char mystring[100];
  pngimage_t * theImage = (pngimage_t *) malloc(sizeof(pngimage_t));
  sprintf(mystring, "./img%03d.png", theCounter%3);
  read_png_file(theImage, mystring);
  theCounter ++;
  return theImage;
}
bool PngImageExt::Read(const char * filename)
{
	if (read_png_file(filename, &width, &height, &data) == 0)
	{
		if (CommandLineParser::Instance()->GetVerbose())
		{
			printf("FAILED TO OPEN PNG FILE: %s\n", filename);
		}
	}
	return true;
}
Exemple #10
0
int main(int argc, char **argv)
{
	if (argc != 3)
		abort_("Usage: program_name <file_in> <file_out>");
	// three of the above functions called here ....
	read_png_file(argv[1]);
	process_file();
	write_png_file(argv[2]);

        return 0;
}
Exemple #11
0
int main(int argc, char **argv)
{
	puts("running pixel-by-pixel checker");
	printf("file 1 : %s\n", argv[1]);
	printf("file 2 : %s\n", argv[2]);
	png_info_t *png_info_1 = malloc(sizeof(png_info_t));
	png_info_t *png_info_2 = malloc(sizeof(png_info_t));
	FILE* fp1 = read_png_file_stats(argv[1], png_info_1);
	FILE* fp2 = read_png_file_stats(argv[2], png_info_2);

	png_bytep* row_pointers_1 = (png_bytep*) malloc(sizeof(png_bytep) * png_info_1->height);
	for (int y = 0; y < png_info_1->height; y++)
		row_pointers_1[y] = (png_byte*) malloc(png_get_rowbytes(png_info_1->png_ptr,png_info_1->info_ptr));
	png_bytep* row_pointers_2 = (png_bytep*) malloc(sizeof(png_bytep) * png_info_2->height);
	for (int y = 0; y < png_info_2->height; y++)
		row_pointers_2[y] = (png_byte*) malloc(png_get_rowbytes(png_info_2->png_ptr,png_info_2->info_ptr));

	read_png_file(&row_pointers_1, png_info_1, fp1);
	read_png_file(&row_pointers_2, png_info_2, fp2);

	assert(png_info_1->height == png_info_2->height);
	assert(png_info_1->width  == png_info_2->width);

	int height =  png_info_1->height;
	int width  =  png_info_1->width;
	for (int y = 0; y < height; y++) {
		png_byte* row_1 = row_pointers_1[y];
		png_byte* row_2 = row_pointers_2[y];
		for (int x = 0; x < width; x++) {
			png_byte* ptr_1 = &(row_1[x*3]);
			png_byte* ptr_2 = &(row_2[x*3]);
			assert(ptr_1[0] == ptr_2[0]);
			assert(ptr_1[1] == ptr_2[1]);
			assert(ptr_1[2] == ptr_2[2]);
		}
	}

	return 0;
}
static RoadMapImage load_png (const char *full_name) {

   int width;
   int height;
   int stride;

   unsigned char *buf = read_png_file(full_name, &width, &height, &stride);

   if (!buf) return NULL;

   RoadMapImage image =  new roadmap_canvas_image();
   image->rbuf.attach (buf, width, height, stride);

   return image;
}
static Util::PngImageHolder load_png(const char* filename) {
    int width, height, color_type;
    uint8_t* png_data = read_png_file(filename, &width, &height, &color_type);
    //printf("width %d height %d \n", width, height);
    if(color_type == 0) {
        Eigen::MapRMatUb tmp(bwa_to_bw_in_place((uint8_t*)png_data, height * width), height, width);
        return Util::PngImageHolder(tmp);
    } else if(color_type == 4) {
        Eigen::MapRMatUb tmp((uint8_t*) png_data, height, width);
        return Util::PngImageHolder(tmp);
    } else if (color_type == 6){
        Eigen::MapRMatVec4Ub tmp((Eigen::Vector4Ub*) png_data, height, width);
        return Util::PngImageHolder(tmp);
    } else {
        throw std::runtime_error("Unknown color_type");
    }
}
Exemple #14
0
int main(int argc, char **argv)
{
	if (argc != 3)
		abort_("Usage: program_name <file_in> <file_out>");

	read_png_file(argv[1]);
	process_file(argv[2]);
	write_png_file("output.png");
/*
	int y;
	for (y=0; y<height; y++)
		free(row_pointers[y]);
	free(row_pointers);
*/

	return 0;
}
void gui_load_image_png(const char *filename, gui_image_t *image_data)
{
    const int area_height = GET_GUI_AREA_HEIGHT(&image_data->area);
    const int area_width  = GET_GUI_AREA_WIDTH(&image_data->area);
    png_image_data_t png_image_data;

    read_png_file(filename, &png_image_data, area_width, area_height);

    /* see if area has to be resized, because of any of these reasons:
        a) the image is smaller than the area
        b) the area is 0 (auto size for the background)
    */
    if (area_height > png_image_data.height || area_height <= 0)
        SET_GUI_AREA_HEIGHT(&image_data->area, png_image_data.height);
    if (area_width > png_image_data.width || area_width <= 0)
        SET_GUI_AREA_WIDTH(&image_data->area, png_image_data.width);

    image_data->image = png_image_data.image4c;
}
Exemple #16
0
int main(int argc, char **argv) {
  if (argc < 2 || argc > 3) {
    abort_("Usage: png2tx file_in [file_out]");
  }

  struct PNG png = read_png_file(argv[1]);
  char *output_filename;
  if (argc == 3) {
    output_filename = argv[2];
  } else {
    output_filename = argv[1];
    int len = strlen(output_filename);
    output_filename[len - 3] = 't';
    output_filename[len - 2] = 'x';
    output_filename[len - 1] = '\0';
  }
  write_tx_file(png, output_filename);
  free_data(png);

  return 0;
}
// ------------------------------------------------------------------------------------------------
//
//
struct T_FRAME *Sprites_CreateFrame(char *ruta)
{
  int bpp, pitchx_bytes, pitchx_pixels, pitchy_pixels ;
  struct T_FRAME *frame ;

  ASSERT(ruta) ;

  frame = (struct T_FRAME *) malloc(sizeof(struct T_FRAME)) ;

  if(frame != NULL) {

    memset(frame, 0, sizeof(struct T_FRAME)) ;

    // Pedimos a la rutina de carga de PNG que lea el fichero de la ruta pasada como parámetro, aloje memoria para
    // los píxels, la llene con la imagen y nos rellene las variables de tamaños del sprite
    frame->pixels = (unsigned long *) read_png_file(ruta, &bpp, &frame->tamx, &frame->tamy, &pitchx_bytes, &pitchx_pixels, &pitchy_pixels) ;

    if(frame->pixels != NULL) {

      // Si la cosa ha salido bien pedimos a la SDL que le diga al hardware que vamos a usar estos píxels para dibujar
      frame->surface = SDL_CreateRGBSurfaceFrom(frame->pixels,
                                                frame->tamx, frame->tamy,
                                                32,
                                                frame->tamx * 4,
                                                VIDEO_MASCARA_R, VIDEO_MASCARA_G, VIDEO_MASCARA_B, VIDEO_MASCARA_A
                                               ) ;

      // Creamos el handle de textura de hardware
      frame->texture = SDL_CreateTextureFromSurface(g_Video.renderer, frame->surface) ;

      // Indicamos al hardware de que este sprite va a necesitar cálculos de alpha blending (para que no se vea el rectángulo donde no hay dibujo)
      SDL_SetTextureBlendMode(frame->texture, SDL_BLENDMODE_BLEND) ;
    }
  }

  return frame ;
}
Exemple #18
0
int main(int argc, char **argv) {
	// Argument parsing
	char usage[256];
	char *pgrm = argv[0];
	sprintf(usage, "\
Usage: %s -e [message/file] [image]\n\
       %s -d [image]\n\
       %s -s [image(s)]\
", pgrm, pgrm, pgrm);

	if (argc == 1)
		Error(usage);

	char *options = "\n\
Options:\n\
  -h  Show this help message and exit\n\
  -e  Encode data into image\n\
  -d  Decode data from image\n\
  -s  Space available in image(s) (the higher the\n\
      resolution, the more space available)\n\
  -o  When encoding, use this filename for the\n\
      new image\
";
	char *e_arg = 0,
	     *d_arg = 0,
	     *s_arg = 0,
	     *o_arg = 0;
	int c;
	opterr = 0;

	while ((c = getopt(argc, argv, "hd:e:s:o:")) != -1) {
		switch(c) {
			case 'h':
				puts(usage);
				puts(options);
				return 0;
				break;
			case 'e':
				e_arg = optarg;
				break;
			case 'd':
				d_arg = optarg;
				break;
			case 's':
				s_arg = optarg;
				break;
			case 'o':
				o_arg = optarg;
				break;
			case '?':
				break;
			default:
				Error(usage);
		}
	}

	char (*last_args)[256] = malloc(256 * sizeof(*last_args));
	int index = s_arg ? 1 : 0;
	if (optind < argc) {
		while (optind < argc)
			sprintf(last_args[index++], "%s", argv[optind++]);
	}
	if (s_arg)
		sprintf(last_args[0], "%s", s_arg);

	if (e_arg || d_arg) {
		if (e_arg && !index)
			Error(usage);

		// Prompt for password
		char *pass = getpass("Password for encoding:");
		if (strcmp(pass, "") == 0)
			Error("No password entered.");

		// Prepare encryption and decryption:
		// The salt paramter is used as a salt in the derivation:
		// it should point to an 8 byte buffer or NULL if no salt is used.
		unsigned char salt[] = {1, 2, 3, 4, 5, 6, 7, 8};

		unsigned char *key_data = (unsigned char *) pass;
		int key_data_len = strlen(pass);

		// Gen key and iv. init the cipher ctx object
		if (aes_init(key_data, key_data_len, salt, &en, &de))
			Error("Error initializing AES cipher");
	}
	// Encode
	if (e_arg)
		encode(e_arg, last_args[0], o_arg);

	// Decode
	else if (d_arg)
		decode(d_arg);

	// Print space in image(s)
	else if (s_arg) {
		puts("Space available in image(s):");
		for (int i = 0; i < index; i++) {
			read_png_file(last_args[i]);
			int space = (width * height) * (3.0f / 4.0f);
			space -= 256+ AES_BLOCK_SIZE +12; // 256 for filename
			char *rspace = byteconvert(space);
			printf("%s: %s\n", basename(last_args[i]), rspace);
			free(rspace);
		}
	}
	else
		Error(usage);
	if (opterr)
		return 1;

	// Cleanup
	free(last_args);
	aes_clean();
	png_clean();

	return 0;
}
Exemple #19
0
void decode(char *img) {
	unsigned char *data, *dec_data;
	unsigned char prefix[16];
	int pindex = 0, dindex = 0;

	read_png_file(img);

	int found_prefix = 0, file = 0;
	int len = 0; // the length of the data to find
	// Main loop through pixels
	int pixel_loc = 3; // start with 4th one (0, 1, 2, 3)
	int x, y;
	png_byte* pixel;
	for (;; pixel_loc += 4) {
		int temp_data[3] = {0, 0, 0}; // 3 bytes of data at a time (stored as ints,
			// later cast to char)

		// Loop for each color component (and byte of data)
		for (int j = 0; j < 3; j++, pixel_loc += 4) {
			// reset to continue looping through the same pixels every time by doing += 4
			// going through them backwards this time to regain the data

			for (int p = 0; p < 4; p++, pixel_loc--) {
				x = pixel_loc % width, y = pixel_loc / width;
				pixel = &(row_pointers[y][x*3]);

				// slowly expand and add room for 2 bits of data every time
				temp_data[j] <<= 2;
				temp_data[j] |= pixel[j] & 3; // adding on 2 bits
					// & 3 is to only get the last 2 bits on the end
					// (After all, the data is only stored in the least 2 significant
					// bits of each color component of each pixel)
			}
		}

		if (found_prefix) {
			// Stop before adding too much data
			// We can't go over the len, this removes any padded null bytes
			// just to fit into the image evenly
			if (len - (dindex + 3) <= 0) {
				for (int k = 0; dindex < len; k++)
					data[dindex++] = (unsigned char)temp_data[k];
				break; // Found all the data; stop looping
			}
			else {
				for (int k = 0; k < 3; k++)
					data[dindex++] = (unsigned char)temp_data[k];
			}
		}
		else {
			// We're looking for the prefix here
			// First, add the data found so far into the prefix var
			for (int k = 0; k < 3; k++)
				prefix[pindex++] = (unsigned char)temp_data[k];

			// Now check to see if we've found the whole prefix yet
			// We should find it within 16 chars, so 6 iterations (3 chars added each time)
			int l;
			for (l = 0; l < pindex; l++) {
				if (prefix[l] == '<') {
					found_prefix = 1;
					break;
				}
				else if (prefix[l] == '>') {
					found_prefix = file = 1;
					break;
				}
				else {
					// The prefix starts with the length
					// Look for the length, if we can't find it then there's no data here
					len *= 10;
					int digit = prefix[l] - '0'; // Ascii to int (this works for digits)
					if (digit < 0 || digit > 9)
						Error("Hidden data either nonexistent or corrupted");
					len += digit;
				}
			}

			// If we found it, transfer any trailing data from the prefix to the main data
			// Either way, allocate memory to the main data var now
			if (found_prefix) {
				data = malloc(len);

				// Transfer remaining data if there is any
				if (l < pindex -1) {
					// Skip one, the ending of the prefix
					for (l = l + 1; l < pindex; l++)
						data[dindex++] = prefix[l];
				}
			}
			else {
				len = 0; // reset the len if we haven't found the whole number of it yet
				if (pindex >= 16)
					Error("Hidden data either nonexistent or corrupted");
					// Prefix is never this long, just quit at this point
			}
		}
	}

	// Decrypt the data
	dec_data = aes_decrypt(&de, data, &len);
	free(data); // Done with this

	// Output decrypted data
	if (file) {
		int found = 0, i;
		for (i = 0; i <= 256; i++) {
			if (dec_data[i] == ':') {
				found = 1;
				break;
			}
		}
		if (!found)
			Error("Could not find filename from encrypted data");
		char *filename = malloc(i); // i is the lenght of the filename
		memcpy(filename, dec_data, i);

		FILE *fp = fopen(filename, "wb");
		if (!fp)
			Error("File %s could not be opened for writing", filename);

		printf("Saving data to %s\n", filename);
		fwrite(dec_data+i+1, 1, len-i-1, fp); // 1 for the colon
		fclose(fp);

		free(filename);
	}
	else
		printf("%s\n", dec_data);

	free(dec_data); // Done
}
Exemple #20
0
void encode(char *msg, char *img, char *out_filename) {
	unsigned char *data, *enc_data, *final_data;
	char *filename = 0;
	int len, plen, final_len;

	FILE *fp = fopen(msg, "rb");
	// Not saving the last null byte (in legal C strings) in either case
	// because all the chars are going into the image
	if (!fp) {
		len = strlen(msg);
		data = malloc(len);
		memcpy(data, msg, len);
	}
	else {
		filename = basename(msg);
		int fplen = strlen(filename)+1; // 1 for the colon
		char fprefix[fplen];
		sprintf(fprefix, "%s:", filename);

		// Read the file to data
		fseek(fp, 0, SEEK_END);
		int file_len = ftell(fp);
		len = fplen + file_len;
		rewind(fp);

		data = malloc(len);

		// all chars are 1 byte
		int read_size = fread(data, 1, file_len, fp);
		if (file_len != read_size)
			Error("Error reading file");

		// Prepend filename with colons (filenames can't have colons)
		// Filename gets encrypted too
		memmove(data+fplen, data, file_len);
		memcpy(data, fprefix, fplen);
	}
	fclose(fp);

	// Encrypt the data
	enc_data = aes_encrypt(&en, data, &len);
	// len gets updated here ^ to the new len of the encrypted data
	free(data); // Don't need this anymore

	plen = digits(len)+1;
	char prefix[plen];
	sprintf(prefix, filename ? "%d>" : "%d<", len);
	// The different symbols are to differentiate between file data and plaintext

	final_len = plen + len;
	int padding = 3 - (final_len % 3); // Data needs to be divisible by 3 before being put
		// into the image
	int padded_len = final_len + padding;
	final_data = malloc(padded_len);
	memcpy(final_data, enc_data, len);
	free(enc_data); // All we need now is the final data

	// Prepend the encrypted data with the prefix of how long
	// it is so we know where to stop when decoding
	memmove(final_data+plen, final_data, len);
	memcpy(final_data, prefix, plen);
	// Last, add the padding of null bytes to make it divisible by 3
	// Note: this will get removed in the end because
	// we keep the size not including the padding. We need to have it divisibile by 3 because
	// if we have 2 bits left of data, we need to store it in 1 whole pixel, which holds
	// 6 possible bits of information
	for (int i = final_len; i < padded_len; i++)
		final_data[i] = '\0';

	// Checking if possible
	read_png_file(img);
	int space = (width * height) * (3.0f / 4.0f);
	if (padded_len > space) { // Make sure there is enough space in the image for the data
		puts("Not enough space in image.");
		char *rspace;
		rspace = byteconvert(padded_len);
		printf("Data size: %s\n", rspace);
		free(rspace);

		rspace = byteconvert(space);
		printf("Space available: %s\n", rspace);
		free(rspace);

		exit(1);
	}


	// Loop through all the data, 3 bytes at a time,
	// putting every 3 bytes into groups of 4 pixels
	// (8 bits for 3 bytes is 24 total bits, 6 bits for each of
	// 4 pixels (matching of total 24))
	int pixel_loc = 0;
	int x, y;
	png_byte* pixel;
	for (int i = 0; i < padded_len; i += 3, pixel_loc += 4) {
		// next group of pixels every loop, so add 4 each time

		// Loop for each color component and for each byte of data
		// (3 of each)
		// Each byte has 8 bits, 2 of each go into each of the 4 pixels
		for (int j = 0; j < 3; j++, pixel_loc -= 4) {
			// reset to continue looping through the same pixels every time by doing -= 4

			// Loop for each of 4 pixels to put the data into
			for (int p = 0; p < 4; p++, pixel_loc++) {
				x = pixel_loc % width, y = pixel_loc / width;
				pixel = &(row_pointers[y][x*3]);

				// j for color component
				// Replace last 2 bits with zeros
				pixel[j] &= ~3;

				int sh = p * 2;
				// Add 2 bits of data at a time
				pixel[j] |= ((int)final_data[i + j] & (3 << sh)) >> sh;
				// & 3 gets only the last 2 bits of the data (1 byte) because
				// 3 is 00000011 in binary,
				// 3 << 2 is 00001100, 3 << 4 is 00110000, etc
			}
		}
	}
	// Save the image with the data inside it
	// (use output filename if specified, otherwsie just "new-image.png")
	if (out_filename)
		write_png_file(out_filename);
	else
		write_png_file("new-image.png");


	free(final_data); // Done with this
}
Exemple #21
0
int main(int argc, char **argv) {
    int shader = 0;

    if (argc >= 3){
        if(sscanf (argv[2], "%i", &anim_delay)!=1){
            printf ("Error, delay must be an integer \n");
            return 0;
        }
    }

    int newbrightness = 0;
    if (argc >= 4){
        if(sscanf (argv[3], "%i", &newbrightness)!=1){
            printf ("Error, brightness must be an integer \n");
            return 0;

        }else{
            setBrightness(newbrightness);
        }
    }
    if (argc == 2){
        if(sscanf (argv[1], "%i", &newbrightness)==1){
            setBrightness(newbrightness);
            shader = 1;
        }
    }

    int i;
    for (i = 0; i < 64; i++) {
        struct sigaction sa;
        memset(&sa, 0, sizeof(sa));
        sa.sa_handler = unicorn_exit;
        sigaction(i, &sa, NULL);
    }

    setvbuf(stdout, NULL, _IONBF, 0);

    if(ws2811_init(&ledstring))
    {
        return -1;
    }

    clearLEDBuffer();

    if(argc < 2){
        shader = 1;
    }

    if(shader){
        run_shader();
    }else{

        read_png_file(argv[1]);
        while(1){
            process_file();
            if (height/8 == 1){
                break;
            }
        }

    }

    unicorn_exit(0);

    return 0;
}
int main(int argc, char **argv)
{
  int c;
  int num_threads = 4;
  int img = 1;
  bool received_all_fragments = false;
  bool * received_fragments = calloc(N, sizeof(bool));

  while ((c = getopt (argc, argv, "t:i:")) != -1) {
    switch (c) {
    case 't':
      num_threads = strtoul(optarg, NULL, 10);
      if (num_threads == 0) {
	printf("%s: option requires an argument > 0 -- 't'\n", argv[0]);
	return -1;
      }
      break;
    case 'i':
      img = strtoul(optarg, NULL, 10);
      if (img == 0) {
	printf("%s: option requires an argument > 0 -- 'i'\n", argv[0]);
	return -1;
      }
      break;
    default:
      return -1;
    }
  }

  CURL *curl;
  CURLcode res;
  png_structp png_ptr;
  png_infop info_ptr;
  
  png_byte * output_buffer = calloc(WIDTH*HEIGHT*4, sizeof(png_byte));

  curl = curl_easy_init();
  if (!curl)
    abort_("[main] could not initialize curl");

  char * url = malloc(sizeof(char)*strlen(BASE_URL)+4*5);
  png_bytep input_buffer = malloc(sizeof(png_byte)*BUF_SIZE);

  struct bufdata bd; 
  bd.buf = input_buffer; 
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bd);

  struct headerdata hd; hd.received_fragments = received_fragments;
  curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hd);
  curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_cb);

  // request appropriate URL
  sprintf(url, BASE_URL, img);
  printf("requesting URL %s\n", url);
  curl_easy_setopt(curl, CURLOPT_URL, url);

  do {
    png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (!png_ptr)
      abort_("[main] png_create_read_struct failed");

    // reset input buffer
    bd.len = bd.pos = 0; bd.max_size = BUF_SIZE;

    // do curl request; check for errors
    res = curl_easy_perform(curl);
    if(res != CURLE_OK)
      abort_("[main] curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    // read PNG (as downloaded from network) and copy it to output buffer
    png_bytep* row_pointers = read_png_file(png_ptr, &info_ptr, &bd);
    paint_destination(png_ptr, row_pointers, hd.n*BUF_WIDTH, 0, output_buffer);

    // free allocated memory
    for (int y=0; y<BUF_HEIGHT; y++)
      free(row_pointers[y]);
    free(row_pointers);
    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);

    // check for unreceived fragments
    received_all_fragments = true;
    for (int i = 0; i < N; i++)
      if (!received_fragments[i])
        received_all_fragments = false;
  } while (!received_all_fragments);
  free(url);
  free(input_buffer);

  curl_easy_cleanup(curl);

  // now, write the array back to disk using write_png_file
  png_bytep * output_row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * HEIGHT);

  for (int i = 0; i < HEIGHT; i++)
    output_row_pointers[i] = &output_buffer[i*WIDTH*4];

  write_png_file("output.png", output_row_pointers);
  free(output_row_pointers);
  free(output_buffer);
  free(received_fragments);
  
  return 0;
}
int main(int argc, char **argv)
{
	int c;
	int num_handle = 4;
	int img = 1;
	bool received_all_fragments = false;
	bool * received_fragments = calloc(N, sizeof(bool));
	
	bool * tempBoolCheck = calloc(N, sizeof(bool));

	while ((c = getopt (argc, argv, "t:i:")) != -1) {
		switch (c) {
		case 't':
			num_handle = strtoul(optarg, NULL, 10);
			if (num_handle == 0) {
				printf("%s: option requires an argument > 0 -- 't'\n", argv[0]);
				return -1;
			}
			break;
		case 'i':
			img = strtoul(optarg, NULL, 10);
			if (img == 0) {
				printf("%s: option requires an argument > 0 -- 'i'\n", argv[0]);
				return -1;
			}
			break;
		default:
			return -1;
		}
	}


	png_structp png_ptr[num_handle];
	png_infop info_ptr[num_handle];

	png_byte * output_buffer = calloc(WIDTH*HEIGHT*4, sizeof(png_byte));

  //Lock for pthread
  // pthread_mutex_init(&lock, NULL);
   pthread_mutex_init(&lock_hd, NULL);
  // pthread_mutex_init(&lock_read_cb, NULL);

	char * url = malloc(sizeof(char)*strlen(BASE_URL)+4*5);
	char * url_2 = malloc(sizeof(char)*strlen(BASE_URL_2)+4*5);
	char * url_3 = malloc(sizeof(char)*strlen(BASE_URL_3)+4*5);
	
	png_bytep input_buffer[num_handle];

	struct bufdata bd[num_handle];
	struct headerdata hd[num_handle];
	for(int i = 0; i< num_handle; i++)
	{
		input_buffer[i] = malloc(sizeof(png_byte)*BUF_SIZE);
		bd[i].buf = input_buffer[i];
		hd[i].received_fragments = received_fragments;
	}
	// request appropriate URL
	sprintf(url, BASE_URL, img);
	sprintf(url_2, BASE_URL_2, img);
	sprintf(url_3, BASE_URL_3, img);
	printf("requesting URL %s\n", url);

	CURL *handles[num_handle];
	CURLM *multi_handle;
	CURLcode res = 0;
	int running_handles;
	
	CURLMsg *msg; /* for picking up messages with the transfer status */
	int msgs_left; /* how many messages are left */
	
	for (int i = 0; i < num_handle; i++)
	{
		handles[i] = curl_easy_init();
		if(!handles[i])
		{
			abort_("[main] could not initialize curl");
		}
		curl_easy_setopt(handles[i], CURLOPT_WRITEFUNCTION, write_cb);
		curl_easy_setopt(handles[i], CURLOPT_WRITEDATA, &(bd[i]));
		curl_easy_setopt(handles[i], CURLOPT_HEADERDATA, &hd[i]);
		curl_easy_setopt(handles[i], CURLOPT_HEADERFUNCTION, header_cb);
		if(i%3 == 0)
		{
			curl_easy_setopt(handles[i], CURLOPT_URL, url);
		}
		else if(i%3 == 1)
		{
			curl_easy_setopt(handles[i], CURLOPT_URL, url_2);
		}
		else
		{
			curl_easy_setopt(handles[i], CURLOPT_URL, url_3);
		}
		
		//keep pointer to array index
		//curl_easy_setopt(handles[i], CURLOPT_PRIVATE, url);
		// reset input buffer
		bd[i].len = bd[i].pos = 0; bd[i].max_size = BUF_SIZE;
	}



	/* init a multi stack */
	multi_handle = curl_multi_init();
	/* add the individual transfers */
	for (int i = 0; i < num_handle; i++)
	{
		curl_multi_add_handle(multi_handle, handles[i]);
	}
		

		// do curl request; check for errors
		// res = curl_easy_perform(curl);
		// if(res != CURLE_OK)
		// abort_("[main] curl_easy_perform() failed: %s\n",
		// curl_easy_strerror(res));
		

		//curl_multi_perform(multi_handle, &running_handles);
		
		do
		{
			int numfds=0;
			res = curl_multi_wait(multi_handle, NULL, 0, MAX_WAIT_MSECS, &numfds);
			if(res != CURLM_OK) {
				fprintf(stderr, "error: curl_multi_wait() returned %d\n", res);
				return EXIT_FAILURE;
			}
			curl_multi_perform(multi_handle, &running_handles);
 #ifdef _DEBUG_1_
	//printf("\n## numfds: %d, num_handle: %d\n", numfds, num_handle);
	fflush(stdout);
#endif
/* If the amount of running_handles is changed from the previous call (or is less than the amount of easy handles you've added to the multi handle), you know that there is one or more transfers less "running". You can then call curl_multi_info_read to get information about each individual completed transfer, and that returned info includes CURLcode and more. If an added handle fails very quickly, it may never be counted as a running_handle.*/
			if(running_handles < num_handle)
			{
#ifdef _DEBUG_1_
	printf("\nIn IF:, running_handles: %d\n", running_handles);
	fflush(stdout);
#endif
		
				while((msg = curl_multi_info_read(multi_handle, &msgs_left)))
				{
					
#ifdef _DEBUG_1_
	printf("\nmsgs_left:%d\n", msgs_left);
	fflush(stdout);
#endif
					if (msg->msg == CURLMSG_DONE)
					{
						CURL* replaceHandle = msg->easy_handle;
						
												
						curl_multi_remove_handle(multi_handle, replaceHandle);
						curl_multi_add_handle(multi_handle, replaceHandle);
						
						
						int iBdIndex = -1;
						for (int i = 0; i < num_handle; i++)
						{
							if (handles[i] == replaceHandle)
							{
								iBdIndex = i;
#ifdef _DEBUG_1_
	printf("\nfound handle, i:%d", i);
	fflush(stdout);
#endif
								break;
							}
						}
						
						
						res = msg->data.result;
						if(res != CURLE_OK)
						{
#ifdef _DEBUG_1_
	printf("\nContinued in the while loop, res is %d", res);
	fflush(stdout);
#endif
							continue;
							//abort_("[main] curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
						}
//check for dup

								// if (received_fragments[hd[iBdIndex].n])
								// {
// #ifdef _DEBUG_1_
		// printf("\nContinued in the while loop, dup for %d", hd[iBdIndex].n);
		// fflush(stdout);
// #endif
									// continue;
								// }
						
						
	//pthread_mutex_lock(&lock);
						png_ptr[iBdIndex] = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
						if (!png_ptr[iBdIndex])
						{
							abort_("[main] png_create_read_struct failed");
						}
  // Write to the shared resource .
						
						// read PNG (as downloaded from network) and copy it to output buffer
#ifdef _DEBUG_1_
	printf("\nindex: %d, bd->pos: %d, bd->len: %d, hd.n: %d\n",iBdIndex, bd[iBdIndex].pos, bd[iBdIndex].len,hd[iBdIndex].n);
	fflush(stdout);
#endif

						png_bytep* row_pointers = read_png_file(png_ptr[iBdIndex], &info_ptr[iBdIndex], &bd[iBdIndex]);
						paint_destination(png_ptr[iBdIndex], row_pointers, hd[iBdIndex].n*BUF_WIDTH, 0, output_buffer);
						// reset input buffer
						bd[iBdIndex].len = bd[iBdIndex].pos = 0; bd[iBdIndex].max_size = BUF_SIZE;

						//bd[1].len = bd[1].pos = 0; bd[1].max_size = BUF_SIZE;
						// free allocated memory
						for (int y=0; y<BUF_HEIGHT; y++)
						{
							free(row_pointers[y]);
						}
						free(row_pointers);
						png_destroy_read_struct(&png_ptr[iBdIndex], &info_ptr[iBdIndex], NULL);

						// check for unreceived fragments
						received_all_fragments = true;
						for (int i = 0; i < N; i++)
						{
							if (!received_fragments[i])
							{
								received_all_fragments = false;
							}
						}
						
						//tempBoolCheck
						tempBoolCheck[hd[iBdIndex].n]=true;
						for(int i = 0; i < N; i++)
						{
							if(!tempBoolCheck[i])
							{
								received_all_fragments=false;
							}
						}
	//pthread_mutex_unlock(&lock);
					}
					else
					{
						//Error, replace the handle
						#ifdef _DEBUG_1_
	printf("\nError, replace the handle\n");
	fflush(stdout);
#endif
						CURL* replaceHandle = msg->easy_handle;
						curl_multi_remove_handle(multi_handle, replaceHandle);
						curl_multi_add_handle(multi_handle, replaceHandle);
						for (int i = 0; i < num_handle; i++)
						{
							if (handles[i] == replaceHandle)
							{
								bd[i].len = bd[i].pos = 0; bd[i].max_size = BUF_SIZE;
								break;
							}
						}
					}
					//break;
				}
			}

		} while(!received_all_fragments);
		
	free(url);
	free(url_2);
	free(url_3);
	//free(input_buffer);
	

	//curl_easy_cleanup(curl);
	curl_multi_cleanup(multi_handle);
	/* Free the CURL handles */
	for (int i=0; i<num_handle; i++)
	{
		free(input_buffer[i]);
		curl_easy_cleanup(handles[i]);
	}

	// now, write the array back to disk using write_png_file
	png_bytep * output_row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * HEIGHT);

	for (int i = 0; i < HEIGHT; i++)
		output_row_pointers[i] = &output_buffer[i*WIDTH*4];

	write_png_file("output.png", output_row_pointers);
	free(output_row_pointers);
	free(output_buffer);
	free(received_fragments);
	
	  //destory lock
  	// pthread_mutex_destroy(&lock);
	 pthread_mutex_destroy(&lock_hd);
	// pthread_mutex_destroy(&lock_read_cb);

	return 0;
}
Exemple #24
0
int window_loop() {

    GLFWwindow* window;

    window = glfwCreateWindow(640, 480, "Shader test", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return 0;
    }

    glfwMakeContextCurrent(window);
    //glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetKeyCallback(window, key_callback);

    //glfwSetCursorPosCallback(window, cursor_callback);

    //glEnable(GL_CULL_FACE);
    glEnable(GL_LIGHT0);
    //glEnable(GL_DEPTH_TEST);
//	glEnable(GL_LIGHTING);

//	glEnable(GL_BLEND);
    // glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD);
    // glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO);
//	glEnable(GL_NORMALIZE);
    //glEnable(GL_NORMALIZE);
    glEnable(GL_TEXTURE_2D);
//glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

    // glPolygonMode( GL_FRONT, GL_LINE );
    // glPolygonMode( GL_BACK, GL_POINT );

//	glEnable(GL_COLOR_MATERIAL);

    cudaGLSetGLDevice(0);


    double ot, nt = glfwGetTime();

    GLuint textureID[6];
    glGenTextures(1, textureID);

    png_bytep* tex1;
    int lw, lh;
    printf("Laddar PNG\n");
    read_png_file("/srv/texturer/Slate Tiles - (Normal Map).png", &tex1, &lw, &lh);

    printf("Laddade textur som är %i x %i pixelitaz stor.\n", lw, lh);

    float3* normal_map = NULL;

    size_t normal_map_bufferSize = 1024 * 1024 * sizeof(float3);
    cudaMalloc( &normal_map, normal_map_bufferSize );
    float3* host_normal_map = calloc(1024*1024, sizeof(float3));



    glBindTexture(GL_TEXTURE_2D, textureID[0]);

    for (int y=0; y<1024; y++) {
        for (int x=0; x<1024; x++) {
            host_normal_map[y*1024+x].x = (float)(tex1[y][x*3+0]-127) / 127;
            host_normal_map[y*1024+x].y = (float)(tex1[y][x*3+1]-127) / 127;
            host_normal_map[y*1024+x].z = (float)(tex1[y][x*3+2]-127) / 127;
        }
    }

    cudaMemcpy(normal_map, host_normal_map, normal_map_bufferSize, cudaMemcpyHostToDevice);

    glTexImage2D(GL_TEXTURE_2D, 0,GL_RGBA, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);


    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    double cx, cy;
    glfwGetCursorPos(window, &cx, &cy);


    struct cudaGraphicsResource *test1;
    int r1=cudaGraphicsGLRegisterImage(&test1, textureID[0], GL_TEXTURE_2D, cudaGraphicsMapFlagsWriteDiscard);
    printf("r1=%i\n");

    uchar4* g_dstBuffer = NULL;

    size_t bufferSize = 1024 * 1024 * sizeof(uchar4);
    cudaMalloc( &g_dstBuffer, bufferSize );

    cudaMemset(g_dstBuffer, 0x7F, bufferSize);	//Make texture gray to start with

    printf("cuda alloc: %p\n", g_dstBuffer);

    double fps_time =0 ;
    int fps_count=0;

    while (!glfwWindowShouldClose(window))
    {

        ot=nt;
        nt =glfwGetTime();
        float dt = nt - ot;


        fps_time += dt;
        fps_count++;

        if (fps_time > 1) {
            printf("FPS: %f\n", fps_count/fps_time);
            fps_time=0;
            fps_count =0;

        }




        int width, height;
        glfwGetFramebufferSize(window, &width, &height);



        glClearColor(0.0, 0.0, 0.1, 1.0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glViewport(0, 0, width-1, height-1);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        glOrtho(0, width-1, height-1, 0,0,1);

        glMatrixMode(GL_MODELVIEW);


        for (int testa_flera=0; testa_flera<16; testa_flera++) {

            glLoadIdentity();
            glTranslatef(testa_flera*150, testa_flera*50+100, 0);
            glRotatef(testa_flera*10, 0,0,1);
            glTranslatef(0, testa_flera*50, 0);
            glScalef(0.5, 0.5, 0.5);


            float ta = fmod(nt+testa_flera*0.2, M_PI*2.0);
            float tb = fmod(nt*0.7+testa_flera*0.4, M_PI*2.0);
            float tc = fmod(nt*0.3+testa_flera*0.1, M_PI*2.0);
            float3 cam_vec = {sin(ta), sin(tb), sin(tc)};

            int res=cudaGraphicsMapResources(1, &test1, 0);
            //printf("res: %i (succ=%i)\n", res, cudaSuccess);
            struct cudaArray* dstArray = 0;
            int r2 = cudaGraphicsSubResourceGetMappedArray( &dstArray, test1, 0, 0 );
            //printf("r2: %i array: %p\n", r2, dstArray);

            first_test(g_dstBuffer, normal_map, cam_vec, 1024, 1024);

            cudaMemcpyToArray( dstArray, 0, 0, g_dstBuffer, bufferSize, cudaMemcpyDeviceToDevice );

            cudaGraphicsUnmapResources(1, &test1, 0);

            glColor3f(1,1,1);
            glBegin(GL_QUADS);
            glTexCoord2f(0,0);
            glVertex3f(0,0,0);

            glTexCoord2f(1,0);
            glVertex3f(511,0,0);

            glTexCoord2f(1,1);
            glVertex3f(511,511,0);

            glTexCoord2f(0,1);
            glVertex3f(0,511,0);
            glEnd();



        }






        glfwSwapBuffers(window);
        glfwPollEvents();
    }


    glfwDestroyWindow(window);

    glfwTerminate();
    return(EXIT_SUCCESS);
}
void * thread_callback(void * shared_resource_void){
	struct shared_res * shared_resource = (struct shared_res*)shared_resource_void;
	CURL *curl;
	CURLcode res;
	png_structp png_ptr;
	png_infop info_ptr;
	bool received_all_fragments = false;
	curl = curl_easy_init();
	if (!curl)
	abort_("[main] could not initialize curl");

	char * url = malloc(sizeof(char)*strlen(BASE_URL1)+4*5);
	png_bytep input_buffer = malloc(sizeof(png_byte)*BUF_SIZE);

	struct bufdata bd;
	bd.buf = input_buffer;
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bd);

	struct headerdata hd; hd.received_fragments = shared_resource->received_fragments;
	curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hd);
	curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_cb);

	// request appropriate URL
	printf("server count = %d\n", shared_resource->server_count);
	sprintf(url, BASE_URL[shared_resource->server_count], shared_resource->img);

	printf("requesting URL %s\n", url);
	curl_easy_setopt(curl, CURLOPT_URL, url);

	do {
	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (!png_ptr)
	  abort_("[main] png_create_read_struct failed");

	// reset input buffer
	bd.len = bd.pos = 0; bd.max_size = BUF_SIZE;

	// do curl request; check for errors
	res = curl_easy_perform(curl);


	if(res != CURLE_OK)
	  abort_("[main] curl_easy_perform() failed: %s\n",
			  curl_easy_strerror(res));

	// read PNG (as downloaded from network) and copy it to output buffer
	png_bytep* row_pointers = read_png_file(png_ptr, &info_ptr, &bd);
	pthread_mutex_lock(&mutex2);
	paint_destination(png_ptr, row_pointers, hd.n*BUF_WIDTH, 0, shared_resource->output_buffer);
	pthread_mutex_unlock(&mutex2);

	// free allocated memory
	for (int y=0; y<BUF_HEIGHT; y++)
	  free(row_pointers[y]);
	free(row_pointers);
	png_destroy_read_struct(&png_ptr, &info_ptr, NULL);

	// check for unreceived fragments
	received_all_fragments = true;
	for (int i = 0; i < N; i++)
	  if (!shared_resource->received_fragments[i])
		received_all_fragments = false;
	} while (!received_all_fragments);
	free(url);
	free(input_buffer);

	curl_easy_cleanup(curl);
	return NULL;
}
void * requestFrag(void * tempthreaddata)
{
	CURL *curl;
	CURLcode res;
	png_structp png_ptr;
	png_infop info_ptr;
	
	bool received_all_fragments = false;

	struct threaddata * temp = (struct threaddata *) tempthreaddata;
#ifdef _DEBUG_1_
	printf("\n###0###\n");
	printf("%s", temp->url);
	fflush(stdout);
#endif
//Making URL for thread
	char * temp_url = malloc(256);
	#ifdef _DEBUG_1_
	printf("\n###566###\n");
	//printf("%s", sizeof(temp->url));
	fflush(stdout);
#endif
	strcpy(temp_url, temp->url);
	
	
#ifdef _DEBUG_1_
	printf("\n###555###\n");
	printf("%s", temp_url);
	fflush(stdout);
#endif

	curl = curl_easy_init();
	if (!curl)
		abort_("[main] could not initialize curl");

  
	png_bytep input_buffer = malloc(sizeof(png_byte)*BUF_SIZE);
	struct bufdata bd; 
	bd.buf = input_buffer; 
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &bd);

	struct headerdata hd; hd.received_fragments = temp->received_fragments;
	curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hd);
	curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_cb);
  
	//set url
	curl_easy_setopt(curl, CURLOPT_URL, temp_url);


	do {
		png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
		if (!png_ptr)
		  abort_("[main] png_create_read_struct failed");

		// reset input buffer
		bd.len = bd.pos = 0; bd.max_size = BUF_SIZE;

		// do curl request; check for errors
		//pthread_mutex_lock(&lock);
		res = curl_easy_perform(curl);
		//pthread_mutex_unlock(&lock);
		if(res != CURLE_OK)
		  abort_("[main] curl_easy_perform() failed: %s\n",
				  curl_easy_strerror(res));

		// read PNG (as downloaded from network) and copy it to output buffer
		png_bytep* row_pointers = read_png_file(png_ptr, &info_ptr, &bd);
		pthread_mutex_lock(&lock);
		paint_destination(png_ptr, row_pointers, hd.n*BUF_WIDTH, 0, temp->output_buffer);
		pthread_mutex_unlock(&lock);

		// free allocated memory
		for (int y=0; y<BUF_HEIGHT; y++)
		  free(row_pointers[y]);
		free(row_pointers);
		png_destroy_read_struct(&png_ptr, &info_ptr, NULL);

		// check for unreceived fragments
		received_all_fragments = true;
		for (int i = 0; i < N; i++)
		  if (!temp->received_fragments[i])
			received_all_fragments = false;
  } while (!received_all_fragments);
  
  #ifdef _DEBUG_1_
	printf("\n###1###\n");
	fflush(stdout);
#endif
free(temp_url);
  free(input_buffer);
    curl_easy_cleanup(curl);
}
Exemple #27
0
void kappa_fifo_create_logo(char *group,kafifo_t *output,kafifo_t *input)
{
	if (! strlen(input->logo)) return;
	
	fprintf(stderr,"Header	logo   %s %s\n",group,input->logo);
	
	char fullpath[ 256 ];
	char target	 [ 256 ];
	
	strcpy(target,input->logo);
	strcat(target,".png");
	
	DIR *dir = opendir(strcpy(fullpath,"./fliegen"));
	if (! dir) dir = opendir(strcpy(fullpath,kappa_fifo_pipedir));
	
	struct dirent *entry;
	int match = false;
	int lwidth;

	while (true)
	{
		entry = readdir(dir);
		if (! entry) break;
		
		if (! strstr(entry->d_name,target)) continue;
		
		lwidth = atoi(entry->d_name);
		if (lwidth != input->final_width) continue;
		
		strcat(fullpath,"/");
		strcat(fullpath,entry->d_name);
		
		fprintf(stderr,"Header	logo   %s %s\n",group,fullpath);
		
		match = true;
	}
	
	closedir(dir);
	
	if (! match) return;
	
	//
	// int res = ff_load_image(
	// int res = read_png_file(
	//
	
	int res = read_png_file(
		input->logo_rgb_data,input->logo_rgb_size,
		&input->logo_width,&input->logo_height,
		&input->logo_pixfmt,
		fullpath, 
		NULL
		);
	
	if (res < 0)
	{
		fprintf(stderr,"Could not open logo %s, exitting now...\n",fullpath);
		exit(1);
	}
	
	fprintf(stderr,"Header	logo   %s %s %dx%d format=%s\n",
		group,fullpath,
		input->logo_width,input->logo_height,
		av_get_pix_fmt_name(input->logo_pixfmt)
		);
	
	//
	// Convert logo pixels to YUV444P video format.
	//
	
	struct SwsContext *ctx = sws_getContext(
		input->logo_width,input->logo_height,input->logo_pixfmt, 
		input->logo_width,input->logo_height,AV_PIX_FMT_YUV444P, 
		0, 
		NULL, NULL, NULL
		);
	
	const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(input->pixfmt);

	int y_shift = desc->log2_chroma_h;
	int x_shift = desc->log2_chroma_w;

	input->logo_yuv_size[ 0 ] = input->logo_width;
	input->logo_yuv_size[ 1 ] = input->logo_width;
	input->logo_yuv_size[ 2 ] = input->logo_width;

	input->logo_yuv_data[ 0 ] = (uint8_t *) malloc(input->logo_yuv_size[ 0 ] * input->logo_height);
	input->logo_yuv_data[ 1 ] = (uint8_t *) malloc(input->logo_yuv_size[ 1 ] * input->logo_height);
	input->logo_yuv_data[ 2 ] = (uint8_t *) malloc(input->logo_yuv_size[ 2 ] * input->logo_height);
		
	sws_scale(
		ctx,
		(const uint8_t * const *) input->logo_rgb_data,
		input->logo_rgb_size,
		0,input->logo_height,
		input->logo_yuv_data,
		input->logo_yuv_size
		);
		
	sws_freeContext(ctx);
	
	//
	// Build alpha lookup table.
	//
	
	input->alphatable = (uint8_t *) malloc(256 * 256);
	
	int alpha;
	int pixel;
	
	for (alpha = 0; alpha < 256; alpha++)
	{
		for (pixel = 0; pixel < 256; pixel++)
		{
			input->alphatable[ (alpha << 8) + pixel ] = (uint8_t) ((pixel * alpha) / 255);
		}
	}
	
	//
	// Optimize logo rectangle.
	//

	int logowid = input->logo_width;
	int logohei = input->logo_height;
	int logosiz = input->logo_rgb_size[ 0 ];
	
	int 	 wid;
	int 	 hei;
	int		 zero;
	uint8_t *rgba;
	
	//
	// Optimize top.
	//
	
	rgba = input->logo_rgb_data[ 0 ] + 3;
	
	for (hei = 0; (hei < logohei) && (input->logo_height > 0); hei++)
	{	
		for (zero = true, wid = 0; zero && (wid < logowid); wid++)
		{
			if (*rgba > 0) zero = false;
			
			rgba += 4;
		}
		
		if (! zero) break;
		
		input->logo_top++;
		input->logo_height--;
	}
	
	//
	// Optimize height.
	//
	
	rgba = input->logo_rgb_data[ 0 ] - 1 + (logohei * logosiz);
	
	for (hei = 0; (hei < logohei) && (input->logo_height > 0); hei++)
	{	
		for (zero = true, wid = 0; zero && (wid < logowid); wid++)
		{
			if (*rgba > 0) zero = false;
			
			rgba -= 4;
		}
		
		if (! zero) break;
		
		input->logo_height--;
	}
	
	//
	// Optimize left.
	//
	
	for (wid = 0; (wid < logowid) && (input->logo_width > 0); wid++)
	{	
		rgba = input->logo_rgb_data[ 0 ] + 3 + (wid * 4);
	
		for (zero = true, hei = 0; zero && (hei < logohei); hei++)
		{
			if (*rgba > 0) zero = false;
			
			rgba += logosiz;
		}
		
		if (! zero) break;
		
		input->logo_left++;
		input->logo_width--;
	}
	
	//
	// Optimize width.
	//
	
	for (wid = 0; (wid < logowid) && (input->logo_width > 1); wid++)
	{	
		rgba = input->logo_rgb_data[ 0 ] - 1 + (logohei * logosiz) - (wid * 4);
		
		for (zero = true, hei = 0; zero && (hei < logohei); hei++)
		{
			if (*rgba > 0) zero = false;
			
			rgba -= logosiz;
		}
		
		if (! zero) break;
		
		input->logo_width--;
	}
	
	fprintf(stderr,"Header	logo   %s %s %d:%d => %dx%d\n",
		group,fullpath,
		input->logo_left,input->logo_top,
		input->logo_width,input->logo_height
		);
	
	input->wantlogo = true;
}