<commit_before>#include "config.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cstring>

using namespace std;

//// parameters
// for bam file and reads
int min_flank_length = 5;
int32_t min_bundle_gap = 50;
int min_num_hits_in_bundle = 20;
uint32_t min_mapping_quality = 1;
int32_t min_splice_boundary_hits = 1;
bool use_second_alignment = false;
int library_type = UNSTRAND;

// for identifying subgraphs
double max_indel_ratio = 0.2;
double min_subregion_overlap = 2;
int32_t min_subregion_gap = 3;
int32_t min_subregion_length = 15;

// for revising splice graph
double min_inner_vertex_weight = 10;
double min_inner_boundary_weight = 4.0;
double min_splice_edge_weight = 2.5;
bool extend_isolated_boundary = true;

// for decomposing splice graph
double max_split_error_ratio = 0.25;
double max_decompose_error_ratio = 0.01;

// for selecting paths
double min_transcript_coverage = 0.9;
double min_transcript_numreads = 20;
int min_transcript_length = 200;

// for identifying new boundaries
bool identify_extra_boundary = false;
int min_boundary_length = 80;
int min_boundary_score = 100;
double min_boundary_ave_ratio = 3.0;
double min_boundary_sigma = 5.0;

// for subsetsum and router
int max_dp_table_size = 10000;
int min_router_count = 1;

// for simulation
int simulation_num_vertices = 0;
int simulation_num_edges = 0;
int simulation_max_edge_weight = 0;

// input and output
string algo = "scallop";
string input_file;
string ref_file;
string ref_file1;
string ref_file2;
string output_file;

// for controling
int32_t average_read_length = 100;
bool output_tex_files = false;
string fixed_gene_name = "";

int print_parameters()
{
	printf("parameters:\n");

	// for bam file and reads
	printf("min_flank_length = %d\n", min_flank_length);
	printf("min_bundle_gap = %d\n", min_bundle_gap);
	printf("min_num_hits_in_bundle = %d\n", min_num_hits_in_bundle);
	printf("min_mapping_quality = %d\n", min_mapping_quality);
	printf("min_splice_boundary_hits = %d\n", min_splice_boundary_hits);

	// for identifying subgraphs
	printf("max_indel_ratio = %.2lf\n", max_indel_ratio);
	printf("min_subregion_gap = %d\n", min_subregion_gap);
	printf("min_subregion_length = %d\n", min_subregion_length);
	printf("min_subregion_overlap = %.2lf\n", min_subregion_overlap);

	// for splice graph
	printf("min_splice_edge_weight = %.2lf\n", min_splice_edge_weight);
	printf("min_inner_vertex_weight = %.2lf\n", min_inner_vertex_weight);
	printf("min_inner_boundary_weight = %.2lf\n", min_inner_boundary_weight);
	printf("min_transcript_coverage = %.2lf\n", min_transcript_coverage);
	printf("min_transcript_numreads = %.2lf\n", min_transcript_numreads);
	printf("min_transcript_length = %d\n", min_transcript_length);
	printf("max_split_error_ratio = %.2lf\n", max_split_error_ratio);
	printf("max_decompose_error_ratio = %.2lf\n", max_decompose_error_ratio);
	printf("extend_isolated_bounary = %c\n", extend_isolated_boundary ? 'T' : 'F');

	// for identifying new boundaries
	printf("identify_extra_boundary = %c\n", identify_extra_boundary ? 'T' : 'F');
	printf("min_boundary_length = %d\n", min_boundary_length);
	printf("min_boundary_score = %d\n", min_boundary_score);
	printf("min_boundary_ave_ratio = %.2lf\n", min_boundary_ave_ratio);
	printf("min_boundary_signma = %.2lf\n", min_boundary_sigma);

	// for subsetsum and router
	printf("max_dp_table_size = %d\n", max_dp_table_size);
	printf("min_router_count = %d\n", min_router_count);

	// for simulation
	printf("simulation_num_vertices = %d\n", simulation_num_vertices);
	printf("simulation_num_edges = %d\n", simulation_num_edges);
	printf("simulation_max_edge_weight = %d\n", simulation_max_edge_weight);

	// for input and output
	printf("algo = %s\n", algo.c_str());
	printf("input_file = %s\n", input_file.c_str());
	printf("ref_file = %s\n", ref_file.c_str());
	printf("ref_file1 = %s\n", ref_file1.c_str());
	printf("ref_file2 = %s\n", ref_file2.c_str());
	printf("output_file = %s\n", output_file.c_str());

	// for controling
	printf("average_read_length = %d\n", average_read_length);
	printf("library_type = %d\n", library_type);
	printf("output_tex_files = %c\n", output_tex_files ? 'T' : 'F');
	printf("fixed_gene_name = %s\n", fixed_gene_name.c_str());
	printf("use_second_alignment = %c\n", use_second_alignment ? 'T' : 'F');

	printf("\n");

	return 0;
}

int print_command_line(int argc, const char ** argv)
{
	printf("command line: ");
	for(int i = 0; i < argc; i++)
	{
		printf("%s ", argv[i]);
	}
	printf("\n");
	return 0;
}

