Пример #1
0
static riemann_event_t *
wrr_value_to_event(struct riemann_host const *host, /* {{{ */
                   data_set_t const *ds, value_list_t const *vl, size_t index,
                   gauge_t const *rates, int status) {
  riemann_event_t *event;
  char name_buffer[5 * DATA_MAX_NAME_LEN];
  char service_buffer[6 * DATA_MAX_NAME_LEN];
  size_t i;

  event = riemann_event_new();
  if (event == NULL) {
    ERROR("write_riemann plugin: riemann_event_new() failed.");
    return NULL;
  }

  format_name(name_buffer, sizeof(name_buffer),
              /* host = */ "", vl->plugin, vl->plugin_instance, vl->type,
              vl->type_instance);
  if (host->always_append_ds || (ds->ds_num > 1)) {
    if (host->event_service_prefix == NULL)
      snprintf(service_buffer, sizeof(service_buffer), "%s/%s", &name_buffer[1],
               ds->ds[index].name);
    else
      snprintf(service_buffer, sizeof(service_buffer), "%s%s/%s",
               host->event_service_prefix, &name_buffer[1], ds->ds[index].name);
  } else {
    if (host->event_service_prefix == NULL)
      sstrncpy(service_buffer, &name_buffer[1], sizeof(service_buffer));
    else
      snprintf(service_buffer, sizeof(service_buffer), "%s%s",
               host->event_service_prefix, &name_buffer[1]);
  }

  riemann_event_set(
      event, RIEMANN_EVENT_FIELD_HOST, vl->host, RIEMANN_EVENT_FIELD_TIME,
      (int64_t)CDTIME_T_TO_TIME_T(vl->time), RIEMANN_EVENT_FIELD_TTL,
      (float)CDTIME_T_TO_DOUBLE(vl->interval) * host->ttl_factor,
      RIEMANN_EVENT_FIELD_STRING_ATTRIBUTES, "plugin", vl->plugin, "type",
      vl->type, "ds_name", ds->ds[index].name, NULL,
      RIEMANN_EVENT_FIELD_SERVICE, service_buffer, RIEMANN_EVENT_FIELD_NONE);

#if RCC_VERSION_NUMBER >= 0x010A00
  riemann_event_set(event, RIEMANN_EVENT_FIELD_TIME_MICROS,
                    (int64_t)CDTIME_T_TO_US(vl->time));
#endif

  if (host->check_thresholds) {
    const char *state = NULL;

    switch (status) {
    case STATE_OKAY:
      state = "ok";
      break;
    case STATE_ERROR:
      state = "critical";
      break;
    case STATE_WARNING:
      state = "warning";
      break;
    case STATE_MISSING:
      state = "unknown";
      break;
    }
    if (state)
      riemann_event_set(event, RIEMANN_EVENT_FIELD_STATE, state,
                        RIEMANN_EVENT_FIELD_NONE);
  }

  if (vl->plugin_instance[0] != 0)
    riemann_event_string_attribute_add(event, "plugin_instance",
                                       vl->plugin_instance);
  if (vl->type_instance[0] != 0)
    riemann_event_string_attribute_add(event, "type_instance",
                                       vl->type_instance);

  if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL)) {
    char ds_type[DATA_MAX_NAME_LEN];

    snprintf(ds_type, sizeof(ds_type), "%s:rate",
             DS_TYPE_TO_STRING(ds->ds[index].type));
    riemann_event_string_attribute_add(event, "ds_type", ds_type);
  } else {
    riemann_event_string_attribute_add(event, "ds_type",
                                       DS_TYPE_TO_STRING(ds->ds[index].type));
  }

  {
    char ds_index[DATA_MAX_NAME_LEN];

    snprintf(ds_index, sizeof(ds_index), "%" PRIsz, index);
    riemann_event_string_attribute_add(event, "ds_index", ds_index);
  }

  for (i = 0; i < riemann_attrs_num; i += 2)
    riemann_event_string_attribute_add(event, riemann_attrs[i],
                                       riemann_attrs[i + 1]);

  for (i = 0; i < riemann_tags_num; i++)
    riemann_event_tag_add(event, riemann_tags[i]);

  if (ds->ds[index].type == DS_TYPE_GAUGE) {
    riemann_event_set(event, RIEMANN_EVENT_FIELD_METRIC_D,
                      (double)vl->values[index].gauge,
                      RIEMANN_EVENT_FIELD_NONE);
  } else if (rates != NULL) {
    riemann_event_set(event, RIEMANN_EVENT_FIELD_METRIC_D, (double)rates[index],
                      RIEMANN_EVENT_FIELD_NONE);
  } else {
    int64_t metric;

    if (ds->ds[index].type == DS_TYPE_DERIVE)
      metric = (int64_t)vl->values[index].derive;
    else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
      metric = (int64_t)vl->values[index].absolute;
    else
      metric = (int64_t)vl->values[index].counter;

    riemann_event_set(event, RIEMANN_EVENT_FIELD_METRIC_S64, (int64_t)metric,
                      RIEMANN_EVENT_FIELD_NONE);
  }

  DEBUG("write_riemann plugin: Successfully created message for metric: "
        "host = \"%s\", service = \"%s\"",
        event->host, event->service);
  return event;
} /* }}} riemann_event_t *wrr_value_to_event */
Пример #2
0
bool
WebpOutput::open (const std::string &name, const ImageSpec &spec,
                 OpenMode mode)
{
    if (mode != Create) {
        error ("%s does not support subimages or MIP levels", format_name());
        return false;
    }

    // saving 'name' and 'spec' for later use
    m_filename = name;
    m_spec = spec;

    if (m_spec.nchannels != 3 && m_spec.nchannels != 4) {
        error ("%s does not support %d-channel images\n",
               format_name(), m_spec.nchannels);
        return false;
    }

    m_file = Filesystem::fopen (m_filename, "wb");
    if (!m_file) {
        error ("Unable to open file \"%s\"", m_filename.c_str ());
        return false;
    }

    if (!WebPPictureInit(&m_webp_picture))
    {
        error("Couldn't initialize WebPPicture\n");
        close();
        return false;
    }

    m_webp_picture.width = m_spec.width;
    m_webp_picture.height = m_spec.height;
    m_webp_picture.writer = WebpImageWriter;
    m_webp_picture.custom_ptr = (void*)m_file;

    if (!WebPConfigInit(&m_webp_config))
    {
        error("Couldn't initialize WebPPicture\n");
        close();
        return false;
    }

    m_webp_config.method = 6;
    int compression_quality = 100;
    const ParamValue *qual = m_spec.find_attribute ("CompressionQuality",
                                                          TypeDesc::INT);
    if (qual)
    {
        compression_quality = *static_cast<const int*>(qual->data());
    }
    m_webp_config.quality = compression_quality;
    
    // forcing UINT8 format
    m_spec.set_format (TypeDesc::UINT8);
    m_dither = m_spec.get_int_attribute ("oiio:dither", 0);

    m_scanline_size = m_spec.width * m_spec.nchannels;
    const int image_buffer = m_spec.height * m_scanline_size;
    m_uncompressed_image.resize(image_buffer, 0);
    return true;
}
Пример #3
0
bool
TIFFOutput::open (const std::string &name, const ImageSpec &userspec,
                  OpenMode mode)
{
    if (mode == AppendMIPLevel) {
        error ("%s does not support MIP levels", format_name());
        return false;
    }

    close ();  // Close any already-opened file
    m_spec = userspec;  // Stash the spec

    // Check for things this format doesn't support
    if (m_spec.width < 1 || m_spec.height < 1) {
        error ("Image resolution must be at least 1x1, you asked for %d x %d",
               m_spec.width, m_spec.height);
        return false;
    }
    if (m_spec.depth < 1)
        m_spec.depth = 1;

    // Open the file
#ifdef _WIN32
    std::wstring wname = Strutil::utf8_to_utf16 (name);
    m_tif = TIFFOpenW (wname.c_str(), mode == AppendSubimage ? "a" : "w");
#else
    m_tif = TIFFOpen (name.c_str(), mode == AppendSubimage ? "a" : "w");
#endif
    if (! m_tif) {
        error ("Can't open \"%s\" for output.", name.c_str());
        return false;
    }

    TIFFSetField (m_tif, TIFFTAG_XPOSITION, (float)m_spec.x);
    TIFFSetField (m_tif, TIFFTAG_YPOSITION, (float)m_spec.y);
    TIFFSetField (m_tif, TIFFTAG_IMAGEWIDTH, m_spec.width);
    TIFFSetField (m_tif, TIFFTAG_IMAGELENGTH, m_spec.height);
    if ((m_spec.full_width != 0 || m_spec.full_height != 0) &&
        (m_spec.full_width != m_spec.width || m_spec.full_height != m_spec.height)) {
        TIFFSetField (m_tif, TIFFTAG_PIXAR_IMAGEFULLWIDTH, m_spec.full_width);
        TIFFSetField (m_tif, TIFFTAG_PIXAR_IMAGEFULLLENGTH, m_spec.full_height);
    }
    if (m_spec.tile_width) {
        TIFFSetField (m_tif, TIFFTAG_TILEWIDTH, m_spec.tile_width);
        TIFFSetField (m_tif, TIFFTAG_TILELENGTH, m_spec.tile_height);
    } else {
        // Scanline images must set rowsperstrip
        TIFFSetField (m_tif, TIFFTAG_ROWSPERSTRIP, 32);
    }
    TIFFSetField (m_tif, TIFFTAG_SAMPLESPERPIXEL, m_spec.nchannels);
    int orientation = m_spec.get_int_attribute("Orientation", 1);
    TIFFSetField (m_tif, TIFFTAG_ORIENTATION, orientation);
    
    int bps, sampformat;
    switch (m_spec.format.basetype) {
    case TypeDesc::INT8:
        bps = 8;
        sampformat = SAMPLEFORMAT_INT;
        break;
    case TypeDesc::UINT8:
        bps = 8;
        sampformat = SAMPLEFORMAT_UINT;
        break;
    case TypeDesc::INT16:
        bps = 16;
        sampformat = SAMPLEFORMAT_INT;
        break;
    case TypeDesc::UINT16:
        bps = 16;
        sampformat = SAMPLEFORMAT_UINT;
        break;
    case TypeDesc::HALF:
        // Silently change requests for unsupported 'half' to 'float'
        m_spec.set_format (TypeDesc::FLOAT);
    case TypeDesc::FLOAT:
        bps = 32;
        sampformat = SAMPLEFORMAT_IEEEFP;
        break;
    case TypeDesc::DOUBLE:
        bps = 64;
        sampformat = SAMPLEFORMAT_IEEEFP;
        break;
    default:
        // Everything else, including UNKNOWN -- default to 8 bit
        bps = 8;
        sampformat = SAMPLEFORMAT_UINT;
        m_spec.set_format (TypeDesc::UINT8);
        break;
    }
    TIFFSetField (m_tif, TIFFTAG_BITSPERSAMPLE, bps);
    TIFFSetField (m_tif, TIFFTAG_SAMPLEFORMAT, sampformat);

    int photo = (m_spec.nchannels > 1 ? PHOTOMETRIC_RGB : PHOTOMETRIC_MINISBLACK);
    TIFFSetField (m_tif, TIFFTAG_PHOTOMETRIC, photo);

    // ExtraSamples tag
    if (m_spec.nchannels > 3) {
        bool unass = m_spec.get_int_attribute("oiio:UnassociatedAlpha", 0);
        short e = m_spec.nchannels-3;
        std::vector<unsigned short> extra (e);
        for (int c = 0;  c < e;  ++c) {
            if (m_spec.alpha_channel == (c+3))
                extra[c] = unass ? EXTRASAMPLE_UNASSALPHA : EXTRASAMPLE_ASSOCALPHA;
            else
                extra[c] = EXTRASAMPLE_UNSPECIFIED;
        }
        TIFFSetField (m_tif, TIFFTAG_EXTRASAMPLES, e, &extra[0]);
    }

    // Default to LZW compression if no request came with the user spec
    if (! m_spec.find_attribute("compression"))
        m_spec.attribute ("compression", "lzw");

    ImageIOParameter *param;
    const char *str = NULL;

    // Did the user request separate planar configuration?
    m_planarconfig = PLANARCONFIG_CONTIG;
    if ((param = m_spec.find_attribute("planarconfig", TypeDesc::STRING)) ||
        (param = m_spec.find_attribute("tiff:planarconfig", TypeDesc::STRING))) {
        str = *(char **)param->data();
        if (str && Strutil::iequals (str, "separate")) {
            m_planarconfig = PLANARCONFIG_SEPARATE;
            if (! m_spec.tile_width) {
                // I can only seem to make separate planarconfig work when
                // rowsperstrip is 1.
                TIFFSetField (m_tif, TIFFTAG_ROWSPERSTRIP, 1);
            }
        }
    }
    TIFFSetField (m_tif, TIFFTAG_PLANARCONFIG, m_planarconfig);

    // Automatically set date field if the client didn't supply it.
    if (! m_spec.find_attribute("DateTime")) {
        time_t now;
        time (&now);
        struct tm mytm;
        Sysutil::get_local_time (&now, &mytm);
        std::string date = Strutil::format ("%4d:%02d:%02d %2d:%02d:%02d",
                               mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
                               mytm.tm_hour, mytm.tm_min, mytm.tm_sec);
        m_spec.attribute ("DateTime", date);
    }

    if (Strutil::iequals (m_spec.get_string_attribute ("oiio:ColorSpace"), "sRGB"))
        m_spec.attribute ("Exif:ColorSpace", 1);

    // Deal with all other params
    for (size_t p = 0;  p < m_spec.extra_attribs.size();  ++p)
        put_parameter (m_spec.extra_attribs[p].name().string(),
                       m_spec.extra_attribs[p].type(),
                       m_spec.extra_attribs[p].data());

    std::vector<char> iptc;
    encode_iptc_iim (m_spec, iptc);
    if (iptc.size()) {
        iptc.resize ((iptc.size()+3) & (0xffff-3));  // round up
        TIFFSetField (m_tif, TIFFTAG_RICHTIFFIPTC, iptc.size()/4, &iptc[0]);
    }

    std::string xmp = encode_xmp (m_spec, true);
    if (! xmp.empty())
        TIFFSetField (m_tif, TIFFTAG_XMLPACKET, xmp.size(), xmp.c_str());
    
    TIFFCheckpointDirectory (m_tif);  // Ensure the header is written early
    m_checkpointTimer.start(); // Initialize the to the fileopen time
    m_checkpointItems = 0; // Number of tiles or scanlines we've written
    
    return true;
}
Пример #4
0
static riemann_message_t *
wrr_notification_to_message(struct riemann_host *host, /* {{{ */
                            notification_t const *n) {
  riemann_message_t *msg;
  riemann_event_t *event;
  char service_buffer[6 * DATA_MAX_NAME_LEN];
  char const *severity;

  switch (n->severity) {
  case NOTIF_OKAY:
    severity = "ok";
    break;
  case NOTIF_WARNING:
    severity = "warning";
    break;
  case NOTIF_FAILURE:
    severity = "critical";
    break;
  default:
    severity = "unknown";
  }

  format_name(service_buffer, sizeof(service_buffer),
              /* host = */ "", n->plugin, n->plugin_instance, n->type,
              n->type_instance);

  event = riemann_event_create(
      RIEMANN_EVENT_FIELD_HOST, n->host, RIEMANN_EVENT_FIELD_TIME,
      (int64_t)CDTIME_T_TO_TIME_T(n->time), RIEMANN_EVENT_FIELD_TAGS,
      "notification", NULL, RIEMANN_EVENT_FIELD_STATE, severity,
      RIEMANN_EVENT_FIELD_SERVICE, &service_buffer[1],
      RIEMANN_EVENT_FIELD_NONE);

#if RCC_VERSION_NUMBER >= 0x010A00
  riemann_event_set(event, RIEMANN_EVENT_FIELD_TIME_MICROS,
                    (int64_t)CDTIME_T_TO_US(n->time));
#endif

  if (n->host[0] != 0)
    riemann_event_string_attribute_add(event, "host", n->host);
  if (n->plugin[0] != 0)
    riemann_event_string_attribute_add(event, "plugin", n->plugin);
  if (n->plugin_instance[0] != 0)
    riemann_event_string_attribute_add(event, "plugin_instance",
                                       n->plugin_instance);

  if (n->type[0] != 0)
    riemann_event_string_attribute_add(event, "type", n->type);
  if (n->type_instance[0] != 0)
    riemann_event_string_attribute_add(event, "type_instance",
                                       n->type_instance);

  for (size_t i = 0; i < riemann_attrs_num; i += 2)
    riemann_event_string_attribute_add(event, riemann_attrs[i],
                                       riemann_attrs[i + 1]);

  for (size_t i = 0; i < riemann_tags_num; i++)
    riemann_event_tag_add(event, riemann_tags[i]);

  if (n->message[0] != 0)
    riemann_event_string_attribute_add(event, "description", n->message);

  /* Pull in values from threshold and add extra attributes */
  for (notification_meta_t *meta = n->meta; meta != NULL; meta = meta->next) {
    if (strcasecmp("CurrentValue", meta->name) == 0 &&
        meta->type == NM_TYPE_DOUBLE) {
      riemann_event_set(event, RIEMANN_EVENT_FIELD_METRIC_D,
                        (double)meta->nm_value.nm_double,
                        RIEMANN_EVENT_FIELD_NONE);
      continue;
    }

    if (meta->type == NM_TYPE_STRING) {
      riemann_event_string_attribute_add(event, meta->name,
                                         meta->nm_value.nm_string);
      continue;
    }
  }

  msg = riemann_message_create_with_events(event, NULL);
  if (msg == NULL) {
    ERROR("write_riemann plugin: riemann_message_create_with_events() failed.");
    riemann_event_free(event);
    return NULL;
  }

  DEBUG("write_riemann plugin: Successfully created message for notification: "
        "host = \"%s\", service = \"%s\", state = \"%s\"",
        event->host, event->service, event->state);
  return msg;
} /* }}} riemann_message_t *wrr_notification_to_message */
Пример #5
0
bool
ZfileOutput::open (const std::string &name, const ImageSpec &userspec,
                   OpenMode mode)
{
    if (mode != Create) {
        error ("%s does not support subimages or MIP levels", format_name());
        return false;
    }

    close ();  // Close any already-opened file
    m_gz = 0;
    m_file = NULL;
    m_spec = userspec;  // Stash the spec

    // Check for things this format doesn't support
    if (m_spec.width < 1 || m_spec.height < 1) {
        error ("Image resolution must be at least 1x1, you asked for %d x %d",
               m_spec.width, m_spec.height);
        return false;
    }
    if (m_spec.depth < 1)
        m_spec.depth = 1;
    if (m_spec.depth > 1) {
        error ("%s does not support volume images (depth > 1)", format_name());
        return false;
    }

    if (m_spec.nchannels != 1) {
        error ("Zfile only supports 1 channel, not %d", m_spec.nchannels);
        return false;
    }

    // Force float
    if (m_spec.format != TypeDesc::FLOAT)
        m_spec.format = TypeDesc::FLOAT;

    ZfileHeader header;
    header.magic = zfile_magic;
    header.width = (int)m_spec.width;
    header.height = (int)m_spec.height;

    ParamValue *p;
    static float ident[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
    if ((p = m_spec.find_attribute ("worldtocamera", TypeDesc::TypeMatrix)))
        memcpy (header.worldtocamera, p->data(), 16*sizeof(float));
    else
        memcpy (header.worldtocamera, ident, 16*sizeof(float));
    if ((p = m_spec.find_attribute ("worldtoscreen", TypeDesc::TypeMatrix)))
        memcpy (header.worldtoscreen, p->data(), 16*sizeof(float));
    else
        memcpy (header.worldtoscreen, ident, 16*sizeof(float));

    if (m_spec.get_string_attribute ("compression", "none") != std::string("none")) {
        FILE *fd = Filesystem::fopen (name, "wb");
        if (fd) {
            m_gz = gzdopen (fileno (fd), "wb");
            if (!m_gz)
                fclose (fd);
        }
    }
    else
        m_file = Filesystem::fopen (name, "wb");
    if (! m_file  &&  ! m_gz) {
        error ("Could not open file \"%s\"", name.c_str());
        return false;
    }

    if (m_gz)
        gzwrite (m_gz, &header, sizeof(header));
    else {
    	size_t b = fwrite (&header, sizeof(header), 1, m_file);
    	if (b != 1) {
            error ("Failed write zfile::open (err: %d)", b);
            return false;
    	}
    }

    // If user asked for tiles -- which this format doesn't support, emulate
    // it by buffering the whole image.this form
    if (m_spec.tile_width && m_spec.tile_height)
        m_tilebuffer.resize (m_spec.image_bytes());

    return true;
}
Пример #6
0
	void Person::firstname(const std::string &s) {
		std::string ss = format_name(s);
		this->set_string(DomainConstants::FIRSTNAME, ss);
	}
Пример #7
0
OIIO_PLUGIN_EXPORTS_END


bool
HdrOutput::open (const std::string &name, const ImageSpec &newspec,
                 OpenMode mode)
{
    if (mode != Create) {
        error ("%s does not support subimages or MIP levels", format_name());
        return false;
    }

    // Save spec for later use
    m_spec = newspec;
    // HDR always behaves like floating point
    m_spec.set_format (TypeDesc::FLOAT);

    // Check for things HDR can't support
    if (m_spec.nchannels != 3) {
        error ("HDR can only support 3-channel images");
        return false;
    }
    if (m_spec.width < 1 || m_spec.height < 1) {
        error ("Image resolution must be at least 1x1, you asked for %d x %d",
               m_spec.width, m_spec.height);
        return false;
    }
    if (m_spec.depth < 1)
        m_spec.depth = 1;
    if (m_spec.depth > 1) {
        error ("%s does not support volume images (depth > 1)", format_name());
        return false;
    }

    m_spec.set_format (TypeDesc::FLOAT);   // Native rgbe is float32 only

    m_fd = Filesystem::fopen (name, "wb");
    if (m_fd == NULL) {
        error ("Unable to open file");
        return false;
    }

    rgbe_header_info h;
    h.valid = 0;

    // Most readers seem to think that rgbe files are valid only if they
    // identify themselves as from "RADIANCE".
    h.valid |= RGBE_VALID_PROGRAMTYPE;
    Strutil::safe_strcpy (h.programtype, "RADIANCE", sizeof(h.programtype));

    ImageIOParameter *p;
    p = m_spec.find_attribute ("Orientation", TypeDesc::INT);
    if (p) {
        h.valid |= RGBE_VALID_ORIENTATION;
        h.orientation = * (int *)p->data();
    }

    // FIXME -- should we do anything about gamma, exposure, software,
    // pixaspect, primaries?  (N.B. rgbe.c doesn't even handle most of them)

    int r = RGBE_WriteHeader (m_fd, m_spec.width, m_spec.height, &h, rgbe_error);
    if (r != RGBE_RETURN_SUCCESS)
        error ("%s", rgbe_error);

    return true;
}
Пример #8
0
    return status;
  }

  close(fd);
  return status;
} /* }}} int nagios_print */

