<commit_before>#ifndef TOOLBOX_HH
#define TOOLBOX_HH

#include <deque>

#include "io.hh"
#include "WordGraph.hh"
#include "NowayHmmReader.hh"
#include "NowayLexiconReader.hh"
#include "TPNowayLexReader.hh"
#include "LnaReaderCircular.hh"
#include "Expander.hh"
#include "Search.hh"
#include "TokenPassSearch.hh"
#include "OneFrameAcoustics.hh"

class Toolbox {
public:
  Toolbox();
  ~Toolbox();

  // Decoder selection: 0=token pass, 1 = stack
  void select_decoder(int stack_dec) { m_use_stack_decoder = stack_dec; }

  // HMM models
  void hmm_read(const char *file);
  void duration_read(const char *dur_file);
  const std::vector<Hmm> &hmms() const { return m_hmms; }

  // Lexicon

  /// \brief Reads a dictionary file that specifies the lexicon and
  /// pronunciations used in the decoding.
  ///
  /// \param file Name of a NOWAY dictionary file where the lexicon is
  /// read from.
  ///
  void lex_read(const char *file);

  const std::string &lex_word() const { return m_lexicon_reader.word(); }
  const std::string &lex_phone() const { return m_lexicon_reader.phone(); }
  const std::string &word(int index) const
  {
    if (m_use_stack_decoder)
      return m_vocabulary.word(index);
    return m_tp_vocabulary.word(index);
  }

  // Ngram
  void ngram_read(const char *file, float weight, bool binary=true);
  void read_lookahead_ngram(const char *file, bool binary=true);

  /// \brief Reads a finite-state automaton language model.
  ///
  /// \param file Name of the file where the language model is read from.
  /// \param binary If set to true, the file is expected to be in a non-standard
  /// format that lm utility writes. Otherwise ARPA format is expected.
  ///
  void fsa_lm_read(const char *file, bool binary=true);

  // Lna
  void lna_open(const char *file, int size);
  void lna_close();
  void lna_seek(int frame) { m_lna_reader.seek(frame); }
  Acoustics &acoustics() { return *m_acoustics; }
  void use_one_frame_acoustics()
  {
    m_acoustics = &m_one_frame_acoustics;
    m_tp_search.set_acoustics(m_acoustics);
  }
  void set_one_frame(int frame, const std::vector<float> log_probs)
  {
    assert(m_acoustics == &m_one_frame_acoustics);
    m_one_frame_acoustics.set(frame, log_probs);
  }

  // Expander
  void expand(int frame, int frames);
  const std::string &best_word();
  void print_words(int words);
  int find_word(const std::string &word);
  std::vector<Expander::Word*> words() { return m_expander.words(); }

  // Stack search
  void init(int expand_window);
  bool expand_stack(int frame) { return m_search.expand_stack(frame); }
  void expand_words(int frame, const std::string &words)
  { m_search.expand_words(frame, words); }
  void go(int frame) { m_search.go(frame); }
  bool runto(int frame);
  bool recognize_segment(int start_frame, int end_frame);

  // Both searches
  void reset(int frame) { if (m_use_stack_decoder) m_search.reset_search(frame);  else m_tp_search.reset_search(frame);}
  void set_end(int frame) { if (m_use_stack_decoder) m_search.set_end_frame(frame); else m_tp_search.set_end_frame(frame); }
  bool run() { return (m_use_stack_decoder?m_search.run():m_tp_search.run()); }

  // Token pass search
  WordGraph &tp_word_graph() { return m_tp_search.word_graph; }
  void write_word_graph(const std::string &file_name)
  { m_tp_search.write_word_graph(file_name); }
  void print_best_lm_history(FILE *out=stdout)
  {
    m_tp_search.print_lm_history(out, true);
  }
  void print_best_lm_history_to_file(FILE *out) {print_best_lm_history(out);}

  // Miscellaneous
  void segment(const std::string &str, int start_frame, int end_frame);

  // Info
  TokenPassSearch &tp_search() { return m_tp_search; }
  int frame() { return (m_use_stack_decoder?m_search.frame():m_tp_search.frame()); }
  int first_frame() { return m_search.first_frame(); }
  int last_frame() { return m_search.last_frame(); }
  HypoStack &stack(int frame) { return m_search.stack(frame); }
  void prune(int frame, int top);
  int paths() const { return HypoPath::g_count; }

  // Options
  void set_forced_end(bool forced_end)
  { m_expander.set_forced_end(forced_end); }
  void set_hypo_limit(int hypo_limit) { m_search.set_hypo_limit(hypo_limit); }
  void set_prune_similar(int prune_similar) { m_search.set_prune_similar(prune_similar); m_tp_search.set_similar_lm_history_span(prune_similar); }
  void set_word_limit(int word_limit) { m_search.set_word_limit(word_limit); }
  void set_word_beam(float word_beam) { m_search.set_word_beam(word_beam); }
  void set_lm_scale(float lm_scale) { m_search.set_lm_scale(lm_scale); m_tp_search.set_lm_scale(lm_scale); }
  void set_lm_offset(float lm_offset) { m_search.set_lm_offset(lm_offset); }
  void set_unk_offset(float unk_offset) { m_search.set_unk_offset(unk_offset); }
  void set_token_limit(int limit) { m_expander.set_token_limit(limit); m_tp_search.set_max_num_tokens(limit); }
  void set_state_beam(float beam) { m_expander.set_beam(beam); }
  void set_duration_scale(float scale) { m_expander.set_duration_scale(scale); m_tp_search.set_duration_scale(scale); }
  void set_transition_scale(float scale) { m_expander.set_transition_scale(scale); m_tp_search.set_transition_scale(scale); }
  void set_rabiner_post_mode(int mode) { m_expander.set_rabiner_post_mode(mode); }
  void set_hypo_beam(float beam) { m_search.set_hypo_beam(beam); }
  void set_global_beam(float beam)
  { m_search.set_global_beam(beam); m_tp_search.set_global_beam(beam); }
  void set_word_end_beam(float beam) { m_tp_search.set_word_end_beam(beam); }
  void set_eq_depth_beam(float beam) { m_tp_search.set_eq_depth_beam(beam); }
  void set_eq_word_count_beam(float beam) { m_tp_search.set_eq_word_count_beam(beam); }
  void set_fan_in_beam(float beam) { m_tp_search.set_fan_in_beam(beam); }
  void set_fan_out_beam(float beam) { m_tp_search.set_fan_out_beam(beam); }
  void set_tp_state_beam(float beam) { m_tp_search.set_state_beam(beam); }
  void set_max_state_duration(int duration)
  { m_expander.set_max_state_duration(duration); }
  void set_lm_lookahead(int lmlh) { m_tp_lexicon.set_lm_lookahead(lmlh); m_tp_search.set_lm_lookahead(lmlh); }
  void set_cross_word_triphones(bool cw_triphones) { m_tp_lexicon.set_cross_word_triphones(cw_triphones); }
  void set_insertion_penalty(float ip) { m_tp_search.set_insertion_penalty(ip); }
  void set_silence_is_word(bool b) { m_tp_lexicon.set_silence_is_word(b); m_tp_lexicon_reader.set_silence_is_word(b); }
  void set_ignore_case(bool b) { m_tp_lexicon.set_ignore_case(b);}
  void set_verbose(int verbose) { m_search.set_verbose(verbose); m_tp_lexicon.set_verbose(verbose); m_tp_search.set_verbose(verbose);}
  void set_print_text_result(int print) { m_tp_search.set_print_text_result(print); }
  void set_print_state_segmentation(int print) { m_tp_search.set_print_state_segmentation(print); }
  void set_keep_state_segmentation(int value) { m_tp_search.set_keep_state_segmentation(value); }
  void set_print_probs(bool print_probs)
  {
    m_search.set_print_probs(print_probs);
    m_tp_search.set_print_probs(print_probs);
  }
  void set_multiple_endings(int multiple_endings)
  { m_search.set_multiple_endings(multiple_endings); }
  void set_print_indices(bool print_indices)
  { m_search.set_print_indices(print_indices); }
  void set_print_frames(bool print_frames)
  {
    m_search.set_print_frames(print_frames);
  }
  void set_word_boundary(const std::string &word)
  { if (m_use_stack_decoder) m_search.set_word_boundary(word); else m_word_boundary = word; }
  void set_sentence_boundary(const std::string &start, const std::string &end) { m_tp_search.set_sentence_boundary(start, end); }
  void set_dummy_word_boundaries(bool value)
  { m_search.set_dummy_word_boundaries(value); }
  void set_require_sentence_end(bool s) { m_tp_search.set_require_sentence_end(s); }

  void set_optional_short_silence(bool state) { m_tp_lexicon.set_optional_short_silence(state); }

  void prune_lm_lookahead_buffers(int min_delta, int max_depth) { m_tp_lexicon.prune_lookahead_buffers(min_delta, max_depth); }
  void set_generate_word_graph(bool value)
  { m_tp_search.set_generate_word_graph(value); }
  void set_use_lm_cache(bool value)
  { m_tp_search.set_use_lm_cache(value); }

  // Debug
  void print_prunings()
  { m_search.print_prunings(); }
  void print_hypo(Hypo &hypo);
  void print_sure() { m_search.print_sure(); }
  void write_word_history(const std::string file_name) {
    io::Stream out(file_name, "w");
    m_tp_search.write_word_history(out.file);
  }
  void write_word_history() { m_tp_search.write_word_history(); }
  void print_lm_history() { m_tp_search.print_lm_history(); }
  void write_state_segmentation(const std::string &file)
  {
    m_tp_search.print_state_history(io::Stream(file, "w").file);
  }

  TokenPassSearch &debug_get_tp() { return m_tp_search; }
  TPLexPrefixTree &debug_get_tp_lex() { return m_tp_lexicon; }
  void debug_print_best_lm_history()
  { m_tp_search.debug_print_best_lm_history(); }

  struct OpenError : public std::exception {
    virtual const char *what() const throw()
    { return "Toolbox: open error"; }
  };

  void print_tp_lex_node(int node) { m_tp_lexicon.print_node_info(node); }
  void print_tp_lex_lookahead(int node) {m_tp_lexicon.print_lookahead_info(node, m_tp_vocabulary); }

private:
  int m_use_stack_decoder;

  NowayHmmReader m_hmm_reader;
  std::map<std::string,int> &m_hmm_map;
  std::vector<Hmm> &m_hmms;

  NowayLexiconReader m_lexicon_reader;
  Lexicon &m_lexicon;
  const Vocabulary &m_vocabulary;

  TPLexPrefixTree m_tp_lexicon;
  TPNowayLexReader m_tp_lexicon_reader;
  Vocabulary m_tp_vocabulary;
  TokenPassSearch m_tp_search;

  Acoustics *m_acoustics;
  LnaReaderCircular m_lna_reader;
  OneFrameAcoustics m_one_frame_acoustics;

  std::string m_word_boundary;

  std::vector<TreeGram*> m_ngrams;
  fsalm::LM *m_fsa_lm;
  std::deque<int> m_history;
  TreeGram *m_lookahead_ngram;

  Expander m_expander;

  Search m_search;
};

#endif /* TOOLBOX_HH */
<commit_msg>Added Doxygen comments.<commit_after>#ifndef TOOLBOX_HH
#define TOOLBOX_HH

#include <deque>

#include "io.hh"
#include "WordGraph.hh"
#include "NowayHmmReader.hh"
#include "NowayLexiconReader.hh"
#include "TPNowayLexReader.hh"
#include "LnaReaderCircular.hh"
#include "Expander.hh"
#include "Search.hh"
#include "TokenPassSearch.hh"
#include "OneFrameAcoustics.hh"

class Toolbox {
public:
  Toolbox();
  ~Toolbox();

  // Decoder selection: 0=token pass, 1 = stack
  void select_decoder(int stack_dec) { m_use_stack_decoder = stack_dec; }

  // HMM models
  void hmm_read(const char *file);
  void duration_read(const char *dur_file);
  const std::vector<Hmm> &hmms() const { return m_hmms; }

  // Lexicon

  /// \brief Reads a dictionary file that specifies the lexicon and
  /// pronunciations used in the decoding.
  ///
  /// \param file Name of a NOWAY dictionary file where the lexicon is
  /// read from.
  ///
  void lex_read(const char *file);

  const std::string &lex_word() const { return m_lexicon_reader.word(); }
  const std::string &lex_phone() const { return m_lexicon_reader.phone(); }
  const std::string &word(int index) const
  {
    if (m_use_stack_decoder)
      return m_vocabulary.word(index);
    return m_tp_vocabulary.word(index);
  }

  // Ngram
  void ngram_read(const char *file, float weight, bool binary=true);
  void read_lookahead_ngram(const char *file, bool binary=true);

  /// \brief Reads a finite-state automaton language model.
  ///
  /// \param file Name of the file where the language model is read from.
  /// \param binary If set to true, the file is expected to be in a non-standard
  /// format that lm utility writes. Otherwise ARPA format is expected.
  ///
  void fsa_lm_read(const char *file, bool binary=true);

