<commit_before>/*
 * (C) Copyright 2015 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */

#include "DotGraph.hpp"
#include <string.h>

namespace kurento
{

static std::string
debug_dump_get_element_state (GstElement *element)
{
  static std::string state_icons[] = {"[~]", "[0]", "[-]", "[=]", "[>]"};

  GstState state = GST_STATE_VOID_PENDING;
  GstState pending = GST_STATE_VOID_PENDING;

  gst_element_get_state (element, &state, &pending, 0);

  if (pending == GST_STATE_VOID_PENDING) {
    gboolean is_locked = gst_element_is_locked_state (element);

    return "\\n" + state_icons[state] + (is_locked ? "(locked)" : "");
  } else {
    return "\\n" + state_icons[state] + " -> " + state_icons[pending];
  }
}

static std::string
debug_dump_get_element_params (GstElement *element)
{
  std::string params;
  GParamSpec **properties;
  GValue value = { 0, };
  guint number_of_properties;

  /* get paramspecs and show non-default properties */
  properties =
    g_object_class_list_properties (G_OBJECT_CLASS (GST_ELEMENT_GET_CLASS
                                    (element) ), &number_of_properties);

  if (properties) {
    guint i;

    for (i = 0; i < number_of_properties; i++) {
      GParamSpec *property;

      property = properties[i];

      if (! (property->flags & G_PARAM_READABLE) ) {
        continue;
      }

      if (!strcmp (property->name, "name") ) {
        continue;
      }

      g_value_init (&value, property->value_type);
      g_object_get_property (G_OBJECT (element), property->name, &value);

      if (! (g_param_value_defaults (property, &value) ) ) {
        gchar *tmp, *value_str;

        tmp = g_strdup_value_contents (&value);
        value_str = g_strescape (tmp, NULL);
        g_free (tmp);

        params += "\\n" + std::string (property->name) + "=" + std::string (value_str);
        g_free (value_str);
      }

      g_value_unset (&value);
    }

    g_free (properties);
  }

  return params;
}

static std::string
debug_dump_make_object_name (GstObject *obj)
{
  gchar *c_str = g_strcanon (g_strdup_printf ("%s_%p", GST_OBJECT_NAME (obj),
                             obj),
                             G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_", '_');
  std::string ret (c_str);

  g_free (c_str);

  return ret;
}

static std::string
debug_dump_pad (GstPad *pad, const std::string &colorName,
                const std::string &elementName, GstDebugGraphDetails details,
                const std::string &indentStr)
{
  std::string ret;
  GstPadTemplate *pad_templ;
  GstPadPresence presence;
  std::string padName;
  std::string styleName;

  padName = debug_dump_make_object_name (GST_OBJECT (pad) );

  /* pad availability */
  styleName = "filled,solid";

  if ( (pad_templ = gst_pad_get_pad_template (pad) ) ) {
    presence = GST_PAD_TEMPLATE_PRESENCE (pad_templ);
    gst_object_unref (pad_templ);

    if (presence == GST_PAD_SOMETIMES) {
      styleName = "filled,dotted";
    } else if (presence == GST_PAD_REQUEST) {
      styleName = "filled,dashed";
    }
  }

  if (details & GST_DEBUG_GRAPH_SHOW_STATES) {
    static std::string activationMode[] = {"-", ">", "<" };
    std::string padFlags;
    std::string taskMode;
    GstTask *task;

    GST_OBJECT_LOCK (pad);
    task = GST_PAD_TASK (pad);

    if (task) {
      switch (gst_task_get_state (task) ) {
      case GST_TASK_STARTED:
        taskMode = "[T]";
        break;

      case GST_TASK_PAUSED:
        taskMode = "[t]";
        break;

      default:
        /* Invalid task state, ignoring */
        break;
      }
    }

    GST_OBJECT_UNLOCK (pad);

    /* check if pad flags */
    padFlags.append (GST_OBJECT_FLAG_IS_SET (pad,
                     GST_PAD_FLAG_BLOCKED) ? "B" : "b");
    padFlags.append (GST_OBJECT_FLAG_IS_SET (pad,
                     GST_PAD_FLAG_FLUSHING) ? "F" : "f");
    padFlags.append (GST_OBJECT_FLAG_IS_SET (pad,
                     GST_PAD_FLAG_BLOCKING) ? "B" : "b");

    ret += indentStr + "  " + elementName + "_" + padName +
           " [color=black, fillcolor=\"" + colorName + "\", label=\"" + std::string (
             GST_OBJECT_NAME (pad) ) + "\\n[" + activationMode[pad->mode] + "][" + padFlags +
           "]" + taskMode + "\", height=\"0.2\", style=\"" + styleName + "\"];\n";
  } else {
    ret += indentStr + "  " + elementName + "_" + padName +
           " [color=black, fillcolor=\"" + colorName + "\", label=\"" + std::string (
             GST_OBJECT_NAME (pad) ) + "\", height=\"0.2\", style=\"" + styleName + "\"];\n";
  }

  return ret;
}

static std::string
debug_dump_element_pad (GstPad *pad, GstElement *element,
                        GstDebugGraphDetails details, const gint indent)
{
  std::string ret;

  GstElement *target_element;
  GstPad *target_pad, *tmp_pad;
  GstPadDirection dir;
  std::string elementName;
  std::string targetElementName;
  std::string colorName;
  std::string indentStr (indent * 2, ' ');

  dir = gst_pad_get_direction (pad);
  elementName = debug_dump_make_object_name (GST_OBJECT (element) );

  if (GST_IS_GHOST_PAD (pad) ) {
    colorName =
      (dir == GST_PAD_SRC) ? "#ffdddd" : ( (dir ==
                                            GST_PAD_SINK) ? "#ddddff" : "#ffffff");

    /* output target-pad so that it belongs to this element */
    if ( (tmp_pad = gst_ghost_pad_get_target (GST_GHOST_PAD (pad) ) ) ) {
      if ( (target_pad = gst_pad_get_peer (tmp_pad) ) ) {
        std::string padName;
        std::string targetPadName;

        if ( (target_element = gst_pad_get_parent_element (target_pad) ) ) {
          targetElementName =
            debug_dump_make_object_name (GST_OBJECT (target_element) );
        }

        ret += debug_dump_pad (target_pad, colorName, targetElementName, details,
                               indentStr);
        /* src ghostpad relationship */
        padName = debug_dump_make_object_name (GST_OBJECT (pad) );
        targetPadName = debug_dump_make_object_name (GST_OBJECT (target_pad) );

        if (dir == GST_PAD_SRC) {
          ret += indentStr + targetElementName + "_" + targetPadName + " -> " +
                 elementName + "_" + padName + " [style=dashed, minlen=0]\n";
        } else {
          ret += indentStr + elementName + "_" + padName + " -> " + targetElementName +
                 "_" + targetPadName + " [style=dashed, minlen=0]\n";
        }

        if (target_element) {
          gst_object_unref (target_element);
        }

        gst_object_unref (target_pad);
      }

      gst_object_unref (tmp_pad);
    }
  } else {
    colorName =
      (dir == GST_PAD_SRC) ? "#ffaaaa" : ( (dir ==
                                            GST_PAD_SINK) ? "#aaaaff" : "#cccccc");
  }

  /* pads */
  ret += debug_dump_pad (pad, colorName, elementName, details, indentStr);

  return ret;
}

static std::string
debug_dump_element_pads (GstIterator *pad_iter, GstPad *pad,
                         GstElement *element, GstDebugGraphDetails details, const gint indent,
                         guint *src_pads, guint *sink_pads)
{
  GValue item = { 0, };
  gboolean pads_done;
  GstPadDirection dir;
  std::string ret;

  pads_done = FALSE;

  while (!pads_done) {
    switch (gst_iterator_next (pad_iter, &item) ) {
    case GST_ITERATOR_OK:
      pad = GST_PAD (g_value_get_object (&item) );
      ret += debug_dump_element_pad (pad, element, details, indent);
      dir = gst_pad_get_direction (pad);

      if (dir == GST_PAD_SRC) {
        (*src_pads)++;
      } else if (dir == GST_PAD_SINK) {
        (*sink_pads)++;
      }

      g_value_reset (&item);
      break;

    case GST_ITERATOR_RESYNC:
      gst_iterator_resync (pad_iter);
      break;

    case GST_ITERATOR_ERROR:
    case GST_ITERATOR_DONE:
      pads_done = TRUE;
      break;
    }
  }

  return ret;
}

static gboolean
string_append_field (GQuark field, const GValue *value, gpointer ptr)
{
  std::string *str = (std::string *) ptr;
  gchar *value_str = gst_value_serialize (value);
  gchar *esc_value_str;

  if (value_str == NULL) {
    gchar *c_tmp = g_strdup_printf ("  %18s: NULL\\l", g_quark_to_string (field) );
    std::string tmp (c_tmp);
    g_free (c_tmp);
    str->append (tmp);
    return TRUE;
  }

  /* some enums can become really long */
  if (strlen (value_str) > 25) {
    gint pos = 24;

    /* truncate */
    value_str[25] = '\0';

    /* mirror any brackets and quotes */
    if (value_str[0] == '<') {
      value_str[pos--] = '>';
    }

    if (value_str[0] == '[') {
      value_str[pos--] = ']';
    }

    if (value_str[0] == '(') {
      value_str[pos--] = ')';
    }

    if (value_str[0] == '{') {
      value_str[pos--] = '}';
    }

    if (value_str[0] == '"') {
      value_str[pos--] = '"';
    }

    if (pos != 24) {
      value_str[pos--] = ' ';
    }

    /* elippsize */
    value_str[pos--] = '.';
    value_str[pos--] = '.';
    value_str[pos--] = '.';
  }

  esc_value_str = g_strescape (value_str, NULL);

  gchar *c_tmp = g_strdup_printf ("  %18s: %s\\l", g_quark_to_string (field),
                                  esc_value_str);

  std::string tmp (c_tmp);
  g_free (c_tmp);

  str->append (tmp);

  g_free (value_str);
  g_free (esc_value_str);
  return TRUE;
}

static std::string
debug_dump_describe_caps (GstCaps *caps, GstDebugGraphDetails details)
{
  std::string media;

  if (details & GST_DEBUG_GRAPH_SHOW_CAPS_DETAILS) {

    if (gst_caps_is_any (caps) || gst_caps_is_empty (caps) ) {
      gchar *tmp = gst_caps_to_string (caps);

      media = tmp;
      g_free (tmp);

    } else {
      std::string str;

      for (guint i = 0; i < gst_caps_get_size (caps); i++) {
        GstStructure *structure = gst_caps_get_structure (caps, i);

        str.append (gst_structure_get_name (structure) );
        str.append ("\\l");

        gst_structure_foreach (structure, string_append_field, (gpointer) &str);
      }

      media = str;
    }

  } else {
    if (GST_CAPS_IS_SIMPLE (caps) ) {
      media = gst_structure_get_name (gst_caps_get_structure (caps, 0) );
    } else {
      media = "*";
    }
  }

  return media;
}

static std::string
debug_dump_element_pad_link (GstPad *pad, GstElement *element,
                             GstDebugGraphDetails details, const std::string &indentStr)
{
  std::string ret;
  GstElement *peer_element;
  GstPad *peer_pad;
  GstCaps *caps, *peer_caps;
  std::string media;
  std::string mediaSrc;
  std::string mediaSink;
  std::string padName;
  std::string elementName;
  std::string peerPadName;
  std::string peerElementName;

  if ( (peer_pad = gst_pad_get_peer (pad) ) ) {
    if ( (details & GST_DEBUG_GRAPH_SHOW_MEDIA_TYPE) ||
         (details & GST_DEBUG_GRAPH_SHOW_CAPS_DETAILS)
       ) {
      caps = gst_pad_get_current_caps (pad);

      if (!caps) {
        caps = gst_pad_get_pad_template_caps (pad);
      }

      peer_caps = gst_pad_get_current_caps (peer_pad);

      if (!peer_caps) {
        peer_caps = gst_pad_get_pad_template_caps (peer_pad);
      }

      media = debug_dump_describe_caps (caps, details);

      /* check if peer caps are different */
      if (peer_caps && !gst_caps_is_equal (caps, peer_caps) ) {

        if (gst_pad_get_direction (pad) == GST_PAD_SRC) {
          mediaSrc = media;
          mediaSink = debug_dump_describe_caps (peer_caps, details);;
        } else {
          mediaSrc = debug_dump_describe_caps (peer_caps, details);;
          mediaSink = media;
        }

        media = "";
      }

      gst_caps_unref (peer_caps);
      gst_caps_unref (caps);
    }

    padName = debug_dump_make_object_name (GST_OBJECT (pad) );

    if (element) {
      elementName = debug_dump_make_object_name (GST_OBJECT (element) );
    }

    peerPadName = debug_dump_make_object_name (GST_OBJECT (peer_pad) );

    if ( (peer_element = gst_pad_get_parent_element (peer_pad) ) ) {
      peerElementName =
        debug_dump_make_object_name (GST_OBJECT (peer_element) );
    }

    /* pad link */
    ret += indentStr + elementName + "_" + padName + " -> " + peerElementName +
           "_" + peerPadName;

    if (!media.empty() ) {
      ret += " [label=\"" + media + "\"]\n";
    } else if (!mediaSrc.empty() && !mediaSink.empty() ) {
      /* dot has some issues with placement of head and taillabels,
       * we need an empty label to make space */
      ret += " [labeldistance=\"10\", labelangle=\"0\", "
             "label=\"                                                  \", "
             "taillabel=\"" + mediaSrc + "\", headlabel=\"" + mediaSink + "\"]\n";
    }

    if (peer_element) {
      gst_object_unref (peer_element);
    }

    gst_object_unref (peer_pad);
  }

  return ret;
}

static std::string
debug_dump_element (GstBin *bin, GstDebugGraphDetails details,
                    const gint indent)
{
  std::string ret;

  GstIterator *element_iter, *pad_iter;
  gboolean elements_done, pads_done;
  GValue item = { 0, };
  GValue item2 = { 0, };
  GstElement *element;
  GstPad *pad = NULL;
  guint src_pads, sink_pads;
  std::string elementName;
  std::string stateName;
  std::string params;
  std::string indentStr (indent * 2, ' ');

  element_iter = gst_bin_iterate_elements (bin);
  elements_done = FALSE;

  while (!elements_done) {
    switch (gst_iterator_next (element_iter, &item) ) {
    case GST_ITERATOR_OK:
      element = GST_ELEMENT (g_value_get_object (&item) );
      elementName = debug_dump_make_object_name (GST_OBJECT (element) );

      if (details & GST_DEBUG_GRAPH_SHOW_STATES) {
        stateName = debug_dump_get_element_state (GST_ELEMENT (element) );
      }

      if (details & GST_DEBUG_GRAPH_SHOW_NON_DEFAULT_PARAMS) {
        params = debug_dump_get_element_params (GST_ELEMENT (element) );
      }

      /* elements */
      ret += indentStr + "subgraph cluster_" + elementName + " {\n";
      ret += indentStr + "  fontname=\"Bitstream Vera Sans\";\n";
      ret += indentStr + "  fontsize=\"8\";\n";
      ret += indentStr + "  style=filled;\n";
      ret += indentStr + "  color=black;\n\n";
      ret += indentStr + "  label=\"" + std::string (G_OBJECT_TYPE_NAME (
               element) ) + "\\n" + std::string (GST_OBJECT_NAME (element) ) + stateName +
             params + "\";\n",

             src_pads = sink_pads = 0;

      if ( (pad_iter = gst_element_iterate_sink_pads (element) ) ) {
        ret += debug_dump_element_pads (pad_iter, pad, element, details, indent,
                                        &src_pads, &sink_pads);
        gst_iterator_free (pad_iter);
      }

      if ( (pad_iter = gst_element_iterate_src_pads (element) ) ) {
        ret += debug_dump_element_pads (pad_iter, pad, element, details, indent,
                                        &src_pads, &sink_pads);
        gst_iterator_free (pad_iter);
      }

      if (GST_IS_BIN (element) ) {
        ret += indentStr + "  fillcolor=\"#ffffff\";\n";
        /* recurse */
        ret += debug_dump_element (GST_BIN (element), details, indent + 1);
      } else {
        if (src_pads && !sink_pads) {
          ret += indentStr + "  fillcolor=\"#ffaaaa\";\n";
        } else if (!src_pads && sink_pads) {
          ret += indentStr + "  fillcolor=\"#aaaaff\";\n";
        } else if (src_pads && sink_pads) {
          ret += indentStr + "  fillcolor=\"#aaffaa\";\n";
        } else {
          ret += indentStr + "  fillcolor=\"#ffffff\";\n";
        }
      }

      ret += indentStr + "}\n\n";

      if ( (pad_iter = gst_element_iterate_pads (element) ) ) {
        pads_done = FALSE;

        while (!pads_done) {
          switch (gst_iterator_next (pad_iter, &item2) ) {
          case GST_ITERATOR_OK:
            pad = GST_PAD (g_value_get_object (&item2) );

            if (gst_pad_is_linked (pad) ) {
              if (gst_pad_get_direction (pad) == GST_PAD_SRC) {
                ret += debug_dump_element_pad_link (pad, element, details, indentStr);
              } else {
                GstPad *peer_pad = gst_pad_get_peer (pad);

                if (peer_pad) {
                  if (!GST_IS_GHOST_PAD (peer_pad)
                      && GST_IS_PROXY_PAD (peer_pad) ) {
                    ret += debug_dump_element_pad_link (peer_pad, NULL, details, indentStr);
                  }

                  gst_object_unref (peer_pad);
                }
              }
            }

            g_value_reset (&item2);
            break;

          case GST_ITERATOR_RESYNC:
            gst_iterator_resync (pad_iter);
            break;

          case GST_ITERATOR_ERROR:
          case GST_ITERATOR_DONE:
            pads_done = TRUE;
            break;
          }
        }

        g_value_unset (&item2);
        gst_iterator_free (pad_iter);
      }

      g_value_reset (&item);
      break;

    case GST_ITERATOR_RESYNC:
      gst_iterator_resync (element_iter);
      break;

    case GST_ITERATOR_ERROR:
    case GST_ITERATOR_DONE:
      elements_done = TRUE;
      break;
    }
  }

  g_value_unset (&item);
  gst_iterator_free (element_iter);

  return ret;
}

std::string
generateDotGraph (GstBin *bin, GstDebugGraphDetails details)
{
  std::string retString;

  g_return_val_if_fail (GST_IS_BIN (bin), "");

  std::string stateName;
  std::string params;

  if (details & GST_DEBUG_GRAPH_SHOW_STATES) {
    stateName = debug_dump_get_element_state (GST_ELEMENT (bin) );
  }

  if (details & GST_DEBUG_GRAPH_SHOW_NON_DEFAULT_PARAMS) {
    params = debug_dump_get_element_params (GST_ELEMENT (bin) );
  }

  /* write header */
  retString = (
                "digraph pipeline {\n"
                "  rankdir=LR;\n"
                "  fontname=\"sans\";\n"
                "  fontsize=\"10\";\n"
                "  labelloc=t;\n"
                "  nodesep=.1;\n"
                "  ranksep=.2;\n"
                "  label=\"<" + std::string (G_OBJECT_TYPE_NAME (bin) ) + ">\\n" + std::string (
                  GST_OBJECT_NAME (bin) ) + stateName + params + "\";\n"
                "  node [style=filled, shape=box, fontsize=\"9\", fontname=\"sans\", margin=\"0.0,0.0\"];\n"
                "  edge [labelfontsize=\"6\", fontsize=\"9\", fontname=\"monospace\"];\n"
                "  \n"
                "  legend [\n"
                "    pos=\"0,0!\",\n"
                "    margin=\"0.05,0.05\",\n"
                "    label=\"Legend\\lElement-States: [~] void-pending, [0] null, [-] ready, [=] paused, [>] playing\\lPad-Activation: [-] none, [>] push, [<] pull\\lPad-Flags: [b]locked, [f]lushing, [b]locking; upper-case is set\\lPad-Task: [T] has started task, [t] has paused task\\l\"\n"
                "  ];"
                "\n");

  retString += debug_dump_element (bin, details, 1);

  /* write footer */
  retString += "}\n";

  return retString;
}

} /* kurento */
<commit_msg>DotGraph: Use gstreamer utility to generate dot graph<commit_after>/*
 * (C) Copyright 2015 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */

#include "DotGraph.hpp"
#include <string.h>

namespace kurento
{

std::string
generateDotGraph (GstBin *bin, GstDebugGraphDetails details)
{
  std::string retString;
  gchar *data = gst_debug_bin_to_dot_data (bin, details);

  retString = std::string (data);
  g_free (data);

  return retString;
}

} /* kurento */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: signaturestate.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-21 16:45:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SFX2_SIGNATURESTATE_HXX
#define SFX2_SIGNATURESTATE_HXX

// xmlsec05, check with SFX team
#define SIGNATURESTATE_UNKNOWN                  (sal_Int16)(-1)
#define SIGNATURESTATE_NOSIGNATURES             (sal_Int16)0
#define SIGNATURESTATE_SIGNATURES_OK            (sal_Int16)1
#define SIGNATURESTATE_SIGNATURES_BROKEN        (sal_Int16)2
#define SIGNATURESTATE_SIGNATURES_INVALID       (sal_Int16)3    // State was SIGNATURES_OK, but doc is modified now
#define SIGNATURESTATE_SIGNATURES_NOTVALIDATED  (sal_Int16)4    // signature is OK, but certificate could not be validated

#endif // SFX2_SIGNATURESTATE_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.118); FILE MERGED 2008/03/31 13:37:57 rt 1.2.118.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: signaturestate.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SFX2_SIGNATURESTATE_HXX
#define SFX2_SIGNATURESTATE_HXX

// xmlsec05, check with SFX team
#define SIGNATURESTATE_UNKNOWN                  (sal_Int16)(-1)
#define SIGNATURESTATE_NOSIGNATURES             (sal_Int16)0
#define SIGNATURESTATE_SIGNATURES_OK            (sal_Int16)1
#define SIGNATURESTATE_SIGNATURES_BROKEN        (sal_Int16)2
#define SIGNATURESTATE_SIGNATURES_INVALID       (sal_Int16)3    // State was SIGNATURES_OK, but doc is modified now
#define SIGNATURESTATE_SIGNATURES_NOTVALIDATED  (sal_Int16)4    // signature is OK, but certificate could not be validated

#endif // SFX2_SIGNATURESTATE_HXX
<|endoftext|>


<commit_before>#include "QtLocation/private/qgeocameracapabilities_p.h"
#include "qgeotiledmappingmanagerenginegooglemaps.h"
#include "qgeotiledmapgooglemaps.h"
#include "qgeotilefetchergooglemaps.h"
#include "QtLocation/private/qgeotilespec_p.h"
#if QT_VERSION < QT_VERSION_CHECK(5,6,0)
#include <QStandardPaths>
#include "QtLocation/private/qgeotilecache_p.h"
#else
#include "QtLocation/private/qgeofiletilecache_p.h"
#endif

#include <QDebug>
#include <QDir>
#include <QVariant>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonDocument>
#include <QtCore/qmath.h>
#include <QtCore/qstandardpaths.h>

QT_BEGIN_NAMESPACE

QGeoTiledMappingManagerEngineGooglemaps::QGeoTiledMappingManagerEngineGooglemaps(const QVariantMap &parameters,
    QGeoServiceProvider::Error *error,
    QString *errorString)
    : QGeoTiledMappingManagerEngine()
{
    Q_UNUSED(error);
    Q_UNUSED(errorString);

    QGeoCameraCapabilities capabilities;
    capabilities.setMinimumZoomLevel(0.0);
    capabilities.setMaximumZoomLevel(21.0);

    setCameraCapabilities(capabilities);

    int tile = parameters.value(QStringLiteral("googlemaps.maps.tilesize"), 256).toInt();

    setTileSize(QSize(tile, tile));

    QList<QGeoMapType> types;
#if QT_VERSION < QT_VERSION_CHECK(5,9,0)
    types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1);
    types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2);
    types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3);
    types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4);