int parse_arguments(int argc, const char ** argv)
{
	for(int i = 1; i < argc; i++)
	{
		// necessary ones
		if(string(argv[i]) == "-i")
		{
			input_file = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-o")
		{
			output_file = string(argv[i + 1]);
			i++;
		}

		// internal use
		else if(string(argv[i]) == "-a")
		{
			algo = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-r")
		{
			ref_file = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-r1")
		{
			ref_file1 = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-r2")
		{
			ref_file2 = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-g")
		{
			fixed_gene_name = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-t")
		{
			output_tex_files = true;
		}

		// user specified
		else if(string(argv[i]) == "--min_flank_length")
		{
			min_flank_length = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_bundle_gap")
		{
			min_bundle_gap = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_num_hits_in_bundle")
		{
			min_num_hits_in_bundle = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_mapping_quality")
		{
			min_mapping_quality = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_splice_boundary_hits")
		{
			min_splice_boundary_hits = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--max_indel_ratio")
		{
			max_indel_ratio = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_subregion_gap")
		{
			min_subregion_gap = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_subregion_length")
		{
			min_subregion_length = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_subregion_overlap")
		{
			min_subregion_overlap = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--identify_extra_boundary")
		{
			string s(argv[i + 1]);
			if(s == "true") identify_extra_boundary = true;
			else identify_extra_boundary = false;
			i++;
		}
		else if(string(argv[i]) == "--min_splice_edge_weight")
		{
			min_splice_edge_weight = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_inner_vertex_weight")
		{
			min_inner_vertex_weight = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_inner_boundary_weight")
		{
			min_inner_boundary_weight = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_transcript_coverage")
		{
			min_transcript_coverage = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_transcript_numreads")
		{
			min_transcript_numreads = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_transcript_length")
		{
			min_transcript_length = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--max_split_error_ratio")
		{
			max_split_error_ratio = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--max_decompose_error_ratio")
		{
			max_decompose_error_ratio = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--extend_isolated_boundary")
		{
			string s(argv[i + 1]);
			if(s == "true") extend_isolated_boundary = true;
			else extend_isolated_boundary = false;
			i++;
		}
		else if(string(argv[i]) == "--min_boundary_length")
		{
			min_boundary_length = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_boundary_score")
		{
			min_boundary_score = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_boundary_ave_ratio")
		{
			min_boundary_ave_ratio = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_boundary_sigma")
		{
			min_boundary_sigma = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--max_dp_table_size")
		{
			max_dp_table_size = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_router_count")
		{
			min_router_count = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--library_type")
		{
			string s(argv[i + 1]);
			if(s == "unstrand") library_type = UNSTRAND;
			if(s == "first") library_type = FR_FIRST;
			if(s == "second") library_type = FR_SECOND;
			i++;
		}
		else if(string(argv[i]) == "--use_second_alignment")
		{
			string s(argv[i + 1]);
			if(s == "true") use_second_alignment = true;
			else use_second_alignment = false;
			i++;
		}
	}

	// TODO
	//min_splice_edge_weight = min_transcript_coverage;

	return 0;
}
<commit_msg>use 1.5 for min_splice_edge_weight<commit_after>#include "config.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cstring>

using namespace std;

//// parameters
// for bam file and reads
int min_flank_length = 5;
int32_t min_bundle_gap = 50;
int min_num_hits_in_bundle = 20;
uint32_t min_mapping_quality = 1;
int32_t min_splice_boundary_hits = 1;
bool use_second_alignment = false;
int library_type = UNSTRAND;

// for identifying subgraphs
double max_indel_ratio = 0.2;
double min_subregion_overlap = 2;
int32_t min_subregion_gap = 3;
int32_t min_subregion_length = 15;

// for revising splice graph
double min_inner_vertex_weight = 10;
double min_inner_boundary_weight = 4.0;
double min_splice_edge_weight = 1.5;
bool extend_isolated_boundary = true;

// for decomposing splice graph
double max_split_error_ratio = 0.25;
double max_decompose_error_ratio = 0.01;

// for selecting paths
double min_transcript_coverage = 0.9;
double min_transcript_numreads = 20;
int min_transcript_length = 200;

// for identifying new boundaries
bool identify_extra_boundary = false;
int min_boundary_length = 80;
int min_boundary_score = 100;
double min_boundary_ave_ratio = 3.0;
double min_boundary_sigma = 5.0;

// for subsetsum and router
int max_dp_table_size = 10000;
int min_router_count = 1;

// for simulation
int simulation_num_vertices = 0;
int simulation_num_edges = 0;
int simulation_max_edge_weight = 0;

// input and output
string algo = "scallop";
string input_file;
string ref_file;
string ref_file1;
string ref_file2;
string output_file;

// for controling
int32_t average_read_length = 100;
bool output_tex_files = false;
string fixed_gene_name = "";

int print_parameters()
{
	printf("parameters:\n");

	// for bam file and reads
	printf("min_flank_length = %d\n", min_flank_length);
	printf("min_bundle_gap = %d\n", min_bundle_gap);
	printf("min_num_hits_in_bundle = %d\n", min_num_hits_in_bundle);
	printf("min_mapping_quality = %d\n", min_mapping_quality);
	printf("min_splice_boundary_hits = %d\n", min_splice_boundary_hits);

	// for identifying subgraphs
	printf("max_indel_ratio = %.2lf\n", max_indel_ratio);
	printf("min_subregion_gap = %d\n", min_subregion_gap);
	printf("min_subregion_length = %d\n", min_subregion_length);
	printf("min_subregion_overlap = %.2lf\n", min_subregion_overlap);

	// for splice graph
	printf("min_splice_edge_weight = %.2lf\n", min_splice_edge_weight);
	printf("min_inner_vertex_weight = %.2lf\n", min_inner_vertex_weight);
	printf("min_inner_boundary_weight = %.2lf\n", min_inner_boundary_weight);
	printf("min_transcript_coverage = %.2lf\n", min_transcript_coverage);
	printf("min_transcript_numreads = %.2lf\n", min_transcript_numreads);
	printf("min_transcript_length = %d\n", min_transcript_length);
	printf("max_split_error_ratio = %.2lf\n", max_split_error_ratio);
	printf("max_decompose_error_ratio = %.2lf\n", max_decompose_error_ratio);
	printf("extend_isolated_bounary = %c\n", extend_isolated_boundary ? 'T' : 'F');

	// for identifying new boundaries
	printf("identify_extra_boundary = %c\n", identify_extra_boundary ? 'T' : 'F');
	printf("min_boundary_length = %d\n", min_boundary_length);
	printf("min_boundary_score = %d\n", min_boundary_score);
	printf("min_boundary_ave_ratio = %.2lf\n", min_boundary_ave_ratio);
	printf("min_boundary_signma = %.2lf\n", min_boundary_sigma);

	// for subsetsum and router
	printf("max_dp_table_size = %d\n", max_dp_table_size);
	printf("min_router_count = %d\n", min_router_count);

	// for simulation
	printf("simulation_num_vertices = %d\n", simulation_num_vertices);
	printf("simulation_num_edges = %d\n", simulation_num_edges);
	printf("simulation_max_edge_weight = %d\n", simulation_max_edge_weight);

	// for input and output
	printf("algo = %s\n", algo.c_str());
	printf("input_file = %s\n", input_file.c_str());
	printf("ref_file = %s\n", ref_file.c_str());
	printf("ref_file1 = %s\n", ref_file1.c_str());
	printf("ref_file2 = %s\n", ref_file2.c_str());
	printf("output_file = %s\n", output_file.c_str());

	// for controling
	printf("average_read_length = %d\n", average_read_length);
	printf("library_type = %d\n", library_type);
	printf("output_tex_files = %c\n", output_tex_files ? 'T' : 'F');
	printf("fixed_gene_name = %s\n", fixed_gene_name.c_str());
	printf("use_second_alignment = %c\n", use_second_alignment ? 'T' : 'F');

	printf("\n");

	return 0;
}

int print_command_line(int argc, const char ** argv)
{
	printf("command line: ");
	for(int i = 0; i < argc; i++)
	{
		printf("%s ", argv[i]);
	}
	printf("\n");
	return 0;
}

int parse_arguments(int argc, const char ** argv)
{
	for(int i = 1; i < argc; i++)
	{
		// necessary ones
		if(string(argv[i]) == "-i")
		{
			input_file = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-o")
		{
			output_file = string(argv[i + 1]);
			i++;
		}

		// internal use
		else if(string(argv[i]) == "-a")
		{
			algo = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-r")
		{
			ref_file = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-r1")
		{
			ref_file1 = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-r2")
		{
			ref_file2 = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-g")
		{
			fixed_gene_name = string(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "-t")
		{
			output_tex_files = true;
		}

		// user specified
		else if(string(argv[i]) == "--min_flank_length")
		{
			min_flank_length = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_bundle_gap")
		{
			min_bundle_gap = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_num_hits_in_bundle")
		{
			min_num_hits_in_bundle = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_mapping_quality")
		{
			min_mapping_quality = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_splice_boundary_hits")
		{
			min_splice_boundary_hits = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--max_indel_ratio")
		{
			max_indel_ratio = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_subregion_gap")
		{
			min_subregion_gap = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_subregion_length")
		{
			min_subregion_length = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_subregion_overlap")
		{
			min_subregion_overlap = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--identify_extra_boundary")
		{
			string s(argv[i + 1]);
			if(s == "true") identify_extra_boundary = true;
			else identify_extra_boundary = false;
			i++;
		}
		else if(string(argv[i]) == "--min_splice_edge_weight")
		{
			min_splice_edge_weight = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_inner_vertex_weight")
		{
			min_inner_vertex_weight = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_inner_boundary_weight")
		{
			min_inner_boundary_weight = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_transcript_coverage")
		{
			min_transcript_coverage = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_transcript_numreads")
		{
			min_transcript_numreads = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_transcript_length")
		{
			min_transcript_length = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--max_split_error_ratio")
		{
			max_split_error_ratio = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--max_decompose_error_ratio")
		{
			max_decompose_error_ratio = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--extend_isolated_boundary")
		{
			string s(argv[i + 1]);
			if(s == "true") extend_isolated_boundary = true;
			else extend_isolated_boundary = false;
			i++;
		}
		else if(string(argv[i]) == "--min_boundary_length")
		{
			min_boundary_length = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_boundary_score")
		{
			min_boundary_score = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_boundary_ave_ratio")
		{
			min_boundary_ave_ratio = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_boundary_sigma")
		{
			min_boundary_sigma = atof(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--max_dp_table_size")
		{
			max_dp_table_size = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--min_router_count")
		{
			min_router_count = atoi(argv[i + 1]);
			i++;
		}
		else if(string(argv[i]) == "--library_type")
		{
			string s(argv[i + 1]);
			if(s == "unstrand") library_type = UNSTRAND;
			if(s == "first") library_type = FR_FIRST;
			if(s == "second") library_type = FR_SECOND;
			i++;
		}
		else if(string(argv[i]) == "--use_second_alignment")
		{
			string s(argv[i + 1]);
			if(s == "true") use_second_alignment = true;
			else use_second_alignment = false;
			i++;
		}
	}

	// TODO
	//min_splice_edge_weight = min_transcript_coverage;

	return 0;
}
<|endoftext|>


<commit_before>#include "subcarrier.h"

#include <complex>
#include <deque>
#include <iostream>

#include "liquid_wrappers.h"

namespace redsea {

namespace {

const float kFs = 228000.0f;
const float kFc_0 = 57000.0f;
const int kInputBufferSize = 4096;
const int kSamplesPerSymbol = 4;

}

DeltaDecoder::DeltaDecoder() : prev_(0) {

}

DeltaDecoder::~DeltaDecoder() {

}

unsigned DeltaDecoder::decode(unsigned d) {
  unsigned bit = (d != prev_);
  prev_ = d;
  return bit;
}

Subcarrier::Subcarrier() : numsamples_(0), bit_buffer_(),
  fir_lpf_(256, 2100.0f / kFs), is_eof_(false), agc_(0.001f),
  nco_approx_(kFc_0 * 2 * M_PI / kFs), nco_exact_(0.0f),
  symsync_(LIQUID_FIRFILT_RRC, kSamplesPerSymbol, 5, 0.5f, 32),
  modem_(LIQUID_MODEM_PSK2), symbol_clock_(0), prev_biphase_(0),
  delta_decoder_(), symbol_errors_(0) {

    symsync_.setBandwidth(0.02f);
    symsync_.setOutputRate(1);
    nco_exact_.setPLLBandwidth(0.0004f);

}

Subcarrier::~Subcarrier() {

}

void Subcarrier::demodulateMoreBits() {

  int16_t sample[kInputBufferSize];
  int samplesread = fread(sample, sizeof(int16_t), kInputBufferSize, stdin);
  if (samplesread < kInputBufferSize) {
    is_eof_ = true;
    return;
  }

  for (int i = 0; i < samplesread; i++) {

    std::complex<float> sample_baseband = nco_approx_.mixDown(sample[i]);

    fir_lpf_.push(sample_baseband);

    if (numsamples_ % (96 / kSamplesPerSymbol) == 0) {

      std::complex<float> sample_lopass = agc_.execute(fir_lpf_.execute());

      nco_exact_.stepPLL(modem_.getPhaseError());
      sample_lopass = nco_exact_.mixDown(sample_lopass);

      std::vector<std::complex<float>> symbols =
        symsync_.execute(sample_lopass);

      for (std::complex<float> symbol : symbols) {
        unsigned biphase = modem_.demodulate(symbol);

        if (symbol_clock_ == 1) {
          bit_buffer_.push_back(delta_decoder_.decode(biphase));

          if (biphase == prev_biphase_) {
            symbol_errors_ ++;
            if (symbol_errors_ >= 5)
              symbol_clock_ = 0;
          } else {
            symbol_errors_ = 0;
          }
        }

        prev_biphase_ = biphase;

        symbol_clock_ ^= 1;

      }
    }

    nco_approx_.step();

    numsamples_ ++;

  }

}

int Subcarrier::getNextBit() {
  while (bit_buffer_.size() < 1 && !isEOF())
    demodulateMoreBits();

  int bit = 0;

  if (bit_buffer_.size() > 0) {
    bit = bit_buffer_.front();
    bit_buffer_.pop_front();
  }

  return bit;
}

bool Subcarrier::isEOF() const {
  return is_eof_;
}

} // namespace redsea
<commit_msg>trial-and-error says 7 is marginally better<commit_after>#include "subcarrier.h"

#include <complex>
#include <deque>
#include <iostream>

#include "liquid_wrappers.h"

namespace redsea {

namespace {

const float kFs = 228000.0f;
const float kFc_0 = 57000.0f;
const int kInputBufferSize = 4096;
const int kSamplesPerSymbol = 4;

}

DeltaDecoder::DeltaDecoder() : prev_(0) {

}

DeltaDecoder::~DeltaDecoder() {

}

unsigned DeltaDecoder::decode(unsigned d) {
  unsigned bit = (d != prev_);
  prev_ = d;
  return bit;
}

Subcarrier::Subcarrier() : numsamples_(0), bit_buffer_(),
  fir_lpf_(256, 2100.0f / kFs), is_eof_(false), agc_(0.001f),
  nco_approx_(kFc_0 * 2 * M_PI / kFs), nco_exact_(0.0f),
  symsync_(LIQUID_FIRFILT_RRC, kSamplesPerSymbol, 5, 0.5f, 32),
  modem_(LIQUID_MODEM_PSK2), symbol_clock_(0), prev_biphase_(0),
  delta_decoder_(), symbol_errors_(0) {

    symsync_.setBandwidth(0.02f);
    symsync_.setOutputRate(1);
    nco_exact_.setPLLBandwidth(0.0004f);

}

Subcarrier::~Subcarrier() {

}

void Subcarrier::demodulateMoreBits() {

  int16_t sample[kInputBufferSize];
  int samplesread = fread(sample, sizeof(int16_t), kInputBufferSize, stdin);
  if (samplesread < kInputBufferSize) {
    is_eof_ = true;
    return;
  }

  for (int i = 0; i < samplesread; i++) {

    std::complex<float> sample_baseband = nco_approx_.mixDown(sample[i]);

    fir_lpf_.push(sample_baseband);

    if (numsamples_ % (96 / kSamplesPerSymbol) == 0) {

      std::complex<float> sample_lopass = agc_.execute(fir_lpf_.execute());

      nco_exact_.stepPLL(modem_.getPhaseError());
      sample_lopass = nco_exact_.mixDown(sample_lopass);

      std::vector<std::complex<float>> symbols =
        symsync_.execute(sample_lopass);

      for (std::complex<float> symbol : symbols) {
        unsigned biphase = modem_.demodulate(symbol);

        if (symbol_clock_ == 1) {
          bit_buffer_.push_back(delta_decoder_.decode(biphase));

          if (biphase == prev_biphase_) {
            symbol_errors_ ++;
            if (symbol_errors_ >= 7)
              symbol_clock_ = 0;
          } else {
            symbol_errors_ = 0;
          }
        }

        prev_biphase_ = biphase;

        symbol_clock_ ^= 1;

      }
    }

    nco_approx_.step();

    numsamples_ ++;

  }

}

int Subcarrier::getNextBit() {
  while (bit_buffer_.size() < 1 && !isEOF())
    demodulateMoreBits();

  int bit = 0;

  if (bit_buffer_.size() > 0) {
    bit = bit_buffer_.front();
    bit_buffer_.pop_front();
  }

  return bit;
}

bool Subcarrier::isEOF() const {
  return is_eof_;
}

} // namespace redsea
<|endoftext|>


<commit_before><commit_msg>force flush<commit_after><|endoftext|>


<commit_before><commit_msg>Fix linux build<commit_after><|endoftext|>


<commit_before><commit_msg>Forgot to completely update the experiment.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#define _WITH_DPRINTF

#include <cstdlib>
#include <cstdio>
#include <cassert>

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>

#include <sys/types.h>
#include <sys/socket.h>

#include <iostream>

#include <openssl/sha.h>

#include "debug.h"
#include "util.h"
#include "object.h"
#include "httpclient.h"
#include "httprepo.h"

using namespace std;

/*
 * HttpRepo
 */

HttpRepo::HttpRepo(HttpClient *client)
    : client(client)
{
}

HttpRepo::~HttpRepo()
{
}

void
HttpRepo::preload(const std::vector<std::string> &objs)
{
    // TODO
    return;
}

std::string
HttpRepo::getHead()
{
    int status;
    string headId;

    status = client->getRequest("/HEAD", headId);
    if (status < 0) {
        assert(false);
        return "";
    }

    return headId;
}

Object::sp
HttpRepo::getObject(const std::string &id)
{
    int status;
    string index;
    ObjectInfo info = ObjectInfo(id.c_str());
    std::string payload;

    status = client->getRequest("/objs/" + id, payload);
    if (status < 0) {
        assert(false);
        return Object::sp();
    }

    info.setInfo(payload.substr(0, 16));

    // TODO: add raw data to cache
    _addPayload(info.hash, payload.substr(16));

    return Object::sp(new HttpObject(this, info));
}

bool
HttpRepo::hasObject(const std::string &id) {
    NOT_IMPLEMENTED(false);
    return false;
}

std::set<ObjectInfo>
HttpRepo::listObjects()
{
    int status;
    string index;
    set<ObjectInfo> rval;

    status = client->getRequest("/index", index);
    if (status < 0) {
        assert(false);
        return rval;
    }

    // Parse response
    for (int offset = 0; offset < index.size();)
    {
        string hash;
        string objInfo;
        ObjectInfo info;

        hash = index.substr(offset, SHA256_DIGEST_LENGTH * 2);
        offset += SHA256_DIGEST_LENGTH * 2;
        objInfo = index.substr(offset, 16);
        offset += 16;

        info = ObjectInfo(hash.c_str());
        info.setInfo(objInfo);
        rval.insert(info);
    }

    return rval;
}

int
HttpRepo::addObjectRaw(const ObjectInfo &info, bytestream *bs)
{
    NOT_IMPLEMENTED(false);
    return -1;
}

vector<Commit>
HttpRepo::listCommits()
{
    vector<Commit> rval;

    string index;
    int status = client->getRequest("/commits", index);
    if (status < 0) {
        assert(false);
        return rval;
    }

    // Parse response
    for (int offset = 0; offset < index.size();)
    {
        int16_t bsize = *(int16_t*)&index[offset];
        bsize = ntohs(bsize);
        offset += sizeof(int16_t);

        string blob = index.substr(offset, bsize);
        offset += bsize;

        Commit c;
        c.fromBlob(blob);
        rval.push_back(c);
    }

    return rval;
}

std::string &
HttpRepo::_payload(const std::string &id)
{
    return payloads[id];
}

void
HttpRepo::_addPayload(const std::string &id, const std::string &payload)
{
    payloads[id] = payload;
}

void
HttpRepo::_clearPayload(const std::string &id)
{
    payloads.erase(id);
}

/*
 * HttpObject
 */

HttpObject::HttpObject(HttpRepo *repo, ObjectInfo info)
    : Object(info), repo(repo)
{
    assert(repo != NULL);
    assert(info.hash.size() > 0);
}

HttpObject::~HttpObject()
{
    repo->_clearPayload(info.hash);
}

bytestream::ap
HttpObject::getPayloadStream()
{
    if (info.getCompressed()) {
        bytestream::ap bs(getStoredPayloadStream());
        return bytestream::ap(new lzmastream(bs.release()));
    }
    return getStoredPayloadStream();
}

bytestream::ap
HttpObject::getStoredPayloadStream()
{
    return bytestream::ap(new strstream(repo->_payload(info.hash)));
}

size_t
HttpObject::getStoredPayloadSize()
{
    return repo->_payload(info.hash).length();
}
<commit_msg>Fixing HttpRepo build on BSDs<commit_after>/*
 * Copyright (c) 2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#define _WITH_DPRINTF

#include <cstdlib>
#include <cstdio>
#include <cassert>

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#include <iostream>

#include <openssl/sha.h>

#include "debug.h"
#include "util.h"
#include "object.h"
#include "httpclient.h"
#include "httprepo.h"

using namespace std;

/*
 * HttpRepo
 */

HttpRepo::HttpRepo(HttpClient *client)
    : client(client)
{
}

HttpRepo::~HttpRepo()
{
}

void
HttpRepo::preload(const std::vector<std::string> &objs)
{
    // TODO
    return;
}

std::string
HttpRepo::getHead()
{
    int status;
    string headId;

    status = client->getRequest("/HEAD", headId);
    if (status < 0) {
        assert(false);
        return "";
    }

    return headId;
}

Object::sp
HttpRepo::getObject(const std::string &id)
{
    int status;
    string index;
    ObjectInfo info = ObjectInfo(id.c_str());
    std::string payload;

    status = client->getRequest("/objs/" + id, payload);
    if (status < 0) {
        assert(false);
        return Object::sp();
    }

    info.setInfo(payload.substr(0, 16));

    // TODO: add raw data to cache
    _addPayload(info.hash, payload.substr(16));

    return Object::sp(new HttpObject(this, info));
}

bool
HttpRepo::hasObject(const std::string &id) {
    NOT_IMPLEMENTED(false);
    return false;
}

std::set<ObjectInfo>
HttpRepo::listObjects()
{
    int status;
    string index;
    set<ObjectInfo> rval;

    status = client->getRequest("/index", index);
    if (status < 0) {
        assert(false);
        return rval;
    }

    // Parse response
    for (int offset = 0; offset < index.size();)
    {
        string hash;
        string objInfo;
        ObjectInfo info;

        hash = index.substr(offset, SHA256_DIGEST_LENGTH * 2);
        offset += SHA256_DIGEST_LENGTH * 2;
        objInfo = index.substr(offset, 16);
        offset += 16;

        info = ObjectInfo(hash.c_str());
        info.setInfo(objInfo);
        rval.insert(info);
    }

    return rval;
}

int
HttpRepo::addObjectRaw(const ObjectInfo &info, bytestream *bs)
{
    NOT_IMPLEMENTED(false);
    return -1;
}

vector<Commit>
HttpRepo::listCommits()
{
    vector<Commit> rval;

    string index;
    int status = client->getRequest("/commits", index);
    if (status < 0) {
        assert(false);
        return rval;
    }

    // Parse response
    for (int offset = 0; offset < index.size();)
    {
        int16_t bsize = *(int16_t*)&index[offset];
        bsize = ntohs(bsize);
        offset += sizeof(int16_t);

        string blob = index.substr(offset, bsize);
        offset += bsize;

        Commit c;
        c.fromBlob(blob);
        rval.push_back(c);
    }

    return rval;
}

std::string &
HttpRepo::_payload(const std::string &id)
{
    return payloads[id];
}

void
HttpRepo::_addPayload(const std::string &id, const std::string &payload)
{
    payloads[id] = payload;
}

void
HttpRepo::_clearPayload(const std::string &id)
{
    payloads.erase(id);
}

/*
 * HttpObject
 */

HttpObject::HttpObject(HttpRepo *repo, ObjectInfo info)
    : Object(info), repo(repo)
{
    assert(repo != NULL);
    assert(info.hash.size() > 0);
}

HttpObject::~HttpObject()
{
    repo->_clearPayload(info.hash);
}

bytestream::ap
HttpObject::getPayloadStream()
{
    if (info.getCompressed()) {
        bytestream::ap bs(getStoredPayloadStream());
        return bytestream::ap(new lzmastream(bs.release()));
    }
    return getStoredPayloadStream();
}

bytestream::ap
HttpObject::getStoredPayloadStream()
{
    return bytestream::ap(new strstream(repo->_payload(info.hash)));
}

size_t
HttpObject::getStoredPayloadSize()
{
    return repo->_payload(info.hash).length();
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Network.cpp
 * @author Alex Leverington <nessence@gmail.com>
 * @author Gav Wood <i@gavwood.com>
 * @author Eric Lombrozo <elombrozo@gmail.com> (Windows version of getInterfaceAddresses())
 * @date 2014
 */

#include <sys/types.h>
#ifndef _WIN32
#include <ifaddrs.h>
#endif

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>

#include <libdevcore/Common.h>
#include <libdevcore/Assertions.h>
#include <libdevcore/CommonIO.h>
#include <libethcore/Exceptions.h>
#include "Common.h"
#include "UPnP.h"
#include "Network.h"

using namespace std;
using namespace dev;
using namespace dev::p2p;

std::set<bi::address> Network::getInterfaceAddresses()
{
	std::set<bi::address> addresses;

#ifdef _WIN32
	WSAData wsaData;
	if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
		BOOST_THROW_EXCEPTION(NoNetworking());

	char ac[80];
	if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR)
	{
		clog(NetWarn) << "Error " << WSAGetLastError() << " when getting local host name.";
		WSACleanup();
		BOOST_THROW_EXCEPTION(NoNetworking());
	}

	struct hostent* phe = gethostbyname(ac);
	if (phe == 0)
	{
		clog(NetWarn) << "Bad host lookup.";
		WSACleanup();
		BOOST_THROW_EXCEPTION(NoNetworking());
	}

	for (int i = 0; phe->h_addr_list[i] != 0; ++i)
	{
		struct in_addr addr;
		memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
		char *addrStr = inet_ntoa(addr);
		bi::address address(bi::address::from_string(addrStr));
		if (!isLocalHostAddress(address))
			addresses.insert(address.to_v4());
	}

	WSACleanup();
#else
	ifaddrs* ifaddr;
	if (getifaddrs(&ifaddr) == -1)
		BOOST_THROW_EXCEPTION(NoNetworking());

	for (auto ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
	{
		if (!ifa->ifa_addr || string(ifa->ifa_name) == "lo0")
			continue;

		if (ifa->ifa_addr->sa_family == AF_INET)
		{
			in_addr addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
			boost::asio::ip::address_v4 address(boost::asio::detail::socket_ops::network_to_host_long(addr.s_addr));
			if (!isLocalHostAddress(address))
				addresses.insert(address);
		}
		else if (ifa->ifa_addr->sa_family == AF_INET6)
		{
			sockaddr_in6* sockaddr = ((struct sockaddr_in6 *)ifa->ifa_addr);
			in6_addr addr = sockaddr->sin6_addr;
			boost::asio::ip::address_v6::bytes_type bytes;
			memcpy(&bytes[0], addr.s6_addr, 16);
			boost::asio::ip::address_v6 address(bytes, sockaddr->sin6_scope_id);
			if (!isLocalHostAddress(address))
				addresses.insert(address);
		}
	}

	if (ifaddr!=NULL)
		freeifaddrs(ifaddr);

#endif

	return std::move(addresses);
}

int Network::tcp4Listen(bi::tcp::acceptor& _acceptor, NetworkPreferences const& _netPrefs)
{
	int retport = -1;
	if (_netPrefs.listenIPAddress.empty())
		for (unsigned i = 0; i < 2; ++i)
		{
			// try to connect w/listenPort, else attempt net-allocated port
			bi::tcp::endpoint endpoint(bi::tcp::v4(), i ? 0 : _netPrefs.listenPort);
			try
			{
				_acceptor.open(endpoint.protocol());
				_acceptor.set_option(ba::socket_base::reuse_address(true));
				_acceptor.bind(endpoint);
				_acceptor.listen();
				retport = _acceptor.local_endpoint().port();
				break;
			}
			catch (...)
			{
				if (i)
				{
					// both attempts failed
					cwarn << "Couldn't start accepting connections on host. Something very wrong with network?\n" << boost::current_exception_diagnostic_information();
				}

				// first attempt failed
				_acceptor.close();
				continue;
			}
		}
	else
	{
		bi::tcp::endpoint endpoint(bi::address::from_string(_netPrefs.listenIPAddress), _netPrefs.listenPort);
		try
		{
			_acceptor.open(endpoint.protocol());
			_acceptor.set_option(ba::socket_base::reuse_address(true));
			_acceptor.bind(endpoint);
			_acceptor.listen();
			retport = _acceptor.local_endpoint().port();
		}
		catch (...)
		{
			clog(NetWarn) << "Couldn't start accepting connections on host. Failed to accept socket.\n" << boost::current_exception_diagnostic_information();
		}
		assert(retport == _netPrefs.listenPort);
		return retport;
	}
	return retport;
}

bi::tcp::endpoint Network::traverseNAT(std::set<bi::address> const& _ifAddresses, unsigned short _listenPort, bi::address& o_upnpInterfaceAddr)
{
	asserts(_listenPort != 0);

	UPnP* upnp = nullptr;
	try
	{
		upnp = new UPnP;
	}
	// let m_upnp continue as null - we handle it properly.
	catch (...) {}

	bi::tcp::endpoint upnpEP;
	if (upnp && upnp->isValid())
	{
		bi::address pAddr;
		int extPort = 0;
		for (auto const& addr: _ifAddresses)
			if (addr.is_v4() && isPrivateAddress(addr) && (extPort = upnp->addRedirect(addr.to_string().c_str(), _listenPort)))
			{
				pAddr = addr;
				break;
			}

		auto eIP = upnp->externalIP();
		bi::address eIPAddr(bi::address::from_string(eIP));
		if (extPort && eIP != string("0.0.0.0") && !isPrivateAddress(eIPAddr))
		{
			clog(NetNote) << "Punched through NAT and mapped local port" << _listenPort << "onto external port" << extPort << ".";
			clog(NetNote) << "External addr:" << eIP;
			o_upnpInterfaceAddr = pAddr;
			upnpEP = bi::tcp::endpoint(eIPAddr, (unsigned short)extPort);
		}
		else
			clog(NetWarn) << "Couldn't punch through NAT (or no NAT in place).";

		if (upnp)
			delete upnp;
	}

	return upnpEP;
}

bi::tcp::endpoint Network::resolveHost(string const& _addr)
{
	static boost::asio::io_service s_resolverIoService;

	vector<string> split;
	boost::split(split, _addr, boost::is_any_of(":"));
	unsigned port = split.size() > 1 ? stoi(split[1]) : c_defaultIPPort;

	bi::tcp::endpoint ep(bi::address(), port);
	boost::system::error_code ec;
	bi::address address = bi::address::from_string(split[0], ec);
	if (!ec)
		ep.address(address);
	else
	{
		boost::system::error_code ec;
		// resolve returns an iterator (host can resolve to multiple addresses)
		bi::tcp::resolver r(s_resolverIoService);
		auto it = r.resolve({split[0], toString(port)}, ec);
		if (ec)
			clog(NetWarn) << "Error resolving host address " << _addr << ":" << ec.message();
		else
			ep = *it;
	}
	return ep;
}

<commit_msg>use explicit name of const<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Network.cpp
 * @author Alex Leverington <nessence@gmail.com>
 * @author Gav Wood <i@gavwood.com>
 * @author Eric Lombrozo <elombrozo@gmail.com> (Windows version of getInterfaceAddresses())
 * @date 2014
 */

#include <sys/types.h>
#ifndef _WIN32
#include <ifaddrs.h>
#endif

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>

#include <libdevcore/Common.h>
#include <libdevcore/Assertions.h>
#include <libdevcore/CommonIO.h>
#include <libethcore/Exceptions.h>
#include "Common.h"
#include "UPnP.h"
#include "Network.h"

using namespace std;
using namespace dev;
using namespace dev::p2p;

std::set<bi::address> Network::getInterfaceAddresses()
{
	std::set<bi::address> addresses;

#ifdef _WIN32
	WSAData wsaData;
	if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
		BOOST_THROW_EXCEPTION(NoNetworking());

	char ac[80];
	if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR)
	{
		clog(NetWarn) << "Error " << WSAGetLastError() << " when getting local host name.";
		WSACleanup();
		BOOST_THROW_EXCEPTION(NoNetworking());
	}

	struct hostent* phe = gethostbyname(ac);
	if (phe == 0)
	{
		clog(NetWarn) << "Bad host lookup.";
		WSACleanup();
		BOOST_THROW_EXCEPTION(NoNetworking());
	}

	for (int i = 0; phe->h_addr_list[i] != 0; ++i)
	{
		struct in_addr addr;
		memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
		char *addrStr = inet_ntoa(addr);
		bi::address address(bi::address::from_string(addrStr));
		if (!isLocalHostAddress(address))
			addresses.insert(address.to_v4());
	}

	WSACleanup();
#else
	ifaddrs* ifaddr;
	if (getifaddrs(&ifaddr) == -1)
		BOOST_THROW_EXCEPTION(NoNetworking());

	for (auto ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
	{
		if (!ifa->ifa_addr || string(ifa->ifa_name) == "lo0")
			continue;

		if (ifa->ifa_addr->sa_family == AF_INET)
		{
			in_addr addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
			boost::asio::ip::address_v4 address(boost::asio::detail::socket_ops::network_to_host_long(addr.s_addr));
			if (!isLocalHostAddress(address))
				addresses.insert(address);
		}
		else if (ifa->ifa_addr->sa_family == AF_INET6)
		{
			sockaddr_in6* sockaddr = ((struct sockaddr_in6 *)ifa->ifa_addr);
			in6_addr addr = sockaddr->sin6_addr;
			boost::asio::ip::address_v6::bytes_type bytes;
			memcpy(&bytes[0], addr.s6_addr, 16);
			boost::asio::ip::address_v6 address(bytes, sockaddr->sin6_scope_id);
			if (!isLocalHostAddress(address))
				addresses.insert(address);
		}
	}

	if (ifaddr!=NULL)
		freeifaddrs(ifaddr);

#endif

	return std::move(addresses);
}

int Network::tcp4Listen(bi::tcp::acceptor& _acceptor, NetworkPreferences const& _netPrefs)
{
	int retport = -1;
	if (_netPrefs.listenIPAddress.empty())
		for (unsigned i = 0; i < 2; ++i)
		{
			// try to connect w/listenPort, else attempt net-allocated port
			bi::tcp::endpoint endpoint(bi::tcp::v4(), i ? 0 : _netPrefs.listenPort);
			try
			{
				_acceptor.open(endpoint.protocol());
				_acceptor.set_option(ba::socket_base::reuse_address(true));
				_acceptor.bind(endpoint);
				_acceptor.listen();
				retport = _acceptor.local_endpoint().port();
				break;
			}
			catch (...)
			{
				if (i)
				{
					// both attempts failed
					cwarn << "Couldn't start accepting connections on host. Something very wrong with network?\n" << boost::current_exception_diagnostic_information();
				}

				// first attempt failed
				_acceptor.close();
				continue;
			}
		}
	else
	{
		bi::tcp::endpoint endpoint(bi::address::from_string(_netPrefs.listenIPAddress), _netPrefs.listenPort);
		try
		{
			_acceptor.open(endpoint.protocol());
			_acceptor.set_option(ba::socket_base::reuse_address(true));
			_acceptor.bind(endpoint);
			_acceptor.listen();
			retport = _acceptor.local_endpoint().port();
		}
		catch (...)
		{
			clog(NetWarn) << "Couldn't start accepting connections on host. Failed to accept socket.\n" << boost::current_exception_diagnostic_information();
		}
		assert(retport == _netPrefs.listenPort);
		return retport;
	}
	return retport;
}

bi::tcp::endpoint Network::traverseNAT(std::set<bi::address> const& _ifAddresses, unsigned short _listenPort, bi::address& o_upnpInterfaceAddr)
{
	asserts(_listenPort != 0);

	UPnP* upnp = nullptr;
	try
	{
		upnp = new UPnP;
	}
	// let m_upnp continue as null - we handle it properly.
	catch (...) {}

	bi::tcp::endpoint upnpEP;
	if (upnp && upnp->isValid())
	{
		bi::address pAddr;
		int extPort = 0;
		for (auto const& addr: _ifAddresses)
			if (addr.is_v4() && isPrivateAddress(addr) && (extPort = upnp->addRedirect(addr.to_string().c_str(), _listenPort)))
			{
				pAddr = addr;
				break;
			}

		auto eIP = upnp->externalIP();
		bi::address eIPAddr(bi::address::from_string(eIP));
		if (extPort && eIP != string("0.0.0.0") && !isPrivateAddress(eIPAddr))
		{
			clog(NetNote) << "Punched through NAT and mapped local port" << _listenPort << "onto external port" << extPort << ".";
			clog(NetNote) << "External addr:" << eIP;
			o_upnpInterfaceAddr = pAddr;
			upnpEP = bi::tcp::endpoint(eIPAddr, (unsigned short)extPort);
		}
		else
			clog(NetWarn) << "Couldn't punch through NAT (or no NAT in place).";

		if (upnp)
			delete upnp;
	}

	return upnpEP;
}

bi::tcp::endpoint Network::resolveHost(string const& _addr)
{
	static boost::asio::io_service s_resolverIoService;

	vector<string> split;
	boost::split(split, _addr, boost::is_any_of(":"));
	unsigned port = split.size() > 1 ? stoi(split[1]) : dev::p2p::c_defaultIPPort;

	bi::tcp::endpoint ep(bi::address(), port);
	boost::system::error_code ec;
	bi::address address = bi::address::from_string(split[0], ec);
	if (!ec)
		ep.address(address);
	else
	{
		boost::system::error_code ec;
		// resolve returns an iterator (host can resolve to multiple addresses)
		bi::tcp::resolver r(s_resolverIoService);
		auto it = r.resolve({split[0], toString(port)}, ec);
		if (ec)
			clog(NetWarn) << "Error resolving host address " << _addr << ":" << ec.message();
		else
			ep = *it;
	}
	return ep;
}

<|endoftext|>


<commit_before><commit_msg>Added $pluswildcard<commit_after><|endoftext|>


<commit_before>// Test doesn't build on windows, because OpenGL on windows is a nightmare.
#ifdef _WIN32
#include <stdio.h>
int main() {
    printf("Skipping test on Windows\n");
    return 0;
}
#else

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <cstring>
#include "../src/runtime/mini_opengl.h"
#include "Halide.h"

extern "C" void glGenTextures(GLsizei, GLuint *);
extern "C" void glTexParameteri(GLenum, GLenum, GLint);
extern "C" void glBindTexture(GLenum, GLuint);
extern "C" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
extern "C" GLuint glCreateProgram();
extern "C" void glAttachShader(GLuint, GLuint);
extern "C" void glLinkProgram(GLuint);
extern "C" void glGetProgramiv(GLuint, GLenum, GLint *);
extern "C" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);
extern "C" GLuint glCreateShader(GLenum);
extern "C" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *);
extern "C" void glCompileShader(GLuint);
extern "C" void glGetShaderiv(GLuint, GLenum, GLint *);
extern "C" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);
extern "C" void glEnable(GLenum);
extern "C" void glDisable(GLenum);
extern "C" void glGetIntegerv(GLenum, GLint *);
extern "C" void glGetBooleanv(GLenum, GLboolean *);
extern "C" GLenum glGetError();
extern "C" void glActiveTexture(GLenum);
extern "C" void glEnableVertexAttribArray(GLuint);
extern "C" void glDisableVertexAttribArray(GLuint);
extern "C" void glUseProgram(GLuint);
extern "C" void glGenBuffers(GLsizei, GLuint *);
extern "C" void glViewport(GLint, GLint, GLsizei, GLsizei);
extern "C" void glGenFramebuffers(GLsizei, GLuint *);
extern "C" void glBindBuffer(GLenum, GLuint);
extern "C" void glBindFramebuffer(GLenum, GLuint);
extern "C" void glGenVertexArrays(GLsizei, GLuint *);
extern "C" void glBindVertexArray(GLuint);
extern "C" void glGetVertexAttribiv(GLuint, GLenum, GLint *);
extern "C" const GLubyte* glGetString(GLenum name);

// Generates an arbitrary program.
class Program
{
    public:

    static GLuint handle()
    {
        const char *vertexShader = " \
                                    attribute vec4 Position;  \
                                    attribute vec2 TexCoordIn; \
                                    varying vec2 TexCoordOut; \
                                    void main(void) {  \
                                        gl_Position = Position; \
                                        TexCoordOut = TexCoordIn; \
                                    }";

        const char *fragmentShader = " \
                                      varying vec2 TexCoordOut; \
                                      uniform sampler2D Texture; \
                                      void main(void) { \
                                          gl_FragColor = texture2D(Texture, TexCoordOut); \
                                      }";

        GLuint handle = glCreateProgram();
        glAttachShader(handle, compileShader("vertex", vertexShader, GL_VERTEX_SHADER));
        glAttachShader(handle, compileShader("fragment", fragmentShader, GL_FRAGMENT_SHADER));
        glLinkProgram(handle);

        GLint linkSuccess;
        glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess);
        if (linkSuccess == GL_FALSE) {
            GLchar messages[256];
            glGetProgramInfoLog(handle, sizeof(messages), 0, messages);
            fprintf(stderr, "Error linking program: %s\n", messages);
            exit(1);
        }

        return handle;
    }

    private:

    static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType)
    {
        const GLuint handle = glCreateShader(shaderType);
        const int len = strlen(shaderString);
        glShaderSource(handle, 1, &shaderString, &len);
        glCompileShader(handle);
        GLint compileSuccess;
        glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess);
        if (compileSuccess == GL_FALSE) {
            GLchar messages[256];
            glGetShaderInfoLog(handle, sizeof(messages), 0, messages);
            fprintf(stderr, "Error compiling %s shader: %s\n", label, messages);
            exit(1);
        }
        return handle;
    }
};

// Encapsulates setting OpenGL's state to arbitrary values, and checking
// whether the state matches those values.
class KnownState
{
    private:

    void gl_enable(GLenum cap, bool state)
    {
        (state ? glEnable : glDisable)(cap);
    }

    GLuint gl_gen(void (*fn)(GLsizei, GLuint *))
    {
        GLuint val;
        (*fn)(1, &val);
        return val;
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLint initial)
    {
        GLint val;
        glGetIntegerv(pname, &val);
        if (val != initial) {
            fprintf(stderr, "%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\n", operation, label, initial, initial, val, val);
            errors = true;
        }
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLenum initial)
    {
        check_value(operation, label, pname, (GLint) initial);
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4)
    {
        GLint val[2048];
        glGetIntegerv(pname, val);
        for (int i=0; i<n; i++) {
            if (val[i] != initial[i]) {
                fprintf(stderr, "%s did not restore %s: initial value was", operation, label);
                for (int j=0; j<n; j++) fprintf(stderr, " %d", initial[j]);
                fprintf(stderr, ", current value is");
                for (int j=0; j<n; j++) fprintf(stderr, " %d", val[j]);
                fprintf(stderr, "\n");
                errors = true;
                return;
            }
        }
    }

    void check_value(const char *operation, const char *label, GLenum pname, bool initial)
    {
        GLboolean val;
        glGetBooleanv(pname, &val);
        if (val != initial) {
            fprintf(stderr, "%s did not restore boolean %s: initial value was %s, current value is %s\n", operation, label, initial ? "true" : "false", val ? "true" : "false");
            errors = true;
        }
    }

    void check_error(const char *label)
    {
        GLenum err = glGetError();
        if (err != GL_NO_ERROR) {
            fprintf(stderr, "Error setting %s: OpenGL error %#x\n", label, err);
            errors = true;
        }
    }

    // version of OpenGL
    int gl_major_version;
    int gl_minor_version;

    GLenum initial_active_texture;
    GLint initial_viewport[4];
    GLuint initial_array_buffer_binding;
    GLuint initial_element_array_buffer_binding;
    GLuint initial_current_program;
    GLuint initial_framebuffer_binding;
    static const int ntextures = 10;
    GLuint initial_bound_textures[ntextures];
    bool initial_cull_face;
    bool initial_depth_test;

    static const int nvertex_attribs = 10;
    bool initial_vertex_attrib_array_enabled[nvertex_attribs];

    // The next two functions are stolen from opengl.cpp
    // and are used to parse the major/minor version of OpenGL
    // to see if vertex array objects are supported
    const char *parse_int(const char *str, int *val) {
        int v = 0;
        size_t i = 0;
        while (str[i] >= '0' && str[i] <= '9') {
            v = 10 * v + (str[i] - '0');
            i++;
        }
        if (i > 0) {
            *val = v;
            return &str[i];
        }
        return NULL;
    }

    const char *parse_opengl_version(const char *str, int *major, int *minor) {
        str = parse_int(str, major);
        if (str == NULL || *str != '.') {
            return NULL;
        }
        return parse_int(str + 1, minor);
    }

    GLuint initial_vertex_array_binding;

    public:

    bool errors;

    // This sets most values to generated or arbitrary values, which the
    // halide calls would be unlikely to accidentally use.  But for boolean
    // values, we want to be sure that halide is really restoring the
    // initial value, not just setting it to true or false.  So we need to
    // be able to try both.
    void setup(bool boolval)
    {
        // parse the OpenGL version
        const char *version = (const char *)glGetString(GL_VERSION);
        parse_opengl_version(version, &gl_major_version, &gl_minor_version);

        glGenTextures(ntextures, initial_bound_textures);
        for (int i=0; i<ntextures; i++) {
            glActiveTexture(GL_TEXTURE0 + i);
            glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]);
        }
	    glActiveTexture(initial_active_texture = GL_TEXTURE3);

        for (int i=0; i<nvertex_attribs; i++) {
            if ( (initial_vertex_attrib_array_enabled[i] = boolval ) )
                glEnableVertexAttribArray(i);
            else
                glDisableVertexAttribArray(i);
            char buf[256];
            sprintf(buf, "vertex attrib array %d state", i);
            check_error(buf);
        }

        glUseProgram(initial_current_program = Program::handle());
        glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444);
        gl_enable(GL_CULL_FACE, initial_cull_face = boolval);
        gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval);
        glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers));
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers));
        glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers));

        // Vertex array objects are only used by Halide if the OpenGL version >=3
        if (gl_major_version >= 3) {
            glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays));
            check_error("known state");
        }
    }

    void check(const char *operation)
    {
        check_value(operation, "ActiveTexture", GL_ACTIVE_TEXTURE, initial_active_texture);
        check_value(operation, "current program", GL_CURRENT_PROGRAM, initial_current_program);
        check_value(operation, "framebuffer binding", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding);
        check_value(operation, "array buffer binding", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding);
        check_value(operation, "element array buffer binding", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding);
        check_value(operation, "viewport", GL_VIEWPORT, initial_viewport);
        check_value(operation, "GL_CULL_FACE", GL_CULL_FACE, initial_cull_face);
        check_value(operation, "GL_DEPTH_TEST", GL_DEPTH_TEST, initial_cull_face);

        // Vertex array objects are only used by Halide if the OpenGL version >=3
        if (gl_major_version >= 3) {
            check_value(operation, "vertex array binding", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding);
        }

        for (int i=0; i<ntextures; i++) {
            char buf[100];
            sprintf(buf, "bound texture (unit %d)", i);
            glActiveTexture(GL_TEXTURE0 + i);
            check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]);
        }

        for (int i=0; i < nvertex_attribs; i++) {
            int initial = initial_vertex_attrib_array_enabled[i];
            GLint val;
            glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val);
            if (val != initial) {
                fprintf(stderr, "%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\n", operation, i, initial ? "true" : "false", val ? "true" : "false");
                errors = true;
            }
        }
    }
};

using namespace Halide;

int main() {
    KnownState known_state;

    Image<uint8_t> input(255, 10, 3);
    Buffer out(UInt(8), 255, 10, 3);

    Var x, y, c;
    Func g;
    g(x, y, c) = input(x, y, c);
    g.bound(c, 0, 3);
    g.glsl(x, y, c);
    g.realize(out); // let Halide initialize OpenGL

    known_state.setup(true);
    g.realize(out);
    known_state.check("realize");

    known_state.setup(true);
    out.copy_to_host();
    known_state.check("copy_to_host");

    known_state.setup(false);
    g.realize(out);
    known_state.check("realize");

    known_state.setup(false);
    out.copy_to_host();
    known_state.check("copy_to_host");

    if (known_state.errors) {
	return 1;
    }

    printf("Success!\n");
    return 0;
}

#endif
<commit_msg>Minor formatting.<commit_after>// Test doesn't build on windows, because OpenGL on windows is a nightmare.
#ifdef _WIN32
#include <stdio.h>
int main() {
    printf("Skipping test on Windows\n");
    return 0;
}
#else

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <cstring>
#include "../src/runtime/mini_opengl.h"
#include "Halide.h"

extern "C" void glGenTextures(GLsizei, GLuint *);
extern "C" void glTexParameteri(GLenum, GLenum, GLint);
extern "C" void glBindTexture(GLenum, GLuint);
extern "C" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
extern "C" GLuint glCreateProgram();
extern "C" void glAttachShader(GLuint, GLuint);
extern "C" void glLinkProgram(GLuint);
extern "C" void glGetProgramiv(GLuint, GLenum, GLint *);
extern "C" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);
extern "C" GLuint glCreateShader(GLenum);
extern "C" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *);
extern "C" void glCompileShader(GLuint);
extern "C" void glGetShaderiv(GLuint, GLenum, GLint *);
extern "C" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);
extern "C" void glEnable(GLenum);
extern "C" void glDisable(GLenum);
extern "C" void glGetIntegerv(GLenum, GLint *);
extern "C" void glGetBooleanv(GLenum, GLboolean *);
extern "C" GLenum glGetError();
extern "C" void glActiveTexture(GLenum);
extern "C" void glEnableVertexAttribArray(GLuint);
extern "C" void glDisableVertexAttribArray(GLuint);
extern "C" void glUseProgram(GLuint);
extern "C" void glGenBuffers(GLsizei, GLuint *);
extern "C" void glViewport(GLint, GLint, GLsizei, GLsizei);
extern "C" void glGenFramebuffers(GLsizei, GLuint *);
extern "C" void glBindBuffer(GLenum, GLuint);
extern "C" void glBindFramebuffer(GLenum, GLuint);
extern "C" void glGenVertexArrays(GLsizei, GLuint *);
extern "C" void glBindVertexArray(GLuint);
extern "C" void glGetVertexAttribiv(GLuint, GLenum, GLint *);
extern "C" const GLubyte* glGetString(GLenum name);

// Generates an arbitrary program.
class Program
{
    public:

    static GLuint handle()
    {
        const char *vertexShader = " \
                                    attribute vec4 Position;  \
                                    attribute vec2 TexCoordIn; \
                                    varying vec2 TexCoordOut; \
                                    void main(void) {  \
                                        gl_Position = Position; \
                                        TexCoordOut = TexCoordIn; \
                                    }";

        const char *fragmentShader = " \
                                      varying vec2 TexCoordOut; \
                                      uniform sampler2D Texture; \
                                      void main(void) { \
                                          gl_FragColor = texture2D(Texture, TexCoordOut); \
                                      }";

        GLuint handle = glCreateProgram();
        glAttachShader(handle, compileShader("vertex", vertexShader, GL_VERTEX_SHADER));
        glAttachShader(handle, compileShader("fragment", fragmentShader, GL_FRAGMENT_SHADER));
        glLinkProgram(handle);

        GLint linkSuccess;
        glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess);
        if (linkSuccess == GL_FALSE) {
            GLchar messages[256];
            glGetProgramInfoLog(handle, sizeof(messages), 0, messages);
            fprintf(stderr, "Error linking program: %s\n", messages);
            exit(1);
        }

        return handle;
    }

    private:

    static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType)
    {
        const GLuint handle = glCreateShader(shaderType);
        const int len = strlen(shaderString);
        glShaderSource(handle, 1, &shaderString, &len);
        glCompileShader(handle);
        GLint compileSuccess;
        glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess);
        if (compileSuccess == GL_FALSE) {
            GLchar messages[256];
            glGetShaderInfoLog(handle, sizeof(messages), 0, messages);
            fprintf(stderr, "Error compiling %s shader: %s\n", label, messages);
            exit(1);
        }
        return handle;
    }
};

// Encapsulates setting OpenGL's state to arbitrary values, and checking
// whether the state matches those values.
class KnownState
{
    private:

    void gl_enable(GLenum cap, bool state)
    {
        (state ? glEnable : glDisable)(cap);
    }

    GLuint gl_gen(void (*fn)(GLsizei, GLuint *))
    {
        GLuint val;
        (*fn)(1, &val);
        return val;
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLint initial)
    {
        GLint val;
        glGetIntegerv(pname, &val);
        if (val != initial) {
            fprintf(stderr, "%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\n", operation, label, initial, initial, val, val);
            errors = true;
        }
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLenum initial)
    {
        check_value(operation, label, pname, (GLint) initial);
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4)
    {
        GLint val[2048];
        glGetIntegerv(pname, val);
        for (int i=0; i<n; i++) {
            if (val[i] != initial[i]) {
                fprintf(stderr, "%s did not restore %s: initial value was", operation, label);
                for (int j=0; j<n; j++) fprintf(stderr, " %d", initial[j]);
                fprintf(stderr, ", current value is");
                for (int j=0; j<n; j++) fprintf(stderr, " %d", val[j]);
                fprintf(stderr, "\n");
                errors = true;
                return;
            }
        }
    }

    void check_value(const char *operation, const char *label, GLenum pname, bool initial)
    {
        GLboolean val;
        glGetBooleanv(pname, &val);
        if (val != initial) {
            fprintf(stderr, "%s did not restore boolean %s: initial value was %s, current value is %s\n", operation, label, initial ? "true" : "false", val ? "true" : "false");
            errors = true;
        }
    }

    void check_error(const char *label)
    {
        GLenum err = glGetError();
        if (err != GL_NO_ERROR) {
            fprintf(stderr, "Error setting %s: OpenGL error %#x\n", label, err);
            errors = true;
        }
    }

    // version of OpenGL
    int gl_major_version;
    int gl_minor_version;

    GLenum initial_active_texture;
    GLint initial_viewport[4];
    GLuint initial_array_buffer_binding;
    GLuint initial_element_array_buffer_binding;
    GLuint initial_current_program;
    GLuint initial_framebuffer_binding;
    static const int ntextures = 10;
    GLuint initial_bound_textures[ntextures];
    bool initial_cull_face;
    bool initial_depth_test;

    static const int nvertex_attribs = 10;
    bool initial_vertex_attrib_array_enabled[nvertex_attribs];

    // The next two functions are stolen from opengl.cpp
    // and are used to parse the major/minor version of OpenGL
    // to see if vertex array objects are supported
    const char *parse_int(const char *str, int *val) {
        int v = 0;
        size_t i = 0;
        while (str[i] >= '0' && str[i] <= '9') {
            v = 10 * v + (str[i] - '0');
            i++;
        }
        if (i > 0) {
            *val = v;
            return &str[i];
        }
        return NULL;
    }

    const char *parse_opengl_version(const char *str, int *major, int *minor) {
        str = parse_int(str, major);
        if (str == NULL || *str != '.') {
            return NULL;
        }
        return parse_int(str + 1, minor);
    }

    GLuint initial_vertex_array_binding;

    public:

    bool errors;

    // This sets most values to generated or arbitrary values, which the
    // halide calls would be unlikely to accidentally use.  But for boolean
    // values, we want to be sure that halide is really restoring the
    // initial value, not just setting it to true or false.  So we need to
    // be able to try both.
    void setup(bool boolval)
    {
        // parse the OpenGL version
        const char *version = (const char *)glGetString(GL_VERSION);
        parse_opengl_version(version, &gl_major_version, &gl_minor_version);

        glGenTextures(ntextures, initial_bound_textures);
        for (int i=0; i<ntextures; i++) {
            glActiveTexture(GL_TEXTURE0 + i);
            glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]);
        }
        glActiveTexture(initial_active_texture = GL_TEXTURE3);

        for (int i=0; i<nvertex_attribs; i++) {
            if ( (initial_vertex_attrib_array_enabled[i] = boolval ) )
                glEnableVertexAttribArray(i);
            else
                glDisableVertexAttribArray(i);
            char buf[256];
            sprintf(buf, "vertex attrib array %d state", i);
            check_error(buf);
        }

        glUseProgram(initial_current_program = Program::handle());
        glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444);
        gl_enable(GL_CULL_FACE, initial_cull_face = boolval);
        gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval);
        glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers));
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers));
        glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers));

        // Vertex array objects are only used by Halide if the OpenGL version >=3
        if (gl_major_version >= 3) {
            glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays));
            check_error("known state");
        }
    }

    void check(const char *operation)
    {
        check_value(operation, "ActiveTexture", GL_ACTIVE_TEXTURE, initial_active_texture);
        check_value(operation, "current program", GL_CURRENT_PROGRAM, initial_current_program);
        check_value(operation, "framebuffer binding", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding);
        check_value(operation, "array buffer binding", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding);
        check_value(operation, "element array buffer binding", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding);
        check_value(operation, "viewport", GL_VIEWPORT, initial_viewport);
        check_value(operation, "GL_CULL_FACE", GL_CULL_FACE, initial_cull_face);
        check_value(operation, "GL_DEPTH_TEST", GL_DEPTH_TEST, initial_cull_face);

        // Vertex array objects are only used by Halide if the OpenGL version >=3
        if (gl_major_version >= 3) {
            check_value(operation, "vertex array binding", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding);
        }

        for (int i=0; i<ntextures; i++) {
            char buf[100];
            sprintf(buf, "bound texture (unit %d)", i);
            glActiveTexture(GL_TEXTURE0 + i);
            check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]);
        }

        for (int i=0; i < nvertex_attribs; i++) {
            int initial = initial_vertex_attrib_array_enabled[i];
            GLint val;
            glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val);
            if (val != initial) {
                fprintf(stderr, "%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\n", operation, i, initial ? "true" : "false", val ? "true" : "false");
                errors = true;
            }
        }
    }
};

using namespace Halide;

int main() {
    KnownState known_state;

    Image<uint8_t> input(255, 10, 3);
    Buffer out(UInt(8), 255, 10, 3);

    Var x, y, c;
    Func g;
    g(x, y, c) = input(x, y, c);
    g.bound(c, 0, 3);
    g.glsl(x, y, c);
    g.realize(out); // let Halide initialize OpenGL

    known_state.setup(true);
    g.realize(out);
    known_state.check("realize");

    known_state.setup(true);
    out.copy_to_host();
    known_state.check("copy_to_host");

    known_state.setup(false);
    g.realize(out);
    known_state.check("realize");

    known_state.setup(false);
    out.copy_to_host();
    known_state.check("copy_to_host");

    if (known_state.errors) {
	return 1;
    }

    printf("Success!\n");
    return 0;
}

#endif
<|endoftext|>


<commit_before>// Test doesn't build on windows, because OpenGL on windows is a nightmare.
#ifdef _WIN32
#include <stdio.h>
int main() {
    printf("Skipping test on Windows\n");
    return 0;
}
#else

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <cstring>
#include "../src/runtime/mini_opengl.h"
#include "Halide.h"

extern "C" void glGenTextures(GLsizei, GLuint *);
extern "C" void glTexParameteri(GLenum, GLenum, GLint);
extern "C" void glBindTexture(GLenum, GLuint);
extern "C" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
extern "C" GLuint glCreateProgram();
extern "C" void glAttachShader(GLuint, GLuint);
extern "C" void glLinkProgram(GLuint);
extern "C" void glGetProgramiv(GLuint, GLenum, GLint *);
extern "C" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);
extern "C" GLuint glCreateShader(GLenum);
extern "C" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *);
extern "C" void glCompileShader(GLuint);
extern "C" void glGetShaderiv(GLuint, GLenum, GLint *);
extern "C" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);
extern "C" void glEnable(GLenum);
extern "C" void glDisable(GLenum);
extern "C" void glGetIntegerv(GLenum, GLint *);
extern "C" void glGetBooleanv(GLenum, GLboolean *);
extern "C" GLenum glGetError();
extern "C" void glActiveTexture(GLenum);
extern "C" void glEnableVertexAttribArray(GLuint);
extern "C" void glDisableVertexAttribArray(GLuint);
extern "C" void glUseProgram(GLuint);
extern "C" void glGenBuffers(GLsizei, GLuint *);
extern "C" void glViewport(GLint, GLint, GLsizei, GLsizei);
extern "C" void glGenFramebuffers(GLsizei, GLuint *);
extern "C" void glBindBuffer(GLenum, GLuint);
extern "C" void glBindFramebuffer(GLenum, GLuint);
extern "C" void glGenVertexArrays(GLsizei, GLuint *);
extern "C" void glBindVertexArray(GLuint);
extern "C" void glGetVertexAttribiv(GLuint, GLenum, GLint *);
extern "C" const GLubyte* glGetString(GLenum name);

// Generates an arbitrary program.
class Program
{
    public:

    static GLuint handle()
    {
        const char *vertexShader = " \
                                    attribute vec4 Position;  \
                                    attribute vec2 TexCoordIn; \
                                    varying vec2 TexCoordOut; \
                                    void main(void) {  \
                                        gl_Position = Position; \
                                        TexCoordOut = TexCoordIn; \
                                    }";

        const char *fragmentShader = " \
                                      varying vec2 TexCoordOut; \
                                      uniform sampler2D Texture; \
                                      void main(void) { \
                                          gl_FragColor = texture2D(Texture, TexCoordOut); \
                                      }";

        GLuint handle = glCreateProgram();
        glAttachShader(handle, compileShader("vertex", vertexShader, GL_VERTEX_SHADER));
        glAttachShader(handle, compileShader("fragment", fragmentShader, GL_FRAGMENT_SHADER));
        glLinkProgram(handle);

        GLint linkSuccess;
        glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess);
        if (linkSuccess == GL_FALSE) {
            GLchar messages[256];
            glGetProgramInfoLog(handle, sizeof(messages), 0, messages);
            fprintf(stderr, "Error linking program: %s\n", messages);
            exit(1);
        }

        return handle;
    }

    private:

    static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType)
    {
        const GLuint handle = glCreateShader(shaderType);
        const int len = strlen(shaderString);
        glShaderSource(handle, 1, &shaderString, &len);
        glCompileShader(handle);
        GLint compileSuccess;
        glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess);
        if (compileSuccess == GL_FALSE) {
            GLchar messages[256];
            glGetShaderInfoLog(handle, sizeof(messages), 0, messages);
            fprintf(stderr, "Error compiling %s shader: %s\n", label, messages);
            exit(1);
        }
        return handle;
    }
};

// Encapsulates setting OpenGL's state to arbitrary values, and checking
// whether the state matches those values.
class KnownState
{
    private:

    void gl_enable(GLenum cap, bool state)
    {
        (state ? glEnable : glDisable)(cap);
    }

    GLuint gl_gen(void (*fn)(GLsizei, GLuint *))
    {
        GLuint val;
        (*fn)(1, &val);
        return val;
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLint initial)
    {
        GLint val;
        glGetIntegerv(pname, &val);
        if (val != initial) {
            fprintf(stderr, "%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\n", operation, label, initial, initial, val, val);
            errors = true;
        }
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLenum initial)
    {
        check_value(operation, label, pname, (GLint) initial);
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4)
    {
        GLint val[2048];
        glGetIntegerv(pname, val);
        for (int i=0; i<n; i++) {
            if (val[i] != initial[i]) {
                fprintf(stderr, "%s did not restore %s: initial value was", operation, label);
                for (int j=0; j<n; j++) fprintf(stderr, " %d", initial[j]);
                fprintf(stderr, ", current value is");
                for (int j=0; j<n; j++) fprintf(stderr, " %d", val[j]);
                fprintf(stderr, "\n");
                errors = true;
                return;
            }
        }
    }

    void check_value(const char *operation, const char *label, GLenum pname, bool initial)
    {
        GLboolean val;
        glGetBooleanv(pname, &val);
        if (val != initial) {
            fprintf(stderr, "%s did not restore boolean %s: initial value was %s, current value is %s\n", operation, label, initial ? "true" : "false", val ? "true" : "false");
            errors = true;
        }
    }

    void check_error(const char *label)
    {
        GLenum err = glGetError();
        if (err != GL_NO_ERROR) {
            fprintf(stderr, "Error setting %s: OpenGL error %#x\n", label, err);
            errors = true;
        }
    }

    // version of OpenGL
    int gl_major_version;
    int gl_minor_version;

    GLenum initial_active_texture;
    GLint initial_viewport[4];
    GLuint initial_array_buffer_binding;
    GLuint initial_element_array_buffer_binding;
    GLuint initial_current_program;
    GLuint initial_framebuffer_binding;
    static const int ntextures = 10;
    GLuint initial_bound_textures[ntextures];
    bool initial_cull_face;
    bool initial_depth_test;

    static const int nvertex_attribs = 10;
    bool initial_vertex_attrib_array_enabled[nvertex_attribs];

    // The next two functions are stolen from opengl.cpp
    // and are used to parse the major/minor version of OpenGL
    // to see if vertex array objects are supported
    const char *parse_int(const char *str, int *val) {
        int v = 0;
        size_t i = 0;
        while (str[i] >= '0' && str[i] <= '9') {
            v = 10 * v + (str[i] - '0');
            i++;
        }
        if (i > 0) {
            *val = v;
            return &str[i];
        }
        return NULL;
    }

    const char *parse_opengl_version(const char *str, int *major, int *minor) {
        str = parse_int(str, major);
        if (str == NULL || *str != '.') {
            return NULL;
        }
        return parse_int(str + 1, minor);
    }

    GLuint initial_vertex_array_binding;

    public:

    bool errors;

    // This sets most values to generated or arbitrary values, which the
    // halide calls would be unlikely to accidentally use.  But for boolean
    // values, we want to be sure that halide is really restoring the
    // initial value, not just setting it to true or false.  So we need to
    // be able to try both.
    void setup(bool boolval)
    {
        // parse the OpenGL version
        const char *version = (const char *)glGetString(GL_VERSION);
        parse_opengl_version(version, &gl_major_version, &gl_minor_version);

        glGenTextures(ntextures, initial_bound_textures);
        for (int i=0; i<ntextures; i++) {
            glActiveTexture(GL_TEXTURE0 + i);
            glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]);
        }
        glActiveTexture(initial_active_texture = GL_TEXTURE3);

        for (int i=0; i<nvertex_attribs; i++) {
            if ( (initial_vertex_attrib_array_enabled[i] = boolval ) )
                glEnableVertexAttribArray(i);
            else
                glDisableVertexAttribArray(i);
            char buf[256];
            sprintf(buf, "vertex attrib array %d state", i);
            check_error(buf);
        }

        glUseProgram(initial_current_program = Program::handle());
        glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444);
        gl_enable(GL_CULL_FACE, initial_cull_face = boolval);
        gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval);
        glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers));
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers));
        glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers));

        // Vertex array objects are only used by Halide if the OpenGL version >=3
        if (gl_major_version >= 3) {
            glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays));
        }

        check_error("known state");
    }

    void check(const char *operation)
    {
        check_value(operation, "ActiveTexture", GL_ACTIVE_TEXTURE, initial_active_texture);
        check_value(operation, "current program", GL_CURRENT_PROGRAM, initial_current_program);
        check_value(operation, "framebuffer binding", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding);
        check_value(operation, "array buffer binding", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding);
        check_value(operation, "element array buffer binding", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding);
        check_value(operation, "viewport", GL_VIEWPORT, initial_viewport);
        check_value(operation, "GL_CULL_FACE", GL_CULL_FACE, initial_cull_face);
        check_value(operation, "GL_DEPTH_TEST", GL_DEPTH_TEST, initial_cull_face);

        // Vertex array objects are only used by Halide if the OpenGL version >=3
        if (gl_major_version >= 3) {
            check_value(operation, "vertex array binding", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding);
        } else {
            fprintf(stderr, "Skipping vertex array binding tests because OpenGL version is %d.%d (<3.0)\n", gl_major_version, gl_minor_version);
        }

        for (int i=0; i<ntextures; i++) {
            char buf[100];
            sprintf(buf, "bound texture (unit %d)", i);
            glActiveTexture(GL_TEXTURE0 + i);
            check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]);
        }

        for (int i=0; i < nvertex_attribs; i++) {
            int initial = initial_vertex_attrib_array_enabled[i];
            GLint val;
            glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val);
            if (val != initial) {
                fprintf(stderr, "%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\n", operation, i, initial ? "true" : "false", val ? "true" : "false");
                errors = true;
            }
        }
    }
};

