text:
package com.touchgraph.graphlayout;

import  java.awt.Color;
import  java.awt.Dimension;
import  java.awt.Point;
import  java.awt.Font;
import  java.awt.FontMetrics;
import  java.awt.Graphics;
import  java.util.Date;
import  java.util.Vector;
import  java.util.Iterator;

/**  Node.
  *
  *  @author   Alexander Shapiro
  *  @author   Murray Altheim (2001-11-06; added support for round rects and alternate Node colors)
  *  @version  1.21  $Id: Node.java,v 1.1.1.1 2007/01/07 07:58:19 andrew Exp $
  */
public class Node {

   /** This Node's type is a Rectangle. */
    public final static int TYPE_RECTANGLE = 1;

   /** This Node's type is a Round Rectangle. */
    public final static int TYPE_ROUNDRECT = 2;

   /** This Node's type is an Ellipse. */
    public final static int TYPE_ELLIPSE   = 3;

   /** This Node's type is a Circle. */
    public final static int TYPE_CIRCLE    = 4;

    public static final Font SMALL_TAG_FONT = new Font("Courier",Font.PLAIN,9);

   // Variables that store default values for colors + fonts + node type
    public static Color BACK_FIXED_COLOR        = Color.red;
    public static Color BACK_SELECT_COLOR       = new Color(255, 224, 0);
    public static Color BACK_DEFAULT_COLOR      = new Color(208, 96, 0);
    public static Color BACK_HILIGHT_COLOR      = Color.decode("#ffb200"); // altheim: new

    public static Color BORDER_DRAG_COLOR       = Color.black;
    public static Color BORDER_MOUSE_OVER_COLOR = new Color(160,160,160);
    public static Color BORDER_INACTIVE_COLOR   = Color.white;

    public static Color TEXT_COLOR              = Color.white;

    public static Font TEXT_FONT = new Font("Courier",Font.PLAIN,12);

    public static int DEFAULT_TYPE = 1;

   /** an int indicating the Node type.
     * @see TYPE_RECTANGLE
     * @see TYPE_ROUNDRECT
     * @see TYPE_ELLIPSE
     */
    protected int typ = TYPE_RECTANGLE;
    private String id;

    public double drawx;
    public double drawy;

    protected FontMetrics fontMetrics;
    protected Font font;

    protected String lbl;
    protected Color backColor = BACK_DEFAULT_COLOR;
    protected Color textColor = TEXT_COLOR;

    public double x;
    public double y;

    protected double dx; //Used by layout
    protected double dy; //Used by layout

    protected boolean fixed;
    protected int repulsion; //Used by layout

    public boolean justMadeLocal = false;
    public boolean markedForRemoval = false;

    public int visibleEdgeCnt; //Should only be modified by graphelements.VisibleLocality
    protected boolean visible;

    private Vector edges;

  // ............

   /** Minimal constructor which will generate an ID value from Java's Date class.
     * Defaults will be used for type and color. The label will be taken from the ID value.
     */
    public Node()
    {
        initialize(null);
        lbl = id;
    }

   /** Constructor with the required ID <tt>id</tt>, using defaults
     * for type (rectangle), color (a static variable from TGPanel).
     * The Node's label will be taken from the ID value.
     */
    public Node( String id )
    {
        initialize(id);
        lbl = id;
    }

   /** Constructor with Strings for ID <tt>id</tt> and <tt>label</tt>, using defaults
     * for type (rectangle) and color (a static variable from TGPanel).
     * If the label is null, it will be taken from the ID value.
     */
    public Node( String id, String label )
    {
        initialize(id);
        if ( label == null ) lbl = id;
        else lbl = label;
    }

   /** Constructor with a String ID <tt>id</tt>, an int <tt>type</tt>, Background Color <tt>bgColor</tt>,
     * and a String <tt>label</tt>. If the label is null, it will be taken from the ID value.
     * @see TYPE_RECTANGLE
     * @see TYPE_ROUNDRECT
     */
    public Node( String id, int type, Color color, String label )
    {
        initialize(id);
        typ = type;
        backColor = color;
        if ( label == null ) lbl = id;
        else lbl = label;
    }

    private void initialize( String identifier ) {
        this.id = identifier;
        edges = new Vector();
        x = Math.random()*2-1; // If multiple nodes are added without repositioning,
        y = Math.random()*2-1; // randomizing starting location causes them to spread out nicely.
        repulsion = 100;
        font = TEXT_FONT;
        fixed = false;
        typ = DEFAULT_TYPE;
        visibleEdgeCnt=0;
        visible = false;
    }

   // setters and getters ...............

    public static void setNodeBackFixedColor( Color color ) { BACK_FIXED_COLOR = color; }
    public static void setNodeBackSelectColor( Color color ) { BACK_SELECT_COLOR = color; }
    public static void setNodeBackDefaultColor( Color color ) { BACK_DEFAULT_COLOR = color; }
    public static void setNodeBackHilightColor( Color color ) { BACK_HILIGHT_COLOR = color; }
    public static void setNodeBorderDragColor( Color color ) { BORDER_DRAG_COLOR = color; }
    public static void setNodeBorderMouseOverColor( Color color ) { BORDER_MOUSE_OVER_COLOR = color; }
    public static void setNodeBorderInactiveColor( Color color ) { BORDER_INACTIVE_COLOR = color; }
    public static void setNodeTextColor( Color color ) { TEXT_COLOR = color; }
    public static void setNodeTextFont( Font font ) { TEXT_FONT = font; }
    public static void setNodeType( int type ) { DEFAULT_TYPE = type; }

    /** Set the ID of this Node to the String <tt>id</tt>.
      */
    public void setID( String id ) {
        this.id = id;
    }

    /** Return the ID of this Node as a String.
     */
    public String getID() {
        return id;
    }

    /** Set the location of this Node provided the Point <tt>p</tt>.
      */
    public void setLocation( Point p ) {
        this.x = p.x;
        this.y = p.y;
    }

    /** Return the location of this Node as a Point.
      */
    public Point getLocation() {
        return new Point((int)x,(int)y);
    }

    /** Set the visibility of this Node to the boolean <tt>v</tt>.
      */
    public void setVisible( boolean v) {
        visible = v;
    }

    /** Return the visibility of this Node as a boolean.
      */
    public boolean isVisible() {
        return visible;
    }

    /** Set the type of this Node to the int <tt>type</tt>.
      * @see TYPE_RECTANGLE
      * @see TYPE_ROUNDRECT
      * @see TYPE_ELLIPSE
      * @see TYPE_CIRCLE
      */

    public void setType( int type ) {
        typ = type;
    }

    /** Return the type of this Node as an int.
      * @see TYPE_RECTANGLE
      * @see TYPE_ROUNDRECT
      * @see TYPE_ELLIPSE
      * @see TYPE_CIRCLE
      */
    public int getType() {
        return typ;
    }

    /** Set the font of this Node to the Font <tt>font</tt>. */
    public void setFont( Font font ) {
        this.font = font;
    }

    /** Returns the font of this Node as a Font*/
    public Font getFont() {
        return font;
    }

    /** Set the background color of this Node to the Color <tt>bgColor</tt>. */
    public void setBackColor( Color bgColor ) {
        backColor = bgColor;
    }

   /** Return the background color of this Node as a Color.
     */
    public Color getBackColor() {
        return backColor;
    }

    /** Set the text color of this Node to the Color <tt>txtColor</tt>. */
    public void setTextColor( Color txtColor ) {
        textColor = txtColor;
    }

   /** Return the text color of this Node as a Color.
     */
    public Color getTextColor() {
        return textColor;
    }

   /** Set the label of this Node to the String <tt>label</tt>. */
    public void setLabel( String label ) {
        lbl = label;
    }

   /** Return the label of this Node as a String.
     */
    public String getLabel() {
        return lbl;
    }

   /** Set the fixed status of this Node to the boolean <tt>fixed</tt>. */
    public void setFixed( boolean fixed ) {
        this.fixed = fixed;
    }

   /** Returns true if this Node is fixed (in place).
     */
    public boolean getFixed() {
        return fixed;
    }

    // ....

    /** Return the number of Edges in the cumulative Vector.
      * @deprecated        this method has been replaced by the <tt>edgeCount()</tt> method.
      */
    public int edgeNum() {
        return edges.size();
    }

    /** Return the number of Edges in the cumulative Vector. */
    public int edgeCount() {
        return edges.size();
    }

    /** Return an iterator over the Edges in the cumulative Vector, null if it is empty. */
    public Iterator getEdges() {
        if ( edges.size() == 0 ) return null;
        else return edges.iterator();
    }

    /** Returns the local Edge count. */
    public int visibleEdgeCount() {
        return visibleEdgeCnt;
    }

    /** Return the Edge at int <tt>index</tt>. */
    public Edge edgeAt( int index ) {
        return (Edge)edges.elementAt(index);
    }

    /** Add the Edge <tt>edge</tt> to the graph. */
    public void addEdge( Edge edge ) {
        if ( edge == null ) return;
        edges.addElement(edge);
    }

    /** Remove the Edge <tt>edge</tt> from the graph. */
    public void removeEdge( Edge edge ) {
        edges.removeElement(edge);
    }

    /** Return the width of this Node. */
    public int getWidth() {
        if ( fontMetrics != null && lbl != null ) {
            return fontMetrics.stringWidth(lbl) + 12;
        } else {
            return 10;
        }
    }

    /** Return the height of this Node. */
    public int getHeight() {
        if ( fontMetrics != null ) {
            return fontMetrics.getHeight() + 6;
        } else {
            return 6;
        }
    }

    /** Returns true if this Node intersects Dimension <tt>d</tt>. */
    public boolean intersects( Dimension d ) {
        return ( drawx > 0 && drawx < d.width && drawy>0 && drawy < d.height );
    }

    /** Returns true if this Node contains the Point <tt>px,py</tt>. */
    public boolean containsPoint( double px, double py ) {
        return (( px > drawx-getWidth()/2) && ( px < drawx+getWidth()/2)
                && ( py > drawy-getHeight()/2) && ( py < drawy+getHeight()/2));
    }