#elif QT_VERSION < QT_VERSION_CHECK(5,10,0)
    types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1, "googlemaps");
    types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2, "googlemaps");
    types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3, "googlemaps");
    types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4, "googlemaps");
#else
    types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1, "googlemaps", capabilities, parameters);
    types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2, "googlemaps", capabilities, parameters);
    types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3, "googlemaps", capabilities, parameters);
    types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4, "googlemaps", capabilities, parameters);
#endif
    setSupportedMapTypes(types);

    QGeoTileFetcherGooglemaps *fetcher = new QGeoTileFetcherGooglemaps(parameters, this, tileSize());
    setTileFetcher(fetcher);

    if (parameters.contains(QStringLiteral("googlemaps.cachefolder")))
        m_cacheDirectory = parameters.value(QStringLiteral("googlemaps.cachefolder")).toString().toLatin1();

    const int szCache = 100 * 1024 * 1024;
#if QT_VERSION < QT_VERSION_CHECK(5,6,0)
    if (m_cacheDirectory.isEmpty())
        m_cacheDirectory = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QLatin1String("googlemaps");
    QGeoTileCache *tileCache = createTileCacheWithDir(m_cacheDirectory);
    if (tileCache)
        tileCache->setMaxDiskUsage(szCache);
#else
    if (m_cacheDirectory.isEmpty())
        m_cacheDirectory = QAbstractGeoTileCache::baseCacheDirectory() + QLatin1String("googlemaps");
    QAbstractGeoTileCache *tileCache = new QGeoFileTileCache(m_cacheDirectory);
    tileCache->setMaxDiskUsage(szCache);
    setTileCache(tileCache);
