<commit_before>/*****************************************************************************
 * quartztext.c : Put text on the video, using Mac OS X Quartz Engine
 *****************************************************************************
 * Copyright (C) 2007 the VideoLAN team
 * $Id$
 *
 * Authors: <NAME> <b dot purcell at adbglobal dot com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

//////////////////////////////////////////////////////////////////////////////
// Preamble
//////////////////////////////////////////////////////////////////////////////
#include <stdlib.h>                                      // malloc(), free()
#include <string.h>

#include <vlc/vlc.h>
#include <vlc_vout.h>
#include <vlc_osd.h>
#include <vlc_block.h>
#include <vlc_filter.h>
#include <vlc_stream.h>
#include <vlc_xml.h>

#include <math.h>

#include <Carbon/Carbon.h>

#define DEFAULT_FONT           "Verdana"
#define DEFAULT_FONT_COLOR     0xffffff
#define DEFAULT_REL_FONT_SIZE  16

#define VERTICAL_MARGIN 3
#define HORIZONTAL_MARGIN 10

//////////////////////////////////////////////////////////////////////////////
// Local prototypes
//////////////////////////////////////////////////////////////////////////////
static int  Create ( vlc_object_t * );
static void Destroy( vlc_object_t * );

static int RenderText( filter_t *, subpicture_region_t *,
                       subpicture_region_t * );
static int RenderHtml( filter_t *, subpicture_region_t *,
                       subpicture_region_t * );

static int RenderYUVA( filter_t *p_filter, subpicture_region_t *p_region,
                       UniChar *psz_utfString, uint32_t i_text_len,
                       uint32_t i_runs, uint32_t *pi_run_lengths,
                       ATSUStyle *pp_styles );
static ATSUStyle CreateStyle( char *psz_fontname, int i_font_size,
                              int i_font_color, int i_font_alpha,
                              vlc_bool_t b_bold, vlc_bool_t b_italic,
                              vlc_bool_t b_uline );
//////////////////////////////////////////////////////////////////////////////
// Module descriptor
//////////////////////////////////////////////////////////////////////////////

// The preferred way to set font style information is for it to come from the
// subtitle file, and for it to be rendered with RenderHtml instead of
// RenderText. This module, unlike Freetype, doesn't provide any options to
// override the fallback font selection used when this style information is
// absent.
vlc_module_begin();
    set_shortname( _("Mac Text renderer"));
    set_description( _("Quartz font renderer") );
    set_category( CAT_VIDEO );
    set_subcategory( SUBCAT_VIDEO_SUBPIC );

    set_capability( "text renderer", 120 );
    add_shortcut( "text" );
    set_callbacks( Create, Destroy );
vlc_module_end();

typedef struct font_stack_t font_stack_t;
struct font_stack_t
{
    char          *psz_name;
    int            i_size;
    int            i_color;
    int            i_alpha;

    font_stack_t  *p_next;
};

typedef struct offscreen_bitmap_t offscreen_bitmap_t;
struct offscreen_bitmap_t
{
    uint8_t       *p_data;
    int            i_bitsPerChannel;
    int            i_bitsPerPixel;
    int            i_bytesPerPixel;
    int            i_bytesPerRow;
};

//////////////////////////////////////////////////////////////////////////////
// filter_sys_t: quartztext local data
//////////////////////////////////////////////////////////////////////////////
// This structure is part of the video output thread descriptor.
// It describes the freetype specific properties of an output thread.
//////////////////////////////////////////////////////////////////////////////
struct filter_sys_t
{
    char          *psz_font_name;
    uint8_t        i_font_opacity;
    int            i_font_color;
    int            i_font_size;
};

//////////////////////////////////////////////////////////////////////////////
// Create: allocates osd-text video thread output method
//////////////////////////////////////////////////////////////////////////////
// This function allocates and initializes a Clone vout method.
//////////////////////////////////////////////////////////////////////////////
static int Create( vlc_object_t *p_this )
{
    filter_t *p_filter = (filter_t *)p_this;
    filter_sys_t *p_sys;

    // Allocate structure
    p_filter->p_sys = p_sys = malloc( sizeof( filter_sys_t ) );
    if( !p_sys )
    {
        msg_Err( p_filter, "out of memory" );
        return VLC_ENOMEM;
    }
    p_sys->psz_font_name  = strdup( DEFAULT_FONT );
    p_sys->i_font_opacity = 255;
    p_sys->i_font_color   = DEFAULT_FONT_COLOR;
    p_sys->i_font_size    = p_filter->fmt_out.video.i_height / DEFAULT_REL_FONT_SIZE;

    p_filter->pf_render_text = RenderText;
    p_filter->pf_render_html = RenderHtml;

    return VLC_SUCCESS;
}

//////////////////////////////////////////////////////////////////////////////
// Destroy: destroy Clone video thread output method
//////////////////////////////////////////////////////////////////////////////
// Clean up all data and library connections
//////////////////////////////////////////////////////////////////////////////
static void Destroy( vlc_object_t *p_this )
{
    filter_t *p_filter = (filter_t *)p_this;
    filter_sys_t *p_sys = p_filter->p_sys;

    free( p_sys->psz_font_name );
    free( p_sys );
}

#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
// Original version of these functions available on:
// http://developer.apple.com/documentation/Carbon/Conceptual/QuickDrawToQuartz2D/tq_color/chapter_4_section_3.html

#define kGenericRGBProfilePathStr "/System/Library/ColorSync/Profiles/Generic RGB Profile.icc" 
 
static CMProfileRef OpenGenericProfile( void )
{
    static CMProfileRef cached_rgb_prof = NULL;
 
    // Create the profile reference only once
    if( cached_rgb_prof == NULL )
    {
        OSStatus            err;
        CMProfileLocation   loc;
 
        loc.locType = cmPathBasedProfile;
        strcpy( loc.u.pathLoc.path, kGenericRGBProfilePathStr );
 
        err = CMOpenProfile( &cached_rgb_prof, &loc );
 
        if( err != noErr )
        {
            cached_rgb_prof = NULL;<commit_msg>Dynamically load any TTF or OTF fonts available in the attachments of the media file and make them available to the Quartz engine for subtitle rendering.<commit_after>/*****************************************************************************
 * quartztext.c : Put text on the video, using Mac OS X Quartz Engine
 *****************************************************************************
 * Copyright (C) 2007 the VideoLAN team
 * $Id$
 *
 * Authors: <NAME> <<EMAIL>>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

//////////////////////////////////////////////////////////////////////////////
// Preamble
//////////////////////////////////////////////////////////////////////////////
#include <stdlib.h>                                      // malloc(), free()
#include <string.h>

#include <vlc/vlc.h>
#include <vlc_vout.h>
#include <vlc_osd.h>
#include <vlc_block.h>
#include <vlc_filter.h>
#include <vlc_stream.h>
#include <vlc_xml.h>
#include <vlc_input.h>

#include <math.h>

#include <Carbon/Carbon.h>

#define DEFAULT_FONT           "Verdana"
#define DEFAULT_FONT_COLOR     0xffffff
#define DEFAULT_REL_FONT_SIZE  16

#define VERTICAL_MARGIN 3
#define HORIZONTAL_MARGIN 10

//////////////////////////////////////////////////////////////////////////////
// Local prototypes
//////////////////////////////////////////////////////////////////////////////
static int  Create ( vlc_object_t * );
static void Destroy( vlc_object_t * );

static int LoadFontsFromAttachments( filter_t *p_filter );

static int RenderText( filter_t *, subpicture_region_t *,
                       subpicture_region_t * );
static int RenderHtml( filter_t *, subpicture_region_t *,
                       subpicture_region_t * );

static int RenderYUVA( filter_t *p_filter, subpicture_region_t *p_region,
                       UniChar *psz_utfString, uint32_t i_text_len,
                       uint32_t i_runs, uint32_t *pi_run_lengths,
                       ATSUStyle *pp_styles );
static ATSUStyle CreateStyle( char *psz_fontname, int i_font_size,
                              int i_font_color, int i_font_alpha,
                              vlc_bool_t b_bold, vlc_bool_t b_italic,
                              vlc_bool_t b_uline );
//////////////////////////////////////////////////////////////////////////////
// Module descriptor
//////////////////////////////////////////////////////////////////////////////

// The preferred way to set font style information is for it to come from the
// subtitle file, and for it to be rendered with RenderHtml instead of
// RenderText. This module, unlike Freetype, doesn't provide any options to
// override the fallback font selection used when this style information is
// absent.
vlc_module_begin();
    set_shortname( _("Mac Text renderer"));
    set_description( _("Quartz font renderer") );
    set_category( CAT_VIDEO );
    set_subcategory( SUBCAT_VIDEO_SUBPIC );

    set_capability( "text renderer", 120 );
    add_shortcut( "text" );
    set_callbacks( Create, Destroy );
vlc_module_end();

typedef struct font_stack_t font_stack_t;
struct font_stack_t
{
    char          *psz_name;
    int            i_size;
    int            i_color;
    int            i_alpha;

    font_stack_t  *p_next;
};

typedef struct offscreen_bitmap_t offscreen_bitmap_t;
struct offscreen_bitmap_t
{
    uint8_t       *p_data;
    int            i_bitsPerChannel;
    int            i_bitsPerPixel;
    int            i_bytesPerPixel;
    int            i_bytesPerRow;
};

//////////////////////////////////////////////////////////////////////////////
// filter_sys_t: quartztext local data
//////////////////////////////////////////////////////////////////////////////
// This structure is part of the video output thread descriptor.
// It describes the freetype specific properties of an output thread.
//////////////////////////////////////////////////////////////////////////////
struct filter_sys_t
{
    char          *psz_font_name;
    uint8_t        i_font_opacity;
    int            i_font_color;
    int            i_font_size;

    ATSFontContainerRef    *p_fonts;
    int                     i_fonts;
};

//////////////////////////////////////////////////////////////////////////////
// Create: allocates osd-text video thread output method
//////////////////////////////////////////////////////////////////////////////
// This function allocates and initializes a Clone vout method.
//////////////////////////////////////////////////////////////////////////////
static int Create( vlc_object_t *p_this )
{
    filter_t *p_filter = (filter_t *)p_this;
    filter_sys_t *p_sys;

    // Allocate structure
    p_filter->p_sys = p_sys = malloc( sizeof( filter_sys_t ) );
    if( !p_sys )
    {
        msg_Err( p_filter, "out of memory" );
        return VLC_ENOMEM;
    }
    p_sys->psz_font_name  = strdup( DEFAULT_FONT );
    p_sys->i_font_opacity = 255;
    p_sys->i_font_color   = DEFAULT_FONT_COLOR;
    p_sys->i_font_size    = p_filter->fmt_out.video.i_height / DEFAULT_REL_FONT_SIZE;

    p_filter->pf_render_text = RenderText;
    p_filter->pf_render_html = RenderHtml;

    p_sys->p_fonts = NULL;
    p_sys->i_fonts = 0;

    LoadFontsFromAttachments( p_filter );

    return VLC_SUCCESS;
}

//////////////////////////////////////////////////////////////////////////////
// Destroy: destroy Clone video thread output method
//////////////////////////////////////////////////////////////////////////////
// Clean up all data and library connections
//////////////////////////////////////////////////////////////////////////////
static void Destroy( vlc_object_t *p_this )
{
    filter_t *p_filter = (filter_t *)p_this;
    filter_sys_t *p_sys = p_filter->p_sys;

    if( p_sys->p_fonts )
    {
        int   k;

        for( k = 0; k < p_sys->i_fonts; k++ )
        {
            ATSFontDeactivate( p_sys->p_fonts[k], NULL, kATSOptionFlagsDefault );
        }

        free( p_sys->p_fonts );
    }

    if( p_sys->psz_font_name ) free( p_sys->psz_font_name );

    free( p_sys );
}

//////////////////////////////////////////////////////////////////////////////
// Make any TTF/OTF fonts present in the attachments of the media file
// available to the Quartz engine for text rendering
//////////////////////////////////////////////////////////////////////////////
static int LoadFontsFromAttachments( filter_t *p_filter )
{
    filter_sys_t         *p_sys = p_filter->p_sys;
    input_thread_t       *p_input;
    input_attachment_t  **pp_attachments;
    int                   i_attachments_cnt;
    int                   k;
    int                   rv = VLC_SUCCESS;

    p_input = (input_thread_t *)vlc_object_find( p_filter, VLC_OBJECT_INPUT, FIND_PARENT );
    if( ! p_input )
        return VLC_EGENERIC;
    
    if( VLC_SUCCESS != input_Control( p_input, INPUT_GET_ATTACHMENTS, &pp_attachments, &i_attachments_cnt ))
        return VLC_EGENERIC;

    p_sys->i_fonts = 0;
    p_sys->p_fonts = malloc( i_attachments_cnt * sizeof( ATSFontContainerRef ) );
    if(! p_sys->p_fonts )
        rv = VLC_ENOMEM;

    for( k = 0; k < i_attachments_cnt; k++ )
    {
        input_attachment_t *p_attach = pp_attachments[k];

        if( p_sys->p_fonts )
        {
            if(( !strcmp( p_attach->psz_mime, "application/x-truetype-font" ) || // TTF
                 !strcmp( p_attach->psz_mime, "application/x-font-otf" ) ) &&    // OTF
               ( p_attach->i_data > 0 ) &&
               ( p_attach->p_data != NULL ) )
            {
                ATSFontContainerRef  container;

                if( noErr == ATSFontActivateFromMemory( p_attach->p_data,
                                                        p_attach->i_data,
                                                        kATSFontContextLocal,
                                                        kATSFontFormatUnspecified,
                                                        NULL,
                                                        kATSOptionFlagsDefault,
                                                        &container ))
                {
                    p_sys->p_fonts[ p_sys->i_fonts++ ] = container;
                }
            }
        }
        vlc_input_attachment_Delete( p_attach );
    }
    free( pp_attachments );        

    return rv;
}

#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
// Original version of these functions available on:
// http://developer.apple.com/documentation/Carbon/Conceptual/QuickDrawToQuartz2D/tq_color/chapter_4_section_3.html

#define kGenericRGBProfilePathStr "/System/Library/ColorSync/Profiles/Generic RGB Profile.icc" 
 
static CMProfileRef OpenGenericProfile( void )
{
    static CMProfileRef cached_rgb_prof = NULL;
 
    // Create the profile reference only once
    if( cached_rgb_prof == NULL )
    {
        OSStatus            err;
        CMProfileLocation   loc;
 
        loc.locType = cmPathBasedProfile;
        strcpy( loc.u.pathLoc.path, kGenericRGBProfilePathStr );
 
        err = CMOpenProfile( &cached_rgb_prof, &loc );
 
        if( err != noErr )
        {
            cached_rgb_prof = NULL;
{'fraction_non_alphanumeric': 0.24146732355909065, 'fraction_numerical': 0.005282839674719535, 'mean_word_length': 1.5722137404580152, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 72, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 18, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1276703', 'n_tokens_mistral': 4586, 'n_tokens_neox': 4407, 'n_words': 1203}