    /** Returns true if this Node contains the Point <tt>p</tt>. */
    public boolean containsPoint( Point p ) {
        return (( p.x > drawx-getWidth()/2) && ( p.x < drawx+getWidth()/2)
                && ( p.y > drawy-getHeight()/2) && ( p.y < drawy+getHeight()/2));
    }

    /** Paints the Node. */
    public void paint( Graphics g, TGPanel tgPanel ) {
        if (!intersects(tgPanel.getSize()) ) return;
        paintNodeBody(g, tgPanel);

        if ( visibleEdgeCount()<edgeCount() ) {
            int ix = (int)drawx;
            int iy = (int)drawy;
            int h = getHeight();
            int w = getWidth();
            int tagX = ix+(w-7)/2-2+w%2;
            int tagY = iy-h/2-2;
            char character;
            int hiddenEdgeCount = edgeCount()-visibleEdgeCount();
            character = (hiddenEdgeCount<9) ? (char) ('0' + hiddenEdgeCount) : '*';
            paintSmallTag(g, tgPanel, tagX, tagY, Color.red, Color.white, character);
        }
    }

    public Color getPaintBorderColor(TGPanel tgPanel) {
        if (this == tgPanel.getDragNode()) return BORDER_DRAG_COLOR;
        else if (this == tgPanel.getMouseOverN()) return BORDER_MOUSE_OVER_COLOR;
        else return BORDER_INACTIVE_COLOR;
    }

    public Color getPaintBackColor(TGPanel tgPanel) {
        if ( this == tgPanel.getSelect() ) {
            return BACK_SELECT_COLOR;
        } else {
            if (fixed) return BACK_FIXED_COLOR;
            if (markedForRemoval) return new Color(100,60,40);
            if (justMadeLocal) return new Color(255,220,200);
            return backColor;
        }
    }

    public Color getPaintTextColor(TGPanel tgPanel) {
        return textColor;
    }

    /** Paints the background of the node, along with its label */
    public void paintNodeBody( Graphics g, TGPanel tgPanel) {
        g.setFont(font);
        fontMetrics = g.getFontMetrics();

        int ix = (int)drawx;
        int iy = (int)drawy;
        int h = getHeight();
        int w = getWidth();
        int r = h/2+1; // arc radius

        Color borderCol = getPaintBorderColor(tgPanel);
        g.setColor(borderCol);

        if ( typ == TYPE_ROUNDRECT ) {
            g.fillRoundRect(ix - w/2, iy - h / 2, w, h, r, r);
        } else if ( typ == TYPE_ELLIPSE ) {
            g.fillOval(ix - w/2, iy - h / 2, w, h );
        } else if ( typ == TYPE_CIRCLE ) { // just use width for both dimensions
            g.fillOval(ix - w/2, iy - w / 2, w, w );
        } else { // TYPE_RECTANGLE
            g.fillRect(ix - w/2, iy - h / 2, w, h);
        }

        Color backCol = getPaintBackColor(tgPanel);
        g.setColor(backCol);

        if ( typ == TYPE_ROUNDRECT ) {
            g.fillRoundRect(ix - w/2+2, iy - h / 2+2, w-4, h-4, r, r );
        } else if ( typ == TYPE_ELLIPSE ) {
            g.fillOval(ix - w/2+2, iy - h / 2+2, w-4, h-4 );
        } else if ( typ == TYPE_CIRCLE ) {
            g.fillOval(ix - w/2+2, iy - w / 2+2, w-4, w-4 );
        } else { // TYPE_RECTANGLE
            g.fillRect(ix - w/2+2, iy - h / 2+2, w-4, h-4);
        }

        Color textCol = getPaintTextColor(tgPanel);
        g.setColor(textCol);
        g.drawString(lbl, ix - fontMetrics.stringWidth(lbl)/2, iy + fontMetrics.getDescent() +1);
    }

    /** Paints a tag with containing a character in a small font. */
    public void paintSmallTag(Graphics g, TGPanel tgPanel, int tagX, int tagY,
                              Color backCol, Color textCol, char character) {
        g.setColor(backCol);
        g.fillRect(tagX, tagY, 8, 8);
        g.setColor(textCol);
        g.setFont(SMALL_TAG_FONT);
        g.drawString(""+character, tagX+2, tagY+7);
    }

} // end com.touchgraph.graphlayout.Node


text:
/*
 * - Principles of Operation -
 *
 * The CrystalHD decoder operates at the bitstream level - which is an even
 * higher level than the decoding hardware you typically see in modern GPUs.
 * This means it has a very simple interface, in principle. You feed demuxed
 * packets in one end and get decoded picture (fields/frames) out the other.
 *
 * Of course, nothing is ever that simple. Due, at the very least, to b-frame
 * dependencies in the supported formats, the hardware has a delay between
 * when a packet goes in, and when a picture comes out. Furthermore, this delay
 * is not just a function of time, but also one of the dependency on additional
 * frames being fed into the decoder to satisfy the b-frame dependencies.
 *
 * As such, a pipeline will build up that is roughly equivalent to the required
 * DPB for the file being played. If that was all it took, things would still
 * be simple - so, of course, it isn't.
 *
 * The hardware has a way of indicating that a picture is ready to be copied out,
 * but this is unreliable - and sometimes the attempt will still fail so, based
 * on testing, the code will wait until 3 pictures are ready before starting
 * to copy out - and this has the effect of extending the pipeline.
 *
 * Finally, while it is tempting to say that once the decoder starts outputting
 * frames, the software should never fail to return a frame from a decode(),
 * this is a hard assertion to make, because the stream may switch between
 * differently encoded content (number of b-frames, interlacing, etc) which
 * might require a longer pipeline than before. If that happened, you could
 * deadlock trying to retrieve a frame that can't be decoded without feeding
 * in additional packets.
 *
 * As such, the code will return in the event that a picture cannot be copied
 * out, leading to an increase in the length of the pipeline. This in turn,
 * means we have to be sensitive to the time it takes to decode a picture;
 * We do not want to give up just because the hardware needed a little more
 * time to prepare the picture! For this reason, there are delays included
 * in the decode() path that ensure that, under normal conditions, the hardware
 * will only fail to return a frame if it really needs additional packets to
 * complete the decoding.
 *
 * Finally, to be explicit, we do not want the pipeline to grow without bound
 * for two reasons: 1) The hardware can only buffer a finite number of packets,
 * and 2) The client application may not be able to cope with arbitrarily long
 * delays in the video path relative to the audio path. For example. MPlayer
 * can only handle a 20 picture delay (although this is arbitrary, and needs
 * to be extended to fully support the CrystalHD where the delay could be up
 * to 32 pictures - consider PAFF H.264 content with 16 b-frames).
 */

/*****************************************************************************
 * Includes
 ****************************************************************************/

#define _XOPEN_SOURCE 600
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <libcrystalhd/bc_dts_types.h>
#include <libcrystalhd/bc_dts_defs.h>
#include <libcrystalhd/libcrystalhd_if.h>

#include "avcodec.h"
#include "h264.h"
#include "libavutil/imgutils.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/opt.h"

/** Timeout parameter passed to DtsProcOutput() in us */
#define OUTPUT_PROC_TIMEOUT 50
/** Step between fake timestamps passed to hardware in units of 100ns */
#define TIMESTAMP_UNIT 100000
/** Initial value in us of the wait in decode() */
#define BASE_WAIT 10000
/** Increment in us to adjust wait in decode() */
#define WAIT_UNIT 1000

/*****************************************************************************
 * Module private data
 ****************************************************************************/

typedef enum {
    RET_ERROR           = -1,
    RET_OK              = 0,
    RET_COPY_AGAIN      = 1,
    RET_SKIP_NEXT_COPY  = 2,
    RET_COPY_NEXT_FIELD = 3,
} CopyRet;

typedef struct OpaqueList {
    struct OpaqueList *next;
    uint64_t fake_timestamp;
    uint64_t reordered_opaque;
    uint8_t pic_type;
} OpaqueList;

typedef struct {
    AVClass *av_class;
    AVCodecContext *avctx;
    AVFrame pic;
    HANDLE dev;

    uint8_t *orig_extradata;
    uint32_t orig_extradata_size;

    AVBitStreamFilterContext *bsfc;
    AVCodecParserContext *parser;

    uint8_t is_70012;
    uint8_t *sps_pps_buf;
    uint32_t sps_pps_size;
    uint8_t is_nal;
    uint8_t output_ready;
    uint8_t need_second_field;
    uint8_t skip_next_output;
    uint64_t decode_wait;

    uint64_t last_picture;

    OpaqueList *head;
    OpaqueList *tail;

    /* Options */
    uint32_t sWidth;
    uint8_t bframe_bug;
} CHDContext;

static const AVOption options[] = {
    { "crystalhd_downscale_width",
      "Turn on downscaling to the specified width",
      offsetof(CHDContext, sWidth),
      AV_OPT_TYPE_INT, 0, 0, UINT32_MAX,
      AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM, },
    { NULL, },
};

/*****************************************************************************
 * Helper functions
 ****************************************************************************/

static inline BC_MEDIA_SUBTYPE id2subtype(CHDContext *priv, enum AVCodecID id)
{
    switch (id) {
    case AV_CODEC_ID_MPEG4:
        return BC_MSUBTYPE_DIVX;
    case AV_CODEC_ID_MSMPEG4V3:
        return BC_MSUBTYPE_DIVX311;
    case AV_CODEC_ID_MPEG2VIDEO:
        return BC_MSUBTYPE_MPEG2VIDEO;
    case AV_CODEC_ID_VC1:
        return BC_MSUBTYPE_VC1;
    case AV_CODEC_ID_WMV3:
        return BC_MSUBTYPE_WMV3;
    case AV_CODEC_ID_H264:
        return priv->is_nal ? BC_MSUBTYPE_AVC1 : BC_MSUBTYPE_H264;
    default:
        return BC_MSUBTYPE_INVALID;
    }
}