#endif

    *error = QGeoServiceProvider::NoError;
    errorString->clear();
}

QGeoTiledMappingManagerEngineGooglemaps::~QGeoTiledMappingManagerEngineGooglemaps()
{
}

QGeoMap *QGeoTiledMappingManagerEngineGooglemaps::createMap()
{
    return new QGeoTiledMapGooglemaps(this);
}

QT_END_NAMESPACE

<commit_msg>Fix map tile cache not working on windows for non ASCII cachefolder<commit_after>#include "QtLocation/private/qgeocameracapabilities_p.h"
#include "qgeotiledmappingmanagerenginegooglemaps.h"
#include "qgeotiledmapgooglemaps.h"
#include "qgeotilefetchergooglemaps.h"
#include "QtLocation/private/qgeotilespec_p.h"
#if QT_VERSION < QT_VERSION_CHECK(5,6,0)
#include <QStandardPaths>
#include "QtLocation/private/qgeotilecache_p.h"
#else
#include "QtLocation/private/qgeofiletilecache_p.h"
#endif

#include <QDebug>
#include <QDir>
#include <QVariant>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonDocument>
#include <QtCore/qmath.h>
#include <QtCore/qstandardpaths.h>

QT_BEGIN_NAMESPACE

QGeoTiledMappingManagerEngineGooglemaps::QGeoTiledMappingManagerEngineGooglemaps(const QVariantMap &parameters,
    QGeoServiceProvider::Error *error,
    QString *errorString)
    : QGeoTiledMappingManagerEngine()
{
    Q_UNUSED(error);
    Q_UNUSED(errorString);

    QGeoCameraCapabilities capabilities;
    capabilities.setMinimumZoomLevel(0.0);
    capabilities.setMaximumZoomLevel(21.0);

    setCameraCapabilities(capabilities);

    int tile = parameters.value(QStringLiteral("googlemaps.maps.tilesize"), 256).toInt();

    setTileSize(QSize(tile, tile));

    QList<QGeoMapType> types;
#if QT_VERSION < QT_VERSION_CHECK(5,9,0)
    types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1);
    types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2);
    types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3);
    types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4);
#elif QT_VERSION < QT_VERSION_CHECK(5,10,0)
    types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1, "googlemaps");
    types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2, "googlemaps");
    types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3, "googlemaps");
    types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4, "googlemaps");
#else
    types << QGeoMapType(QGeoMapType::StreetMap, tr("Road Map"), tr("Normal map view in daylight mode"), false, false, 1, "googlemaps", capabilities, parameters);
    types << QGeoMapType(QGeoMapType::SatelliteMapDay, tr("Satellite"), tr("Satellite map view in daylight mode"), false, false, 2, "googlemaps", capabilities, parameters);
    types << QGeoMapType(QGeoMapType::TerrainMap, tr("Terrain"), tr("Terrain map view in daylight mode"), false, false, 3, "googlemaps", capabilities, parameters);
    types << QGeoMapType(QGeoMapType::HybridMap, tr("Hybrid"), tr("Satellite map view with streets in daylight mode"), false, false, 4, "googlemaps", capabilities, parameters);
#endif
    setSupportedMapTypes(types);

    QGeoTileFetcherGooglemaps *fetcher = new QGeoTileFetcherGooglemaps(parameters, this, tileSize());
    setTileFetcher(fetcher);

    if (parameters.contains(QStringLiteral("googlemaps.cachefolder")))
        m_cacheDirectory = parameters.value(QStringLiteral("googlemaps.cachefolder")).toString();

    const int szCache = 100 * 1024 * 1024;
