/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: maasurf.cpp,v 1.5.12.1 2004/07/09 01:59:14 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

// Here is a little site I did as an example of a replacement site. It
// shows how you can tailor the mini site to output to just about any
// kind of device. This one outputs all the RGB and video in Ascii Art! 
// :) It is just a wrapper, basically, around the very nice AALib,
// which you need to have installed:
//    http://aa-project.sourceforge.net/aalib
//

#include <aalib.h>
#include "minisite.h"
#include "hxvsurf.h"
#include "coloracc.h"

#include "minisurf.h"
#include "maasurf.h"

#include "minifmt.h"


CMiniUnixSurface::CMiniUnixSurface(IUnknown* pContext, CMiniBaseSite* pSite)
    :  CMiniBaseSurface(pContext, pSite)
       , m_context(NULL)
       , m_nAAScale(2)
       , m_nWidth(0)
       , m_nHeight(0)
{
    memset( &m_hardware_params, 0, sizeof(m_hardware_params) );
    memset( &m_hardware_params, 0, sizeof(m_hardware_params) );

    //Init the rendering params...
    m_render_params.bright    = 40;
	m_render_params.contrast  = 2;
	m_render_params.gamma     = 4;
	m_render_params.dither    = AA_FLOYD_S;
	m_render_params.inversion = 0;
	m_render_params.randomval = 0;


    //Just output a little help text.
    fprintf( stderr, "\n\nThe Ascii Art player!\n\n" );
    fprintf( stderr, "This site takes keyboard input to control the contrast\n" );
    fprintf( stderr, "brightness and gamma settings. You will need these to \n" );
    fprintf( stderr, "adjust for movies that are overly dark or bright:\n\n" );
    fprintf( stderr, "'G'/'g' increase/decrease gamma.\n" );
    fprintf( stderr, "'B'/'b' increase/decrease brightness.\n" );
    fprintf( stderr, "'C'/'c' increase/decrease contrast.\n" ); 
    fprintf( stderr, "'S'/'s' increase/decrease scaling.\n\n" );
    fprintf( stderr, "\n" ); 
}

CMiniUnixSurface::~CMiniUnixSurface()
{
}