static inline void print_frame_info(CHDContext *priv, BC_DTS_PROC_OUT *output)
{
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffSz: %u\n", output->YbuffSz);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tYBuffDoneSz: %u\n",
           output->YBuffDoneSz);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tUVBuffDoneSz: %u\n",
           output->UVBuffDoneSz);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tTimestamp: %"PRIu64"\n",
           output->PicInfo.timeStamp);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tPicture Number: %u\n",
           output->PicInfo.picture_number);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tWidth: %u\n",
           output->PicInfo.width);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tHeight: %u\n",
           output->PicInfo.height);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tChroma: 0x%03x\n",
           output->PicInfo.chroma_format);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tPulldown: %u\n",
           output->PicInfo.pulldown);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tFlags: 0x%08x\n",
           output->PicInfo.flags);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrame Rate/Res: %u\n",
           output->PicInfo.frame_rate);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tAspect Ratio: %u\n",
           output->PicInfo.aspect_ratio);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tColor Primaries: %u\n",
           output->PicInfo.colour_primaries);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tMetaData: %u\n",
           output->PicInfo.picture_meta_payload);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tSession Number: %u\n",
           output->PicInfo.sess_num);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tycom: %u\n",
           output->PicInfo.ycom);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tCustom Aspect: %u\n",
           output->PicInfo.custom_aspect_ratio_width_height);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tFrames to Drop: %u\n",
           output->PicInfo.n_drop);
    av_log(priv->avctx, AV_LOG_VERBOSE, "\tH264 Valid Fields: 0x%08x\n",
           output->PicInfo.other.h264.valid);
}

/*****************************************************************************
 * OpaqueList functions
 ****************************************************************************/

static uint64_t opaque_list_push(CHDContext *priv, uint64_t reordered_opaque,
                                 uint8_t pic_type)
{
    OpaqueList *newNode = av_mallocz(sizeof (OpaqueList));
    if (!newNode) {
        av_log(priv->avctx, AV_LOG_ERROR,
               "Unable to allocate new node in OpaqueList.\n");
        return 0;
    }
    if (!priv->head) {
        newNode->fake_timestamp = TIMESTAMP_UNIT;
        priv->head              = newNode;
    } else {
        newNode->fake_timestamp = priv->tail->fake_timestamp + TIMESTAMP_UNIT;
        priv->tail->next        = newNode;
    }
    priv->tail = newNode;
    newNode->reordered_opaque = reordered_opaque;
    newNode->pic_type = pic_type;

    return newNode->fake_timestamp;
}

/*
 * The OpaqueList is built in decode order, while elements will be removed
 * in presentation order. If frames are reordered, this means we must be
 * able to remove elements that are not the first element.
 *
 * Returned node must be freed by caller.
 */
static OpaqueList *opaque_list_pop(CHDContext *priv, uint64_t fake_timestamp)
{
    OpaqueList *node = priv->head;

    if (!priv->head) {
        av_log(priv->avctx, AV_LOG_ERROR,
               "CrystalHD: Attempted to query non-existent timestamps.\n");
        return NULL;
    }

    /*
     * The first element is special-cased because we have to manipulate
     * the head pointer rather than the previous element in the list.
     */
    if (priv->head->fake_timestamp == fake_timestamp) {
        priv->head = node->next;

        if (!priv->head->next)
            priv->tail = priv->head;

        node->next = NULL;
        return node;
    }

    /*
     * The list is processed at arm's length so that we have the
     * previous element available to rewrite its next pointer.
     */
    while (node->next) {
        OpaqueList *current = node->next;
        if (current->fake_timestamp == fake_timestamp) {
            node->next = current->next;

            if (!node->next)
               priv->tail = node;

            current->next = NULL;
            return current;
        } else {
            node = current;
        }
    }

    av_log(priv->avctx, AV_LOG_VERBOSE,
           "CrystalHD: Couldn't match fake_timestamp.\n");
    return NULL;
}

/*****************************************************************************
 * Video decoder API function definitions
 ****************************************************************************/

static void flush(AVCodecContext *avctx)
{
    CHDContext *priv = avctx->priv_data;

    avctx->has_b_frames     = 0;
    priv->last_picture      = -1;
    priv->output_ready      = 0;
    priv->need_second_field = 0;
    priv->skip_next_output  = 0;
    priv->decode_wait       = BASE_WAIT;

    if (priv->pic.data[0])
        avctx->release_buffer(avctx, &priv->pic);

    /* Flush mode 4 flushes all software and hardware buffers. */
    DtsFlushInput(priv->dev, 4);
}

static av_cold int uninit(AVCodecContext *avctx)
{
    CHDContext *priv = avctx->priv_data;
    HANDLE device;

    device = priv->dev;
    DtsStopDecoder(device);
    DtsCloseDecoder(device);
    DtsDeviceClose(device);

    /*
     * Restore original extradata, so that if the decoder is
     * reinitialised, the bitstream detection and filtering
     * will work as expected.
     */
    if (priv->orig_extradata) {
        av_free(avctx->extradata);
        avctx->extradata = priv->orig_extradata;
        avctx->extradata_size = priv->orig_extradata_size;
        priv->orig_extradata = NULL;
        priv->orig_extradata_size = 0;
    }

    av_parser_close(priv->parser);
    if (priv->bsfc) {
        av_bitstream_filter_close(priv->bsfc);
    }

    av_free(priv->sps_pps_buf);

    if (priv->pic.data[0])
        avctx->release_buffer(avctx, &priv->pic);

    if (priv->head) {
       OpaqueList *node = priv->head;
       while (node) {
          OpaqueList *next = node->next;
          av_free(node);
          node = next;
       }
    }

    return 0;
}

static av_cold int init(AVCodecContext *avctx)
{
    CHDContext* priv;
    BC_STATUS ret;
    BC_INFO_CRYSTAL version;
    BC_INPUT_FORMAT format = {
        .FGTEnable   = FALSE,
        .Progressive = TRUE,
        .OptFlags    = 0x80000000 | vdecFrameRate59_94 | 0x40,
        .width       = avctx->width,
        .height      = avctx->height,
    };

    BC_MEDIA_SUBTYPE subtype;

    uint32_t mode = DTS_PLAYBACK_MODE |
                    DTS_LOAD_FILE_PLAY_FW |
                    DTS_SKIP_TX_CHK_CPB |
                    DTS_PLAYBACK_DROP_RPT_MODE |
                    DTS_SINGLE_THREADED_MODE |
                    DTS_DFLT_RESOLUTION(vdecRESOLUTION_1080p23_976);

    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD Init for %s\n",
           avctx->codec->name);

    avctx->pix_fmt = PIX_FMT_YUYV422;

    /* Initialize the library */
    priv               = avctx->priv_data;
    priv->avctx        = avctx;
    priv->is_nal       = avctx->extradata_size > 0 && *(avctx->extradata) == 1;
    priv->last_picture = -1;
    priv->decode_wait  = BASE_WAIT;

    subtype = id2subtype(priv, avctx->codec->id);
    switch (subtype) {
    case BC_MSUBTYPE_AVC1:
        {
            uint8_t *dummy_p;
            int dummy_int;

            /* Back up the extradata so it can be restored at close time. */
            priv->orig_extradata = av_malloc(avctx->extradata_size);
            if (!priv->orig_extradata) {
                av_log(avctx, AV_LOG_ERROR,
                       "Failed to allocate copy of extradata\n");
                return AVERROR(ENOMEM);
            }
            priv->orig_extradata_size = avctx->extradata_size;
            memcpy(priv->orig_extradata, avctx->extradata, avctx->extradata_size);

            priv->bsfc = av_bitstream_filter_init("h264_mp4toannexb");
            if (!priv->bsfc) {
                av_log(avctx, AV_LOG_ERROR,
                       "Cannot open the h264_mp4toannexb BSF!\n");
                return AVERROR_BSF_NOT_FOUND;
            }
            av_bitstream_filter_filter(priv->bsfc, avctx, NULL, &dummy_p,
                                       &dummy_int, NULL, 0, 0);
        }
        subtype = BC_MSUBTYPE_H264;
        // Fall-through
    case BC_MSUBTYPE_H264:
        format.startCodeSz = 4;
        // Fall-through
    case BC_MSUBTYPE_VC1:
    case BC_MSUBTYPE_WVC1:
    case BC_MSUBTYPE_WMV3:
    case BC_MSUBTYPE_WMVA:
    case BC_MSUBTYPE_MPEG2VIDEO:
    case BC_MSUBTYPE_DIVX:
    case BC_MSUBTYPE_DIVX311:
        format.pMetaData  = avctx->extradata;
        format.metaDataSz = avctx->extradata_size;
        break;
    default:
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: Unknown codec name\n");
        return AVERROR(EINVAL);
    }
    format.mSubtype = subtype;

    if (priv->sWidth) {
        format.bEnableScaling = 1;
        format.ScalingParams.sWidth = priv->sWidth;
    }

    /* Get a decoder instance */
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: starting up\n");
    // Initialize the Link and Decoder devices
    ret = DtsDeviceOpen(&priv->dev, mode);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: DtsDeviceOpen failed\n");
        goto fail;
    }

    ret = DtsCrystalHDVersion(priv->dev, &version);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_VERBOSE,
               "CrystalHD: DtsCrystalHDVersion failed\n");
        goto fail;
    }
    priv->is_70012 = version.device == 0;

    if (priv->is_70012 &&
        (subtype == BC_MSUBTYPE_DIVX || subtype == BC_MSUBTYPE_DIVX311)) {
        av_log(avctx, AV_LOG_VERBOSE,
               "CrystalHD: BCM70012 doesn't support MPEG4-ASP/DivX/Xvid\n");
        goto fail;
    }

    ret = DtsSetInputFormat(priv->dev, &format);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: SetInputFormat failed\n");
        goto fail;
    }

    ret = DtsOpenDecoder(priv->dev, BC_STREAM_TYPE_ES);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsOpenDecoder failed\n");
        goto fail;
    }

    ret = DtsSetColorSpace(priv->dev, OUTPUT_MODE422_YUY2);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsSetColorSpace failed\n");
        goto fail;
    }
    ret = DtsStartDecoder(priv->dev);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartDecoder failed\n");
        goto fail;
    }
    ret = DtsStartCapture(priv->dev);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: DtsStartCapture failed\n");
        goto fail;
    }

    if (avctx->codec->id == AV_CODEC_ID_H264) {
        priv->parser = av_parser_init(avctx->codec->id);
        if (!priv->parser)
            av_log(avctx, AV_LOG_WARNING,
                   "Cannot open the h.264 parser! Interlaced h.264 content "
                   "will not be detected reliably.\n");
        priv->parser->flags = PARSER_FLAG_COMPLETE_FRAMES;
    }
    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Init complete.\n");

    return 0;

 fail:
    uninit(avctx);
    return -1;
}