using namespace Halide;

int main() {
    // This test must be run with an OpenGL target.
    const Target target = get_jit_target_from_environment().with_feature(Target::OpenGL);

    KnownState known_state;

    Image<uint8_t> input(255, 10, 3);
    Image<uint8_t> out(UInt(8), 255, 10, 3);

    Var x, y, c;
    Func g;
    g(x, y, c) = input(x, y, c);
    g.bound(c, 0, 3);
    g.glsl(x, y, c);
    g.realize(out, target); // let Halide initialize OpenGL

    known_state.setup(true);
    g.realize(out, target);
    known_state.check("realize");

    known_state.setup(true);
    out.copy_to_host();
    known_state.check("copy_to_host");

    known_state.setup(false);
    g.realize(out, target);
    known_state.check("realize");

    known_state.setup(false);
    out.copy_to_host();
    known_state.check("copy_to_host");

    if (known_state.errors) {
	return 1;
    }

    printf("Success!\n");
    return 0;
}

#endif
<commit_msg>Initialize 'errors' field in save_state test<commit_after>// Test doesn't build on windows, because OpenGL on windows is a nightmare.
#ifdef _WIN32
#include <stdio.h>
int main() {
    printf("Skipping test on Windows\n");
    return 0;
}
#else

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <cstring>
#include "../src/runtime/mini_opengl.h"
#include "Halide.h"