#if QT_VERSION < QT_VERSION_CHECK(5,6,0)
    if (m_cacheDirectory.isEmpty())
        m_cacheDirectory = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QLatin1String("googlemaps");
    QGeoTileCache *tileCache = createTileCacheWithDir(m_cacheDirectory);
    if (tileCache)
        tileCache->setMaxDiskUsage(szCache);
#else
    if (m_cacheDirectory.isEmpty())
        m_cacheDirectory = QAbstractGeoTileCache::baseCacheDirectory() + QLatin1String("googlemaps");
    QAbstractGeoTileCache *tileCache = new QGeoFileTileCache(m_cacheDirectory);
    tileCache->setMaxDiskUsage(szCache);
    setTileCache(tileCache);
#endif

    *error = QGeoServiceProvider::NoError;
    errorString->clear();
}

QGeoTiledMappingManagerEngineGooglemaps::~QGeoTiledMappingManagerEngineGooglemaps()
{
}

QGeoMap *QGeoTiledMappingManagerEngineGooglemaps::createMap()
{
    return new QGeoTiledMapGooglemaps(this);
}

QT_END_NAMESPACE

<|endoftext|>


<commit_before>/*
** Copyright 2011 Merethis
**
** This file is part of Centreon Clib.
**
** Centreon Clib is free software: you can redistribute it
** and/or modify it under the terms of the GNU Affero General Public
** License as published by the Free Software Foundation, either version
** 3 of the License, or (at your option) any later version.
**
** Centreon Clib 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
** Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public
** License along with Centreon Clib. If not, see
** <http://www.gnu.org/licenses/>.
*/

#ifndef CC_EXCEPTIONS_BASIC_HH
#  define CC_EXCEPTIONS_BASIC_HH

#  include <exception>
#  include <string>
#  include "com/centreon/namespace.hh"
#  include "com/centreon/misc/stringifier.hh"

CC_BEGIN()

namespace               exceptions {
  /**
   *  @class basic basic.hh "com/centreon/exceptions/basic.hh"
   *  @brief Base exception class.
   *
   *  Simple exception class containing an basic error message.
   */
  class                 basic : public std::exception {
  public:
                        basic() throw();
                        basic(
                          char const* file,
                          char const* function,
                          int line) throw ();
                        basic(basic const& right) throw ();
    virtual             ~basic() throw ();
    virtual basic&      operator=(basic const& right) throw ();
    template<typename T>
    basic&              operator<<(T t) throw () {
      _buffer << t;
      return (*this);
    }
    virtual char const* what() const throw ();

  private:
    basic&              _internal_copy(basic const& right);

    misc::stringifier   _buffer;
  };
}

CC_END()

#  ifdef __GNUC__
#    define FUNCTION __PRETTY_FUNCTION__
#  else
#    define FUNCTION __func__
#  endif

#  ifndef NDEBUG
#    define basic_error() com::centreon::exceptions::basic( \
                          __FILE__,                        \
                          FUNCTION,                        \
                          __LINE__)
#  else
#    define basic_error() com::centreon::exceptions::basic()
#  endif // !NDEBUG
#endif // !CC_EXCEPTIONS_BASIC_HH
<commit_msg>Fix function name macro on Win32 from __func__ to __FUNCTION__.<commit_after>/*
** Copyright 2011 Merethis
**
** This file is part of Centreon Clib.
**
** Centreon Clib is free software: you can redistribute it
** and/or modify it under the terms of the GNU Affero General Public
** License as published by the Free Software Foundation, either version
** 3 of the License, or (at your option) any later version.
**
** Centreon Clib 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
** Affero General Public License for more details.
**
** You should have received a copy of the GNU Affero General Public
** License along with Centreon Clib. If not, see
** <http://www.gnu.org/licenses/>.
*/

#ifndef CC_EXCEPTIONS_BASIC_HH
#  define CC_EXCEPTIONS_BASIC_HH

#  include <exception>
#  include <string>
#  include "com/centreon/namespace.hh"
#  include "com/centreon/misc/stringifier.hh"

CC_BEGIN()

namespace               exceptions {
  /**
   *  @class basic basic.hh "com/centreon/exceptions/basic.hh"
   *  @brief Base exception class.
   *
   *  Simple exception class containing an basic error message.
   */
  class                 basic : public std::exception {
  public:
                        basic() throw();
                        basic(
                          char const* file,
                          char const* function,
                          int line) throw ();
                        basic(basic const& right) throw ();
    virtual             ~basic() throw ();
    virtual basic&      operator=(basic const& right) throw ();
    template<typename T>
    basic&              operator<<(T t) throw () {
      _buffer << t;
      return (*this);
    }
    virtual char const* what() const throw ();

  private:
    basic&              _internal_copy(basic const& right);

    misc::stringifier   _buffer;
  };
}

CC_END()

#  ifdef __GNUC__
#    define FUNCTION __PRETTY_FUNCTION__
#  elif defined(_MSC_VER)
#    define FUNCTION __FUNCTION__
#  else
#    define FUNCTION __func__
#  endif

#  ifndef NDEBUG
#    define basic_error() com::centreon::exceptions::basic( \
                          __FILE__,                        \
                          FUNCTION,                        \
                          __LINE__)
#  else
#    define basic_error() com::centreon::exceptions::basic()
#  endif // !NDEBUG
#endif // !CC_EXCEPTIONS_BASIC_HH
<|endoftext|>


<commit_before>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <iostream>
#include <iomanip>
#include "hip_runtime.h"

#define KNRM  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

#define failed(...) \
    printf ("%serror: ", KRED);\
    printf (__VA_ARGS__);\
    printf ("\n");\
    printf ("error: TEST FAILED\n%s", KNRM );\
    exit(EXIT_FAILURE);

#define HIPCHECK(error) \
    if (error != hipSuccess) { \
        printf("%serror: '%s'(%d) at %s:%d%s\n", \
               KRED, hipGetErrorString(error), error,\
               __FILE__, __LINE__,KNRM);\
        failed("API returned error code.");\
    }

void printCompilerInfo ()
{
#ifdef __HCC__
    printf ("compiler: hcc version=%s, workweek (YYWWD) = %u\n", __hcc_version__, __hcc_workweek__);
#endif
#ifdef __NVCC__
    printf ("compiler: nvcc\n");
#endif
}

double bytesToGB(size_t s)
{
    return (double)s / (1024.0*1024.0*1024.0);
}

void printDeviceProp (int deviceId)
{
    using namespace std;
    const int w1 = 30;

    cout << left;

    cout << setw(w1) << "--------------------------------------------------------------------------------" << endl;
    cout << setw(w1) << "device#" << deviceId << endl;

    hipDeviceProp_t props;
    HIPCHECK(hipGetDeviceProperties(&props, deviceId));

    cout << setw(w1) << "Name: " << props.name << endl;
    cout << setw(w1) << "pciBusID: " << props.pciBusID << endl;
    cout << setw(w1) << "pciDeviceID: " << props.pciDeviceID << endl;
    cout << setw(w1) << "multiProcessorCount: " << props.multiProcessorCount << endl;
    cout << setw(w1) << "maxThreadsPerMultiProcessor: " << props.maxThreadsPerMultiProcessor << endl;
    cout << setw(w1) << "isMultiGpuBoard: " << props.isMultiGpuBoard << endl;
    cout << setw(w1) << "clockRate: " << (float)props.clockRate / 1000.0 << " Mhz" << endl;
    cout << setw(w1) << "memoryClockRate: " << (float)props.memoryClockRate / 1000.0 << " Mhz" << endl;
    cout << setw(w1) << "memoryBusWidth: " << props.memoryBusWidth << endl;
    cout << setw(w1) << "clockInstructionRate: " << (float)props.clockInstructionRate / 1000.0 << " Mhz" << endl;
    cout << setw(w1) << "totalGlobalMem: " << fixed << setprecision(2) << bytesToGB(props.totalGlobalMem) << " GB" << endl;
    cout << setw(w1) << "maxSharedMemoryPerMultiProcessor: " << fixed << setprecision(2) << bytesToGB(props.maxSharedMemoryPerMultiProcessor) << " GB" << endl;
    cout << setw(w1) << "totalConstMem: " << props.totalConstMem << endl;
    cout << setw(w1) << "sharedMemPerBlock: " << (float)props.sharedMemPerBlock / 1024.0 << " KB" << endl;
    cout << setw(w1) << "regsPerBlock: " << props.regsPerBlock << endl;
    cout << setw(w1) << "warpSize: " << props.warpSize << endl;
    cout << setw(w1) << "l2CacheSize: " << props.l2CacheSize << endl;
    cout << setw(w1) << "computeMode: " << props.computeMode << endl;
    cout << setw(w1) << "maxThreadsPerBlock: " << props.maxThreadsPerBlock << endl;
    cout << setw(w1) << "maxThreadsDim.x: " << props.maxThreadsDim[0] << endl;
    cout << setw(w1) << "maxThreadsDim.y: " << props.maxThreadsDim[1] << endl;
    cout << setw(w1) << "maxThreadsDim.z: " << props.maxThreadsDim[2] << endl;
    cout << setw(w1) << "maxGridSize.x: " << props.maxGridSize[0] << endl;
    cout << setw(w1) << "maxGridSize.y: " << props.maxGridSize[1] << endl;
    cout << setw(w1) << "maxGridSize.z: " << props.maxGridSize[2] << endl;
    cout << setw(w1) << "major: " << props.major << endl;
    cout << setw(w1) << "minor: " << props.minor << endl;
    cout << setw(w1) << "concurrentKernels: " << props.concurrentKernels << endl;
    cout << setw(w1) << "arch.hasGlobalInt32Atomics: " <<     props.arch.hasGlobalInt32Atomics    << endl;
    cout << setw(w1) << "arch.hasGlobalFloatAtomicExch: " <<  props.arch.hasGlobalFloatAtomicExch << endl;
    cout << setw(w1) << "arch.hasSharedInt32Atomics: " <<     props.arch.hasSharedInt32Atomics    << endl;
    cout << setw(w1) << "arch.hasSharedFloatAtomicExch: " <<  props.arch.hasSharedFloatAtomicExch << endl;
    cout << setw(w1) << "arch.hasFloatAtomicAdd: " <<         props.arch.hasFloatAtomicAdd        << endl;
    cout << setw(w1) << "arch.hasGlobalInt64Atomics: " <<     props.arch.hasGlobalInt64Atomics    << endl;
    cout << setw(w1) << "arch.hasSharedInt64Atomics: " <<     props.arch.hasSharedInt64Atomics    << endl;
    cout << setw(w1) << "arch.hasDoubles: " <<                props.arch.hasDoubles               << endl;
    cout << setw(w1) << "arch.hasWarpVote: " <<               props.arch.hasWarpVote              << endl;
    cout << setw(w1) << "arch.hasWarpBallot: " <<             props.arch.hasWarpBallot            << endl;
    cout << setw(w1) << "arch.hasWarpShuffle: " <<            props.arch.hasWarpShuffle           << endl;
    cout << setw(w1) << "arch.hasFunnelShift: " <<            props.arch.hasFunnelShift           << endl;
    cout << setw(w1) << "arch.hasThreadFenceSystem: " <<      props.arch.hasThreadFenceSystem     << endl;
    cout << setw(w1) << "arch.hasSyncThreadsExt: " <<         props.arch.hasSyncThreadsExt        << endl;
    cout << setw(w1) << "arch.hasSurfaceFuncs: " <<           props.arch.hasSurfaceFuncs          << endl;
    cout << setw(w1) << "arch.has3dGrid: " <<                 props.arch.has3dGrid                << endl;
    cout << setw(w1) << "arch.hasDynamicParallelism: " <<     props.arch.hasDynamicParallelism    << endl;

    int deviceCnt;
    hipGetDeviceCount(&deviceCnt);
    cout << setw(w1) << "peers: ";
    for (int i=0; i<deviceCnt; i++) {
        int isPeer;
        hipDeviceCanAccessPeer(&isPeer, deviceId, i);
        if (isPeer) {
            cout << "device#" << i << " ";
        }
    }
    cout << endl;

    cout << endl;

    size_t free, total;
    hipMemGetInfo(&free, &total);

    cout << fixed << setprecision(2);
    cout << setw(w1) << "memInfo.total: " << bytesToGB(total) << " GB" << endl;
    cout << setw(w1) << "memInfo.free:  " << bytesToGB(free) << " GB (" << setprecision(0) << (float)free/total * 100.0 << "%)" << endl;
}