  // Lna
  void lna_open(const char *file, int size);
  void lna_close();
  void lna_seek(int frame) { m_lna_reader.seek(frame); }
  Acoustics &acoustics() { return *m_acoustics; }
  void use_one_frame_acoustics()
  {
    m_acoustics = &m_one_frame_acoustics;
    m_tp_search.set_acoustics(m_acoustics);
  }
  void set_one_frame(int frame, const std::vector<float> log_probs)
  {
    assert(m_acoustics == &m_one_frame_acoustics);
    m_one_frame_acoustics.set(frame, log_probs);
  }

  // Expander
  void expand(int frame, int frames);
  const std::string &best_word();
  void print_words(int words);
  int find_word(const std::string &word);
  std::vector<Expander::Word*> words() { return m_expander.words(); }

  // Stack search
  void init(int expand_window);
  bool expand_stack(int frame) { return m_search.expand_stack(frame); }
  void expand_words(int frame, const std::string &words)
  { m_search.expand_words(frame, words); }
  void go(int frame) { m_search.go(frame); }
  bool runto(int frame);
  bool recognize_segment(int start_frame, int end_frame);

  // Both searches
  void reset(int frame) { if (m_use_stack_decoder) m_search.reset_search(frame);  else m_tp_search.reset_search(frame);}
  void set_end(int frame) { if (m_use_stack_decoder) m_search.set_end_frame(frame); else m_tp_search.set_end_frame(frame); }

  /// \brief Proceeds decoding one frame.
  ///
  /// \return true if a frame was available, false if there are no more frames.
  ///
  bool run() { return (m_use_stack_decoder?m_search.run():m_tp_search.run()); }

  // Token pass search
  WordGraph &tp_word_graph() { return m_tp_search.word_graph; }
  void write_word_graph(const std::string &file_name)
  { m_tp_search.write_word_graph(file_name); }
  void print_best_lm_history(FILE *out=stdout)
  {
    m_tp_search.print_lm_history(out, true);
  }
  void print_best_lm_history_to_file(FILE *out) {print_best_lm_history(out);}

  // Miscellaneous
  void segment(const std::string &str, int start_frame, int end_frame);

  // Info
  TokenPassSearch &tp_search() { return m_tp_search; }
  int frame() { return (m_use_stack_decoder?m_search.frame():m_tp_search.frame()); }
  int first_frame() { return m_search.first_frame(); }
  int last_frame() { return m_search.last_frame(); }
  HypoStack &stack(int frame) { return m_search.stack(frame); }
  void prune(int frame, int top);
  int paths() const { return HypoPath::g_count; }

  // Options
  void set_forced_end(bool forced_end)
  { m_expander.set_forced_end(forced_end); }
  void set_hypo_limit(int hypo_limit) { m_search.set_hypo_limit(hypo_limit); }
  void set_prune_similar(int prune_similar) { m_search.set_prune_similar(prune_similar); m_tp_search.set_similar_lm_history_span(prune_similar); }
  void set_word_limit(int word_limit) { m_search.set_word_limit(word_limit); }
  void set_word_beam(float word_beam) { m_search.set_word_beam(word_beam); }
  void set_lm_scale(float lm_scale) { m_search.set_lm_scale(lm_scale); m_tp_search.set_lm_scale(lm_scale); }
  void set_lm_offset(float lm_offset) { m_search.set_lm_offset(lm_offset); }
  void set_unk_offset(float unk_offset) { m_search.set_unk_offset(unk_offset); }
  void set_token_limit(int limit) { m_expander.set_token_limit(limit); m_tp_search.set_max_num_tokens(limit); }
  void set_state_beam(float beam) { m_expander.set_beam(beam); }
  void set_duration_scale(float scale) { m_expander.set_duration_scale(scale); m_tp_search.set_duration_scale(scale); }
  void set_transition_scale(float scale) { m_expander.set_transition_scale(scale); m_tp_search.set_transition_scale(scale); }
  void set_rabiner_post_mode(int mode) { m_expander.set_rabiner_post_mode(mode); }
  void set_hypo_beam(float beam) { m_search.set_hypo_beam(beam); }
  void set_global_beam(float beam)
  { m_search.set_global_beam(beam); m_tp_search.set_global_beam(beam); }
  void set_word_end_beam(float beam) { m_tp_search.set_word_end_beam(beam); }
  void set_eq_depth_beam(float beam) { m_tp_search.set_eq_depth_beam(beam); }
  void set_eq_word_count_beam(float beam) { m_tp_search.set_eq_word_count_beam(beam); }
  void set_fan_in_beam(float beam) { m_tp_search.set_fan_in_beam(beam); }
  void set_fan_out_beam(float beam) { m_tp_search.set_fan_out_beam(beam); }
  void set_tp_state_beam(float beam) { m_tp_search.set_state_beam(beam); }
  void set_max_state_duration(int duration)
  { m_expander.set_max_state_duration(duration); }
  void set_lm_lookahead(int lmlh) { m_tp_lexicon.set_lm_lookahead(lmlh); m_tp_search.set_lm_lookahead(lmlh); }
  void set_cross_word_triphones(bool cw_triphones) { m_tp_lexicon.set_cross_word_triphones(cw_triphones); }
  void set_insertion_penalty(float ip) { m_tp_search.set_insertion_penalty(ip); }
  void set_silence_is_word(bool b) { m_tp_lexicon.set_silence_is_word(b); m_tp_lexicon_reader.set_silence_is_word(b); }
  void set_ignore_case(bool b) { m_tp_lexicon.set_ignore_case(b);}
  void set_verbose(int verbose) { m_search.set_verbose(verbose); m_tp_lexicon.set_verbose(verbose); m_tp_search.set_verbose(verbose);}
  void set_print_text_result(int print) { m_tp_search.set_print_text_result(print); }
  void set_print_state_segmentation(int print) { m_tp_search.set_print_state_segmentation(print); }
  void set_keep_state_segmentation(int value) { m_tp_search.set_keep_state_segmentation(value); }
  void set_print_probs(bool print_probs)
  {
    m_search.set_print_probs(print_probs);
    m_tp_search.set_print_probs(print_probs);
  }
  void set_multiple_endings(int multiple_endings)
  { m_search.set_multiple_endings(multiple_endings); }
  void set_print_indices(bool print_indices)
  { m_search.set_print_indices(print_indices); }
  void set_print_frames(bool print_frames)
  {
    m_search.set_print_frames(print_frames);
  }
  void set_word_boundary(const std::string &word)
  { if (m_use_stack_decoder) m_search.set_word_boundary(word); else m_word_boundary = word; }
  void set_sentence_boundary(const std::string &start, const std::string &end) { m_tp_search.set_sentence_boundary(start, end); }
  void set_dummy_word_boundaries(bool value)
  { m_search.set_dummy_word_boundaries(value); }
  void set_require_sentence_end(bool s) { m_tp_search.set_require_sentence_end(s); }

  void set_optional_short_silence(bool state) { m_tp_lexicon.set_optional_short_silence(state); }

  void prune_lm_lookahead_buffers(int min_delta, int max_depth) { m_tp_lexicon.prune_lookahead_buffers(min_delta, max_depth); }
  void set_generate_word_graph(bool value)
  { m_tp_search.set_generate_word_graph(value); }
  void set_use_lm_cache(bool value)
  { m_tp_search.set_use_lm_cache(value); }

  // Debug
  void print_prunings()
  { m_search.print_prunings(); }
  void print_hypo(Hypo &hypo);
  void print_sure() { m_search.print_sure(); }
  void write_word_history(const std::string file_name) {
    io::Stream out(file_name, "w");
    m_tp_search.write_word_history(out.file);
  }
  void write_word_history() { m_tp_search.write_word_history(); }
  void print_lm_history() { m_tp_search.print_lm_history(); }
  void write_state_segmentation(const std::string &file)
  {
    m_tp_search.print_state_history(io::Stream(file, "w").file);
  }

  TokenPassSearch &debug_get_tp() { return m_tp_search; }
  TPLexPrefixTree &debug_get_tp_lex() { return m_tp_lexicon; }
  void debug_print_best_lm_history()
  { m_tp_search.debug_print_best_lm_history(); }

  struct OpenError : public std::exception {
    virtual const char *what() const throw()
    { return "Toolbox: open error"; }
  };

  void print_tp_lex_node(int node) { m_tp_lexicon.print_node_info(node); }
  void print_tp_lex_lookahead(int node) {m_tp_lexicon.print_lookahead_info(node, m_tp_vocabulary); }

private:
  int m_use_stack_decoder;

  NowayHmmReader m_hmm_reader;
  std::map<std::string,int> &m_hmm_map;
  std::vector<Hmm> &m_hmms;

  NowayLexiconReader m_lexicon_reader;
  Lexicon &m_lexicon;
  const Vocabulary &m_vocabulary;

  TPLexPrefixTree m_tp_lexicon;
  TPNowayLexReader m_tp_lexicon_reader;
  Vocabulary m_tp_vocabulary;
  TokenPassSearch m_tp_search;

  Acoustics *m_acoustics;
  LnaReaderCircular m_lna_reader;
  OneFrameAcoustics m_one_frame_acoustics;

  std::string m_word_boundary;

  std::vector<TreeGram*> m_ngrams;
  fsalm::LM *m_fsa_lm;
  std::deque<int> m_history;
  TreeGram *m_lookahead_ngram;

  Expander m_expander;

  Search m_search;
};

#endif /* TOOLBOX_HH */
<|endoftext|>


<commit_before>#include "UvcCam.hxx"

UvcCam::UvcCam(cv::Size size, int device) : Cam(size) {
    memset(map, 0, sizeof(void *) * BUFFERS);

    std::string str = (boost::format("/dev/video%d") % device).str();
    fd = v4l2_open(str.c_str(), O_RDWR);
    if (fd < 0)
        throw std::runtime_error("Couldn't open video device");

    v4l2_capability cap;
    memset(&cap, 0, sizeof(v4l2_capability));
    if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap)) {
        v4l2_close(fd);
        throw std::runtime_error("ioctl kaboom!!!");
    }
    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) ||
        !(cap.capabilities & V4L2_CAP_STREAMING)) {
        v4l2_close(fd);
        throw std::runtime_error("Ur cam iz shitty");
    }

    v4l2_format fmt;
    memset(&fmt, 0, sizeof(v4l2_format));
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    fmt.fmt.pix.width = size.width;
    fmt.fmt.pix.height = size.height;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
    fmt.fmt.pix.field = V4L2_FIELD_ANY;
    errno = 0;
    if (v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt)) {
        perror("v4l2_ioctl");
        v4l2_close(fd);
        throw std::runtime_error("Can't set format");
    }
    if (fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_JPEG) {
        v4l2_close(fd);
        throw std::runtime_error("jpg not supported");
    }

    v4l2_requestbuffers rq;
    memset(&rq, 0, sizeof(v4l2_requestbuffers));
    rq.count = BUFFERS;
    rq.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    rq.memory = V4L2_MEMORY_MMAP;
    if (v4l2_ioctl(fd, VIDIOC_REQBUFS, &rq)) {
        v4l2_close(fd);
        throw std::runtime_error("bufferalloc failed");
    }

    v4l2_buffer buf;
    for (size_t i = 0; i < BUFFERS; ++i) {
        memset(&buf, 0, sizeof(v4l2_buffer));
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = i;
        if (v4l2_ioctl(fd, VIDIOC_QUERYBUF, &buf)) {
            v4l2_close(fd);
            throw std::runtime_error("buffer queue fail'd");
        }

        len = buf.length;
        map[i] = mmap(0, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd,
                      buf.m.offset);
        if (map[i] == MAP_FAILED) {
            destroy();
            throw std::runtime_error("mmap fail'd");
        }
    }

    for (size_t i = 0; i < BUFFERS; ++i) {
        memset(&buf, 0, sizeof(v4l2_buffer));
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = i;
        if (v4l2_ioctl(fd, VIDIOC_QBUF, &buf)) {
            destroy();
            throw std::runtime_error("queue buffer fail'd");
        }
    }

    v4l2_streamparm fps;
    memset(&fps, 0, sizeof(v4l2_streamparm));
    fps.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    fps.parm.capture.timeperframe.numerator = 1;
    fps.parm.capture.timeperframe.denominator = 25;
    v4l2_ioctl(fd, VIDIOC_S_PARM, fps);

    v4l2_queryctrl ctrl;
    for (int i = V4L2_CID_PRIVATE_BASE;; ++i) {
        ctrl.id = i;
        if (v4l2_ioctl(fd, VIDIOC_QUERYCTRL, &ctrl))
            break;
        if (ctrl.type == V4L2_CTRL_TYPE_BOOLEAN &&
            strncasecmp(reinterpret_cast<char *>(ctrl.name), "auto", 4)) {
            std::cerr << "Automatically disabling private auto thing: "
                      << ctrl.name << std::endl;
            disable(reinterpret_cast<char *>(ctrl.name), ctrl.id);
        } else {
            std::cerr << ctrl.name << "; " << ctrl.type << std::endl;
        }
    }
#define CDISABLE(x) disable(#x, x)
    CDISABLE(V4L2_CID_AUTO_WHITE_BALANCE);
    CDISABLE(V4L2_CID_AUTOGAIN);
    CDISABLE(V4L2_CID_HUE_AUTO);
    CDISABLE(V4L2_CID_AUTOBRIGHTNESS);