extern "C" void glGenTextures(GLsizei, GLuint *);
extern "C" void glTexParameteri(GLenum, GLenum, GLint);
extern "C" void glBindTexture(GLenum, GLuint);
extern "C" void glTexImage2D(GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
extern "C" GLuint glCreateProgram();
extern "C" void glAttachShader(GLuint, GLuint);
extern "C" void glLinkProgram(GLuint);
extern "C" void glGetProgramiv(GLuint, GLenum, GLint *);
extern "C" void glGetProgramInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);
extern "C" GLuint glCreateShader(GLenum);
extern "C" void glShaderSource(GLuint, GLsizei, const GLchar **, const GLint *);
extern "C" void glCompileShader(GLuint);
extern "C" void glGetShaderiv(GLuint, GLenum, GLint *);
extern "C" void glGetShaderInfoLog(GLuint, GLsizei, GLsizei *, GLchar *);
extern "C" void glEnable(GLenum);
extern "C" void glDisable(GLenum);
extern "C" void glGetIntegerv(GLenum, GLint *);
extern "C" void glGetBooleanv(GLenum, GLboolean *);
extern "C" GLenum glGetError();
extern "C" void glActiveTexture(GLenum);
extern "C" void glEnableVertexAttribArray(GLuint);
extern "C" void glDisableVertexAttribArray(GLuint);
extern "C" void glUseProgram(GLuint);
extern "C" void glGenBuffers(GLsizei, GLuint *);
extern "C" void glViewport(GLint, GLint, GLsizei, GLsizei);
extern "C" void glGenFramebuffers(GLsizei, GLuint *);
extern "C" void glBindBuffer(GLenum, GLuint);
extern "C" void glBindFramebuffer(GLenum, GLuint);
extern "C" void glGenVertexArrays(GLsizei, GLuint *);
extern "C" void glBindVertexArray(GLuint);
extern "C" void glGetVertexAttribiv(GLuint, GLenum, GLint *);
extern "C" const GLubyte* glGetString(GLenum name);