int main(int argc, char *argv[])
{
    using namespace std;

    cout << endl;

    printCompilerInfo();

    int deviceCnt;

    HIPCHECK(hipGetDeviceCount(&deviceCnt));

    for (int i=0; i< deviceCnt; i++) {
        printDeviceProp(i);
    }

    std::cout << std::endl;
}
<commit_msg>fix peer query order<commit_after>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <iostream>
#include <iomanip>
#include "hip_runtime.h"

#define KNRM  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

#define failed(...) \
    printf ("%serror: ", KRED);\
    printf (__VA_ARGS__);\
    printf ("\n");\
    printf ("error: TEST FAILED\n%s", KNRM );\
    exit(EXIT_FAILURE);

#define HIPCHECK(error) \
    if (error != hipSuccess) { \
        printf("%serror: '%s'(%d) at %s:%d%s\n", \
               KRED, hipGetErrorString(error), error,\
               __FILE__, __LINE__,KNRM);\
        failed("API returned error code.");\
    }

void printCompilerInfo ()
{
#ifdef __HCC__
    printf ("compiler: hcc version=%s, workweek (YYWWD) = %u\n", __hcc_version__, __hcc_workweek__);
#endif
#ifdef __NVCC__
    printf ("compiler: nvcc\n");
#endif
}

double bytesToGB(size_t s)
{
    return (double)s / (1024.0*1024.0*1024.0);
}

void printDeviceProp (int deviceId)
{
    using namespace std;
    const int w1 = 30;

    cout << left;

    cout << setw(w1) << "--------------------------------------------------------------------------------" << endl;
    cout << setw(w1) << "device#" << deviceId << endl;

    hipDeviceProp_t props;
    HIPCHECK(hipGetDeviceProperties(&props, deviceId));

    cout << setw(w1) << "Name: " << props.name << endl;
    cout << setw(w1) << "pciBusID: " << props.pciBusID << endl;
    cout << setw(w1) << "pciDeviceID: " << props.pciDeviceID << endl;
    cout << setw(w1) << "multiProcessorCount: " << props.multiProcessorCount << endl;
    cout << setw(w1) << "maxThreadsPerMultiProcessor: " << props.maxThreadsPerMultiProcessor << endl;
    cout << setw(w1) << "isMultiGpuBoard: " << props.isMultiGpuBoard << endl;
    cout << setw(w1) << "clockRate: " << (float)props.clockRate / 1000.0 << " Mhz" << endl;
    cout << setw(w1) << "memoryClockRate: " << (float)props.memoryClockRate / 1000.0 << " Mhz" << endl;
    cout << setw(w1) << "memoryBusWidth: " << props.memoryBusWidth << endl;
    cout << setw(w1) << "clockInstructionRate: " << (float)props.clockInstructionRate / 1000.0 << " Mhz" << endl;
    cout << setw(w1) << "totalGlobalMem: " << fixed << setprecision(2) << bytesToGB(props.totalGlobalMem) << " GB" << endl;
    cout << setw(w1) << "maxSharedMemoryPerMultiProcessor: " << fixed << setprecision(2) << bytesToGB(props.maxSharedMemoryPerMultiProcessor) << " GB" << endl;
    cout << setw(w1) << "totalConstMem: " << props.totalConstMem << endl;
    cout << setw(w1) << "sharedMemPerBlock: " << (float)props.sharedMemPerBlock / 1024.0 << " KB" << endl;
    cout << setw(w1) << "regsPerBlock: " << props.regsPerBlock << endl;
    cout << setw(w1) << "warpSize: " << props.warpSize << endl;
    cout << setw(w1) << "l2CacheSize: " << props.l2CacheSize << endl;
    cout << setw(w1) << "computeMode: " << props.computeMode << endl;
    cout << setw(w1) << "maxThreadsPerBlock: " << props.maxThreadsPerBlock << endl;
    cout << setw(w1) << "maxThreadsDim.x: " << props.maxThreadsDim[0] << endl;
    cout << setw(w1) << "maxThreadsDim.y: " << props.maxThreadsDim[1] << endl;
    cout << setw(w1) << "maxThreadsDim.z: " << props.maxThreadsDim[2] << endl;
    cout << setw(w1) << "maxGridSize.x: " << props.maxGridSize[0] << endl;
    cout << setw(w1) << "maxGridSize.y: " << props.maxGridSize[1] << endl;
    cout << setw(w1) << "maxGridSize.z: " << props.maxGridSize[2] << endl;
    cout << setw(w1) << "major: " << props.major << endl;
    cout << setw(w1) << "minor: " << props.minor << endl;
    cout << setw(w1) << "concurrentKernels: " << props.concurrentKernels << endl;
    cout << setw(w1) << "arch.hasGlobalInt32Atomics: " <<     props.arch.hasGlobalInt32Atomics    << endl;
    cout << setw(w1) << "arch.hasGlobalFloatAtomicExch: " <<  props.arch.hasGlobalFloatAtomicExch << endl;
    cout << setw(w1) << "arch.hasSharedInt32Atomics: " <<     props.arch.hasSharedInt32Atomics    << endl;
    cout << setw(w1) << "arch.hasSharedFloatAtomicExch: " <<  props.arch.hasSharedFloatAtomicExch << endl;
    cout << setw(w1) << "arch.hasFloatAtomicAdd: " <<         props.arch.hasFloatAtomicAdd        << endl;
    cout << setw(w1) << "arch.hasGlobalInt64Atomics: " <<     props.arch.hasGlobalInt64Atomics    << endl;
    cout << setw(w1) << "arch.hasSharedInt64Atomics: " <<     props.arch.hasSharedInt64Atomics    << endl;
    cout << setw(w1) << "arch.hasDoubles: " <<                props.arch.hasDoubles               << endl;
    cout << setw(w1) << "arch.hasWarpVote: " <<               props.arch.hasWarpVote              << endl;
    cout << setw(w1) << "arch.hasWarpBallot: " <<             props.arch.hasWarpBallot            << endl;
    cout << setw(w1) << "arch.hasWarpShuffle: " <<            props.arch.hasWarpShuffle           << endl;
    cout << setw(w1) << "arch.hasFunnelShift: " <<            props.arch.hasFunnelShift           << endl;
    cout << setw(w1) << "arch.hasThreadFenceSystem: " <<      props.arch.hasThreadFenceSystem     << endl;
    cout << setw(w1) << "arch.hasSyncThreadsExt: " <<         props.arch.hasSyncThreadsExt        << endl;
    cout << setw(w1) << "arch.hasSurfaceFuncs: " <<           props.arch.hasSurfaceFuncs          << endl;
    cout << setw(w1) << "arch.has3dGrid: " <<                 props.arch.has3dGrid                << endl;
    cout << setw(w1) << "arch.hasDynamicParallelism: " <<     props.arch.hasDynamicParallelism    << endl;

    int deviceCnt;
    hipGetDeviceCount(&deviceCnt);
    cout << setw(w1) << "peers: ";
    for (int i=0; i<deviceCnt; i++) {
        int isPeer;
        hipDeviceCanAccessPeer(&isPeer, i, deviceId);
        if (isPeer) {
            cout << "device#" << i << " ";
        }
    }
    cout << endl;

    cout << endl;

    size_t free, total;
    hipMemGetInfo(&free, &total);

    cout << fixed << setprecision(2);
    cout << setw(w1) << "memInfo.total: " << bytesToGB(total) << " GB" << endl;
    cout << setw(w1) << "memInfo.free:  " << bytesToGB(free) << " GB (" << setprecision(0) << (float)free/total * 100.0 << "%)" << endl;
}