HX_RESULT CMiniUnixSurface::_CreateDestBuffer(int cidIn,
                                              int nWidth,
                                              int nHeight,
                                              int& nCount)
{
    HX_ASSERT( m_pSite );
    
    //For now, we just support RGB32
    HX_ASSERT( cidIn == CID_I420 );

    if( m_context )
    {
        aa_close(m_context);
        m_context = NULL;
    }

    m_nWidth  = nWidth;
    m_nHeight = nHeight;
    
    //XXXgwright must be even and 2 or larger.
    HX_ASSERT( m_nAAScale>=2 );
    HX_ASSERT( m_nAAScale%2 == 0 );
    
    //Init the AA
    m_hardware_params.width     = nWidth/m_nAAScale;
    m_hardware_params.height    = nHeight/(m_nAAScale*2);
    m_hardware_params.font      = &aa_font16;
    m_hardware_params.supported =
        AA_NORMAL_MASK | AA_BOLD_MASK | AA_DIM_MASK | AA_EXTENDED;

    //Init the context.
    m_context = aa_autoinit(&m_hardware_params);
    HX_ASSERT( m_context );

    //Init the keyboard.
    aa_autoinitkbd(m_context, 0);

    //Allocate.
	aa_resize(m_context);

    return HXR_OK;
}

         
HX_RESULT CMiniUnixSurface::_LockDestBuffer(UCHAR** ppDestPtr,
                                            LONG32* pnDestPitch,
                                            int& cid,
                                            REF(HXxSize) srcSize,
                                            int nIndex)
{
    *ppDestPtr   = aa_image(m_context);
    *pnDestPitch = aa_imgwidth(m_context);
    cid = CID_RGB8;
    
    return HXR_OK;
}

         
HX_RESULT CMiniUnixSurface::_TransferToDestBuffer(UCHAR* pSrcBuffer,
                                                  HXBitmapInfoHeader* pBitmapInfo,
                                                  HXxRect* prSrcRect,
                                                  HXxRect* prDstRect,
                                                  UCHAR* pDstBuffer,
                                                  LONG32 nDstPitch)
{
    BOOL bRecreateSurface = FALSE;
    int key       = 0;
    HX_RESULT res = HXR_OK;
    int nCidIn    = m_pImageHelper->GetBitmapColor( (HXBitmapInfo*)pBitmapInfo );

    //The input has to be a planar YUV format because I just use the lum
    //plane as the 8-bit greyscale and I don't do any color convertions.
    //It would be good to make a full-site version of this AA site. That
    //way we would already have the code to do all the color conversions
    //from any incoming format (YUY2, RGB, etc) to our 8-bit grey scale.
    //But for now, I am just assuming that whatever renderer is being used
    //is outputing in I420.
    HX_ASSERT( nCidIn == CID_I420 );
    if( nCidIn == CID_I420 )
    {
        //Try a little c loop to convert to grey scale. It would be
        //nice to use our fast color coverters for this. We will just
        //use the lum plain as a greyscale image and do scaling
        //here. If we can get the above color coverters working then I
        //think the picture would look a lot better because it would
        //be using some of the color info.
        int nSrcPitch = m_pImageHelper->GetBitmapPitch((HXBitmapInfo*)pBitmapInfo);
        UCHAR* pDestBuff = aa_image(m_context);
        UCHAR* pSrcBuff = pSrcBuffer;
        
        for( int y=0; y<aa_imgheight(m_context); y++)
        {
            //We are just going to throw away each row.
            for( int x=0; x<aa_imgwidth(m_context); x++ )
            {
                int t = 0;
                int z = 0;
                for( ; z<m_nAAScale/2 ; z++ )
                {
                    t += *pSrcBuff;
                    pSrcBuff++;
                }
                *pDestBuff = t/z;
                pDestBuff++;
            }
            pSrcBuff = pSrcBuffer+(y*m_nAAScale*nSrcPitch);
        }

        key = aa_getkey( m_context, 0 );
        switch( key )
        {
           case 'c':
               m_render_params.contrast--;
               break;
           case 'C':
               m_render_params.contrast++;
               break;
           case 'b':
               m_render_params.bright--;
               break;
           case 'B':
               m_render_params.bright++;
               break;
           case 'g':
               m_render_params.gamma-=.5;
               break;
           case 'G':
               m_render_params.gamma+=.5;
               break;
           case 'S':
               m_nAAScale+= 2;
               bRecreateSurface=TRUE;
               break;
           case 's':
               m_nAAScale-=2;
               if( m_nAAScale<2)
                   m_nAAScale=2;
               bRecreateSurface=TRUE;
               break;
           default:
               break;
        }
        
        if( bRecreateSurface )
        {
            //User changed the scale. We have to tear down our window and
            //rebuild it.
            int n = 0;
            _CreateDestBuffer( CID_I420, m_nWidth, m_nHeight, n );
        }
        
#if defined( _DEBUG)
        if( key != 0 )
        {
            fprintf( stderr, "Scale: %d Gamma: %f   Brightness: %d   Contrast: %d\n",
                     m_nAAScale,
                     m_render_params.gamma,
                     m_render_params.bright,
                     m_render_params.contrast);
        }
#endif  
        
        aa_render( m_context,
                   &m_render_params,
                   0, 0,
                   aa_imgwidth(m_context),
                   aa_imgheight(m_context)
                   );
    }
    else
    {
        fprintf( stderr, "You need to play content that outputs in I420.\n" );
        fprintf( stderr, "Like RealVideo for example.\n" ); 
    }
    
 
    return res;
}

         
HX_RESULT CMiniUnixSurface::_UnlockDestBuffer(UCHAR* pSurfPtr, int nIndex=0)
{
    return HXR_OK;
}

         
HX_RESULT CMiniUnixSurface::_RenderDestBuffer(HXxRect* prSrcRect,
                                              HXxRect* prDestRect,
                                              int nIndex)
{
    aa_flush(m_context);
    return HXR_OK;
}

         
HX_RESULT CMiniUnixSurface::_DestroyDestBuffer(int cid, int nCount)
{
    if( m_context )
    {
        aa_close(m_context);
        m_context = NULL;
    }

    return HXR_OK;
}

int CMiniUnixSurface::GetDstCID(int nIndex)
{
    //XXXgwright This can be anything because I just grab the lum plane
    //from the incoming I420 frames and use that as my 8bit greyscale.
    return CID_RGB32;
}

HX_RESULT CMiniUnixSurface::_ResizeVideoBuffer( INT32 nSize)
{
    return HXR_OK;
}

HX_RESULT CMiniUnixSurface::_init()
{
    return HXR_OK;
}