// Generates an arbitrary program.
class Program
{
    public:

    static GLuint handle()
    {
        const char *vertexShader = " \
                                    attribute vec4 Position;  \
                                    attribute vec2 TexCoordIn; \
                                    varying vec2 TexCoordOut; \
                                    void main(void) {  \
                                        gl_Position = Position; \
                                        TexCoordOut = TexCoordIn; \
                                    }";

        const char *fragmentShader = " \
                                      varying vec2 TexCoordOut; \
                                      uniform sampler2D Texture; \
                                      void main(void) { \
                                          gl_FragColor = texture2D(Texture, TexCoordOut); \
                                      }";

        GLuint handle = glCreateProgram();
        glAttachShader(handle, compileShader("vertex", vertexShader, GL_VERTEX_SHADER));
        glAttachShader(handle, compileShader("fragment", fragmentShader, GL_FRAGMENT_SHADER));
        glLinkProgram(handle);

        GLint linkSuccess;
        glGetProgramiv(handle, GL_LINK_STATUS, &linkSuccess);
        if (linkSuccess == GL_FALSE) {
            GLchar messages[256];
            glGetProgramInfoLog(handle, sizeof(messages), 0, messages);
            fprintf(stderr, "Error linking program: %s\n", messages);
            exit(1);
        }

        return handle;
    }