int main(int argc, char *argv[])
{
    using namespace std;

    cout << endl;

    printCompilerInfo();

    int deviceCnt;

    HIPCHECK(hipGetDeviceCount(&deviceCnt));

    for (int i=0; i< deviceCnt; i++) {
        printDeviceProp(i);
    }

    std::cout << std::endl;
}
<|endoftext|>


<commit_before>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2015 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  platform/win32/window/simple.hpp                                                */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

#if !defined(UKACHULLDCS_08961_PLATFORM_WIN32_WINDOW_SIMPLE_HPP)

#define UKACHULLDCS_08961_PLATFORM_WIN32_WINDOW_SIMPLE_HPP

// includes, system

//#include <>

// includes, project

#include <platform/win32/window/base.hpp>

namespace platform {

  namespace win32 {

    namespace window {

      // types, exported (class, enum, struct, union, typedef)

      class DCS08961_PLATFORM_EXPORT simple : public platform::win32::window::base {

      public:

        using rect = platform::window::rect;

        field::value::single<bool> focused;
        field::value::single<bool> minimized;

        explicit simple(std::string const& /* title */,
                        rect const&        /* rect */ = rect::dflt_rect);

        virtual ~simple();

      protected:

        virtual LRESULT CALLBACK cb_window_proc(HWND, UINT, WPARAM, LPARAM);

        virtual bool focus (bool /* focused or not */);
        virtual bool redraw();
        virtual bool resize(glm::ivec2 const& /* size */, bool /* minimized */);

      };

      // variables, exported (extern)

      // functions, inlined (inline)

      // functions, exported (extern)

    } // namespace window {

  } // namespace win32 {

} // namespace platform {

#endif // #if !defined(UKACHULLDCS_08961_PLATFORM_WIN32_WINDOW_SIMPLE_HPP)
<commit_msg>update<commit_after>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2015 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  platform/win32/window/simple.hpp                                                */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

#if !defined(UKACHULLDCS_08961_PLATFORM_WIN32_WINDOW_SIMPLE_HPP)

#define UKACHULLDCS_08961_PLATFORM_WIN32_WINDOW_SIMPLE_HPP

// includes, system

//#include <>

// includes, project

#include <platform/win32/window/base.hpp>

namespace platform {

  namespace win32 {

    namespace window {

      // types, exported (class, enum, struct, union, typedef)

      class DCS08961_PLATFORM_EXPORT simple : public platform::win32::window::base {

      public:

        using rect = platform::window::rect;

        field::value::single<bool> focused;
        field::value::single<bool> minimized;

        explicit simple(std::string const& /* title */,
                        rect const&        /* rect */ = rect::dflt_rect);

        virtual ~simple();

      protected:

        virtual LRESULT CALLBACK cb_window_proc(HWND, UINT, WPARAM, LPARAM);

        virtual bool focus (bool /* focused or not */);
        virtual bool redraw();
        virtual bool resize(glm::ivec2 const& /* size */, bool /* minimized */);

      };

      // variables, exported (extern)

      // functions, inlined (inline)

      // functions, exported (extern)

    } // namespace window {

  } // namespace win32 {

} // namespace platform {

#endif // #if !defined(UKACHULLDCS_08961_PLATFORM_WIN32_WINDOW_SIMPLE_HPP)
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBenchmark.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRandom.h"
#include "SkString.h"

// This bench simulates the calls Skia sees from various HTML5 canvas
// game bench marks
class GameBench : public SkBenchmark {
public:
    enum Type {
        kScale_Type,
        kTranslate_Type,
        kRotate_Type
    };

    GameBench(void* param, Type type, bool partialClear)
        : INHERITED(param)
        , fType(type)
        , fPartialClear(partialClear)
        , fName("game")
        , fNumSaved(0)
        , fInitialized(false) {

        switch (fType) {
        case kScale_Type:
            fName.append("_scale");
            break;
        case kTranslate_Type:
            fName.append("_trans");
            break;
        case kRotate_Type:
            fName.append("_rot");
            break;
        };

        if (partialClear) {
            fName.append("_partial");
        } else {
            fName.append("_full");
        }

        // It's HTML 5 canvas, so always AA
        fName.append("_aa");
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return fName.c_str();;
    }

    virtual void onPreDraw() SK_OVERRIDE {
        if (!fInitialized) {
            this->makeCheckerboard();
            fInitialized = true;
        }
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        static SkMWCRandom scaleRand;
        static SkMWCRandom transRand;
        static SkMWCRandom rotRand;

        SkPaint clearPaint;
        clearPaint.setColor(0xFF000000);
        clearPaint.setAntiAlias(true);

        SkISize size = canvas->getDeviceSize();

        SkScalar maxTransX, maxTransY;

        if (kScale_Type == fType) {
            maxTransX = size.fWidth  - (1.5f * kCheckerboardWidth);
            maxTransY = size.fHeight - (1.5f * kCheckerboardHeight);
        } else if (kTranslate_Type == fType) {
            maxTransX = SkIntToScalar(size.fWidth  - kCheckerboardWidth);
            maxTransY = SkIntToScalar(size.fHeight - kCheckerboardHeight);
        } else {
            SkASSERT(kRotate_Type == fType);
            // Yes, some rotations will be off the top and left sides
            maxTransX = size.fWidth  - SK_ScalarSqrt2 * kCheckerboardHeight;
            maxTransY = size.fHeight - SK_ScalarSqrt2 * kCheckerboardHeight;
        }

        SkMatrix mat;
        SkIRect src = { 0, 0, kCheckerboardWidth, kCheckerboardHeight };
        SkRect dst = { 0, 0, kCheckerboardWidth, kCheckerboardHeight };
        SkRect clearRect = { -1.0f, -1.0f,
                             kCheckerboardWidth+1.0f, kCheckerboardHeight+1.0f };

        SkPaint p;
        p.setColor(0xFF000000);
        p.setFilterBitmap(true);

        for (int i = 0; i < kNumRects; ++i, ++fNumSaved) {

            if (0 == i % kNumBeforeClear) {
                if (fPartialClear) {
                    for (int j = 0; j < fNumSaved; ++j) {
                        canvas->setMatrix(SkMatrix::I());
                        mat.setTranslate(fSaved[j][0], fSaved[j][1]);

                        if (kScale_Type == fType) {
                            mat.preScale(fSaved[j][2], fSaved[j][2]);
                        } else if (kRotate_Type == fType) {
                            mat.preRotate(fSaved[j][2]);
                        }

                        canvas->concat(mat);
                        canvas->drawRect(clearRect, clearPaint);
                    }
                } else {
                    canvas->clear(0xFF000000);
                }

                fNumSaved = 0;
            }

            SkASSERT(fNumSaved < kNumBeforeClear);

            canvas->setMatrix(SkMatrix::I());

            fSaved[fNumSaved][0] = transRand.nextRangeScalar(0.0f, maxTransX);
            fSaved[fNumSaved][1] = transRand.nextRangeScalar(0.0f, maxTransY);

            mat.setTranslate(fSaved[fNumSaved][0], fSaved[fNumSaved][1]);

            if (kScale_Type == fType) {
                fSaved[fNumSaved][2] = scaleRand.nextRangeScalar(0.5f, 1.5f);
                mat.preScale(fSaved[fNumSaved][2], fSaved[fNumSaved][2]);
            } else if (kRotate_Type == fType) {
                fSaved[fNumSaved][2] = rotRand.nextRangeScalar(0.0f, 360.0f);
                mat.preRotate(fSaved[fNumSaved][2]);
            }

            canvas->concat(mat);
            canvas->drawBitmapRect(fCheckerboard, &src, dst, &p);
        }
    }

private:
    static const int kCheckerboardWidth = 64;
    static const int kCheckerboardHeight = 128;
#ifdef SK_DEBUG
    static const int kNumRects = 100;
    static const int kNumBeforeClear = 10;
#else
    static const int kNumRects = 5000;
    static const int kNumBeforeClear = 300;
#endif

    Type     fType;
    bool     fPartialClear;
    SkString fName;
    int      fNumSaved; // num draws stored in 'fSaved'
    bool     fInitialized;

    // 0 & 1 are always x & y translate. 2 is either scale or rotate.
    SkScalar fSaved[kNumBeforeClear][3];
    SkBitmap fCheckerboard;

    // Note: the resulting checker board has transparency
    void makeCheckerboard() {
        static int kCheckSize = 16;

        fCheckerboard.setConfig(SkBitmap::kARGB_8888_Config,
                                kCheckerboardWidth, kCheckerboardHeight);
        fCheckerboard.allocPixels();
        SkAutoLockPixels lock(fCheckerboard);
        for (int y = 0; y < kCheckerboardHeight; ++y) {
            int even = (y / kCheckSize) % 2;

            SkPMColor* scanline = fCheckerboard.getAddr32(0, y);

            for (int x = 0; x < kCheckerboardWidth; ++x) {
                if (even == (x / kCheckSize) % 2) {
                    *scanline++ = 0xFFFF0000;
                } else {
                    *scanline++ = 0x00000000;
                }
            }
        }
    }

    typedef SkBenchmark INHERITED;
};

// Partial clear
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kScale_Type, false)); )
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kTranslate_Type, false)); )
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kRotate_Type, false)); )

// Full clear
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kScale_Type, true)); )
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kTranslate_Type, true)); )
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kRotate_Type, true)); )
<commit_msg>Add aligned case to game bench<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBenchmark.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRandom.h"
#include "SkString.h"