static inline CopyRet copy_frame(AVCodecContext *avctx,
                                 BC_DTS_PROC_OUT *output,
                                 void *data, int *data_size)
{
    BC_STATUS ret;
    BC_DTS_STATUS decoder_status = { 0, };
    uint8_t trust_interlaced;
    uint8_t interlaced;

    CHDContext *priv = avctx->priv_data;
    int64_t pkt_pts  = AV_NOPTS_VALUE;
    uint8_t pic_type = 0;

    uint8_t bottom_field = (output->PicInfo.flags & VDEC_FLAG_BOTTOMFIELD) ==
                           VDEC_FLAG_BOTTOMFIELD;
    uint8_t bottom_first = !!(output->PicInfo.flags & VDEC_FLAG_BOTTOM_FIRST);

    int width    = output->PicInfo.width;
    int height   = output->PicInfo.height;
    int bwidth;
    uint8_t *src = output->Ybuff;
    int sStride;
    uint8_t *dst;
    int dStride;

    if (output->PicInfo.timeStamp != 0) {
        OpaqueList *node = opaque_list_pop(priv, output->PicInfo.timeStamp);
        if (node) {
            pkt_pts = node->reordered_opaque;
            pic_type = node->pic_type;
            av_free(node);
        } else {
            /*
             * We will encounter a situation where a timestamp cannot be
             * popped if a second field is being returned. In this case,
             * each field has the same timestamp and the first one will
             * cause it to be popped. To keep subsequent calculations
             * simple, pic_type should be set a FIELD value - doesn't
             * matter which, but I chose BOTTOM.
             */
            pic_type = PICT_BOTTOM_FIELD;
        }
        av_log(avctx, AV_LOG_VERBOSE, "output \"pts\": %"PRIu64"\n",
               output->PicInfo.timeStamp);
        av_log(avctx, AV_LOG_VERBOSE, "output picture type %d\n",
               pic_type);
    }

    ret = DtsGetDriverStatus(priv->dev, &decoder_status);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR,
               "CrystalHD: GetDriverStatus failed: %u\n", ret);
       return RET_ERROR;
    }

    /*
     * For most content, we can trust the interlaced flag returned
     * by the hardware, but sometimes we can't. These are the
     * conditions under which we can trust the flag:
     *
     * 1) It's not h.264 content
     * 2) The UNKNOWN_SRC flag is not set
     * 3) We know we're expecting a second field
     * 4) The hardware reports this picture and the next picture
     *    have the same picture number.
     *
     * Note that there can still be interlaced content that will
     * fail this check, if the hardware hasn't decoded the next
     * picture or if there is a corruption in the stream. (In either
     * case a 0 will be returned for the next picture number)
     */
    trust_interlaced = avctx->codec->id != AV_CODEC_ID_H264 ||
                       !(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
                       priv->need_second_field ||
                       (decoder_status.picNumFlags & ~0x40000000) ==
                       output->PicInfo.picture_number;

    /*
     * If we got a false negative for trust_interlaced on the first field,
     * we will realise our mistake here when we see that the picture number is that
     * of the previous picture. We cannot recover the frame and should discard the
     * second field to keep the correct number of output frames.
     */
    if (output->PicInfo.picture_number == priv->last_picture && !priv->need_second_field) {
        av_log(avctx, AV_LOG_WARNING,
               "Incorrectly guessed progressive frame. Discarding second field\n");
        /* Returning without providing a picture. */
        return RET_OK;
    }

    interlaced = (output->PicInfo.flags & VDEC_FLAG_INTERLACED_SRC) &&
                 trust_interlaced;

    if (!trust_interlaced && (decoder_status.picNumFlags & ~0x40000000) == 0) {
        av_log(avctx, AV_LOG_VERBOSE,
               "Next picture number unknown. Assuming progressive frame.\n");
    }

    av_log(avctx, AV_LOG_VERBOSE, "Interlaced state: %d | trust_interlaced %d\n",
           interlaced, trust_interlaced);

    if (priv->pic.data[0] && !priv->need_second_field)
        avctx->release_buffer(avctx, &priv->pic);

    priv->need_second_field = interlaced && !priv->need_second_field;

    priv->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE |
                             FF_BUFFER_HINTS_REUSABLE;
    if (!priv->pic.data[0]) {
        if (avctx->get_buffer(avctx, &priv->pic) < 0) {
            av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
            return RET_ERROR;
        }
    }

    bwidth = av_image_get_linesize(avctx->pix_fmt, width, 0);
    if (priv->is_70012) {
        int pStride;

        if (width <= 720)
            pStride = 720;
        else if (width <= 1280)
            pStride = 1280;
        else pStride = 1920;
        sStride = av_image_get_linesize(avctx->pix_fmt, pStride, 0);
    } else {
        sStride = bwidth;
    }

    dStride = priv->pic.linesize[0];
    dst     = priv->pic.data[0];

    av_log(priv->avctx, AV_LOG_VERBOSE, "CrystalHD: Copying out frame\n");

    if (interlaced) {
        int dY = 0;
        int sY = 0;

        height /= 2;
        if (bottom_field) {
            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: bottom field\n");
            dY = 1;
        } else {
            av_log(priv->avctx, AV_LOG_VERBOSE, "Interlaced: top field\n");
            dY = 0;
        }

        for (sY = 0; sY < height; dY++, sY++) {
            memcpy(&(dst[dY * dStride]), &(src[sY * sStride]), bwidth);
            dY++;
        }
    } else {
        av_image_copy_plane(dst, dStride, src, sStride, bwidth, height);
    }

    priv->pic.interlaced_frame = interlaced;
    if (interlaced)
        priv->pic.top_field_first = !bottom_first;

    priv->pic.pkt_pts = pkt_pts;

    if (!priv->need_second_field) {
        *data_size       = sizeof(AVFrame);
        *(AVFrame *)data = priv->pic;
    }

    /*
     * Two types of PAFF content have been observed. One form causes the
     * hardware to return a field pair and the other individual fields,
     * even though the input is always individual fields. We must skip
     * copying on the next decode() call to maintain pipeline length in
     * the first case.
     */
    if (!interlaced && (output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) &&
        (pic_type == PICT_TOP_FIELD || pic_type == PICT_BOTTOM_FIELD)) {
        av_log(priv->avctx, AV_LOG_VERBOSE, "Fieldpair from two packets.\n");
        return RET_SKIP_NEXT_COPY;
    }

    /*
     * The logic here is purely based on empirical testing with samples.
     * If we need a second field, it could come from a second input packet,
     * or it could come from the same field-pair input packet at the current
     * field. In the first case, we should return and wait for the next time
     * round to get the second field, while in the second case, we should
     * ask the decoder for it immediately.
     *
     * Testing has shown that we are dealing with the fieldpair -> two fields
     * case if the VDEC_FLAG_UNKNOWN_SRC is not set or if the input picture
     * type was PICT_FRAME (in this second case, the flag might still be set)
     */
    return priv->need_second_field &&
           (!(output->PicInfo.flags & VDEC_FLAG_UNKNOWN_SRC) ||
            pic_type == PICT_FRAME) ?
           RET_COPY_NEXT_FIELD : RET_OK;
}

static inline CopyRet receive_frame(AVCodecContext *avctx,
                                    void *data, int *data_size)
{
    BC_STATUS ret;
    BC_DTS_PROC_OUT output = {
        .PicInfo.width  = avctx->width,
        .PicInfo.height = avctx->height,
    };
    CHDContext *priv = avctx->priv_data;
    HANDLE dev       = priv->dev;

    *data_size = 0;

    // Request decoded data from the driver
    ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);
    if (ret == BC_STS_FMT_CHANGE) {
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");
        avctx->width  = output.PicInfo.width;
        avctx->height = output.PicInfo.height;
        switch ( output.PicInfo.aspect_ratio ) {
        case vdecAspectRatioSquare:
            avctx->sample_aspect_ratio = (AVRational) {  1,  1};
            break;
        case vdecAspectRatio12_11:
            avctx->sample_aspect_ratio = (AVRational) { 12, 11};
            break;
        case vdecAspectRatio10_11:
            avctx->sample_aspect_ratio = (AVRational) { 10, 11};
            break;
        case vdecAspectRatio16_11:
            avctx->sample_aspect_ratio = (AVRational) { 16, 11};
            break;
        case vdecAspectRatio40_33:
            avctx->sample_aspect_ratio = (AVRational) { 40, 33};
            break;
        case vdecAspectRatio24_11:
            avctx->sample_aspect_ratio = (AVRational) { 24, 11};
            break;
        case vdecAspectRatio20_11:
            avctx->sample_aspect_ratio = (AVRational) { 20, 11};
            break;
        case vdecAspectRatio32_11:
            avctx->sample_aspect_ratio = (AVRational) { 32, 11};
            break;
        case vdecAspectRatio80_33:
            avctx->sample_aspect_ratio = (AVRational) { 80, 33};
            break;
        case vdecAspectRatio18_11:
            avctx->sample_aspect_ratio = (AVRational) { 18, 11};
            break;
        case vdecAspectRatio15_11:
            avctx->sample_aspect_ratio = (AVRational) { 15, 11};
            break;
        case vdecAspectRatio64_33:
            avctx->sample_aspect_ratio = (AVRational) { 64, 33};
            break;
        case vdecAspectRatio160_99:
            avctx->sample_aspect_ratio = (AVRational) {160, 99};
            break;
        case vdecAspectRatio4_3:
            avctx->sample_aspect_ratio = (AVRational) {  4,  3};
            break;
        case vdecAspectRatio16_9:
            avctx->sample_aspect_ratio = (AVRational) { 16,  9};
            break;
        case vdecAspectRatio221_1:
            avctx->sample_aspect_ratio = (AVRational) {221,  1};
            break;
        }
        return RET_COPY_AGAIN;
    } else if (ret == BC_STS_SUCCESS) {
        int copy_ret = -1;
        if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {
            if (priv->last_picture == -1) {
                /*
                 * Init to one less, so that the incrementing code doesn't
                 * need to be special-cased.
                 */
                priv->last_picture = output.PicInfo.picture_number - 1;
            }

            if (avctx->codec->id == AV_CODEC_ID_MPEG4 &&
                output.PicInfo.timeStamp == 0 && priv->bframe_bug) {
                av_log(avctx, AV_LOG_VERBOSE,
                       "CrystalHD: Not returning packed frame twice.\n");
                priv->last_picture++;
                DtsReleaseOutputBuffs(dev, NULL, FALSE);
                return RET_COPY_AGAIN;
            }

            print_frame_info(priv, &output);

            if (priv->last_picture + 1 < output.PicInfo.picture_number) {
                av_log(avctx, AV_LOG_WARNING,
                       "CrystalHD: Picture Number discontinuity\n");
                /*
                 * Have we lost frames? If so, we need to shrink the
                 * pipeline length appropriately.
                 *
                 * XXX: I have no idea what the semantics of this situation
                 * are so I don't even know if we've lost frames or which
                 * ones.
                 *
                 * In any case, only warn the first time.
                 */
               priv->last_picture = output.PicInfo.picture_number - 1;
            }

            copy_ret = copy_frame(avctx, &output, data, data_size);
            if (*data_size > 0) {
                avctx->has_b_frames--;
                priv->last_picture++;
                av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",
                       avctx->has_b_frames);
            }
        } else {
            /*
             * An invalid frame has been consumed.
             */
            av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "
                                        "invalid PIB\n");
            avctx->has_b_frames--;
            copy_ret = RET_OK;
        }
        DtsReleaseOutputBuffs(dev, NULL, FALSE);

        return copy_ret;
    } else if (ret == BC_STS_BUSY) {
        return RET_COPY_AGAIN;
    } else {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);
        return RET_ERROR;
    }
}