    private:

    static GLuint compileShader(const char *label, const char *shaderString, GLenum shaderType)
    {
        const GLuint handle = glCreateShader(shaderType);
        const int len = strlen(shaderString);
        glShaderSource(handle, 1, &shaderString, &len);
        glCompileShader(handle);
        GLint compileSuccess;
        glGetShaderiv(handle, GL_COMPILE_STATUS, &compileSuccess);
        if (compileSuccess == GL_FALSE) {
            GLchar messages[256];
            glGetShaderInfoLog(handle, sizeof(messages), 0, messages);
            fprintf(stderr, "Error compiling %s shader: %s\n", label, messages);
            exit(1);
        }
        return handle;
    }
};

// Encapsulates setting OpenGL's state to arbitrary values, and checking
// whether the state matches those values.
class KnownState
{
    private:

    void gl_enable(GLenum cap, bool state)
    {
        (state ? glEnable : glDisable)(cap);
    }

    GLuint gl_gen(void (*fn)(GLsizei, GLuint *))
    {
        GLuint val;
        (*fn)(1, &val);
        return val;
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLint initial)
    {
        GLint val;
        glGetIntegerv(pname, &val);
        if (val != initial) {
            fprintf(stderr, "%s did not restore %s: initial value was %d (%#x), current value is %d (%#x)\n", operation, label, initial, initial, val, val);
            errors = true;
        }
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLenum initial)
    {
        check_value(operation, label, pname, (GLint) initial);
    }