// This bench simulates the calls Skia sees from various HTML5 canvas
// game bench marks
class GameBench : public SkBenchmark {
public:
    enum Type {
        kScale_Type,
        kTranslate_Type,
        kRotate_Type
    };

    GameBench(void* param, Type type, bool partialClear, bool aligned = false)
        : INHERITED(param)
        , fType(type)
        , fPartialClear(partialClear)
        , fAligned(aligned)
        , fName("game")
        , fNumSaved(0)
        , fInitialized(false) {

        switch (fType) {
        case kScale_Type:
            fName.append("_scale");
            break;
        case kTranslate_Type:
            fName.append("_trans");
            break;
        case kRotate_Type:
            fName.append("_rot");
            break;
        };

        if (aligned) {
            fName.append("_aligned");
        }

        if (partialClear) {
            fName.append("_partial");
        } else {
            fName.append("_full");
        }

        // It's HTML 5 canvas, so always AA
        fName.append("_aa");
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return fName.c_str();;
    }

    virtual void onPreDraw() SK_OVERRIDE {
        if (!fInitialized) {
            this->makeCheckerboard();
            fInitialized = true;
        }
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        static SkMWCRandom scaleRand;
        static SkMWCRandom transRand;
        static SkMWCRandom rotRand;

        SkPaint clearPaint;
        clearPaint.setColor(0xFF000000);
        clearPaint.setAntiAlias(true);

        SkISize size = canvas->getDeviceSize();

        SkScalar maxTransX, maxTransY;

        if (kScale_Type == fType) {
            maxTransX = size.fWidth  - (1.5f * kCheckerboardWidth);
            maxTransY = size.fHeight - (1.5f * kCheckerboardHeight);
        } else if (kTranslate_Type == fType) {
            maxTransX = SkIntToScalar(size.fWidth  - kCheckerboardWidth);
            maxTransY = SkIntToScalar(size.fHeight - kCheckerboardHeight);
        } else {
            SkASSERT(kRotate_Type == fType);
            // Yes, some rotations will be off the top and left sides
            maxTransX = size.fWidth  - SK_ScalarSqrt2 * kCheckerboardHeight;
            maxTransY = size.fHeight - SK_ScalarSqrt2 * kCheckerboardHeight;
        }

        SkMatrix mat;
        SkIRect src = { 0, 0, kCheckerboardWidth, kCheckerboardHeight };
        SkRect dst = { 0, 0, kCheckerboardWidth, kCheckerboardHeight };
        SkRect clearRect = { -1.0f, -1.0f,
                             kCheckerboardWidth+1.0f, kCheckerboardHeight+1.0f };

        SkPaint p;
        p.setColor(0xFF000000);
        p.setFilterBitmap(true);

        for (int i = 0; i < kNumRects; ++i, ++fNumSaved) {

            if (0 == i % kNumBeforeClear) {
                if (fPartialClear) {
                    for (int j = 0; j < fNumSaved; ++j) {
                        canvas->setMatrix(SkMatrix::I());
                        mat.setTranslate(fSaved[j][0], fSaved[j][1]);

                        if (kScale_Type == fType) {
                            mat.preScale(fSaved[j][2], fSaved[j][2]);
                        } else if (kRotate_Type == fType) {
                            mat.preRotate(fSaved[j][2]);
                        }

                        canvas->concat(mat);
                        canvas->drawRect(clearRect, clearPaint);
                    }
                } else {
                    canvas->clear(0xFF000000);
                }

                fNumSaved = 0;
            }

            SkASSERT(fNumSaved < kNumBeforeClear);

            canvas->setMatrix(SkMatrix::I());

            fSaved[fNumSaved][0] = transRand.nextRangeScalar(0.0f, maxTransX);
            fSaved[fNumSaved][1] = transRand.nextRangeScalar(0.0f, maxTransY);
            if (fAligned) {
                // make the translations integer aligned
                fSaved[fNumSaved][0] = SkScalarFloorToScalar(fSaved[fNumSaved][0]);
                fSaved[fNumSaved][1] = SkScalarFloorToScalar(fSaved[fNumSaved][1]);
            }

            mat.setTranslate(fSaved[fNumSaved][0], fSaved[fNumSaved][1]);

            if (kScale_Type == fType) {
                fSaved[fNumSaved][2] = scaleRand.nextRangeScalar(0.5f, 1.5f);
                mat.preScale(fSaved[fNumSaved][2], fSaved[fNumSaved][2]);
            } else if (kRotate_Type == fType) {
                fSaved[fNumSaved][2] = rotRand.nextRangeScalar(0.0f, 360.0f);
                mat.preRotate(fSaved[fNumSaved][2]);
            }

            canvas->concat(mat);
            canvas->drawBitmapRect(fCheckerboard, &src, dst, &p);
        }
    }

private:
    static const int kCheckerboardWidth = 64;
    static const int kCheckerboardHeight = 128;
#ifdef SK_DEBUG
    static const int kNumRects = 100;
    static const int kNumBeforeClear = 10;
#else
    static const int kNumRects = 5000;
    static const int kNumBeforeClear = 300;
#endif

    Type     fType;
    bool     fPartialClear;
    bool     fAligned;
    SkString fName;
    int      fNumSaved; // num draws stored in 'fSaved'
    bool     fInitialized;

    // 0 & 1 are always x & y translate. 2 is either scale or rotate.
    SkScalar fSaved[kNumBeforeClear][3];
    SkBitmap fCheckerboard;

    // Note: the resulting checker board has transparency
    void makeCheckerboard() {
        static int kCheckSize = 16;

        fCheckerboard.setConfig(SkBitmap::kARGB_8888_Config,
                                kCheckerboardWidth, kCheckerboardHeight);
        fCheckerboard.allocPixels();
        SkAutoLockPixels lock(fCheckerboard);
        for (int y = 0; y < kCheckerboardHeight; ++y) {
            int even = (y / kCheckSize) % 2;

            SkPMColor* scanline = fCheckerboard.getAddr32(0, y);

            for (int x = 0; x < kCheckerboardWidth; ++x) {
                if (even == (x / kCheckSize) % 2) {
                    *scanline++ = 0xFFFF0000;
                } else {
                    *scanline++ = 0x00000000;
                }
            }
        }
    }

    typedef SkBenchmark INHERITED;
};

// Partial clear
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kScale_Type, false)); )
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kTranslate_Type, false)); )
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kTranslate_Type, false, true)); )
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kRotate_Type, false)); )

// Full clear
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kScale_Type, true)); )
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kTranslate_Type, true)); )
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kTranslate_Type, true, true)); )
DEF_BENCH( return SkNEW_ARGS(GameBench, (p, GameBench::kRotate_Type, true)); )
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <iostream>
#include <signal.h>
#include <X11/Xlib.h>

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/scoped_ptr.h"
#include "base/thread.h"
#include "media/base/media.h"
#include "media/base/media_switches.h"
#include "media/base/pipeline_impl.h"
#include "media/filters/audio_renderer_impl.h"
#include "media/filters/ffmpeg_audio_decoder.h"
#include "media/filters/ffmpeg_demuxer.h"
#include "media/filters/ffmpeg_video_decoder.h"
#include "media/filters/file_data_source.h"
#include "media/filters/null_audio_renderer.h"
#include "media/filters/omx_video_decoder.h"

#if defined(RENDERER_GL)
#include "media/tools/player_x11/gl_video_renderer.h"
typedef GlVideoRenderer Renderer;
#elif defined(RENDERER_GLES)
#include "media/tools/player_x11/gles_video_renderer.h"
typedef GlesVideoRenderer Renderer;
#elif defined(RENDERER_X11)
#include "media/tools/player_x11/x11_video_renderer.h"
typedef X11VideoRenderer Renderer;
#else
#error No video renderer defined.
#endif

Display* g_display = NULL;
Window g_window = 0;
bool g_running = false;

// Initialize X11. Returns true if successful. This method creates the X11
// window. Further initialization is done in X11VideoRenderer.
bool InitX11() {
  g_display = XOpenDisplay(NULL);
  if (!g_display) {
    std::cout << "Error - cannot open display" << std::endl;
    return false;
  }

  // Get properties of the screen.
  int screen = DefaultScreen(g_display);
  int root_window = RootWindow(g_display, screen);

  // Creates the window.
  g_window = XCreateSimpleWindow(g_display, root_window, 1, 1, 100, 50, 0,
                                 BlackPixel(g_display, screen),
                                 BlackPixel(g_display, screen));
  XStoreName(g_display, g_window, "X11 Media Player");

  XSelectInput(g_display, g_window, ExposureMask | ButtonPressMask);
  XMapWindow(g_display, g_window);
  return true;
}

bool InitPipeline(MessageLoop* message_loop,
                  const char* filename, bool enable_audio,
                  scoped_refptr<media::PipelineImpl>* pipeline) {
  // Initialize OpenMAX.
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableOpenMax) &&
      !media::InitializeOpenMaxLibrary(FilePath())) {
    std::cout << "Unable to initialize OpenMAX library."<< std::endl;
    return false;
  }

  // Load media libraries.
  if (!media::InitializeMediaLibrary(FilePath())) {
    std::cout << "Unable to initialize the media library." << std::endl;
    return false;
  }

  // Create our filter factories.
  scoped_refptr<media::FilterFactoryCollection> factories =
      new media::FilterFactoryCollection();
  factories->AddFactory(media::FileDataSource::CreateFactory());
  factories->AddFactory(media::FFmpegAudioDecoder::CreateFactory());
  factories->AddFactory(media::FFmpegDemuxer::CreateFilterFactory());
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableOpenMax)) {
    factories->AddFactory(media::OmxVideoDecoder::CreateFactory());
  }
  factories->AddFactory(media::FFmpegVideoDecoder::CreateFactory());
  factories->AddFactory(Renderer::CreateFactory(g_display, g_window));

  if (enable_audio) {
    factories->AddFactory(media::AudioRendererImpl::CreateFilterFactory());
  } else {
    factories->AddFactory(media::NullAudioRenderer::CreateFilterFactory());
  }

  // Creates the pipeline and start it.
  *pipeline = new media::PipelineImpl(message_loop);
  (*pipeline)->Start(factories, filename, NULL);

  // Wait until the pipeline is fully initialized.
  while (true) {
    PlatformThread::Sleep(100);
    if ((*pipeline)->IsInitialized())
      break;
    if ((*pipeline)->GetError() != media::PIPELINE_OK) {
      (*pipeline)->Stop(NULL);
      return false;
    }
  }

  // And starts the playback.
  (*pipeline)->SetPlaybackRate(1.0f);
  return true;
}