static int decode(AVCodecContext *avctx, void *data, int *data_size, AVPacket *avpkt)
{
    BC_STATUS ret;
    BC_DTS_STATUS decoder_status = { 0, };
    CopyRet rec_ret;
    CHDContext *priv   = avctx->priv_data;
    HANDLE dev         = priv->dev;
    uint8_t *in_data   = avpkt->data;
    int len            = avpkt->size;
    int free_data      = 0;
    uint8_t pic_type   = 0;

    av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: decode_frame\n");

    if (avpkt->size == 7 && !priv->bframe_bug) {
        /*
         * The use of a drop frame triggers the bug
         */
        av_log(avctx, AV_LOG_INFO,
               "CrystalHD: Enabling work-around for packed b-frame bug\n");
        priv->bframe_bug = 1;
    } else if (avpkt->size == 8 && priv->bframe_bug) {
        /*
         * Delay frames don't trigger the bug
         */
        av_log(avctx, AV_LOG_INFO,
               "CrystalHD: Disabling work-around for packed b-frame bug\n");
        priv->bframe_bug = 0;
    }

    if (len) {
        int32_t tx_free = (int32_t)DtsTxFreeSize(dev);

        if (priv->parser) {
            int ret = 0;

            if (priv->bsfc) {
                ret = av_bitstream_filter_filter(priv->bsfc, avctx, NULL,
                                                 &in_data, &len,
                                                 avpkt->data, len, 0);
            }
            free_data = ret > 0;

            if (ret >= 0) {
                uint8_t *pout;
                int psize;
                int index;
                H264Context *h = priv->parser->priv_data;

                index = av_parser_parse2(priv->parser, avctx, &pout, &psize,
                                         in_data, len, avctx->pkt->pts,
                                         avctx->pkt->dts, 0);
                if (index < 0) {
                    av_log(avctx, AV_LOG_WARNING,
                           "CrystalHD: Failed to parse h.264 packet to "
                           "detect interlacing.\n");
                } else if (index != len) {
                    av_log(avctx, AV_LOG_WARNING,
                           "CrystalHD: Failed to parse h.264 packet "
                           "completely. Interlaced frames may be "
                           "incorrectly detected.\n");
                } else {
                    av_log(avctx, AV_LOG_VERBOSE,
                           "CrystalHD: parser picture type %d\n",
                           h->s.picture_structure);
                    pic_type = h->s.picture_structure;
                }
            } else {
                av_log(avctx, AV_LOG_WARNING,
                       "CrystalHD: mp4toannexb filter failed to filter "
                       "packet. Interlaced frames may be incorrectly "
                       "detected.\n");
            }
        }

        if (len < tx_free - 1024) {
            /*
             * Despite being notionally opaque, either libcrystalhd or
             * the hardware itself will mangle pts values that are too
             * small or too large. The docs claim it should be in units
             * of 100ns. Given that we're nominally dealing with a black
             * box on both sides, any transform we do has no guarantee of
             * avoiding mangling so we need to build a mapping to values
             * we know will not be mangled.
             */
            uint64_t pts = opaque_list_push(priv, avctx->pkt->pts, pic_type);
            if (!pts) {
                if (free_data) {
                    av_freep(&in_data);
                }
                return AVERROR(ENOMEM);
            }
            av_log(priv->avctx, AV_LOG_VERBOSE,
                   "input \"pts\": %"PRIu64"\n", pts);
            ret = DtsProcInput(dev, in_data, len, pts, 0);
            if (free_data) {
                av_freep(&in_data);
            }
            if (ret == BC_STS_BUSY) {
                av_log(avctx, AV_LOG_WARNING,
                       "CrystalHD: ProcInput returned busy\n");
                usleep(BASE_WAIT);
                return AVERROR(EBUSY);
            } else if (ret != BC_STS_SUCCESS) {
                av_log(avctx, AV_LOG_ERROR,
                       "CrystalHD: ProcInput failed: %u\n", ret);
                return -1;
            }
            avctx->has_b_frames++;
        } else {
            av_log(avctx, AV_LOG_WARNING, "CrystalHD: Input buffer full\n");
            len = 0; // We didn't consume any bytes.
        }
    } else {
        av_log(avctx, AV_LOG_INFO, "CrystalHD: No more input data\n");
    }

    if (priv->skip_next_output) {
        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Skipping next output.\n");
        priv->skip_next_output = 0;
        avctx->has_b_frames--;
        return len;
    }

    ret = DtsGetDriverStatus(dev, &decoder_status);
    if (ret != BC_STS_SUCCESS) {
        av_log(avctx, AV_LOG_ERROR, "CrystalHD: GetDriverStatus failed\n");
        return -1;
    }

    /*
     * No frames ready. Don't try to extract.
     *
     * Empirical testing shows that ReadyListCount can be a damn lie,
     * and ProcOut still fails when count > 0. The same testing showed
     * that two more iterations were needed before ProcOutput would
     * succeed.
     */
    if (priv->output_ready < 2) {
        if (decoder_status.ReadyListCount != 0)
            priv->output_ready++;
        usleep(BASE_WAIT);
        av_log(avctx, AV_LOG_INFO, "CrystalHD: Filling pipeline.\n");
        return len;
    } else if (decoder_status.ReadyListCount == 0) {
        /*
         * After the pipeline is established, if we encounter a lack of frames
         * that probably means we're not giving the hardware enough time to
         * decode them, so start increasing the wait time at the end of a
         * decode call.
         */
        usleep(BASE_WAIT);
        priv->decode_wait += WAIT_UNIT;
        av_log(avctx, AV_LOG_INFO, "CrystalHD: No frames ready. Returning\n");
        return len;
    }

    do {
        rec_ret = receive_frame(avctx, data, data_size);
        if (rec_ret == RET_OK && *data_size == 0) {
            /*
             * This case is for when the encoded fields are stored
             * separately and we get a separate avpkt for each one. To keep
             * the pipeline stable, we should return nothing and wait for
             * the next time round to grab the second field.
             * H.264 PAFF is an example of this.
             */
            av_log(avctx, AV_LOG_VERBOSE, "Returning after first field.\n");
            avctx->has_b_frames--;
        } else if (rec_ret == RET_COPY_NEXT_FIELD) {
            /*
             * This case is for when the encoded fields are stored in a
             * single avpkt but the hardware returns then separately. Unless
             * we grab the second field before returning, we'll slip another
             * frame in the pipeline and if that happens a lot, we're sunk.
             * So we have to get that second field now.
             * Interlaced mpeg2 and vc1 are examples of this.
             */
            av_log(avctx, AV_LOG_VERBOSE, "Trying to get second field.\n");
            while (1) {
                usleep(priv->decode_wait);
                ret = DtsGetDriverStatus(dev, &decoder_status);
                if (ret == BC_STS_SUCCESS &&
                    decoder_status.ReadyListCount > 0) {
                    rec_ret = receive_frame(avctx, data, data_size);
                    if ((rec_ret == RET_OK && *data_size > 0) ||
                        rec_ret == RET_ERROR)
                        break;
                }
            }
            av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Got second field.\n");
        } else if (rec_ret == RET_SKIP_NEXT_COPY) {
            /*
             * Two input packets got turned into a field pair. Gawd.
             */
            av_log(avctx, AV_LOG_VERBOSE,
                   "Don't output on next decode call.\n");
            priv->skip_next_output = 1;
        }
        /*
         * If rec_ret == RET_COPY_AGAIN, that means that either we just handled
         * a FMT_CHANGE event and need to go around again for the actual frame,
         * we got a busy status and need to try again, or we're dealing with
         * packed b-frames, where the hardware strangely returns the packed
         * p-frame twice. We choose to keep the second copy as it carries the
         * valid pts.
         */
    } while (rec_ret == RET_COPY_AGAIN);
    usleep(priv->decode_wait);
    return len;
}

#if CONFIG_H264_CRYSTALHD_DECODER
static AVClass h264_class = {
    "h264_crystalhd",
    av_default_item_name,
    options,
    LIBAVUTIL_VERSION_INT,
};