#undef CDISABLE

    int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (v4l2_ioctl(fd, VIDIOC_STREAMON, &type)) {
        destroy();
        throw std::runtime_error("can't start capture");
    }

    frame_.create(this->size(), CV_8UC3);
}

void UvcCam::disable(const std::string& name, int ctrlid) {
    v4l2_control ctrl;
    memset(&ctrl, 0, sizeof(v4l2_control));
    ctrl.id = ctrlid;
    ctrl.value = true;
    if (v4l2_ioctl(fd, VIDIOC_S_CTRL, &ctrl)) {
        std::cerr << "Can't disable control " << name << " (" << ctrlid
                  << ") (maybe not supported?)" << std::endl;
    }
}

UvcCam::~UvcCam() {
    int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    v4l2_ioctl(fd, VIDIOC_STREAMOFF, &type);
    destroy();
}

const cv::Mat & UvcCam::jpeg() const {
    return jpeg_;
}

const cv::Mat & UvcCam::frame() const {
    return frame_;
}

void UvcCam::grabImage() {
    v4l2_buffer buf;
    memset(&buf, 0, sizeof(v4l2_buffer));
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_MMAP;
    if (v4l2_ioctl(fd, VIDIOC_DQBUF, &buf)) {
        throw std::string("buffer dequeue fail'd");
    }

    if (buf.bytesused > 0xaf) {
        cv::Mat cjpg(buf.bytesused, 1, CV_8U);
        memcpy(cjpg.ptr(0), map[buf.index], buf.bytesused);
        cv::Mat cfrm = cv::imdecode(cjpg, 1);

        if (cfrm.dims > 0 &&
            //(cfrm.type() & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL &&
            (cfrm.cols > 0 && cfrm.rows > 0)) {
            jpeg_ = cjpg;
            frame_ = cfrm;
        }
    }

    if (v4l2_ioctl(fd, VIDIOC_QBUF, &buf)) {
        throw std::string("buffer queue fail'd");
    }
}

void UvcCam::destroy() {
    for (size_t i = 0; i < BUFFERS; ++i)
        if (map[i])
            munmap(map[i], len);
    v4l2_close(fd);
}
<commit_msg>UvcCam supports more cams<commit_after>#include "UvcCam.hxx"

UvcCam::UvcCam(cv::Size size, int device) : Cam(size) {
    memset(map, 0, sizeof(void *) * BUFFERS);

    std::string str = (boost::format("/dev/video%d") % device).str();
    fd = v4l2_open(str.c_str(), O_RDWR);
    if (fd < 0)
        throw std::runtime_error("Couldn't open video device");

    v4l2_capability cap;
    memset(&cap, 0, sizeof(v4l2_capability));
    if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap)) {
        v4l2_close(fd);
        throw std::runtime_error("ioctl kaboom!!!");
    }
    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) ||
        !(cap.capabilities & V4L2_CAP_STREAMING)) {
        v4l2_close(fd);
        throw std::runtime_error("Ur cam iz shitty");
    }

    v4l2_format fmt;
    memset(&fmt, 0, sizeof(v4l2_format));
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    fmt.fmt.pix.width = size.width;
    fmt.fmt.pix.height = size.height;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
    fmt.fmt.pix.field = V4L2_FIELD_ANY;
    errno = 0;
    if (v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt)) {
        perror("v4l2_ioctl");
        v4l2_close(fd);
        throw std::runtime_error("Can't set format");
    }
    if (fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_JPEG
            && fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_MJPEG) {
        v4l2_close(fd);
        throw std::runtime_error("jpg not supported");
    }

    v4l2_requestbuffers rq;
    memset(&rq, 0, sizeof(v4l2_requestbuffers));
    rq.count = BUFFERS;
    rq.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    rq.memory = V4L2_MEMORY_MMAP;
    if (v4l2_ioctl(fd, VIDIOC_REQBUFS, &rq)) {
        v4l2_close(fd);
        throw std::runtime_error("bufferalloc failed");
    }

    v4l2_buffer buf;
    for (size_t i = 0; i < BUFFERS; ++i) {
        memset(&buf, 0, sizeof(v4l2_buffer));
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = i;
        if (v4l2_ioctl(fd, VIDIOC_QUERYBUF, &buf)) {
            v4l2_close(fd);
            throw std::runtime_error("buffer queue fail'd");
        }

        len = buf.length;
        map[i] = mmap(0, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd,
                      buf.m.offset);
        if (map[i] == MAP_FAILED) {
            destroy();
            throw std::runtime_error("mmap fail'd");
        }
    }

    for (size_t i = 0; i < BUFFERS; ++i) {
        memset(&buf, 0, sizeof(v4l2_buffer));
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = i;
        if (v4l2_ioctl(fd, VIDIOC_QBUF, &buf)) {
            destroy();
            throw std::runtime_error("queue buffer fail'd");
        }
    }

    v4l2_streamparm fps;
    memset(&fps, 0, sizeof(v4l2_streamparm));
    fps.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    fps.parm.capture.timeperframe.numerator = 1;
    fps.parm.capture.timeperframe.denominator = 25;
    v4l2_ioctl(fd, VIDIOC_S_PARM, fps);

    v4l2_queryctrl ctrl;
    for (int i = V4L2_CID_PRIVATE_BASE;; ++i) {
        ctrl.id = i;
        if (v4l2_ioctl(fd, VIDIOC_QUERYCTRL, &ctrl))
            break;
        if (ctrl.type == V4L2_CTRL_TYPE_BOOLEAN &&
            strncasecmp(reinterpret_cast<char *>(ctrl.name), "auto", 4)) {
            std::cerr << "Automatically disabling private auto thing: "
                      << ctrl.name << std::endl;
            disable(reinterpret_cast<char *>(ctrl.name), ctrl.id);
        } else {
            std::cerr << ctrl.name << "; " << ctrl.type << std::endl;
        }
    }
#define CDISABLE(x) disable(#x, x)
    CDISABLE(V4L2_CID_AUTO_WHITE_BALANCE);
    CDISABLE(V4L2_CID_AUTOGAIN);
    CDISABLE(V4L2_CID_HUE_AUTO);
    CDISABLE(V4L2_CID_AUTOBRIGHTNESS);
#undef CDISABLE

    int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (v4l2_ioctl(fd, VIDIOC_STREAMON, &type)) {
        destroy();
        throw std::runtime_error("can't start capture");
    }

    frame_.create(this->size(), CV_8UC3);
}

void UvcCam::disable(const std::string& name, int ctrlid) {
    v4l2_control ctrl;
    memset(&ctrl, 0, sizeof(v4l2_control));
    ctrl.id = ctrlid;
    ctrl.value = true;
    if (v4l2_ioctl(fd, VIDIOC_S_CTRL, &ctrl)) {
        std::cerr << "Can't disable control " << name << " (" << ctrlid
                  << ") (maybe not supported?)" << std::endl;
    }
}

UvcCam::~UvcCam() {
    int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    v4l2_ioctl(fd, VIDIOC_STREAMOFF, &type);
    destroy();
}

const cv::Mat & UvcCam::jpeg() const {
    return jpeg_;
}

const cv::Mat & UvcCam::frame() const {
    return frame_;
}

void UvcCam::grabImage() {
    v4l2_buffer buf;
    memset(&buf, 0, sizeof(v4l2_buffer));
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_MMAP;
    if (v4l2_ioctl(fd, VIDIOC_DQBUF, &buf)) {
        throw std::string("buffer dequeue fail'd");
    }

    if (buf.bytesused > 0xaf) {
        cv::Mat cjpg(buf.bytesused, 1, CV_8U);
        memcpy(cjpg.ptr(0), map[buf.index], buf.bytesused);
        cv::Mat cfrm = cv::imdecode(cjpg, 1);

        if (cfrm.dims > 0 &&
            //(cfrm.type() & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL &&
            (cfrm.cols > 0 && cfrm.rows > 0)) {
            jpeg_ = cjpg;
            frame_ = cfrm;
        }
    }

    if (v4l2_ioctl(fd, VIDIOC_QBUF, &buf)) {
        throw std::string("buffer queue fail'd");
    }
}