void TerminateHandler(int signal) {
  g_running = false;
}

int main(int argc, char** argv) {
  // Read arguments.
  if (argc == 1) {
    std::cout << "Usage: " << argv[0] << " --file=FILE" << std::endl
              << std::endl
              << "Optional arguments:" << std::endl
              << "  [--enable-openmax]"
              << "  [--audio]"
              << "  [--alsa-device=DEVICE]" << std::endl;
    return 1;
  }

  // Read command line.
  CommandLine::Init(argc, argv);
  std::string filename =
      CommandLine::ForCurrentProcess()->GetSwitchValueASCII("file");
  bool enable_audio = CommandLine::ForCurrentProcess()->HasSwitch("audio");

  // Install the signal handler.
  signal(SIGTERM, &TerminateHandler);
  signal(SIGINT, &TerminateHandler);

  // Initialize X11.
  if (!InitX11())
    return 1;

  // Initialize the pipeline thread and the pipeline.
  base::AtExitManager at_exit;
  scoped_ptr<base::Thread> thread;
  scoped_refptr<media::PipelineImpl> pipeline;
  thread.reset(new base::Thread("PipelineThread"));
  thread->Start();
  if (InitPipeline(thread->message_loop(), filename.c_str(),
                   enable_audio, &pipeline)) {
    // Main loop of the application.
    g_running = true;
    while (g_running) {
      if (XPending(g_display)) {
        XEvent e;
        XNextEvent(g_display, &e);
        if (e.type == Expose) {
          // Tell the renderer to paint.
          DCHECK(Renderer::instance());
          Renderer::instance()->Paint();
        } else if (e.type == ButtonPress) {
          // Stop the playback.
          break;
        }
      } else {
        // If there's no event in the queue, make an expose event.
        XEvent event;
        event.type = Expose;
        XSendEvent(g_display, g_window, true, ExposureMask, &event);

        // TODO(hclam): It is rather arbitrary to sleep for 10ms and wait
        // for the next event. We should submit an expose event when
        // a frame is available but not firing an expose event every 10ms.
        usleep(10000);
      }
    }
    pipeline->Stop(NULL);
  } else{
    std::cout << "Pipeline initialization failed..." << std::endl;
  }

  // Cleanup tasks.
  thread->Stop();
  XDestroyWindow(g_display, g_window);
  XCloseDisplay(g_display);
  return 0;
}
<commit_msg>Adding support for playing audio only also files through player_x11 application. Currently the application just hangs without doing anything if an audio only file is given as input to it.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <iostream>
#include <signal.h>
#include <X11/Xlib.h>

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/scoped_ptr.h"
#include "base/thread.h"
#include "media/base/media.h"
#include "media/base/media_switches.h"
#include "media/base/pipeline_impl.h"
#include "media/filters/audio_renderer_impl.h"
#include "media/filters/ffmpeg_audio_decoder.h"
#include "media/filters/ffmpeg_demuxer.h"
#include "media/filters/ffmpeg_video_decoder.h"
#include "media/filters/file_data_source.h"
#include "media/filters/null_audio_renderer.h"
#include "media/filters/omx_video_decoder.h"

#if defined(RENDERER_GL)
#include "media/tools/player_x11/gl_video_renderer.h"
typedef GlVideoRenderer Renderer;
#elif defined(RENDERER_GLES)
#include "media/tools/player_x11/gles_video_renderer.h"
typedef GlesVideoRenderer Renderer;
#elif defined(RENDERER_X11)
#include "media/tools/player_x11/x11_video_renderer.h"
typedef X11VideoRenderer Renderer;
#else
#error No video renderer defined.
#endif

Display* g_display = NULL;
Window g_window = 0;
bool g_running = false;

// Initialize X11. Returns true if successful. This method creates the X11
// window. Further initialization is done in X11VideoRenderer.
bool InitX11() {
  g_display = XOpenDisplay(NULL);
  if (!g_display) {
    std::cout << "Error - cannot open display" << std::endl;
    return false;
  }

  // Get properties of the screen.
  int screen = DefaultScreen(g_display);
  int root_window = RootWindow(g_display, screen);

  // Creates the window.
  g_window = XCreateSimpleWindow(g_display, root_window, 1, 1, 100, 50, 0,
                                 BlackPixel(g_display, screen),
                                 BlackPixel(g_display, screen));
  XStoreName(g_display, g_window, "X11 Media Player");

  XSelectInput(g_display, g_window, ExposureMask | ButtonPressMask);
  XMapWindow(g_display, g_window);
  return true;
}

bool InitPipeline(MessageLoop* message_loop,
                  const char* filename, bool enable_audio,
                  scoped_refptr<media::PipelineImpl>* pipeline) {
  // Initialize OpenMAX.
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableOpenMax) &&
      !media::InitializeOpenMaxLibrary(FilePath())) {
    std::cout << "Unable to initialize OpenMAX library."<< std::endl;
    return false;
  }

  // Load media libraries.
  if (!media::InitializeMediaLibrary(FilePath())) {
    std::cout << "Unable to initialize the media library." << std::endl;
    return false;
  }

  // Create our filter factories.
  scoped_refptr<media::FilterFactoryCollection> factories =
      new media::FilterFactoryCollection();
  factories->AddFactory(media::FileDataSource::CreateFactory());
  factories->AddFactory(media::FFmpegAudioDecoder::CreateFactory());
  factories->AddFactory(media::FFmpegDemuxer::CreateFilterFactory());
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableOpenMax)) {
    factories->AddFactory(media::OmxVideoDecoder::CreateFactory());
  }
  factories->AddFactory(media::FFmpegVideoDecoder::CreateFactory());
  factories->AddFactory(Renderer::CreateFactory(g_display, g_window));

  if (enable_audio) {
    factories->AddFactory(media::AudioRendererImpl::CreateFilterFactory());
  } else {
    factories->AddFactory(media::NullAudioRenderer::CreateFilterFactory());
  }

  // Creates the pipeline and start it.
  *pipeline = new media::PipelineImpl(message_loop);
  (*pipeline)->Start(factories, filename, NULL);

  // Wait until the pipeline is fully initialized.
  while (true) {
    PlatformThread::Sleep(100);
    if ((*pipeline)->IsInitialized())
      break;
    if ((*pipeline)->GetError() != media::PIPELINE_OK) {
      (*pipeline)->Stop(NULL);
      return false;
    }
  }

  // And starts the playback.
  (*pipeline)->SetPlaybackRate(1.0f);
  return true;
}

void TerminateHandler(int signal) {
  g_running = false;
}

int main(int argc, char** argv) {
  // Read arguments.
  if (argc == 1) {
    std::cout << "Usage: " << argv[0] << " --file=FILE" << std::endl
              << std::endl
              << "Optional arguments:" << std::endl
              << "  [--enable-openmax]"
              << "  [--audio]"
              << "  [--alsa-device=DEVICE]" << std::endl;
    return 1;
  }

  // Read command line.
  CommandLine::Init(argc, argv);
  std::string filename =
      CommandLine::ForCurrentProcess()->GetSwitchValueASCII("file");
  bool enable_audio = CommandLine::ForCurrentProcess()->HasSwitch("audio");
  bool audio_only = false;

  // Install the signal handler.
  signal(SIGTERM, &TerminateHandler);
  signal(SIGINT, &TerminateHandler);

  // Initialize X11.
  if (!InitX11())
    return 1;

  // Initialize the pipeline thread and the pipeline.
  base::AtExitManager at_exit;
  scoped_ptr<base::Thread> thread;
  scoped_refptr<media::PipelineImpl> pipeline;
  thread.reset(new base::Thread("PipelineThread"));
  thread->Start();
  if (InitPipeline(thread->message_loop(), filename.c_str(),
                   enable_audio, &pipeline)) {
    // Main loop of the application.
    g_running = true;

    // Check if video is present.
    audio_only = !pipeline->IsRendered(media::mime_type::kMajorTypeVideo);

    while (g_running) {
      if (XPending(g_display)) {
        XEvent e;
        XNextEvent(g_display, &e);
        if (e.type == Expose) {
          if (!audio_only) {
            // Tell the renderer to paint.
            DCHECK(Renderer::instance());
            Renderer::instance()->Paint();
          }
        } else if (e.type == ButtonPress) {
          // Stop the playback.
          break;
        }
      } else {
        // If there's no event in the queue, make an expose event.
        XEvent event;
        event.type = Expose;
        XSendEvent(g_display, g_window, true, ExposureMask, &event);

        // TODO(hclam): It is rather arbitrary to sleep for 10ms and wait
        // for the next event. We should submit an expose event when
        // a frame is available but not firing an expose event every 10ms.
        usleep(10000);
      }
    }
    pipeline->Stop(NULL);
  } else{
    std::cout << "Pipeline initialization failed..." << std::endl;
  }

  // Cleanup tasks.
  thread->Stop();
  XDestroyWindow(g_display, g_window);
  XCloseDisplay(g_display);
  return 0;
}
<|endoftext|>