AVCodec ff_h264_crystalhd_decoder = {
    .name           = "h264_crystalhd",
    .type           = AVMEDIA_TYPE_VIDEO,
    .id             = AV_CODEC_ID_H264,
    .priv_data_size = sizeof(CHDContext),
    .init           = init,
    .close          = uninit,
    .decode         = decode,
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
    .flush          = flush,
    .long_name      = NULL_IF_CONFIG_SMALL("H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (CrystalHD acceleration)"),
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
    .priv_class     = &h264_class,
};
#endif

#if CONFIG_MPEG2_CRYSTALHD_DECODER
static AVClass mpeg2_class = {
    "mpeg2_crystalhd",
    av_default_item_name,
    options,
    LIBAVUTIL_VERSION_INT,
};

AVCodec ff_mpeg2_crystalhd_decoder = {
    .name           = "mpeg2_crystalhd",
    .type           = AVMEDIA_TYPE_VIDEO,
    .id             = AV_CODEC_ID_MPEG2VIDEO,
    .priv_data_size = sizeof(CHDContext),
    .init           = init,
    .close          = uninit,
    .decode         = decode,
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
    .flush          = flush,
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-2 Video (CrystalHD acceleration)"),
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
    .priv_class     = &mpeg2_class,
};
#endif

#if CONFIG_MPEG4_CRYSTALHD_DECODER
static AVClass mpeg4_class = {
    "mpeg4_crystalhd",
    av_default_item_name,
    options,
    LIBAVUTIL_VERSION_INT,
};

AVCodec ff_mpeg4_crystalhd_decoder = {
    .name           = "mpeg4_crystalhd",
    .type           = AVMEDIA_TYPE_VIDEO,
    .id             = AV_CODEC_ID_MPEG4,
    .priv_data_size = sizeof(CHDContext),
    .init           = init,
    .close          = uninit,
    .decode         = decode,
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
    .flush          = flush,
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 (CrystalHD acceleration)"),
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
    .priv_class     = &mpeg4_class,
};
#endif

#if CONFIG_MSMPEG4_CRYSTALHD_DECODER
static AVClass msmpeg4_class = {
    "msmpeg4_crystalhd",
    av_default_item_name,
    options,
    LIBAVUTIL_VERSION_INT,
};

AVCodec ff_msmpeg4_crystalhd_decoder = {
    .name           = "msmpeg4_crystalhd",
    .type           = AVMEDIA_TYPE_VIDEO,
    .id             = AV_CODEC_ID_MSMPEG4V3,
    .priv_data_size = sizeof(CHDContext),
    .init           = init,
    .close          = uninit,
    .decode         = decode,
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY | CODEC_CAP_EXPERIMENTAL,
    .flush          = flush,
    .long_name      = NULL_IF_CONFIG_SMALL("MPEG-4 Part 2 Microsoft variant version 3 (CrystalHD acceleration)"),
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
    .priv_class     = &msmpeg4_class,
};
#endif

#if CONFIG_VC1_CRYSTALHD_DECODER
static AVClass vc1_class = {
    "vc1_crystalhd",
    av_default_item_name,
    options,
    LIBAVUTIL_VERSION_INT,
};

AVCodec ff_vc1_crystalhd_decoder = {
    .name           = "vc1_crystalhd",
    .type           = AVMEDIA_TYPE_VIDEO,
    .id             = AV_CODEC_ID_VC1,
    .priv_data_size = sizeof(CHDContext),
    .init           = init,
    .close          = uninit,
    .decode         = decode,
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
    .flush          = flush,
    .long_name      = NULL_IF_CONFIG_SMALL("SMPTE VC-1 (CrystalHD acceleration)"),
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
    .priv_class     = &vc1_class,
};
#endif

#if CONFIG_WMV3_CRYSTALHD_DECODER
static AVClass wmv3_class = {
    "wmv3_crystalhd",
    av_default_item_name,
    options,
    LIBAVUTIL_VERSION_INT,
};

AVCodec ff_wmv3_crystalhd_decoder = {
    .name           = "wmv3_crystalhd",
    .type           = AVMEDIA_TYPE_VIDEO,
    .id             = AV_CODEC_ID_WMV3,
    .priv_data_size = sizeof(CHDContext),
    .init           = init,
    .close          = uninit,
    .decode         = decode,
    .capabilities   = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
    .flush          = flush,
    .long_name      = NULL_IF_CONFIG_SMALL("Windows Media Video 9 (CrystalHD acceleration)"),
    .pix_fmts       = (const enum PixelFormat[]){PIX_FMT_YUYV422, PIX_FMT_NONE},
    .priv_class     = &wmv3_class,
};
#endif

redpajama_set_name: RedPajamaGithub