void UvcCam::destroy() {
    for (size_t i = 0; i < BUFFERS; ++i)
        if (map[i])
            munmap(map[i], len);
    v4l2_close(fd);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <map>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int iabs(int a) { return a < 0 ? -a : a; }

int main(int argc, char* argv[]) {
    ifstream instance(argv[1]);
    ifstream solver_output(argv[2]);
    string line;

    map<int, int> variables;
    bool SAT_answer = false;
    while (getline(solver_output, line)) {
        istringstream lss(line);
        string timestamp, prefix;
        lss >> timestamp >> prefix; // read away timestamp
        if (prefix == "s") {
            string answer;
            lss >> answer;
            if (answer == "UNKNOWN") {
                cout << "Solver reported unknown." << endl;
                return 0;
            }
            else if (answer == "SATISFIABLE") {
                cout << "Solver reported satisfiable. Checking." << endl;
                SAT_answer = true;
            }
            else if (answer == "UNSATISFIABLE") {
                cout << "Solver reported unsatisfiable. I guess it must be right!" << endl;
                return 10;
            }
        }
        else if (prefix == "v") {
            // read solution
            int v;
            while (lss >> v && v != 0) {
                variables[iabs(v)] = v;
            }
        }
    }
    if (SAT_answer) {
        while (getline(instance, line)) {
            if (line.substr(0, 1) == "c" || line.substr(0, 1) == "p") continue;
            istringstream lss(line);
            int v;
            bool sat_clause = false;
            while (lss >> v && v != 0) {
                if (variables.find(iabs(v)) == variables.end()) {
                    sat_clause = false;
                    break;
                }
                if (variables[iabs(v)] == v) {
                    sat_clause = true;
                    break;
                }
            }
            if (!sat_clause) {
                cout << "Wrong solution." << endl;
                return 0;
            }
        }
        cout << "Solution verified." << endl;
        return 11;
    }
    cout << "Didn't really find anything interesting in the output" << endl;
    return 0;
}
<commit_msg>verifier bugfix<commit_after>#include <iostream>
#include <map>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int iabs(int a) { return a < 0 ? -a : a; }

int main(int argc, char* argv[]) {
    ifstream instance(argv[1]);
    ifstream solver_output(argv[2]);
    string line;

    map<int, int> variables;
    bool SAT_answer = false;
    while (getline(solver_output, line)) {
        istringstream lss(line);
        string timestamp, prefix;
        lss >> timestamp >> prefix; // read away timestamp
        if (prefix == "s") {
            string answer;
            lss >> answer;
            if (answer == "UNKNOWN") {
                cout << "Solver reported unknown." << endl;
                return 0;
            }
            else if (answer == "SATISFIABLE") {
                cout << "Solver reported satisfiable. Checking." << endl;
                SAT_answer = true;
            }
            else if (answer == "UNSATISFIABLE") {
                cout << "Solver reported unsatisfiable. I guess it must be right!" << endl;
                return 10;
            }
        }
        else if (prefix == "v") {
            // read solution
            int v;
            while (lss >> v && v != 0) {
                variables[iabs(v)] = v;
            }
        }
    }
    if (SAT_answer) {
        while (getline(instance, line)) {
            if (line.substr(0, 1) == "c" || line.substr(0, 1) == "p") continue;
            istringstream lss(line);
            int v;
            bool sat_clause = false;
            int num_vars = 0;
            while (lss >> v && v != 0) {
                num_vars++;
                if (variables.find(iabs(v)) == variables.end()) {
                    sat_clause = false;
                    break;
                }
                if (variables[iabs(v)] == v) {
                    sat_clause = true;
                    break;
                }
            }
            if (!sat_clause && num_vars > 0) {
                cout << "Wrong solution." << endl;
                return 0;
            }
        }
        cout << "Solution verified." << endl;
        return 11;
    }
    cout << "Didn't really find anything interesting in the output" << endl;
    return 0;
}
<|endoftext|>


<commit_before>/**
 * \file XTPlot.cpp
 * \brief Implements class for drawing the XT plots
 */

#include "XTPlot.h"
#include "ChaosSettings.h"

XTPlot::XTPlot(wxWindow* parent, wxWindowID id, const wxPoint& pos,
                       const wxSize& size, long style, const wxString& name)
                       : ChaosPlot(parent, id, pos, size, style, name) {
    /**
    *   Constructor for the XT plot. Defaults to only showing X.
    */
    side_gutter_size = 15;
    bottom_gutter_size = 1;
    x1Visible = true;
    x2Visible = false;
    x3Visible = false;
    graph_title = wxT("Waveform as a function of time");
    graph_subtitle = wxT("X (V) vs. T");
}

XTPlot::~XTPlot() {
    /**
    *   Deconstructor for the Rotating3dPlot class
    */
}

void XTPlot::drawPlot() {
    /**
    *   Main drawing function for the XTPlot class.
    *
    *   Calculates the units for the axis and then draws them
    *   Draws an XT graph using X, X', and X'' depending on which ones
    *   the user has selected.
    *
    */
    const int xt_points = 300;

    static int times_called = 0;

    int x1,x2,x1_old,x2_old, x3, x3_old;
    int start;

    startDraw();
    if(ChaosSettings::YAxisLabels == ChaosSettings::Y_AXIS_VGND) {
        graph_subtitle = wxT("X (V) vs. T");
        drawYAxis(0.0,3.3,1);
    } else if(ChaosSettings::YAxisLabels == ChaosSettings::Y_AXIS_VBIAS) {
        graph_subtitle = wxT("X (V) vs. T");
        drawYAxis(-1.2,2.1,.5);
    } else {
        graph_subtitle = wxT("X (ADC) vs. T");
        drawYAxis(0,1024,341);
    }

    if(device_connected == false) {
        endDraw();
        return;
    }

    int plot_width = width-side_gutter_size-2;
    int plot_points;
    float x_scale;
    float y_scale = float(graph_height)/1024.0;

    if(plot_width > xt_points) {
        plot_points = xt_points;
        x_scale = float(plot_width)/xt_points;
    } else {
        plot_points = plot_width;
        x_scale = 1.0;
    }

    start = libchaos_getTriggerIndex();

    // Get first plot point
    libchaos_getPlotPoint(&x1,&x2,&x3, start);
    x3 = graph_height + top_gutter_size - int(x3*y_scale);
    x2 = graph_height + top_gutter_size - int(x2*y_scale);
    x1 = graph_height + top_gutter_size - int(x1*y_scale);
    x1_old = x1;
    x2_old = x2;
    x3_old = x3;

    for(int i = 1; i < plot_points; i++) {
        libchaos_getPlotPoint(&x1,&x2,&x3, i+start);
        x3 = graph_height + top_gutter_size - int(x3*y_scale);
        x2 = graph_height + top_gutter_size - int(x2*y_scale);
        x1 = graph_height + top_gutter_size - int(x1*y_scale);

        if(x1Visible == true) {
            //Use red pen
            wxPen rPen(*wxRED, 2); // red pen of width 2
            buffer->SetPen(rPen);
            buffer->DrawLine((int)(x_scale*(i-1)+side_gutter_size+1), x1_old, (int)(x_scale*i+side_gutter_size+1), x1);
        }

        if(x2Visible == true) {
            //Use blue pen
            wxPen bPen(*wxBLUE, 2); // blue pen of width 2
            buffer->SetPen(bPen);
            buffer->DrawLine((int)(x_scale*(i-1)+side_gutter_size+1), x2_old, (int)(x_scale*i+side_gutter_size+1), x2);
        }

        if(x3Visible == true) {
            //Use green pen
            wxPen gPen(*wxGREEN, 2); // blue pen of width 2
            buffer->SetPen(gPen);
            buffer->DrawLine((int)(x_scale*(i-1)+side_gutter_size+1), x3_old, (int)(x_scale*i+side_gutter_size+1), x3);
        }

        x1_old = x1;
        x2_old = x2;
        x3_old = x3;
    }
    times_called = 0;

    // Display buffer
    endDraw();
}

void XTPlot::setX1Visibility(bool visible) {
    /**
    *   Enables or disables the visibility of X on the graph
    */
    x1Visible = visible;
}

void XTPlot::setX2Visibility(bool visible) {
    /**
    *   Enables or disables the visibility of X' on the graph
    */
    x2Visible = visible;
}

void XTPlot::setX3Visibility(bool visible) {
    /**
    *   Enables or disables the visibility of X'' on the graph
    */
    x3Visible = visible;
}
<commit_msg>- modified XT plot to never truncate the graph<commit_after>/**
 * \file XTPlot.cpp
 * \brief Implements class for drawing the XT plots
 */

#include "XTPlot.h"
#include "ChaosSettings.h"

XTPlot::XTPlot(wxWindow* parent, wxWindowID id, const wxPoint& pos,
                       const wxSize& size, long style, const wxString& name)
                       : ChaosPlot(parent, id, pos, size, style, name) {
    /**
    *   Constructor for the XT plot. Defaults to only showing X.
    */
    side_gutter_size = 20;
    bottom_gutter_size = 20;
    x1Visible = true;
    x2Visible = false;
    x3Visible = false;
    graph_title = wxT("Waveform as a function of time");
    graph_subtitle = wxT("X (V) vs. T");
}

XTPlot::~XTPlot() {
    /**
    *   Deconstructor for the Rotating3dPlot class
    */
}

void XTPlot::drawPlot() {
    /**
    *   Main drawing function for the XTPlot class.
    *
    *   Calculates the units for the axis and then draws them
    *   Draws an XT graph using X, X', and X'' depending on which ones
    *   the user has selected.
    *
    */
    const int xt_points = 300;

    static int times_called = 0;

    int x1,x2,x1_old,x2_old, x3, x3_old;
    int start;

    startDraw();
    if(ChaosSettings::YAxisLabels == ChaosSettings::Y_AXIS_VGND) {
        graph_subtitle = wxT("X (V) vs. T");
        drawYAxis(0.0,3.3,1);
    } else if(ChaosSettings::YAxisLabels == ChaosSettings::Y_AXIS_VBIAS) {
        graph_subtitle = wxT("X (V) vs. T");
        drawYAxis(-1.2,2.1,.5);
    } else {
        graph_subtitle = wxT("X (ADC) vs. T");
        drawYAxis(0,1024,341);
    }
    drawXAxis(0,5,1);

    if(device_connected == false) {
        endDraw();
        return;
    }

    int plot_width = width-side_gutter_size-2;
    int plot_points;
    float x_scale;
    float y_scale = float(graph_height)/1024.0;

    plot_points = xt_points;
    x_scale = float(plot_width)/xt_points;

    start = libchaos_getTriggerIndex();

    // Get first plot point
    libchaos_getPlotPoint(&x1,&x2,&x3, start);
    x3 = graph_height + top_gutter_size - int(x3*y_scale);
    x2 = graph_height + top_gutter_size - int(x2*y_scale);
    x1 = graph_height + top_gutter_size - int(x1*y_scale);
    x1_old = x1;
    x2_old = x2;
    x3_old = x3;

    for(int i = 1; i < plot_points; i++) {
        libchaos_getPlotPoint(&x1,&x2,&x3, i+start);
        x3 = graph_height + top_gutter_size - int(x3*y_scale);
        x2 = graph_height + top_gutter_size - int(x2*y_scale);
        x1 = graph_height + top_gutter_size - int(x1*y_scale);

        if(x1Visible == true) {
            //Use red pen
            wxPen rPen(*wxRED, 2); // red pen of width 2
            buffer->SetPen(rPen);
            buffer->DrawLine((int)(x_scale*(i-1)+side_gutter_size+1), x1_old, (int)(x_scale*i+side_gutter_size+1), x1);
        }

        if(x2Visible == true) {
            //Use blue pen
            wxPen bPen(*wxBLUE, 2); // blue pen of width 2
            buffer->SetPen(bPen);
            buffer->DrawLine((int)(x_scale*(i-1)+side_gutter_size+1), x2_old, (int)(x_scale*i+side_gutter_size+1), x2);
        }

        if(x3Visible == true) {
            //Use green pen
            wxPen gPen(*wxGREEN, 2); // blue pen of width 2
            buffer->SetPen(gPen);
            buffer->DrawLine((int)(x_scale*(i-1)+side_gutter_size+1), x3_old, (int)(x_scale*i+side_gutter_size+1), x3);
        }

        x1_old = x1;
        x2_old = x2;
        x3_old = x3;
    }
    times_called = 0;

    // Display buffer
    endDraw();
}

void XTPlot::setX1Visibility(bool visible) {
    /**
    *   Enables or disables the visibility of X on the graph
    */
    x1Visible = visible;
}

void XTPlot::setX2Visibility(bool visible) {
    /**
    *   Enables or disables the visibility of X' on the graph
    */
    x2Visible = visible;
}

void XTPlot::setX3Visibility(bool visible) {
    /**
    *   Enables or disables the visibility of X'' on the graph
    */
    x3Visible = visible;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>

#include "pcl/common/time.h"
#include "pcl/features/fpfh_omp.h"
#include "pcl/features/normal_3d_omp.h"
#include "pcl/filters/crop_box.h"
#include "pcl/filters/filter.h"
#include "pcl/filters/voxel_grid.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl/registration/icp.h"
#include "pcl/registration/sample_consensus_prerejective.h"
#include "pcl/segmentation/sac_segmentation.h"
#include "pcl_conversions/pcl_conversions.h"
#include "pcl_ros/transforms.h"
#include "rapid_perception/pr2.h"
#include "rapid_perception/box3d_roi_server.h"
#include "rapid_perception/pose_estimation.h"
#include "rapid_msgs/GetStaticCloud.h"
#include "rapid_msgs/ListStaticClouds.h"
#include "rapid_msgs/RemoveStaticCloud.h"
#include "rapid_msgs/SaveStaticCloud.h"
#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "visualization_msgs/Marker.h"

#include "object_search/capture_roi.h"
#include "object_search/commands.h"
#include "object_search/command_line.h"
#include "object_search/cloud_database.h"

using sensor_msgs::PointCloud2;
using pcl::FPFHSignature33;
using pcl::PointCloud;
using pcl::PointXYZRGB;
using pcl::PointXYZRGBNormal;
using visualization_msgs::Marker;
namespace rp = rapid::perception;

using namespace object_search;

int main(int argc, char** argv) {
  ros::init(argc, argv, "object_search");
  ros::NodeHandle nh;
  ros::AsyncSpinner spinner(4);
  spinner.start();

  // Build databases
  ros::ServiceClient get_cloud =
      nh.serviceClient<rapid_msgs::GetStaticCloud>("get_static_cloud");
  ros::ServiceClient list_clouds =
      nh.serviceClient<rapid_msgs::ListStaticClouds>("list_static_clouds");
  ros::ServiceClient remove_cloud =
      nh.serviceClient<rapid_msgs::RemoveStaticCloud>("remove_static_cloud");
  ros::ServiceClient save_cloud =
      nh.serviceClient<rapid_msgs::SaveStaticCloud>("save_static_cloud");
  Database object_db("object_search", "objects", get_cloud, list_clouds,
                     remove_cloud, save_cloud);
  Database scene_db("object_search", "scenes", get_cloud, list_clouds,
                    remove_cloud, save_cloud);

  // Visualization publishers
  ros::Publisher object_pub = nh.advertise<PointCloud2>("/landmark", 1, true);
  ros::Publisher scene_pub = nh.advertise<PointCloud2>("/scene", 1, true);
  ros::Publisher heatmap_pub = nh.advertise<PointCloud2>("/heatmap", 1, true);
  ros::Publisher candidates_pub =
      nh.advertise<PointCloud2>("/candidate_samples", 1, true);
  ros::Publisher best_pub =
      nh.advertise<PointCloud2>("/best_alignment", 1, true);

  // Build ROI server
  tf::TransformListener tf_listener;
  rapid::perception::Box3DRoiServer roi_server("roi");
  CaptureRoi capture(&roi_server);

  // Build pose estimator
  rapid::perception::PoseEstimator pose_estimator;

  ListCommand list_objects(&object_db, "object");
  ListCommand list_scenes(&scene_db, "scene");
  RecordObjectCommand record_object(&object_db, &capture);
  RecordSceneCommand record_scene(&scene_db);
  DeleteCommand delete_object(&object_db);
  DeleteCommand delete_scene(&scene_db);
  UseCommand use_object(&object_db, &pose_estimator, "object", object_pub);
  UseCommand use_scene(&scene_db, &pose_estimator, "scene", scene_pub);
  RunCommand run(&pose_estimator, heatmap_pub, candidates_pub, best_pub);
  SetDebugCommand set_debug(&pose_estimator);

  CommandLine cli;
  cli.set_list_objects(&list_objects);
  cli.set_list_scenes(&list_scenes);
  cli.set_record_object(&record_object);
  cli.set_record_scene(&record_scene);
  cli.set_delete_object(&delete_object);
  cli.set_delete_scene(&delete_scene);
  cli.set_use_object(&use_object);
  cli.set_use_scene(&use_scene);
  cli.set_run(&run);
  cli.set_debug(&set_debug);

  while (cli.Next()) {
  }

  spinner.stop();
  return 0;
}

// bool FindLandmark(PointCloud<PointXYZRGB>::Ptr scene,
//                  PointCloud<PointXYZRGB>::Ptr landmark,
//                  PointCloud<PointXYZRGB>::Ptr found_landmark, bool debug) {
//  pcl::ScopeTime t("FindLandmark");
//
//  // Normal estimation
//  double normal_radius;
//  ros::param::param<double>("normal_radius", normal_radius, 0.01);
//  // Features
//  double feature_radius;
//  ros::param::param<double>("feature_radius", feature_radius, 0.045);
//  // Alignment
//  double sample_ratio;
//  int max_samples;
//  double max_sample_radius;
//  int max_neighbors;
//  double feature_threshold;
//  int num_candidates;
//  ros::param::param<double>("sample_ratio", sample_ratio, 0.1);
//  ros::param::param<int>("max_samples", max_samples, 1000);
//  ros::param::param<double>("max_sample_radius", max_sample_radius, 0.1);
//  ros::param::param<int>("max_neighbors", max_neighbors, 400);
//  ros::param::param<double>("feature_threshold", feature_threshold, 1500);
//  ros::param::param<int>("num_candidates", num_candidates, 100);
//  ROS_INFO(
//      "Parameters:\n"
//      "sample_ratio: %f\n"
//      "max_samples: %d\n"
//      "max_sample_radius: %f\n"
//      "max_neighbors: %d\n"
//      "feature_threshold: %f\n"
//      "num_candidates: %d\n",
//      sample_ratio, max_samples, max_sample_radius, max_neighbors,
//      feature_threshold, num_candidates);
//
//  ros::NodeHandle nh;
//  ros::Publisher scene_pub = nh.advertise<PointCloud2>("/scene", 1, true);
//
//  // Filter NaNs
//  std::vector<int> mapping;
//  scene->is_dense = false;  // Force check for NaNs
//  pcl::removeNaNFromPointCloud(*scene, *scene, mapping);
//  ROS_INFO("Filtered NaNs: %ld", scene->size());
//
//  // Visualize scene
//  PointCloud2 scene_msg;
//  pcl::toROSMsg(*scene, scene_msg);
//  scene_pub.publish(scene_msg);
//
//  PointCloud<PointXYZRGBNormal>::Ptr scene_normals(
//      new PointCloud<PointXYZRGBNormal>);
//  PointCloud<PointXYZRGBNormal>::Ptr landmark_normals(
//      new PointCloud<PointXYZRGBNormal>);
//  pcl::copyPointCloud(*scene, *scene_normals);
//  pcl::copyPointCloud(*landmark, *landmark_normals);
//  ROS_INFO("Estimating scene normals...");
//  pcl::NormalEstimationOMP<PointXYZRGB, PointXYZRGBNormal> nest;
//  nest.setRadiusSearch(normal_radius);
//  nest.setInputCloud(scene);
//  nest.compute(*scene_normals);
//  nest.setInputCloud(landmark);
//  {
//    pcl::ScopeTime nest_time("Computing normals");
//    nest.compute(*landmark_normals);
//  }
//
//  // Estimate features
//  ROS_INFO("Estimating features...");
//  pcl::FPFHEstimationOMP<PointXYZRGBNormal, PointXYZRGBNormal,
//  FPFHSignature33>
//      fest;
//  fest.setRadiusSearch(feature_radius);
//  PointCloud<FPFHSignature33>::Ptr object_features(
//      new PointCloud<FPFHSignature33>());
//  fest.setInputCloud(landmark_normals);
//  fest.setInputNormals(landmark_normals);
//  {
//    pcl::ScopeTime fest_time("Estimating landmark features");
//    fest.compute(*object_features);
//  }
//  PointCloud<FPFHSignature33>::Ptr scene_features(
//      new PointCloud<FPFHSignature33>());
//  fest.setInputCloud(scene_normals);
//  fest.setInputNormals(scene_normals);
//  {
//    pcl::ScopeTime fest_time("Estimating scene features");
//    fest.compute(*scene_features);
//  }
//
//  // Perform alignment
//  ROS_INFO("Starting alignment...");
//  rp::PoseEstimator pose_est;
//  pose_est.set_scene(scene_normals);
//  pose_est.set_scene_features(scene_features);
//  pose_est.set_object(landmark_normals);
//  pose_est.set_object_features(object_features);
//  pose_est.set_sample_ratio(sample_ratio);
//  pose_est.set_max_samples(max_samples);
//  pose_est.set_max_sample_radius(max_sample_radius);
//  pose_est.set_max_neighbors(max_neighbors);
//  pose_est.set_feature_threshold(feature_threshold);
//  pose_est.set_num_candidates(num_candidates);
//  pose_est.set_debug(debug);
//
//  // Set up visualization
//  ros::Publisher heatmap_pub = nh.advertise<PointCloud2>("/heatmap", 1, true);
//  pose_est.set_heatmap_publisher(heatmap_pub);
//  ros::Publisher candidates_pub =
//      nh.advertise<PointCloud2>("/candidate_samples", 1, true);
//  pose_est.set_candidates_publisher(candidates_pub);
//  ros::Publisher best_pub =
//      nh.advertise<PointCloud2>("/best_alignment", 1, true);
//  pose_est.set_best_publisher(best_pub);
//  bool found = pose_est.Find();
//  if (found) {
//    return true;
//  } else {
//    return false;
//  }
//}
<commit_msg>Removed commented out code<commit_after>#include <iostream>
#include <string>
#include <vector>

#include "pcl/common/time.h"
#include "pcl/features/fpfh_omp.h"
#include "pcl/features/normal_3d_omp.h"
#include "pcl/filters/crop_box.h"
#include "pcl/filters/filter.h"
#include "pcl/filters/voxel_grid.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl/registration/icp.h"
#include "pcl/registration/sample_consensus_prerejective.h"
#include "pcl/segmentation/sac_segmentation.h"
#include "pcl_conversions/pcl_conversions.h"
#include "pcl_ros/transforms.h"
#include "rapid_perception/pr2.h"
#include "rapid_perception/box3d_roi_server.h"
#include "rapid_perception/pose_estimation.h"
#include "rapid_msgs/GetStaticCloud.h"
#include "rapid_msgs/ListStaticClouds.h"
#include "rapid_msgs/RemoveStaticCloud.h"
#include "rapid_msgs/SaveStaticCloud.h"
#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "visualization_msgs/Marker.h"

#include "object_search/capture_roi.h"
#include "object_search/commands.h"
#include "object_search/command_line.h"
#include "object_search/cloud_database.h"

using sensor_msgs::PointCloud2;
using pcl::FPFHSignature33;
using pcl::PointCloud;
using pcl::PointXYZRGB;
using pcl::PointXYZRGBNormal;
using visualization_msgs::Marker;
namespace rp = rapid::perception;

using namespace object_search;

int main(int argc, char** argv) {
  ros::init(argc, argv, "object_search");
  ros::NodeHandle nh;
  ros::AsyncSpinner spinner(4);
  spinner.start();

  // Build databases
  ros::ServiceClient get_cloud =
      nh.serviceClient<rapid_msgs::GetStaticCloud>("get_static_cloud");
  ros::ServiceClient list_clouds =
      nh.serviceClient<rapid_msgs::ListStaticClouds>("list_static_clouds");
  ros::ServiceClient remove_cloud =
      nh.serviceClient<rapid_msgs::RemoveStaticCloud>("remove_static_cloud");
  ros::ServiceClient save_cloud =
      nh.serviceClient<rapid_msgs::SaveStaticCloud>("save_static_cloud");
  Database object_db("object_search", "objects", get_cloud, list_clouds,
                     remove_cloud, save_cloud);
  Database scene_db("object_search", "scenes", get_cloud, list_clouds,
                    remove_cloud, save_cloud);

  // Visualization publishers
  ros::Publisher object_pub = nh.advertise<PointCloud2>("/landmark", 1, true);
  ros::Publisher scene_pub = nh.advertise<PointCloud2>("/scene", 1, true);
  ros::Publisher heatmap_pub = nh.advertise<PointCloud2>("/heatmap", 1, true);
  ros::Publisher candidates_pub =
      nh.advertise<PointCloud2>("/candidate_samples", 1, true);
  ros::Publisher best_pub =
      nh.advertise<PointCloud2>("/best_alignment", 1, true);

  // Build ROI server
  tf::TransformListener tf_listener;
  rapid::perception::Box3DRoiServer roi_server("roi");
  CaptureRoi capture(&roi_server);

  // Build pose estimator
  rapid::perception::PoseEstimator pose_estimator;

  ListCommand list_objects(&object_db, "object");
  ListCommand list_scenes(&scene_db, "scene");
  RecordObjectCommand record_object(&object_db, &capture);
  RecordSceneCommand record_scene(&scene_db);
  DeleteCommand delete_object(&object_db);
  DeleteCommand delete_scene(&scene_db);
  UseCommand use_object(&object_db, &pose_estimator, "object", object_pub);
  UseCommand use_scene(&scene_db, &pose_estimator, "scene", scene_pub);
  RunCommand run(&pose_estimator, heatmap_pub, candidates_pub, best_pub);
  SetDebugCommand set_debug(&pose_estimator);

  CommandLine cli;
  cli.set_list_objects(&list_objects);
  cli.set_list_scenes(&list_scenes);
  cli.set_record_object(&record_object);
  cli.set_record_scene(&record_scene);
  cli.set_delete_object(&delete_object);
  cli.set_delete_scene(&delete_scene);
  cli.set_use_object(&use_object);
  cli.set_use_scene(&use_scene);
  cli.set_run(&run);
  cli.set_debug(&set_debug);

  while (cli.Next()) {
  }

  spinner.stop();
  return 0;
}
<|endoftext|>


<commit_before>#include "texture.h"
#include "android_native_app_glue.h"
#include <android/log.h>
#include <vector>

#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "texture.cpp", __VA_ARGS__))

namespace Texture {

	struct KTXHeader {
		uint8_t identifier[12];
		uint32_t endianness;
		uint32_t glType;
		uint32_t glTypeSize;
		uint32_t glFormat;
		uint32_t glInternalFormat;
		uint32_t glBaseInternalFormat;
		uint32_t pixelWidth;
		uint32_t pixelHeight;
		uint32_t pixelDepth;
		uint32_t numberOfArrayElements;
		uint32_t numberOfFaces;
		uint32_t numberOfMipmapLevels;
		uint32_t bytesOfKeyValueData;
	};

	enum Endian {
		Endian_Little,
		Endian_Big,
		Endian_Unknown,
	};

	Endian GetEndian(const KTXHeader& h) {
		const uint8_t* p = reinterpret_cast<const uint8_t*>(&h.endianness);
		if (p[0] == 0x01 && p[1] == 0x02 && p[2] == 0x03 && p[3] == 0x04) {
			return Endian_Little;
		} else if (p[0] == 0x04 && p[1] == 0x03 && p[2] == 0x02 && p[3] == 0x01) {
			return Endian_Big;
		}
		return Endian_Unknown;
	}

	uint32_t GetValue(const uint32_t* pBuf, Endian e) {
		const uint8_t* p = reinterpret_cast<const uint8_t*>(pBuf);
		if (e == Endian_Little) {
			return p[3] * 0x1000000 + p[2] * 0x10000 + p[1] * 0x100 + p[0];
		}
		return p[0] * 0x1000000 + p[1] * 0x10000 + p[2] * 0x100 + p[3];
	}

	bool IsKTXHeader(const KTXHeader& h) {
		static const uint8_t fileIdentifier[12] = {
			0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
		};
		for (int i = 0; i < sizeof(fileIdentifier); ++i) {
			if (h.identifier[i] != fileIdentifier[i]) {
				return false;
			}
		}
		return true;
	}

	struct Texture : public ITexture {
		GLuint texId;
		GLenum internalFormat;
		GLenum target;
		uint16_t width;
		uint16_t height;

		Texture() : texId(0) {}
		virtual ~Texture() {
			if (texId) {
				glDeleteTextures(1, &texId);
			}
		}
		virtual GLuint TextureId() const { return texId; }
		virtual GLenum InternalFormat() const { return internalFormat; }
		virtual GLenum Target() const { return target; }
		virtual GLsizei Width() const { return width; }
		virtual GLsizei Height() const { return height; }
	};

	/** ̃eNX`쐬.
	*/
	TexturePtr CreateEmpty2D(int w, int h) {
		TexturePtr p = std::make_shared<Texture>();
		Texture& tex = static_cast<Texture&>(*p);
		tex.internalFormat = GL_RGBA;
		tex.width = w;
		tex.height = h;
		tex.target = GL_TEXTURE_2D;

		glGenTextures(1, &tex.texId);
		glBindTexture(tex.Target(), tex.texId);
		glTexImage2D(GL_TEXTURE_2D, 0, tex.InternalFormat(), tex.width, tex.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
		glTexParameteri(tex.Target(), GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(tex.Target(), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glBindTexture(tex.Target(), 0);
		return p;
	}

	/** _~[2DeNX`쐬.
	*/
	TexturePtr CreateDummy2D() {
		TexturePtr p = std::make_shared<Texture>();
		Texture& tex = static_cast<Texture&>(*p);
		tex.internalFormat = GL_RGBA;
		tex.width = 1;
		tex.height = 1;
		tex.target = GL_TEXTURE_2D;
		glGenTextures(1, &tex.texId);
		glBindTexture(tex.Target(), tex.texId);
		static const uint8_t pixels[] = { 0xF0, 0x40, 0x20, 0xff };
		glTexImage2D(GL_TEXTURE_2D, 0, tex.InternalFormat(), 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
		const GLenum result = glGetError();
		if (result != GL_NO_ERROR) {
		  LOGW("glTexImage2D error 0x%04x", result);
		}
		glTexParameteri(tex.Target(), GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(tex.Target(), GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glBindTexture(tex.Target(), 0);
		return p;
	}

	/** _~[L[u}bv쐬.
	*/
	TexturePtr CreateDummyCubeMap() {
		TexturePtr p = std::make_shared<Texture>();
		Texture& tex = static_cast<Texture&>(*p);
		tex.internalFormat = GL_RGBA;
		tex.width = 1;
		tex.height = 1;
		tex.target = GL_TEXTURE_CUBE_MAP;
		glGenTextures(1, &tex.texId);
		glBindTexture(tex.Target(), tex.texId);
		/*
		     +--+
			 |-Y|
		  +--+--+--+--+
		  |+X|-Z|-X|+Z|
		  +--+--+--+--+
		     |+Y|
			 +--+
		*/
		static const uint8_t pixels[][4] = {
			{ 0xff, 0x00, 0x00, 0xff }, // GL_TEXTURE_CUBE_MAP_POSITIVE_X
			{ 0x00, 0xff, 0x00, 0xff }, // GL_TEXTURE_CUBE_MAP_NEGATIVE_X
			{ 0x00, 0x00, 0x00, 0xff }, // GL_TEXTURE_CUBE_MAP_POSITIVE_Y
			{ 0x00, 0x00, 0xff, 0xff }, // GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
			{ 0xff, 0xff, 0x00, 0xff }, // GL_TEXTURE_CUBE_MAP_POSITIVE_Z
			{ 0xff, 0x00, 0xff, 0xff }, // GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
		};
		for (int faceIndex = 0; faceIndex < 6; ++faceIndex) {
			glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, 0, tex.InternalFormat(), 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels[faceIndex]);
		}
		glTexParameteri(tex.Target(), GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(tex.Target(), GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glBindTexture(tex.Target(), 0);
		return p;
	}

	/** KTXt@Cǂݍ.
	*/
	TexturePtr LoadKTX(android_app* state, const char* filename) {
		struct Finalizer {
			Finalizer(AAsset* a) : p(a) {}
			~Finalizer() { AAsset_close(p); }
			AAsset* p;
		};
		AAsset* pAsset = AAssetManager_open(state->activity->assetManager, filename, 0);
		if (!pAsset) {
			LOGW("cannot open:'%s'", filename);
			return nullptr;
		}

		const Finalizer finalizer(pAsset);
		const off_t size = AAsset_getLength(pAsset);
		if (size <= sizeof(KTXHeader)) {
			LOGW("illegal size:'%s'", filename);
			return nullptr;
		}
		KTXHeader header;
		int result = AAsset_read(pAsset, &header, sizeof(KTXHeader));
		if (result < 0 || !IsKTXHeader(header)) {
			LOGW("illegal header:'%s'", filename);
			return nullptr;
		}
		TexturePtr p = std::make_shared<Texture>();
		Texture& tex = static_cast<Texture&>(*p);
		const Endian endianness = GetEndian(header);
		const GLenum type = GetValue(&header.glType, endianness);
		const GLenum format = GetValue(&header.glBaseInternalFormat, endianness);
		const int faceCount = GetValue(&header.numberOfFaces, endianness);
		const int mipCount = GetValue(&header.numberOfMipmapLevels, endianness);
		tex.internalFormat = GetValue(&header.glInternalFormat, endianness);
		tex.width = GetValue(&header.pixelWidth, endianness);
		tex.height = GetValue(&header.pixelHeight, endianness);
		tex.target = faceCount == 6 ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D;

		const uint32_t off = GetValue(&header.bytesOfKeyValueData, endianness);
		AAsset_seek(pAsset, off, SEEK_CUR);

		glGenTextures(1, &tex.texId);
		glBindTexture(tex.Target(), tex.texId);
		std::vector<uint8_t> data;
		GLsizei curWidth = tex.Width();
		GLsizei curHeight = tex.Height();
		for (int mipLevel = 0; mipLevel < (mipCount ? mipCount : 1); ++mipLevel) {
			uint32_t imageSize;
			result = AAsset_read(pAsset, &imageSize, 4);
			if (result < 0) {
				LOGW("can't read(miplevel=%d):'%s'", mipLevel, filename);
				return nullptr;
			}
			imageSize = GetValue(&imageSize, endianness);
			const uint32_t imageSizeWithPadding = (imageSize + 3) & ~3;
			data.resize(imageSizeWithPadding * faceCount);
			result = AAsset_read(pAsset, &data[0], data.size());
			if (result < 0) {
				LOGW("can't read(miplevel=%d):'%s'", mipLevel, filename);
				return nullptr;
			}
			const uint8_t* pImage = reinterpret_cast<const uint8_t*>(&data[0]);
			const GLenum target = tex.Target() == GL_TEXTURE_CUBE_MAP ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : GL_TEXTURE_2D;
			for (int faceIndex = 0; faceIndex < faceCount; ++faceIndex) {
				if (type == 0) {
					glCompressedTexImage2D(target + faceIndex, mipLevel, tex.InternalFormat(), curWidth, curHeight, 0, imageSize, pImage);
				} else {
					glTexImage2D(target + faceIndex, mipLevel, tex.InternalFormat(), curWidth, curHeight, 0, format, type, pImage);
				}
				const GLenum result = glGetError();
				switch(result) {
				case GL_NO_ERROR:
				  break;
				case GL_INVALID_OPERATION:
				  LOGW("glCompressed/TexImage2D return GL_INVALID_OPERATION");
				  break;
				default:
				  LOGW("glCompressed/TexImage2D return error code 0x%04x", result);
				  break;
				}
				pImage += imageSizeWithPadding;
			}
			curWidth = std::max(1, curWidth / 2);
			curHeight = std::max(1, curHeight / 2);
		}
		glTexParameteri(tex.Target(), GL_TEXTURE_MIN_FILTER, mipCount > 1 ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
		glTexParameteri(tex.Target(), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glBindTexture(tex.Target(), 0);
		return p;
	}
}<commit_msg>fix the mistake of selecting argument for texImage2D.<commit_after>#include "texture.h"
#include "android_native_app_glue.h"
#include <android/log.h>
#include <vector>

#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "texture.cpp", __VA_ARGS__))

namespace Texture {

	struct KTXHeader {
		uint8_t identifier[12];
		uint32_t endianness;
		uint32_t glType;
		uint32_t glTypeSize;
		uint32_t glFormat;
		uint32_t glInternalFormat;
		uint32_t glBaseInternalFormat;
		uint32_t pixelWidth;
		uint32_t pixelHeight;
		uint32_t pixelDepth;
		uint32_t numberOfArrayElements;
		uint32_t numberOfFaces;
		uint32_t numberOfMipmapLevels;
		uint32_t bytesOfKeyValueData;
	};

	enum Endian {
		Endian_Little,
		Endian_Big,
		Endian_Unknown,
	};

	Endian GetEndian(const KTXHeader& h) {
		const uint8_t* p = reinterpret_cast<const uint8_t*>(&h.endianness);
		if (p[0] == 0x01 && p[1] == 0x02 && p[2] == 0x03 && p[3] == 0x04) {
			return Endian_Little;
		} else if (p[0] == 0x04 && p[1] == 0x03 && p[2] == 0x02 && p[3] == 0x01) {
			return Endian_Big;
		}
		return Endian_Unknown;
	}

	uint32_t GetValue(const uint32_t* pBuf, Endian e) {
		const uint8_t* p = reinterpret_cast<const uint8_t*>(pBuf);
		if (e == Endian_Little) {
			return p[3] * 0x1000000 + p[2] * 0x10000 + p[1] * 0x100 + p[0];
		}
		return p[0] * 0x1000000 + p[1] * 0x10000 + p[2] * 0x100 + p[3];
	}

	bool IsKTXHeader(const KTXHeader& h) {
		static const uint8_t fileIdentifier[12] = {
			0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
		};
		for (int i = 0; i < sizeof(fileIdentifier); ++i) {
			if (h.identifier[i] != fileIdentifier[i]) {
				return false;
			}
		}
		return true;
	}

	struct Texture : public ITexture {
		GLuint texId;
		GLenum internalFormat;
		GLenum target;
		uint16_t width;
		uint16_t height;

		Texture() : texId(0) {}
		virtual ~Texture() {
			if (texId) {
				glDeleteTextures(1, &texId);
			}
		}
		virtual GLuint TextureId() const { return texId; }
		virtual GLenum InternalFormat() const { return internalFormat; }
		virtual GLenum Target() const { return target; }
		virtual GLsizei Width() const { return width; }
		virtual GLsizei Height() const { return height; }
	};

	/** ̃eNX`쐬.
	*/
	TexturePtr CreateEmpty2D(int w, int h) {
		TexturePtr p = std::make_shared<Texture>();
		Texture& tex = static_cast<Texture&>(*p);
		tex.internalFormat = GL_RGBA;
		tex.width = w;
		tex.height = h;
		tex.target = GL_TEXTURE_2D;

		glGenTextures(1, &tex.texId);
		glBindTexture(tex.Target(), tex.texId);
		glTexImage2D(GL_TEXTURE_2D, 0, tex.InternalFormat(), tex.width, tex.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
		glTexParameteri(tex.Target(), GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(tex.Target(), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glBindTexture(tex.Target(), 0);
		return p;
	}

	/** _~[2DeNX`쐬.
	*/
	TexturePtr CreateDummy2D() {
		TexturePtr p = std::make_shared<Texture>();
		Texture& tex = static_cast<Texture&>(*p);
		tex.internalFormat = GL_RGBA;
		tex.width = 1;
		tex.height = 1;
		tex.target = GL_TEXTURE_2D;
		glGenTextures(1, &tex.texId);
		glBindTexture(tex.Target(), tex.texId);
		static const uint8_t pixels[] = { 0xF0, 0x40, 0x20, 0xff };
		glTexImage2D(GL_TEXTURE_2D, 0, tex.InternalFormat(), 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
		const GLenum result = glGetError();
		if (result != GL_NO_ERROR) {
		  LOGW("glTexImage2D error 0x%04x", result);
		}
		glTexParameteri(tex.Target(), GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(tex.Target(), GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glBindTexture(tex.Target(), 0);
		return p;
	}

	/** _~[L[u}bv쐬.
	*/
	TexturePtr CreateDummyCubeMap() {
		TexturePtr p = std::make_shared<Texture>();
		Texture& tex = static_cast<Texture&>(*p);
		tex.internalFormat = GL_RGBA;
		tex.width = 1;
		tex.height = 1;
		tex.target = GL_TEXTURE_CUBE_MAP;
		glGenTextures(1, &tex.texId);
		glBindTexture(tex.Target(), tex.texId);
		/*
		     +--+
			 |-Y|
		  +--+--+--+--+
		  |+X|-Z|-X|+Z|
		  +--+--+--+--+
		     |+Y|
			 +--+
		*/
		static const uint8_t pixels[][4] = {
			{ 0xff, 0x00, 0x00, 0xff }, // GL_TEXTURE_CUBE_MAP_POSITIVE_X
			{ 0x00, 0xff, 0x00, 0xff }, // GL_TEXTURE_CUBE_MAP_NEGATIVE_X
			{ 0x00, 0x00, 0x00, 0xff }, // GL_TEXTURE_CUBE_MAP_POSITIVE_Y
			{ 0x00, 0x00, 0xff, 0xff }, // GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
			{ 0xff, 0xff, 0x00, 0xff }, // GL_TEXTURE_CUBE_MAP_POSITIVE_Z
			{ 0xff, 0x00, 0xff, 0xff }, // GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
		};
		for (int faceIndex = 0; faceIndex < 6; ++faceIndex) {
			glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, 0, tex.InternalFormat(), 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels[faceIndex]);
		}
		glTexParameteri(tex.Target(), GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(tex.Target(), GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glBindTexture(tex.Target(), 0);
		return p;
	}

	/** KTXt@Cǂݍ.
	*/
	TexturePtr LoadKTX(android_app* state, const char* filename) {
		struct Finalizer {
			Finalizer(AAsset* a) : p(a) {}
			~Finalizer() { AAsset_close(p); }
			AAsset* p;
		};
		AAsset* pAsset = AAssetManager_open(state->activity->assetManager, filename, 0);
		if (!pAsset) {
			LOGW("cannot open:'%s'", filename);
			return nullptr;
		}

		const Finalizer finalizer(pAsset);
		const off_t size = AAsset_getLength(pAsset);
		if (size <= sizeof(KTXHeader)) {
			LOGW("illegal size:'%s'", filename);
			return nullptr;
		}
		KTXHeader header;
		int result = AAsset_read(pAsset, &header, sizeof(KTXHeader));
		if (result < 0 || !IsKTXHeader(header)) {
			LOGW("illegal header:'%s'", filename);
			return nullptr;
		}
		TexturePtr p = std::make_shared<Texture>();
		Texture& tex = static_cast<Texture&>(*p);
		const Endian endianness = GetEndian(header);
		const GLenum type = GetValue(&header.glType, endianness);
		const GLenum format = GetValue(type ? &header.glFormat : &header.glBaseInternalFormat, endianness);
		const int faceCount = GetValue(&header.numberOfFaces, endianness);
		const int mipCount = GetValue(&header.numberOfMipmapLevels, endianness);
		tex.internalFormat = GetValue(type ? &header.glBaseInternalFormat : &header.glInternalFormat, endianness);
		tex.width = GetValue(&header.pixelWidth, endianness);
		tex.height = GetValue(&header.pixelHeight, endianness);
		tex.target = faceCount == 6 ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D;

		const uint32_t off = GetValue(&header.bytesOfKeyValueData, endianness);
		AAsset_seek(pAsset, off, SEEK_CUR);

		glGenTextures(1, &tex.texId);
		glBindTexture(tex.Target(), tex.texId);
		std::vector<uint8_t> data;
		GLsizei curWidth = tex.Width();
		GLsizei curHeight = tex.Height();
		for (int mipLevel = 0; mipLevel < (mipCount ? mipCount : 1); ++mipLevel) {
			uint32_t imageSize;
			result = AAsset_read(pAsset, &imageSize, 4);
			if (result < 0) {
				LOGW("can't read(miplevel=%d):'%s'", mipLevel, filename);
				return nullptr;
			}
			imageSize = GetValue(&imageSize, endianness);
			const uint32_t imageSizeWithPadding = (imageSize + 3) & ~3;
			data.resize(imageSizeWithPadding * faceCount);
			result = AAsset_read(pAsset, &data[0], data.size());
			if (result < 0) {
				LOGW("can't read(miplevel=%d):'%s'", mipLevel, filename);
				return nullptr;
			}
			const uint8_t* pImage = reinterpret_cast<const uint8_t*>(&data[0]);
			const GLenum target = tex.Target() == GL_TEXTURE_CUBE_MAP ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : GL_TEXTURE_2D;
			for (int faceIndex = 0; faceIndex < faceCount; ++faceIndex) {
				if (type == 0) {
					glCompressedTexImage2D(target + faceIndex, mipLevel, tex.InternalFormat(), curWidth, curHeight, 0, imageSize, pImage);
				} else {
					glTexImage2D(target + faceIndex, mipLevel, tex.InternalFormat(), curWidth, curHeight, 0, format, type, pImage);
				}
				const GLenum result = glGetError();
				switch(result) {
				case GL_NO_ERROR:
				  break;
				case GL_INVALID_OPERATION:
				  LOGW("glCompressed/TexImage2D return GL_INVALID_OPERATION");
				  break;
				default:
				  LOGW("glCompressed/TexImage2D return error code 0x%04x", result);
				  break;
				}
				pImage += imageSizeWithPadding;
			}
			curWidth = std::max(1, curWidth / 2);
			curHeight = std::max(1, curHeight / 2);
		}
		glTexParameteri(tex.Target(), GL_TEXTURE_MIN_FILTER, mipCount > 1 ? GL_LINEAR_MIPMAP_LINEAR : GL_LINEAR);
		glTexParameteri(tex.Target(), GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(tex.Target(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glBindTexture(tex.Target(), 0);
		return p;
	}
}<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/voice_engine/utility.h"

#include "webrtc/base/logging.h"
#include "webrtc/common_audio/resampler/include/push_resampler.h"
#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
#include "webrtc/common_types.h"
#include "webrtc/modules/include/module_common_types.h"
#include "webrtc/modules/utility/include/audio_frame_operations.h"
#include "webrtc/voice_engine/voice_engine_defines.h"

namespace webrtc {
namespace voe {

void RemixAndResample(const AudioFrame& src_frame,
                      PushResampler<int16_t>* resampler,
                      AudioFrame* dst_frame) {
  RemixAndResample(src_frame.data_, src_frame.samples_per_channel_,
                   src_frame.num_channels_, src_frame.sample_rate_hz_,
                   resampler, dst_frame);
  dst_frame->timestamp_ = src_frame.timestamp_;
  dst_frame->elapsed_time_ms_ = src_frame.elapsed_time_ms_;
  dst_frame->ntp_time_ms_ = src_frame.ntp_time_ms_;
}

void RemixAndResample(const int16_t* src_data,
                      size_t samples_per_channel,
                      size_t num_channels,
                      int sample_rate_hz,
                      PushResampler<int16_t>* resampler,
                      AudioFrame* dst_frame) {
  const int16_t* audio_ptr = src_data;
  size_t audio_ptr_num_channels = num_channels;
  int16_t mono_audio[AudioFrame::kMaxDataSizeSamples];

  // Downmix before resampling.
  if (num_channels == 2 && dst_frame->num_channels_ == 1) {
    AudioFrameOperations::StereoToMono(src_data, samples_per_channel,
                                       mono_audio);
    audio_ptr = mono_audio;
    audio_ptr_num_channels = 1;
  }

  if (resampler->InitializeIfNeeded(sample_rate_hz, dst_frame->sample_rate_hz_,
                                    audio_ptr_num_channels) == -1) {
    LOG(LS_ERROR) << "InitializeIfNeeded failed: sample_rate_hz = "
                  << sample_rate_hz << ", dst_frame->sample_rate_hz_ = "
                  << dst_frame->sample_rate_hz_
                  << ", audio_ptr_num_channels = " << audio_ptr_num_channels;
    assert(false);
  }

  const size_t src_length = samples_per_channel * audio_ptr_num_channels;
  int out_length = resampler->Resample(audio_ptr, src_length, dst_frame->data_,
                                       AudioFrame::kMaxDataSizeSamples);
  if (out_length == -1) {
    LOG(LS_ERROR) << "Resample failed: audio_ptr = " << audio_ptr
                  << ", src_length = " << src_length
                  << ", dst_frame->data_ = " << dst_frame->data_;
    assert(false);
  }
  dst_frame->samples_per_channel_ = out_length / audio_ptr_num_channels;

  // Upmix after resampling.
  if (num_channels == 1 && dst_frame->num_channels_ == 2) {
    // The audio in dst_frame really is mono at this point; MonoToStereo will
    // set this back to stereo.
    dst_frame->num_channels_ = 1;
    AudioFrameOperations::MonoToStereo(dst_frame);
  }
}

void MixWithSat(int16_t target[],
                size_t target_channel,
                const int16_t source[],
                size_t source_channel,
                size_t source_len) {
  assert(target_channel == 1 || target_channel == 2);
  assert(source_channel == 1 || source_channel == 2);

  if (target_channel == 2 && source_channel == 1) {
    // Convert source from mono to stereo.
    int32_t left = 0;
    int32_t right = 0;
    for (size_t i = 0; i < source_len; ++i) {
      left = source[i] + target[i * 2];
      right = source[i] + target[i * 2 + 1];
      target[i * 2] = WebRtcSpl_SatW32ToW16(left);
      target[i * 2 + 1] = WebRtcSpl_SatW32ToW16(right);
    }
  } else if (target_channel == 1 && source_channel == 2) {
    // Convert source from stereo to mono.
    int32_t temp = 0;
    for (size_t i = 0; i < source_len / 2; ++i) {
      temp = ((source[i * 2] + source[i * 2 + 1]) >> 1) + target[i];
      target[i] = WebRtcSpl_SatW32ToW16(temp);
    }
  } else {
    int32_t temp = 0;
    for (size_t i = 0; i < source_len; ++i) {
      temp = source[i] + target[i];
      target[i] = WebRtcSpl_SatW32ToW16(temp);
    }
  }
}

}  // namespace voe
}  // namespace webrtc
<commit_msg>Reland of Adding a some checks and switching out a few assert for RTC_[D]CHECK. (patchset #1 id:1 of https://codereview.webrtc.org/2018553002/ )<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/voice_engine/utility.h"

#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/common_audio/resampler/include/push_resampler.h"
#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
#include "webrtc/common_types.h"
#include "webrtc/modules/include/module_common_types.h"
#include "webrtc/modules/utility/include/audio_frame_operations.h"
#include "webrtc/voice_engine/voice_engine_defines.h"

namespace webrtc {
namespace voe {

void RemixAndResample(const AudioFrame& src_frame,
                      PushResampler<int16_t>* resampler,
                      AudioFrame* dst_frame) {
  RemixAndResample(src_frame.data_, src_frame.samples_per_channel_,
                   src_frame.num_channels_, src_frame.sample_rate_hz_,
                   resampler, dst_frame);
  dst_frame->timestamp_ = src_frame.timestamp_;
  dst_frame->elapsed_time_ms_ = src_frame.elapsed_time_ms_;
  dst_frame->ntp_time_ms_ = src_frame.ntp_time_ms_;
}

void RemixAndResample(const int16_t* src_data,
                      size_t samples_per_channel,
                      size_t num_channels,
                      int sample_rate_hz,
                      PushResampler<int16_t>* resampler,
                      AudioFrame* dst_frame) {
  const int16_t* audio_ptr = src_data;
  size_t audio_ptr_num_channels = num_channels;
  int16_t mono_audio[AudioFrame::kMaxDataSizeSamples];

  // Downmix before resampling.
  if (num_channels == 2 && dst_frame->num_channels_ == 1) {
    AudioFrameOperations::StereoToMono(src_data, samples_per_channel,
                                       mono_audio);
    audio_ptr = mono_audio;
    audio_ptr_num_channels = 1;
  }

  if (resampler->InitializeIfNeeded(sample_rate_hz, dst_frame->sample_rate_hz_,
                                    audio_ptr_num_channels) == -1) {
    FATAL() << "InitializeIfNeeded failed: sample_rate_hz = " << sample_rate_hz
            << ", dst_frame->sample_rate_hz_ = " << dst_frame->sample_rate_hz_
            << ", audio_ptr_num_channels = " << audio_ptr_num_channels;
  }

  const size_t src_length = samples_per_channel * audio_ptr_num_channels;
  int out_length = resampler->Resample(audio_ptr, src_length, dst_frame->data_,
                                       AudioFrame::kMaxDataSizeSamples);
  if (out_length == -1) {
    FATAL() << "Resample failed: audio_ptr = " << audio_ptr
            << ", src_length = " << src_length
            << ", dst_frame->data_ = " << dst_frame->data_;
  }
  dst_frame->samples_per_channel_ = out_length / audio_ptr_num_channels;

  // Upmix after resampling.
  if (num_channels == 1 && dst_frame->num_channels_ == 2) {
    // The audio in dst_frame really is mono at this point; MonoToStereo will
    // set this back to stereo.
    dst_frame->num_channels_ = 1;
    AudioFrameOperations::MonoToStereo(dst_frame);
  }
}

void MixWithSat(int16_t target[],
                size_t target_channel,
                const int16_t source[],
                size_t source_channel,
                size_t source_len) {
  RTC_DCHECK_GE(target_channel, 1u);
  RTC_DCHECK_LE(target_channel, 2u);
  RTC_DCHECK_GE(source_channel, 1u);
  RTC_DCHECK_LE(source_channel, 2u);

  if (target_channel == 2 && source_channel == 1) {
    // Convert source from mono to stereo.
    int32_t left = 0;
    int32_t right = 0;
    for (size_t i = 0; i < source_len; ++i) {
      left = source[i] + target[i * 2];
      right = source[i] + target[i * 2 + 1];
      target[i * 2] = WebRtcSpl_SatW32ToW16(left);
      target[i * 2 + 1] = WebRtcSpl_SatW32ToW16(right);
    }
  } else if (target_channel == 1 && source_channel == 2) {
    // Convert source from stereo to mono.
    int32_t temp = 0;
    for (size_t i = 0; i < source_len / 2; ++i) {
      temp = ((source[i * 2] + source[i * 2 + 1]) >> 1) + target[i];
      target[i] = WebRtcSpl_SatW32ToW16(temp);
    }
  } else {
    int32_t temp = 0;
    for (size_t i = 0; i < source_len; ++i) {
      temp = source[i] + target[i];
      target[i] = WebRtcSpl_SatW32ToW16(temp);
    }
  }
}

}  // namespace voe
}  // namespace webrtc
<|endoftext|>


<commit_before>#include "NEKeyManager.hpp"
#include "define/define.hpp"
#include "../Kernal/Kernal.hpp"
#include "../NEBooleanKey/NEBooleanKey.hpp"
#include "../NECharKey/NECharKey.hpp"
#include "../NEByteKey/NEByteKey.hpp"
#include "../NEUByteKey/NEUByteKey.hpp"
#include "../NEWCharKey/NEWCharKey.hpp"
#include "../NEShortKey/NEShortKey.hpp"
#include "../NEUShortKey/NEUShortKey.hpp"
#include "../NEIntKey/NEIntKey.hpp"
#include "../NEUIntKey/NEUIntKey.hpp"
#include "../NEInt64Key/NEInt64Key.hpp"
#include "../NEFloatKey/NEFloatKey.hpp"
#include "../NEDoubleKey/NEDoubleKey.hpp"
#include "../NEStringKey/NEStringKey.hpp"
#include "../NEWStringKey/NEWStringKey.hpp"
#include "../NEBooleanSetKey/NEBooleanSetKey.hpp"
#include "../NEByteSetKey/NEByteSetKey.hpp"
#include "../NEUByteSetKey/NEUByteSetKey.hpp"
#include "../NEShortSetKey/NEShortSetKey.hpp"
#include "../NEUShortSetKey/NEUShortSetKey.hpp"
#include "../NEIntSetKey/NEIntSetKey.hpp"
#include "../NEUIntSetKey/NEUIntSetKey.hpp"
#include "../NEInt64SetKey/NEInt64SetKey.hpp"
#include "../NEFloatSetKey/NEFloatSetKEy.hpp"
#include "../NEDoubleSetKey/NEDoubleSetKey.hpp"
#include "../NEStringSetKey/NEStringSetKey.hpp"
#include "../NEWStringSetKey/NEWStringSetKey.hpp"
#include "../NENodeSelector/NENodeSelector.hpp"
#include "../NEModuleSelector/NEModuleSelector.hpp"
#include "../NEKeySelector/NEKeySelector.hpp"
#include "../NEModuleCodeSetKey/NEModuleCodeSetKey.hpp"
#include "../NENodeCodeSetKey/NENodeCodeSetKey.hpp"

namespace NE
{
	bool NEKeyManager::operator==(const NEKeyManager& source) const
	{
		if(this == &source) return true;

		return NEModule::operator==(source);
	}
	bool NEKeyManager::operator!=(const NEKeyManager& source) const
	{
		return ! operator==(source);
	}
	const NEKey& NEKeyManager::getKey(NEType::Type type) const
	{
		for(int n=0; n < _keyset.getLength() ;n++)
			if(_keyset[n].getType() == type)
				return _keyset[n];

		KERNAL_ERROR(", մ ׷ Ű  \n\t: û Ű %s(%d)", NEType::getTypeName(type), type);
		NEKey* nullpointer = 0x00;
		return *nullpointer;
	}

	const NEKey& NEKeyManager::getKey(const NEString& type_name) const
	{
		for(int n=0; n < _keyset.getLength() ;n++)
			if(NEString(_keyset[n].getTypeName()) == type_name)
				return _keyset[n];

		NEKey* nullpointer = 0x00;
		return *nullpointer;
	}

	type_result NEKeyManager::initialize()
	{
		_keyset.create(31);
		_keyset.push(NEBooleanKey());
		_keyset.push(NECharKey());
		_keyset.push(NEByteKey());
		_keyset.push(NEUByteKey());
		_keyset.push(NEWCharKey());
		_keyset.push(NEShortKey());
		_keyset.push(NEUShortKey());
		_keyset.push(NEIntKey());
		_keyset.push(NEUIntKey());
		_keyset.push(NEInt64Key());
		_keyset.push(NEFloatKey());
		_keyset.push(NEDoubleKey());
		_keyset.push(NEStringKey());
		_keyset.push(NEWStringKey());
		_keyset.push(NEBooleanSetKey());
		_keyset.push(NEByteSetKey());
		_keyset.push(NEUByteSetKey());
		_keyset.push(NEShortSetKey());
		_keyset.push(NEUShortSetKey());
		_keyset.push(NEIntSetKey());
		_keyset.push(NEUIntSetKey());
		_keyset.push(NEInt64SetKey());
		_keyset.push(NEFloatSetKey());
		_keyset.push(NEDoubleSetKey());
		_keyset.push(NEStringSetKey());
		_keyset.push(NEWStringSetKey());
		_keyset.push(NEModuleCodeSetKey());
		_keyset.push(NENodeCodeSetKey());
		_keyset.push(NENodeSelector());
		_keyset.push(NEModuleSelector());
		_keyset.push(NEKeySelector());

		return RESULT_SUCCESS;
	}
	const NEExportable::ModuleHeader& NEKeyManager::getHeader() const
	{
		static NEExportable::ModuleHeader _header;

		if(_header.isValid() != RESULT_SUCCESS)
		{
			_header.getName() = _T(_NAME);
			_header.getDeveloper() = _T(_DEVELOPER);;
			_header.setRevision(_REVISION);
			_header.getReleaseDate() = _T(_DATE);
			_header.getVersion()  = _T(_VERSION);
			_header.getComment() = _T(_COMMENT);
			//_header.setMaxErrorCodeCount(NEKeyManager::END_OF_ERROR_CODE - 1);
		}

		return _header;
	}
	type_result NEKeyManager::execute()
	{
		return RESULT_SUCCESS;
	}
	NEType::Type NEKeyManager::getType() const
	{
		return NEType::NEKEY_MANAGER;
	}
	NEObject& NEKeyManager::clone() const
	{
		return *(new NEKeyManager(*this));
	}

	const NEKeySet& NEKeyManager::getKeySet() const
	{
		return _keyset;
	}
}<commit_msg>NEKeyManager에서 키배열 접근자 추가<commit_after>#include "NEKeyManager.hpp"
#include "define/define.hpp"
#include "../Kernal/Kernal.hpp"
#include "../NEBooleanKey/NEBooleanKey.hpp"
#include "../NECharKey/NECharKey.hpp"
#include "../NEByteKey/NEByteKey.hpp"
#include "../NEUByteKey/NEUByteKey.hpp"
#include "../NEWCharKey/NEWCharKey.hpp"
#include "../NEShortKey/NEShortKey.hpp"
#include "../NEUShortKey/NEUShortKey.hpp"
#include "../NEIntKey/NEIntKey.hpp"
#include "../NEUIntKey/NEUIntKey.hpp"
#include "../NEInt64Key/NEInt64Key.hpp"
#include "../NEFloatKey/NEFloatKey.hpp"
#include "../NEDoubleKey/NEDoubleKey.hpp"
#include "../NEStringKey/NEStringKey.hpp"
#include "../NEWStringKey/NEWStringKey.hpp"
#include "../NEBooleanSetKey/NEBooleanSetKey.hpp"
#include "../NEByteSetKey/NEByteSetKey.hpp"
#include "../NEUByteSetKey/NEUByteSetKey.hpp"
#include "../NEShortSetKey/NEShortSetKey.hpp"
#include "../NEUShortSetKey/NEUShortSetKey.hpp"
#include "../NEIntSetKey/NEIntSetKey.hpp"
#include "../NEUIntSetKey/NEUIntSetKey.hpp"
#include "../NEInt64SetKey/NEInt64SetKey.hpp"
#include "../NEFloatSetKey/NEFloatSetKEy.hpp"
#include "../NEDoubleSetKey/NEDoubleSetKey.hpp"
#include "../NEStringSetKey/NEStringSetKey.hpp"
#include "../NEWStringSetKey/NEWStringSetKey.hpp"
#include "../NENodeSelector/NENodeSelector.hpp"
#include "../NEModuleSelector/NEModuleSelector.hpp"
#include "../NEKeySelector/NEKeySelector.hpp"
#include "../NEModuleCodeSetKey/NEModuleCodeSetKey.hpp"
#include "../NENodeCodeSetKey/NENodeCodeSetKey.hpp"

namespace NE
{
	bool NEKeyManager::operator==(const NEKeyManager& source) const
	{
		if(this == &source) return true;

		return NEModule::operator==(source);
	}
	bool NEKeyManager::operator!=(const NEKeyManager& source) const
	{
		return ! operator==(source);
	}
	const NEKey& NEKeyManager::getKey(NEType::Type type) const
	{
		for(int n=0; n < _keyset.getLength() ;n++)
			if(_keyset[n].getType() == type)
				return _keyset[n];

		KERNAL_ERROR(", մ ׷ Ű  \n\t: û Ű %s(%d)", NEType::getTypeName(type), type);
		NEKey* nullpointer = 0x00;
		return *nullpointer;
	}
	type_result NEKeyManager::initialize()
	{
		_keyset.create(31);
		_keyset.push(NEBooleanKey());
		_keyset.push(NECharKey());
		_keyset.push(NEByteKey());
		_keyset.push(NEUByteKey());
		_keyset.push(NEWCharKey());
		_keyset.push(NEShortKey());
		_keyset.push(NEUShortKey());
		_keyset.push(NEIntKey());
		_keyset.push(NEUIntKey());
		_keyset.push(NEInt64Key());
		_keyset.push(NEFloatKey());
		_keyset.push(NEDoubleKey());
		_keyset.push(NEStringKey());
		_keyset.push(NEWStringKey());
		_keyset.push(NEBooleanSetKey());
		_keyset.push(NEByteSetKey());
		_keyset.push(NEUByteSetKey());
		_keyset.push(NEShortSetKey());
		_keyset.push(NEUShortSetKey());
		_keyset.push(NEIntSetKey());
		_keyset.push(NEUIntSetKey());
		_keyset.push(NEInt64SetKey());
		_keyset.push(NEFloatSetKey());
		_keyset.push(NEDoubleSetKey());
		_keyset.push(NEStringSetKey());
		_keyset.push(NEWStringSetKey());
		_keyset.push(NEModuleCodeSetKey());
		_keyset.push(NENodeCodeSetKey());
		_keyset.push(NENodeSelector());
		_keyset.push(NEModuleSelector());
		_keyset.push(NEKeySelector());

		return RESULT_SUCCESS;
	}
	const NEExportable::ModuleHeader& NEKeyManager::getHeader() const
	{
		static NEExportable::ModuleHeader _header;

		if(_header.isValid() != RESULT_SUCCESS)
		{
			_header.getName() = _T(_NAME);
			_header.getDeveloper() = _T(_DEVELOPER);;
			_header.setRevision(_REVISION);
			_header.getReleaseDate() = _T(_DATE);
			_header.getVersion()  = _T(_VERSION);
			_header.getComment() = _T(_COMMENT);
			//_header.setMaxErrorCodeCount(NEKeyManager::END_OF_ERROR_CODE - 1);
		}

		return _header;
	}
	type_result NEKeyManager::execute()
	{
		return RESULT_SUCCESS;
	}
	NEType::Type NEKeyManager::getType() const
	{
		return NEType::NEKEY_MANAGER;
	}
	NEObject& NEKeyManager::clone() const
	{
		return *(new NEKeyManager(*this));
	}
	const NEKeySet& NEKeyManager::getKeySet() const
	{
		return _keyset;
	}
}<|endoftext|>


<commit_before>/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2017 Roman Lebedev

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#ifndef PARSER
#error PARSER must be defined
#endif

#ifndef GETDECODER
#error GETDECODER must be defined as bool
#endif

#include "io/Buffer.h"                   // for Buffer, DataBuffer
#include "io/IOException.h"              // for IOException
#include "parsers/CiffParser.h"          // IWYU pragma: keep
#include "parsers/CiffParserException.h" // IWYU pragma: keep
#include "parsers/FiffParser.h"          // IWYU pragma: keep
#include "parsers/FiffParserException.h" // IWYU pragma: keep
#include "parsers/RawParser.h"           // IWYU pragma: keep
#include "parsers/RawParserException.h"  // IWYU pragma: keep
#include "parsers/TiffParser.h"          // IWYU pragma: keep
#include "parsers/TiffParserException.h" // IWYU pragma: keep
#include "parsers/X3fParser.h"           // IWYU pragma: keep
#include "parsers/X3fParserException.h"  // IWYU pragma: keep
#include "tiff/TiffEntry.h"              // IWYU pragma: keep
#include <cassert>                       // for assert
#include <cstdint>                       // for uint8_t
#include <cstdio>                        // for size_t

#if GETDECODER
#include "decoders/RawDecoder.h" // IWYU pragma: keep
#endif

#define TOKENPASTE2(x, y) x##y
#define TOKENPASTE(x, y) TOKENPASTE2(x, y)

// define this function, it is only declared in rawspeed:
// for fuzzing, do not want any threading.
extern "C" int __attribute__((const)) rawspeed_get_number_of_processor_cores() {
  return 1;
}

using PARSERException = TOKENPASTE(rawspeed::PARSER, Exception);

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size);

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) {
  assert(Data);

  const rawspeed::Buffer buffer(Data, Size);

  try {
    rawspeed::PARSER parser(&buffer);

#if GETDECODER
    parser.getDecoder();
#endif
  } catch (PARSERException&) {
    return 0;
  } catch (rawspeed::IOException&) {
    return 0;
  }

  return 0;
}
<commit_msg>Parser fuzzer: catch RawDecoderException too<commit_after>/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2017 Roman Lebedev

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/

#ifndef PARSER
#error PARSER must be defined
#endif

#ifndef GETDECODER
#error GETDECODER must be defined as bool
#endif

#include "io/Buffer.h"                   // for Buffer, DataBuffer
#include "io/IOException.h"              // for IOException
#include "parsers/CiffParser.h"          // IWYU pragma: keep
#include "parsers/CiffParserException.h" // IWYU pragma: keep
#include "parsers/FiffParser.h"          // IWYU pragma: keep
#include "parsers/FiffParserException.h" // IWYU pragma: keep
#include "parsers/RawParser.h"           // IWYU pragma: keep
#include "parsers/RawParserException.h"  // IWYU pragma: keep
#include "parsers/TiffParser.h"          // IWYU pragma: keep
#include "parsers/TiffParserException.h" // IWYU pragma: keep
#include "parsers/X3fParser.h"           // IWYU pragma: keep
#include "parsers/X3fParserException.h"  // IWYU pragma: keep
#include "tiff/TiffEntry.h"              // IWYU pragma: keep
#include <cassert>                       // for assert
#include <cstdint>                       // for uint8_t
#include <cstdio>                        // for size_t

#if GETDECODER
#include "decoders/RawDecoder.h" // IWYU pragma: keep
#endif

#define TOKENPASTE2(x, y) x##y
#define TOKENPASTE(x, y) TOKENPASTE2(x, y)

// define this function, it is only declared in rawspeed:
// for fuzzing, do not want any threading.
extern "C" int __attribute__((const)) rawspeed_get_number_of_processor_cores() {
  return 1;
}

using PARSERException = TOKENPASTE(rawspeed::PARSER, Exception);

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size);

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) {
  assert(Data);

  const rawspeed::Buffer buffer(Data, Size);

  try {
    rawspeed::PARSER parser(&buffer);

#if GETDECODER
    parser.getDecoder();
#endif
  } catch (PARSERException&) {
    return 0;
  } catch (rawspeed::RawDecoderException&) {
    return 0;
  } catch (rawspeed::IOException&) {
    return 0;
  }

  return 0;
}
<|endoftext|>