flac.c
上传用户:kjfoods
上传日期:2020-07-06
资源大小:29949k
文件大小:47k
源码类别:

midi

开发平台:

Unix_Linux

  1. /*****************************************************************************
  2.  * flac.c: flac decoder/packetizer/encoder module making use of libflac
  3.  *****************************************************************************
  4.  * Copyright (C) 1999-2001 the VideoLAN team
  5.  * $Id: be411d5489e14e3a49ef35fe41006c99c038e8e0 $
  6.  *
  7.  * Authors: Gildas Bazin <gbazin@videolan.org>
  8.  *          Sigmund Augdal Helberg <dnumgis@videolan.org>
  9.  *
  10.  * This program is free software; you can redistribute it and/or modify
  11.  * it under the terms of the GNU General Public License as published by
  12.  * the Free Software Foundation; either version 2 of the License, or
  13.  * (at your option) any later version.
  14.  *
  15.  * This program is distributed in the hope that it will be useful,
  16.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  18.  * GNU General Public License for more details.
  19.  *
  20.  * You should have received a copy of the GNU General Public License
  21.  * along with this program; if not, write to the Free Software
  22.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  23.  *****************************************************************************/
  24. /*****************************************************************************
  25.  * Preamble
  26.  *****************************************************************************/
  27. #ifdef HAVE_CONFIG_H
  28. # include "config.h"
  29. #endif
  30. #include <vlc_common.h>
  31. #include <vlc_plugin.h>
  32. #include <vlc_codec.h>
  33. #include <vlc_aout.h>
  34. #ifdef HAVE_FLAC_STREAM_DECODER_H
  35. #   include <FLAC/stream_decoder.h>
  36. #   include <FLAC/stream_encoder.h>
  37. #   define USE_LIBFLAC
  38. #endif
  39. #include <vlc_block_helper.h>
  40. #include <vlc_bits.h>
  41. #define MAX_FLAC_HEADER_SIZE 16
  42. #if defined(FLAC_API_VERSION_CURRENT) && FLAC_API_VERSION_CURRENT >= 8
  43. #   define USE_NEW_FLAC_API
  44. #endif
  45. /*****************************************************************************
  46.  * decoder_sys_t : FLAC decoder descriptor
  47.  *****************************************************************************/
  48. struct decoder_sys_t
  49. {
  50.     /*
  51.      * Input properties
  52.      */
  53.     int i_state;
  54.     block_bytestream_t bytestream;
  55.     /*
  56.      * Input/Output properties
  57.      */
  58.     block_t *p_block;
  59.     aout_buffer_t *p_aout_buffer;
  60.     /*
  61.      * FLAC properties
  62.      */
  63. #ifdef USE_LIBFLAC
  64.     FLAC__StreamDecoder *p_flac;
  65.     FLAC__StreamMetadata_StreamInfo stream_info;
  66. #else
  67.     struct
  68.     {
  69.         unsigned min_blocksize, max_blocksize;
  70.         unsigned min_framesize, max_framesize;
  71.         unsigned sample_rate;
  72.         unsigned channels;
  73.         unsigned bits_per_sample;
  74.     } stream_info;
  75. #endif
  76.     bool b_stream_info;
  77.     /*
  78.      * Common properties
  79.      */
  80.     audio_date_t end_date;
  81.     mtime_t i_pts;
  82.     int i_frame_size, i_frame_length, i_bits_per_sample;
  83.     unsigned int i_rate, i_channels, i_channels_conf;
  84. };
  85. enum {
  86.     STATE_NOSYNC,
  87.     STATE_SYNC,
  88.     STATE_HEADER,
  89.     STATE_NEXT_SYNC,
  90.     STATE_GET_DATA,
  91.     STATE_SEND_DATA
  92. };
  93. static const int pi_channels_maps[7] =
  94. {
  95.     0,
  96.     AOUT_CHAN_CENTER,
  97.     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
  98.     AOUT_CHAN_CENTER | AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT,
  99.     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_REARLEFT
  100.      | AOUT_CHAN_REARRIGHT,
  101.     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
  102.      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT,
  103.     AOUT_CHAN_LEFT | AOUT_CHAN_RIGHT | AOUT_CHAN_CENTER
  104.      | AOUT_CHAN_REARLEFT | AOUT_CHAN_REARRIGHT | AOUT_CHAN_LFE
  105. };
  106. /*****************************************************************************
  107.  * Local prototypes
  108.  *****************************************************************************/
  109. static int  OpenDecoder   ( vlc_object_t * );
  110. static int  OpenPacketizer( vlc_object_t * );
  111. static void CloseDecoder  ( vlc_object_t * );
  112. #ifdef USE_LIBFLAC
  113. static int OpenEncoder   ( vlc_object_t * );
  114. static void CloseEncoder ( vlc_object_t * );
  115. #endif
  116. #ifdef USE_LIBFLAC
  117. static aout_buffer_t *DecodeBlock( decoder_t *, block_t ** );
  118. #endif
  119. static block_t *PacketizeBlock( decoder_t *, block_t ** );
  120. static int SyncInfo( decoder_t *, uint8_t *, unsigned int *, unsigned int *,
  121.                      unsigned int *,int * );
  122. #ifdef USE_LIBFLAC
  123. static FLAC__StreamDecoderReadStatus
  124. DecoderReadCallback( const FLAC__StreamDecoder *decoder,
  125.                      FLAC__byte buffer[], unsigned *bytes, void *client_data );
  126. static FLAC__StreamDecoderWriteStatus
  127. DecoderWriteCallback( const FLAC__StreamDecoder *decoder,
  128.                       const FLAC__Frame *frame,
  129.                       const FLAC__int32 *const buffer[], void *client_data );
  130. static void DecoderMetadataCallback( const FLAC__StreamDecoder *decoder,
  131.                                      const FLAC__StreamMetadata *metadata,
  132.                                      void *client_data );
  133. static void DecoderErrorCallback( const FLAC__StreamDecoder *decoder,
  134.                                   FLAC__StreamDecoderErrorStatus status,
  135.                                   void *client_data);
  136. static void Interleave32( int32_t *p_out, const int32_t * const *pp_in,
  137.                           const int *pi_order, int i_nb_channels, int i_samples );
  138. static void Interleave24( int8_t *p_out, const int32_t * const *pp_in,
  139.                           const int *pi_order, int i_nb_channels, int i_samples );
  140. static void Interleave16( int16_t *p_out, const int32_t * const *pp_in,
  141.                           const int *pi_order, int i_nb_channels, int i_samples );
  142. static void decoder_state_error( decoder_t *p_dec,
  143.                                  FLAC__StreamDecoderState state );
  144. #endif
  145. static uint64_t read_utf8( const uint8_t *p_buf, int *pi_read );
  146. static uint8_t flac_crc8( const uint8_t *data, unsigned len );
  147. /*****************************************************************************
  148.  * Module descriptor
  149.  *****************************************************************************/
  150. vlc_module_begin ()
  151.     set_category( CAT_INPUT )
  152.     set_subcategory( SUBCAT_INPUT_ACODEC )
  153.     add_shortcut( "flac" )
  154. #ifdef USE_LIBFLAC
  155.     set_description( N_("Flac audio decoder") )
  156.     set_capability( "decoder", 100 )
  157.     set_callbacks( OpenDecoder, CloseDecoder )
  158.     add_submodule ()
  159.     add_shortcut( "flac" )
  160.     set_description( N_("Flac audio encoder") )
  161.     set_capability( "encoder", 100 )
  162.     set_callbacks( OpenEncoder, CloseEncoder )
  163.     add_submodule ()
  164.     add_shortcut( "flac" )
  165. #endif
  166.     set_description( N_("Flac audio packetizer") )
  167.     set_capability( "packetizer", 100 )
  168.     set_callbacks( OpenPacketizer, CloseDecoder )
  169. vlc_module_end ()
  170. /*****************************************************************************
  171.  * OpenDecoder: probe the decoder and return score
  172.  *****************************************************************************/
  173. static int OpenDecoder( vlc_object_t *p_this )
  174. {
  175.     decoder_t *p_dec = (decoder_t*)p_this;
  176.     decoder_sys_t *p_sys;
  177.     if( p_dec->fmt_in.i_codec != VLC_FOURCC('f','l','a','c') )
  178.     {
  179.         return VLC_EGENERIC;
  180.     }
  181.     /* Allocate the memory needed to store the decoder's structure */
  182.     if( ( p_dec->p_sys = p_sys = malloc(sizeof(*p_sys)) ) == NULL )
  183.         return VLC_ENOMEM;
  184.     /* Misc init */
  185.     aout_DateSet( &p_sys->end_date, 0 );
  186.     p_sys->i_state = STATE_NOSYNC;
  187.     p_sys->b_stream_info = false;
  188.     p_sys->p_block=NULL;
  189.     p_sys->bytestream = block_BytestreamInit();
  190. #ifdef USE_LIBFLAC
  191.     /* Take care of flac init */
  192.     if( !(p_sys->p_flac = FLAC__stream_decoder_new()) )
  193.     {
  194.         msg_Err( p_dec, "FLAC__stream_decoder_new() failed" );
  195.         free( p_sys );
  196.         return VLC_EGENERIC;
  197.     }
  198. #ifdef USE_NEW_FLAC_API
  199.     if( FLAC__stream_decoder_init_stream( p_sys->p_flac,
  200.                                           DecoderReadCallback,
  201.                                           NULL,
  202.                                           NULL,
  203.                                           NULL,
  204.                                           NULL,
  205.                                           DecoderWriteCallback,
  206.                                           DecoderMetadataCallback,
  207.                                           DecoderErrorCallback,
  208.                                           p_dec )
  209.         != FLAC__STREAM_DECODER_INIT_STATUS_OK )
  210.     {
  211.         msg_Err( p_dec, "FLAC__stream_decoder_init_stream() failed" );
  212.         FLAC__stream_decoder_delete( p_sys->p_flac );
  213.         free( p_sys );
  214.         return VLC_EGENERIC;
  215.     }
  216. #else
  217.     FLAC__stream_decoder_set_read_callback( p_sys->p_flac,
  218.                                             DecoderReadCallback );
  219.     FLAC__stream_decoder_set_write_callback( p_sys->p_flac,
  220.                                              DecoderWriteCallback );
  221.     FLAC__stream_decoder_set_metadata_callback( p_sys->p_flac,
  222.                                                 DecoderMetadataCallback );
  223.     FLAC__stream_decoder_set_error_callback( p_sys->p_flac,
  224.                                              DecoderErrorCallback );
  225.     FLAC__stream_decoder_set_client_data( p_sys->p_flac, p_dec );
  226.     FLAC__stream_decoder_init( p_sys->p_flac );
  227. #endif
  228. #endif
  229.     /* Set output properties */
  230.     p_dec->fmt_out.i_cat = AUDIO_ES;
  231.     p_dec->fmt_out.i_codec = VLC_FOURCC('f','l','3','2');
  232.     /* Set callbacks */
  233. #ifdef USE_LIBFLAC
  234.     p_dec->pf_decode_audio = DecodeBlock;
  235. #endif
  236.     return VLC_SUCCESS;
  237. }
  238. static int OpenPacketizer( vlc_object_t *p_this )
  239. {
  240.     decoder_t *p_dec = (decoder_t*)p_this;
  241.     es_format_t es_save = p_dec->fmt_out;
  242.     int i_ret;
  243.     /* */
  244.     es_format_Copy( &p_dec->fmt_out, &p_dec->fmt_in );
  245.     i_ret = OpenDecoder( p_this );
  246.     p_dec->pf_decode_audio = NULL;
  247.     p_dec->pf_packetize    = PacketizeBlock;
  248.     /* Set output properties */
  249.     p_dec->fmt_out.i_codec = VLC_FOURCC('f','l','a','c');
  250.     if( i_ret != VLC_SUCCESS )
  251.     {
  252.         es_format_Clean( &p_dec->fmt_out );
  253.         p_dec->fmt_out = es_save;
  254.     }
  255.     return i_ret;
  256. }
  257. /*****************************************************************************
  258.  * CloseDecoder: flac decoder destruction
  259.  *****************************************************************************/
  260. static void CloseDecoder( vlc_object_t *p_this )
  261. {
  262.     decoder_t *p_dec = (decoder_t *)p_this;
  263.     decoder_sys_t *p_sys = p_dec->p_sys;
  264. #ifdef USE_LIBFLAC
  265.     FLAC__stream_decoder_finish( p_sys->p_flac );
  266.     FLAC__stream_decoder_delete( p_sys->p_flac );
  267. #endif
  268.     free( p_sys->p_block );
  269.     free( p_sys );
  270. }
  271. /*****************************************************************************
  272.  * ProcessHeader: process Flac header.
  273.  *****************************************************************************/
  274. static void ProcessHeader( decoder_t *p_dec )
  275. {
  276.     decoder_sys_t *p_sys = p_dec->p_sys;
  277. #ifdef USE_LIBFLAC
  278.     if( !p_dec->fmt_in.i_extra ) return;
  279.     /* Decode STREAMINFO */
  280.     msg_Dbg( p_dec, "decode STREAMINFO" );
  281.     p_sys->p_block = block_New( p_dec, p_dec->fmt_in.i_extra );
  282.     memcpy( p_sys->p_block->p_buffer, p_dec->fmt_in.p_extra,
  283.             p_dec->fmt_in.i_extra );
  284.     FLAC__stream_decoder_process_until_end_of_metadata( p_sys->p_flac );
  285.     msg_Dbg( p_dec, "STREAMINFO decoded" );
  286. #else
  287.     bs_t bs;
  288.     if( !p_dec->fmt_in.i_extra ) return;
  289.     bs_init( &bs, p_dec->fmt_in.p_extra, p_dec->fmt_in.i_extra );
  290.     p_sys->stream_info.min_blocksize = bs_read( &bs, 16 );
  291.     p_sys->stream_info.max_blocksize = bs_read( &bs, 16 );
  292.     p_sys->stream_info.min_framesize = bs_read( &bs, 24 );
  293.     p_sys->stream_info.max_framesize = bs_read( &bs, 24 );
  294.     p_sys->stream_info.sample_rate = bs_read( &bs, 20 );
  295.     p_sys->stream_info.channels = bs_read( &bs, 3 ) + 1;
  296.     p_sys->stream_info.bits_per_sample = bs_read( &bs, 5 ) + 1;
  297. #endif
  298.     if( !p_sys->b_stream_info ) return;
  299.     if( p_dec->fmt_out.i_codec == VLC_FOURCC('f','l','a','c') )
  300.     {
  301.         p_dec->fmt_out.i_extra = p_dec->fmt_in.i_extra;
  302.         p_dec->fmt_out.p_extra =
  303.             realloc( p_dec->fmt_out.p_extra, p_dec->fmt_out.i_extra );
  304.         memcpy( p_dec->fmt_out.p_extra,
  305.                 p_dec->fmt_in.p_extra, p_dec->fmt_out.i_extra );
  306.     }
  307. }
  308. /****************************************************************************
  309.  * PacketizeBlock: the whole thing
  310.  ****************************************************************************
  311.  * This function is called just after the thread is launched.
  312.  ****************************************************************************/
  313. static block_t *PacketizeBlock( decoder_t *p_dec, block_t **pp_block )
  314. {
  315.     decoder_sys_t *p_sys = p_dec->p_sys;
  316.     uint8_t p_header[MAX_FLAC_HEADER_SIZE];
  317.     block_t *p_sout_block;
  318.     if( !pp_block || !*pp_block ) return NULL;
  319.     if( (*pp_block)->i_flags&(BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED) )
  320.     {
  321.         if( (*pp_block)->i_flags&BLOCK_FLAG_CORRUPTED )
  322.         {
  323.             p_sys->i_state = STATE_NOSYNC;
  324.             block_BytestreamEmpty( &p_sys->bytestream );
  325.         }
  326.         aout_DateSet( &p_sys->end_date, 0 );
  327.         block_Release( *pp_block );
  328.         return NULL;
  329.     }
  330.     if( !p_sys->b_stream_info ) ProcessHeader( p_dec );
  331.     if( p_sys->stream_info.channels > 6 )
  332.     {
  333.         msg_Err( p_dec, "This stream uses too many audio channels" );
  334.         return NULL;
  335.     }
  336.     if( !aout_DateGet( &p_sys->end_date ) && !(*pp_block)->i_pts )
  337.     {
  338.         /* We've just started the stream, wait for the first PTS. */
  339.         block_Release( *pp_block );
  340.         return NULL;
  341.     }
  342.     else if( !aout_DateGet( &p_sys->end_date ) )
  343.     {
  344.         /* The first PTS is as good as anything else. */
  345.         p_sys->i_rate = p_dec->fmt_out.audio.i_rate;
  346.         aout_DateInit( &p_sys->end_date, p_sys->i_rate );
  347.         aout_DateSet( &p_sys->end_date, (*pp_block)->i_pts );
  348.     }
  349.     block_BytestreamPush( &p_sys->bytestream, *pp_block );
  350.     while( 1 )
  351.     {
  352.         switch( p_sys->i_state )
  353.         {
  354.         case STATE_NOSYNC:
  355.             while( block_PeekBytes( &p_sys->bytestream, p_header, 2 )
  356.                    == VLC_SUCCESS )
  357.             {
  358.                 if( p_header[0] == 0xFF && p_header[1] == 0xF8 )
  359.                 {
  360.                     p_sys->i_state = STATE_SYNC;
  361.                     break;
  362.                 }
  363.                 block_SkipByte( &p_sys->bytestream );
  364.             }
  365.             if( p_sys->i_state != STATE_SYNC )
  366.             {
  367.                 block_BytestreamFlush( &p_sys->bytestream );
  368.                 /* Need more data */
  369.                 return NULL;
  370.             }
  371.         case STATE_SYNC:
  372.             /* New frame, set the Presentation Time Stamp */
  373.             p_sys->i_pts = p_sys->bytestream.p_block->i_pts;
  374.             if( p_sys->i_pts != 0 &&
  375.                 p_sys->i_pts != aout_DateGet( &p_sys->end_date ) )
  376.             {
  377.                 aout_DateSet( &p_sys->end_date, p_sys->i_pts );
  378.             }
  379.             p_sys->i_state = STATE_HEADER;
  380.         case STATE_HEADER:
  381.             /* Get FLAC frame header (MAX_FLAC_HEADER_SIZE bytes) */
  382.             if( block_PeekBytes( &p_sys->bytestream, p_header,
  383.                                  MAX_FLAC_HEADER_SIZE ) != VLC_SUCCESS )
  384.             {
  385.                 /* Need more data */
  386.                 return NULL;
  387.             }
  388.             /* Check if frame is valid and get frame info */
  389.             p_sys->i_frame_length = SyncInfo( p_dec, p_header,
  390.                                               &p_sys->i_channels,
  391.                                               &p_sys->i_channels_conf,
  392.                                               &p_sys->i_rate,
  393.                                               &p_sys->i_bits_per_sample );
  394.             if( !p_sys->i_frame_length )
  395.             {
  396.                 msg_Dbg( p_dec, "emulated sync word" );
  397.                 block_SkipByte( &p_sys->bytestream );
  398.                 p_sys->i_state = STATE_NOSYNC;
  399.                 break;
  400.             }
  401.             if( p_sys->i_rate != p_dec->fmt_out.audio.i_rate )
  402.             {
  403.                 p_dec->fmt_out.audio.i_rate = p_sys->i_rate;
  404.                 aout_DateInit( &p_sys->end_date, p_sys->i_rate );
  405.             }
  406.             p_sys->i_state = STATE_NEXT_SYNC;
  407.             p_sys->i_frame_size = 1;
  408.         case STATE_NEXT_SYNC:
  409.             /* TODO: If pp_block == NULL, flush the buffer without checking the
  410.              * next sync word */
  411.             /* Check if next expected frame contains the sync word */
  412.             while( block_PeekOffsetBytes( &p_sys->bytestream,
  413.                                           p_sys->i_frame_size, p_header,
  414.                                           MAX_FLAC_HEADER_SIZE )
  415.                    == VLC_SUCCESS )
  416.             {
  417.                 if( p_header[0] == 0xFF && p_header[1] == 0xF8 )
  418.                 {
  419.                     /* Check if frame is valid and get frame info */
  420.                     int i_frame_length =
  421.                         SyncInfo( p_dec, p_header,
  422.                                   &p_sys->i_channels,
  423.                                   &p_sys->i_channels_conf,
  424.                                   &p_sys->i_rate,
  425.                                   &p_sys->i_bits_per_sample );
  426.                     if( i_frame_length )
  427.                     {
  428.                         p_sys->i_state = STATE_SEND_DATA;
  429.                         break;
  430.                     }
  431.                 }
  432.                 p_sys->i_frame_size++;
  433.             }
  434.             if( p_sys->i_state != STATE_SEND_DATA )
  435.             {
  436.                 /* Need more data */
  437.                 return NULL;
  438.             }
  439.         case STATE_SEND_DATA:
  440.             p_sout_block = block_New( p_dec, p_sys->i_frame_size );
  441.             /* Copy the whole frame into the buffer. When we reach this point
  442.              * we already know we have enough data available. */
  443.             block_GetBytes( &p_sys->bytestream, p_sout_block->p_buffer,
  444.                             p_sys->i_frame_size );
  445.             /* Make sure we don't reuse the same pts twice */
  446.             if( p_sys->i_pts == p_sys->bytestream.p_block->i_pts )
  447.                 p_sys->i_pts = p_sys->bytestream.p_block->i_pts = 0;
  448.             /* So p_block doesn't get re-added several times */
  449.             *pp_block = block_BytestreamPop( &p_sys->bytestream );
  450.             p_sys->i_state = STATE_NOSYNC;
  451.             /* Date management */
  452.             p_sout_block->i_pts =
  453.                 p_sout_block->i_dts = aout_DateGet( &p_sys->end_date );
  454.             aout_DateIncrement( &p_sys->end_date, p_sys->i_frame_length );
  455.             p_sout_block->i_length =
  456.                 aout_DateGet( &p_sys->end_date ) - p_sout_block->i_pts;
  457.             return p_sout_block;
  458.         }
  459.     }
  460.     return NULL;
  461. }
  462. #ifdef USE_LIBFLAC
  463. /****************************************************************************
  464.  * DecodeBlock: the whole thing
  465.  ****************************************************************************/
  466. static aout_buffer_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
  467. {
  468.     decoder_sys_t *p_sys = p_dec->p_sys;
  469.     if( !pp_block || !*pp_block ) return NULL;
  470.     p_sys->p_aout_buffer = 0;
  471.     if( ( p_sys->p_block = PacketizeBlock( p_dec, pp_block ) ) )
  472.     {
  473.         if( !FLAC__stream_decoder_process_single( p_sys->p_flac ) )
  474.         {
  475.             decoder_state_error( p_dec,
  476.                 FLAC__stream_decoder_get_state( p_sys->p_flac ) );
  477.             FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
  478.         }
  479.         /* If the decoder is in the "aborted" state,
  480.          * FLAC__stream_decoder_process_single() won't return an error. */
  481.         if( FLAC__stream_decoder_get_state(p_dec->p_sys->p_flac)
  482.             == FLAC__STREAM_DECODER_ABORTED )
  483.         {
  484.             FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
  485.         }
  486.         block_Release( p_sys->p_block );
  487.         p_sys->p_block = NULL;
  488.     }
  489.     return p_sys->p_aout_buffer;
  490. }
  491. /*****************************************************************************
  492.  * DecoderReadCallback: called by libflac when it needs more data
  493.  *****************************************************************************/
  494. static FLAC__StreamDecoderReadStatus
  495. DecoderReadCallback( const FLAC__StreamDecoder *decoder, FLAC__byte buffer[],
  496.                      unsigned *bytes, void *client_data )
  497. {
  498.     VLC_UNUSED(decoder);
  499.     decoder_t *p_dec = (decoder_t *)client_data;
  500.     decoder_sys_t *p_sys = p_dec->p_sys;
  501.     if( p_sys->p_block && p_sys->p_block->i_buffer )
  502.     {
  503.         *bytes = __MIN(*bytes, (unsigned)p_sys->p_block->i_buffer);
  504.         memcpy( buffer, p_sys->p_block->p_buffer, *bytes );
  505.         p_sys->p_block->i_buffer -= *bytes;
  506.         p_sys->p_block->p_buffer += *bytes;
  507.     }
  508.     else
  509.     {
  510.         *bytes = 0;
  511.         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  512.     }
  513.     return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  514. }
  515. /*****************************************************************************
  516.  * DecoderWriteCallback: called by libflac to output decoded samples
  517.  *****************************************************************************/
  518. static FLAC__StreamDecoderWriteStatus
  519. DecoderWriteCallback( const FLAC__StreamDecoder *decoder,
  520.                       const FLAC__Frame *frame,
  521.                       const FLAC__int32 *const buffer[], void *client_data )
  522. {
  523.     /* XXX it supposes our internal format is WG4 */
  524.     static const int ppi_reorder[1+8][8] = {
  525.         {-1},
  526.         { 0, },
  527.         { 0, 1 },
  528.         { 0, 1, 2 },
  529.         { 0, 1, 2, 3 },
  530.         { 0, 1, 3, 4, 2 },
  531.         { 0, 1, 4, 5, 2, 3 },
  532.         { 0, 1, 6, 2, 3, 4, 5 },    /* 7.0 Unspecified by flac */
  533.         { 0, 1, 6, 7, 2, 3, 4, 5 }, /* 7.1 Unspecified by flac */
  534.     };
  535.     VLC_UNUSED(decoder);
  536.     decoder_t *p_dec = (decoder_t *)client_data;
  537.     decoder_sys_t *p_sys = p_dec->p_sys;
  538.     if( p_dec->fmt_out.audio.i_channels <= 0 ||
  539.         p_dec->fmt_out.audio.i_channels > 8 )
  540.         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  541.     const int * const pi_reorder = ppi_reorder[p_dec->fmt_out.audio.i_channels];
  542.     p_sys->p_aout_buffer =
  543.         decoder_NewAudioBuffer( p_dec, frame->header.blocksize );
  544.     if( p_sys->p_aout_buffer == NULL )
  545.         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  546.     switch( frame->header.bits_per_sample )
  547.     {
  548.     case 16:
  549.         Interleave16( (int16_t *)p_sys->p_aout_buffer->p_buffer, buffer, pi_reorder,
  550.                       frame->header.channels, frame->header.blocksize );
  551.         break;
  552.     case 24:
  553.         Interleave24( (int8_t *)p_sys->p_aout_buffer->p_buffer, buffer, pi_reorder,
  554.                       frame->header.channels, frame->header.blocksize );
  555.         break;
  556.     default:
  557.         Interleave32( (int32_t *)p_sys->p_aout_buffer->p_buffer, buffer, pi_reorder,
  558.                       frame->header.channels, frame->header.blocksize );
  559.     }
  560.     /* Date management (already done by packetizer) */
  561.     p_sys->p_aout_buffer->start_date = p_sys->p_block->i_pts;
  562.     p_sys->p_aout_buffer->end_date =
  563.         p_sys->p_block->i_pts + p_sys->p_block->i_length;
  564.     return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  565. }
  566. /*****************************************************************************
  567.  * DecoderMetadataCallback: called by libflac to when it encounters metadata
  568.  *****************************************************************************/
  569. static void DecoderMetadataCallback( const FLAC__StreamDecoder *decoder,
  570.                                      const FLAC__StreamMetadata *metadata,
  571.                                      void *client_data )
  572. {
  573.     VLC_UNUSED(decoder);
  574.     decoder_t *p_dec = (decoder_t *)client_data;
  575.     decoder_sys_t *p_sys = p_dec->p_sys;
  576.     if( p_dec->pf_decode_audio )
  577.     {
  578.         switch( metadata->data.stream_info.bits_per_sample )
  579.         {
  580.         case 8:
  581.             p_dec->fmt_out.i_codec = VLC_FOURCC('s','8',' ',' ');
  582.             break;
  583.         case 16:
  584.             p_dec->fmt_out.i_codec = AOUT_FMT_S16_NE;
  585.             break;
  586.         case 24:
  587.             p_dec->fmt_out.i_codec = AOUT_FMT_S24_NE;
  588.             break;
  589.         default:
  590.             msg_Dbg( p_dec, "strange bit/sample value: %d",
  591.                      metadata->data.stream_info.bits_per_sample );
  592.             p_dec->fmt_out.i_codec = VLC_FOURCC('f','i','3','2');
  593.             break;
  594.         }
  595.     }
  596.     /* Setup the format */
  597.     p_dec->fmt_out.audio.i_rate     = metadata->data.stream_info.sample_rate;
  598.     p_dec->fmt_out.audio.i_channels = metadata->data.stream_info.channels;
  599.     p_dec->fmt_out.audio.i_physical_channels =
  600.         p_dec->fmt_out.audio.i_original_channels =
  601.             pi_channels_maps[metadata->data.stream_info.channels];
  602.     p_dec->fmt_out.audio.i_bitspersample =
  603.         metadata->data.stream_info.bits_per_sample;
  604.     aout_DateInit( &p_sys->end_date, p_dec->fmt_out.audio.i_rate );
  605.     msg_Dbg( p_dec, "channels:%d samplerate:%d bitspersamples:%d",
  606.              p_dec->fmt_out.audio.i_channels, p_dec->fmt_out.audio.i_rate,
  607.              p_dec->fmt_out.audio.i_bitspersample );
  608.     p_sys->b_stream_info = true;
  609.     p_sys->stream_info = metadata->data.stream_info;
  610.     return;
  611. }
  612. /*****************************************************************************
  613.  * DecoderErrorCallback: called when the libflac decoder encounters an error
  614.  *****************************************************************************/
  615. static void DecoderErrorCallback( const FLAC__StreamDecoder *decoder,
  616.                                   FLAC__StreamDecoderErrorStatus status,
  617.                                   void *client_data )
  618. {
  619.     VLC_UNUSED(decoder);
  620.     decoder_t *p_dec = (decoder_t *)client_data;
  621.     switch( status )
  622.     {
  623.     case FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC:
  624.         msg_Warn( p_dec, "an error in the stream caused the decoder to "
  625.                  "lose synchronization." );
  626.         break;
  627.     case FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER:
  628.         msg_Err( p_dec, "the decoder encountered a corrupted frame header." );
  629.         break;
  630.     case FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH:
  631.         msg_Err( p_dec, "frame's data did not match the CRC in the "
  632.                  "footer." );
  633.         break;
  634.     default:
  635.         msg_Err( p_dec, "got decoder error: %d", status );
  636.     }
  637.     FLAC__stream_decoder_flush( p_dec->p_sys->p_flac );
  638.     return;
  639. }
  640. /*****************************************************************************
  641.  * Interleave: helper function to interleave channels
  642.  *****************************************************************************/
  643. static void Interleave32( int32_t *p_out, const int32_t * const *pp_in,
  644.                           const int pi_index[],
  645.                           int i_nb_channels, int i_samples )
  646. {
  647.     int i, j;
  648.     for ( j = 0; j < i_samples; j++ )
  649.     {
  650.         for ( i = 0; i < i_nb_channels; i++ )
  651.         {
  652.             p_out[j * i_nb_channels + i] = pp_in[pi_index[i]][j];
  653.         }
  654.     }
  655. }
  656. static void Interleave24( int8_t *p_out, const int32_t * const *pp_in,
  657.                           const int pi_index[],
  658.                           int i_nb_channels, int i_samples )
  659. {
  660.     int i, j;
  661.     for ( j = 0; j < i_samples; j++ )
  662.     {
  663.         for ( i = 0; i < i_nb_channels; i++ )
  664.         {
  665.             const int i_index = pi_index[i];
  666. #ifdef WORDS_BIGENDIAN
  667.             p_out[3*(j * i_nb_channels + i)+0] = (pp_in[i_index][j] >> 16) & 0xff;
  668.             p_out[3*(j * i_nb_channels + i)+1] = (pp_in[i_index][j] >> 8 ) & 0xff;
  669.             p_out[3*(j * i_nb_channels + i)+2] = (pp_in[i_index][j] >> 0 ) & 0xff;
  670. #else
  671.             p_out[3*(j * i_nb_channels + i)+2] = (pp_in[i_index][j] >> 16) & 0xff;
  672.             p_out[3*(j * i_nb_channels + i)+1] = (pp_in[i_index][j] >> 8 ) & 0xff;
  673.             p_out[3*(j * i_nb_channels + i)+0] = (pp_in[i_index][j] >> 0 ) & 0xff;
  674. #endif
  675.         }
  676.     }
  677. }
  678. static void Interleave16( int16_t *p_out, const int32_t * const *pp_in,
  679.                           const int pi_index[],
  680.                           int i_nb_channels, int i_samples )
  681. {
  682.     int i, j;
  683.     for ( j = 0; j < i_samples; j++ )
  684.     {
  685.         for ( i = 0; i < i_nb_channels; i++ )
  686.         {
  687.             p_out[j * i_nb_channels + i] = (int32_t)(pp_in[pi_index[i]][j]);
  688.         }
  689.     }
  690. }
  691. /*****************************************************************************
  692.  * decoder_state_error: print meaningful error messages
  693.  *****************************************************************************/
  694. static void decoder_state_error( decoder_t *p_dec,
  695.                                  FLAC__StreamDecoderState state )
  696. {
  697.     switch ( state )
  698.     {
  699.     case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  700.         msg_Dbg( p_dec, "the decoder is ready to search for metadata." );
  701.         break;
  702.     case FLAC__STREAM_DECODER_READ_METADATA:
  703.         msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
  704.                  "reading metadata." );
  705.         break;
  706.     case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  707.         msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
  708.                  "searching for the frame sync code." );
  709.         break;
  710.     case FLAC__STREAM_DECODER_READ_FRAME:
  711.         msg_Dbg( p_dec, "the decoder is ready to or is in the process of "
  712.                  "reading a frame." );
  713.         break;
  714.     case FLAC__STREAM_DECODER_END_OF_STREAM:
  715.         msg_Dbg( p_dec, "the decoder has reached the end of the stream." );
  716.         break;
  717. #ifdef USE_NEW_FLAC_API
  718.     case FLAC__STREAM_DECODER_OGG_ERROR:
  719.         msg_Err( p_dec, "error occurred in the Ogg layer." );
  720.         break;
  721.     case FLAC__STREAM_DECODER_SEEK_ERROR:
  722.         msg_Err( p_dec, "error occurred while seeking." );
  723.         break;
  724. #endif
  725.     case FLAC__STREAM_DECODER_ABORTED:
  726.         msg_Warn( p_dec, "the decoder was aborted by the read callback." );
  727.         break;
  728. #ifndef USE_NEW_FLAC_API
  729.     case FLAC__STREAM_DECODER_UNPARSEABLE_STREAM:
  730.         msg_Warn( p_dec, "the decoder encountered reserved fields in use "
  731.                  "in the stream." );
  732.         break;
  733. #endif
  734.     case FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR:
  735.         msg_Err( p_dec, "error when allocating memory." );
  736.         break;
  737. #ifndef USE_NEW_FLAC_API
  738.     case FLAC__STREAM_DECODER_ALREADY_INITIALIZED:
  739.         msg_Err( p_dec, "FLAC__stream_decoder_init() was called when the "
  740.                  "decoder was already initialized, usually because "
  741.                  "FLAC__stream_decoder_finish() was not called." );
  742.         break;
  743.     case FLAC__STREAM_DECODER_INVALID_CALLBACK:
  744.         msg_Err( p_dec, "FLAC__stream_decoder_init() was called without "
  745.                  "all callbacks being set." );
  746.         break;
  747. #endif
  748.     case FLAC__STREAM_DECODER_UNINITIALIZED:
  749.         msg_Err( p_dec, "decoder in uninitialized state." );
  750.         break;
  751.     default:
  752.         msg_Warn(p_dec, "unknown error" );
  753.     }
  754. }
  755. #endif
  756. /*****************************************************************************
  757.  * SyncInfo: parse FLAC sync info
  758.  *****************************************************************************/
  759. static int SyncInfo( decoder_t *p_dec, uint8_t *p_buf,
  760.                      unsigned int * pi_channels,
  761.                      unsigned int * pi_channels_conf,
  762.                      unsigned int * pi_sample_rate,
  763.                      int * pi_bits_per_sample )
  764. {
  765.     decoder_sys_t *p_sys = p_dec->p_sys;
  766.     int i_header, i_temp, i_read;
  767.     unsigned i_blocksize = 0;
  768.     int i_blocksize_hint = 0, i_sample_rate_hint = 0;
  769.     uint64_t i_sample_number = 0;
  770.     bool b_variable_blocksize = ( p_sys->b_stream_info &&
  771.         p_sys->stream_info.min_blocksize != p_sys->stream_info.max_blocksize );
  772.     bool b_fixed_blocksize = ( p_sys->b_stream_info &&
  773.         p_sys->stream_info.min_blocksize == p_sys->stream_info.max_blocksize );
  774.     /* Check syncword */
  775.     if( p_buf[0] != 0xFF || p_buf[1] != 0xF8 ) return 0;
  776.     /* Check there is no emulated sync code in the rest of the header */
  777.     if( p_buf[2] == 0xff || p_buf[3] == 0xFF ) return 0;
  778.     /* Find blocksize (framelength) */
  779.     switch( i_temp = p_buf[2] >> 4 )
  780.     {
  781.     case 0:
  782.         if( b_fixed_blocksize )
  783.             i_blocksize = p_sys->stream_info.min_blocksize;
  784.         else return 0; /* We can't do anything with this */
  785.         break;
  786.     case 1:
  787.         i_blocksize = 192;
  788.         break;
  789.     case 2:
  790.     case 3:
  791.     case 4:
  792.     case 5:
  793.         i_blocksize = 576 << (i_temp - 2);
  794.         break;
  795.     case 6:
  796.     case 7:
  797.         i_blocksize_hint = i_temp;
  798.         break;
  799.     case 8:
  800.     case 9:
  801.     case 10:
  802.     case 11:
  803.     case 12:
  804.     case 13:
  805.     case 14:
  806.     case 15:
  807.         i_blocksize = 256 << (i_temp - 8);
  808.         break;
  809.     }
  810.     /* Find samplerate */
  811.     switch( i_temp = p_buf[2] & 0x0f )
  812.     {
  813.     case 0:
  814.         if( p_sys->b_stream_info )
  815.             *pi_sample_rate = p_sys->stream_info.sample_rate;
  816.         else return 0; /* We can't do anything with this */
  817.         break;
  818.     case 1:
  819.     case 2:
  820.     case 3:
  821.         return 0;
  822.         break;
  823.     case 4:
  824.         *pi_sample_rate = 8000;
  825.         break;
  826.     case 5:
  827.         *pi_sample_rate = 16000;
  828.         break;
  829.     case 6:
  830.         *pi_sample_rate = 22050;
  831.         break;
  832.     case 7:
  833.         *pi_sample_rate = 24000;
  834.         break;
  835.     case 8:
  836.         *pi_sample_rate = 32000;
  837.         break;
  838.     case 9:
  839.         *pi_sample_rate = 44100;
  840.         break;
  841.     case 10:
  842.         *pi_sample_rate = 48000;
  843.         break;
  844.     case 11:
  845.         *pi_sample_rate = 96000;
  846.         break;
  847.     case 12:
  848.     case 13:
  849.     case 14:
  850.         i_sample_rate_hint = i_temp;
  851.         break;
  852.     case 15:
  853.         return 0;
  854.     }
  855.     /* Find channels */
  856.     i_temp = (unsigned)(p_buf[3] >> 4);
  857.     if( i_temp & 8 )
  858.     {
  859. #ifdef USE_LIBFLAC
  860.         int i_channel_assignment; /* ??? */
  861.         switch( i_temp & 7 )
  862.         {
  863.         case 0:
  864.             i_channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  865.             break;
  866.         case 1:
  867.             i_channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  868.             break;
  869.         case 2:
  870.             i_channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  871.             break;
  872.         default:
  873.             return 0;
  874.             break;
  875.         }
  876. #endif
  877.         *pi_channels = 2;
  878.     }
  879.     else
  880.     {
  881.         *pi_channels = i_temp + 1;
  882.         *pi_channels_conf = pi_channels_maps[ *pi_channels ];
  883.     }
  884.     /* Find bits per sample */
  885.     switch( i_temp = (unsigned)(p_buf[3] & 0x0e) >> 1 )
  886.     {
  887.     case 0:
  888.         if( p_sys->b_stream_info )
  889.             *pi_bits_per_sample = p_sys->stream_info.bits_per_sample;
  890.         else
  891.             return 0;
  892.         break;
  893.     case 1:
  894.         *pi_bits_per_sample = 8;
  895.         break;
  896.     case 2:
  897.         *pi_bits_per_sample = 12;
  898.         break;
  899.     case 4:
  900.         *pi_bits_per_sample = 16;
  901.         break;
  902.     case 5:
  903.         *pi_bits_per_sample = 20;
  904.         break;
  905.     case 6:
  906.         *pi_bits_per_sample = 24;
  907.         break;
  908.     case 3:
  909.     case 7:
  910.         return 0;
  911.         break;
  912.     }
  913.     /* Zero padding bit */
  914.     if( p_buf[3] & 0x01 ) return 0;
  915.     /* End of fixed size header */
  916.     i_header = 4;
  917.     /* Find Sample/Frame number */
  918.     if( i_blocksize_hint && b_variable_blocksize )
  919.     {
  920.         i_sample_number = read_utf8( &p_buf[i_header++], &i_read );
  921.         if( i_sample_number == INT64_C(0xffffffffffffffff) ) return 0;
  922.     }
  923.     else
  924.     {
  925.         i_sample_number = read_utf8( &p_buf[i_header++], &i_read );
  926.         if( i_sample_number == INT64_C(0xffffffffffffffff) ) return 0;
  927.         if( p_sys->b_stream_info )
  928.             i_sample_number *= p_sys->stream_info.min_blocksize;
  929.     }
  930.     i_header += i_read;
  931.     /* Read blocksize */
  932.     if( i_blocksize_hint )
  933.     {
  934.         int i_val1 = p_buf[i_header++];
  935.         if( i_blocksize_hint == 7 )
  936.         {
  937.             int i_val2 = p_buf[i_header++];
  938.             i_val1 = (i_val1 << 8) | i_val2;
  939.         }
  940.         i_blocksize = i_val1 + 1;
  941.     }
  942.     /* Read sample rate */
  943.     if( i_sample_rate_hint )
  944.     {
  945.         int i_val1 = p_buf[i_header++];
  946.         if( i_sample_rate_hint != 12 )
  947.         {
  948.             int i_val2 = p_buf[i_header++];
  949.             i_val1 = (i_val1 << 8) | i_val2;
  950.         }
  951.         if( i_sample_rate_hint == 12 ) *pi_sample_rate = i_val1 * 1000;
  952.         else if( i_sample_rate_hint == 13 ) *pi_sample_rate = i_val1;
  953.         else *pi_sample_rate = i_val1 * 10;
  954.     }
  955.     /* Check the CRC-8 byte */
  956.     if( flac_crc8( p_buf, i_header ) != p_buf[i_header] )
  957.     {
  958.         return 0;
  959.     }
  960.     /* Sanity check using stream info header when possible */
  961.     if( p_sys->b_stream_info )
  962.     {
  963.         if( i_blocksize < p_sys->stream_info.min_blocksize ||
  964.             i_blocksize > p_sys->stream_info.max_blocksize )
  965.             return 0;
  966.     }
  967.     return i_blocksize;
  968. }
  969. /* Will return 0xffffffffffffffff for an invalid utf-8 sequence */
  970. static uint64_t read_utf8( const uint8_t *p_buf, int *pi_read )
  971. {
  972.     uint64_t i_result = 0;
  973.     unsigned i, j;
  974.     if( !(p_buf[0] & 0x80) ) /* 0xxxxxxx */
  975.     {
  976.         i_result = p_buf[0];
  977.         i = 0;
  978.     }
  979.     else if( p_buf[0] & 0xC0 && !(p_buf[0] & 0x20) ) /* 110xxxxx */
  980.     {
  981.         i_result = p_buf[0] & 0x1F;
  982.         i = 1;
  983.     }
  984.     else if( p_buf[0] & 0xE0 && !(p_buf[0] & 0x10) ) /* 1110xxxx */
  985.     {
  986.         i_result = p_buf[0] & 0x0F;
  987.         i = 2;
  988.     }
  989.     else if( p_buf[0] & 0xF0 && !(p_buf[0] & 0x08) ) /* 11110xxx */
  990.     {
  991.         i_result = p_buf[0] & 0x07;
  992.         i = 3;
  993.     }
  994.     else if( p_buf[0] & 0xF8 && !(p_buf[0] & 0x04) ) /* 111110xx */
  995.     {
  996.         i_result = p_buf[0] & 0x03;
  997.         i = 4;
  998.     }
  999.     else if( p_buf[0] & 0xFC && !(p_buf[0] & 0x02) ) /* 1111110x */
  1000.     {
  1001.         i_result = p_buf[0] & 0x01;
  1002.         i = 5;
  1003.     }
  1004.     else if( p_buf[0] & 0xFE && !(p_buf[0] & 0x01) ) /* 11111110 */
  1005.     {
  1006.         i_result = 0;
  1007.         i = 6;
  1008.     }
  1009.     else {
  1010.         return INT64_C(0xffffffffffffffff);
  1011.     }
  1012.     for( j = 1; j <= i; j++ )
  1013.     {
  1014.         if( !(p_buf[j] & 0x80) || (p_buf[j] & 0x40) ) /* 10xxxxxx */
  1015.         {
  1016.             return INT64_C(0xffffffffffffffff);
  1017.         }
  1018.         i_result <<= 6;
  1019.         i_result |= (p_buf[j] & 0x3F);
  1020.     }
  1021.     *pi_read = i;
  1022.     return i_result;
  1023. }
  1024. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  1025. static const uint8_t flac_crc8_table[256] = {
  1026.         0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  1027.         0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  1028.         0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  1029.         0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  1030.         0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  1031.         0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  1032.         0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  1033.         0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  1034.         0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  1035.         0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  1036.         0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  1037.         0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  1038.         0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  1039.         0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  1040.         0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  1041.         0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  1042.         0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  1043.         0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  1044.         0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  1045.         0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  1046.         0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  1047.         0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  1048.         0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  1049.         0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  1050.         0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  1051.         0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  1052.         0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  1053.         0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  1054.         0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  1055.         0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  1056.         0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  1057.         0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  1058. };
  1059. static uint8_t flac_crc8( const uint8_t *data, unsigned len )
  1060. {
  1061.     uint8_t crc = 0;
  1062.     while(len--)
  1063.         crc = flac_crc8_table[crc ^ *data++];
  1064.     return crc;
  1065. }
  1066. #ifdef USE_LIBFLAC
  1067. /*****************************************************************************
  1068.  * encoder_sys_t : flac encoder descriptor
  1069.  *****************************************************************************/
  1070. struct encoder_sys_t
  1071. {
  1072.     /*
  1073.      * Input properties
  1074.      */
  1075.     int i_headers;
  1076.     int i_samples_delay;
  1077.     int i_channels;
  1078.     FLAC__int32 *p_buffer;
  1079.     unsigned int i_buffer;
  1080.     block_t *p_chain;
  1081.     /*
  1082.      * FLAC properties
  1083.      */
  1084.     FLAC__StreamEncoder *p_flac;
  1085.     FLAC__StreamMetadata_StreamInfo stream_info;
  1086.     /*
  1087.      * Common properties
  1088.      */
  1089.     mtime_t i_pts;
  1090. };
  1091. #define STREAMINFO_SIZE 38
  1092. static block_t *Encode( encoder_t *, aout_buffer_t * );
  1093. static FLAC__StreamEncoderWriteStatus
  1094. EncoderWriteCallback( const FLAC__StreamEncoder *encoder,
  1095.                       const FLAC__byte buffer[],
  1096.                       unsigned bytes, unsigned samples,
  1097.                       unsigned current_frame, void *client_data );
  1098. static void EncoderMetadataCallback( const FLAC__StreamEncoder *encoder,
  1099.                                      const FLAC__StreamMetadata *metadata,
  1100.                                      void *client_data );
  1101. /*****************************************************************************
  1102.  * OpenEncoder: probe the encoder and return score
  1103.  *****************************************************************************/
  1104. static int OpenEncoder( vlc_object_t *p_this )
  1105. {
  1106.     encoder_t *p_enc = (encoder_t *)p_this;
  1107.     encoder_sys_t *p_sys;
  1108.     if( p_enc->fmt_out.i_codec != VLC_FOURCC('f','l','a','c') &&
  1109.         !p_enc->b_force )
  1110.     {
  1111.         return VLC_EGENERIC;
  1112.     }
  1113.     /* Allocate the memory needed to store the decoder's structure */
  1114.     if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL )
  1115.         return VLC_ENOMEM;
  1116.     p_enc->p_sys = p_sys;
  1117.     p_enc->pf_encode_audio = Encode;
  1118.     p_enc->fmt_out.i_codec = VLC_FOURCC('f','l','a','c');
  1119.     p_sys->i_headers = 0;
  1120.     p_sys->p_buffer = 0;
  1121.     p_sys->i_buffer = 0;
  1122.     p_sys->i_samples_delay = 0;
  1123.     /* Create flac encoder */
  1124.     if( !(p_sys->p_flac = FLAC__stream_encoder_new()) )
  1125.     {
  1126.         msg_Err( p_enc, "FLAC__stream_encoder_new() failed" );
  1127.         free( p_sys );
  1128.         return VLC_EGENERIC;
  1129.     }
  1130.     FLAC__stream_encoder_set_streamable_subset( p_sys->p_flac, 1 );
  1131.     FLAC__stream_encoder_set_channels( p_sys->p_flac,
  1132.                                        p_enc->fmt_in.audio.i_channels );
  1133.     FLAC__stream_encoder_set_sample_rate( p_sys->p_flac,
  1134.                                           p_enc->fmt_in.audio.i_rate );
  1135.     FLAC__stream_encoder_set_bits_per_sample( p_sys->p_flac, 16 );
  1136.     p_enc->fmt_in.i_codec = AOUT_FMT_S16_NE;
  1137.     /* Get and store the STREAMINFO metadata block as a p_extra */
  1138.     p_sys->p_chain = 0;
  1139. #ifdef USE_NEW_FLAC_API
  1140.     if( FLAC__stream_encoder_init_stream( p_sys->p_flac,
  1141.                                           EncoderWriteCallback,
  1142.                                           NULL,
  1143.                                           NULL,
  1144.                                           EncoderMetadataCallback,
  1145.                                           p_enc )
  1146.         != FLAC__STREAM_ENCODER_INIT_STATUS_OK )
  1147.     {
  1148.         msg_Err( p_enc, "FLAC__stream_encoder_init_stream() failed" );
  1149.         FLAC__stream_encoder_delete( p_sys->p_flac );
  1150.         free( p_sys );
  1151.         return VLC_EGENERIC;
  1152.     }
  1153. #else
  1154.     FLAC__stream_encoder_set_write_callback( p_sys->p_flac,
  1155.         EncoderWriteCallback );
  1156.     FLAC__stream_encoder_set_metadata_callback( p_sys->p_flac,
  1157.         EncoderMetadataCallback );
  1158.     FLAC__stream_encoder_set_client_data( p_sys->p_flac, p_enc );
  1159.     FLAC__stream_encoder_init( p_sys->p_flac );
  1160. #endif
  1161.     return VLC_SUCCESS;
  1162. }
  1163. /****************************************************************************
  1164.  * Encode: the whole thing
  1165.  ****************************************************************************
  1166.  * This function spits out ogg packets.
  1167.  ****************************************************************************/
  1168. static block_t *Encode( encoder_t *p_enc, aout_buffer_t *p_aout_buf )
  1169. {
  1170.     encoder_sys_t *p_sys = p_enc->p_sys;
  1171.     block_t *p_chain;
  1172.     unsigned int i;
  1173.     p_sys->i_pts = p_aout_buf->start_date -
  1174.                 (mtime_t)1000000 * (mtime_t)p_sys->i_samples_delay /
  1175.                 (mtime_t)p_enc->fmt_in.audio.i_rate;
  1176.     p_sys->i_samples_delay += p_aout_buf->i_nb_samples;
  1177.     /* Convert samples to FLAC__int32 */
  1178.     if( p_sys->i_buffer < p_aout_buf->i_nb_bytes * 2 )
  1179.     {
  1180.         p_sys->p_buffer =
  1181.             realloc( p_sys->p_buffer, p_aout_buf->i_nb_bytes * 2 );
  1182.         p_sys->i_buffer = p_aout_buf->i_nb_bytes * 2;
  1183.     }
  1184.     for( i = 0 ; i < p_aout_buf->i_nb_bytes / 2 ; i++ )
  1185.     {
  1186.         p_sys->p_buffer[i]= ((int16_t *)p_aout_buf->p_buffer)[i];
  1187.     }
  1188.     FLAC__stream_encoder_process_interleaved( p_sys->p_flac, p_sys->p_buffer,
  1189.                                               p_aout_buf->i_nb_samples );
  1190.     p_chain = p_sys->p_chain;
  1191.     p_sys->p_chain = 0;
  1192.     return p_chain;
  1193. }
  1194. /*****************************************************************************
  1195.  * CloseEncoder: encoder destruction
  1196.  *****************************************************************************/
  1197. static void CloseEncoder( vlc_object_t *p_this )
  1198. {
  1199.     encoder_t *p_enc = (encoder_t *)p_this;
  1200.     encoder_sys_t *p_sys = p_enc->p_sys;
  1201.     FLAC__stream_encoder_delete( p_sys->p_flac );
  1202.     free( p_sys->p_buffer );
  1203.     free( p_sys );
  1204. }
  1205. /*****************************************************************************
  1206.  * EncoderMetadataCallback: called by libflac to output metadata
  1207.  *****************************************************************************/
  1208. static void EncoderMetadataCallback( const FLAC__StreamEncoder *encoder,
  1209.                                      const FLAC__StreamMetadata *metadata,
  1210.                                      void *client_data )
  1211. {
  1212.     VLC_UNUSED(encoder);
  1213.     encoder_t *p_enc = (encoder_t *)client_data;
  1214.     msg_Err( p_enc, "MetadataCallback: %i", metadata->type );
  1215.     return;
  1216. }
  1217. /*****************************************************************************
  1218.  * EncoderWriteCallback: called by libflac to output encoded samples
  1219.  *****************************************************************************/
  1220. static FLAC__StreamEncoderWriteStatus
  1221. EncoderWriteCallback( const FLAC__StreamEncoder *encoder,
  1222.                       const FLAC__byte buffer[],
  1223.                       unsigned bytes, unsigned samples,
  1224.                       unsigned current_frame, void *client_data )
  1225. {
  1226.     VLC_UNUSED(encoder); VLC_UNUSED(current_frame);
  1227.     encoder_t *p_enc = (encoder_t *)client_data;
  1228.     encoder_sys_t *p_sys = p_enc->p_sys;
  1229.     block_t *p_block;
  1230.     if( samples == 0 )
  1231.     {
  1232.         if( p_sys->i_headers == 1 )
  1233.         {
  1234.             msg_Dbg( p_enc, "Writing STREAMINFO: %i", bytes );
  1235.             /* Backup the STREAMINFO metadata block */
  1236.             p_enc->fmt_out.i_extra = STREAMINFO_SIZE + 4;
  1237.             p_enc->fmt_out.p_extra = malloc( STREAMINFO_SIZE + 4 );
  1238.             memcpy( p_enc->fmt_out.p_extra, "fLaC", 4 );
  1239.             memcpy( ((uint8_t *)p_enc->fmt_out.p_extra) + 4, buffer,
  1240.                     STREAMINFO_SIZE );
  1241.             /* Fake this as the last metadata block */
  1242.             ((uint8_t*)p_enc->fmt_out.p_extra)[4] |= 0x80;
  1243.         }
  1244.         p_sys->i_headers++;
  1245.         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  1246.     }
  1247.     p_block = block_New( p_enc, bytes );
  1248.     memcpy( p_block->p_buffer, buffer, bytes );
  1249.     p_block->i_dts = p_block->i_pts = p_sys->i_pts;
  1250.     p_sys->i_samples_delay -= samples;
  1251.     p_block->i_length = (mtime_t)1000000 *
  1252.         (mtime_t)samples / (mtime_t)p_enc->fmt_in.audio.i_rate;
  1253.     /* Update pts */
  1254.     p_sys->i_pts += p_block->i_length;
  1255.     block_ChainAppend( &p_sys->p_chain, p_block );
  1256.     return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  1257. }
  1258. #endif