text:
#adminmenu #toplevel_page_bws_plugins div.wp-menu-image {
    background: url("../images/icon_16.png") no-repeat scroll center center transparent;
}
#wpadminbar li#wp-admin-bar-pdfprnt-bar-menu a:hover span.admin-bar-menu-bws-icon {
    background: url("../images/icon_16_c.png") no-repeat scroll center center transparent;
}
#adminmenu #toplevel_page_bws_plugins:hover div.wp-menu-image,
#adminmenu #toplevel_page_bws_plugins.wp-has-current-submenu div.wp-menu-image {
    background: url("../images/icon_16_c.png") no-repeat scroll center center transparent;
}
.wrap #icon-options-general.icon32-bws {
    background: url("../images/icon_36.png") no-repeat scroll left top transparent;
}
#toplevel_page_bws_plugins .wp-submenu .wp-first-item {
    display: none;
}
.bws_info {
    color: #888888;
    font-size: 10px;
}
/*
* styles for rate-support div on the settings page
*/
.bws-plugin-reviews {
    background: none repeat scroll 0 0 #BEE1F1;
    border: 1px solid #70A8C2;
    border-radius: 3px;
    max-width: 700px;
}
.bws-plugin-reviews-rate {
    padding: 10px;
    border-bottom: 1px dashed #70A8C2;
}
.bws-plugin-reviews-support {
    padding: 10px;
}
/*
* styles for Go PRO tab
*/
.bws_go_pro_tab {
    background-color: #2A95C5;
    border-color: #11688F;
    color: #FFFFFF;
    font-weight: normal !important;
    text-shadow: none;
}
.bws_go_pro_tab:hover {
    background-color: #2080AB;
    color: #FFFFFF;
    border-color: #11688F;
}
/*
* styles for pro_version settings and tooltip
*/
td.bws_pro_version,
tr.bws_pro_version,
.nav-tab.bws_plugin_menu_pro_version,
.nav-tab.bws_plugin_menu_pro_version:hover {
    background: rgba(248, 226, 104, 0.11) url("../images/pattern_bg.png");
    border: 1px solid #AAA;
}
.nav-tab.bws_plugin_menu_pro_version:hover {
    color: #AAAAAA;
}
td.bws_pro_version_tooltip {
    border: 1px solid #AAA;
    position: inherit;
}
.bws_pro_version_bloc {
    position: relative;
    margin: 5px 0;
    border: 1px solid #AAAAAA;
    max-width: 800px;
}
.bws_table_bg {
    background: #f8e268 url("../images/pattern.png");
    opacity: 0.11;
    filter:progid:DXImageTransform.Microsoft.Alpha(opacity=11); /* IE 5.5+*/
    -moz-opacity: 0.11; /* Mozilla 1.6 и ниже */
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 1;
}
.bws_pro_version_table_bloc table.bws_pro_version {
    background: transparent;
    margin: 0;
    border: none;
    width: 100%;
}
table.bws_pro_version {
    background: #E0E0E0;
    border: 1px solid #AAA;
    margin-bottom: 5px;
    width: auto;
}
table.bws_pro_version tbody {
    display: block;
}
table.bws_pro_version th,
table.bws_pro_version td {
    padding-left: 10px;
}
.bws_pro_version_tooltip {
    background: #FFF;
    border-top: 1px solid #AAA;
    position: relative;
    z-index: 2;
    padding: 10px;
    font-size: 14px;
}
.bws_pro_version_tooltip .bws_button {
    background: #dd5738;
    border: none;
    text-decoration: none;
    color: #fff;
    padding: 5px 17px;
    border-radius: 2px;
    margin: 5px 10px;
    float: right;
}
.bws_pro_version_tooltip .bws_info {
    float: left;
    padding-top: 10px;
    font-size: 14px;
    color: #444;
}
.bws_pro_version_tooltip .bws_pro_links {
    float: right;
}
.bws_pro_version_tooltip .bws_trial_info {
    padding-top: 10px;
    display: inline-block;
}
div.bws_pro_version {
    padding: 5px 10px;
}
a.bws_plugin_pro_version {
    display: block;
    background: rgba(248, 226, 104, 0.11) url("../images/pattern_bg.png");
    border: 1px solid #AAA;
    padding: 5px;
    text-decoration: none;
    color: #666;
}
.bws_pro_version_single_link,
.bws_pro_version_single_link:hover {
    text-decoration: none;
    color: #666;
}
/* style for mini-block (ex. google map) */
.bws_pro_version_bloc_mini .bws_pro_version_table_bloc table.bws_pro_version {
    width: auto;
}
.bws_pro_version_bloc_mini .bws_pro_version_tooltip {
    padding: 10px 61px;
    text-align: center;
    width: 200px;
}
.bws_pro_version_bloc_mini .bws_pro_version_tooltip a {
    display: inline-block;
    line-height: 1.5;
}
.bws_pro_version_bloc_mini .bws_pro_version_tooltip .bws_button {
    margin: 10px 10px 5px;
    padding: 5px 50px;
    float: none;
}
/* #### Mobile Phones Portrait or Landscape #### */
@media screen and (max-device-width: 640px) {
    .bws_pro_version_tooltip {
        padding: 10px;
        text-align: center;
    }
    .bws_pro_version_tooltip .bws_info {
        float: none;
        text-align: center;
    }
    .bws_pro_version_tooltip a {
        display: inline-block;
        line-height: 1.5;
    }
    .bws_pro_version_tooltip .bws_info a {
        display: block;
    }
    .bws_pro_version_tooltip .bws_button {
        margin: 10px 10px 5px;
        padding: 5px 50px;
        float: none;
    }
}
/*
* styles for banner
*/
.bws_banner_on_plugin_page {
    border: 1px solid #d4d4d4;
    background: #FFF;
    position: relative;
    overflow: hidden;
    margin: 12px 0;
    background: #ECECEC;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
}
.bws_banner_on_plugin_page .text {
    color: #000;
    font-size: 15px;
    line-height: 26px;
    margin: 18px 18px 14px;
    float: left;
    width: auto;
    max-width: 80%;
}
.bws_banner_on_plugin_page .text span {
    font-size: 12px;
    opacity: 0.7;
}
div.bws_banner_on_plugin_page .button {
    float: right;
    border: none;
    font-size: 14px;
    margin: 18px 16px;
    padding: 14px 29px;
    color: #FFF;
    text-shadow: none;
    font-weight: bold;
    background: #0074A2;
    -moz-border-radius: 3px;
    border-radius: 3px;
    -webkit-border-radius: 3px;
    text-decoration: none;
    height: 50px;
    text-align: center;
    text-transform: uppercase;
    box-shadow: none;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
.bws_banner_on_plugin_page .button:hover,
.bws_banner_on_plugin_page .button:focus {
    background: #222;
    color: #FFF;
}
div.bws_banner_on_plugin_page .icon {
    float: left;
    margin: 12px 8px 8px 12px;
}
.bws_banner_on_plugin_page .icon img {
    max-width: 60px;
}
.bws_banner_on_plugin_page .text + .icon {
    display: none;
}
.bws_banner_on_plugin_page .close_icon {
    float: right;
    margin: 8px;
    cursor: pointer;
}
/* #### Mobile Phones Portrait or Landscape #### */
@media screen and (max-device-width: 640px) {
    .bws_banner_on_plugin_page .text,
    .bws_banner_on_plugin_page .icon,
    .bws_banner_on_plugin_page .button_div,
    .bws_banner_on_plugin_page .button {
        float: none;
        text-align: center;
    }
    .bws_banner_on_plugin_page .icon {
        position: relative;
        left: 8px;
    }
}


text:
package com.facebook.buck.io.filesystem;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import com.facebook.buck.io.watchman.Capability;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.nio.file.Paths;
import java.util.EnumSet;
import org.junit.Test;

public class GlobPatternMatcherTest {

  @Test
  public void matchesPathsUnderProvidedBasePath() {
    GlobPatternMatcher matcher = GlobPatternMatcher.of("foo/*");
    assertTrue(matcher.matches(Paths.get("foo").resolve("bar")));
  }

  @Test
  public void doesNotMatchPathsOutsideOfProvidedBasePath() {
    GlobPatternMatcher matcher = GlobPatternMatcher.of("foo/*");
    assertFalse(matcher.matches(Paths.get("not_relative_too_root")));
  }

  @Test
  public void usesWatchmanQueryToMatchProvidedBasePath() {
    GlobPatternMatcher matcher = GlobPatternMatcher.of("foo/*");
    assertEquals(
        matcher.toWatchmanMatchQuery(EnumSet.noneOf(Capability.class)),
        ImmutableList.of("match", "foo/*", "wholename", ImmutableMap.of("includedotfiles", true)));
  }

  @Test
  public void returnsAGlobWhenAskedForPathOrGlob() {
    GlobPatternMatcher matcher = GlobPatternMatcher.of("foo/*");
    assertEquals(matcher.getPathOrGlob(), "foo/*");
  }
}


text:
var http = require("http");
var express = require("express");
var config = require("../config/config.js");
var beforeRouter = require("./beforeRouter");
var router = require("./router");

var ejs = require("ejs");

var bodyParser = require("body-parser");
var timeout = require("connect-timeout");
var methodOverride = require("method-override");
var cookieParser = require("cookie-parser");
var session = require('cookie-session');
var md5 = require("md5");

var app = express();

function haltByTimeout(req, res, next) {
	if(!req.timedout) next();
	else res.end("服务器像蜗牛一样,超时啦!");
}

app.set("views", __dirname + "/../views");
app.set("view engine", "ejs");

app.use('/static', function(req, res, next){
	if(/j1/.test(req.url)) {
		next();
	}
	else express.static(__dirname + '/../public/static')(req, res, next);
});

app.use(function(req, res, next) {
	if(/t\.jpg/.test(req.url)) {
		console.log(req.url);
	}
	next();
})

app.use(timeout(5000));
app.use(bodyParser({keepExtensions: true, uploadDir: "/var/tmp/"}))
app.use(bodyParser.urlencoded());
app.use(haltByTimeout);
app.use(methodOverride());
app.use(haltByTimeout);
app.use(cookieParser(config.cookieSecret));
app.use(haltByTimeout);
app.use(session({
	keys: [config.sessionKey1, config.sessionKey2],
	overwrite: true,
	maxage: ( config.sessionExpire || 20 ) * 60 * 1000,
	expires: new Date("31/12/2050 00:00:00"),
}));
app.use(haltByTimeout);

// 添加额外信息, 判断了UserAgent
app.all("*", beforeRouter.assembleParam);

app.use(router.route);

app.listen(config.port);

http.createServer(app);

console.log("服务器已启动,监听" + config.port);


text:
<?php

namespace ClassGeneration\Element;

use ClassGeneration\DocBlock;
use ClassGeneration\DocBlockInterface;

/**
 * Interface for Document Class Elements
 * @author Antonio Spinelli <tonicospinelli@gmail.com>
 */
interface DocumentBlockInterface
{

    /**
     * Returns the DocBlock Object.
     * @return DocBlock
     */
    public function getDocBlock();

    /**
     * Sets the DocBlock Object.
     *
     * @param DocBlockInterface $docBlock
     *
     * @return ElementInterface
     */
    public function setDocBlock(DocBlockInterface $docBlock);
}


text:
import { createStore, applyMiddleware, compose } from 'redux';
import createSagaMiddleware from 'redux-saga';
import ReduxThunk from 'redux-thunk'
import { createLogger } from 'redux-logger';

import reducer from './reducers';
import mainSaga from './main-saga';

const NODE_ENV = process.env.NODE_ENV || 'development';

const configureStore = (initialState = {}) => {
  const sagaMiddleware = createSagaMiddleware();
  const middlewares = [applyMiddleware(sagaMiddleware), applyMiddleware(ReduxThunk)];
  if (NODE_ENV === 'development') {
    middlewares.push(applyMiddleware(createLogger()));
  }
  const enhancer = compose.apply(null, middlewares);
  const store = createStore(reducer, initialState, enhancer);
  sagaMiddleware.run(mainSaga);
  return store;
};

export default configureStore;


text:
package com.twu.biblioteca;

/**
 * Created by nataliadjohari on 21/02/2017.
 */
public class Book extends LibraryItem {
    private String author;
    private int yearPublished;

    public Book(String title, String author, int yearPublished) {
        super(title);
        this.author = author;
        this.yearPublished = yearPublished;
        this.setType(Type.BOOK);
    }

    public Book(String title) {
        this(title, "", 0);
    }

    public Book() {
        this("");
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getAuthor() {
        return this.author;
    }

    public void setYearPublished(int year) {
        this.yearPublished = year;
    }

    public int getYearPublished() {
        return this.yearPublished;
    }

    public String getDetails() {
        String result = "";

        result += this.getTitle();
        result += "\nAuthor: " + this.author;
        result += "\nYear Published: " + this.yearPublished;
        result += "\n";

        return result;
    }

    @Override
    public boolean equals(Object otherBook) {
        return otherBook.getClass() == this.getClass() &&
                this.getTitle().equals(((Book)otherBook).getTitle());
    }
}


text:
package Views.api;

import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.ArrowKeyMovementMethod;
import android.text.method.MovementMethod;
import android.util.AttributeSet;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.TextView;

public class FMedittext extends TextView {

    public FMedittext(Context context) {

        super(context, null);
    }

    @Override
    protected boolean getDefaultEditable() {
        return true;
    }

    @Override
    protected MovementMethod getDefaultMovementMethod() {
        return ArrowKeyMovementMethod.getInstance();
    }

    @Override
    public Editable getText() {
        return (Editable) super.getText();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, BufferType.EDITABLE);
    }

    /**
     * Convenience for {@link Selection#setSelection(Spannable, int, int)}.
     */
    public void setSelection(int start, int stop) {
        Selection.setSelection(getText(), start, stop);
    }

    /**
     * Convenience for {@link Selection#setSelection(Spannable, int)}.
     */
    public void setSelection(int index) {
        Selection.setSelection(getText(), index);
    }

    /**
     * Convenience for {@link Selection#selectAll}.
     */
    public void selectAll() {
        Selection.selectAll(getText());
    }

    /**
     * Convenience for {@link Selection#extendSelection}.
     */
    public void extendSelection(int index) {
        Selection.extendSelection(getText(), index);
    }

    @Override
    public void setEllipsize(TextUtils.TruncateAt ellipsis) {
        if (ellipsis == TextUtils.TruncateAt.MARQUEE) {
            throw new IllegalArgumentException("EditText cannot use the ellipsize mode "
                    + "TextUtils.TruncateAt.MARQUEE");
        }
        super.setEllipsize(ellipsis);
    }

    @Override
    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
        super.onInitializeAccessibilityEvent(event);
        event.setClassName(android.widget.EditText.class.getName());
    }

    @Override
    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
        super.onInitializeAccessibilityNodeInfo(info);
        info.setClassName(android.widget.EditText.class.getName());
    }
}


text:
/*
Package test provides some operations for testing.
*/
package test


text:
<?php

namespace SilverShop\Forms;

use Closure;
use SilverShop\Model\Order;
use SilverShop\Model\Variation\Variation;
use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FormField;
use SilverStripe\Forms\TextField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\SS_List;
use SilverStripe\View\SSViewer;

/**
 * Field for editing cart/items within a form
 *
 * @package shop
 */
class CartEditField extends FormField
{
    /**
     * @var Order
     */
    protected $cart;

    protected $items;

    protected $template = 'Cart';

    protected $editableItemsCallback;

    public function __construct($name, $title, $cart)
    {
        parent::__construct($name, $title);
        $this->cart = $cart;
        $this->items = $cart->Items();
    }