    void check_value(const char *operation, const char *label, GLenum pname, GLint initial[], int n=4)
    {
        GLint val[2048];
        glGetIntegerv(pname, val);
        for (int i=0; i<n; i++) {
            if (val[i] != initial[i]) {
                fprintf(stderr, "%s did not restore %s: initial value was", operation, label);
                for (int j=0; j<n; j++) fprintf(stderr, " %d", initial[j]);
                fprintf(stderr, ", current value is");
                for (int j=0; j<n; j++) fprintf(stderr, " %d", val[j]);
                fprintf(stderr, "\n");
                errors = true;
                return;
            }
        }
    }

    void check_value(const char *operation, const char *label, GLenum pname, bool initial)
    {
        GLboolean val;
        glGetBooleanv(pname, &val);
        if (val != initial) {
            fprintf(stderr, "%s did not restore boolean %s: initial value was %s, current value is %s\n", operation, label, initial ? "true" : "false", val ? "true" : "false");
            errors = true;
        }
    }

    void check_error(const char *label)
    {
        GLenum err = glGetError();
        if (err != GL_NO_ERROR) {
            fprintf(stderr, "Error setting %s: OpenGL error %#x\n", label, err);
            errors = true;
        }
    }

    // version of OpenGL
    int gl_major_version;
    int gl_minor_version;