static int nagios_notify(const notification_t *n, /* {{{ */
                         __attribute__((unused)) user_data_t *user_data) {
  char svc_description[4 * DATA_MAX_NAME_LEN];
  char buffer[4096];
  int code;
  int status;

  status = format_name(svc_description, (int)sizeof(svc_description),
                       /* host */ "", n->plugin, n->plugin_instance, n->type,
                       n->type_instance);
  if (status != 0) {
    ERROR("notify_nagios plugin: Formatting service name failed.");
    return status;
  }

  switch (n->severity) {
  case NOTIF_OKAY:
    code = NAGIOS_OK;
    break;
  case NOTIF_WARNING:
    code = NAGIOS_WARNING;
    break;
  case NOTIF_FAILURE:
    code = NAGIOS_CRITICAL;
Пример #9
0
bool
PNGOutput::open (const std::string &name, const ImageSpec &userspec,
                 OpenMode mode)
{
    if (mode != Create) {
        error ("%s does not support subimages or MIP levels", format_name());
        return false;
    }

    close ();  // Close any already-opened file
    m_spec = userspec;  // Stash the spec

    // If not uint8 or uint16, default to uint8
    if (m_spec.format != TypeDesc::UINT8 && m_spec.format != TypeDesc::UINT16)
        m_spec.set_format (TypeDesc::UINT8);

    m_file = Filesystem::fopen (name, "wb");
    if (! m_file) {
        error ("Could not open file \"%s\"", name.c_str());
        return false;
    }

    std::string s = PNG_pvt::create_write_struct (m_png, m_info,
                                                  m_color_type, m_spec);
    if (s.length ()) {
        close ();
        error ("%s", s.c_str ());
        return false;
    }

    png_init_io (m_png, m_file);
    png_set_compression_level (m_png, std::max (std::min (m_spec.get_int_attribute ("png:compressionLevel", 6/* medium speed vs size tradeoff */), Z_BEST_COMPRESSION), Z_NO_COMPRESSION));
    std::string compression = m_spec.get_string_attribute ("compression");
    if (compression.empty ()) {
        png_set_compression_strategy(m_png, Z_DEFAULT_STRATEGY);
    }
    else if (Strutil::iequals (compression, "default")) {
        png_set_compression_strategy(m_png, Z_DEFAULT_STRATEGY);
    }
    else if (Strutil::iequals (compression, "filtered")) {
        png_set_compression_strategy(m_png, Z_FILTERED);
    }
    else if (Strutil::iequals (compression, "huffman")) {
        png_set_compression_strategy(m_png, Z_HUFFMAN_ONLY);
    }
    else if (Strutil::iequals (compression, "rle")) {
        png_set_compression_strategy(m_png, Z_RLE);
    }
    else if (Strutil::iequals (compression, "fixed")) {
        png_set_compression_strategy(m_png, Z_FIXED);
    }
    else {
        png_set_compression_strategy(m_png, Z_DEFAULT_STRATEGY);
    }


    PNG_pvt::write_info (m_png, m_info, m_color_type, m_spec, m_pngtext,
                         m_convert_alpha, m_gamma);

    return true;
}
Пример #10
0
static pixman_bool_t
verify (int test_no,
        pixman_op_t op,
        pixman_image_t *source,
	pixman_image_t *mask,
        pixman_image_t *dest,
        pixman_image_t *orig_dest,
        int x, int y,
        int width, int height,
	pixman_bool_t component_alpha)
{
    pixel_checker_t dest_checker, src_checker, mask_checker;
    int i, j;

    pixel_checker_init (&src_checker, source->bits.format);
    pixel_checker_init (&dest_checker, dest->bits.format);
    pixel_checker_init (&mask_checker, mask->bits.format);

    assert (dest->bits.format == orig_dest->bits.format);

    for (j = y; j < y + height; ++j)
    {
        for (i = x; i < x + width; ++i)
        {
            color_t src_color, mask_color, orig_dest_color, result;
            uint32_t dest_pixel, orig_dest_pixel, src_pixel, mask_pixel;

            access (dest, i, j, &dest_pixel);

	    get_color (&src_checker,
		       source, i - x, j - y,
		       &src_color, &src_pixel);

	    get_color (&mask_checker,
		       mask, i - x, j - y,
		       &mask_color, &mask_pixel);

	    get_color (&dest_checker, 
		       orig_dest, i, j,
		       &orig_dest_color, &orig_dest_pixel);

	    do_composite (op, 
			  &src_color, &mask_color, &orig_dest_color,
			  &result, component_alpha);

            if (!pixel_checker_check (&dest_checker, dest_pixel, &result))
            {
                int a, r, g, b;

                printf ("--------- Test 0x%x failed ---------\n", test_no);
                
                printf ("   operator:         %s (%s alpha)\n", operator_name (op),
			component_alpha? "component" : "unified");
                printf ("   dest_x, dest_y:   %d %d\n", x, y);
                printf ("   width, height:    %d %d\n", width, height);
                printf ("   source:           format: %-14s  size: %2d x %2d\n",
                        format_name (source->bits.format),
			source->bits.width, source->bits.height);
                printf ("   mask:             format: %-14s  size: %2d x %2d\n",
                        format_name (mask->bits.format),
			mask->bits.width, mask->bits.height);
                printf ("   dest:             format: %-14s  size: %2d x %2d\n",
                        format_name (dest->bits.format),
			dest->bits.width, dest->bits.height);
                printf ("   -- Failed pixel: (%d, %d) --\n", i, j);
                printf ("   source ARGB:      %f  %f  %f  %f   (pixel: %x)\n",
                        src_color.a, src_color.r, src_color.g, src_color.b,
                        src_pixel);
                printf ("   mask ARGB:        %f  %f  %f  %f   (pixel: %x)\n",
                        mask_color.a, mask_color.r, mask_color.g, mask_color.b,
                        mask_pixel);
                printf ("   dest ARGB:        %f  %f  %f  %f   (pixel: %x)\n",
                        orig_dest_color.a, orig_dest_color.r, orig_dest_color.g, orig_dest_color.b,
                        orig_dest_pixel);
                printf ("   expected ARGB:    %f  %f  %f  %f\n",
                        result.a, result.r, result.g, result.b);

                pixel_checker_get_min (&dest_checker, &result, &a, &r, &g, &b);
                printf ("   min acceptable:   %8d  %8d  %8d  %8d\n", a, r, g, b);

                pixel_checker_split_pixel (&dest_checker, dest_pixel, &a, &r, &g, &b);
                printf ("   got:              %8d  %8d  %8d  %8d   (pixel: %x)\n", a, r, g, b, dest_pixel);
                
                pixel_checker_get_max (&dest_checker, &result, &a, &r, &g, &b);
                printf ("   max acceptable:   %8d  %8d  %8d  %8d\n", a, r, g, b);
		printf ("\n");
		printf ("    { %s,\n", operator_name (op));
		printf ("      PIXMAN_%s,\t0x%x,\n", format_name (source->bits.format), src_pixel);
		printf ("      PIXMAN_%s,\t0x%x,\n", format_name (mask->bits.format), mask_pixel);
		printf ("      PIXMAN_%s,\t0x%x\n", format_name (dest->bits.format), orig_dest_pixel);
		printf ("    },\n");
                return FALSE;
            }
        }
    }

    return TRUE;
}
Пример #11
0
bool
TIFFOutput::open (const std::string &name, const ImageSpec &userspec,
                  OpenMode mode)
{
    if (mode == AppendMIPLevel) {
        error ("%s does not support MIP levels", format_name());
        return false;
    }

    close ();  // Close any already-opened file
    m_spec = userspec;  // Stash the spec

    // Check for things this format doesn't support
    if (m_spec.width < 1 || m_spec.height < 1) {
        error ("Image resolution must be at least 1x1, you asked for %d x %d",
               m_spec.width, m_spec.height);
        return false;
    }
    if (m_spec.tile_width) {
       if (m_spec.tile_width  % 16 != 0 ||
           m_spec.tile_height % 16 != 0 ||
           m_spec.tile_height == 0) {
          error("Tile size must be a multiple of 16, you asked for %d x %d", m_spec.tile_width, m_spec.tile_height);
          return false;
       }
    }
    if (m_spec.depth < 1)
        m_spec.depth = 1;

    // Open the file
#ifdef _WIN32
    std::wstring wname = Strutil::utf8_to_utf16 (name);
    m_tif = TIFFOpenW (wname.c_str(), mode == AppendSubimage ? "a" : "w");
#else
    m_tif = TIFFOpen (name.c_str(), mode == AppendSubimage ? "a" : "w");
#endif
    if (! m_tif) {
        error ("Can't open \"%s\" for output.", name.c_str());
        return false;
    }

    // N.B. Clamp position at 0... TIFF is internally incapable of having
    // negative origin.
    TIFFSetField (m_tif, TIFFTAG_XPOSITION, (float)std::max (0, m_spec.x));
    TIFFSetField (m_tif, TIFFTAG_YPOSITION, (float)std::max (0, m_spec.y));

    TIFFSetField (m_tif, TIFFTAG_IMAGEWIDTH, m_spec.width);
    TIFFSetField (m_tif, TIFFTAG_IMAGELENGTH, m_spec.height);
    if ((m_spec.full_width != 0 || m_spec.full_height != 0) &&
        (m_spec.full_width != m_spec.width || m_spec.full_height != m_spec.height)) {
        TIFFSetField (m_tif, TIFFTAG_PIXAR_IMAGEFULLWIDTH, m_spec.full_width);
        TIFFSetField (m_tif, TIFFTAG_PIXAR_IMAGEFULLLENGTH, m_spec.full_height);
    }
    if (m_spec.tile_width) {
        TIFFSetField (m_tif, TIFFTAG_TILEWIDTH, m_spec.tile_width);
        TIFFSetField (m_tif, TIFFTAG_TILELENGTH, m_spec.tile_height);
    } else {
        // Scanline images must set rowsperstrip
        TIFFSetField (m_tif, TIFFTAG_ROWSPERSTRIP, 32);
    }
    TIFFSetField (m_tif, TIFFTAG_SAMPLESPERPIXEL, m_spec.nchannels);
    int orientation = m_spec.get_int_attribute("Orientation", 1);
    TIFFSetField (m_tif, TIFFTAG_ORIENTATION, orientation);
    
    m_bitspersample = m_spec.get_int_attribute ("oiio:BitsPerSample");
    int sampformat;
    switch (m_spec.format.basetype) {
    case TypeDesc::INT8:
        m_bitspersample = 8;
        sampformat = SAMPLEFORMAT_INT;
        break;
    case TypeDesc::UINT8:
        if (m_bitspersample != 2 && m_bitspersample != 4)
            m_bitspersample = 8;
        sampformat = SAMPLEFORMAT_UINT;
        break;
    case TypeDesc::INT16:
        m_bitspersample = 16;
        sampformat = SAMPLEFORMAT_INT;
        break;
    case TypeDesc::UINT16:
        if (m_bitspersample != 10 && m_bitspersample != 12)
            m_bitspersample = 16;
        sampformat = SAMPLEFORMAT_UINT;
        break;
    case TypeDesc::INT32:
        m_bitspersample = 32;
        sampformat = SAMPLEFORMAT_INT;
        break;
    case TypeDesc::UINT32:
        m_bitspersample = 32;
        sampformat = SAMPLEFORMAT_UINT;
        break;
    case TypeDesc::HALF:
#if 0
        // Adobe extension, see http://chriscox.org/TIFFTN3d1.pdf
        // Unfortunately, Nuke 9.0, and probably many other apps we care
        // about, cannot read 16 bit float TIFFs correctly. Revisit this
        // again in future releases. (comment added Feb 2015)
        m_bitspersample = 16;
        sampformat = SAMPLEFORMAT_IEEEFP;
        break;
#else
        // Silently change requests for unsupported 'half' to 'float'
        m_spec.set_format (TypeDesc::FLOAT);
#endif
    case TypeDesc::FLOAT:
        m_bitspersample = 32;
        sampformat = SAMPLEFORMAT_IEEEFP;
        break;
    case TypeDesc::DOUBLE:
        m_bitspersample = 64;
        sampformat = SAMPLEFORMAT_IEEEFP;
        break;
    default:
        // Everything else, including UNKNOWN -- default to 8 bit
        m_bitspersample = 8;
        sampformat = SAMPLEFORMAT_UINT;
        m_spec.set_format (TypeDesc::UINT8);
        break;
    }
    TIFFSetField (m_tif, TIFFTAG_BITSPERSAMPLE, m_bitspersample);
    TIFFSetField (m_tif, TIFFTAG_SAMPLEFORMAT, sampformat);

    m_photometric = (m_spec.nchannels > 1 ? PHOTOMETRIC_RGB : PHOTOMETRIC_MINISBLACK);

    string_view comp = m_spec.get_string_attribute("Compression", "zip");
    if (Strutil::iequals (comp, "jpeg") &&
        (m_spec.format != TypeDesc::UINT8 || m_spec.nchannels != 3)) {
        comp = "zip";   // can't use JPEG for anything but 3xUINT8
    }
    m_compression = tiff_compression_code (comp);
    TIFFSetField (m_tif, TIFFTAG_COMPRESSION, m_compression);

    // Use predictor when using compression
    if (m_compression == COMPRESSION_LZW || m_compression == COMPRESSION_ADOBE_DEFLATE) {
        if (m_spec.format == TypeDesc::FLOAT || m_spec.format == TypeDesc::DOUBLE || m_spec.format == TypeDesc::HALF) {
            TIFFSetField (m_tif, TIFFTAG_PREDICTOR, PREDICTOR_FLOATINGPOINT);
            // N.B. Very old versions of libtiff did not support this
            // predictor.  It's possible that certain apps can't read
            // floating point TIFFs with this set.  But since it's been
            // documented since 2005, let's take our chances.  Comment
            // out the above line if this is problematic.
        }
        else if (m_bitspersample == 8 || m_bitspersample == 16) {
            // predictors not supported for unusual bit depths (e.g. 10)
            TIFFSetField (m_tif, TIFFTAG_PREDICTOR, PREDICTOR_HORIZONTAL);
        }
    } else if (m_compression == COMPRESSION_JPEG) {
        TIFFSetField (m_tif, TIFFTAG_JPEGQUALITY,
                      m_spec.get_int_attribute("CompressionQuality", 95));
        TIFFSetField (m_tif, TIFFTAG_ROWSPERSTRIP, 64);
        m_spec.attribute ("tiff:RowsPerStrip", 64);
        if (m_photometric == PHOTOMETRIC_RGB) {
            // Compression works so much better when we ask the library to
            // auto-convert RGB to YCbCr.
            TIFFSetField (m_tif, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
            m_photometric = PHOTOMETRIC_YCBCR;
        }
    }
    m_outputchans = m_spec.nchannels;
    if (m_photometric == PHOTOMETRIC_RGB) {
        // There are a few ways in which we allow allow the user to specify
        // translation to different photometric types.
        string_view photo = m_spec.get_string_attribute("tiff:ColorSpace");
        if (Strutil::iequals (photo, "CMYK")) {
            // CMYK: force to 4 channel output, either uint8 or uint16
            m_photometric = PHOTOMETRIC_SEPARATED;
            m_outputchans = 4;
            TIFFSetField (m_tif, TIFFTAG_SAMPLESPERPIXEL, m_outputchans);
            if (m_spec.format != TypeDesc::UINT8 || m_spec.format != TypeDesc::UINT16) {
                m_spec.format = TypeDesc::UINT8;
                m_bitspersample = 8;
                TIFFSetField (m_tif, TIFFTAG_BITSPERSAMPLE, m_bitspersample);
                TIFFSetField (m_tif, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);
            }
        }
    }

    TIFFSetField (m_tif, TIFFTAG_PHOTOMETRIC, m_photometric);

    // ExtraSamples tag
    if (m_spec.nchannels > 3 && m_photometric != PHOTOMETRIC_SEPARATED) {
        bool unass = m_spec.get_int_attribute("oiio:UnassociatedAlpha", 0);
        short e = m_spec.nchannels-3;
        std::vector<unsigned short> extra (e);
        for (int c = 0;  c < e;  ++c) {
            if (m_spec.alpha_channel == (c+3))
                extra[c] = unass ? EXTRASAMPLE_UNASSALPHA : EXTRASAMPLE_ASSOCALPHA;
            else
                extra[c] = EXTRASAMPLE_UNSPECIFIED;
        }
        TIFFSetField (m_tif, TIFFTAG_EXTRASAMPLES, e, &extra[0]);
    }

    ImageIOParameter *param;
    const char *str = NULL;

    // Did the user request separate planar configuration?
    m_planarconfig = PLANARCONFIG_CONTIG;
    if ((param = m_spec.find_attribute("planarconfig", TypeDesc::STRING)) ||
        (param = m_spec.find_attribute("tiff:planarconfig", TypeDesc::STRING))) {
        str = *(char **)param->data();
        if (str && Strutil::iequals (str, "separate"))
            m_planarconfig = PLANARCONFIG_SEPARATE;
    }
    // Can't deal with the headache of separate image planes when using
    // bit packing, or CMYK. Just punt by forcing contig in those cases.
    if (m_bitspersample != spec().format.size()*8 ||
            m_photometric == PHOTOMETRIC_SEPARATED)
        m_planarconfig = PLANARCONFIG_CONTIG;
    if (m_planarconfig == PLANARCONFIG_SEPARATE) {
        if (! m_spec.tile_width) {
            // I can only seem to make separate planarconfig work when
            // rowsperstrip is 1.
            TIFFSetField (m_tif, TIFFTAG_ROWSPERSTRIP, 1);
        }
    }
    TIFFSetField (m_tif, TIFFTAG_PLANARCONFIG, m_planarconfig);

    // Automatically set date field if the client didn't supply it.
    if (! m_spec.find_attribute("DateTime")) {
        time_t now;
        time (&now);
        struct tm mytm;
        Sysutil::get_local_time (&now, &mytm);
        std::string date = Strutil::format ("%4d:%02d:%02d %2d:%02d:%02d",
                               mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
                               mytm.tm_hour, mytm.tm_min, mytm.tm_sec);
        m_spec.attribute ("DateTime", date);
    }

    // Write ICC profile, if we have anything
    const ImageIOParameter* icc_profile_parameter = m_spec.find_attribute(ICC_PROFILE_ATTR);
    if (icc_profile_parameter != NULL) {
        unsigned char *icc_profile = (unsigned char*)icc_profile_parameter->data();
        uint32 length = icc_profile_parameter->type().size();
        if (icc_profile && length)
            TIFFSetField (m_tif, TIFFTAG_ICCPROFILE, length, icc_profile);
    }

    if (Strutil::iequals (m_spec.get_string_attribute ("oiio:ColorSpace"), "sRGB"))
        m_spec.attribute ("Exif:ColorSpace", 1);

    // Deal with missing XResolution or YResolution, or a PixelAspectRatio
    // that contradicts them.
    float X_density = m_spec.get_float_attribute ("XResolution", 1.0f);
    float Y_density = m_spec.get_float_attribute ("YResolution", 1.0f);
    float aspect = m_spec.get_float_attribute ("PixelAspectRatio", 1.0f);
    if (X_density < 1.0f || Y_density < 1.0f || aspect*X_density != Y_density) {
        if (X_density < 1.0f || Y_density < 1.0f) {
            X_density = Y_density = 1.0f;
            m_spec.attribute ("ResolutionUnit", "none");
        }
        m_spec.attribute ("XResolution", X_density);
        m_spec.attribute ("YResolution", X_density * aspect);
    }

    // Deal with all other params
    for (size_t p = 0;  p < m_spec.extra_attribs.size();  ++p)
        put_parameter (m_spec.extra_attribs[p].name().string(),
                       m_spec.extra_attribs[p].type(),
                       m_spec.extra_attribs[p].data());

    std::vector<char> iptc;
    encode_iptc_iim (m_spec, iptc);
    if (iptc.size()) {
        iptc.resize ((iptc.size()+3) & (0xffff-3));  // round up
        TIFFSetField (m_tif, TIFFTAG_RICHTIFFIPTC, iptc.size()/4, &iptc[0]);
    }

    std::string xmp = encode_xmp (m_spec, true);
    if (! xmp.empty())
        TIFFSetField (m_tif, TIFFTAG_XMLPACKET, xmp.size(), xmp.c_str());
    
    TIFFCheckpointDirectory (m_tif);  // Ensure the header is written early
    m_checkpointTimer.start(); // Initialize the to the fileopen time
    m_checkpointItems = 0; // Number of tiles or scanlines we've written

    m_dither = (m_spec.format == TypeDesc::UINT8) ?
                    m_spec.get_int_attribute ("oiio:dither", 0) : 0;

    return true;
}
Пример #12
0
static pixman_bool_t
verify (int test_no, const pixel_combination_t *combination, int size)
{
    pixman_image_t *src, *dest;
    pixel_checker_t src_checker, dest_checker;
    color_t source_color, dest_color, reference_color;
    pixman_bool_t result = TRUE;
    int i, j;

    /* Compute reference color */
    pixel_checker_init (&src_checker, combination->src_format);
    pixel_checker_init (&dest_checker, combination->dest_format);
    pixel_checker_convert_pixel_to_color (
	&src_checker, combination->src_pixel, &source_color);
    pixel_checker_convert_pixel_to_color (
	&dest_checker, combination->dest_pixel, &dest_color);
    do_composite (combination->op,
		  &source_color, NULL, &dest_color,
		  &reference_color, FALSE);

    src = pixman_image_create_bits (
	combination->src_format, size, size, NULL, -1);
    dest = pixman_image_create_bits (
	combination->dest_format, size, size, NULL, -1);

    fill (src, combination->src_pixel);
    fill (dest, combination->dest_pixel);

    pixman_image_composite32 (
	combination->op, src, NULL, dest, 0, 0, 0, 0, 0, 0, size, size);

    for (j = 0; j < size; ++j)
    {
	for (i = 0; i < size; ++i)
	{
	    uint32_t computed = access (dest, i, j);
	    int32_t a, r, g, b;

	    if (!pixel_checker_check (&dest_checker, computed, &reference_color))
	    {
		printf ("----------- Test %d failed ----------\n", test_no);

		printf ("   operator:         %s\n", operator_name (combination->op));
		printf ("   src format:       %s\n", format_name (combination->src_format));
		printf ("   dest format:      %s\n", format_name (combination->dest_format));
                printf (" - source ARGB:      %f  %f  %f  %f   (pixel: %8x)\n",
                        source_color.a, source_color.r, source_color.g, source_color.b,
                        combination->src_pixel);
		pixel_checker_split_pixel (&src_checker, combination->src_pixel,
					   &a, &r, &g, &b);
                printf ("                     %8d  %8d  %8d  %8d\n", a, r, g, b);

                printf (" - dest ARGB:        %f  %f  %f  %f   (pixel: %8x)\n",
                        dest_color.a, dest_color.r, dest_color.g, dest_color.b,
                        combination->dest_pixel);
		pixel_checker_split_pixel (&dest_checker, combination->dest_pixel,
					   &a, &r, &g, &b);
                printf ("                     %8d  %8d  %8d  %8d\n", a, r, g, b);

                pixel_checker_split_pixel (&dest_checker, computed, &a, &r, &g, &b);
                printf (" - expected ARGB:    %f  %f  %f  %f\n",
                        reference_color.a, reference_color.r, reference_color.g, reference_color.b);

                pixel_checker_get_min (&dest_checker, &reference_color, &a, &r, &g, &b);
                printf ("   min acceptable:   %8d  %8d  %8d  %8d\n", a, r, g, b);

                pixel_checker_split_pixel (&dest_checker, computed, &a, &r, &g, &b);
                printf ("   got:              %8d  %8d  %8d  %8d   (pixel: %8x)\n", a, r, g, b, computed);

                pixel_checker_get_max (&dest_checker, &reference_color, &a, &r, &g, &b);
                printf ("   max acceptable:   %8d  %8d  %8d  %8d\n", a, r, g, b);

		result = FALSE;
		goto done;
	    }
	}
    }

done:
    pixman_image_unref (src);
    pixman_image_unref (dest);

    return result;
}
Пример #13
0
bool
PNGOutput::open(const std::string& name, const ImageSpec& userspec,
                OpenMode mode)
{
    if (mode != Create) {
        errorf("%s does not support subimages or MIP levels", format_name());
        return false;
    }

    close();            // Close any already-opened file
    m_spec = userspec;  // Stash the spec

    // If not uint8 or uint16, default to uint8
    if (m_spec.format != TypeDesc::UINT8 && m_spec.format != TypeDesc::UINT16)
        m_spec.set_format(TypeDesc::UINT8);

    // See if we were requested to write to a memory buffer, and if so,
    // extract the pointer.
    auto ioparam = m_spec.find_attribute("oiio:ioproxy", TypeDesc::PTR);
    m_io         = ioparam ? ioparam->get<Filesystem::IOProxy*>() : nullptr;
    if (!m_io) {
        // If no proxy was supplied, create a file writer
        m_io = new Filesystem::IOFile(name, Filesystem::IOProxy::Mode::Write);
        m_local_io.reset(m_io);
    }
    if (!m_io || m_io->mode() != Filesystem::IOProxy::Mode::Write) {
        errorf("Could not open \"%s\"", name);
        return false;
    }

    std::string s = PNG_pvt::create_write_struct(m_png, m_info, m_color_type,
                                                 m_spec);
    if (s.length()) {
        close();
        errorf("%s", s);
        return false;
    }

    png_set_write_fn(m_png, this, PngWriteCallback, PngFlushCallback);

    png_set_compression_level(
        m_png, std::max(std::min(m_spec.get_int_attribute(
                                     "png:compressionLevel",
                                     6 /* medium speed vs size tradeoff */),
                                 Z_BEST_COMPRESSION),
                        Z_NO_COMPRESSION));
    std::string compression = m_spec.get_string_attribute("compression");
    if (compression.empty()) {
        png_set_compression_strategy(m_png, Z_DEFAULT_STRATEGY);
    } else if (Strutil::iequals(compression, "default")) {
        png_set_compression_strategy(m_png, Z_DEFAULT_STRATEGY);
    } else if (Strutil::iequals(compression, "filtered")) {
        png_set_compression_strategy(m_png, Z_FILTERED);
    } else if (Strutil::iequals(compression, "huffman")) {
        png_set_compression_strategy(m_png, Z_HUFFMAN_ONLY);
    } else if (Strutil::iequals(compression, "rle")) {
        png_set_compression_strategy(m_png, Z_RLE);
    } else if (Strutil::iequals(compression, "fixed")) {
        png_set_compression_strategy(m_png, Z_FIXED);
    } else {
        png_set_compression_strategy(m_png, Z_DEFAULT_STRATEGY);
    }

    PNG_pvt::write_info(m_png, m_info, m_color_type, m_spec, m_pngtext,
                        m_convert_alpha, m_gamma);

    m_dither = (m_spec.format == TypeDesc::UINT8)
                   ? m_spec.get_int_attribute("oiio:dither", 0)
                   : 0;

    m_convert_alpha = m_spec.alpha_channel != -1
                      && !m_spec.get_int_attribute("oiio:UnassociatedAlpha", 0);

    // If user asked for tiles -- which this format doesn't support, emulate
    // it by buffering the whole image.
    if (m_spec.tile_width && m_spec.tile_height)
        m_tilebuffer.resize(m_spec.image_bytes());

    return true;
}
Пример #14
0
static Msg *riemann_notification_to_protobuf (struct riemann_host *host, /* {{{ */
        notification_t const *n)
{
    Msg *msg;
    Event *event;
    char service_buffer[6 * DATA_MAX_NAME_LEN];
    char const *severity;
    notification_meta_t *meta;
    int i;

    msg = malloc (sizeof (*msg));
    if (msg == NULL)
    {
        ERROR ("write_riemann plugin: malloc failed.");
        return (NULL);
    }
    memset (msg, 0, sizeof (*msg));
    msg__init (msg);

    msg->events = malloc (sizeof (*msg->events));
    if (msg->events == NULL)
    {
        ERROR ("write_riemann plugin: malloc failed.");
        sfree (msg);
        return (NULL);
    }

    event = malloc (sizeof (*event));
    if (event == NULL)
    {
        ERROR ("write_riemann plugin: malloc failed.");
        sfree (msg->events);
        sfree (msg);
        return (NULL);
    }
    memset (event, 0, sizeof (*event));
    event__init (event);

    msg->events[0] = event;
    msg->n_events = 1;

    event->host = strdup (n->host);
    event->time = CDTIME_T_TO_TIME_T (n->time);
    event->has_time = 1;

    switch (n->severity)
    {
    case NOTIF_OKAY:
        severity = "ok";
        break;
    case NOTIF_WARNING:
        severity = "warning";
        break;
    case NOTIF_FAILURE:
        severity = "critical";
        break;
    default:
        severity = "unknown";
    }
    event->state = strdup (severity);

    riemann_event_add_tag (event, "notification");
    if (n->host[0] != 0)
        riemann_event_add_attribute (event, "host", n->host);
    if (n->plugin[0] != 0)
        riemann_event_add_attribute (event, "plugin", n->plugin);
    if (n->plugin_instance[0] != 0)
        riemann_event_add_attribute (event, "plugin_instance",
                                     n->plugin_instance);

    if (n->type[0] != 0)
        riemann_event_add_attribute (event, "type", n->type);
    if (n->type_instance[0] != 0)
        riemann_event_add_attribute (event, "type_instance",
                                     n->type_instance);

    for (i = 0; i < riemann_attrs_num; i += 2)
        riemann_event_add_attribute(event,
                                    riemann_attrs[i],
                                    riemann_attrs[i +1]);

    for (i = 0; i < riemann_tags_num; i++)
        riemann_event_add_tag (event, riemann_tags[i]);

    format_name (service_buffer, sizeof (service_buffer),
                 /* host = */ "", n->plugin, n->plugin_instance,
                 n->type, n->type_instance);
    event->service = strdup (&service_buffer[1]);

    if (n->message[0] != 0)
        riemann_event_add_attribute (event, "description", n->message);

    /* Pull in values from threshold and add extra attributes */
    for (meta = n->meta; meta != NULL; meta = meta->next)
    {
        if (strcasecmp ("CurrentValue", meta->name) == 0 && meta->type == NM_TYPE_DOUBLE)
        {
            event->metric_d = meta->nm_value.nm_double;
            event->has_metric_d = 1;
            continue;
        }

        if (meta->type == NM_TYPE_STRING) {
            riemann_event_add_attribute (event, meta->name, meta->nm_value.nm_string);
            continue;
        }
    }

    DEBUG ("write_riemann plugin: Successfully created protobuf for notification: "
           "host = \"%s\", service = \"%s\", state = \"%s\"",
           event->host, event->service, event->state);
    return (msg);
} /* }}} Msg *riemann_notification_to_protobuf */
Пример #15
0
/*
 * int ut_threshold_add
 *
 * Adds a threshold configuration to the list of thresholds. The threshold_t
 * structure is copied and may be destroyed after this call. Returns zero on
 * success, non-zero otherwise.
 */
static int ut_threshold_add (const threshold_t *th)
{ /* {{{ */
  char name[6 * DATA_MAX_NAME_LEN];
  char *name_copy;
  threshold_t *th_copy;
  threshold_t *th_ptr;
  int status = 0;

  if (format_name (name, sizeof (name), th->host,
	th->plugin, th->plugin_instance,
	th->type, th->type_instance) != 0)
  {
    ERROR ("ut_threshold_add: format_name failed.");
    return (-1);
  }

  name_copy = strdup (name);
  if (name_copy == NULL)
  {
    ERROR ("ut_threshold_add: strdup failed.");
    return (-1);
  }

  th_copy = malloc (sizeof (*th_copy));
  if (th_copy == NULL)
  {
    sfree (name_copy);
    ERROR ("ut_threshold_add: malloc failed.");
    return (-1);
  }
  memcpy (th_copy, th, sizeof (threshold_t));

  DEBUG ("ut_threshold_add: Adding entry `%s'", name);

  pthread_mutex_lock (&threshold_lock);

  th_ptr = threshold_get (th->host, th->plugin, th->plugin_instance,
      th->type, th->type_instance);

  while ((th_ptr != NULL) && (th_ptr->next != NULL))
    th_ptr = th_ptr->next;

  if (th_ptr == NULL) /* no such threshold yet */
  {
    status = c_avl_insert (threshold_tree, name_copy, th_copy);
  }
  else /* th_ptr points to the last threshold in the list */
  {
    th_ptr->next = th_copy;
    /* name_copy isn't needed */
    sfree (name_copy);
  }

  pthread_mutex_unlock (&threshold_lock);

  if (status != 0)
  {
    ERROR ("ut_threshold_add: c_avl_insert (%s) failed.", name);
    sfree (name_copy);
    sfree (th_copy);
  }

  return (status);
} /* }}} int ut_threshold_add */
Пример #16
0
static Event *riemann_value_to_protobuf (struct riemann_host const *host, /* {{{ */
        data_set_t const *ds,
        value_list_t const *vl, size_t index,
        gauge_t const *rates)
{
    Event *event;
    char name_buffer[5 * DATA_MAX_NAME_LEN];
    char service_buffer[6 * DATA_MAX_NAME_LEN];
    double ttl;
    int i;

    event = malloc (sizeof (*event));
    if (event == NULL)
    {
        ERROR ("write_riemann plugin: malloc failed.");
        return (NULL);
    }
    memset (event, 0, sizeof (*event));
    event__init (event);

    event->host = strdup (vl->host);
    event->time = CDTIME_T_TO_TIME_T (vl->time);
    event->has_time = 1;

    ttl = CDTIME_T_TO_DOUBLE (vl->interval) * host->ttl_factor;
    event->ttl = (float) ttl;
    event->has_ttl = 1;

    riemann_event_add_attribute (event, "plugin", vl->plugin);
    if (vl->plugin_instance[0] != 0)
        riemann_event_add_attribute (event, "plugin_instance",
                                     vl->plugin_instance);

    riemann_event_add_attribute (event, "type", vl->type);
    if (vl->type_instance[0] != 0)
        riemann_event_add_attribute (event, "type_instance",
                                     vl->type_instance);

    if ((ds->ds[index].type != DS_TYPE_GAUGE) && (rates != NULL))
    {
        char ds_type[DATA_MAX_NAME_LEN];

        ssnprintf (ds_type, sizeof (ds_type), "%s:rate",
                   DS_TYPE_TO_STRING(ds->ds[index].type));
        riemann_event_add_attribute (event, "ds_type", ds_type);
    }
    else
    {
        riemann_event_add_attribute (event, "ds_type",
                                     DS_TYPE_TO_STRING(ds->ds[index].type));
    }
    riemann_event_add_attribute (event, "ds_name", ds->ds[index].name);
    {
        char ds_index[DATA_MAX_NAME_LEN];

        ssnprintf (ds_index, sizeof (ds_index), "%zu", index);
        riemann_event_add_attribute (event, "ds_index", ds_index);
    }

    for (i = 0; i < riemann_attrs_num; i += 2)
        riemann_event_add_attribute(event,
                                    riemann_attrs[i],
                                    riemann_attrs[i +1]);

    for (i = 0; i < riemann_tags_num; i++)
        riemann_event_add_tag (event, riemann_tags[i]);

    if (ds->ds[index].type == DS_TYPE_GAUGE)
    {
        event->has_metric_d = 1;
        event->metric_d = (double) vl->values[index].gauge;
    }
    else if (rates != NULL)
    {
        event->has_metric_d = 1;
        event->metric_d = (double) rates[index];
    }
    else
    {
        event->has_metric_sint64 = 1;
        if (ds->ds[index].type == DS_TYPE_DERIVE)
            event->metric_sint64 = (int64_t) vl->values[index].derive;
        else if (ds->ds[index].type == DS_TYPE_ABSOLUTE)
            event->metric_sint64 = (int64_t) vl->values[index].absolute;
        else
            event->metric_sint64 = (int64_t) vl->values[index].counter;
    }

    format_name (name_buffer, sizeof (name_buffer),
                 /* host = */ "", vl->plugin, vl->plugin_instance,
                 vl->type, vl->type_instance);
    if (host->always_append_ds || (ds->ds_num > 1))
        ssnprintf (service_buffer, sizeof (service_buffer),
                   "%s/%s", &name_buffer[1], ds->ds[index].name);
    else
        sstrncpy (service_buffer, &name_buffer[1],
                  sizeof (service_buffer));

    event->service = strdup (service_buffer);

    DEBUG ("write_riemann plugin: Successfully created protobuf for metric: "
           "host = \"%s\", service = \"%s\"",
           event->host, event->service);
    return (event);
} /* }}} Event *riemann_value_to_protobuf */
Пример #17
0
bool
OpenEXROutput::open (const std::string &name, const ImageSpec &userspec,
                     OpenMode mode)
{
    if (mode == AppendSubimage) {
        error ("%s does not support subimages", format_name());
        return false;
    }

    if (mode == AppendMIPLevel && (m_output_scanline || m_output_tiled)) {
        // Special case for appending to an open file -- we don't need
        // to close and reopen
        if (m_spec.tile_width && m_levelmode != Imf::ONE_LEVEL) {
            // OpenEXR does not support differing tile sizes on different
            // MIP-map levels.  Reject the open() if not using the original
            // tile sizes.
            if (userspec.tile_width != m_spec.tile_width ||
                userspec.tile_height != m_spec.tile_height) {
                error ("OpenEXR tiles must have the same size on all MIPmap levels");
                return false;
            }
            // Copy the new mip level size.  Keep everything else from the
            // original level.
            m_spec.width = userspec.width;
            m_spec.height = userspec.height;
            // N.B. do we need to copy anything else from userspec?
            ++m_miplevel;
            return true;
        }
    }

    m_spec = userspec;  // Stash the spec

    if (m_spec.width < 1 || m_spec.height < 1) {
        error ("Image resolution must be at least 1x1, you asked for %d x %d",
               userspec.width, userspec.height);
        return false;
    }
    if (m_spec.depth < 1)
        m_spec.depth = 1;
    if (m_spec.depth > 1) {
        error ("%s does not support volume images (depth > 1)", format_name());
        return false;
    }

    if (m_spec.full_width <= 0)
        m_spec.full_width = m_spec.width;
    if (m_spec.full_height <= 0)
        m_spec.full_height = m_spec.height;

    // Force use of one of the three data types that OpenEXR supports
    switch (m_spec.format.basetype) {
    case TypeDesc::UINT:
        m_spec.format = TypeDesc::UINT;
        break;
    case TypeDesc::FLOAT:
    case TypeDesc::DOUBLE:
        m_spec.format = TypeDesc::FLOAT;
        break;
    default:
        // Everything else defaults to half
        m_spec.format = TypeDesc::HALF;
    }

    Imath::Box2i dataWindow (Imath::V2i (m_spec.x, m_spec.y),
                             Imath::V2i (m_spec.width + m_spec.x - 1,
                                         m_spec.height + m_spec.y - 1));
    Imath::Box2i displayWindow (Imath::V2i (m_spec.full_x, m_spec.full_y),
                                Imath::V2i (m_spec.full_width+m_spec.full_x-1,
                                            m_spec.full_height+m_spec.full_y-1));
    m_header = new Imf::Header (displayWindow, dataWindow);

    // Insert channels into the header.  Also give the channels names if
    // the user botched it.
    static const char *default_chan_names[] = { "R", "G", "B", "A" };
    m_spec.channelnames.resize (m_spec.nchannels);
    for (int c = 0;  c < m_spec.nchannels;  ++c) {
        if (m_spec.channelnames[c].empty())
            m_spec.channelnames[c] = (c<4) ? default_chan_names[c]
                                           : Strutil::format ("unknown %d", c);
        TypeDesc format = m_spec.channelformats.size() ?
                                  m_spec.channelformats[c] : m_spec.format;
        Imf::PixelType ptype;
        switch (format.basetype) {
        case TypeDesc::UINT:
            ptype = Imf::UINT;
            format = TypeDesc::UINT;
            break;
        case TypeDesc::FLOAT:
        case TypeDesc::DOUBLE:
            ptype = Imf::FLOAT;
            format = TypeDesc::FLOAT;
            break;
        default:
            // Everything else defaults to half
            ptype = Imf::HALF;
            format = TypeDesc::HALF;
        }
        
#ifdef OPENEXR_VERSION_IS_1_6_OR_LATER
        // Hint to lossy compression methods that indicates whether
        // human perception of the quantity represented by this channel
        // is closer to linear or closer to logarithmic.  Compression
        // methods may optimize image quality by adjusting pixel data
        // quantization acording to this hint.
        
        bool pLinear = Strutil::iequals (m_spec.get_string_attribute ("oiio:ColorSpace", "Linear"), "Linear");
#endif
        m_pixeltype.push_back (ptype);
        if (m_spec.channelformats.size())
            m_spec.channelformats[c] = format;
        m_header->channels().insert (m_spec.channelnames[c].c_str(),
                                     Imf::Channel(ptype, 1, 1
#ifdef OPENEXR_VERSION_IS_1_6_OR_LATER
                                     , pLinear
#endif
                                     ));
    }
    ASSERT (m_pixeltype.size() == (size_t)m_spec.nchannels);

    // Default to ZIP compression if no request came with the user spec.
    if (! m_spec.find_attribute("compression"))
        m_spec.attribute ("compression", "zip");

    // Default to increasingY line order, same as EXR.
    if (! m_spec.find_attribute("openexr:lineOrder"))
        m_spec.attribute ("openexr:lineOrder", "increasingY");

    // Automatically set date field if the client didn't supply it.
    if (! m_spec.find_attribute("DateTime")) {
        time_t now;
        time (&now);
        struct tm mytm;
        Sysutil::get_local_time (&now, &mytm);
        std::string date = Strutil::format ("%4d:%02d:%02d %2d:%02d:%02d",
                               mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
                               mytm.tm_hour, mytm.tm_min, mytm.tm_sec);
        m_spec.attribute ("DateTime", date);
    }

    m_nsubimages = 1;
    m_subimage = 0;
    m_nmiplevels = 1;
    m_miplevel = 0;

    // Figure out if we are a mipmap or an environment map
    ImageIOParameter *param = m_spec.find_attribute ("textureformat");
    const char *textureformat = param ? *(char **)param->data() : NULL;
    m_levelmode = Imf::ONE_LEVEL;  // Default to no MIP-mapping
    m_roundingmode = m_spec.get_int_attribute ("openexr:roundingmode",
                                               Imf::ROUND_DOWN);

    if (textureformat) {
        if (Strutil::iequals (textureformat, "Plain Texture")) {
            m_levelmode = m_spec.get_int_attribute ("openexr:levelmode",
                                                    Imf::MIPMAP_LEVELS);
        } else if (Strutil::iequals (textureformat, "CubeFace Environment")) {
            m_levelmode = m_spec.get_int_attribute ("openexr:levelmode",
                                                    Imf::MIPMAP_LEVELS);
            m_header->insert ("envmap", Imf::EnvmapAttribute(Imf::ENVMAP_CUBE));
        } else if (Strutil::iequals (textureformat, "LatLong Environment")) {
            m_levelmode = m_spec.get_int_attribute ("openexr:levelmode",
                                                    Imf::MIPMAP_LEVELS);
            m_header->insert ("envmap", Imf::EnvmapAttribute(Imf::ENVMAP_LATLONG));
        } else if (Strutil::iequals (textureformat, "Shadow")) {
            m_levelmode = Imf::ONE_LEVEL;  // Force one level for shadow maps
        }

        if (m_levelmode == Imf::MIPMAP_LEVELS) {
            // Compute how many mip levels there will be
            int w = m_spec.width;
            int h = m_spec.height;
            while (w > 1 && h > 1) {
                if (m_roundingmode == Imf::ROUND_DOWN) {
                    w = w / 2;
                    h = h / 2;
                } else {
                    w = (w + 1) / 2;
                    h = (h + 1) / 2;
                }
                w = std::max (1, w);
                h = std::max (1, h);
                ++m_nmiplevels;
            }
        }
    }

    // Deal with all other params
    for (size_t p = 0;  p < m_spec.extra_attribs.size();  ++p)
        put_parameter (m_spec.extra_attribs[p].name().string(),
                       m_spec.extra_attribs[p].type(),
                       m_spec.extra_attribs[p].data());

    try {
        m_output_stream = new OpenEXROutputStream (name.c_str());

        if (m_spec.tile_width) {
            m_header->setTileDescription (
                Imf::TileDescription (m_spec.tile_width, m_spec.tile_height,
                                      Imf::LevelMode(m_levelmode),
                                      Imf::LevelRoundingMode(m_roundingmode)));
            m_output_tiled = new Imf::TiledOutputFile (*m_output_stream, *m_header);
        } else {
            m_output_scanline = new Imf::OutputFile (*m_output_stream, *m_header);
        }
    }
    catch (const std::exception &e) {
        delete m_output_stream;
        m_output_stream = NULL;

        error ("OpenEXR exception: %s", e.what());
        m_output_scanline = NULL;
        return false;
    }
    if (! m_output_scanline && ! m_output_tiled) {
        error ("Unknown error opening EXR file");
        return false;
    }

    return true;
}