    /**
     * Set tempalte for rendering editable cart.
     *
     * @param string $template
     */
    public function setTemplate($template)
    {
        $this->template = $template;
        return $this;
    }

    /**
     * Allow overriding the given items list.
     * This helps with formatting, grouping, ordering etc.
     */
    public function setItemsList(SS_List $list)
    {
        $this->items = $list;
        return $this;
    }

    /**
     * Get the items list being used to produce the cart.
     *
     * @return SS_List
     */
    public function getItemsList()
    {
        return $this->items;
    }

    /**
     * Provides a way to modify the editableItems list
     * before it is rendered.
     *
     * @param Closure $callback
     */
    public function setEditableItemsCallback(Closure $callback)
    {
        $this->editableItemsCallback = $callback;
    }

    /**
     * Render the cart with editable item fields.
     *
     * @param array $properties
     */
    public function Field($properties = array())
    {
        $editables = $this->editableItems();
        $customcartdata = array(
            'Items' => $editables,
        );
        // NOTE: this was originally incorrect - passing just $editables and $customcartdata
        // which broke modules like Display_Logic.
        $this->extend('onBeforeRender', $this, $editables, $customcartdata);

        return SSViewer::execute_template(
            $this->template,
            $this->cart->customise($customcartdata),
            array('Editable' => true)
        );
    }

    /**
     * Add quantity, variation and remove fields to the
     * item set.
     *
     * @param SS_List $items
     */
    protected function editableItems()
    {
        $editables = ArrayList::create();
        foreach ($this->items as $item) {
            $buyable = $item->Buyable();
            if (!$buyable) {
                continue;
            }
            // If the buyable is a variation, use the belonging product instead for variation-form generation
            if ($buyable instanceof Variation) {
                $buyable = $buyable->Product();
            }
            $name = $this->name . "[$item->ID]";
            $quantity = TextField::create(
                $name . '[Quantity]',
                'Quantity',
                $item->Quantity
            )
                ->addExtraClass('numeric')
                ->setAttribute('type', 'number')
                ->setAttribute('min', '0');

            $variationfield = false;
            if ($buyable->hasMany('Variations')) {
                $variations = $buyable->Variations();
                if ($variations->exists()) {
                    $variationfield = DropdownField::create(
                        $name . '[ProductVariationID]',
                        _t('SilverShop\Model\Variation\Variation.SINGULARNAME', 'Variation'),
                        $variations->map('ID', 'Title'),
                        $item->ProductVariationID
                    );
                }
            }
            $remove = CheckboxField::create($name . '[Remove]', _t('SilverShop\Generic.Remove', 'Remove'));
            $editables->push(
                $item->customise(
                    array(
                        'QuantityField' => $quantity,
                        'VariationField' => $variationfield,
                        'RemoveField' => $remove,
                    )
                )
            );
        }

        if (is_callable($this->editableItemsCallback)) {
            $callback = $this->editableItemsCallback;
            $editables = $callback($editables);
        }

        return $editables;
    }
}


text:
    <title>Test of form submission</title>

        <form action="network_confirm.php" method="get">
            Text A <input type="text" name="a">

            Text area B <textarea name="b"></textarea>

            Text area C
                <textarea name="c">
                </textarea>

            Selection D
                <select name="d">
                    <option value="" selected>D1</option>
                    <option>D2</option>
                    <option value="0">D3</option>
                    <option value="?">D4</option>
                </select>

            Checkbox E <input type="checkbox" name="e" value="" checked>

            Checkbox F <input type="checkbox" name="f" checked>

            Checkbox G <input type="checkbox" name="g" value="0" checked>

            Checkbox H <input type="checkbox" name="h" value="?" checked>

            Radio I
            I1<input type="radio" name="i" checked>
            I2<input type="radio" name="i" value="">
            I3<input type="radio" name="i" value="0">
            I4<input type="radio" name="i" value="?">

            <input type="submit" name="go" value="Go!">
        </form>


text:
Initial release

### Added

- Fundamental features

### Deprecated

- Nothing

### Removed

- Nothing

### Fixed

- Nothing


text:
"""Representation of a toggleButton."""
from typing import Any

from homeassistant.components.button import ButtonEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from . import ZWaveMeEntity
from .const import DOMAIN, ZWaveMePlatform

DEVICE_NAME = ZWaveMePlatform.BUTTON

async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up the number platform."""

    @callback
    def add_new_device(new_device):
        controller = hass.data[DOMAIN][config_entry.entry_id]
        button = ZWaveMeButton(controller, new_device)

        async_add_entities(
            [
                button,
            ]
        )

    config_entry.async_on_unload(
        async_dispatcher_connect(
            hass, f"ZWAVE_ME_NEW_{DEVICE_NAME.upper()}", add_new_device
        )
    )

class ZWaveMeButton(ZWaveMeEntity, ButtonEntity):
    """Representation of a ZWaveMe button."""

    def press(self, **kwargs: Any) -> None:
        """Turn the entity on."""
        self.controller.zwave_api.send_command(self.device.id, "on")


text:
class CreateSuccessStories < ActiveRecord::Migration
  def change
    create_table :success_stories do |t|
      t.string :photo_url
      t.string :date
      t.string :title
      t.text :description
      t.timestamps null: false
    end
  end
end


text:
namespace System.Data.Odbc
{
    internal sealed class DbSchemaInfo
    {
        internal DbSchemaInfo()
        {
        }

        internal string _name;
        internal string _typename;
        internal Type _type;
        internal ODBC32.SQL_TYPE? _dbtype;
    }

    /////////////////////////////////////////////////////////////////////////////
    // Cache
    //
    //  This is a on-demand cache, only caching what the user requests.
    //  The reational is that for ForwardOnly access (the default and LCD of drivers)
    //  we cannot obtain the data more than once, and even GetData(0) (to determine is-null)
    //  still obtains data for fixed lenght types.

    //  So simple code like:
    //      if (!rReader.IsDBNull(i))
    //          rReader.GetInt32(i)
    //
    //  Would fail, unless we cache on the IsDBNull call, and return the cached
    //  item for GetInt32.  This actually improves perf anyway, (even if the driver could
    //  support it), since we are not making a separate interop call...

    //  We do not cache all columns, so reading out of order is still not
    //
    /////////////////////////////////////////////////////////////////////////////
    internal sealed class DbCache
    {
        //Data

        private readonly bool[] _isBadValue;
        private DbSchemaInfo[] _schema;
        private readonly object[] _values;
        private readonly OdbcDataReader _record;
        internal int _count;
        internal bool _randomaccess = true;

        //Constructor
        internal DbCache(OdbcDataReader record, int count)
        {
            _count = count;
            _record = record;
            _randomaccess = (!record.IsBehavior(CommandBehavior.SequentialAccess));
            _values = new object[count];
            _isBadValue = new bool[count];
        }

        //Accessor
        internal object this[int i]
        {
            get
            {
                if (_isBadValue[i])
                {
                    OverflowException innerException = (OverflowException)Values[i];
                    throw new OverflowException(innerException.Message, innerException);
                }
                return Values[i];
            }
            set
            {
                Values[i] = value;
                _isBadValue[i] = false;
            }
        }

        internal int Count
        {
            get
            {
                return _count;
            }
        }

        internal void InvalidateValue(int i)
        {
            _isBadValue[i] = true;
        }

        internal object[] Values
        {
            get
            {
                return _values;
            }
        }

        internal object AccessIndex(int i)
        {
            //Note: We could put this directly in this[i], instead of having an explicit overload.
            //However that means that EVERY access into the cache takes the hit of checking, so
            //something as simple as the following code would take two hits.  It's nice not to
            //have to take the hit when you know what your doing.
            //
            //  if (cache[i] == null)
            //      ....
            //  return cache[i];

            object[] values = this.Values;
            if (_randomaccess)
            {
                //Random
                //Means that the user can ask for the values int any order (ie: out of order).
                //  In order to achieve this on a forward only stream, we need to actually
                //  retreive all the value in between so they can go back to values they've skipped
                for (int c = 0; c < i; c++)
                {
                    if (values[c] == null)
                    {
                        values[c] = _record.GetValue(c);
                    }
                }
            }
            return values[i];
        }

        internal DbSchemaInfo GetSchema(int i)
        {
            if (_schema == null)
            {
                _schema = new DbSchemaInfo[Count];
            }
            if (_schema[i] == null)
            {
                _schema[i] = new DbSchemaInfo();
            }
            return _schema[i];
        }

        internal void FlushValues()
        {
            //Set all objects to null (to explcitly release them)
            //Note: SchemaInfo remains the same for all rows - no need to reget those...
            int count = _values.Length;
            for (int i = 0; i < count; ++i)
            {
                _values[i] = null;
            }
        }
    }
}


text:
// Copyright 2019 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.
package org.chromium.chrome.browser.feed.library.sharedstream.constants;

/** A set of constants to be used in sharedStream */
public final class Constants {
    // Default minimum time for a view to be onscreen and not scrolling before it is counted as a
    // view
    public static final long VIEW_MIN_TIME_MS_DEFAULT = 500L;
}


text:
from django.db.models import fields

from wysihtml5.conf import settings
from wysihtml5.utils import keeptags
from wysihtml5.widgets import Wysihtml5TextareaWidget

class Wysihtml5TextField(fields.TextField):
    def __init__(self, *args, **kwargs):
        self.keep_tags = kwargs.pop('keep_tags',
                                    settings.WYSIHTML5_ALLOWED_TAGS)
        super(Wysihtml5TextField, self).__init__(*args, **kwargs)

    def formfield(self, **kwargs):
        defaults = {"widget": Wysihtml5TextareaWidget}
        defaults.update(kwargs)
        return super(Wysihtml5TextField, self).formfield(**defaults)

    def pre_save(self, model_instance, add):
        value = super(Wysihtml5TextField, self).pre_save(model_instance, add)
        return keeptags(value, self.keep_tags)

try:
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules([], ["^wysihtml5\.fields\.Wysihtml5TextField"])
except ImportError:
    pass


text:
alchemtinker
============

A Minetest mod that adds Magic.
This is the only magic mod for Minetest that uses the 5 elements to create wands, spells, and tools.