    GLenum initial_active_texture;
    GLint initial_viewport[4];
    GLuint initial_array_buffer_binding;
    GLuint initial_element_array_buffer_binding;
    GLuint initial_current_program;
    GLuint initial_framebuffer_binding;
    static const int ntextures = 10;
    GLuint initial_bound_textures[ntextures];
    bool initial_cull_face;
    bool initial_depth_test;

    static const int nvertex_attribs = 10;
    bool initial_vertex_attrib_array_enabled[nvertex_attribs];

    // The next two functions are stolen from opengl.cpp
    // and are used to parse the major/minor version of OpenGL
    // to see if vertex array objects are supported
    const char *parse_int(const char *str, int *val) {
        int v = 0;
        size_t i = 0;
        while (str[i] >= '0' && str[i] <= '9') {
            v = 10 * v + (str[i] - '0');
            i++;
        }
        if (i > 0) {
            *val = v;
            return &str[i];
        }
        return NULL;
    }

    const char *parse_opengl_version(const char *str, int *major, int *minor) {
        str = parse_int(str, major);
        if (str == NULL || *str != '.') {
            return NULL;
        }
        return parse_int(str + 1, minor);
    }

    GLuint initial_vertex_array_binding;

    public:

    bool errors{false};

    // This sets most values to generated or arbitrary values, which the
    // halide calls would be unlikely to accidentally use.  But for boolean
    // values, we want to be sure that halide is really restoring the
    // initial value, not just setting it to true or false.  So we need to
    // be able to try both.
    void setup(bool boolval)
    {
        // parse the OpenGL version
        const char *version = (const char *)glGetString(GL_VERSION);
        parse_opengl_version(version, &gl_major_version, &gl_minor_version);

        glGenTextures(ntextures, initial_bound_textures);
        for (int i=0; i<ntextures; i++) {
            glActiveTexture(GL_TEXTURE0 + i);
            glBindTexture(GL_TEXTURE_2D, initial_bound_textures[i]);
        }
        glActiveTexture(initial_active_texture = GL_TEXTURE3);

        for (int i=0; i<nvertex_attribs; i++) {
            if ( (initial_vertex_attrib_array_enabled[i] = boolval ) )
                glEnableVertexAttribArray(i);
            else
                glDisableVertexAttribArray(i);
            char buf[256];
            sprintf(buf, "vertex attrib array %d state", i);
            check_error(buf);
        }

        glUseProgram(initial_current_program = Program::handle());
        glViewport(initial_viewport[0] = 111, initial_viewport[1] = 222, initial_viewport[2] = 333, initial_viewport[3] = 444);
        gl_enable(GL_CULL_FACE, initial_cull_face = boolval);
        gl_enable(GL_DEPTH_TEST, initial_depth_test = boolval);
        glBindBuffer(GL_ARRAY_BUFFER, initial_array_buffer_binding = gl_gen(glGenBuffers));
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, initial_element_array_buffer_binding = gl_gen(glGenBuffers));
        glBindFramebuffer(GL_FRAMEBUFFER, initial_framebuffer_binding = gl_gen(glGenFramebuffers));

        // Vertex array objects are only used by Halide if the OpenGL version >=3
        if (gl_major_version >= 3) {
            glBindVertexArray(initial_vertex_array_binding = gl_gen(glGenVertexArrays));
        }

        check_error("known state");
    }

    void check(const char *operation)
    {
        check_value(operation, "ActiveTexture", GL_ACTIVE_TEXTURE, initial_active_texture);
        check_value(operation, "current program", GL_CURRENT_PROGRAM, initial_current_program);
        check_value(operation, "framebuffer binding", GL_FRAMEBUFFER_BINDING, initial_framebuffer_binding);
        check_value(operation, "array buffer binding", GL_ARRAY_BUFFER_BINDING, initial_array_buffer_binding);
        check_value(operation, "element array buffer binding", GL_ELEMENT_ARRAY_BUFFER_BINDING, initial_element_array_buffer_binding);
        check_value(operation, "viewport", GL_VIEWPORT, initial_viewport);
        check_value(operation, "GL_CULL_FACE", GL_CULL_FACE, initial_cull_face);
        check_value(operation, "GL_DEPTH_TEST", GL_DEPTH_TEST, initial_cull_face);

        // Vertex array objects are only used by Halide if the OpenGL version >=3
        if (gl_major_version >= 3) {
            check_value(operation, "vertex array binding", GL_VERTEX_ARRAY_BINDING, initial_vertex_array_binding);
        } else {
            fprintf(stderr, "Skipping vertex array binding tests because OpenGL version is %d.%d (<3.0)\n", gl_major_version, gl_minor_version);
        }

        for (int i=0; i<ntextures; i++) {
            char buf[100];
            sprintf(buf, "bound texture (unit %d)", i);
            glActiveTexture(GL_TEXTURE0 + i);
            check_value(operation, buf, GL_TEXTURE_BINDING_2D, initial_bound_textures[i]);
        }

        for (int i=0; i < nvertex_attribs; i++) {
            int initial = initial_vertex_attrib_array_enabled[i];
            GLint val;
            glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &val);
            if (val != initial) {
                fprintf(stderr, "%s did not restore boolean VertexAttributeArrayEnabled(%d): initial value was %s, current value is %s\n", operation, i, initial ? "true" : "false", val ? "true" : "false");
                errors = true;
            }
        }
    }
};

using namespace Halide;

int main() {
    // This test must be run with an OpenGL target.
    const Target target = get_jit_target_from_environment().with_feature(Target::OpenGL);

    KnownState known_state;

    Image<uint8_t> input(255, 10, 3);
    Image<uint8_t> out(UInt(8), 255, 10, 3);

    Var x, y, c;
    Func g;
    g(x, y, c) = input(x, y, c);
    g.bound(c, 0, 3);
    g.glsl(x, y, c);
    g.realize(out, target); // let Halide initialize OpenGL

    known_state.setup(true);
    g.realize(out, target);
    known_state.check("realize");

    known_state.setup(true);
    out.copy_to_host();
    known_state.check("copy_to_host");

    known_state.setup(false);
    g.realize(out, target);
    known_state.check("realize");

    known_state.setup(false);
    out.copy_to_host();
    known_state.check("copy_to_host");

    if (known_state.errors) {
	return 1;
    }

    printf("Success!\n");
    return 0;
}

#endif
<|endoftext|>