M4MCS_API.c revision 32ed3f4dad00f8a65f7e6b38402c70d5341c57eb
1/*
2 * Copyright (C) 2004-2011 NXP Software
3 * Copyright (C) 2011 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/**
19 *************************************************************************
20 * @file   M4MCS_API.c
21 * @brief  MCS implementation (Video Compressor Service)
22 * @note   This file implements the API and the processing of the MCS
23 *************************************************************************
24 **/
25
26/**
27 ********************************************************************
28 * Includes
29 ********************************************************************
30 */
31/**
32 * OSAL headers */
33#include "M4OSA_Memory.h" /**< OSAL memory management */
34#include "M4OSA_Debug.h"  /**< OSAL debug management */
35
36/* PCM samples */
37#include "VideoEditorResampler.h"
38/**
39 * Decoder interface */
40#include "M4DECODER_Common.h"
41
42/* Encoder interface*/
43#include "M4ENCODER_common.h"
44
45/* Enable for DEBUG logging */
46//#define MCS_DUMP_PCM_TO_FILE
47#ifdef MCS_DUMP_PCM_TO_FILE
48#include <stdio.h>
49FILE *file_au_reader = NULL;
50FILE *file_pcm_decoder = NULL;
51FILE *file_pcm_encoder = NULL;
52#endif
53
54/* Core headers */
55#include "M4MCS_API.h"
56#include "M4MCS_ErrorCodes.h"
57#include "M4MCS_InternalTypes.h"
58#include "M4MCS_InternalConfig.h"
59#include "M4MCS_InternalFunctions.h"
60
61#ifdef M4MCS_SUPPORT_STILL_PICTURE
62#include "M4MCS_StillPicture.h"
63#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
64
65/* Common headers (for aac) */
66#include "M4_Common.h"
67
68#include "NXPSW_CompilerSwitches.h"
69
70#ifdef M4VSS_ENABLE_EXTERNAL_DECODERS
71#include "M4VD_EXTERNAL_Interface.h"
72#endif /* M4VSS_ENABLE_EXTERNAL_DECODERS */
73
74#include "M4AIR_API.h"
75
76/* Version */
77#define M4MCS_VERSION_MAJOR 3
78#define M4MCS_VERSION_MINOR 4
79#define M4MCS_VERSION_REVISION  3
80
81/**
82 ********************************************************************
83 * Static local functions
84 ********************************************************************
85 */
86
87static M4OSA_ERR M4MCS_intStepSet( M4MCS_InternalContext *pC );
88static M4OSA_ERR M4MCS_intPrepareVideoDecoder(
89                                    M4MCS_InternalContext *pC );
90static M4OSA_ERR M4MCS_intPrepareVideoEncoder(
91                                    M4MCS_InternalContext *pC );
92static M4OSA_ERR M4MCS_intPrepareAudioProcessing(
93                                    M4MCS_InternalContext *pC );
94static M4OSA_ERR M4MCS_intPrepareWriter( M4MCS_InternalContext *pC );
95static M4OSA_ERR M4MCS_intPrepareAudioBeginCut(
96                                    M4MCS_InternalContext *pC );
97static M4OSA_ERR M4MCS_intStepEncoding(
98                                    M4MCS_InternalContext *pC,
99                                    M4OSA_UInt8 *pTranscodedTime );
100static M4OSA_ERR M4MCS_intStepBeginVideoJump(
101                                    M4MCS_InternalContext *pC );
102static M4OSA_ERR M4MCS_intStepBeginVideoDecode(
103                                    M4MCS_InternalContext *pC );
104static M4OSA_ERR M4MCS_intAudioNullEncoding( M4MCS_InternalContext *pC );
105static M4OSA_ERR M4MCS_intAudioTranscoding( M4MCS_InternalContext *pC );
106static M4OSA_ERR M4MCS_intVideoNullEncoding( M4MCS_InternalContext *pC );
107static M4OSA_ERR M4MCS_intVideoTranscoding( M4MCS_InternalContext *pC );
108static M4OSA_ERR M4MCS_intGetInputClipProperties(
109                                    M4MCS_InternalContext   *pContext );
110static M4OSA_UInt32 M4MCS_intGetFrameSize_AMRNB(
111                                    M4OSA_MemAddr8 pAudioFrame );
112static M4OSA_UInt32 M4MCS_intGetFrameSize_EVRC(
113                                    M4OSA_MemAddr8 pAudioFrame );
114static M4OSA_ERR M4MCS_intCheckMaxFileSize( M4MCS_Context pContext );
115static M4VIDEOEDITING_Bitrate M4MCS_intGetNearestBitrate(
116                                    M4OSA_Int32 freebitrate,
117                                    M4OSA_Int8 mode );
118static M4OSA_ERR M4MCS_intCleanUp_ReadersDecoders(
119                                    M4MCS_InternalContext *pC );
120static M4OSA_ERR M4MCS_intReallocTemporaryAU(
121                                    M4OSA_MemAddr8 *addr,
122                                    M4OSA_UInt32 newSize );
123
124/**
125 **********************************************************************
126 * External function used only by VideoEditor and that does not appear
127 * in the API
128 **********************************************************************
129 */
130
131M4OSA_ERR M4MCS_open_normalMode( M4MCS_Context pContext,
132                                 M4OSA_Void *pFileIn,
133                                 M4VIDEOEDITING_FileType InputFileType,
134                                 M4OSA_Void *pFileOut,
135                                 M4OSA_Void *pTempFile );
136
137/* All errors are fatal in the MCS */
138#define M4ERR_CHECK_RETURN(err) if(M4NO_ERROR!=err) return err;
139
140/* A define used with SSRC 1.04 and above to avoid taking blocks smaller
141 * that the minimal block size
142 */
143#define M4MCS_SSRC_MINBLOCKSIZE        100
144
145static M4OSA_UChar Tab_MCS[8] =
146{
147    17, 5, 3, 3, 1, 1, 1, 1
148};
149
150M4OSA_ERR H264MCS_Getinstance( NSWAVC_MCS_t ** instance )
151{
152    NSWAVC_MCS_t *p_bs = M4OSA_NULL;
153    M4OSA_ERR err = M4NO_ERROR;
154    p_bs = (NSWAVC_MCS_t *)M4OSA_malloc(sizeof(NSWAVC_MCS_t), M4MCS,
155        (M4OSA_Char *)"NSWAVC_MCS_t");
156
157    if( M4OSA_NULL == p_bs )
158    {
159        M4OSA_TRACE1_0("H264MCS_Getinstance: allocation error");
160        return M4ERR_ALLOC;
161    }
162
163    p_bs->prev_frame_num = 0;
164    p_bs->cur_frame_num = 0;
165    p_bs->log2_max_frame_num_minus4 = 0;
166    p_bs->prev_new_frame_num = 0;
167    p_bs->is_done = 0;
168    p_bs->is_first = 1;
169
170    p_bs->m_pDecoderSpecificInfo = M4OSA_NULL;
171    p_bs->m_decoderSpecificInfoSize = 0;
172
173    p_bs->m_pEncoderSPS = M4OSA_NULL;
174    p_bs->m_encoderSPSSize = 0;
175
176    p_bs->m_pEncoderPPS = M4OSA_NULL;
177    p_bs->m_encoderPPSSize = 0;
178
179    p_bs->m_pFinalDSI = M4OSA_NULL;
180    p_bs->m_pFinalDSISize = 0;
181
182    p_bs->p_clip_sps = M4OSA_NULL;
183    p_bs->m_encoder_SPS_Cnt = 0;
184
185    p_bs->p_clip_pps = M4OSA_NULL;
186    p_bs->m_encoder_PPS_Cnt = 0;
187
188    p_bs->p_encoder_sps = M4OSA_NULL;
189    p_bs->p_encoder_pps = M4OSA_NULL;
190
191    p_bs->encoder_pps.slice_group_id = M4OSA_NULL;
192
193    *instance = (NSWAVC_MCS_t *)p_bs;
194    return err;
195}
196
197M4OSA_UInt32 H264MCS_getBits( ComBitStreamMCS_t *p_bs, M4OSA_UInt32 numBits )
198{
199    M4OSA_UInt32 ui32RetBits;
200    M4OSA_UInt8 *pbs;
201    M4OSA_Int32 bcnt;
202    p_bs->i8BitCnt -= numBits;
203    bcnt = p_bs->i8BitCnt;
204
205    /* Measure the quantity of bits to be read in ui32TempBuff */
206    ui32RetBits = p_bs->ui32TempBuff >> (32 - numBits);
207
208    /* Read numBits in ui32TempBuff */
209    p_bs->ui32TempBuff <<= numBits;
210    p_bs->bitPos += numBits;
211
212    if( bcnt > 24 )
213    {
214        return (ui32RetBits);
215    }
216    else
217    { /* at least one byte can be buffered in ui32TempBuff */
218        pbs = (M4OSA_UInt8 *)p_bs->pui8BfrPtr;
219
220        if( bcnt < (int)(p_bs->numBitsInBuffer - p_bs->bitPos) )
221        { /* not enough remaining bits in ui32TempBuff: need to be filled */
222            do
223            {
224                /* On the fly detection of EPB byte */
225                if( ( *(pbs) == 0x03)
226                    && (!(( pbs[-1])
227                    | (pbs[-2])))) //(p_bs->ui32LastTwoBytes & 0x0000FFFF) == 0)
228                {
229                    /* EPB byte found: skip it and update bitPos accordingly */
230                            (pbs)++;
231                            p_bs->bitPos += 8;
232                        }
233
234                        p_bs->ui32TempBuff |= *(pbs)++ << (24 - bcnt);
235                        bcnt += 8;
236            } while ( bcnt <= 24 );
237
238            p_bs->pui8BfrPtr = (M4OSA_Int8 *)pbs;
239            p_bs->i8BitCnt = bcnt;
240            return (ui32RetBits);
241        }
242    }
243
244    if( p_bs->bitPos <= p_bs->numBitsInBuffer )
245    {
246        return (ui32RetBits);
247    }
248    else
249    {
250        return (0);
251    }
252}
253
254M4OSA_Void H264MCS_flushBits( ComBitStreamMCS_t *p_bs, M4OSA_UInt32 numBits )
255{
256    M4OSA_UInt8 *pbs;
257    M4OSA_UInt32 bcnt;
258    p_bs->i8BitCnt -= numBits;
259    bcnt = p_bs->i8BitCnt;
260
261    p_bs->ui32TempBuff <<= numBits;
262    p_bs->bitPos += numBits;
263
264    if( bcnt > 24 )
265    {
266        return;
267    }
268    else
269    { /* at least one byte can be buffered in ui32TempBuff */
270        pbs = (M4OSA_UInt8 *)p_bs->pui8BfrPtr;
271
272        if( bcnt < (p_bs->numBitsInBuffer - p_bs->bitPos) )
273        {   /* Not enough remaining bits in ui32TempBuff: need to be filled */
274            do
275            {
276                /*  On the fly detection of EPB byte */
277                if( ( *(pbs) == 0x03) && (!(( pbs[-1]) | (pbs[-2]))) )
278                { /* JC: EPB byte found: skip it and update bitPos accordingly */
279                    (pbs)++;
280                    p_bs->bitPos += 8;
281                }
282                p_bs->ui32TempBuff |= *(pbs)++ << (24 - bcnt);
283                bcnt += 8;
284            } while ( bcnt <= 24 );
285
286            p_bs->pui8BfrPtr = (M4OSA_Int8 *)pbs;
287            p_bs->i8BitCnt = bcnt;
288        }
289    }
290
291    return;
292}
293
294M4OSA_UInt32 H264MCS_DecVLCReadExpGolombCode( ComBitStreamMCS_t *p_bs )
295{
296    M4OSA_UInt32 code, l0 = 0, l1;
297    /* Reading 32 Bits from local cache buffer of Bitstream structure*/
298    code = p_bs->ui32TempBuff;
299
300    /* Checking in first 3 bits*/
301    if( code >> 29 )
302    {
303        l0 = Tab_MCS[(code >> 29)];
304        code = code >> (32 - l0);
305        H264MCS_flushBits(p_bs, l0);
306    }
307    else
308        {
309            if( code )
310            {
311                code <<= 3;
312
313                for ( l0 = 3; code < 0x80000000; code <<= 1, l0++ );
314
315                if( l0 < 16 ) /*all useful bits are inside the 32 bits read */
316                {
317                    code = code >> (31 - l0);
318                    H264MCS_flushBits(p_bs, 2 * l0 + 1);
319                }
320                else
321            { /* Read the useful bits in 2 parts */
322                    l1 = ( l0 << 1) - 31;
323                    code >>= l0;
324                    H264MCS_flushBits(p_bs, 32);
325                    code = ( code << l1) | H264MCS_getBits(p_bs, l1);
326                }
327            }
328            else
329            {
330                H264MCS_flushBits(p_bs, 32);
331
332                if( H264MCS_getBits(p_bs, 1) )
333                {
334                    /* if number of leading 0's is 32, the only code allowed is 1 followed
335                    by 32 0's */
336
337                    /*reading 32 more bits from bitstream buffer*/
338                    code = H264MCS_getBits(p_bs, 32);
339
340                    if( code == 0 )
341                    {
342                        return (code - 1);
343                    }
344                }
345                /*if number of leading 0's is >32, then symbol is >32 bits,
346                which is an error */
347                //p_bs->state = _BS_ERR;
348                //p_bs->flags |= _BF_SYM_ERR;
349                return (0);
350            }
351        }
352
353        if( 1 ) //(p_bs->state == _BS_OK)
354        {
355            return (code - 1);
356        }
357        else
358        {
359            return (0);
360        }
361    }
362
363M4OSA_Int32 H264MCS_DecVLCReadSignedExpGolombCode( ComBitStreamMCS_t *p_bs )
364{
365    M4OSA_Int32 codeNo, ret;
366
367    /* read the unsigned code number */
368    codeNo = H264MCS_DecVLCReadExpGolombCode(p_bs);
369
370    /* map to the signed value, if value is odd then it's positive,
371    if even then it's negative, formula is (-1)^(k+1)*CEIL(k/2) */
372
373    ret = (codeNo & 0x01) ? (( codeNo + 1) >> 1) : (( -codeNo) >> 1);
374
375    return ret;
376}
377
378M4OSA_Void DecBitStreamReset_MCS( ComBitStreamMCS_t *p_bs,
379                                 M4OSA_UInt32 bytes_read )
380{
381    p_bs->bitPos = 0;
382
383    p_bs->lastTotalBits = 0;
384    p_bs->numBitsInBuffer = bytes_read << 3;
385    p_bs->readableBytesInBuffer = bytes_read;
386    //p_bs->state = M4NO_ERROR;//_BS_OK;
387    //p_bs->flags = 0;
388
389    p_bs->ui32TempBuff = 0;
390    p_bs->i8BitCnt = 0;
391    p_bs->pui8BfrPtr = (M4OSA_Int8 *)p_bs->Buffer;
392    p_bs->ui32LastTwoBytes = 0xFFFFFFFF;
393    H264MCS_getBits(p_bs, 0);
394}
395
396M4OSA_ERR NSWAVCMCS_initBitstream( NSWAVC_bitStream_t_MCS *bS )
397{
398    bS->bitPos = 0;
399    bS->byteCnt = 0;
400    bS->currBuff = 0;
401    bS->prevByte = 0xff;
402    bS->prevPrevByte = 0xff;
403
404    return M4NO_ERROR;
405}
406
407M4OSA_ERR NSWAVCMCS_putBits( NSWAVC_bitStream_t_MCS *bS, M4OSA_UInt32 value,
408                            M4OSA_UInt8 length )
409{
410    M4OSA_UInt32 maskedValue = 0, temp = 0;
411    M4OSA_UInt8 byteOne;
412
413    M4OSA_UInt32 len1 = (length == 32) ? 31 : length;
414
415    if( !(length) )
416    {
417        /* Length = 0, return OK*/
418        return M4NO_ERROR;
419    }
420
421    maskedValue = (M4OSA_UInt32)(value &(( 1 << len1) - 1));
422
423    if( 32 > (length + bS->bitPos) )
424    {
425        bS->bitPos += length;
426        bS->currBuff |= maskedValue << (32 - bS->bitPos);
427    }
428    else
429    {
430        temp = (( bS->bitPos + length) - 32);
431
432        bS->currBuff |= (maskedValue >> (temp));
433
434        byteOne =
435            bS->streamBuffer[bS->byteCnt++] = (M4OSA_UInt8)(bS->currBuff >> 24);
436
437        if( (( bS->prevPrevByte
438            == 0) & (bS->prevByte == 0) & (!(byteOne & 0xFC))) )
439        {
440            bS->byteCnt -= 1;
441            bS->prevPrevByte = bS->streamBuffer[bS->byteCnt++] = 0x03;
442            bS->prevByte = bS->streamBuffer[bS->byteCnt++] = byteOne;
443        }
444        else
445        {
446            bS->prevPrevByte = bS->prevByte;
447            bS->prevByte = byteOne;
448        }
449        byteOne = bS->streamBuffer[bS->byteCnt++] =
450            (M4OSA_UInt8)(( bS->currBuff >> 16) & 0xff);
451
452        if( (( bS->prevPrevByte
453            == 0) & (bS->prevByte == 0) & (!(byteOne & 0xFC))) )
454        {
455            bS->byteCnt -= 1;
456            bS->prevPrevByte = bS->streamBuffer[bS->byteCnt++] = 0x03;
457            bS->prevByte = bS->streamBuffer[bS->byteCnt++] = byteOne;
458        }
459        else
460        {
461            bS->prevPrevByte = bS->prevByte;
462            bS->prevByte = byteOne;
463        }
464        byteOne = bS->streamBuffer[bS->byteCnt++] =
465            (M4OSA_UInt8)(( bS->currBuff >> 8) & 0xff);
466
467        if( (( bS->prevPrevByte
468            == 0) & (bS->prevByte == 0) & (!(byteOne & 0xFC))) )
469        {
470            bS->byteCnt -= 1;
471            bS->prevPrevByte = bS->streamBuffer[bS->byteCnt++] = 0x03;
472            bS->prevByte = bS->streamBuffer[bS->byteCnt++] = byteOne;
473        }
474        else
475        {
476            bS->prevPrevByte = bS->prevByte;
477            bS->prevByte = byteOne;
478        }
479        byteOne = bS->streamBuffer[bS->byteCnt++] =
480            (M4OSA_UInt8)((bS->currBuff) &0xff);
481
482        if( (( bS->prevPrevByte
483            == 0) & (bS->prevByte == 0) & (!(byteOne & 0xFC))) )
484        {
485            bS->byteCnt -= 1;
486            bS->prevPrevByte = bS->streamBuffer[bS->byteCnt++] = 0x03;
487            bS->prevByte = bS->streamBuffer[bS->byteCnt++] = byteOne;
488        }
489        else
490        {
491            bS->prevPrevByte = bS->prevByte;
492            bS->prevByte = byteOne;
493        }
494
495        bS->currBuff = 0;
496
497        bS->currBuff |= ( maskedValue &(( 1 << temp) - 1)) << (32 - temp);
498
499        bS->bitPos = temp;
500    }
501
502    return M4NO_ERROR;
503}
504
505M4OSA_ERR NSWAVCMCS_putBit( NSWAVC_bitStream_t_MCS *bS, M4OSA_UInt32 value )
506{
507    M4OSA_UInt32 maskedValue = 0, temp = 0;
508    M4OSA_UInt8 byteOne;
509
510    maskedValue = (value ? 1 : 0);
511
512    if( 32 > (1 + bS->bitPos) )
513    {
514        bS->bitPos += 1;
515        bS->currBuff |= maskedValue << (32 - bS->bitPos);
516    }
517    else
518    {
519        temp = 0;
520
521        bS->currBuff |= (maskedValue);
522
523        /* writing it to memory*/
524        byteOne =
525            bS->streamBuffer[bS->byteCnt++] =
526            (M4OSA_UInt8)(bS->currBuff >> 24);
527
528        if( (( bS->prevPrevByte
529            == 0) & (bS->prevByte == 0) & (!(byteOne & 0xFC))) )
530        {
531            bS->byteCnt -= 1;
532            bS->prevPrevByte = bS->streamBuffer[bS->byteCnt++] = 0x03;
533            bS->prevByte = bS->streamBuffer[bS->byteCnt++] = byteOne;
534        }
535        else
536        {
537            bS->prevPrevByte = bS->prevByte;
538            bS->prevByte = byteOne;
539        }
540        byteOne = bS->streamBuffer[bS->byteCnt++] =
541            (M4OSA_UInt8)(( bS->currBuff >> 16) & 0xff);
542
543        if( (( bS->prevPrevByte
544            == 0) & (bS->prevByte == 0) & (!(byteOne & 0xFC))) )
545        {
546            bS->byteCnt -= 1;
547            bS->prevPrevByte = bS->streamBuffer[bS->byteCnt++] = 0x03;
548            bS->prevByte = bS->streamBuffer[bS->byteCnt++] = byteOne;
549        }
550        else
551        {
552            bS->prevPrevByte = bS->prevByte;
553            bS->prevByte = byteOne;
554        }
555        byteOne = bS->streamBuffer[bS->byteCnt++] =
556            (M4OSA_UInt8)(( bS->currBuff >> 8) & 0xff);
557
558        if( (( bS->prevPrevByte
559            == 0) & (bS->prevByte == 0) & (!(byteOne & 0xFC))) )
560        {
561            bS->byteCnt -= 1;
562            bS->prevPrevByte = bS->streamBuffer[bS->byteCnt++] = 0x03;
563            bS->prevByte = bS->streamBuffer[bS->byteCnt++] = byteOne;
564        }
565        else
566        {
567            bS->prevPrevByte = bS->prevByte;
568            bS->prevByte = byteOne;
569        }
570        byteOne = bS->streamBuffer[bS->byteCnt++] =
571            (M4OSA_UInt8)((bS->currBuff) &0xff);
572
573        if( (( bS->prevPrevByte
574            == 0) & (bS->prevByte == 0) & (!(byteOne & 0xFC))) )
575        {
576            bS->byteCnt -= 1;
577            bS->prevPrevByte = bS->streamBuffer[bS->byteCnt++] = 0x03;
578            bS->prevByte = bS->streamBuffer[bS->byteCnt++] = byteOne;
579        }
580        else
581        {
582            bS->prevPrevByte = bS->prevByte;
583            bS->prevByte = byteOne;
584        }
585        bS->currBuff = 0;
586        bS->bitPos = 0;
587    }
588
589    return M4NO_ERROR;
590}
591
592M4OSA_Int32 NSWAVCMCS_putRbspTbits( NSWAVC_bitStream_t_MCS *bS )
593{
594    M4OSA_UInt8 trailBits = 0;
595    M4OSA_UInt8 byteCnt = 0;
596
597    trailBits = (M4OSA_UInt8)(bS->bitPos % 8);
598
599    /* Already in the byte aligned position,
600    RBSP trailing bits will be 1000 0000 */
601    if( 0 == trailBits )
602    {
603        trailBits = (1 << 7);
604        NSWAVCMCS_putBits(bS, trailBits, 8);
605    }
606    else
607    {
608        trailBits = (8 - trailBits);
609        NSWAVCMCS_putBit(bS, 1);
610        trailBits--;
611
612        if( trailBits )
613        { /* put trailBits times zeros */
614            NSWAVCMCS_putBits(bS, 0, trailBits);
615        }
616    }
617
618    /* For writting the currBuff in streamBuff 4byte alignment is required*/
619    byteCnt = (M4OSA_UInt8)(( bS->bitPos + 4) / 8);
620
621    switch( byteCnt )
622    {
623        case 1:
624            bS->streamBuffer[bS->byteCnt++] = (M4OSA_UInt8)(bS->currBuff >> 24);
625            break;
626
627        case 2:
628            bS->streamBuffer[bS->byteCnt++] = (M4OSA_UInt8)(bS->currBuff >> 24);
629            bS->streamBuffer[bS->byteCnt++] =
630                (M4OSA_UInt8)(( bS->currBuff >> 16) & 0xff);
631            break;
632
633        case 3:
634            bS->streamBuffer[bS->byteCnt++] = (M4OSA_UInt8)(bS->currBuff >> 24);
635            bS->streamBuffer[bS->byteCnt++] =
636                (M4OSA_UInt8)(( bS->currBuff >> 16) & 0xff);
637            bS->streamBuffer[bS->byteCnt++] =
638                (M4OSA_UInt8)(( bS->currBuff >> 8) & 0xff);
639
640            break;
641
642        default:
643            /* It will not come here */
644            break;
645    }
646
647    //    bS->bitPos =0;
648    //    bS->currBuff = 0;
649
650    return M4NO_ERROR;
651}
652
653M4OSA_ERR NSWAVCMCS_uExpVLC( NSWAVC_bitStream_t_MCS *bS, M4OSA_Int32 codeNum )
654{
655
656    M4OSA_Int32 loop, temp;
657    M4OSA_Int32 data = 0;
658    M4OSA_UInt8 codeLen = 0;
659
660    /* The codeNum cannot be less than zero for this ue(v) */
661    if( codeNum < 0 )
662    {
663        return 0;
664    }
665
666    /* Implementation for Encoding of the Table 9-1 in the Standard */
667    temp = codeNum + 1;
668
669    for ( loop = 0; temp != 0; loop++ )
670    {
671        temp /= 2;
672    }
673
674    codeLen = (( loop * 2) - 1);
675
676    data = codeNum + 1;
677
678    NSWAVCMCS_putBits(bS, data, codeLen);
679
680    return M4NO_ERROR;
681}
682
683M4OSA_ERR NSWAVCMCS_sExpVLC( NSWAVC_bitStream_t_MCS *bS, M4OSA_Int32 codeNum )
684{
685
686    M4OSA_Int32 loop, temp1, temp2;
687    M4OSA_Int32 data = 0;
688    M4OSA_UInt8 codeLen = 0, isPositive = 0;
689    M4OSA_UInt32 abscodeNum;
690
691    if( codeNum > 0 )
692    {
693        isPositive = 1;
694    }
695
696    if( codeNum > 0 )
697    {
698        abscodeNum = codeNum;
699    }
700    else
701    {
702        abscodeNum = -codeNum;
703    }
704
705    temp1 = ( ( ( abscodeNum) << 1) - isPositive) + 1;
706    temp2 = temp1;
707
708    for ( loop = 0; loop < 16 && temp2 != 0; loop++ )
709    {
710        temp2 /= 2;
711    }
712
713    codeLen = ( loop * 2) - 1;
714
715    data = temp1;
716
717    NSWAVCMCS_putBits(bS, data, codeLen);
718
719    return M4NO_ERROR;
720}
721
722M4OSA_ERR H264MCS_ProcessEncodedNALU(   M4OSA_Void *ainstance,
723                                        M4OSA_UInt8 *inbuff,
724                                        M4OSA_Int32 inbuf_size,
725                                        M4OSA_UInt8 *outbuff,
726                                        M4OSA_Int32 *outbuf_size )
727{
728    ComBitStreamMCS_t *p_bs, bs;
729    NSWAVC_MCS_t *instance;
730    M4OSA_UInt8 nalu_info;
731    M4OSA_Int32 forbidden_bit, nal_ref_idc, nal_unit_type;
732    M4OSA_Int32 first_mb_in_slice, slice_type, pic_parameter_set_id, frame_num;
733    M4OSA_Int32 seq_parameter_set_id;
734    M4OSA_UInt8 temp1, temp2, temp3, temp4;
735    M4OSA_Int32 temp_frame_num;
736    M4OSA_Int32 bitstoDiacard, bytes;
737    M4OSA_UInt32 mask_bits = 0xFFFFFFFF;
738    M4OSA_Int32 new_bytes, init_bit_pos;
739    M4OSA_UInt32 nal_size;
740    M4OSA_UInt32 cnt;
741    M4OSA_UInt32 outbuffpos = 0;
742    M4OSA_UInt32 nal_size_low16, nal_size_high16;
743    M4OSA_UInt32 frame_size = 0;
744    M4OSA_UInt32 temp = 0;
745
746    // StageFright encoder does not provide the size in the first 4 bytes of the AU, add it
747    M4OSA_Int8 *pTmpBuff1 = M4OSA_NULL;
748    M4OSA_Int8 *pTmpBuff2 = M4OSA_NULL;
749
750    p_bs = &bs;
751    instance = (NSWAVC_MCS_t *)ainstance;
752
753    M4OSA_TRACE1_2(
754        "In  H264MCS_ProcessEncodedNALU with FrameSize = %d  inBuf_Size=%d",
755        frame_size, inbuf_size);
756
757    // StageFright codecs may add a start code, make sure it is not present
758
759    if( !memcmp((void *)inbuff,
760        "\x00\x00\x00\x01", 4) )
761    {
762        M4OSA_TRACE1_3(
763            "H264MCS_ProcessNALU ERROR : NALU start code has not been removed %d "
764            "0x%X 0x%X", inbuf_size, ((M4OSA_UInt32 *)inbuff)[0],
765            ((M4OSA_UInt32 *)inbuff)[1]);
766
767        return M4ERR_PARAMETER;
768    }
769
770    // StageFright encoder does not provide the size in the first 4 bytes of the AU, add it
771    pTmpBuff1 = (M4OSA_Int8 *)M4OSA_malloc(inbuf_size + 4, M4MCS,
772        (M4OSA_Char *)"tmpNALU");
773    memcpy((void *)(pTmpBuff1 + 4), (void *)inbuff,
774        inbuf_size);
775    pTmpBuff1[3] = ( (M4OSA_UInt32)inbuf_size) & 0x000000FF;
776    pTmpBuff1[2] = ( (M4OSA_UInt32)inbuf_size >> 8) & 0x000000FF;
777    pTmpBuff1[1] = ( (M4OSA_UInt32)inbuf_size >> 16) & 0x000000FF;
778    pTmpBuff1[0] = ( (M4OSA_UInt32)inbuf_size >> 24) & 0x000000FF;
779    pTmpBuff2 = (M4OSA_Int8 *)inbuff;
780    inbuff = (M4OSA_UInt8 *)pTmpBuff1;
781    inbuf_size += 4;
782
783    // Make sure the available size was set
784    if( inbuf_size >= *outbuf_size )
785    {
786        M4OSA_TRACE1_1(
787            "!!! H264MCS_ProcessNALU ERROR : specified available size is incorrect %d ",
788            *outbuf_size);
789        return M4ERR_PARAMETER;
790    }
791
792
793
794    while( (M4OSA_Int32)frame_size < inbuf_size )
795    {
796        mask_bits = 0xFFFFFFFF;
797        p_bs->Buffer = (M4OSA_UInt8 *)(inbuff + frame_size);
798
799        // Use unsigned value to fix errors due to bit sign extension, this fix should be generic
800
801        nal_size_high16 = ( ( (M4OSA_UInt8 *)p_bs->Buffer)[0] << 8)
802            + ((M4OSA_UInt8 *)p_bs->Buffer)[1];
803        nal_size_low16 = ( ( (M4OSA_UInt8 *)p_bs->Buffer)[2] << 8)
804            + ((M4OSA_UInt8 *)p_bs->Buffer)[3];
805
806        nalu_info = (unsigned char)p_bs->Buffer[4];
807
808        outbuff[outbuffpos] = p_bs->Buffer[4];
809
810        p_bs->Buffer = p_bs->Buffer + 5;
811
812        p_bs->bitPos = 0;
813        p_bs->lastTotalBits = 0;
814        p_bs->numBitsInBuffer = ( inbuf_size - frame_size - 5) << 3;
815        p_bs->readableBytesInBuffer = inbuf_size - frame_size - 5;
816
817        p_bs->ui32TempBuff = 0;
818        p_bs->i8BitCnt = 0;
819        p_bs->pui8BfrPtr = (M4OSA_Int8 *)p_bs->Buffer;
820        p_bs->ui32LastTwoBytes = 0xFFFFFFFF;
821
822        H264MCS_getBits(p_bs, 0);
823
824        nal_size = ( nal_size_high16 << 16) + nal_size_low16;
825
826        frame_size += nal_size + 4;
827
828        forbidden_bit = ( nalu_info >> 7) & 1;
829        nal_ref_idc = ( nalu_info >> 5) & 3;
830        nal_unit_type = (nalu_info) &0x1f;
831
832        NSWAVCMCS_initBitstream(&instance->encbs);
833
834        instance->encbs.streamBuffer = outbuff + outbuffpos + 1;
835
836        if( nal_unit_type == 8 )
837        {
838            M4OSA_TRACE1_0("Error : PPS");
839            return 0;
840        }
841
842        if( nal_unit_type == 7 )
843        {
844            /*SPS Packet */
845            M4OSA_TRACE1_0("Error : SPS");
846            return 0;
847        }
848
849        if( (nal_unit_type == 5) )
850        {
851            instance->frame_count = 0;
852            instance->POC_lsb = 0;
853        }
854
855        if( ( nal_unit_type == 1) || (nal_unit_type == 5) )
856        {
857            first_mb_in_slice = H264MCS_DecVLCReadExpGolombCode(p_bs);
858            slice_type = H264MCS_DecVLCReadExpGolombCode(p_bs);
859            pic_parameter_set_id = H264MCS_DecVLCReadExpGolombCode(p_bs);
860
861            /* First MB in slice */
862            NSWAVCMCS_uExpVLC(&instance->encbs, first_mb_in_slice);
863
864            /* Slice Type */
865            NSWAVCMCS_uExpVLC(&instance->encbs, slice_type);
866
867            /* Picture Parameter set Id */
868            pic_parameter_set_id = instance->encoder_pps.pic_parameter_set_id;
869            NSWAVCMCS_uExpVLC(&instance->encbs, pic_parameter_set_id);
870
871            temp = H264MCS_getBits(p_bs,
872                instance->encoder_sps.log2_max_frame_num_minus4 + 4);
873            NSWAVCMCS_putBits(&instance->encbs, instance->frame_count,
874                instance->clip_sps.log2_max_frame_num_minus4 + 4);
875
876            // In Baseline Profile: frame_mbs_only_flag should be ON
877            if( nal_unit_type == 5 )
878            {
879                temp = H264MCS_DecVLCReadExpGolombCode(p_bs);
880                NSWAVCMCS_uExpVLC(&instance->encbs, temp);
881            }
882
883            if( instance->encoder_sps.pic_order_cnt_type == 0 )
884            {
885                temp = H264MCS_getBits(p_bs,
886                    instance->encoder_sps.log2_max_pic_order_cnt_lsb_minus4
887                    + 4);
888
889                // in baseline profile field_pic_flag should be off.
890                if( instance->encoder_pps.pic_order_present_flag )
891                {
892                    temp = H264MCS_DecVLCReadSignedExpGolombCode(p_bs);
893                }
894            }
895
896            if( ( instance->encoder_sps.pic_order_cnt_type == 1)
897                && (instance->encoder_sps.delta_pic_order_always_zero_flag) )
898            {
899                temp = H264MCS_DecVLCReadSignedExpGolombCode(p_bs);
900
901                // in baseline profile field_pic_flag should be off.
902                if( instance->encoder_pps.pic_order_present_flag )
903                {
904                    temp = H264MCS_DecVLCReadSignedExpGolombCode(p_bs);
905                }
906            }
907
908            if( instance->clip_sps.pic_order_cnt_type == 0 )
909            {
910                NSWAVCMCS_putBits(&instance->encbs, instance->POC_lsb,
911                    instance->clip_sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
912
913                // in baseline profile field_pic_flag should be off.
914                if( instance->encoder_pps.pic_order_present_flag )
915                {
916                    NSWAVCMCS_sExpVLC(&instance->encbs, 0);
917                }
918            }
919
920            if( ( instance->clip_sps.pic_order_cnt_type == 1)
921                && (instance->clip_sps.delta_pic_order_always_zero_flag) )
922            {
923                NSWAVCMCS_sExpVLC(&instance->encbs, 0);
924
925                // in baseline profile field_pic_flag should be off.
926                if( instance->encoder_pps.pic_order_present_flag )
927                {
928                    NSWAVCMCS_sExpVLC(&instance->encbs, 0);
929                }
930            }
931
932            cnt = p_bs->bitPos & 0x7;
933
934            if( cnt )
935            {
936                cnt = 8 - cnt;
937                temp = H264MCS_getBits(p_bs, cnt);
938                NSWAVCMCS_putBits(&instance->encbs, temp, cnt);
939            }
940
941            cnt = p_bs->bitPos >> 3;
942
943            while( cnt < (nal_size - 2) )
944            {
945                temp = H264MCS_getBits(p_bs, 8);
946                NSWAVCMCS_putBits(&instance->encbs, temp, 8);
947                cnt = p_bs->bitPos >> 3;
948            }
949
950            temp = H264MCS_getBits(p_bs, 8);
951
952            if( temp != 0 )
953            {
954                cnt = 0;
955
956                while( ( temp & 0x1) == 0 )
957                {
958                    cnt++;
959                    temp = temp >> 1;
960                }
961                cnt++;
962                temp = temp >> 1;
963
964                if( 8 - cnt )
965                {
966                    NSWAVCMCS_putBits(&instance->encbs, temp, (8 - cnt));
967                }
968
969                NSWAVCMCS_putRbspTbits(&instance->encbs);
970            }
971            else
972            {
973
974                M4OSA_TRACE1_1(
975                    "H264MCS_ProcessEncodedNALU : 13 temp = 0 trailing bits = %d",
976                    instance->encbs.bitPos % 8);
977
978                if( instance->encbs.bitPos % 8 )
979                {
980                    NSWAVCMCS_putBits(&instance->encbs, 0,
981                        (8 - instance->encbs.bitPos % 8));
982                }
983            }
984
985            temp = instance->encbs.byteCnt;
986            temp = temp + 1;
987
988            outbuffpos = outbuffpos + temp;
989        }
990    }
991
992    *outbuf_size = outbuffpos;
993
994    instance->POC_lsb = instance->POC_lsb + 1;
995
996    if( instance->POC_lsb == instance->POC_lsb_mod )
997    {
998        instance->POC_lsb = 0;
999    }
1000    instance->frame_count = instance->frame_count + 1;
1001
1002    if( instance->frame_count == instance->frame_mod_count )
1003    {
1004        instance->frame_count = 0;
1005    }
1006
1007    // StageFright encoder does not provide the size in the first 4 bytes of the AU, add it
1008
1009    M4OSA_free((M4OSA_MemAddr32)pTmpBuff1);
1010    pTmpBuff1 = M4OSA_NULL;
1011    inbuff = (M4OSA_UInt8 *)pTmpBuff2;
1012
1013    return M4NO_ERROR;
1014}
1015
1016M4OSA_Int32 DecSPSMCS( ComBitStreamMCS_t *p_bs,
1017                      ComSequenceParameterSet_t_MCS *sps )
1018{
1019    M4OSA_UInt32 i;
1020    M4OSA_Int32 temp_max_dpb_size;
1021    M4OSA_Int32 nb_ignore_bits;
1022    M4OSA_Int32 error;
1023    M4OSA_UInt8 profile_idc, level_idc, reserved_zero_4bits,
1024        seq_parameter_set_id;
1025    M4OSA_UInt8 constraint_set0_flag, constraint_set1_flag,
1026        constraint_set2_flag, constraint_set3_flag;
1027
1028    sps->profile_idc = (M4OSA_UInt8)H264MCS_getBits(p_bs, 8);
1029    sps->constraint_set0_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1030    sps->constraint_set1_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1031    sps->constraint_set2_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1032    sps->constraint_set3_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1033    reserved_zero_4bits = (M4OSA_UInt8)H264MCS_getBits(p_bs, 4);
1034    sps->level_idc = (M4OSA_UInt8)H264MCS_getBits(p_bs, 8);
1035    sps->seq_parameter_set_id =
1036        (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1037    sps->log2_max_frame_num_minus4 =
1038        (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1039    sps->MaxFrameNum = 1 << (sps->log2_max_frame_num_minus4 + 4);
1040    sps->pic_order_cnt_type =
1041        (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1042
1043    if (sps->pic_order_cnt_type == 0)
1044    {
1045        sps->log2_max_pic_order_cnt_lsb_minus4 =
1046            (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1047        sps->MaxPicOrderCntLsb =
1048            1 << (sps->log2_max_pic_order_cnt_lsb_minus4 + 4);
1049    }
1050    else if( sps->pic_order_cnt_type == 1 )
1051    {
1052        sps->delta_pic_order_always_zero_flag =
1053            (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1054
1055        // This fix should be generic to remove codec dependency
1056
1057        sps->offset_for_non_ref_pic =
1058            H264MCS_DecVLCReadSignedExpGolombCode(p_bs);
1059        sps->offset_for_top_to_bottom_field =
1060            H264MCS_DecVLCReadSignedExpGolombCode(p_bs);
1061
1062
1063        /*num_ref_frames_in_pic_order_cnt_cycle must be in the range 0, 255*/
1064
1065        sps->num_ref_frames_in_pic_order_cnt_cycle =
1066            (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1067
1068        /* compute deltaPOC */
1069        sps->expectedDeltaPerPicOrderCntCycle = 0;
1070
1071        for ( i = 0; i < sps->num_ref_frames_in_pic_order_cnt_cycle; i++ )
1072        {
1073            // This fix should be generic to remove codec dependency
1074            sps->offset_for_ref_frame[i] =
1075                H264MCS_DecVLCReadSignedExpGolombCode(p_bs);
1076
1077            sps->expectedDeltaPerPicOrderCntCycle +=
1078                sps->offset_for_ref_frame[i];
1079        }
1080    }
1081
1082    /* num_ref_frames must be in the range 0,16 */
1083    sps->num_ref_frames = (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1084    sps->gaps_in_frame_num_value_allowed_flag =
1085        (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1086
1087    sps->pic_width_in_mbs_minus1 =
1088        (M4OSA_UInt16)H264MCS_DecVLCReadExpGolombCode(p_bs);
1089    sps->pic_height_in_map_units_minus1 =
1090        (M4OSA_UInt16)H264MCS_DecVLCReadExpGolombCode(p_bs);
1091
1092    sps->frame_mbs_only_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1093
1094    if (!sps->frame_mbs_only_flag)
1095    {
1096        sps->mb_adaptive_frame_field_flag =
1097            (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1098    }
1099    else
1100    {
1101        sps->mb_adaptive_frame_field_flag = 0;
1102    }
1103
1104    sps->PicWidthInMbs = sps->pic_width_in_mbs_minus1 + 1;
1105    sps->FrameHeightInMbs = ( 2 - sps->frame_mbs_only_flag) * \
1106        (sps->pic_height_in_map_units_minus1 + 1);
1107#ifdef _CAP_FMO_
1108
1109    sps->NumSliceGroupMapUnits =
1110        sps->PicWidthInMbs * (sps->pic_height_in_map_units_minus1 + 1);
1111    sps->MaxPicSizeInMbs = sps->PicWidthInMbs * sps->FrameHeightInMbs;
1112
1113#endif /*_CAP_FMO_*/
1114
1115    sps->direct_8x8_inference_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1116
1117    if( sps->frame_mbs_only_flag == 0 )
1118        sps->direct_8x8_inference_flag = 1;
1119
1120    sps->frame_cropping_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1121
1122    if( sps->frame_cropping_flag )
1123    {
1124        sps->frame_crop_left_offset = H264MCS_DecVLCReadExpGolombCode(p_bs);
1125        sps->frame_crop_right_offset = H264MCS_DecVLCReadExpGolombCode(p_bs);
1126        sps->frame_crop_top_offset = H264MCS_DecVLCReadExpGolombCode(p_bs);
1127        sps->frame_crop_bottom_offset = H264MCS_DecVLCReadExpGolombCode(p_bs);
1128    }
1129    else
1130    {
1131        sps->frame_crop_left_offset = 0;
1132        sps->frame_crop_right_offset = 0;
1133        sps->frame_crop_top_offset = 0;
1134        sps->frame_crop_bottom_offset = 0;
1135    }
1136
1137    sps->vui_parameters_present_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1138
1139    if (sps->vui_parameters_present_flag) {
1140        /* no error message as stream can be decoded without VUI messages */
1141    }
1142
1143    return M4NO_ERROR;
1144}
1145
1146M4OSA_Int32 DecPPSMCS( ComBitStreamMCS_t *p_bs,
1147                      ComPictureParameterSet_t_MCS *pps )
1148{
1149    M4OSA_Int32 error;
1150    M4OSA_UInt32 pic_parameter_set_id;
1151
1152#ifdef _CAP_FMO_
1153    M4OSA_UInt32 i, length, v;
1154#endif
1155
1156    M4OSA_Int32 nb_ignore_bits;
1157
1158    pic_parameter_set_id = H264MCS_DecVLCReadExpGolombCode(p_bs);
1159    pps->pic_parameter_set_id = (M4OSA_UInt8)pic_parameter_set_id;
1160
1161    pps->seq_parameter_set_id =
1162        (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1163
1164    /* entropy_coding_mode_flag must be 0 or 1 */
1165    pps->entropy_coding_mode_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1166    pps->pic_order_present_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1167
1168    pps->num_slice_groups_minus1 =
1169        (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1170
1171#ifdef _CAP_FMO_
1172    /* FMO stuff begins here */
1173
1174    pps->map_initialized = FALSE;
1175
1176    if( pps->num_slice_groups_minus1 > 0 )
1177    {
1178        pps->slice_group_map_type =
1179            (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1180
1181        switch( pps->slice_group_map_type )
1182        {
1183            case 0:
1184                for ( i = 0; i <= pps->num_slice_groups_minus1; i++ )
1185                {
1186                    pps->run_length_minus1[i] =
1187                        (M4OSA_UInt16)H264MCS_DecVLCReadExpGolombCode(p_bs);
1188                }
1189                break;
1190
1191            case 2:
1192                for ( i = 0; i < pps->num_slice_groups_minus1; i++ )
1193                {
1194                    pps->top_left[i] =
1195                        (M4OSA_UInt16)H264MCS_DecVLCReadExpGolombCode(p_bs);
1196                    pps->bottom_right[i] =
1197                        (M4OSA_UInt16)H264MCS_DecVLCReadExpGolombCode(p_bs);
1198                }
1199                break;
1200
1201            case 3:
1202            case 4:
1203            case 5:
1204                pps->slice_group_change_direction_flag =
1205                    (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1206                pps->slice_group_change_rate_minus1 =
1207                    (M4OSA_UInt16)H264MCS_DecVLCReadExpGolombCode(p_bs);
1208                break;
1209
1210            case 6:
1211                pps->pic_size_in_map_units_minus1 =
1212                    (M4OSA_UInt16)H264MCS_DecVLCReadExpGolombCode(p_bs);
1213
1214                pps->slice_group_id = (H264UInt8
1215                    *)M4H264Dec_malloc((pps->pic_size_in_map_units_minus1
1216                    + 1), M4H264_COREID, (M4OSA_Char *)"PPS");
1217
1218                if (M4OSA_NULL == pps->slice_group_id)
1219                {
1220                    M4OSA_TRACE1_0("DecPPSMCS: allocation error");
1221                    return M4ERR_ALLOC;
1222                }
1223
1224                for ( length = 0, v = pps->num_slice_groups_minus1 + 1; v != 0;
1225                    v >>= 1, length++ );
1226
1227                    for ( i = 0; i <= pps->pic_size_in_map_units_minus1; i++ )
1228                    {
1229                        pps->slice_group_id[i] =
1230                            (M4OSA_UInt8)getBits(p_vlc_engine->p_bs, length);
1231                    }
1232                    break;
1233        }
1234    }
1235    else
1236    {
1237        pps->slice_group_map_type = 0;
1238    }
1239    /* End of FMO stuff */
1240
1241#else
1242
1243#endif /* _CAP_FMO_ */
1244
1245    /* num_ref_idx_l0_active_minus1 must be in the range 0, 31 */
1246
1247    pps->num_ref_idx_l0_active_minus1 =
1248        (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1249    /* num_ref_idx_l1_active_minus1 must be in the range 0, 31 */
1250    pps->num_ref_idx_l1_active_minus1 =
1251        (M4OSA_UInt8)H264MCS_DecVLCReadExpGolombCode(p_bs);
1252    pps->weighted_pred_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1253
1254    /* weighted_bipred_idc must be in the range 0,2 */
1255    pps->weighted_bipred_idc = (M4OSA_Bool)H264MCS_getBits(p_bs, 2);
1256
1257    /* pic_init_qp_minus26 must be in the range -26,25 */
1258    pps->pic_init_qp_minus26 =
1259        (M4OSA_Int16)H264MCS_DecVLCReadSignedExpGolombCode(p_bs);
1260
1261    /* pic_init_qs_minus26 must be in the range -26,25 */
1262    pps->pic_init_qs_minus26 =
1263        (M4OSA_Int16)H264MCS_DecVLCReadSignedExpGolombCode(p_bs);
1264
1265    /* chroma_qp_index_offset must be in the range -12,+12 */
1266    pps->chroma_qp_index_offset =
1267        (M4OSA_Int16)H264MCS_DecVLCReadSignedExpGolombCode(p_bs);
1268    pps->deblocking_filter_control_present_flag =
1269        (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1270    pps->constrained_intra_pred_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1271    pps->redundant_pic_cnt_present_flag = (M4OSA_Bool)H264MCS_getBits(p_bs, 1);
1272
1273    return M4NO_ERROR;
1274}
1275
1276M4OSA_ERR H264MCS_ProcessSPS_PPS( NSWAVC_MCS_t *instance, M4OSA_UInt8 *inbuff,
1277                                 M4OSA_Int32 inbuf_size )
1278{
1279    ComBitStreamMCS_t *p_bs, bs;
1280    ComBitStreamMCS_t *p_bs1, bs1;
1281
1282    M4OSA_UInt8 nalu_info = 0;
1283    M4OSA_Int32 forbidden_bit, nal_ref_idc, nal_unit_type;
1284    M4OSA_Int32 first_mb_in_slice, slice_type, pic_parameter_set_id = 0,
1285        frame_num;
1286    M4OSA_Int32 seq_parameter_set_id;
1287    M4OSA_UInt8 temp1, temp2, temp3, temp4;
1288    M4OSA_Int32 temp_frame_num;
1289    M4OSA_Int32 bitstoDiacard, bytes;
1290    M4OSA_UInt32 mask_bits = 0xFFFFFFFF;
1291    M4OSA_Int32 new_bytes, init_bit_pos;
1292    M4OSA_UInt32 nal_size = 0;
1293    M4OSA_UInt32 cnt, cnt1;
1294    M4OSA_UInt32 outbuffpos = 0;
1295    M4OSA_UInt32 nal_size_low16, nal_size_high16;
1296    M4OSA_UInt32 frame_size = 0;
1297    M4OSA_UInt32 temp = 0;
1298    M4OSA_UInt8 *lClipDSI;
1299    M4OSA_UInt8 *lClipDSI_PPS_start;
1300    M4OSA_UInt32 lClipDSI_PPS_offset = 0;
1301
1302    M4OSA_UInt8 *lPPS_Buffer = M4OSA_NULL;
1303    M4OSA_UInt32 lPPS_Buffer_Size = 0;
1304
1305    M4OSA_UInt32 lSize, lSize1;
1306    M4OSA_UInt32 lActiveSPSID_Clip;
1307    M4OSA_UInt32 lClipPPSRemBits = 0;
1308
1309    M4OSA_UInt32 lEncoder_SPSID = 0;
1310    M4OSA_UInt32 lEncoder_PPSID = 0;
1311    M4OSA_UInt32 lEncoderPPSRemBits = 0;
1312    M4OSA_UInt32 lFound = 0;
1313    M4OSA_UInt32 size;
1314
1315    M4OSA_UInt8 Clip_SPSID[32] = { 0 };
1316    M4OSA_UInt8 Clip_UsedSPSID[32] = { 0 };
1317    M4OSA_UInt8 Clip_PPSID[256] = { 0 };
1318    M4OSA_UInt8 Clip_SPSID_in_PPS[256] = { 0 };
1319    M4OSA_UInt8 Clip_UsedPPSID[256] = { 0 };
1320    M4OSA_ERR err = M4NO_ERROR;
1321
1322    p_bs = &bs;
1323    p_bs1 = &bs1;
1324
1325    /* Find the active SPS ID */
1326    M4OSA_DEBUG_IF2((M4OSA_NULL == instance), M4ERR_PARAMETER,
1327        "H264MCS_ProcessSPS_PPS: instance is M4OSA_NULL");
1328
1329    switch( instance->m_pDecoderSpecificInfo[4] & 0x3 )
1330    {
1331        case 0:
1332            instance->m_Num_Bytes_NALUnitLength = 1;
1333            break;
1334
1335        case 1:
1336            instance->m_Num_Bytes_NALUnitLength = 2;
1337            break;
1338
1339        case 3:
1340            //Note: Current code supports only this...
1341            instance->m_Num_Bytes_NALUnitLength = 4;
1342            break;
1343    }
1344
1345    instance->m_encoder_SPS_Cnt = instance->m_pDecoderSpecificInfo[5] & 0x1F;
1346
1347    lClipDSI = instance->m_pDecoderSpecificInfo + 6;
1348
1349    lClipDSI_PPS_offset = 6;
1350
1351    for ( cnt = 0; cnt < instance->m_encoder_SPS_Cnt; cnt++ )
1352    {
1353        lSize = ( lClipDSI[0] << 8) + lClipDSI[1];
1354        lClipDSI = lClipDSI + 2;
1355
1356        p_bs->Buffer = (M4OSA_UInt8 *)(lClipDSI + 4);
1357        DecBitStreamReset_MCS(p_bs, lSize - 4);
1358
1359        Clip_SPSID[cnt] = H264MCS_DecVLCReadExpGolombCode(p_bs);
1360        Clip_UsedSPSID[Clip_SPSID[cnt]] = 1;
1361
1362        lClipDSI = lClipDSI + lSize;
1363        lClipDSI_PPS_offset = lClipDSI_PPS_offset + 2 + lSize;
1364    }
1365
1366    instance->m_encoder_PPS_Cnt = lClipDSI[0];
1367    lClipDSI = lClipDSI + 1;
1368
1369    lClipDSI_PPS_start = lClipDSI;
1370
1371    for ( cnt = 0; cnt < instance->m_encoder_PPS_Cnt; cnt++ )
1372    {
1373        lSize = ( lClipDSI[0] << 8) + lClipDSI[1];
1374        lClipDSI = lClipDSI + 2;
1375
1376        p_bs->Buffer = (M4OSA_UInt8 *)(lClipDSI + 1);
1377        DecBitStreamReset_MCS(p_bs, lSize - 1);
1378
1379        Clip_PPSID[cnt] = H264MCS_DecVLCReadExpGolombCode(p_bs);
1380        Clip_UsedPPSID[Clip_PPSID[cnt]] = 1;
1381        Clip_SPSID_in_PPS[Clip_PPSID[cnt]] =
1382            H264MCS_DecVLCReadExpGolombCode(p_bs);
1383
1384        lClipDSI = lClipDSI + lSize;
1385    }
1386
1387    /* Find the clip SPS ID used at the cut start frame */
1388    while( ( (M4OSA_Int32)frame_size) < inbuf_size )
1389    {
1390        mask_bits = 0xFFFFFFFF;
1391        p_bs->Buffer = (M4OSA_UInt8 *)(inbuff + frame_size);
1392
1393        switch( instance->m_Num_Bytes_NALUnitLength )
1394        {
1395            case 1:
1396                nal_size = (unsigned char)p_bs->Buffer[0];
1397                nalu_info = (unsigned char)p_bs->Buffer[1];
1398                p_bs->Buffer = p_bs->Buffer + 2;
1399
1400                break;
1401
1402            case 2:
1403                nal_size_high16 = ( p_bs->Buffer[0] << 8) + p_bs->Buffer[1];
1404                nal_size = nal_size_high16;
1405                nalu_info = (unsigned char)p_bs->Buffer[2];
1406                p_bs->Buffer = p_bs->Buffer + 3;
1407
1408                break;
1409
1410            case 4:
1411                nal_size_high16 = ( p_bs->Buffer[0] << 8) + p_bs->Buffer[1];
1412                nal_size_low16 = ( p_bs->Buffer[2] << 8) + p_bs->Buffer[3];
1413                nal_size = ( nal_size_high16 << 16) + nal_size_low16;
1414                nalu_info = (unsigned char)p_bs->Buffer[4];
1415                p_bs->Buffer = p_bs->Buffer + 5;
1416
1417                break;
1418        }
1419
1420        p_bs->bitPos = 0;
1421        p_bs->lastTotalBits = 0;
1422        p_bs->numBitsInBuffer =
1423            ( inbuf_size - frame_size - instance->m_Num_Bytes_NALUnitLength - 1)
1424            << 3;
1425        p_bs->readableBytesInBuffer =
1426            inbuf_size - frame_size - instance->m_Num_Bytes_NALUnitLength - 1;
1427
1428        p_bs->ui32TempBuff = 0;
1429        p_bs->i8BitCnt = 0;
1430        p_bs->pui8BfrPtr = (M4OSA_Int8 *)p_bs->Buffer;
1431        p_bs->ui32LastTwoBytes = 0xFFFFFFFF;
1432
1433        H264MCS_getBits(p_bs, 0);
1434
1435        frame_size += nal_size + instance->m_Num_Bytes_NALUnitLength;
1436
1437        forbidden_bit = ( nalu_info >> 7) & 1;
1438        nal_ref_idc = ( nalu_info >> 5) & 3;
1439        nal_unit_type = (nalu_info) &0x1f;
1440
1441        if( nal_unit_type == 8 )
1442        {
1443            M4OSA_TRACE1_0("H264MCS_ProcessSPS_PPS() Error: PPS");
1444            return err;
1445        }
1446
1447        if( nal_unit_type == 7 )
1448        {
1449            /*SPS Packet */
1450            M4OSA_TRACE1_0("H264MCS_ProcessSPS_PPS() Error: SPS");
1451            return err;
1452        }
1453
1454        if( ( nal_unit_type == 1) || (nal_unit_type == 5) )
1455        {
1456            first_mb_in_slice = H264MCS_DecVLCReadExpGolombCode(p_bs);
1457            slice_type = H264MCS_DecVLCReadExpGolombCode(p_bs);
1458            pic_parameter_set_id = H264MCS_DecVLCReadExpGolombCode(p_bs);
1459            break;
1460        }
1461    }
1462
1463    lActiveSPSID_Clip = Clip_SPSID_in_PPS[pic_parameter_set_id];
1464
1465    instance->final_SPS_ID = lActiveSPSID_Clip;
1466    /* Do we need to add encoder PPS to clip PPS */
1467
1468    lClipDSI = lClipDSI_PPS_start;
1469
1470    for ( cnt = 0; cnt < instance->m_encoder_PPS_Cnt; cnt++ )
1471    {
1472        lSize = ( lClipDSI[0] << 8) + lClipDSI[1];
1473        lClipDSI = lClipDSI + 2;
1474
1475        if( lActiveSPSID_Clip == Clip_SPSID_in_PPS[Clip_PPSID[cnt]] )
1476        {
1477            lPPS_Buffer = lClipDSI + 1;
1478            lPPS_Buffer_Size = lSize - 1;
1479
1480            p_bs->Buffer = (M4OSA_UInt8 *)(lClipDSI + 1);
1481            DecBitStreamReset_MCS(p_bs, lSize - 1);
1482
1483            Clip_PPSID[cnt] = H264MCS_DecVLCReadExpGolombCode(p_bs);
1484            Clip_UsedPPSID[Clip_SPSID[cnt]] = 1;
1485            Clip_SPSID_in_PPS[cnt] = H264MCS_DecVLCReadExpGolombCode(p_bs);
1486            lClipPPSRemBits = ( lSize - 1) << 3;
1487            lClipPPSRemBits -= p_bs->bitPos;
1488
1489            temp = lClipDSI[lSize - 1];
1490
1491            cnt1 = 0;
1492
1493            while( ( temp & 0x1) == 0 )
1494            {
1495                cnt1++;
1496                temp = temp >> 1;
1497            }
1498            cnt1++;
1499            lClipPPSRemBits -= cnt1;
1500
1501            lSize1 = instance->m_encoderPPSSize - 1;
1502            p_bs1->Buffer = (M4OSA_UInt8 *)(instance->m_pEncoderPPS + 1);
1503            DecBitStreamReset_MCS(p_bs1, lSize1);
1504
1505            lEncoder_PPSID = H264MCS_DecVLCReadExpGolombCode(p_bs1);
1506            lEncoder_SPSID = H264MCS_DecVLCReadExpGolombCode(p_bs1);
1507
1508            lEncoderPPSRemBits = ( lSize1) << 3;
1509            lEncoderPPSRemBits -= p_bs1->bitPos;
1510
1511            temp = instance->m_pEncoderPPS[lSize1];
1512
1513            cnt1 = 0;
1514
1515            while( ( temp & 0x1) == 0 )
1516            {
1517                cnt1++;
1518                temp = temp >> 1;
1519            }
1520            cnt1++;
1521            lEncoderPPSRemBits -= cnt1;
1522
1523            if( lEncoderPPSRemBits == lClipPPSRemBits )
1524            {
1525                while( lEncoderPPSRemBits > 8 )
1526                {
1527                    temp1 = H264MCS_getBits(p_bs, 8);
1528                    temp2 = H264MCS_getBits(p_bs1, 8);
1529                    lEncoderPPSRemBits = lEncoderPPSRemBits - 8;
1530
1531                    if( temp1 != temp2 )
1532                    {
1533                        break;
1534                    }
1535                }
1536
1537                if( lEncoderPPSRemBits < 8 )
1538                {
1539                    if( lEncoderPPSRemBits )
1540                    {
1541                        temp1 = H264MCS_getBits(p_bs, lEncoderPPSRemBits);
1542                        temp2 = H264MCS_getBits(p_bs1, lEncoderPPSRemBits);
1543
1544                        if( temp1 == temp2 )
1545                        {
1546                            lFound = 1;
1547                        }
1548                    }
1549                    else
1550                    {
1551                        lFound = 1;
1552                    }
1553                }
1554                break;
1555            }
1556        }
1557
1558        lClipDSI = lClipDSI + lSize;
1559    }
1560
1561    /* Form the final SPS and PPS data */
1562
1563    if( lFound == 1 )
1564    {
1565        /* No need to add PPS */
1566        instance->final_PPS_ID = Clip_PPSID[cnt];
1567
1568        instance->m_pFinalDSI =
1569            (M4OSA_UInt8 *)M4OSA_malloc(instance->m_decoderSpecificInfoSize,
1570            M4MCS, (M4OSA_Char *)"instance->m_pFinalDSI");
1571
1572        if( instance->m_pFinalDSI == M4OSA_NULL )
1573        {
1574            M4OSA_TRACE1_0("instance->m_pFinalDSI: allocation error");
1575            return M4ERR_ALLOC;
1576        }
1577
1578        instance->m_pFinalDSISize = instance->m_decoderSpecificInfoSize;
1579        memcpy((void *)instance->m_pFinalDSI,
1580            (void *)instance->m_pDecoderSpecificInfo,
1581            instance->m_decoderSpecificInfoSize);
1582    }
1583    else
1584    {
1585        /* ADD PPS */
1586        /* find the free PPS ID */
1587
1588        cnt = 0;
1589
1590        while( Clip_UsedPPSID[cnt] )
1591        {
1592            cnt++;
1593        }
1594        instance->final_PPS_ID = cnt;
1595
1596        size = instance->m_decoderSpecificInfoSize + instance->m_encoderPPSSize
1597            + 10;
1598
1599        instance->m_pFinalDSI = (M4OSA_UInt8 *)M4OSA_malloc(size, M4MCS,
1600            (M4OSA_Char *)"instance->m_pFinalDSI");
1601
1602        if( instance->m_pFinalDSI == M4OSA_NULL )
1603        {
1604            M4OSA_TRACE1_0("instance->m_pFinalDSI: allocation error");
1605            return M4ERR_ALLOC;
1606        }
1607
1608        memcpy((void *)instance->m_pFinalDSI,
1609            (void *)instance->m_pDecoderSpecificInfo,
1610            instance->m_decoderSpecificInfoSize);
1611
1612        temp = instance->m_pFinalDSI[lClipDSI_PPS_offset];
1613        temp = temp + 1;
1614        instance->m_pFinalDSI[lClipDSI_PPS_offset] = temp;
1615
1616        //temp = instance->m_pEncoderPPS[0];
1617        lSize1 = instance->m_encoderPPSSize - 1;
1618        p_bs1->Buffer = (M4OSA_UInt8 *)(instance->m_pEncoderPPS + 1);
1619        DecBitStreamReset_MCS(p_bs1, lSize1);
1620
1621        lEncoder_PPSID = H264MCS_DecVLCReadExpGolombCode(p_bs1);
1622        lEncoder_SPSID = H264MCS_DecVLCReadExpGolombCode(p_bs1);
1623
1624        lEncoderPPSRemBits = ( lSize1) << 3;
1625        lEncoderPPSRemBits -= p_bs1->bitPos;
1626
1627        temp = instance->m_pEncoderPPS[lSize1];
1628
1629        cnt1 = 0;
1630
1631        while( ( temp & 0x1) == 0 )
1632        {
1633            cnt1++;
1634            temp = temp >> 1;
1635        }
1636        cnt1++;
1637        lEncoderPPSRemBits -= cnt1;
1638
1639        instance->m_pFinalDSI[instance->m_decoderSpecificInfoSize + 2] =
1640            instance->m_pEncoderPPS[0];
1641
1642        NSWAVCMCS_initBitstream(&instance->encbs);
1643        instance->encbs.streamBuffer =
1644            &(instance->m_pFinalDSI[instance->m_decoderSpecificInfoSize + 3]);
1645        lPPS_Buffer = instance->encbs.streamBuffer;
1646
1647        NSWAVCMCS_uExpVLC(&instance->encbs, instance->final_PPS_ID);
1648        NSWAVCMCS_uExpVLC(&instance->encbs, instance->final_SPS_ID);
1649
1650        while( lEncoderPPSRemBits > 8 )
1651        {
1652            temp = H264MCS_getBits(p_bs1, 8);
1653            NSWAVCMCS_putBits(&instance->encbs, temp, 8);
1654            lEncoderPPSRemBits = lEncoderPPSRemBits - 8;
1655        }
1656
1657        if( lEncoderPPSRemBits )
1658        {
1659            temp = H264MCS_getBits(p_bs1, lEncoderPPSRemBits);
1660            NSWAVCMCS_putBits(&instance->encbs, temp, lEncoderPPSRemBits);
1661        }
1662        NSWAVCMCS_putRbspTbits(&instance->encbs);
1663
1664        temp = instance->encbs.byteCnt;
1665        lPPS_Buffer_Size = temp;
1666        temp = temp + 1;
1667
1668        instance->m_pFinalDSI[instance->m_decoderSpecificInfoSize] =
1669            ( temp >> 8) & 0xFF;
1670        instance->m_pFinalDSI[instance->m_decoderSpecificInfoSize + 1] =
1671            (temp) &0xFF;
1672        instance->m_pFinalDSISize =
1673            instance->m_decoderSpecificInfoSize + 2 + temp;
1674    }
1675
1676    /* Decode the clip SPS */
1677
1678    lClipDSI = instance->m_pDecoderSpecificInfo + 6;
1679
1680    lClipDSI_PPS_offset = 6;
1681
1682    for ( cnt = 0; cnt < instance->m_encoder_SPS_Cnt; cnt++ )
1683    {
1684        lSize = ( lClipDSI[0] << 8) + lClipDSI[1];
1685        lClipDSI = lClipDSI + 2;
1686
1687        if( Clip_SPSID[cnt] == instance->final_SPS_ID )
1688        {
1689            p_bs->Buffer = (M4OSA_UInt8 *)(lClipDSI + 1);
1690            DecBitStreamReset_MCS(p_bs, lSize - 1);
1691
1692            DecSPSMCS(p_bs, &instance->clip_sps);
1693
1694            //Clip_SPSID[cnt] = H264MCS_DecVLCReadExpGolombCode(p_bs);
1695            //Clip_UsedSPSID[Clip_SPSID[cnt]] = 1;
1696            break;
1697        }
1698
1699        lClipDSI = lClipDSI + lSize;
1700    }
1701
1702    /* Decode encoder SPS */
1703    p_bs->Buffer = (M4OSA_UInt8 *)(instance->m_pEncoderSPS + 1);
1704    DecBitStreamReset_MCS(p_bs, instance->m_encoderSPSSize - 1);
1705    DecSPSMCS(p_bs, &instance->encoder_sps);
1706
1707    if( instance->encoder_sps.num_ref_frames
1708    > instance->clip_sps.num_ref_frames )
1709    {
1710        return 100; //not supported
1711    }
1712
1713    p_bs->Buffer = (M4OSA_UInt8 *)lPPS_Buffer;
1714    DecBitStreamReset_MCS(p_bs, lPPS_Buffer_Size);
1715    DecPPSMCS(p_bs, &instance->encoder_pps);
1716
1717    instance->frame_count = 0;
1718    instance->frame_mod_count =
1719        1 << (instance->clip_sps.log2_max_frame_num_minus4 + 4);
1720
1721    instance->POC_lsb = 0;
1722    instance->POC_lsb_mod =
1723        1 << (instance->clip_sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
1724
1725    return M4NO_ERROR;
1726}
1727
1728M4OSA_ERR H264MCS_ProcessNALU( NSWAVC_MCS_t *ainstance, M4OSA_UInt8 *inbuff,
1729                               M4OSA_Int32 inbuf_size, M4OSA_UInt8 *outbuff,
1730                               M4OSA_Int32 *outbuf_size )
1731{
1732    ComBitStreamMCS_t *p_bs, bs;
1733    NSWAVC_MCS_t *instance;
1734    M4OSA_UInt8 nalu_info;
1735    M4OSA_Int32 forbidden_bit, nal_ref_idc, nal_unit_type;
1736    M4OSA_Int32 first_mb_in_slice, slice_type, pic_parameter_set_id, frame_num;
1737    M4OSA_Int32 seq_parameter_set_id;
1738    M4OSA_UInt8 temp1, temp2, temp3, temp4;
1739    M4OSA_Int32 temp_frame_num;
1740    M4OSA_Int32 bitstoDiacard, bytes;
1741    M4OSA_UInt32 mask_bits = 0xFFFFFFFF;
1742    M4OSA_Int32 new_bytes, init_bit_pos;
1743    M4OSA_UInt32 nal_size;
1744    M4OSA_UInt32 cnt;
1745    M4OSA_UInt32 outbuffpos = 0;
1746    //#ifndef DGR_FIX // + new
1747    M4OSA_UInt32 nal_size_low16, nal_size_high16;
1748    //#endif // + end new
1749    M4OSA_UInt32 frame_size = 0;
1750    M4OSA_UInt32 temp = 0;
1751    M4OSA_ERR err = M4NO_ERROR;
1752    M4OSA_UInt8 *buff;
1753
1754    p_bs = &bs;
1755    instance = (NSWAVC_MCS_t *)ainstance;
1756    M4OSA_DEBUG_IF2((M4OSA_NULL == instance), M4ERR_PARAMETER,
1757        "H264MCS_ProcessNALU: instance is M4OSA_NULL");
1758
1759    if( instance->is_done )
1760        return err;
1761
1762    inbuff[0] = 0x00;
1763    inbuff[1] = 0x00;
1764    inbuff[2] = 0x00;
1765    inbuff[3] = 0x01;
1766
1767
1768    while( (M4OSA_Int32)frame_size < inbuf_size )
1769    {
1770        mask_bits = 0xFFFFFFFF;
1771        p_bs->Buffer = (M4OSA_UInt8 *)(inbuff + frame_size);
1772
1773
1774        nalu_info = (unsigned char)p_bs->Buffer[4];
1775
1776        outbuff[outbuffpos] = p_bs->Buffer[0];
1777        outbuff[outbuffpos + 1] = p_bs->Buffer[1];
1778        outbuff[outbuffpos + 2] = p_bs->Buffer[2];
1779        outbuff[outbuffpos + 3] = p_bs->Buffer[3];
1780        outbuff[outbuffpos + 4] = p_bs->Buffer[4];
1781
1782        p_bs->Buffer = p_bs->Buffer + 5;
1783
1784        p_bs->bitPos = 0;
1785        p_bs->lastTotalBits = 0;
1786        p_bs->numBitsInBuffer = ( inbuf_size - frame_size - 5) << 3;
1787        p_bs->readableBytesInBuffer = inbuf_size - frame_size - 5;
1788
1789        p_bs->ui32TempBuff = 0;
1790        p_bs->i8BitCnt = 0;
1791        p_bs->pui8BfrPtr = (M4OSA_Int8 *)p_bs->Buffer;
1792        p_bs->ui32LastTwoBytes = 0xFFFFFFFF;
1793
1794        H264MCS_getBits(p_bs, 0);
1795
1796
1797
1798        nal_size = inbuf_size - frame_size - 4;
1799        buff = inbuff + frame_size + 4;
1800
1801        while( nal_size > 4 )
1802        {
1803            if( ( buff[0] == 0x00) && (buff[1] == 0x00) && (buff[2] == 0x00)
1804                && (buff[3] == 0x01) )
1805            {
1806                break;
1807            }
1808            buff = buff + 1;
1809            nal_size = nal_size - 1;
1810        }
1811
1812        if( nal_size <= 4 )
1813        {
1814            nal_size = 0;
1815        }
1816        nal_size = ( inbuf_size - frame_size - 4) - nal_size;
1817
1818        //      M4OSA_TRACE1_3("H264MCS_ProcessNALU frame  input buff size = %d  current position
1819        //= %d   nal size = %d",
1820        //  inbuf_size, frame_size,  nal_size + 4);
1821        frame_size += nal_size + 4;
1822
1823
1824
1825        forbidden_bit = ( nalu_info >> 7) & 1;
1826        nal_ref_idc = ( nalu_info >> 5) & 3;
1827        nal_unit_type = (nalu_info) &0x1f;
1828
1829        if( nal_unit_type == 5 )
1830        {
1831            /*IDR/PPS Packet - Do nothing*/
1832            instance->is_done = 1;
1833            return err;
1834        }
1835
1836        NSWAVCMCS_initBitstream(&instance->encbs);
1837        instance->encbs.streamBuffer = outbuff + outbuffpos + 5;
1838
1839        if( nal_unit_type == 8 )
1840        {
1841            M4OSA_TRACE1_0("H264MCS_ProcessNALU() Error: PPS");
1842            return err;
1843        }
1844
1845        if( nal_unit_type == 7 )
1846        {
1847            /*SPS Packet */
1848            M4OSA_TRACE1_0("H264MCS_ProcessNALU() Error: SPS");
1849            return 0;
1850        }
1851
1852        if( (nal_unit_type == 5) )
1853        {
1854            instance->frame_count = 0;
1855            instance->POC_lsb = 0;
1856        }
1857
1858        if( (nal_unit_type == 1) )
1859        {
1860            first_mb_in_slice = H264MCS_DecVLCReadExpGolombCode(p_bs);
1861            NSWAVCMCS_uExpVLC(&instance->encbs, first_mb_in_slice);
1862
1863            slice_type = H264MCS_DecVLCReadExpGolombCode(p_bs);
1864            NSWAVCMCS_uExpVLC(&instance->encbs, slice_type);
1865
1866            pic_parameter_set_id = H264MCS_DecVLCReadExpGolombCode(p_bs);
1867            NSWAVCMCS_uExpVLC(&instance->encbs, pic_parameter_set_id);
1868
1869            temp = H264MCS_getBits(p_bs,
1870                instance->clip_sps.log2_max_frame_num_minus4 + 4);
1871            NSWAVCMCS_putBits(&instance->encbs, instance->frame_count,
1872                instance->clip_sps.log2_max_frame_num_minus4 + 4);
1873
1874            // In Baseline Profile: frame_mbs_only_flag should be ON
1875
1876            if( nal_unit_type == 5 )
1877            {
1878                temp = H264MCS_DecVLCReadExpGolombCode(p_bs);
1879                NSWAVCMCS_uExpVLC(&instance->encbs, temp);
1880            }
1881
1882            if( instance->clip_sps.pic_order_cnt_type == 0 )
1883            {
1884                temp = H264MCS_getBits(p_bs,
1885                    instance->clip_sps.log2_max_pic_order_cnt_lsb_minus4
1886                    + 4);
1887                NSWAVCMCS_putBits(&instance->encbs, instance->POC_lsb,
1888                    instance->clip_sps.log2_max_pic_order_cnt_lsb_minus4 + 4);
1889            }
1890
1891            if( ( instance->clip_sps.pic_order_cnt_type == 1)
1892                && (instance->clip_sps.delta_pic_order_always_zero_flag) )
1893            {
1894                temp = H264MCS_DecVLCReadSignedExpGolombCode(p_bs);
1895                NSWAVCMCS_sExpVLC(&instance->encbs, temp);
1896            }
1897
1898            cnt = p_bs->bitPos & 0x7;
1899
1900            if( cnt )
1901            {
1902                cnt = 8 - cnt;
1903                temp = H264MCS_getBits(p_bs, cnt);
1904                NSWAVCMCS_putBits(&instance->encbs, temp, cnt);
1905            }
1906
1907            cnt = p_bs->bitPos >> 3;
1908
1909            while( cnt < (nal_size - 2) )
1910            {
1911                temp = H264MCS_getBits(p_bs, 8);
1912                NSWAVCMCS_putBits(&instance->encbs, temp, 8);
1913                cnt = p_bs->bitPos >> 3;
1914            }
1915
1916            temp = H264MCS_getBits(p_bs, 8);
1917
1918            if( temp != 0 )
1919            {
1920                cnt = 0;
1921
1922                while( ( temp & 0x1) == 0 )
1923                {
1924                    cnt++;
1925                    temp = temp >> 1;
1926                }
1927                cnt++;
1928                temp = temp >> 1;
1929
1930                if( 8 - cnt )
1931                {
1932                    NSWAVCMCS_putBits(&instance->encbs, temp, (8 - cnt));
1933                }
1934
1935                NSWAVCMCS_putRbspTbits(&instance->encbs);
1936            }
1937            else
1938            {
1939                if( instance->encbs.bitPos % 8 )
1940                {
1941                    NSWAVCMCS_putBits(&instance->encbs, 0,
1942                        (8 - instance->encbs.bitPos % 8));
1943                }
1944            }
1945
1946            temp = instance->encbs.byteCnt;
1947            temp = temp + 1;
1948
1949            outbuff[outbuffpos] = (M4OSA_UInt8)(( temp >> 24) & 0xFF);
1950            outbuff[outbuffpos + 1] = (M4OSA_UInt8)(( temp >> 16) & 0xFF);
1951            outbuff[outbuffpos + 2] = (M4OSA_UInt8)(( temp >> 8) & 0xFF);
1952            outbuff[outbuffpos + 3] = (M4OSA_UInt8)((temp) &0xFF);
1953            outbuffpos = outbuffpos + temp + 4;
1954        }
1955        else
1956        {
1957            p_bs->Buffer = p_bs->Buffer - 5;
1958            memcpy((void *) &outbuff[outbuffpos],
1959                (void *)p_bs->Buffer, nal_size + 4);
1960
1961            outbuff[outbuffpos] = (M4OSA_UInt8)((nal_size >> 24)& 0xFF);
1962        outbuff[outbuffpos + 1] = (M4OSA_UInt8)((nal_size >> 16)& 0xFF);;
1963        outbuff[outbuffpos + 2] = (M4OSA_UInt8)((nal_size >> 8)& 0xFF);;
1964        outbuff[outbuffpos + 3] = (M4OSA_UInt8)((nal_size)& 0xFF);;
1965
1966            outbuffpos = outbuffpos + nal_size + 4;
1967        }
1968    }
1969
1970    *outbuf_size = outbuffpos;
1971
1972    instance->POC_lsb = instance->POC_lsb + 1;
1973
1974    if( instance->POC_lsb == instance->POC_lsb_mod )
1975    {
1976        instance->POC_lsb = 0;
1977    }
1978    instance->frame_count = instance->frame_count + 1;
1979
1980    if( instance->frame_count == instance->frame_mod_count )
1981    {
1982        instance->frame_count = 0;
1983    }
1984    return M4NO_ERROR;
1985}
1986
1987M4OSA_ERR   M4MCS_convetFromByteStreamtoNALStream(  M4OSA_UInt8 *inbuff,
1988                                                    M4OSA_UInt32 inbuf_size )
1989{
1990    M4OSA_ERR err = M4NO_ERROR;
1991    M4OSA_UInt32 framesize = 0;
1992    M4OSA_UInt32 nal_size =0;
1993    M4OSA_UInt8 *buff;
1994
1995
1996    while(framesize < inbuf_size)
1997    {
1998            nal_size = inbuf_size - framesize - 4;
1999            buff =  inbuff + framesize + 4;
2000
2001            while(nal_size > 4){
2002                if((buff[0] == 0x00) &&
2003                (buff[1] == 0x00) &&
2004                (buff[2] == 0x00) &&
2005                (buff[3] == 0x01)){
2006                    break;
2007                }
2008                buff = buff + 1;
2009                nal_size = nal_size -1;
2010            }
2011
2012            if(nal_size <= 4){
2013                nal_size = 0;
2014            }
2015            nal_size = (inbuf_size - framesize - 4) - nal_size;
2016
2017        inbuff[framesize + 0]  = (M4OSA_UInt8)((nal_size >> 24)& 0xFF);
2018        inbuff[framesize + 1]  = (M4OSA_UInt8)((nal_size >> 16)& 0xFF);
2019        inbuff[framesize + 2]  = (M4OSA_UInt8)((nal_size >> 8)& 0xFF);
2020        inbuff[framesize + 3]  = (M4OSA_UInt8)((nal_size )& 0xFF);
2021        framesize += nal_size + 4;
2022
2023        M4OSA_TRACE1_2("M4MCS_convetFromByteStreamtoNALStream framesize = %x nalsize = %x",
2024            framesize, nal_size)
2025    }
2026
2027    return  err;
2028}
2029
2030
2031M4OSA_ERR H264MCS_Freeinstance( NSWAVC_MCS_t *instance )
2032{
2033    M4OSA_ERR err = M4NO_ERROR;
2034    M4OSA_DEBUG_IF2((M4OSA_NULL == instance), M4ERR_PARAMETER,
2035        "H264MCS_Freeinstance: instance is M4OSA_NULL");
2036
2037    if( M4OSA_NULL != instance->encoder_pps.slice_group_id )
2038    {
2039        M4OSA_free((M4OSA_MemAddr32)instance->encoder_pps.slice_group_id);
2040    }
2041
2042    if( M4OSA_NULL != instance->p_encoder_sps )
2043    {
2044        M4OSA_free((M4OSA_MemAddr32)instance->p_encoder_sps);
2045        instance->p_encoder_sps = M4OSA_NULL;
2046    }
2047
2048    if( M4OSA_NULL != instance->p_encoder_pps )
2049    {
2050        M4OSA_free((M4OSA_MemAddr32)instance->p_encoder_pps);
2051        instance->p_encoder_pps = M4OSA_NULL;
2052    }
2053
2054    if( M4OSA_NULL != instance->m_pFinalDSI )
2055    {
2056        M4OSA_free((M4OSA_MemAddr32)instance->m_pFinalDSI);
2057        instance->m_pFinalDSI = M4OSA_NULL;
2058    }
2059
2060    if( M4OSA_NULL != instance )
2061    {
2062        M4OSA_free((M4OSA_MemAddr32)instance);
2063        instance = M4OSA_NULL;
2064    }
2065
2066    return err;
2067}
2068/**
2069 ******************************************************************************
2070 * M4OSA_ERR M4MCS_getVersion(M4_VersionInfo* pVersionInfo);
2071 * @brief    Get the MCS version.
2072 * @note Can be called anytime. Do not need any context.
2073 * @param    pVersionInfo        (OUT) Pointer to a version info structure
2074 * @return   M4NO_ERROR:         No error
2075 * @return   M4ERR_PARAMETER:    pVersionInfo is M4OSA_NULL (If Debug Level >= 2)
2076 ******************************************************************************
2077 */
2078M4OSA_ERR M4MCS_getVersion( M4_VersionInfo *pVersionInfo )
2079{
2080    M4OSA_TRACE3_1("M4MCS_getVersion called with pVersionInfo=0x%x",
2081        pVersionInfo);
2082
2083    /**
2084    * Check input parameters */
2085    M4OSA_DEBUG_IF2((M4OSA_NULL == pVersionInfo), M4ERR_PARAMETER,
2086        "M4MCS_getVersion: pVersionInfo is M4OSA_NULL");
2087
2088    pVersionInfo->m_major = M4MCS_VERSION_MAJOR;
2089    pVersionInfo->m_minor = M4MCS_VERSION_MINOR;
2090    pVersionInfo->m_revision = M4MCS_VERSION_REVISION;
2091
2092    /**
2093    * Return with no error */
2094    M4OSA_TRACE3_0("M4MCS_getVersion(): returning M4NO_ERROR");
2095    return M4NO_ERROR;
2096}
2097
2098/**
2099 ******************************************************************************
2100 * @brief    Initializes the MCS (allocates an execution context).
2101 * @note
2102 * @param    pContext            (OUT) Pointer on the MCS context to allocate
2103 * @param    pFileReadPtrFct     (IN) Pointer to OSAL file reader functions
2104 * @param    pFileWritePtrFct    (IN) Pointer to OSAL file writer functions
2105 * @return   M4NO_ERROR:         No error
2106 * @return   M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (If Debug Level >= 2)
2107 * @return   M4ERR_ALLOC:        There is no more available memory
2108 ******************************************************************************
2109 */
2110
2111M4OSA_ERR M4MCS_init( M4MCS_Context *pContext,
2112                     M4OSA_FileReadPointer *pFileReadPtrFct,
2113                     M4OSA_FileWriterPointer *pFileWritePtrFct )
2114{
2115    M4MCS_InternalContext *pC = M4OSA_NULL;
2116    M4OSA_ERR err;
2117
2118    M4OSA_TRACE3_3(
2119        "M4MCS_init called with pContext=0x%x, pFileReadPtrFct=0x%x, pFileWritePtrFct=0x%x",
2120        pContext, pFileReadPtrFct, pFileWritePtrFct);
2121
2122    /**
2123    * Check input parameters */
2124    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
2125        "M4MCS_init: pContext is M4OSA_NULL");
2126    M4OSA_DEBUG_IF2((M4OSA_NULL == pFileReadPtrFct), M4ERR_PARAMETER,
2127        "M4MCS_init: pFileReadPtrFct is M4OSA_NULL");
2128    M4OSA_DEBUG_IF2((M4OSA_NULL == pFileWritePtrFct), M4ERR_PARAMETER,
2129        "M4MCS_init: pFileWritePtrFct is M4OSA_NULL");
2130
2131    /**
2132    * Allocate the MCS context and return it to the user */
2133    pC = (M4MCS_InternalContext *)M4OSA_malloc(sizeof(M4MCS_InternalContext),
2134        M4MCS, (M4OSA_Char *)"M4MCS_InternalContext");
2135    *pContext = pC;
2136
2137    if( M4OSA_NULL == pC )
2138    {
2139        M4OSA_TRACE1_0(
2140            "M4MCS_init(): unable to allocate M4MCS_InternalContext, returning M4ERR_ALLOC");
2141        return M4ERR_ALLOC;
2142    }
2143
2144    /**
2145    * Init the context. All pointers must be initialized to M4OSA_NULL
2146    * because CleanUp() can be called just after Init(). */
2147    pC->State = M4MCS_kState_CREATED;
2148    pC->pOsaFileReadPtr = pFileReadPtrFct;
2149    pC->pOsaFileWritPtr = pFileWritePtrFct;
2150    pC->VideoState = M4MCS_kStreamState_NOSTREAM;
2151    pC->AudioState = M4MCS_kStreamState_NOSTREAM;
2152    pC->noaudio = M4OSA_FALSE;
2153    pC->novideo = M4OSA_FALSE;
2154    pC->uiProgress = 0;
2155
2156    /**
2157    * Reader stuff */
2158    pC->pInputFile = M4OSA_NULL;
2159    pC->InputFileType = M4VIDEOEDITING_kFileType_Unsupported;
2160    pC->bFileOpenedInFastMode = M4OSA_FALSE;
2161    pC->pReaderContext = M4OSA_NULL;
2162    pC->pReaderVideoStream = M4OSA_NULL;
2163    pC->pReaderAudioStream = M4OSA_NULL;
2164    pC->bUnsupportedVideoFound = M4OSA_FALSE;
2165    pC->bUnsupportedAudioFound = M4OSA_FALSE;
2166    pC->iAudioCtsOffset = 0;
2167    /* First temporary video AU to have more precise end video cut*/
2168    pC->ReaderVideoAU1.m_structSize = 0;
2169    /* Second temporary video AU to have more precise end video cut*/
2170    pC->ReaderVideoAU2.m_structSize = 0;
2171    pC->ReaderAudioAU1.m_structSize = 0;
2172    pC->ReaderAudioAU2.m_structSize = 0;
2173    pC->m_audioAUDuration = 0;
2174    pC->m_pDataAddress1 = M4OSA_NULL;
2175    pC->m_pDataAddress2 = M4OSA_NULL;
2176    /* First temporary video AU data to have more precise end video cut*/
2177    pC->m_pDataVideoAddress1 = M4OSA_NULL;
2178    /* Second temporary video AU data to have more precise end video cut*/
2179    pC->m_pDataVideoAddress2 = M4OSA_NULL;
2180
2181    /**
2182    * Video decoder stuff */
2183    pC->pViDecCtxt = M4OSA_NULL;
2184    pC->dViDecStartingCts = 0.0;
2185    pC->iVideoBeginDecIncr = 0;
2186    pC->dViDecCurrentCts = 0.0;
2187    pC->dCtsIncrement = 0.0;
2188    pC->isRenderDup = M4OSA_FALSE;
2189
2190    /**
2191    * Video encoder stuff */
2192    pC->pViEncCtxt = M4OSA_NULL;
2193    pC->pPreResizeFrame = M4OSA_NULL;
2194    pC->uiEncVideoBitrate = 0;
2195    pC->bActivateEmp = M4OSA_FALSE;
2196    pC->encoderState = M4MCS_kNoEncoder;
2197
2198    /**
2199    * Audio decoder stuff */
2200    pC->pAudioDecCtxt = M4OSA_NULL;
2201    pC->AudioDecBufferIn.m_dataAddress = M4OSA_NULL;
2202    pC->AudioDecBufferIn.m_bufferSize = 0;
2203    pC->AudioDecBufferOut.m_dataAddress = M4OSA_NULL;
2204    pC->AudioDecBufferOut.m_bufferSize = 0;
2205    pC->pPosInDecBufferOut = M4OSA_NULL;
2206    /**
2207    * Ssrc stuff */
2208    pC->pSsrcBufferIn = M4OSA_NULL;
2209    pC->pSsrcBufferOut = M4OSA_NULL;
2210    pC->pPosInSsrcBufferIn = M4OSA_NULL;
2211    pC->pPosInSsrcBufferOut = M4OSA_NULL;
2212    pC->iSsrcNbSamplIn = 0;
2213    pC->iSsrcNbSamplOut = 0;
2214    pC->SsrcScratch = M4OSA_NULL;
2215    pC->pLVAudioResampler = M4OSA_NULL;
2216    /**
2217    * Audio encoder */
2218    pC->pAudioEncCtxt = M4OSA_NULL;
2219    pC->pAudioEncDSI.infoSize = 0;
2220    pC->pAudioEncDSI.pInfo = M4OSA_NULL;
2221    pC->pAudioEncoderBuffer = M4OSA_NULL;
2222    pC->pPosInAudioEncoderBuffer = M4OSA_NULL;
2223    pC->audioEncoderGranularity = 0;
2224
2225    /**
2226    * Writer stuff */
2227    pC->pOutputFile = M4OSA_NULL;
2228    pC->pTemporaryFile = M4OSA_NULL;
2229    pC->pWriterContext = M4OSA_NULL;
2230    pC->uiVideoAUCount = 0;
2231    pC->uiVideoMaxAuSize = 0;
2232    pC->uiVideoMaxChunckSize = 0;
2233    pC->uiAudioAUCount = 0;
2234    pC->uiAudioMaxAuSize = 0;
2235
2236    pC->uiAudioCts = 0;
2237    pC->b_isRawWriter = M4OSA_FALSE;
2238    pC->pOutputPCMfile = M4OSA_NULL;
2239
2240    /* Encoding config */
2241    pC->EncodingVideoFormat = M4ENCODER_kNULL; /**< No format set yet */
2242    pC->EncodingWidth = 0;                     /**< No size set yet */
2243    pC->EncodingHeight = 0;                    /**< No size set yet */
2244    pC->EncodingVideoFramerate = 0;            /**< No framerate set yet */
2245
2246    pC->uiBeginCutTime = 0;                    /**< No begin cut */
2247    pC->uiEndCutTime = 0;                      /**< No end cut */
2248    pC->uiMaxFileSize = 0;                     /**< No limit */
2249    pC->uiAudioBitrate =
2250        M4VIDEOEDITING_kUndefinedBitrate; /**< No bitrate set yet */
2251    pC->uiVideoBitrate =
2252        M4VIDEOEDITING_kUndefinedBitrate; /**< No bitrate set yet */
2253
2254#ifdef TIMESCALE_BUG
2255
2256    /* By default, timescale is not modified; if this value is not 0, timescale is
2257     * modified without decode/encode process
2258     */
2259    pC->uiVideoTimescale = 0;
2260    pC->uiTimescaleLength = 0;
2261    pC->uiOrigVideoTimescale = 0;
2262    pC->uiOrigTimescaleLength = 0;
2263
2264#endif
2265
2266    pC->WriterVideoStream.streamType = M4SYS_kVideoUnknown;
2267    pC->WriterVideoStreamInfo.Header.pBuf = M4OSA_NULL;
2268    pC->WriterAudioStream.streamType = M4SYS_kAudioUnknown;
2269
2270    pC->outputVideoTimescale = 0;
2271
2272    /*FB 2008/10/20: add media rendering parameter and AIR context to keep media aspect ratio*/
2273    pC->MediaRendering = M4MCS_kResizing;
2274    pC->m_air_context = M4OSA_NULL;
2275    /**/
2276
2277    /**
2278    * FlB 2009.03.04: add audio Effects*/
2279    pC->pEffects = M4OSA_NULL;
2280    pC->nbEffects = 0;
2281    pC->pActiveEffectNumber = -1;
2282    /**/
2283
2284    /*
2285    * Reset pointers for media and codecs interfaces */
2286    err = M4MCS_clearInterfaceTables(pC);
2287    M4ERR_CHECK_RETURN(err);
2288
2289    /*
2290    *  Call the media and codecs subscription module */
2291    err = M4MCS_subscribeMediaAndCodec(pC);
2292    M4ERR_CHECK_RETURN(err);
2293
2294#ifdef M4MCS_SUPPORT_STILL_PICTURE
2295    /**
2296    * Initialize the Still picture part of MCS*/
2297
2298    err = M4MCS_stillPicInit(pC, pFileReadPtrFct, pFileWritePtrFct);
2299    M4ERR_CHECK_RETURN(err);
2300
2301    pC->m_bIsStillPicture = M4OSA_FALSE;
2302
2303#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
2304
2305    pC->m_pInstance = M4OSA_NULL;
2306    pC->H264MCSTempBuffer = M4OSA_NULL;
2307    pC->H264MCSTempBufferSize = 0;
2308    pC->H264MCSTempBufferDataSize = 0;
2309    pC->bH264Trim = M4OSA_FALSE;
2310
2311    /* Flag to get the last decoded frame cts */
2312    pC->bLastDecodedFrameCTS = M4OSA_FALSE;
2313
2314    if( pC->m_pInstance == M4OSA_NULL )
2315    {
2316        err = H264MCS_Getinstance(&pC->m_pInstance);
2317    }
2318    pC->bExtOMXAudDecoder = M4OSA_FALSE;
2319
2320    /**
2321    * Return with no error */
2322    M4OSA_TRACE3_0("M4MCS_init(): returning M4NO_ERROR");
2323    return M4NO_ERROR;
2324}
2325
2326/**
2327 ******************************************************************************
2328 * M4OSA_ERR M4MCS_open(M4MCS_Context pContext, M4OSA_Void* pFileIn,
2329 *                         M4OSA_Void* pFileOut, M4OSA_Void* pTempFile);
2330 * @brief   Set the MCS input and output files.
2331 * @note    It opens the input file, but the output file is not created yet.
2332 * @param   pContext            (IN) MCS context
2333 * @param   pFileIn             (IN) Input file to transcode (The type of this parameter
2334 *                                 (URL, pipe...) depends on the OSAL implementation).
2335 * @param   mediaType           (IN) Container type (.3gp,.amr,mp3 ...) of input file.
2336 * @param   pFileOut            (IN) Output file to create  (The type of this parameter
2337 *                                    (URL, pipe...) depends on the OSAL implementation).
2338 * @param   pTempFile           (IN) Temporary file for the constant memory writer to
2339 *                                     store metadata ("moov.bin").
2340 * @return  M4NO_ERROR:         No error
2341 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (debug only)
2342 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
2343 * @return  M4ERR_ALLOC:        There is no more available memory
2344 * @return  M4ERR_FILE_NOT_FOUND:   The input file has not been found
2345 * @return  M4MCS_ERR_INVALID_INPUT_FILE:   The input file is not a valid file, or is corrupted
2346 * @return  M4MCS_ERR_INPUT_FILE_CONTAINS_NO_SUPPORTED_STREAM:  The input file contains no
2347 *                                supported audio or video stream
2348 ******************************************************************************
2349 */
2350M4OSA_ERR M4MCS_open( M4MCS_Context pContext, M4OSA_Void *pFileIn,
2351                     M4VIDEOEDITING_FileType InputFileType, M4OSA_Void *pFileOut,
2352                     M4OSA_Void *pTempFile )
2353{
2354    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
2355    M4OSA_ERR err;
2356
2357    M4READER_MediaFamily mediaFamily;
2358    M4_StreamHandler *pStreamHandler;
2359
2360    M4OSA_TRACE2_3(
2361        "M4MCS_open called with pContext=0x%x, pFileIn=0x%x, pFileOut=0x%x",
2362        pContext, pFileIn, pFileOut);
2363
2364    /**
2365    * Check input parameters */
2366    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
2367        "M4MCS_open: pContext is M4OSA_NULL");
2368    M4OSA_DEBUG_IF2((M4OSA_NULL == pFileIn), M4ERR_PARAMETER,
2369        "M4MCS_open: pFileIn is M4OSA_NULL");
2370
2371    if( ( InputFileType == M4VIDEOEDITING_kFileType_JPG)
2372        || (InputFileType == M4VIDEOEDITING_kFileType_PNG)
2373        || (InputFileType == M4VIDEOEDITING_kFileType_GIF)
2374        || (InputFileType == M4VIDEOEDITING_kFileType_BMP) )
2375    {
2376#ifdef M4MCS_SUPPORT_STILL_PICTURE
2377        /**
2378        * Indicate that we must use the still picture functions*/
2379
2380        pC->m_bIsStillPicture = M4OSA_TRUE;
2381
2382        /**
2383        * Call the still picture MCS functions*/
2384        return M4MCS_stillPicOpen(pC, pFileIn, InputFileType, pFileOut);
2385
2386#else
2387
2388        M4OSA_TRACE1_0(
2389            "M4MCS_open: Still picture is not supported with this version of MCS");
2390        return M4MCS_ERR_INPUT_FILE_CONTAINS_NO_SUPPORTED_STREAM;
2391
2392#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
2393
2394    }
2395
2396    /**
2397    * Check state automaton */
2398    if( M4MCS_kState_CREATED != pC->State )
2399    {
2400        M4OSA_TRACE1_1("M4MCS_open(): Wrong State (%d), returning M4ERR_STATE",
2401            pC->State);
2402        return M4ERR_STATE;
2403    }
2404
2405    /* Copy function input parameters into our context */
2406    pC->pInputFile = pFileIn;
2407    pC->InputFileType = InputFileType;
2408    pC->pOutputFile = pFileOut;
2409    pC->pTemporaryFile = pTempFile;
2410    pC->uiProgress = 0;
2411
2412    /***********************************/
2413    /* Open input file with the reader */
2414    /***********************************/
2415
2416    err = M4MCS_setCurrentReader(pContext, pC->InputFileType);
2417    M4ERR_CHECK_RETURN(err);
2418
2419    /**
2420    * Reset reader related variables */
2421    pC->VideoState = M4MCS_kStreamState_NOSTREAM;
2422    pC->AudioState = M4MCS_kStreamState_NOSTREAM;
2423    pC->pReaderVideoStream = M4OSA_NULL;
2424    pC->pReaderAudioStream = M4OSA_NULL;
2425
2426    /*******************************************************/
2427    /* Initializes the reader shell and open the data file */
2428    /*******************************************************/
2429    err = pC->m_pReader->m_pFctCreate(&pC->pReaderContext);
2430
2431    if( M4NO_ERROR != err )
2432    {
2433        M4OSA_TRACE1_1("M4MCS_open(): m_pReader->m_pFctCreate returns 0x%x",
2434            err);
2435        return err;
2436    }
2437
2438    /**
2439    * Link the reader interface to the reader context */
2440    pC->m_pReaderDataIt->m_readerContext = pC->pReaderContext;
2441
2442    /**
2443    * Set the reader shell file access functions */
2444    err = pC->m_pReader->m_pFctSetOption(pC->pReaderContext,
2445        M4READER_kOptionID_SetOsaFileReaderFctsPtr,
2446        (M4OSA_DataOption)pC->pOsaFileReadPtr);
2447
2448    if( M4NO_ERROR != err )
2449    {
2450        M4OSA_TRACE1_1("M4MCS_open(): m_pReader->m_pFctSetOption returns 0x%x",
2451            err);
2452        return err;
2453    }
2454
2455#ifdef M4MCS_WITH_FAST_OPEN
2456
2457    if( M4OSA_FALSE == pC->bFileOpenedInFastMode )
2458    {
2459        M4OSA_Bool trueValue = M4OSA_TRUE;
2460
2461        /* For first call use fast open mode */
2462        err = pC->m_pReader->m_pFctSetOption(pC->pReaderContext,
2463            M4READER_3GP_kOptionID_FastOpenMode, &trueValue);
2464
2465        if( M4NO_ERROR == err )
2466        {
2467            pC->bFileOpenedInFastMode = M4OSA_TRUE;
2468        }
2469        else
2470        {
2471            M4OSA_TRACE1_1(
2472                "M4MCS_open(): M4READER_3GP_kOptionID_FastOpenMode returns 0x%x",
2473                err);
2474
2475            if( ( ( (M4OSA_UInt32)M4ERR_BAD_OPTION_ID) == err)
2476                || (( (M4OSA_UInt32)M4ERR_PARAMETER) == err) )
2477            {
2478                /* Not fatal, some readers may not support fast open mode */
2479                pC->bFileOpenedInFastMode = M4OSA_FALSE;
2480            }
2481            else
2482                return err;
2483        }
2484    }
2485    else
2486    {
2487        M4OSA_Bool falseValue = M4OSA_FALSE;
2488
2489        /* For second call use normal open mode */
2490        err = pC->m_pReader->m_pFctSetOption(pC->pReaderContext,
2491            M4READER_3GP_kOptionID_FastOpenMode, &falseValue);
2492    }
2493
2494#endif /* M4MCS_WITH_FAST_OPEN */
2495
2496    /**
2497    * Open the input file */
2498
2499    err = pC->m_pReader->m_pFctOpen(pC->pReaderContext, pC->pInputFile);
2500
2501    if( M4NO_ERROR != err )
2502    {
2503        M4OSA_UInt32 uiDummy, uiCoreId;
2504        M4OSA_TRACE1_1("M4MCS_open(): m_pReader->m_pFctOpen returns 0x%x", err);
2505
2506        /**
2507        * If the error is from the core reader, we change it to a public VXS error */
2508        M4OSA_ERR_SPLIT(err, uiDummy, uiCoreId, uiDummy);
2509
2510        if( M4MP4_READER == uiCoreId )
2511        {
2512            M4OSA_TRACE1_0(
2513                "M4MCS_open(): returning M4MCS_ERR_INVALID_INPUT_FILE");
2514            return M4MCS_ERR_INVALID_INPUT_FILE;
2515        }
2516        return err;
2517    }
2518
2519    /**
2520    * Get the streams from the input file */
2521    while( M4NO_ERROR == err )
2522    {
2523        err =
2524            pC->m_pReader->m_pFctGetNextStream( pC->pReaderContext,
2525                                                &mediaFamily,
2526                                                &pStreamHandler);
2527
2528        /**
2529        * In case we found a BIFS stream or something else...*/
2530        if( ( err == ((M4OSA_UInt32)M4ERR_READER_UNKNOWN_STREAM_TYPE))
2531            || (err == ((M4OSA_UInt32)M4WAR_TOO_MUCH_STREAMS)) )
2532        {
2533            err = M4NO_ERROR;
2534            continue;
2535        }
2536
2537        if( M4NO_ERROR == err ) /**< One stream found */
2538        {
2539            /**
2540            * Found the first video stream */
2541            if( ( M4READER_kMediaFamilyVideo == mediaFamily)
2542                && (M4OSA_NULL == pC->pReaderVideoStream) )
2543            {
2544                if( ( M4DA_StreamTypeVideoH263 == pStreamHandler->m_streamType)
2545                    || (M4DA_StreamTypeVideoMpeg4
2546                    == pStreamHandler->m_streamType)
2547                    || (M4DA_StreamTypeVideoMpeg4Avc
2548                    == pStreamHandler->m_streamType) )
2549                {
2550                    M4OSA_TRACE3_0(
2551                        "M4MCS_open(): Found a H263 or MPEG-4 video stream in input 3gpp clip");
2552
2553                    /**
2554                    * Keep pointer to the video stream */
2555                    pC->pReaderVideoStream =
2556                        (M4_VideoStreamHandler *)pStreamHandler;
2557                    pC->bUnsupportedVideoFound = M4OSA_FALSE;
2558                    pStreamHandler->m_bStreamIsOK = M4OSA_TRUE;
2559
2560                    /**
2561                    * Init our video stream state variable */
2562                    pC->VideoState = M4MCS_kStreamState_STARTED;
2563
2564                    /**
2565                    * Reset the stream reader */
2566                    err = pC->m_pReader->m_pFctReset(pC->pReaderContext,
2567                        (M4_StreamHandler *)pC->pReaderVideoStream);
2568
2569                    if( M4NO_ERROR != err )
2570                    {
2571                        M4OSA_TRACE1_1(
2572                            "M4MCS_open():\
2573                            m_pReader->m_pFctReset(video) returns 0x%x",
2574                            err);
2575                        return err;
2576                    }
2577
2578                    /**
2579                    * Initializes an access Unit */
2580                    err = pC->m_pReader->m_pFctFillAuStruct(pC->pReaderContext,
2581                        pStreamHandler, &pC->ReaderVideoAU);
2582
2583                    if( M4NO_ERROR != err )
2584                    {
2585                        M4OSA_TRACE1_1(
2586                            "M4MCS_open():\
2587                            m_pReader->m_pFctFillAuStruct(video) returns 0x%x",
2588                            err);
2589                        return err;
2590                    }
2591                }
2592                else /**< Not H263 or MPEG-4 (H264, etc.) */
2593                {
2594                    M4OSA_TRACE1_1("M4MCS_open(): Found an unsupported video stream (0x%x) in\
2595                                   input 3gpp clip",
2596                                   pStreamHandler->m_streamType);
2597
2598                    pC->bUnsupportedVideoFound = M4OSA_TRUE;
2599                    pStreamHandler->m_bStreamIsOK = M4OSA_FALSE;
2600                }
2601                /* +CRLV6775 -H.264 Trimming */
2602                if( M4DA_StreamTypeVideoMpeg4Avc
2603                    == pStreamHandler->m_streamType )
2604                {
2605
2606                    // SPS and PPS are storead as per the 3gp file format
2607                    pC->m_pInstance->m_pDecoderSpecificInfo =
2608                        pStreamHandler->m_pH264DecoderSpecificInfo;
2609                    pC->m_pInstance->m_decoderSpecificInfoSize =
2610                        pStreamHandler->m_H264decoderSpecificInfoSize;
2611                }
2612                /* -CRLV6775 -H.264 Trimming */
2613            }
2614            /**
2615            * Found the first audio stream */
2616            else if( ( M4READER_kMediaFamilyAudio == mediaFamily)
2617                && (M4OSA_NULL == pC->pReaderAudioStream) )
2618            {
2619                if( ( M4DA_StreamTypeAudioAmrNarrowBand
2620                    == pStreamHandler->m_streamType)
2621                    || (M4DA_StreamTypeAudioAac == pStreamHandler->m_streamType)
2622                    || (M4DA_StreamTypeAudioMp3
2623                    == pStreamHandler->m_streamType)
2624                    || (M4DA_StreamTypeAudioEvrc
2625                    == pStreamHandler->m_streamType) )
2626                {
2627                    M4OSA_TRACE3_0(
2628                        "M4MCS_open(): Found an AMR-NB, AAC or MP3 audio stream in input clip");
2629
2630                    /**
2631                    * Keep pointer to the audio stream */
2632                    pC->pReaderAudioStream =
2633                        (M4_AudioStreamHandler *)pStreamHandler;
2634                    pStreamHandler->m_bStreamIsOK = M4OSA_TRUE;
2635                    pC->bUnsupportedAudioFound = M4OSA_FALSE;
2636
2637                    /**
2638                    * Init our audio stream state variable */
2639                    pC->AudioState = M4MCS_kStreamState_STARTED;
2640
2641                    /**
2642                    * Reset the stream reader */
2643                    err = pC->m_pReader->m_pFctReset(pC->pReaderContext,
2644                        (M4_StreamHandler *)pC->pReaderAudioStream);
2645
2646                    if( M4NO_ERROR != err )
2647                    {
2648                        M4OSA_TRACE1_1(
2649                            "M4MCS_open():\
2650                            m_pReader->m_pFctReset(audio) returns 0x%x",
2651                            err);
2652                        return err;
2653                    }
2654
2655                    /**
2656                    * Initializes an access Unit */
2657                    err = pC->m_pReader->m_pFctFillAuStruct(pC->pReaderContext,
2658                        pStreamHandler, &pC->ReaderAudioAU);
2659
2660                    if( M4NO_ERROR != err )
2661                    {
2662                        M4OSA_TRACE1_1(
2663                            "M4MCS_open():\
2664                            m_pReader->m_pFctFillAuStruct(audio) returns 0x%x",
2665                            err);
2666                        return err;
2667                    }
2668
2669                    /**
2670                    * Output max AU size is equal to input max AU size (this value
2671                    * will be changed if there is audio transcoding) */
2672                    pC->uiAudioMaxAuSize = pStreamHandler->m_maxAUSize;
2673                }
2674                else
2675                {
2676                    /**< Not AMR-NB, AAC, MP3 nor EVRC (AMR-WB, WAV...) */
2677                    M4OSA_TRACE1_1("M4MCS_open(): Found an unsupported audio stream (0x%x) in \
2678                                   input 3gpp clip", pStreamHandler->m_streamType);
2679
2680                    pC->bUnsupportedAudioFound = M4OSA_TRUE;
2681                    pStreamHandler->m_bStreamIsOK = M4OSA_FALSE;
2682                }
2683            }
2684        }
2685    } /**< end of while (M4NO_ERROR == err) */
2686
2687    /**
2688    * Check we found at least one supported stream */
2689    if( ( M4OSA_NULL == pC->pReaderVideoStream)
2690        && (M4OSA_NULL == pC->pReaderAudioStream) )
2691    {
2692        M4OSA_TRACE1_0(
2693            "M4MCS_open(): returning M4MCS_ERR_INPUT_FILE_CONTAINS_NO_SUPPORTED_STREAM");
2694        return M4MCS_ERR_INPUT_FILE_CONTAINS_NO_SUPPORTED_STREAM;
2695    }
2696
2697    if( pC->VideoState == M4MCS_kStreamState_STARTED )
2698    {
2699        err = M4MCS_setCurrentVideoDecoder(pContext,
2700            pC->pReaderVideoStream->m_basicProperties.m_streamType);
2701        /*FB 2009-02-09: the error is check and returned only if video codecs are compiled,
2702        else only audio is used, that is why the editing process can continue*/
2703#ifndef M4MCS_AUDIOONLY
2704
2705        M4ERR_CHECK_RETURN(err);
2706
2707#else
2708
2709        if( ( M4NO_ERROR != err) && (M4MCS_WAR_MEDIATYPE_NOT_SUPPORTED != err) )
2710        {
2711            M4ERR_CHECK_RETURN(err);
2712        }
2713
2714#endif /*M4MCS_AUDIOONLY*/
2715
2716    }
2717
2718    if( pC->AudioState == M4MCS_kStreamState_STARTED )
2719    {
2720        //EVRC
2721        if( M4DA_StreamTypeAudioEvrc
2722            != pStreamHandler->
2723            m_streamType ) /* decoder not supported yet, but allow to do null encoding */
2724        {
2725            err = M4MCS_setCurrentAudioDecoder(pContext,
2726                pC->pReaderAudioStream->m_basicProperties.m_streamType);
2727            M4ERR_CHECK_RETURN(err);
2728        }
2729    }
2730
2731    /**
2732    * Get the audio and video stream properties */
2733    err = M4MCS_intGetInputClipProperties(pC);
2734
2735    if( M4NO_ERROR != err )
2736    {
2737        M4OSA_TRACE1_1(
2738            "M4MCS_open(): M4MCS_intGetInputClipProperties returns 0x%x", err);
2739        return err;
2740    }
2741
2742    /**
2743    * Set the begin cut decoding increment according to the input frame rate */
2744    if( 0. != pC->InputFileProperties.fAverageFrameRate ) /**< sanity check */
2745    {
2746        pC->iVideoBeginDecIncr = (M4OSA_Int32)(3000.
2747            / pC->InputFileProperties.
2748            fAverageFrameRate); /**< about 3 frames */
2749    }
2750    else
2751    {
2752        pC->iVideoBeginDecIncr =
2753            200; /**< default value: 200 milliseconds (3 frames @ 15fps)*/
2754    }
2755
2756    /**
2757    * Update state automaton */
2758    pC->State = M4MCS_kState_OPENED;
2759
2760    /**
2761    * Return with no error */
2762    M4OSA_TRACE3_0("M4MCS_open(): returning M4NO_ERROR");
2763    return M4NO_ERROR;
2764}
2765
2766/**
2767 ******************************************************************************
2768 * M4OSA_ERR M4MCS_step(M4MCS_Context pContext, M4OSA_UInt8 *pProgress);
2769 * @brief   Perform one step of trancoding.
2770 * @note
2771 * @param   pContext            (IN) MCS context
2772 * @param   pProgress           (OUT) Progress percentage (0 to 100) of the transcoding
2773 * @note    pProgress must be a valid address.
2774 * @return  M4NO_ERROR:         No error
2775 * @return  M4ERR_PARAMETER:    One of the parameters is M4OSA_NULL (debug only)
2776 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
2777 * @return  M4MCS_WAR_TRANSCODING_DONE: Transcoding is over, user should now call M4MCS_close()
2778 * @return  M4MCS_ERR_AUDIO_CONVERSION_FAILED: The audio conversion (AAC to AMR-NB or MP3) failed
2779 * @return  M4MCS_ERR_INVALID_AAC_SAMPLING_FREQUENCY: The input file contains an AAC audio track
2780 *                                 with an invalid sampling frequency (should never happen)
2781 ******************************************************************************
2782 */
2783M4OSA_ERR M4MCS_step( M4MCS_Context pContext, M4OSA_UInt8 *pProgress )
2784{
2785    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
2786
2787    M4OSA_TRACE3_1("M4MCS_step called with pContext=0x%x", pContext);
2788
2789    /**
2790    * Check input parameters */
2791    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
2792        "M4MCS_step: pContext is M4OSA_NULL");
2793    M4OSA_DEBUG_IF2((M4OSA_NULL == pProgress), M4ERR_PARAMETER,
2794        "M4MCS_step: pProgress is M4OSA_NULL");
2795
2796#ifdef M4MCS_SUPPORT_STILL_PICTURE
2797
2798    if( pC->m_bIsStillPicture )
2799    {
2800        /**
2801        * Call the still picture MCS functions*/
2802        return M4MCS_stillPicStep(pC, pProgress);
2803    }
2804
2805#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
2806
2807    /**
2808    * Check state automaton */
2809
2810    switch( pC->State )
2811    {
2812        case M4MCS_kState_READY:
2813            *pProgress = 0;
2814            return M4MCS_intStepSet(pC);
2815            break;
2816
2817        case M4MCS_kState_BEGINVIDEOJUMP:
2818            *pProgress = pC->uiProgress;
2819            return M4MCS_intStepBeginVideoJump(pC);
2820            break;
2821
2822        case M4MCS_kState_BEGINVIDEODECODE:
2823            *pProgress = pC->uiProgress;
2824            return M4MCS_intStepBeginVideoDecode(pC);
2825            break;
2826
2827        case M4MCS_kState_PROCESSING:
2828            {
2829                M4OSA_ERR err = M4NO_ERROR;
2830                err = M4MCS_intStepEncoding(pC, pProgress);
2831                /* Save progress info in case of pause */
2832                pC->uiProgress = *pProgress;
2833                return err;
2834            }
2835            break;
2836
2837        default: /**< State error */
2838            M4OSA_TRACE1_1(
2839                "M4MCS_step(): Wrong State (%d), returning M4ERR_STATE",
2840                pC->State);
2841            return M4ERR_STATE;
2842    }
2843}
2844
2845/**
2846 ******************************************************************************
2847 * M4OSA_ERR M4MCS_pause(M4MCS_Context pContext);
2848 * @brief   Pause the transcoding i.e. release the (external hardware) video decoder.
2849 * @note    This function is not needed if no hardware accelerators are used.
2850 *          In that case, pausing the MCS is simply achieved by temporarily suspending
2851 *          the M4MCS_step function calls.
2852 * @param   pContext            (IN) MCS context
2853 * @return  M4NO_ERROR:         No error
2854 * @return  M4ERR_PARAMETER:    pContext is M4OSA_NULL (debug only)
2855 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
2856 ******************************************************************************
2857 */
2858M4OSA_ERR M4MCS_pause( M4MCS_Context pContext )
2859{
2860    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
2861    M4OSA_ERR err;
2862
2863    M4OSA_TRACE2_1("M4MCS_pause called with pContext=0x%x", pContext);
2864
2865    /**
2866    * Check input parameters */
2867    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
2868        "M4MCS_pause: pContext is M4OSA_NULL");
2869
2870#ifdef M4MCS_SUPPORT_STILL_PICTURE
2871
2872    if( pC->m_bIsStillPicture )
2873    {
2874        /**
2875        * Call the corresponding still picture MCS function*/
2876        return M4MCS_stillPicPause(pC);
2877    }
2878
2879#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
2880
2881    /**
2882    * Check state automaton */
2883
2884    switch( pC->State )
2885    {
2886        case M4MCS_kState_BEGINVIDEOJUMP: /**< the video decoder has been created,
2887                                            we must destroy it */
2888        case M4MCS_kState_BEGINVIDEODECODE: /**< the video is being used, we must destroy it */
2889        case M4MCS_kState_PROCESSING: /**< the video is being used, we must destroy it */
2890                    /**< OK, nothing to do here */
2891            break;
2892
2893        default: /**< State error */
2894            M4OSA_TRACE1_1(
2895                "M4MCS_pause(): Wrong State (%d), returning M4ERR_STATE",
2896                pC->State);
2897            return M4ERR_STATE;
2898    }
2899
2900    /**
2901    * Set the CTS at which we will resume the decoding */
2902    if( pC->dViDecCurrentCts > pC->dViDecStartingCts )
2903    {
2904        /**
2905        * We passed the starting CTS, so the resume target is the current CTS */
2906        pC->dViDecStartingCts = pC->dViDecCurrentCts;
2907    }
2908    else {
2909        /**
2910        * We haven't passed the starting CTS yet, so the resume target is still the starting CTS
2911        * --> nothing to do in the else block */
2912    }
2913
2914    /**
2915    * Free video decoder stuff */
2916    if( M4OSA_NULL != pC->pViDecCtxt )
2917    {
2918        err = pC->m_pVideoDecoder->m_pFctDestroy(pC->pViDecCtxt);
2919        pC->pViDecCtxt = M4OSA_NULL;
2920
2921        if( M4NO_ERROR != err )
2922        {
2923            M4OSA_TRACE1_1(
2924                "M4MCS_pause: m_pVideoDecoder->pFctDestroy returns 0x%x", err);
2925            return err;
2926        }
2927    }
2928
2929    /**
2930    * State transition */
2931    pC->State = M4MCS_kState_PAUSED;
2932
2933    M4OSA_TRACE3_0("M4MCS_pause(): returning M4NO_ERROR");
2934    return M4NO_ERROR;
2935}
2936
2937/**
2938 ******************************************************************************
2939 * M4OSA_ERR M4MCS_resume(M4MCS_Context pContext);
2940 * @brief   Resume the transcoding after a pause (see M4MCS_pause).
2941 * @note    This function is not needed if no hardware accelerators are used.
2942 *          In that case, resuming the MCS is simply achieved by calling
2943 *          the M4MCS_step function.
2944 * @param   pContext            (IN) MCS context
2945 * @return  M4NO_ERROR:         No error
2946 * @return  M4ERR_PARAMETER:    pContext is M4OSA_NULL (debug only)
2947 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
2948 ******************************************************************************
2949 */
2950M4OSA_ERR M4MCS_resume( M4MCS_Context pContext )
2951{
2952    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
2953    M4OSA_ERR err;
2954
2955    M4OSA_TRACE2_1("M4MCS_resume called with pContext=0x%x", pContext);
2956
2957    /**
2958    * Check input parameters */
2959    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
2960        "M4MCS_resume: pContext is M4OSA_NULL");
2961
2962#ifdef M4MCS_SUPPORT_STILL_PICTURE
2963
2964    if( pC->m_bIsStillPicture )
2965    {
2966        /**
2967        * Call the corresponding still picture MCS function*/
2968        return M4MCS_stillPicResume(pC);
2969    }
2970
2971#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
2972
2973    /**
2974    * Check state automaton */
2975
2976    switch( pC->State )
2977    {
2978        case M4MCS_kState_PAUSED: /**< OK, nothing to do here */
2979            break;
2980
2981        default:                  /**< State error */
2982            M4OSA_TRACE1_1(
2983                "M4MCS_resume(): Wrong State (%d), returning M4ERR_STATE",
2984                pC->State);
2985            return M4ERR_STATE;
2986            break;
2987    }
2988
2989    /**
2990    * Prepare the video decoder */
2991    err = M4MCS_intPrepareVideoDecoder(pC);
2992
2993    if( M4NO_ERROR != err )
2994    {
2995        M4OSA_TRACE1_1(
2996            "M4MCS_resume(): M4MCS_intPrepareVideoDecoder() returns 0x%x", err);
2997        return err;
2998    }
2999
3000    /**
3001    * State transition */
3002    if( 0.0 == pC->dViDecStartingCts )
3003    {
3004        /**
3005        * We are still at the beginning of the decoded stream, no need to jump, we can proceed */
3006        pC->State = M4MCS_kState_PROCESSING;
3007    }
3008    else
3009    {
3010        /**
3011        * Jumping */
3012        pC->State = M4MCS_kState_BEGINVIDEOJUMP;
3013    }
3014
3015    M4OSA_TRACE3_0("M4MCS_resume(): returning M4NO_ERROR");
3016    return M4NO_ERROR;
3017}
3018
3019/**
3020 ******************************************************************************
3021 * M4OSA_ERR M4MCS_close(M4MCS_Context pContext);
3022 * @brief    Finish the MCS transcoding.
3023 * @note The output 3GPP file is ready to be played after this call
3024 * @param    pContext            (IN) MCS context
3025 * @return   M4NO_ERROR:         No error
3026 * @return   M4ERR_PARAMETER:    pContext is M4OSA_NULL (If Debug Level >= 2)
3027 * @return   M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
3028 ******************************************************************************
3029 */
3030M4OSA_ERR M4MCS_close( M4MCS_Context pContext )
3031{
3032    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
3033    M4ENCODER_Header *encHeader;
3034    M4SYS_StreamIDmemAddr streamHeader;
3035
3036    M4OSA_ERR err = M4NO_ERROR, err2;
3037
3038    M4OSA_TRACE2_1("M4MCS_close called with pContext=0x%x", pContext);
3039
3040    /**
3041    * Check input parameters */
3042    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
3043        "M4MCS_close: pContext is M4OSA_NULL");
3044
3045#ifdef M4MCS_SUPPORT_STILL_PICTURE
3046
3047    if( pC->m_bIsStillPicture )
3048    {
3049        /**
3050        * Indicate that current file is no longer a still picture*/
3051        pC->m_bIsStillPicture = M4OSA_FALSE;
3052
3053        /**
3054        * Call the corresponding still picture MCS function*/
3055        return M4MCS_stillPicClose(pC);
3056    }
3057
3058#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
3059
3060    /**
3061    * Check state automaton */
3062
3063    if( M4MCS_kState_FINISHED != pC->State )
3064    {
3065        M4OSA_TRACE1_1("M4MCS_close(): Wrong State (%d), returning M4ERR_STATE",
3066            pC->State);
3067        return M4ERR_STATE;
3068    }
3069
3070    /* Close the encoder before the writer to be certain all the AUs have been written and we can
3071    get the DSI. */
3072
3073    /* Has the encoder actually been started? Don't stop it if that's not the case. */
3074    if( M4MCS_kEncoderRunning == pC->encoderState )
3075    {
3076        if( pC->pVideoEncoderGlobalFcts->pFctStop != M4OSA_NULL )
3077        {
3078            err = pC->pVideoEncoderGlobalFcts->pFctStop(pC->pViEncCtxt);
3079
3080            if( M4NO_ERROR != err )
3081            {
3082                M4OSA_TRACE1_1(
3083                    "M4MCS_close: pVideoEncoderGlobalFcts->pFctStop returns 0x%x",
3084                    err);
3085                /* Well... how the heck do you handle a failed cleanup? */
3086            }
3087        }
3088
3089        pC->encoderState = M4MCS_kEncoderStopped;
3090    }
3091
3092    /* Has the encoder actually been opened? Don't close it if that's not the case. */
3093    if( M4MCS_kEncoderStopped == pC->encoderState )
3094    {
3095        err = pC->pVideoEncoderGlobalFcts->pFctClose(pC->pViEncCtxt);
3096
3097        if( M4NO_ERROR != err )
3098        {
3099            M4OSA_TRACE1_1(
3100                "M4MCS_close: pVideoEncoderGlobalFcts->pFctClose returns 0x%x",
3101                err);
3102            /* Well... how the heck do you handle a failed cleanup? */
3103        }
3104
3105        pC->encoderState = M4MCS_kEncoderClosed;
3106    }
3107
3108    /**********************************/
3109    /******** Close the writer ********/
3110    /**********************************/
3111    if( M4OSA_NULL != pC->pWriterContext ) /* happens in state _SET */
3112    {
3113        /* HW encoder: fetch the DSI from the shell video encoder, and feed it to the writer before
3114        closing it. */
3115
3116        if( pC->novideo != M4OSA_TRUE )
3117        {
3118            if( ( M4ENCODER_kMPEG4 == pC->EncodingVideoFormat)
3119                || (M4ENCODER_kH264 == pC->EncodingVideoFormat) )
3120            {
3121                err = pC->pVideoEncoderGlobalFcts->pFctGetOption(pC->pViEncCtxt,
3122                    M4ENCODER_kOptionID_EncoderHeader,
3123                    (M4OSA_DataOption) &encHeader);
3124
3125                if( ( M4NO_ERROR != err) || (M4OSA_NULL == encHeader->pBuf) )
3126                {
3127                    M4OSA_TRACE1_1(
3128                        "M4MCS_close: failed to get the encoder header (err 0x%x)",
3129                        err);
3130                    /**< no return here, we still have stuff to deallocate after close, even
3131                     if it fails. */
3132                }
3133                else
3134                {
3135                    /* set this header in the writer */
3136                    streamHeader.streamID = M4MCS_WRITER_VIDEO_STREAM_ID;
3137                    streamHeader.size = encHeader->Size;
3138                    streamHeader.addr = (M4OSA_MemAddr32)encHeader->pBuf;
3139                }
3140
3141                M4OSA_TRACE1_0("calling set option");
3142                err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
3143                    M4WRITER_kDSI, &streamHeader);
3144                M4OSA_TRACE1_0("set option done");
3145
3146                if( M4NO_ERROR != err )
3147                {
3148                    M4OSA_TRACE1_1(
3149                        "M4MCS_close: failed to set the DSI in the writer (err 0x%x)",
3150                        err);
3151                }
3152            }
3153
3154            if( ( M4OSA_TRUE == pC->bH264Trim)
3155                && (M4ENCODER_kNULL == pC->EncodingVideoFormat) )
3156            {
3157                if(pC->uiBeginCutTime == 0)
3158                {
3159                    M4OSA_TRACE1_1("Decoder specific info size = %d",
3160                        pC->m_pInstance->m_decoderSpecificInfoSize);
3161                    pC->m_pInstance->m_pFinalDSISize =
3162                        pC->m_pInstance->m_decoderSpecificInfoSize;
3163                    M4OSA_TRACE1_1("Decoder specific info pointer = %d",
3164                        (M4OSA_MemAddr8)pC->m_pInstance->m_pDecoderSpecificInfo);
3165
3166                    pC->m_pInstance->m_pFinalDSI =
3167                        (M4OSA_UInt8 *)M4OSA_malloc(pC->m_pInstance-> \
3168                        m_decoderSpecificInfoSize, M4MCS,
3169                        (M4OSA_Char *)"instance->m_pFinalDSI");
3170
3171                    if( pC->m_pInstance->m_pFinalDSI == M4OSA_NULL )
3172                    {
3173                        M4OSA_TRACE1_0("instance->m_pFinalDSI: allocation error");
3174                        return M4ERR_ALLOC;
3175                    }
3176                    memcpy((void *)pC->m_pInstance->m_pFinalDSI,
3177                        (void *)pC-> \
3178                        m_pInstance->m_pDecoderSpecificInfo,
3179                        pC->m_pInstance->m_decoderSpecificInfoSize);
3180                }
3181                streamHeader.streamID = M4MCS_WRITER_VIDEO_STREAM_ID;
3182                streamHeader.size = pC->m_pInstance->m_pFinalDSISize;
3183                streamHeader.addr =
3184                    (M4OSA_MemAddr32)pC->m_pInstance->m_pFinalDSI;
3185                M4OSA_TRACE1_0("calling set option");
3186                err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
3187                    M4WRITER_kDSI, &streamHeader);
3188                M4OSA_TRACE1_0("set option done");
3189
3190                if( M4NO_ERROR != err )
3191                {
3192                    M4OSA_TRACE1_1(
3193                        "M4MCS_close: failed to set the DSI in the writer (err 0x%x)",
3194                        err);
3195                }
3196            }
3197        }
3198        /* Write and close the 3GP output file */
3199        err2 = pC->pWriterGlobalFcts->pFctCloseWrite(pC->pWriterContext);
3200        pC->pWriterContext = M4OSA_NULL;
3201
3202        if( M4NO_ERROR != err2 )
3203        {
3204            M4OSA_TRACE1_1(
3205                "M4MCS_close: pWriterGlobalFcts->pFctCloseWrite returns 0x%x",
3206                err2);
3207
3208            if( M4NO_ERROR == err )
3209                err = err2;
3210            /**< no return here, we still have stuff to deallocate after close, even if it fails.*/
3211        }
3212    }
3213
3214    /* Close output PCM file if needed */
3215    if( pC->pOutputPCMfile != M4OSA_NULL )
3216    {
3217        pC->pOsaFileWritPtr->closeWrite(pC->pOutputPCMfile);
3218        pC->pOutputPCMfile = M4OSA_NULL;
3219    }
3220
3221    /*FlB 2009.03.04: add audio effects,
3222    free effects list*/
3223    if( M4OSA_NULL != pC->pEffects )
3224    {
3225        M4OSA_free((M4OSA_MemAddr32)pC->pEffects);
3226        pC->pEffects = M4OSA_NULL;
3227    }
3228    pC->nbEffects = 0;
3229    pC->pActiveEffectNumber = -1;
3230
3231    /**
3232    * State transition */
3233    pC->State = M4MCS_kState_CLOSED;
3234
3235    if( M4OSA_NULL != pC->H264MCSTempBuffer )
3236    {
3237        M4OSA_free((M4OSA_MemAddr32)pC->H264MCSTempBuffer);
3238    }
3239
3240    M4OSA_TRACE3_0("M4MCS_close(): returning M4NO_ERROR");
3241    return err;
3242}
3243
3244/**
3245 ******************************************************************************
3246 * M4OSA_ERR M4MCS_cleanUp(M4MCS_Context pContext);
3247 * @brief    Free all resources used by the MCS.
3248 * @note The context is no more valid after this call
3249 * @param    pContext            (IN) MCS context
3250 * @return   M4NO_ERROR:         No error
3251 * @return   M4ERR_PARAMETER:    pContext is M4OSA_NULL (If Debug Level >= 2)
3252 * @return   M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
3253 ******************************************************************************
3254 */
3255M4OSA_ERR M4MCS_cleanUp( M4MCS_Context pContext )
3256{
3257    M4OSA_ERR err = M4NO_ERROR;
3258    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
3259
3260    M4OSA_TRACE3_1("M4MCS_cleanUp called with pContext=0x%x", pContext);
3261
3262#ifdef MCS_DUMP_PCM_TO_FILE
3263
3264    if( file_au_reader )
3265    {
3266        fclose(file_au_reader);
3267        file_au_reader = NULL;
3268    }
3269
3270    if( file_pcm_decoder )
3271    {
3272        fclose(file_pcm_decoder);
3273        file_pcm_decoder = NULL;
3274    }
3275
3276    if( file_pcm_encoder )
3277    {
3278        fclose(file_pcm_encoder);
3279        file_pcm_encoder = NULL;
3280    }
3281
3282#endif
3283
3284    /**
3285    * Check input parameter */
3286
3287    if( M4OSA_NULL == pContext )
3288    {
3289        M4OSA_TRACE1_0(
3290            "M4MCS_cleanUp: pContext is M4OSA_NULL, returning M4ERR_PARAMETER");
3291        return M4ERR_PARAMETER;
3292    }
3293
3294    /**
3295    * Check state automaton */
3296    if( M4MCS_kState_CLOSED != pC->State )
3297    {
3298        M4OSA_TRACE1_1(
3299            "M4MCS_cleanUp(): Wrong State (%d), returning M4ERR_STATE",
3300            pC->State);
3301        return M4ERR_STATE;
3302    }
3303
3304    if( M4OSA_NULL != pC->m_pInstance )
3305    {
3306        err = H264MCS_Freeinstance(pC->m_pInstance);
3307        pC->m_pInstance = M4OSA_NULL;
3308    }
3309
3310    /* ----- Free video encoder stuff, if needed ----- */
3311
3312    if( ( M4OSA_NULL != pC->pViEncCtxt)
3313        && (M4OSA_NULL != pC->pVideoEncoderGlobalFcts) )
3314    {
3315        err = pC->pVideoEncoderGlobalFcts->pFctCleanup(pC->pViEncCtxt);
3316        pC->pViEncCtxt = M4OSA_NULL;
3317
3318        if( M4NO_ERROR != err )
3319        {
3320            M4OSA_TRACE1_1(
3321                "M4MCS_cleanUp: pVideoEncoderGlobalFcts->pFctCleanup returns 0x%x",
3322                err);
3323            /**< don't return, we still have stuff to free */
3324        }
3325
3326        pC->encoderState = M4MCS_kNoEncoder;
3327    }
3328
3329    /**
3330    * In the H263 case, we allocated our own DSI buffer */
3331    if( ( M4ENCODER_kH263 == pC->EncodingVideoFormat)
3332        && (M4OSA_NULL != pC->WriterVideoStreamInfo.Header.pBuf) )
3333    {
3334        M4OSA_free((M4OSA_MemAddr32)pC->WriterVideoStreamInfo.Header.pBuf);
3335        pC->WriterVideoStreamInfo.Header.pBuf = M4OSA_NULL;
3336    }
3337
3338    if( M4OSA_NULL != pC->pPreResizeFrame )
3339    {
3340        if( M4OSA_NULL != pC->pPreResizeFrame[0].pac_data )
3341        {
3342            M4OSA_free((M4OSA_MemAddr32)pC->pPreResizeFrame[0].pac_data);
3343            pC->pPreResizeFrame[0].pac_data = M4OSA_NULL;
3344        }
3345
3346        if( M4OSA_NULL != pC->pPreResizeFrame[1].pac_data )
3347        {
3348            M4OSA_free((M4OSA_MemAddr32)pC->pPreResizeFrame[1].pac_data);
3349            pC->pPreResizeFrame[1].pac_data = M4OSA_NULL;
3350        }
3351
3352        if( M4OSA_NULL != pC->pPreResizeFrame[2].pac_data )
3353        {
3354            M4OSA_free((M4OSA_MemAddr32)pC->pPreResizeFrame[2].pac_data);
3355            pC->pPreResizeFrame[2].pac_data = M4OSA_NULL;
3356        }
3357        M4OSA_free((M4OSA_MemAddr32)pC->pPreResizeFrame);
3358        pC->pPreResizeFrame = M4OSA_NULL;
3359    }
3360
3361    /* ----- Free the ssrc stuff ----- */
3362
3363    if( M4OSA_NULL != pC->SsrcScratch )
3364    {
3365        M4OSA_free((M4OSA_MemAddr32)pC->SsrcScratch);
3366        pC->SsrcScratch = M4OSA_NULL;
3367    }
3368
3369    if( M4OSA_NULL != pC->pSsrcBufferIn )
3370    {
3371        M4OSA_free((M4OSA_MemAddr32)pC->pSsrcBufferIn);
3372        pC->pSsrcBufferIn = M4OSA_NULL;
3373    }
3374
3375    if( M4OSA_NULL != pC->pSsrcBufferOut )
3376    {
3377        M4OSA_free((M4OSA_MemAddr32)pC->pSsrcBufferOut);
3378        pC->pSsrcBufferOut = M4OSA_NULL;
3379    }
3380
3381    if (pC->pLVAudioResampler != M4OSA_NULL)
3382    {
3383        LVDestroy(pC->pLVAudioResampler);
3384        pC->pLVAudioResampler = M4OSA_NULL;
3385    }
3386
3387    /* ----- Free the audio encoder stuff ----- */
3388
3389    if( M4OSA_NULL != pC->pAudioEncCtxt )
3390    {
3391        err = pC->pAudioEncoderGlobalFcts->pFctClose(pC->pAudioEncCtxt);
3392
3393        if( M4NO_ERROR != err )
3394        {
3395            M4OSA_TRACE1_1(
3396                "M4MCS_cleanUp: pAudioEncoderGlobalFcts->pFctClose returns 0x%x",
3397                err);
3398            /**< don't return, we still have stuff to free */
3399        }
3400
3401        err = pC->pAudioEncoderGlobalFcts->pFctCleanUp(pC->pAudioEncCtxt);
3402
3403        if( M4NO_ERROR != err )
3404        {
3405            M4OSA_TRACE1_1(
3406                "M4MCS_cleanUp: pAudioEncoderGlobalFcts->pFctCleanUp returns 0x%x",
3407                err);
3408            /**< don't return, we still have stuff to free */
3409        }
3410
3411        pC->pAudioEncCtxt = M4OSA_NULL;
3412    }
3413
3414    if( M4OSA_NULL != pC->pAudioEncoderBuffer )
3415    {
3416        M4OSA_free((M4OSA_MemAddr32)pC->pAudioEncoderBuffer);
3417        pC->pAudioEncoderBuffer = M4OSA_NULL;
3418    }
3419
3420    /* ----- Free all other stuff ----- */
3421
3422    /**
3423    * Free the readers and the decoders */
3424    M4MCS_intCleanUp_ReadersDecoders(pC);
3425
3426#ifdef M4MCS_SUPPORT_STILL_PICTURE
3427    /**
3428    * Free the still picture resources */
3429
3430    M4MCS_stillPicCleanUp(pC);
3431
3432#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
3433
3434    /**
3435    * Free the shells interfaces */
3436
3437    M4MCS_unRegisterAllWriters(pContext);
3438    M4MCS_unRegisterAllEncoders(pContext);
3439    M4MCS_unRegisterAllReaders(pContext);
3440    M4MCS_unRegisterAllDecoders(pContext);
3441
3442    /**
3443    * Free the context itself */
3444    M4OSA_free((M4OSA_MemAddr32)pC);
3445    pC = M4OSA_NULL;
3446
3447    M4OSA_TRACE3_0("M4MCS_cleanUp(): returning M4NO_ERROR");
3448    return M4NO_ERROR;
3449}
3450
3451/**
3452 ******************************************************************************
3453 * M4OSA_ERR M4MCS_abort(M4MCS_Context pContext);
3454 * @brief    Finish the MCS transcoding and free all resources used by the MCS
3455 *          whatever the state is.
3456 * @note    The context is no more valid after this call
3457 * @param    pContext            (IN) MCS context
3458 * @return    M4NO_ERROR:            No error
3459 * @return    M4ERR_PARAMETER:    pContext is M4OSA_NULL (debug only)
3460 ******************************************************************************
3461 */
3462M4OSA_ERR M4MCS_abort( M4MCS_Context pContext )
3463{
3464    M4OSA_ERR err = M4NO_ERROR;
3465    M4OSA_ERR err1 = M4NO_ERROR;
3466    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
3467
3468    if( M4OSA_NULL == pContext )
3469    {
3470        return M4NO_ERROR;
3471    }
3472
3473    if( ( pC->State == M4MCS_kState_CREATED)
3474        || (pC->State == M4MCS_kState_CLOSED) )
3475    {
3476        pC->State = M4MCS_kState_CLOSED;
3477
3478        err = M4MCS_cleanUp(pContext);
3479
3480        if( err != M4NO_ERROR )
3481        {
3482            M4OSA_TRACE1_1("M4MCS_abort : M4MCS_cleanUp fails err = 0x%x", err);
3483        }
3484    }
3485    else
3486    {
3487#ifdef M4MCS_SUPPORT_STILL_PICTURE
3488
3489        if( pC->m_bIsStillPicture )
3490        {
3491            /**
3492            * Cancel the ongoing processes if any*/
3493            err = M4MCS_stillPicCancel(pC);
3494
3495            if( err != M4NO_ERROR )
3496            {
3497                M4OSA_TRACE1_1(
3498                    "M4MCS_abort : M4MCS_stillPicCancel fails err = 0x%x", err);
3499            }
3500            /*Still picture process is now stopped; Carry on with close and cleanup*/
3501        }
3502
3503#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
3504
3505        pC->State = M4MCS_kState_FINISHED;
3506
3507        err = M4MCS_close(pContext);
3508
3509        if( err != M4NO_ERROR )
3510        {
3511            M4OSA_TRACE1_1("M4MCS_abort : M4MCS_close fails err = 0x%x", err);
3512            err1 = err;
3513        }
3514
3515        err = M4MCS_cleanUp(pContext);
3516
3517        if( err != M4NO_ERROR )
3518        {
3519            M4OSA_TRACE1_1("M4MCS_abort : M4MCS_cleanUp fails err = 0x%x", err);
3520        }
3521    }
3522    err = (err1 == M4NO_ERROR) ? err : err1;
3523    return err;
3524}
3525
3526/**
3527 ******************************************************************************
3528 * M4OSA_ERR M4MCS_getInputFileProperties(M4MCS_Context pContext,
3529 *                                         M4VIDEOEDITING_ClipProperties* pFileProperties);
3530 * @brief   Retrieves the properties of the audio and video streams from the input file.
3531 * @param   pContext            (IN) MCS context
3532 * @param   pProperties         (OUT) Pointer on an allocated M4VIDEOEDITING_ClipProperties
3533structure which is filled with the input stream properties.
3534 * @note    The structure pProperties must be allocated and further de-allocated
3535by the application. The function must be called in the opened state.
3536 * @return  M4NO_ERROR:         No error
3537 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL
3538 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
3539 ******************************************************************************
3540 */
3541M4OSA_ERR M4MCS_getInputFileProperties( M4MCS_Context pContext,
3542                                       M4VIDEOEDITING_ClipProperties *pFileProperties )
3543{
3544    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
3545
3546    M4OSA_TRACE2_2("M4MCS_getInputFileProperties called with pContext=0x%x, \
3547                   pFileProperties=0x%x", pContext, pFileProperties);
3548
3549    /**
3550    * Check input parameters */
3551    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
3552        "M4MCS_getInputFileProperties: pContext is M4OSA_NULL");
3553    M4OSA_DEBUG_IF2((M4OSA_NULL == pFileProperties), M4ERR_PARAMETER,
3554        "M4MCS_getInputFileProperties: pProperties is M4OSA_NULL");
3555
3556#ifdef M4MCS_SUPPORT_STILL_PICTURE
3557
3558    if( pC->m_bIsStillPicture )
3559    {
3560        /**
3561        * Call the corresponding still picture MCS function*/
3562        return M4MCS_stillPicGetInputFileProperties(pC, pFileProperties);
3563    }
3564
3565#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
3566
3567    /**
3568    * Check state automaton */
3569
3570    if( M4MCS_kState_OPENED != pC->State )
3571    {
3572        M4OSA_TRACE1_1(
3573            "M4MCS_getInputFileProperties(): Wrong State (%d), returning M4ERR_STATE",
3574            pC->State);
3575        return M4ERR_STATE;
3576    }
3577
3578    /**
3579    * Copy previously computed properties into given structure */
3580    memcpy((void *)pFileProperties,
3581        (void *) &pC->InputFileProperties,
3582        sizeof(M4VIDEOEDITING_ClipProperties));
3583
3584    return M4NO_ERROR;
3585}
3586
3587/**
3588 ******************************************************************************
3589 * M4OSA_ERR M4MCS_setOutputParams(M4MCS_Context pContext, M4MCS_OutputParams* pParams);
3590 * @brief   Set the MCS video output parameters.
3591 * @note    Must be called after M4MCS_open. Must be called before M4MCS_step.
3592 * @param   pContext            (IN) MCS context
3593 * @param   pParams             (IN/OUT) Transcoding parameters
3594 * @return  M4NO_ERROR:         No error
3595 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (debug only)
3596 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
3597 * @return  M4MCS_ERR_INVALID_VIDEO_FRAME_SIZE_FOR_H263 : Output video frame size parameter is
3598 *                                                        incompatible with H263 encoding
3599 * @return  M4MCS_ERR_INVALID_VIDEO_FRAME_RATE_FOR_H263 : Output video frame size parameter is
3600 *                                                        incompatible with H263 encoding
3601 * @return  M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FORMAT     : Undefined output video format parameter
3602 * @return  M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FRAME_SIZE : Undefined output video frame size
3603 * @return  M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FRAME_RATE : Undefined output video frame rate
3604 * @return  M4MCS_ERR_UNDEFINED_OUTPUT_AUDIO_FORMAT : Undefined output audio format parameter
3605 * @return  M4MCS_ERR_DURATION_IS_NULL : Specified output parameters define a null duration stream
3606 *                                         (no audio and video)
3607 ******************************************************************************
3608 */
3609M4OSA_ERR M4MCS_setOutputParams( M4MCS_Context pContext,
3610                                M4MCS_OutputParams *pParams )
3611{
3612    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
3613    M4OSA_UInt32 uiFrameWidth;
3614    M4OSA_UInt32 uiFrameHeight;
3615    M4OSA_ERR err;
3616
3617    M4OSA_TRACE2_2(
3618        "M4MCS_setOutputParams called with pContext=0x%x, pParams=0x%x",
3619        pContext, pParams);
3620
3621    /**
3622    * Check input parameters */
3623    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
3624        "M4MCS_setOutputParams: pContext is M4OSA_NULL");
3625    M4OSA_DEBUG_IF2((M4OSA_NULL == pParams), M4ERR_PARAMETER,
3626        "M4MCS_setOutputParams: pParam is M4OSA_NULL");
3627
3628#ifdef M4MCS_SUPPORT_STILL_PICTURE
3629
3630    if( pC->m_bIsStillPicture )
3631    {
3632        /**
3633        * Call the corresponding still picture MCS function*/
3634        return M4MCS_stillPicSetOutputParams(pC, pParams);
3635    }
3636
3637#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
3638
3639    /**
3640    * Check state automaton */
3641
3642    if( M4MCS_kState_OPENED != pC->State )
3643    {
3644        M4OSA_TRACE1_1(
3645            "M4MCS_setOutputParams(): Wrong State (%d), returning M4ERR_STATE",
3646            pC->State);
3647        return M4ERR_STATE;
3648    }
3649
3650    /* Ignore audio or video stream if the output do not need it, */
3651    /* or if the input file does not have any audio or video stream */
3652    /*FlB 26.02.2009: add mp3 as mcs output format*/
3653    if( ( pParams->OutputVideoFormat == M4VIDEOEDITING_kNoneVideo)
3654        || (pC->VideoState == M4MCS_kStreamState_NOSTREAM)
3655        || (pParams->OutputFileType == M4VIDEOEDITING_kFileType_AMR)
3656        || (pParams->OutputFileType == M4VIDEOEDITING_kFileType_MP3) )
3657    {
3658        pC->novideo = M4OSA_TRUE;
3659    }
3660
3661    if( ( pParams->OutputAudioFormat == M4VIDEOEDITING_kNoneAudio)
3662        || (pC->AudioState == M4MCS_kStreamState_NOSTREAM) )
3663    {
3664        pC->noaudio = M4OSA_TRUE;
3665    }
3666
3667    if( pC->noaudio && pC->novideo )
3668    {
3669        M4OSA_TRACE1_0(
3670            "!!! M4MCS_setOutputParams : clip is NULL, there is no audio, no video");
3671        return M4MCS_ERR_DURATION_IS_NULL;
3672    }
3673
3674    /* Set writer */
3675    err = M4MCS_setCurrentWriter(pContext, pParams->OutputFileType);
3676    M4ERR_CHECK_RETURN(err);
3677
3678    /* Set video parameters */
3679    if( pC->novideo == M4OSA_FALSE )
3680    {
3681#ifdef TIMESCALE_BUG
3682        /* Check if we are in timescale modification */
3683
3684        if( pParams->OutputVideoTimescale != 0 )
3685        {
3686            pC->uiVideoTimescale = pParams->OutputVideoTimescale;
3687
3688            /* If timescale modification mode is on, we force NULL video encoding ... */
3689            pParams->OutputVideoFormat = M4VIDEOEDITING_kNullVideo;
3690        }
3691
3692#endif
3693
3694        /**
3695        * Check Video Format correctness */
3696
3697        switch( pParams->OutputVideoFormat )
3698        {
3699            case M4VIDEOEDITING_kH263:
3700                if( pParams->OutputFileType == M4VIDEOEDITING_kFileType_MP4 )
3701                    return M4MCS_ERR_H263_FORBIDDEN_IN_MP4_FILE;
3702
3703                pC->EncodingVideoFormat = M4ENCODER_kH263;
3704                err = M4MCS_setCurrentVideoEncoder(pContext,
3705                    pParams->OutputVideoFormat);
3706                M4ERR_CHECK_RETURN(err);
3707                break;
3708
3709            case M4VIDEOEDITING_kMPEG4_EMP:
3710                pC->bActivateEmp = M4OSA_TRUE;
3711
3712            case M4VIDEOEDITING_kMPEG4:
3713
3714                pC->EncodingVideoFormat = M4ENCODER_kMPEG4;
3715                err = M4MCS_setCurrentVideoEncoder(pContext,
3716                    pParams->OutputVideoFormat);
3717                M4ERR_CHECK_RETURN(err);
3718                break;
3719
3720            case M4VIDEOEDITING_kH264:
3721
3722                pC->EncodingVideoFormat = M4ENCODER_kH264;
3723                err = M4MCS_setCurrentVideoEncoder(pContext,
3724                    pParams->OutputVideoFormat);
3725                M4ERR_CHECK_RETURN(err);
3726                break;
3727
3728            case M4VIDEOEDITING_kNullVideo:
3729                if( ( pParams->OutputFileType == M4VIDEOEDITING_kFileType_MP4)
3730                    && (pC->InputFileProperties.VideoStreamType
3731                    == M4VIDEOEDITING_kH263) )
3732                    return M4MCS_ERR_H263_FORBIDDEN_IN_MP4_FILE;
3733
3734
3735                /* If input file is EMP, output file will be too */
3736
3737                if( pC->InputFileProperties.VideoStreamType
3738                    == M4VIDEOEDITING_kMPEG4_EMP )
3739                    pC->bActivateEmp = M4OSA_TRUE;
3740
3741                /* Encoder needed for begin cut to generate an I-frame */
3742                pC->EncodingVideoFormat = M4ENCODER_kNULL;
3743                err = M4MCS_setCurrentVideoEncoder(pContext,
3744                    pC->InputFileProperties.VideoStreamType);
3745                M4ERR_CHECK_RETURN(err);
3746                break;
3747
3748            default:
3749                M4OSA_TRACE1_1("M4MCS_setOutputParams: Undefined output video format (%d),\
3750                               returning M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FORMAT",
3751                               pParams->OutputVideoFormat);
3752                return M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FORMAT;
3753        }
3754
3755        /**
3756        * Check Video frame size correctness */
3757        if( M4VIDEOEDITING_kNullVideo == pParams->OutputVideoFormat )
3758        {
3759            uiFrameWidth =
3760                pC->EncodingWidth = pC->InputFileProperties.uiVideoWidth;
3761            uiFrameHeight =
3762                pC->EncodingHeight = pC->InputFileProperties.uiVideoHeight;
3763        }
3764        else
3765        {
3766            switch( pParams->OutputVideoFrameSize )
3767            {
3768                case M4VIDEOEDITING_kSQCIF:
3769                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_SQCIF_Width;
3770                    uiFrameHeight = pC->EncodingHeight = M4ENCODER_SQCIF_Height;
3771                    break;
3772
3773                case M4VIDEOEDITING_kQQVGA:
3774                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_QQVGA_Width;
3775                    uiFrameHeight = pC->EncodingHeight = M4ENCODER_QQVGA_Height;
3776                    break;
3777
3778                case M4VIDEOEDITING_kQCIF:
3779                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_QCIF_Width;
3780                    uiFrameHeight = pC->EncodingHeight = M4ENCODER_QCIF_Height;
3781                    break;
3782
3783                case M4VIDEOEDITING_kQVGA:
3784                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_QVGA_Width;
3785                    uiFrameHeight = pC->EncodingHeight = M4ENCODER_QVGA_Height;
3786                    break;
3787
3788                case M4VIDEOEDITING_kCIF:
3789                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_CIF_Width;
3790                    uiFrameHeight = pC->EncodingHeight = M4ENCODER_CIF_Height;
3791                    break;
3792
3793                case M4VIDEOEDITING_kVGA:
3794                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_VGA_Width;
3795                    uiFrameHeight = pC->EncodingHeight = M4ENCODER_VGA_Height;
3796                    break;
3797                    /* +PR LV5807 */
3798                case M4VIDEOEDITING_kWVGA:
3799                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_WVGA_Width;
3800                    uiFrameHeight = pC->EncodingHeight = M4ENCODER_WVGA_Height;
3801                    break;
3802
3803                case M4VIDEOEDITING_kNTSC:
3804                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_NTSC_Width;
3805                    uiFrameHeight = pC->EncodingHeight = M4ENCODER_NTSC_Height;
3806                    break;
3807                    /* -PR LV5807*/
3808                    /* +CR Google */
3809                case M4VIDEOEDITING_k640_360:
3810                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_640_360_Width;
3811                    uiFrameHeight =
3812                        pC->EncodingHeight = M4ENCODER_640_360_Height;
3813                    break;
3814
3815                case M4VIDEOEDITING_k854_480:
3816                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_854_480_Width;
3817                    uiFrameHeight =
3818                        pC->EncodingHeight = M4ENCODER_854_480_Height;
3819                    break;
3820
3821                case M4VIDEOEDITING_kHD1280:
3822                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_HD1280_Width;
3823                    uiFrameHeight =
3824                        pC->EncodingHeight = M4ENCODER_HD1280_Height;
3825                    break;
3826
3827                case M4VIDEOEDITING_kHD1080:
3828                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_HD1080_Width;
3829                    uiFrameHeight =
3830                        pC->EncodingHeight = M4ENCODER_HD1080_Height;
3831                    break;
3832
3833                case M4VIDEOEDITING_kHD960:
3834                    uiFrameWidth = pC->EncodingWidth = M4ENCODER_HD960_Width;
3835                    uiFrameHeight = pC->EncodingHeight = M4ENCODER_HD960_Height;
3836                    break;
3837                    /* -CR Google */
3838                default:
3839                    M4OSA_TRACE1_1(
3840                        "M4MCS_setOutputParams: Undefined output video frame size \
3841                        (%d), returning M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FRAME_SIZE",
3842                        pParams->OutputVideoFrameSize);
3843                    return M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FRAME_SIZE;
3844            }
3845        }
3846
3847        /**
3848        * Compute video max au size and max chunck size.
3849        * We do it here because it depends on the frame size only, and
3850        * because we need it for the file size/video bitrate estimations */
3851        pC->uiVideoMaxAuSize =
3852            (M4OSA_UInt32)(1.5F *(M4OSA_Float)(uiFrameWidth * uiFrameHeight) \
3853            *M4MCS_VIDEO_MIN_COMPRESSION_RATIO);
3854        pC->uiVideoMaxChunckSize = (M4OSA_UInt32)(pC->uiVideoMaxAuSize       \
3855            *
3856            M4MCS_VIDEO_CHUNK_AU_SIZE_RATIO); /**< from max AU size to max Chunck size */
3857
3858        if( 0 == pC->uiVideoMaxAuSize )
3859        {
3860            /* Size may be zero in case of null encoding with unrecognized stream */
3861            M4OSA_TRACE1_0("M4MCS_setOutputParams: video frame size is 0 returning\
3862                           M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FRAME_SIZE");
3863            return M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FRAME_SIZE;
3864        }
3865
3866
3867        /**
3868        * Size check for H263 (only valid sizes are CIF, QCIF and SQCIF) */
3869
3870        if( M4VIDEOEDITING_kH263 == pParams->OutputVideoFormat )
3871        {
3872            switch( pParams->OutputVideoFrameSize )
3873            {
3874                case M4VIDEOEDITING_kSQCIF:
3875                case M4VIDEOEDITING_kQCIF:
3876                case M4VIDEOEDITING_kCIF:
3877                    /* OK */
3878                    break;
3879
3880                default:
3881                    M4OSA_TRACE1_0(
3882                        "M4MCS_setOutputParams():\
3883                        returning M4MCS_ERR_INVALID_VIDEO_FRAME_SIZE_FOR_H263");
3884                    return M4MCS_ERR_INVALID_VIDEO_FRAME_SIZE_FOR_H263;
3885            }
3886        }
3887
3888        /**
3889        * Check Video Frame rate correctness */
3890        if( M4VIDEOEDITING_kNullVideo != pParams->OutputVideoFormat )
3891        {
3892            switch( pParams->OutputVideoFrameRate )
3893            {
3894                case M4VIDEOEDITING_k5_FPS:
3895                    pC->EncodingVideoFramerate = M4ENCODER_k5_FPS;
3896                    break;
3897
3898                case M4VIDEOEDITING_k7_5_FPS:
3899                    pC->EncodingVideoFramerate = M4ENCODER_k7_5_FPS;
3900                    break;
3901
3902                case M4VIDEOEDITING_k10_FPS:
3903                    pC->EncodingVideoFramerate = M4ENCODER_k10_FPS;
3904                    break;
3905
3906                case M4VIDEOEDITING_k12_5_FPS:
3907                    pC->EncodingVideoFramerate = M4ENCODER_k12_5_FPS;
3908                    break;
3909
3910                case M4VIDEOEDITING_k15_FPS:
3911                    pC->EncodingVideoFramerate = M4ENCODER_k15_FPS;
3912                    break;
3913
3914                case M4VIDEOEDITING_k20_FPS:
3915                    pC->EncodingVideoFramerate = M4ENCODER_k20_FPS;
3916                    break;
3917
3918                case M4VIDEOEDITING_k25_FPS:
3919                    pC->EncodingVideoFramerate = M4ENCODER_k25_FPS;
3920                    break;
3921
3922                case M4VIDEOEDITING_k30_FPS:
3923                    pC->EncodingVideoFramerate = M4ENCODER_k30_FPS;
3924                    break;
3925
3926                default:
3927                    M4OSA_TRACE1_1(
3928                        "M4MCS_setOutputParams: Undefined output video frame rate\
3929                        (%d), returning M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FRAME_RATE",
3930                        pParams->OutputVideoFrameRate);
3931                    return M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FRAME_RATE;
3932            }
3933        }
3934
3935        /**
3936        * Frame rate check for H263 (only dividers of 30 fps (29.97 actually)) */
3937        if( M4VIDEOEDITING_kH263 == pParams->OutputVideoFormat )
3938        {
3939            switch( pC->EncodingVideoFramerate )
3940            {
3941                case M4ENCODER_k5_FPS:
3942                case M4ENCODER_k7_5_FPS:
3943                case M4ENCODER_k10_FPS:
3944                case M4ENCODER_k15_FPS:
3945                case M4ENCODER_k30_FPS:
3946                    /* OK */
3947                    break;
3948
3949                default:
3950                    M4OSA_TRACE1_0(
3951                        "M4MCS_setOutputParams():\
3952                        returning M4MCS_ERR_INVALID_VIDEO_FRAME_RATE_FOR_H263");
3953                    return M4MCS_ERR_INVALID_VIDEO_FRAME_RATE_FOR_H263;
3954            }
3955        }
3956    }
3957
3958    /* Set audio parameters */
3959    if( pC->noaudio == M4OSA_FALSE )
3960    {
3961        /**
3962        * Check Audio Format correctness */
3963        switch( pParams->OutputAudioFormat )
3964        {
3965            case M4VIDEOEDITING_kAMR_NB:
3966
3967                err = M4MCS_setCurrentAudioEncoder(pContext,
3968                    pParams->OutputAudioFormat);
3969                M4ERR_CHECK_RETURN(err);
3970
3971                pC->AudioEncParams.Format = M4ENCODER_kAMRNB;
3972                pC->AudioEncParams.Frequency = M4ENCODER_k8000Hz;
3973                pC->AudioEncParams.ChannelNum = M4ENCODER_kMono;
3974                pC->AudioEncParams.SpecifParam.AmrSID = M4ENCODER_kAmrNoSID;
3975                break;
3976
3977            case M4VIDEOEDITING_kAAC:
3978
3979                err = M4MCS_setCurrentAudioEncoder(pContext,
3980                    pParams->OutputAudioFormat);
3981                M4ERR_CHECK_RETURN(err);
3982
3983                pC->AudioEncParams.Format = M4ENCODER_kAAC;
3984                pC->AudioEncParams.Frequency = M4ENCODER_k16000Hz;
3985
3986                switch( pParams->OutputAudioSamplingFrequency )
3987                {
3988                    case M4VIDEOEDITING_k8000_ASF:
3989                        pC->AudioEncParams.Frequency = M4ENCODER_k8000Hz;
3990                        break;
3991
3992                    case M4VIDEOEDITING_k16000_ASF:
3993                        pC->AudioEncParams.Frequency = M4ENCODER_k16000Hz;
3994                        break;
3995
3996                    case M4VIDEOEDITING_k22050_ASF:
3997                        pC->AudioEncParams.Frequency = M4ENCODER_k22050Hz;
3998                        break;
3999
4000                    case M4VIDEOEDITING_k24000_ASF:
4001                        pC->AudioEncParams.Frequency = M4ENCODER_k24000Hz;
4002                        break;
4003
4004                    case M4VIDEOEDITING_k32000_ASF:
4005                        pC->AudioEncParams.Frequency = M4ENCODER_k32000Hz;
4006                        break;
4007
4008                    case M4VIDEOEDITING_k44100_ASF:
4009                        pC->AudioEncParams.Frequency = M4ENCODER_k44100Hz;
4010                        break;
4011
4012                    case M4VIDEOEDITING_k48000_ASF:
4013                        pC->AudioEncParams.Frequency = M4ENCODER_k48000Hz;
4014                        break;
4015
4016                    case M4VIDEOEDITING_k11025_ASF:
4017                    case M4VIDEOEDITING_k12000_ASF:
4018                    case M4VIDEOEDITING_kDefault_ASF:
4019                        break;
4020                }
4021                    pC->AudioEncParams.ChannelNum =
4022                        (pParams->bAudioMono == M4OSA_TRUE) ? \
4023                        M4ENCODER_kMono : M4ENCODER_kStereo;
4024                    pC->AudioEncParams.SpecifParam.AacParam.Regulation =
4025                        M4ENCODER_kAacRegulNone; //M4ENCODER_kAacBitReservoir
4026                    /* unused */
4027                    pC->AudioEncParams.SpecifParam.AacParam.bIS = M4OSA_FALSE;
4028                    pC->AudioEncParams.SpecifParam.AacParam.bMS = M4OSA_FALSE;
4029                    pC->AudioEncParams.SpecifParam.AacParam.bPNS = M4OSA_FALSE;
4030                    pC->AudioEncParams.SpecifParam.AacParam.bTNS = M4OSA_FALSE;
4031                    /* TODO change into highspeed asap */
4032                    pC->AudioEncParams.SpecifParam.AacParam.bHighSpeed =
4033                        M4OSA_FALSE;
4034                    break;
4035
4036                    /*FlB 26.02.2009: add mp3 as mcs output format, add mp3 encoder*/
4037                case M4VIDEOEDITING_kMP3:
4038                    err = M4MCS_setCurrentAudioEncoder(pContext,
4039                        pParams->OutputAudioFormat);
4040                    M4ERR_CHECK_RETURN(err);
4041
4042                    pC->AudioEncParams.Format = M4ENCODER_kMP3;
4043                    pC->AudioEncParams.ChannelNum =
4044                        (pParams->bAudioMono == M4OSA_TRUE) ? \
4045                        M4ENCODER_kMono : M4ENCODER_kStereo;
4046
4047                    pC->AudioEncParams.Frequency = M4ENCODER_k16000Hz;
4048
4049                    switch( pParams->OutputAudioSamplingFrequency )
4050                    {
4051                        case M4VIDEOEDITING_k8000_ASF:
4052                            pC->AudioEncParams.Frequency = M4ENCODER_k8000Hz;
4053                            break;
4054
4055                        case M4VIDEOEDITING_k11025_ASF:
4056                            pC->AudioEncParams.Frequency = M4ENCODER_k11025Hz;
4057                            break;
4058
4059                        case M4VIDEOEDITING_k12000_ASF:
4060                            pC->AudioEncParams.Frequency = M4ENCODER_k12000Hz;
4061                            break;
4062
4063                        case M4VIDEOEDITING_k16000_ASF:
4064                            pC->AudioEncParams.Frequency = M4ENCODER_k16000Hz;
4065                            break;
4066
4067                        case M4VIDEOEDITING_k22050_ASF:
4068                            pC->AudioEncParams.Frequency = M4ENCODER_k22050Hz;
4069                            break;
4070
4071                        case M4VIDEOEDITING_k24000_ASF:
4072                            pC->AudioEncParams.Frequency = M4ENCODER_k24000Hz;
4073                            break;
4074
4075                        case M4VIDEOEDITING_k32000_ASF:
4076                            pC->AudioEncParams.Frequency = M4ENCODER_k32000Hz;
4077                            break;
4078
4079                        case M4VIDEOEDITING_k44100_ASF:
4080                            pC->AudioEncParams.Frequency = M4ENCODER_k44100Hz;
4081                            break;
4082
4083                        case M4VIDEOEDITING_k48000_ASF:
4084                            pC->AudioEncParams.Frequency = M4ENCODER_k48000Hz;
4085                            break;
4086
4087                        case M4VIDEOEDITING_kDefault_ASF:
4088                            break;
4089                    }
4090
4091                    break;
4092
4093                case M4VIDEOEDITING_kNullAudio:
4094                    if( pParams->pEffects == M4OSA_NULL || pParams->nbEffects == 0 )
4095                    {
4096                        /* no encoder needed */
4097                        pC->AudioEncParams.Format = M4ENCODER_kAudioNULL;
4098                        pC->AudioEncParams.Frequency =
4099                            pC->pReaderAudioStream->m_samplingFrequency;
4100                        pC->AudioEncParams.ChannelNum =
4101                            (pC->pReaderAudioStream->m_nbChannels == 1) ? \
4102                            M4ENCODER_kMono : M4ENCODER_kStereo;
4103                    }
4104                    else
4105                    {
4106                        pC->AudioEncParams.Frequency =
4107                            pC->pReaderAudioStream->m_samplingFrequency;
4108                        pC->AudioEncParams.ChannelNum =
4109                            (pC->pReaderAudioStream->m_nbChannels == 1) ? \
4110                            M4ENCODER_kMono : M4ENCODER_kStereo;
4111
4112                        switch( pC->InputFileProperties.AudioStreamType )
4113                        {
4114                            case M4VIDEOEDITING_kAMR_NB:
4115                                M4OSA_TRACE3_0(
4116                                    "M4MCS_setOutputParams calling \
4117                                    M4MCS_setCurrentAudioEncoder M4VIDEOEDITING_kNull, AMR");
4118                                err = M4MCS_setCurrentAudioEncoder(pContext,
4119                                    pC->InputFileProperties.AudioStreamType);
4120                                M4ERR_CHECK_RETURN(err);
4121
4122                                pC->AudioEncParams.Format = M4ENCODER_kAMRNB;
4123                                pC->AudioEncParams.Frequency = M4ENCODER_k8000Hz;
4124                                pC->AudioEncParams.ChannelNum = M4ENCODER_kMono;
4125
4126                                if( pC->pReaderAudioStream->m_samplingFrequency
4127                                    != 8000 )
4128                                {
4129                                    pC->AudioEncParams.Format = M4ENCODER_kAMRNB;
4130                                }
4131                                pC->AudioEncParams.SpecifParam.AmrSID =
4132                                    M4ENCODER_kAmrNoSID;
4133                                break;
4134
4135                            case M4VIDEOEDITING_kAAC:
4136                                M4OSA_TRACE3_0(
4137                                    "M4MCS_setOutputParams calling \
4138                                    M4MCS_setCurrentAudioEncoder M4VIDEOEDITING_kNull, AAC");
4139                                err = M4MCS_setCurrentAudioEncoder(pContext,
4140                                    pC->InputFileProperties.AudioStreamType);
4141                                M4ERR_CHECK_RETURN(err);
4142
4143                                pC->AudioEncParams.Format = M4ENCODER_kAAC;
4144                                pC->AudioEncParams.SpecifParam.AacParam.Regulation =
4145                                    M4ENCODER_kAacRegulNone; //M4ENCODER_kAacBitReservoir
4146                                pC->AudioEncParams.Frequency = M4ENCODER_k16000Hz;
4147                                pC->AudioEncParams.Frequency = M4ENCODER_k16000Hz;
4148
4149                                switch( pC->pReaderAudioStream->
4150                                    m_samplingFrequency )
4151                                {
4152                                case 16000:
4153                                    pC->AudioEncParams.Frequency =
4154                                        M4ENCODER_k16000Hz;
4155                                    break;
4156
4157                                case 22050:
4158                                    pC->AudioEncParams.Frequency =
4159                                        M4ENCODER_k22050Hz;
4160                                    break;
4161
4162                                case 24000:
4163                                    pC->AudioEncParams.Frequency =
4164                                        M4ENCODER_k24000Hz;
4165                                    break;
4166
4167                                case 32000:
4168                                    pC->AudioEncParams.Frequency =
4169                                        M4ENCODER_k32000Hz;
4170                                    break;
4171
4172                                case 44100:
4173                                    pC->AudioEncParams.Frequency =
4174                                        M4ENCODER_k44100Hz;
4175                                    break;
4176
4177                                case 48000:
4178                                    pC->AudioEncParams.Frequency =
4179                                        M4ENCODER_k48000Hz;
4180                                    break;
4181
4182                                default:
4183                                    pC->AudioEncParams.Format = M4ENCODER_kAAC;
4184                                    break;
4185                            }
4186                            /* unused */
4187                            pC->AudioEncParams.SpecifParam.AacParam.bIS =
4188                                M4OSA_FALSE;
4189                            pC->AudioEncParams.SpecifParam.AacParam.bMS =
4190                                M4OSA_FALSE;
4191                            pC->AudioEncParams.SpecifParam.AacParam.bPNS =
4192                                M4OSA_FALSE;
4193                            pC->AudioEncParams.SpecifParam.AacParam.bTNS =
4194                                M4OSA_FALSE;
4195                            /* TODO change into highspeed asap */
4196                            pC->AudioEncParams.SpecifParam.AacParam.bHighSpeed =
4197                                M4OSA_FALSE;
4198                            break;
4199
4200                        case M4VIDEOEDITING_kMP3:
4201                            M4OSA_TRACE3_0(
4202                                "M4MCS_setOutputParams calling\
4203                                M4MCS_setCurrentAudioEncoder M4VIDEOEDITING_kNull, MP3");
4204                            err = M4MCS_setCurrentAudioEncoder(pContext,
4205                                pC->InputFileProperties.AudioStreamType);
4206                            M4ERR_CHECK_RETURN(err);
4207
4208                            pC->AudioEncParams.Format = M4ENCODER_kMP3;
4209                            pC->AudioEncParams.Frequency = M4ENCODER_k16000Hz;
4210
4211                            switch( pC->pReaderAudioStream->
4212                                m_samplingFrequency )
4213                            {
4214                                case 8000:
4215                                    pC->AudioEncParams.Frequency =
4216                                        M4ENCODER_k8000Hz;
4217                                    break;
4218
4219                                case 16000:
4220                                    pC->AudioEncParams.Frequency =
4221                                        M4ENCODER_k16000Hz;
4222                                    break;
4223
4224                                case 22050:
4225                                    pC->AudioEncParams.Frequency =
4226                                        M4ENCODER_k22050Hz;
4227                                    break;
4228
4229                                case 24000:
4230                                    pC->AudioEncParams.Frequency =
4231                                        M4ENCODER_k24000Hz;
4232                                    break;
4233
4234                                case 32000:
4235                                    pC->AudioEncParams.Frequency =
4236                                        M4ENCODER_k32000Hz;
4237                                    break;
4238
4239                                case 44100:
4240                                    pC->AudioEncParams.Frequency =
4241                                        M4ENCODER_k44100Hz;
4242                                    break;
4243
4244                                case 48000:
4245                                    pC->AudioEncParams.Frequency =
4246                                        M4ENCODER_k48000Hz;
4247                                    break;
4248
4249                                default:
4250                                    pC->AudioEncParams.Format = M4ENCODER_kMP3;
4251                                    break;
4252                            }
4253                            break;
4254
4255                        case M4VIDEOEDITING_kEVRC:
4256                        case M4VIDEOEDITING_kUnsupportedAudio:
4257                        default:
4258                            M4OSA_TRACE1_1(
4259                                "M4MCS_setOutputParams: Output audio format (%d) is\
4260                                incompatible with audio effects, returning \
4261                                M4MCS_ERR_UNDEFINED_OUTPUT_AUDIO_FORMAT",
4262                                pC->InputFileProperties.AudioStreamType);
4263                            return M4MCS_ERR_UNDEFINED_OUTPUT_AUDIO_FORMAT;
4264                        }
4265                    }
4266                    break;
4267                    /* EVRC
4268                    //            case M4VIDEOEDITING_kEVRC:
4269                    //
4270                    //                err = M4MCS_setCurrentAudioEncoder(pContext, pParams->\
4271                    //                    OutputAudioFormat);
4272                    //                M4ERR_CHECK_RETURN(err);
4273                    //
4274                    //                pC->AudioEncParams.Format = M4ENCODER_kEVRC;
4275                    //                pC->AudioEncParams.Frequency = M4ENCODER_k8000Hz;
4276                    //                pC->AudioEncParams.ChannelNum = M4ENCODER_kMono;
4277                    //                break; */
4278
4279                default:
4280                    M4OSA_TRACE1_1("M4MCS_setOutputParams: Undefined output audio format (%d),\
4281                                   returning M4MCS_ERR_UNDEFINED_OUTPUT_AUDIO_FORMAT",
4282                                   pParams->OutputAudioFormat);
4283                    return M4MCS_ERR_UNDEFINED_OUTPUT_AUDIO_FORMAT;
4284        }
4285    }
4286
4287    if( pParams->pOutputPCMfile != M4OSA_NULL )
4288    {
4289        pC->pOutputPCMfile = pParams->pOutputPCMfile;
4290
4291        /* Open output PCM file */
4292        pC->pOsaFileWritPtr->openWrite(&(pC->pOutputPCMfile),
4293            pParams->pOutputPCMfile, M4OSA_kFileWrite);
4294    }
4295    else
4296    {
4297        pC->pOutputPCMfile = M4OSA_NULL;
4298    }
4299
4300    /*Store media rendering parameter into the internal context*/
4301    pC->MediaRendering = pParams->MediaRendering;
4302
4303    /* Add audio effects*/
4304    /*Copy MCS effects structure into internal context*/
4305    if( pParams->nbEffects > 0 )
4306    {
4307        M4OSA_UInt32 j = 0;
4308        pC->nbEffects = pParams->nbEffects;
4309        pC->pEffects = (M4MCS_EffectSettings *)M4OSA_malloc(pC->nbEffects \
4310            *sizeof(M4MCS_EffectSettings), M4MCS,
4311            (M4OSA_Char *)"Allocation of effects list");
4312
4313        if( pC->pEffects == M4OSA_NULL )
4314        {
4315            M4OSA_TRACE1_0("M4MCS_setOutputParams(): allocation error");
4316            return M4ERR_ALLOC;
4317        }
4318
4319        for ( j = 0; j < pC->nbEffects; j++ )
4320        {
4321            /* Copy effect to "local" structure */
4322            memcpy((void *) &(pC->pEffects[j]),
4323                (void *) &(pParams->pEffects[j]),
4324                sizeof(M4MCS_EffectSettings));
4325
4326            switch( pC->pEffects[j].AudioEffectType )
4327            {
4328                case M4MCS_kAudioEffectType_None:
4329                    M4OSA_TRACE3_1(
4330                        "M4MCS_setOutputParams(): effect type %i is None", j);
4331                    pC->pEffects[j].pExtAudioEffectFctCtxt = M4OSA_NULL;
4332                    pC->pEffects[j].ExtAudioEffectFct = M4OSA_NULL;
4333                    break;
4334
4335                case M4MCS_kAudioEffectType_FadeIn:
4336                    M4OSA_TRACE3_1(
4337                        "M4MCS_setOutputParams(): effect type %i is FadeIn", j);
4338                    pC->pEffects[j].pExtAudioEffectFctCtxt = M4OSA_NULL;
4339                    pC->pEffects[j].ExtAudioEffectFct =
4340                        M4MCS_editAudioEffectFct_FadeIn;
4341                    break;
4342
4343                case M4MCS_kAudioEffectType_FadeOut:
4344                    M4OSA_TRACE3_1(
4345                        "M4MCS_setOutputParams(): effect type %i is FadeOut",
4346                        j);
4347                    pC->pEffects[j].pExtAudioEffectFctCtxt = M4OSA_NULL;
4348                    pC->pEffects[j].ExtAudioEffectFct =
4349                        M4MCS_editAudioEffectFct_FadeOut;
4350                    break;
4351
4352                case M4MCS_kAudioEffectType_External:
4353                    M4OSA_TRACE3_1(
4354                        "M4MCS_setOutputParams(): effect type %i is External",
4355                        j);
4356
4357                    if( pParams->pEffects != M4OSA_NULL )
4358                    {
4359                        if( pParams->pEffects[j].ExtAudioEffectFct
4360                            == M4OSA_NULL )
4361                        {
4362                            M4OSA_TRACE1_1("M4MCS_setOutputParams(): no external effect function\
4363                                           associated to external effect number %i", j);
4364                            return M4ERR_PARAMETER;
4365                        }
4366                        pC->pEffects[j].pExtAudioEffectFctCtxt =
4367                            pParams->pEffects[j].pExtAudioEffectFctCtxt;
4368
4369                        pC->pEffects[j].ExtAudioEffectFct =
4370                            pParams->pEffects[j].ExtAudioEffectFct;
4371                    }
4372
4373                    break;
4374
4375                default:
4376                    M4OSA_TRACE1_0(
4377                        "M4MCS_setOutputParams(): effect type not recognized");
4378                    return M4ERR_PARAMETER;
4379            }
4380        }
4381    }
4382    else
4383    {
4384        pC->nbEffects = 0;
4385        pC->pEffects = M4OSA_NULL;
4386    }
4387
4388    /**
4389    * Update state automaton */
4390    pC->State = M4MCS_kState_SET;
4391
4392    /**
4393    * Return with no error */
4394    M4OSA_TRACE3_0("M4MCS_setOutputParams(): returning M4NO_ERROR");
4395    return M4NO_ERROR;
4396}
4397
4398/**
4399 ******************************************************************************
4400 * M4OSA_ERR M4MCS_setEncodingParams(M4MCS_Context pContext, M4MCS_EncodingParams* pRates)
4401 * @brief   Set the values of the encoding parameters
4402 * @note    Must be called before M4MCS_checkParamsAndStart().
4403 * @param   pContext           (IN) MCS context
4404 * @param   pRates             (IN) Transcoding parameters
4405 * @return  M4NO_ERROR:         No error
4406 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (debug only)
4407 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
4408 * @return  M4MCS_ERR_AUDIOBITRATE_TOO_HIGH: Audio bitrate too high (we limit to 96 kbps)
4409 * @return  M4MCS_ERR_AUDIOBITRATE_TOO_LOW: Audio bitrate is too low (16 kbps min for aac, 12.2
4410 *                                            for amr, 8 for mp3)
4411 * @return  M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT: Begin cut and End cut are equals
4412 * @return  M4MCS_ERR_BEGIN_CUT_LARGER_THAN_DURATION: Begin cut time is larger than the input clip
4413 *                                                     duration
4414 * @return  M4MCS_ERR_END_CUT_SMALLER_THAN_BEGIN_CUT: End cut time is smaller than begin cut time
4415 * @return  M4MCS_ERR_MAXFILESIZE_TOO_SMALL: Not enough space to store whole output file at given
4416 *                                             bitrates
4417 * @return  M4MCS_ERR_VIDEOBITRATE_TOO_HIGH: Video bitrate too high (we limit to 800 kbps)
4418 * @return  M4MCS_ERR_VIDEOBITRATE_TOO_LOW:  Video bitrate too low
4419 ******************************************************************************
4420 */
4421M4OSA_ERR M4MCS_setEncodingParams( M4MCS_Context pContext,
4422                                  M4MCS_EncodingParams *pRates )
4423{
4424    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
4425    M4OSA_UInt32 j = 0;
4426
4427    M4OSA_TRACE2_2(
4428        "M4MCS_setEncodingParams called with pContext=0x%x, pRates=0x%x",
4429        pContext, pRates);
4430
4431    /**
4432    * Check input parameters */
4433    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
4434        "M4MCS_setEncodingParams: pContext is M4OSA_NULL");
4435    M4OSA_DEBUG_IF2((M4OSA_NULL == pRates), M4ERR_PARAMETER,
4436        "M4MCS_setEncodingParams: pRates is M4OSA_NULL");
4437
4438#ifdef M4MCS_SUPPORT_STILL_PICTURE
4439
4440    if( pC->m_bIsStillPicture )
4441    {
4442        /**
4443        * Call the corresponding still picture MCS function*/
4444        return M4MCS_stillPicSetEncodingParams(pC, pRates);
4445    }
4446
4447#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
4448
4449    /**
4450    * Check state automaton */
4451
4452    if( M4MCS_kState_SET != pC->State )
4453    {
4454        M4OSA_TRACE1_1(
4455            "M4MCS_setEncodingParams(): Wrong State (%d), returning M4ERR_STATE",
4456            pC->State);
4457        return M4ERR_STATE;
4458    }
4459
4460    /* Set given values */
4461    pC->uiVideoBitrate = pRates->OutputVideoBitrate;
4462    pC->uiAudioBitrate = pRates->OutputAudioBitrate;
4463    pC->uiBeginCutTime = pRates->BeginCutTime;
4464    pC->uiEndCutTime = pRates->EndCutTime;
4465    pC->uiMaxFileSize = pRates->OutputFileSize;
4466
4467    /**
4468    * Check begin cut time validity */
4469    if( pC->uiBeginCutTime >= pC->InputFileProperties.uiClipDuration )
4470    {
4471        M4OSA_TRACE1_2("M4MCS_setEncodingParams(): Begin cut larger than duration (%d>%d),\
4472                       returning M4MCS_ERR_BEGIN_CUT_LARGER_THAN_DURATION",
4473                       pC->uiBeginCutTime, pC->InputFileProperties.uiClipDuration);
4474        return M4MCS_ERR_BEGIN_CUT_LARGER_THAN_DURATION;
4475    }
4476
4477    /**
4478    * If end cut time is too large, we set it to the clip duration */
4479    if( pC->uiEndCutTime > pC->InputFileProperties.uiClipDuration )
4480    {
4481        pC->uiEndCutTime = pC->InputFileProperties.uiClipDuration;
4482    }
4483
4484    /**
4485    * Check end cut time validity */
4486    if( pC->uiEndCutTime > 0 )
4487    {
4488        if( pC->uiEndCutTime < pC->uiBeginCutTime )
4489        {
4490            M4OSA_TRACE1_2("M4MCS_setEncodingParams(): Begin cut greater than end cut (%d,%d), \
4491                           returning M4MCS_ERR_END_CUT_SMALLER_THAN_BEGIN_CUT",
4492                           pC->uiBeginCutTime, pC->uiEndCutTime);
4493            return M4MCS_ERR_END_CUT_SMALLER_THAN_BEGIN_CUT;
4494        }
4495
4496        if( pC->uiEndCutTime == pC->uiBeginCutTime )
4497        {
4498            M4OSA_TRACE1_2("M4MCS_setEncodingParams(): Begin and End cuts are equal (%d,%d),\
4499                           returning M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT",
4500                           pC->uiBeginCutTime, pC->uiEndCutTime);
4501            return M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT;
4502        }
4503    }
4504
4505    /**
4506    * FlB 2009.03.04: check audio effects start time and duration validity*/
4507    for ( j = 0; j < pC->nbEffects; j++ )
4508    {
4509        M4OSA_UInt32 outputEndCut = pC->uiEndCutTime;
4510
4511        if( pC->uiEndCutTime == 0 )
4512        {
4513            outputEndCut = pC->InputFileProperties.uiClipDuration;
4514        }
4515
4516        if( pC->pEffects[j].uiStartTime > (outputEndCut - pC->uiBeginCutTime) )
4517        {
4518            M4OSA_TRACE1_2("M4MCS_setEncodingParams(): Effects start time is larger than\
4519                           duration (%d,%d), returning M4ERR_PARAMETER",
4520                           pC->pEffects[j].uiStartTime,
4521                           (pC->uiEndCutTime - pC->uiBeginCutTime));
4522            return M4ERR_PARAMETER;
4523        }
4524
4525        if( pC->pEffects[j].uiStartTime + pC->pEffects[j].uiDuration > \
4526            (outputEndCut - pC->uiBeginCutTime) )
4527        {
4528            /* Re-adjust the effect duration until the end of the output clip*/
4529            pC->pEffects[j].uiDuration = (outputEndCut - pC->uiBeginCutTime) - \
4530                pC->pEffects[j].uiStartTime;
4531        }
4532    }
4533
4534    /* Check audio bitrate consistency */
4535    if( ( pC->noaudio == M4OSA_FALSE)
4536        && (pC->AudioEncParams.Format != M4ENCODER_kAudioNULL) )
4537    {
4538        if( pC->uiAudioBitrate != M4VIDEOEDITING_kUndefinedBitrate )
4539        {
4540            if( pC->AudioEncParams.Format == M4ENCODER_kAMRNB )
4541            {
4542                if( pC->uiAudioBitrate > M4VIDEOEDITING_k12_2_KBPS )
4543                    return M4MCS_ERR_AUDIOBITRATE_TOO_HIGH;
4544
4545                if( pC->uiAudioBitrate < M4VIDEOEDITING_k12_2_KBPS )
4546                    return M4MCS_ERR_AUDIOBITRATE_TOO_LOW;
4547            }
4548            //EVRC
4549            //            else if(pC->AudioEncParams.Format == M4ENCODER_kEVRC)
4550            //            {
4551            //                if(pC->uiAudioBitrate > M4VIDEOEDITING_k9_2_KBPS)
4552            //                    return M4MCS_ERR_AUDIOBITRATE_TOO_HIGH;
4553            //                if(pC->uiAudioBitrate < M4VIDEOEDITING_k9_2_KBPS)
4554            //                     return M4MCS_ERR_AUDIOBITRATE_TOO_LOW;
4555            //            }
4556            /*FlB 26.02.2009: add mp3 as mcs output format, add mp3 encoder*/
4557            else if( pC->AudioEncParams.Format == M4ENCODER_kMP3 )
4558            {
4559                if( pC->AudioEncParams.Frequency >= M4ENCODER_k32000Hz )
4560                {
4561                    /*Mpeg layer 1*/
4562                    if( pC->uiAudioBitrate > 320000 )
4563                        return M4MCS_ERR_AUDIOBITRATE_TOO_HIGH;
4564
4565                    if( pC->uiAudioBitrate < 32000 )
4566                        return M4MCS_ERR_AUDIOBITRATE_TOO_LOW;
4567                }
4568                else if( pC->AudioEncParams.Frequency >= M4ENCODER_k16000Hz )
4569                {
4570                    /*Mpeg layer 2*/
4571                    if( pC->uiAudioBitrate > 160000 )
4572                        return M4MCS_ERR_AUDIOBITRATE_TOO_HIGH;
4573
4574                    if( ( pC->uiAudioBitrate < 8000
4575                        && pC->AudioEncParams.ChannelNum == M4ENCODER_kMono)
4576                        || (pC->uiAudioBitrate < 16000
4577                        && pC->AudioEncParams.ChannelNum
4578                        == M4ENCODER_kStereo) )
4579                        return M4MCS_ERR_AUDIOBITRATE_TOO_LOW;
4580                }
4581                else if( pC->AudioEncParams.Frequency == M4ENCODER_k8000Hz
4582                    || pC->AudioEncParams.Frequency == M4ENCODER_k11025Hz
4583                    || pC->AudioEncParams.Frequency == M4ENCODER_k12000Hz )
4584                {
4585                    /*Mpeg layer 2.5*/
4586                    if( pC->uiAudioBitrate > 64000 )
4587                        return M4MCS_ERR_AUDIOBITRATE_TOO_HIGH;
4588
4589                    if( ( pC->uiAudioBitrate < 8000
4590                        && pC->AudioEncParams.ChannelNum == M4ENCODER_kMono)
4591                        || (pC->uiAudioBitrate < 16000
4592                        && pC->AudioEncParams.ChannelNum
4593                        == M4ENCODER_kStereo) )
4594                        return M4MCS_ERR_AUDIOBITRATE_TOO_LOW;
4595                }
4596                else
4597                {
4598                    M4OSA_TRACE1_1("M4MCS_setEncodingParams: MP3 audio sampling frequency error\
4599                                   (%d)", pC->AudioEncParams.Frequency);
4600                    return M4ERR_PARAMETER;
4601                }
4602            }
4603            else
4604            {
4605                if( pC->uiAudioBitrate > M4VIDEOEDITING_k192_KBPS )
4606                    return M4MCS_ERR_AUDIOBITRATE_TOO_HIGH;
4607
4608                if( pC->AudioEncParams.ChannelNum == M4ENCODER_kMono )
4609                {
4610                    if( pC->uiAudioBitrate < M4VIDEOEDITING_k16_KBPS )
4611                        return M4MCS_ERR_AUDIOBITRATE_TOO_LOW;
4612                }
4613                else
4614                {
4615                    if( pC->uiAudioBitrate < M4VIDEOEDITING_k32_KBPS )
4616                        return M4MCS_ERR_AUDIOBITRATE_TOO_LOW;
4617                }
4618            }
4619        }
4620    }
4621    else
4622    {
4623        /* NULL audio : copy input file bitrate */
4624        pC->uiAudioBitrate = pC->InputFileProperties.uiAudioBitrate;
4625    }
4626
4627    /* Check video bitrate consistency */
4628    if( ( pC->novideo == M4OSA_FALSE)
4629        && (pC->EncodingVideoFormat != M4ENCODER_kNULL) )
4630    {
4631        if( pC->uiVideoBitrate != M4VIDEOEDITING_kUndefinedBitrate )
4632        {
4633            if( pC->uiVideoBitrate > M4VIDEOEDITING_k8_MBPS )
4634                return M4MCS_ERR_VIDEOBITRATE_TOO_HIGH;
4635
4636            if( pC->uiVideoBitrate < M4VIDEOEDITING_k16_KBPS )
4637                return M4MCS_ERR_VIDEOBITRATE_TOO_LOW;
4638        }
4639    }
4640    else
4641    {
4642        /* NULL video : copy input file bitrate */
4643        pC->uiVideoBitrate = pC->InputFileProperties.uiVideoBitrate;
4644    }
4645
4646    if( pRates->OutputVideoTimescale <= 30000
4647        && pRates->OutputVideoTimescale > 0 )
4648    {
4649        pC->outputVideoTimescale = pRates->OutputVideoTimescale;
4650    }
4651
4652    /* Check file size */
4653    return M4MCS_intCheckMaxFileSize(pC);
4654}
4655
4656/**
4657 ******************************************************************************
4658 * M4OSA_ERR M4MCS_getExtendedEncodingParams(M4MCS_Context pContext, M4MCS_EncodingParams* pRates)
4659 * @brief   Get the extended values of the encoding parameters
4660 * @note    Could be called after M4MCS_setEncodingParams.
4661 * @param   pContext           (IN) MCS context
4662 * @param   pRates             (OUT) Transcoding parameters
4663 * @return  M4NO_ERROR:         No error
4664 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (debug only)
4665 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
4666 * @return  M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT: Encoding settings would produce a null duration
4667 *                                             clip = encoding is impossible
4668 ******************************************************************************
4669 */
4670M4OSA_ERR M4MCS_getExtendedEncodingParams( M4MCS_Context pContext,
4671                                          M4MCS_EncodingParams *pRates )
4672{
4673    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
4674
4675    M4OSA_Int32 minaudiobitrate;
4676    M4OSA_Int32 minvideobitrate;
4677    M4OSA_Int32 maxcombinedbitrate;
4678
4679    M4OSA_Int32 calcbitrate;
4680
4681    M4OSA_UInt32 maxduration;
4682    M4OSA_UInt32 calcduration;
4683
4684    M4OSA_Bool fixed_audio = M4OSA_FALSE;
4685    M4OSA_Bool fixed_video = M4OSA_FALSE;
4686
4687#ifdef M4MCS_SUPPORT_STILL_PICTURE
4688
4689    if( pC->m_bIsStillPicture )
4690    {
4691        /**
4692        * Call the corresponding still picture MCS function*/
4693        return M4MCS_stillPicGetExtendedEncodingParams(pC, pRates);
4694    }
4695
4696#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
4697
4698    pRates->OutputVideoBitrate =
4699        M4MCS_intGetNearestBitrate(pC->uiVideoBitrate, 0);
4700    pRates->OutputAudioBitrate =
4701        M4MCS_intGetNearestBitrate(pC->uiAudioBitrate, 0);
4702    pRates->BeginCutTime = pC->uiBeginCutTime;
4703    pRates->EndCutTime = pC->uiEndCutTime;
4704    pRates->OutputFileSize = pC->uiMaxFileSize;
4705
4706    /**
4707    * Check state automaton */
4708    if( M4MCS_kState_SET != pC->State )
4709    {
4710        M4OSA_TRACE1_1("M4MCS_getExtendedEncodingParams(): Wrong State (%d),\
4711                       returning M4ERR_STATE", pC->State);
4712        return M4ERR_STATE;
4713    }
4714
4715    /* Compute min audio bitrate */
4716    if( pC->noaudio )
4717    {
4718        fixed_audio = M4OSA_TRUE;
4719        pRates->OutputAudioBitrate = 0;
4720        minaudiobitrate = 0;
4721    }
4722    else if( pC->AudioEncParams.Format == M4ENCODER_kAudioNULL )
4723    {
4724        fixed_audio = M4OSA_TRUE;
4725        pRates->OutputAudioBitrate = pC->InputFileProperties.uiAudioBitrate;
4726        minaudiobitrate = pC->InputFileProperties.uiAudioBitrate;
4727    }
4728    else
4729    {
4730        if( pC->AudioEncParams.Format == M4ENCODER_kAMRNB )
4731        {
4732            fixed_audio = M4OSA_TRUE;
4733            pRates->OutputAudioBitrate = M4VIDEOEDITING_k12_2_KBPS;
4734            minaudiobitrate = M4VIDEOEDITING_k12_2_KBPS;
4735        }
4736        //EVRC
4737        //        if(pC->AudioEncParams.Format == M4ENCODER_kEVRC)
4738        //        {
4739        //            fixed_audio = M4OSA_TRUE;
4740        //            pRates->OutputAudioBitrate = M4VIDEOEDITING_k9_2_KBPS;
4741        //            minaudiobitrate = M4VIDEOEDITING_k9_2_KBPS;
4742        //        }
4743        /*FlB 26.02.2009: add mp3 as mcs output format*/
4744        else if( pC->AudioEncParams.Format == M4ENCODER_kMP3 )
4745        {
4746            minaudiobitrate =
4747                M4VIDEOEDITING_k32_KBPS; /*Default min audio bitrate for MPEG layer 1,
4748                                             for both mono and stereo channels*/
4749        }
4750        else
4751        {
4752            minaudiobitrate = (pC->AudioEncParams.ChannelNum == M4ENCODER_kMono)
4753                ? M4VIDEOEDITING_k16_KBPS : M4VIDEOEDITING_k32_KBPS;
4754        }
4755    }
4756
4757    /* Check audio bitrate is in the correct range */
4758    if( fixed_audio == M4OSA_FALSE )
4759    {
4760        if( ( pC->uiAudioBitrate > 0)
4761            && (pRates->OutputAudioBitrate < minaudiobitrate) )
4762        {
4763            pRates->OutputAudioBitrate = minaudiobitrate;
4764        }
4765
4766        if( pRates->OutputAudioBitrate > M4VIDEOEDITING_k96_KBPS )
4767        {
4768            pRates->OutputAudioBitrate = M4VIDEOEDITING_k96_KBPS;
4769        }
4770    }
4771
4772    /* Compute min video bitrate */
4773    if( pC->novideo )
4774    {
4775        fixed_video = M4OSA_TRUE;
4776        pRates->OutputVideoBitrate = 0;
4777        minvideobitrate = 0;
4778    }
4779    else if( pC->EncodingVideoFormat == M4ENCODER_kNULL )
4780    {
4781        fixed_video = M4OSA_TRUE;
4782        pRates->OutputVideoBitrate = pC->InputFileProperties.uiVideoBitrate;
4783        minvideobitrate = pC->InputFileProperties.uiVideoBitrate;
4784    }
4785    else
4786    {
4787        minvideobitrate = M4VIDEOEDITING_k16_KBPS;
4788    }
4789
4790    /* Check video bitrate is in the correct range */
4791    if( fixed_video == M4OSA_FALSE )
4792    {
4793        if( ( pC->uiVideoBitrate > 0)
4794            && (pRates->OutputVideoBitrate < minvideobitrate) )
4795        {
4796            pRates->OutputVideoBitrate = minvideobitrate;
4797        }
4798        /*+ New Encoder bitrates */
4799        if( pRates->OutputVideoBitrate > M4VIDEOEDITING_k8_MBPS )
4800        {
4801            pRates->OutputVideoBitrate = M4VIDEOEDITING_k8_MBPS;
4802        }
4803        /*- New Encoder bitrates */
4804    }
4805
4806    /* Check cut times are in correct range */
4807    if( ( pRates->BeginCutTime >= pC->InputFileProperties.uiClipDuration)
4808        || (( pRates->BeginCutTime >= pRates->EndCutTime)
4809        && (pRates->EndCutTime > 0)) )
4810    {
4811        pRates->BeginCutTime = 0;
4812        pRates->EndCutTime = 0;
4813    }
4814
4815    if( pRates->EndCutTime == 0 )
4816        calcduration =
4817        pC->InputFileProperties.uiClipDuration - pRates->BeginCutTime;
4818    else
4819        calcduration = pRates->EndCutTime - pRates->BeginCutTime;
4820
4821    /* priority 1 : max file size */
4822    if( pRates->OutputFileSize == 0 )
4823    {
4824        /* we can put maximum values for all undefined parameters */
4825        if( pRates->EndCutTime == 0 )
4826        {
4827            pRates->EndCutTime = pC->InputFileProperties.uiClipDuration;
4828        }
4829
4830        if( ( pRates->OutputAudioBitrate == M4VIDEOEDITING_kUndefinedBitrate)
4831            && (fixed_audio == M4OSA_FALSE) )
4832        {
4833            pRates->OutputAudioBitrate = M4VIDEOEDITING_k96_KBPS;
4834        }
4835
4836        if( ( pRates->OutputVideoBitrate == M4VIDEOEDITING_kUndefinedBitrate)
4837            && (fixed_video == M4OSA_FALSE) )
4838        {
4839            /*+ New Encoder bitrates */
4840            pRates->OutputVideoBitrate = M4VIDEOEDITING_k8_MBPS;
4841            /*- New Encoder bitrates */
4842        }
4843    }
4844    else
4845    {
4846        /* compute max duration */
4847        maxduration = (M4OSA_UInt32)(pRates->OutputFileSize
4848            / M4MCS_MOOV_OVER_FILESIZE_RATIO
4849            / (minvideobitrate + minaudiobitrate) * 8000.0);
4850
4851        if( maxduration
4852            + pRates->BeginCutTime > pC->InputFileProperties.uiClipDuration )
4853        {
4854            maxduration =
4855                pC->InputFileProperties.uiClipDuration - pRates->BeginCutTime;
4856        }
4857
4858        /* priority 2 : cut times */
4859        if( ( pRates->BeginCutTime > 0) || (pRates->EndCutTime > 0) )
4860        {
4861            if( calcduration > maxduration )
4862            {
4863                calcduration = maxduration;
4864            }
4865
4866            if( calcduration == 0 )
4867            {
4868                return M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT;
4869            }
4870
4871            maxcombinedbitrate = (M4OSA_UInt32)(pRates->OutputFileSize
4872                / M4MCS_MOOV_OVER_FILESIZE_RATIO / (calcduration / 8000.0));
4873
4874            /* audio and video bitrates */
4875            if( ( pRates->OutputAudioBitrate
4876                == M4VIDEOEDITING_kUndefinedBitrate)
4877                && (pRates->OutputVideoBitrate
4878                == M4VIDEOEDITING_kUndefinedBitrate) )
4879            {
4880                /* set audio = 1/3 and video = 2/3 */
4881                if( fixed_audio == M4OSA_FALSE )
4882                {
4883                    if( pC->novideo )
4884                        pRates->OutputAudioBitrate =
4885                        M4MCS_intGetNearestBitrate(maxcombinedbitrate, 0);
4886                    else
4887                        pRates->OutputAudioBitrate =
4888                        M4MCS_intGetNearestBitrate(maxcombinedbitrate / 3,
4889                        0);
4890
4891                    if( pRates->OutputAudioBitrate < minaudiobitrate )
4892                        pRates->OutputAudioBitrate = minaudiobitrate;
4893
4894                    if( pRates->OutputAudioBitrate > M4VIDEOEDITING_k96_KBPS )
4895                        pRates->OutputAudioBitrate = M4VIDEOEDITING_k96_KBPS;
4896                }
4897
4898                if( fixed_video == M4OSA_FALSE )
4899                {
4900                    pRates->OutputVideoBitrate =
4901                        M4MCS_intGetNearestBitrate(maxcombinedbitrate
4902                        - pRates->OutputAudioBitrate, 0);
4903
4904                    if( pRates->OutputVideoBitrate < minvideobitrate )
4905                        pRates->OutputVideoBitrate = minvideobitrate;
4906
4907                    if( pRates->OutputVideoBitrate > M4VIDEOEDITING_k8_MBPS )
4908                        pRates->OutputVideoBitrate =
4909                        M4VIDEOEDITING_k8_MBPS; /*+ New Encoder
4910                                                bitrates */
4911                }
4912            }
4913            else
4914            {
4915                /* priority 3 : audio bitrate */
4916                if( pRates->OutputAudioBitrate
4917                    != M4VIDEOEDITING_kUndefinedBitrate )
4918                {
4919                    while( ( fixed_audio == M4OSA_FALSE)
4920                        && (pRates->OutputAudioBitrate >= minaudiobitrate)
4921                        && (pRates->OutputAudioBitrate
4922                        + minvideobitrate > maxcombinedbitrate) )
4923                    {
4924                        pRates->OutputAudioBitrate =
4925                            M4MCS_intGetNearestBitrate(
4926                            pRates->OutputAudioBitrate, -1);
4927                    }
4928
4929                    if( ( fixed_audio == M4OSA_FALSE)
4930                        && (pRates->OutputAudioBitrate < minaudiobitrate) )
4931                    {
4932                        pRates->OutputAudioBitrate = minaudiobitrate;
4933                    }
4934
4935                    calcbitrate = M4MCS_intGetNearestBitrate(
4936                                    maxcombinedbitrate
4937                                    - pRates->OutputAudioBitrate, 0);
4938
4939                    if( calcbitrate < minvideobitrate )
4940                        calcbitrate = minvideobitrate;
4941
4942                    if( calcbitrate > M4VIDEOEDITING_k8_MBPS )
4943                        calcbitrate = M4VIDEOEDITING_k8_MBPS;
4944
4945                    if( ( fixed_video == M4OSA_FALSE)
4946                        && (( pRates->OutputVideoBitrate
4947                        == M4VIDEOEDITING_kUndefinedBitrate)
4948                        || (pRates->OutputVideoBitrate > calcbitrate)) )
4949                    {
4950                        pRates->OutputVideoBitrate = calcbitrate;
4951                    }
4952                }
4953                else
4954                {
4955                    /* priority 4 : video bitrate */
4956                    if( pRates->OutputVideoBitrate
4957                        != M4VIDEOEDITING_kUndefinedBitrate )
4958                    {
4959                        while( ( fixed_video == M4OSA_FALSE)
4960                            && (pRates->OutputVideoBitrate >= minvideobitrate)
4961                            && (pRates->OutputVideoBitrate
4962                            + minaudiobitrate > maxcombinedbitrate) )
4963                        {
4964                            pRates->OutputVideoBitrate =
4965                                M4MCS_intGetNearestBitrate(
4966                                pRates->OutputVideoBitrate, -1);
4967                        }
4968
4969                        if( ( fixed_video == M4OSA_FALSE)
4970                            && (pRates->OutputVideoBitrate < minvideobitrate) )
4971                        {
4972                            pRates->OutputVideoBitrate = minvideobitrate;
4973                        }
4974
4975                        calcbitrate =
4976                            M4MCS_intGetNearestBitrate(maxcombinedbitrate
4977                            - pRates->OutputVideoBitrate, 0);
4978
4979                        if( calcbitrate < minaudiobitrate )
4980                            calcbitrate = minaudiobitrate;
4981
4982                        if( calcbitrate > M4VIDEOEDITING_k96_KBPS )
4983                            calcbitrate = M4VIDEOEDITING_k96_KBPS;
4984
4985                        if( ( fixed_audio == M4OSA_FALSE)
4986                            && (( pRates->OutputAudioBitrate
4987                            == M4VIDEOEDITING_kUndefinedBitrate)
4988                            || (pRates->OutputAudioBitrate > calcbitrate)) )
4989                        {
4990                            pRates->OutputAudioBitrate = calcbitrate;
4991                        }
4992                    }
4993                }
4994            }
4995        }
4996        else
4997        {
4998            /* priority 3 : audio bitrate */
4999            if( pRates->OutputAudioBitrate != M4VIDEOEDITING_kUndefinedBitrate )
5000            {
5001                /* priority 4 : video bitrate */
5002                if( pRates->OutputVideoBitrate
5003                    != M4VIDEOEDITING_kUndefinedBitrate )
5004                {
5005                    /* compute max duration */
5006                    maxduration = (M4OSA_UInt32)(pRates->OutputFileSize
5007                        / M4MCS_MOOV_OVER_FILESIZE_RATIO
5008                        / (pRates->OutputVideoBitrate
5009                        + pRates->OutputAudioBitrate) * 8000.0);
5010
5011                    if( maxduration + pRates->BeginCutTime
5012                        > pC->InputFileProperties.uiClipDuration )
5013                    {
5014                        maxduration = pC->InputFileProperties.uiClipDuration
5015                            - pRates->BeginCutTime;
5016                    }
5017
5018                    if( calcduration > maxduration )
5019                    {
5020                        calcduration = maxduration;
5021                    }
5022
5023                    if( calcduration == 0 )
5024                    {
5025                        return M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT;
5026                    }
5027                }
5028                else
5029                {
5030                    /* start with min video bitrate */
5031                    pRates->OutputVideoBitrate = minvideobitrate;
5032
5033                    /* compute max duration */
5034                    maxduration = (M4OSA_UInt32)(pRates->OutputFileSize
5035                        / M4MCS_MOOV_OVER_FILESIZE_RATIO
5036                        / (pRates->OutputVideoBitrate
5037                        + pRates->OutputAudioBitrate) * 8000.0);
5038
5039                    if( maxduration + pRates->BeginCutTime
5040                        > pC->InputFileProperties.uiClipDuration )
5041                    {
5042                        maxduration = pC->InputFileProperties.uiClipDuration
5043                            - pRates->BeginCutTime;
5044                    }
5045
5046                    if( calcduration > maxduration )
5047                    {
5048                        calcduration = maxduration;
5049                    }
5050
5051                    if( calcduration == 0 )
5052                    {
5053                        return M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT;
5054                    }
5055
5056                    /* search max possible video bitrate */
5057                    maxcombinedbitrate = (M4OSA_UInt32)(pRates->OutputFileSize
5058                        / M4MCS_MOOV_OVER_FILESIZE_RATIO
5059                        / (calcduration / 8000.0));
5060
5061                    while( ( fixed_video == M4OSA_FALSE)
5062                        && (pRates->OutputVideoBitrate
5063                        < M4VIDEOEDITING_k8_MBPS) ) /*+ New Encoder bitrates */
5064                    {
5065                        calcbitrate = M4MCS_intGetNearestBitrate(
5066                            pRates->OutputVideoBitrate, +1);
5067
5068                        if( calcbitrate
5069                            + pRates->OutputAudioBitrate <= maxcombinedbitrate )
5070                            pRates->OutputVideoBitrate = calcbitrate;
5071                        else
5072                            break;
5073                    }
5074                }
5075            }
5076            else
5077            {
5078                /* priority 4 : video bitrate */
5079                if( pRates->OutputVideoBitrate
5080                    != M4VIDEOEDITING_kUndefinedBitrate )
5081                {
5082                    /* start with min audio bitrate */
5083                    pRates->OutputAudioBitrate = minaudiobitrate;
5084
5085                    /* compute max duration */
5086                    maxduration = (M4OSA_UInt32)(pRates->OutputFileSize
5087                        / M4MCS_MOOV_OVER_FILESIZE_RATIO
5088                        / (pRates->OutputVideoBitrate
5089                        + pRates->OutputAudioBitrate) * 8000.0);
5090
5091                    if( maxduration + pRates->BeginCutTime
5092                        > pC->InputFileProperties.uiClipDuration )
5093                    {
5094                        maxduration = pC->InputFileProperties.uiClipDuration
5095                            - pRates->BeginCutTime;
5096                    }
5097
5098                    if( calcduration > maxduration )
5099                    {
5100                        calcduration = maxduration;
5101                    }
5102
5103                    if( calcduration == 0 )
5104                    {
5105                        return M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT;
5106                    }
5107
5108                    /* search max possible audio bitrate */
5109                    maxcombinedbitrate = (M4OSA_UInt32)(pRates->OutputFileSize
5110                        / M4MCS_MOOV_OVER_FILESIZE_RATIO
5111                        / (calcduration / 8000.0));
5112
5113                    while( ( fixed_audio == M4OSA_FALSE)
5114                        && (pRates->OutputAudioBitrate
5115                        < M4VIDEOEDITING_k96_KBPS) )
5116                    {
5117                        calcbitrate = M4MCS_intGetNearestBitrate(
5118                            pRates->OutputAudioBitrate, +1);
5119
5120                        if( calcbitrate
5121                            + pRates->OutputVideoBitrate <= maxcombinedbitrate )
5122                            pRates->OutputAudioBitrate = calcbitrate;
5123                        else
5124                            break;
5125                    }
5126                }
5127                else
5128                {
5129                    /* compute max duration */
5130                    maxduration = (M4OSA_UInt32)(pRates->OutputFileSize
5131                        / M4MCS_MOOV_OVER_FILESIZE_RATIO
5132                        / (minvideobitrate + minaudiobitrate) * 8000.0);
5133
5134                    if( maxduration + pRates->BeginCutTime
5135                        > pC->InputFileProperties.uiClipDuration )
5136                    {
5137                        maxduration = pC->InputFileProperties.uiClipDuration
5138                            - pRates->BeginCutTime;
5139                    }
5140
5141                    if( calcduration > maxduration )
5142                    {
5143                        calcduration = maxduration;
5144                    }
5145
5146                    if( calcduration == 0 )
5147                    {
5148                        return M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT;
5149                    }
5150
5151                    /* set audio = 1/3 and video = 2/3 */
5152                    maxcombinedbitrate = (M4OSA_UInt32)(pRates->OutputFileSize
5153                        / M4MCS_MOOV_OVER_FILESIZE_RATIO
5154                        / (calcduration / 8000.0));
5155
5156                    if( fixed_audio == M4OSA_FALSE )
5157                    {
5158                        if( pC->novideo )
5159                            pRates->OutputAudioBitrate =
5160                            M4MCS_intGetNearestBitrate(maxcombinedbitrate,
5161                            0);
5162                        else
5163                            pRates->OutputAudioBitrate =
5164                            M4MCS_intGetNearestBitrate(maxcombinedbitrate
5165                            / 3, 0);
5166
5167                        if( pRates->OutputAudioBitrate < minaudiobitrate )
5168                            pRates->OutputAudioBitrate = minaudiobitrate;
5169
5170                        if( pRates->OutputAudioBitrate
5171                        > M4VIDEOEDITING_k96_KBPS )
5172                        pRates->OutputAudioBitrate =
5173                        M4VIDEOEDITING_k96_KBPS;
5174                    }
5175
5176                    if( fixed_video == M4OSA_FALSE )
5177                    {
5178                        pRates->OutputVideoBitrate =
5179                            M4MCS_intGetNearestBitrate(maxcombinedbitrate
5180                            - pRates->OutputAudioBitrate, 0);
5181
5182                        if( pRates->OutputVideoBitrate < minvideobitrate )
5183                            pRates->OutputVideoBitrate = minvideobitrate;
5184
5185                        if( pRates->OutputVideoBitrate
5186                        > M4VIDEOEDITING_k8_MBPS )
5187                        pRates->OutputVideoBitrate =
5188                        M4VIDEOEDITING_k8_MBPS; /*+ New Encoder
5189                                                bitrates */
5190                    }
5191                }
5192            }
5193        }
5194    }
5195
5196    /* recompute max duration with final bitrates */
5197    if( pRates->OutputFileSize > 0 )
5198    {
5199        maxduration = (M4OSA_UInt32)(pRates->OutputFileSize
5200            / M4MCS_MOOV_OVER_FILESIZE_RATIO
5201            / (pRates->OutputVideoBitrate + pRates->OutputAudioBitrate)
5202            * 8000.0);
5203    }
5204    else
5205    {
5206        maxduration = pC->InputFileProperties.uiClipDuration;
5207    }
5208
5209    if( maxduration
5210        + pRates->BeginCutTime > pC->InputFileProperties.uiClipDuration )
5211    {
5212        maxduration =
5213            pC->InputFileProperties.uiClipDuration - pRates->BeginCutTime;
5214    }
5215
5216    if( pRates->EndCutTime == 0 )
5217    {
5218        pRates->EndCutTime = pRates->BeginCutTime + maxduration;
5219    }
5220    else
5221    {
5222        calcduration = pRates->EndCutTime - pRates->BeginCutTime;
5223
5224        if( calcduration > maxduration )
5225        {
5226            pRates->EndCutTime = pRates->BeginCutTime + maxduration;
5227        }
5228    }
5229
5230    /* Should never happen : constraints are too strong */
5231    if( pRates->EndCutTime == pRates->BeginCutTime )
5232    {
5233        return M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT;
5234    }
5235
5236    /* estimated resulting file size */
5237    pRates->OutputFileSize = (M4OSA_UInt32)(M4MCS_MOOV_OVER_FILESIZE_RATIO
5238        * (pRates->OutputVideoBitrate + pRates->OutputAudioBitrate)
5239        * (( pRates->EndCutTime - pRates->BeginCutTime) / 8000.0));
5240
5241    return M4NO_ERROR;
5242}
5243
5244/**
5245 ******************************************************************************
5246 * M4OSA_ERR M4MCS_checkParamsAndStart(M4MCS_Context pContext)
5247 * @brief   Check parameters to start
5248 * @note
5249 * @param   pContext           (IN) MCS context
5250 * @return  M4NO_ERROR:         No error
5251 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (debug only)
5252 * @return  M4ERR_STATE:        MCS is not in an appropriate state for
5253 *                              this function to be called
5254 * @return  M4MCS_ERR_AUDIOBITRATE_TOO_HIGH:
5255 *                              Audio bitrate too high (we limit to 96 kbps)
5256 * @return  M4MCS_ERR_AUDIOBITRATE_TOO_LOW:
5257 *                              Audio bitrate is too low (16 kbps min for aac,
5258 *                              12.2 for amr, 8 for mp3)
5259 * @return  M4MCS_ERR_BEGIN_CUT_EQUALS_END_CUT:
5260 *                              Begin cut and End cut are equals
5261 * @return  M4MCS_ERR_BEGIN_CUT_LARGER_THAN_DURATION:
5262 *                              Begin cut time is larger than the input
5263 *                              clip duration
5264 * @return  M4MCS_ERR_END_CUT_SMALLER_THAN_BEGIN_CUT:
5265 *                              End cut time is smaller than begin cut time
5266 * @return  M4MCS_ERR_MAXFILESIZE_TOO_SMALL:
5267 *                              Not enough space to store whole output
5268 *                              file at given bitrates
5269 * @return  M4MCS_ERR_VIDEOBITRATE_TOO_HIGH:
5270 *                              Video bitrate too high (we limit to 800 kbps)
5271 * @return  M4MCS_ERR_VIDEOBITRATE_TOO_LOW:
5272 *                              Video bitrate too low
5273 ******************************************************************************
5274 */
5275M4OSA_ERR M4MCS_checkParamsAndStart( M4MCS_Context pContext )
5276{
5277    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
5278    M4MCS_EncodingParams VerifyRates;
5279    M4OSA_ERR err;
5280
5281    /**
5282    * Check input parameters */
5283    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
5284        "M4MCS_checkParamsAndStart: pContext is M4OSA_NULL");
5285
5286#ifdef M4MCS_SUPPORT_STILL_PICTURE
5287
5288    if( pC->m_bIsStillPicture )
5289    {
5290        /**
5291        * Call the corresponding still picture MCS function*/
5292        return M4MCS_stillPicCheckParamsAndStart(pC);
5293    }
5294
5295#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
5296
5297    /**
5298    * Check state automaton */
5299
5300    if( M4MCS_kState_SET != pC->State )
5301    {
5302        M4OSA_TRACE1_1(
5303            "M4MCS_checkParamsAndStart(): Wrong State (%d), returning M4ERR_STATE",
5304            pC->State);
5305        return M4ERR_STATE;
5306    }
5307
5308    /* Audio bitrate should not stay undefined at this point */
5309    if( ( pC->noaudio == M4OSA_FALSE)
5310        && (pC->AudioEncParams.Format != M4ENCODER_kAudioNULL)
5311        && (pC->uiAudioBitrate == M4VIDEOEDITING_kUndefinedBitrate) )
5312    {
5313        M4OSA_TRACE1_0("M4MCS_checkParamsAndStart : undefined audio bitrate");
5314        return M4MCS_ERR_AUDIOBITRATE_TOO_LOW;
5315    }
5316
5317    /* Video bitrate should not stay undefined at this point */
5318    if( ( pC->novideo == M4OSA_FALSE)
5319        && (pC->EncodingVideoFormat != M4ENCODER_kNULL)
5320        && (pC->uiVideoBitrate == M4VIDEOEDITING_kUndefinedBitrate) )
5321    {
5322        M4OSA_TRACE1_0("M4MCS_checkParamsAndStart : undefined video bitrate");
5323        return M4MCS_ERR_VIDEOBITRATE_TOO_LOW;
5324    }
5325
5326    /* Set end cut time if necessary (not an error) */
5327    if( pC->uiEndCutTime == 0 )
5328    {
5329        pC->uiEndCutTime = pC->InputFileProperties.uiClipDuration;
5330    }
5331
5332    /* Force a re-set to check validity of parameters */
5333    VerifyRates.OutputVideoBitrate = pC->uiVideoBitrate;
5334    VerifyRates.OutputAudioBitrate = pC->uiAudioBitrate;
5335    VerifyRates.BeginCutTime = pC->uiBeginCutTime;
5336    VerifyRates.EndCutTime = pC->uiEndCutTime;
5337    VerifyRates.OutputFileSize = pC->uiMaxFileSize;
5338    VerifyRates.OutputVideoTimescale = pC->outputVideoTimescale;
5339
5340    err = M4MCS_setEncodingParams(pContext, &VerifyRates);
5341
5342    /**
5343    * Check parameters consistency */
5344    if( err != M4NO_ERROR )
5345    {
5346        M4OSA_TRACE1_0("M4MCS_checkParamsAndStart : invalid parameter found");
5347        return err;
5348    }
5349
5350    /**
5351    * All is OK : update state automaton */
5352    pC->uiEncVideoBitrate = pC->uiVideoBitrate;
5353    pC->AudioEncParams.Bitrate = pC->uiAudioBitrate;
5354
5355#ifdef M4MCS_WITH_FAST_OPEN
5356    /**
5357    * Remake the open if it was done in fast mode */
5358
5359    if( M4OSA_TRUE == pC->bFileOpenedInFastMode )
5360    {
5361        /* Close the file opened in fast mode */
5362        M4MCS_intCleanUp_ReadersDecoders(pC);
5363
5364        pC->State = M4MCS_kState_CREATED;
5365
5366        /* Reopen it in normal mode */
5367        err = M4MCS_open(pContext, pC->pInputFile, pC->InputFileType,
5368            pC->pOutputFile, pC->pTemporaryFile);
5369
5370        if( err != M4NO_ERROR )
5371        {
5372            M4OSA_TRACE1_1(
5373                "M4MCS_checkParamsAndStart : M4MCS_Open returns 0x%x", err);
5374            return err;
5375        }
5376    }
5377
5378#endif /* M4MCS_WITH_FAST_OPEN */
5379
5380    pC->State = M4MCS_kState_READY;
5381
5382    return M4NO_ERROR;
5383}
5384
5385/**
5386 ******************************************************************************
5387 * M4OSA_ERR M4MCS_intStepSet(M4MCS_InternalContext* pC)
5388 ******************************************************************************
5389 */
5390static M4OSA_ERR M4MCS_intStepSet( M4MCS_InternalContext *pC )
5391{
5392    M4OSA_ERR err;
5393    M4ENCODER_Header *encHeader;
5394
5395    /**
5396    * Prepare the video decoder */
5397    err = M4MCS_intPrepareVideoDecoder(pC);
5398
5399    if( M4NO_ERROR != err )
5400    {
5401        M4OSA_TRACE1_1(
5402            "M4MCS_intStepSet(): M4MCS_intPrepareVideoDecoder() returns 0x%x",
5403            err);
5404        return err;
5405    }
5406
5407    if( ( pC->InputFileProperties.VideoStreamType == M4VIDEOEDITING_kH264)
5408        && (pC->EncodingVideoFormat == M4ENCODER_kNULL) )
5409    {
5410        pC->bH264Trim = M4OSA_TRUE;
5411    }
5412
5413    /**
5414    * Prepare the video encoder */
5415    err = M4MCS_intPrepareVideoEncoder(pC);
5416
5417    if( M4NO_ERROR != err )
5418    {
5419        M4OSA_TRACE1_1(
5420            "M4MCS_intStepSet(): M4MCS_intPrepareVideoEncoder() returns 0x%x",
5421            err);
5422        return err;
5423    }
5424
5425    if( ( pC->uiBeginCutTime != 0)
5426        && (pC->InputFileProperties.VideoStreamType == M4VIDEOEDITING_kH264)
5427        && (pC->EncodingVideoFormat == M4ENCODER_kNULL) )
5428    {
5429
5430        err = pC->pVideoEncoderGlobalFcts->pFctSetOption(pC->pViEncCtxt,
5431            M4ENCODER_kOptionID_H264ProcessNALUContext,
5432            (M4OSA_DataOption)pC->m_pInstance);
5433
5434        if( err != M4NO_ERROR )
5435        {
5436            M4OSA_TRACE1_1("M4MCS_intStetSet :pFctSetOption failed  (err 0x%x)",
5437                err);
5438            return err;
5439        }
5440
5441        err = pC->pVideoEncoderGlobalFcts->pFctSetOption(pC->pViEncCtxt,
5442            M4ENCODER_kOptionID_SetH264ProcessNALUfctsPtr,
5443            (M4OSA_DataOption) &H264MCS_ProcessEncodedNALU);
5444
5445        if( err != M4NO_ERROR )
5446        {
5447            M4OSA_TRACE1_1("M4MCS_intStetSet :pFctSetOption failed  (err 0x%x)",
5448                err);
5449            return err;
5450        }
5451
5452        err = pC->pVideoEncoderGlobalFcts->pFctGetOption(pC->pViEncCtxt,
5453            M4ENCODER_kOptionID_EncoderHeader,
5454            (M4OSA_DataOption) &encHeader);
5455
5456        if( ( M4NO_ERROR != err) || (M4OSA_NULL == encHeader->pBuf) )
5457        {
5458            M4OSA_TRACE1_1(
5459                "M4MCS_close: failed to get the encoder header (err 0x%x)",
5460                err);
5461            /**< no return here, we still have stuff to deallocate after close, even if it fails.*/
5462        }
5463        else
5464        {
5465            // Handle DSI first bits
5466#define SPS_START_POS 6
5467
5468            pC->m_pInstance->m_encoderSPSSize =
5469                ( encHeader->pBuf[SPS_START_POS] << 8)
5470                + encHeader->pBuf[SPS_START_POS + 1];
5471            pC->m_pInstance->m_pEncoderSPS =
5472                (M4OSA_UInt8 *)(encHeader->pBuf) + SPS_START_POS + 2;
5473
5474            pC->m_pInstance->m_encoderPPSSize =
5475                ( encHeader->pBuf[SPS_START_POS + 3
5476                + pC->m_pInstance->m_encoderSPSSize] << 8)
5477                + encHeader->pBuf[SPS_START_POS + 4
5478                + pC->m_pInstance->m_encoderSPSSize];
5479            pC->m_pInstance->m_pEncoderPPS = (M4OSA_UInt8 *)encHeader->pBuf + SPS_START_POS + 5
5480                + pC->m_pInstance->m_encoderSPSSize;
5481
5482            /* Check the DSI integrity */
5483            if( encHeader->Size != (pC->m_pInstance->m_encoderSPSSize
5484                + pC->m_pInstance->m_encoderPPSSize + 5 + SPS_START_POS) )
5485            {
5486                M4OSA_TRACE1_3(
5487                    "!!! M4MCS_intStepSet ERROR : invalid SPS / PPS %d %d %d",
5488                    encHeader->Size, pC->m_pInstance->m_encoderSPSSize,
5489                    pC->m_pInstance->m_encoderPPSSize);
5490                return M4ERR_PARAMETER;
5491            }
5492        }
5493    }
5494
5495    /**
5496    * Prepare audio processing */
5497    err = M4MCS_intPrepareAudioProcessing(pC);
5498
5499    if( M4NO_ERROR != err )
5500    {
5501        M4OSA_TRACE1_1(
5502            "M4MCS_intStepSet(): M4MCS_intPrepareAudioProcessing() returns 0x%x",
5503            err);
5504        return err;
5505    }
5506
5507    /**
5508    * Prepare the writer */
5509    err = M4MCS_intPrepareWriter(pC);
5510
5511    if( M4NO_ERROR != err )
5512    {
5513        M4OSA_TRACE1_1(
5514            "M4MCS_intStepSet(): M4MCS_intPrepareWriter() returns 0x%x", err);
5515        return err;
5516    }
5517
5518    /**
5519    * Jump the audio stream to the begin cut time (all AUs are RAP)
5520    * Must be done after the 3gpp writer init, because it may write the first
5521    * audio AU in some cases */
5522    err = M4MCS_intPrepareAudioBeginCut(pC);
5523
5524    if( M4NO_ERROR != err )
5525    {
5526        M4OSA_TRACE1_1(
5527            "M4MCS_intStepSet(): M4MCS_intPrepareAudioBeginCut() returns 0x%x",
5528            err);
5529        return err;
5530    }
5531
5532    /**
5533    * Update state automaton */
5534    if( 0 == pC->uiBeginCutTime )
5535    {
5536        pC->dViDecStartingCts = 0.0;
5537        /**
5538        * No begin cut, do the encoding */
5539        pC->State = M4MCS_kState_PROCESSING;
5540    }
5541    else
5542    {
5543        /**
5544        * Remember that we must start the decode/encode process at the begin cut time */
5545        pC->dViDecStartingCts = (M4OSA_Double)pC->uiBeginCutTime;
5546
5547        /**
5548        * Jumping */
5549        pC->State = M4MCS_kState_BEGINVIDEOJUMP;
5550    }
5551
5552    /**
5553    * Return with no error */
5554    M4OSA_TRACE3_0("M4MCS_intStepSet(): returning M4NO_ERROR");
5555    return M4NO_ERROR;
5556}
5557
5558/**
5559 ******************************************************************************
5560 * M4OSA_ERR M4MCS_intPrepareVideoDecoder(M4MCS_InternalContext* pC);
5561 * @brief    Prepare the video decoder.
5562 * @param    pC          (IN) MCS private context
5563 * @return   M4NO_ERROR  No error
5564 * @return   M4MCS_ERR_H263_PROFILE_NOT_SUPPORTED
5565 * @return   Any error returned by an underlaying module
5566 ******************************************************************************
5567 */
5568static M4OSA_ERR M4MCS_intPrepareVideoDecoder( M4MCS_InternalContext *pC )
5569{
5570    M4OSA_ERR err;
5571    M4OSA_Void *decoderUserData;
5572    M4DECODER_OutputFilter FilterOption;
5573
5574    if( pC->novideo )
5575        return M4NO_ERROR;
5576
5577    /**
5578    * Create the decoder, if it has not been created yet (to get video properties for example) */
5579    if( M4OSA_NULL == pC->pViDecCtxt )
5580    {
5581#ifdef M4VSS_ENABLE_EXTERNAL_DECODERS
5582
5583        decoderUserData = pC->m_pCurrentVideoDecoderUserData;
5584
5585#else
5586
5587        decoderUserData = M4OSA_NULL;
5588
5589#endif /* M4VSS_ENABLE_EXTERNAL_DECODERS ? */
5590
5591        err = pC->m_pVideoDecoder->m_pFctCreate(&pC->pViDecCtxt,
5592            &pC->pReaderVideoStream->m_basicProperties, pC->m_pReaderDataIt,
5593            &pC->ReaderVideoAU, decoderUserData);
5594
5595        if( (M4OSA_UInt32)(M4ERR_DECODER_H263_PROFILE_NOT_SUPPORTED) == err )
5596        {
5597            /**
5598            * Our decoder is not compatible with H263 profile other than 0.
5599            * So it returns this internal error code.
5600            * We translate it to our own error code */
5601            M4OSA_TRACE1_0("M4MCS_intPrepareVideoDecoder:\
5602                           returning M4MCS_ERR_H263_PROFILE_NOT_SUPPORTED");
5603            return M4MCS_ERR_H263_PROFILE_NOT_SUPPORTED;
5604        }
5605        else if( M4NO_ERROR != err )
5606        {
5607            M4OSA_TRACE1_1("M4MCS_intPrepareVideoDecoder:\
5608                           m_pVideoDecoder->m_pFctCreate returns 0x%x", err);
5609            return err;
5610        }
5611
5612        if( M4VIDEOEDITING_kH264 == pC->InputFileProperties.VideoStreamType )
5613        {
5614            FilterOption.m_pFilterFunction =
5615                (M4OSA_Void *) &M4VIFI_ResizeBilinearYUV420toYUV420;
5616            FilterOption.m_pFilterUserData = M4OSA_NULL;
5617            err = pC->m_pVideoDecoder->m_pFctSetOption(pC->pViDecCtxt,
5618                M4DECODER_kOptionID_OutputFilter,
5619                (M4OSA_DataOption) &FilterOption);
5620
5621            if( M4NO_ERROR != err )
5622            {
5623                M4OSA_TRACE1_1("M4MCS_intPrepareVideoDecoder:\
5624                               m_pVideoDecoder->m_pFctSetOption returns 0x%x", err);
5625                return err;
5626            }
5627        }
5628    }
5629
5630    /**
5631    * Return with no error */
5632    M4OSA_TRACE3_0("M4MCS_intPrepareVideoDecoder(): returning M4NO_ERROR");
5633    return M4NO_ERROR;
5634}
5635
5636/**
5637 ******************************************************************************
5638 * M4OSA_ERR M4MCS_intPrepareVideoEncoder(M4MCS_InternalContext* pC);
5639 * @brief    Prepare the video encoder.
5640 * @param    pC          (IN) MCS private context
5641 * @return   M4NO_ERROR  No error
5642 * @return   Any error returned by an underlaying module
5643 ******************************************************************************
5644 */
5645static M4OSA_ERR M4MCS_intPrepareVideoEncoder( M4MCS_InternalContext *pC )
5646{
5647    M4OSA_ERR err;
5648    M4ENCODER_AdvancedParams EncParams; /**< Encoder advanced parameters */
5649    M4ENCODER_Params EncParams1;
5650    M4OSA_Double dFrameRate;            /**< tmp variable */
5651
5652    if( pC->novideo )
5653        return M4NO_ERROR;
5654
5655    if( pC->EncodingVideoFormat == M4ENCODER_kNULL )
5656    {
5657        /* Approximative cts increment */
5658        pC->dCtsIncrement = 1000.0 / pC->pReaderVideoStream->m_averageFrameRate;
5659
5660        if( pC->uiBeginCutTime == 0 )
5661        {
5662            M4OSA_TRACE3_0(
5663                "M4MCS_intPrepareVideoEncoder(): Null encoding, do nothing.");
5664            return M4NO_ERROR;
5665        }
5666        else
5667        {
5668            M4OSA_TRACE3_0(
5669                "M4MCS_intPrepareVideoEncoder(): Null encoding, I-frame defaults.");
5670
5671            /* Set useful parameters to encode the first I-frame */
5672            EncParams.InputFormat = M4ENCODER_kIYUV420;
5673
5674            switch( pC->InputFileProperties.VideoStreamType )
5675            {
5676                case M4VIDEOEDITING_kH263:
5677                    EncParams.Format = M4ENCODER_kH263;
5678                    break;
5679
5680                case M4VIDEOEDITING_kMPEG4:
5681                case M4VIDEOEDITING_kMPEG4_EMP:
5682                    EncParams.Format = M4ENCODER_kMPEG4;
5683                    break;
5684
5685                case M4VIDEOEDITING_kH264:
5686                    EncParams.Format = M4ENCODER_kH264;
5687                    break;
5688
5689                default:
5690                    M4OSA_TRACE1_1("M4MCS_intPrepareVideoEncoder: unknown encoding video format\
5691                                   (%d), returning M4MCS_WAR_MEDIATYPE_NOT_SUPPORTED",
5692                                   pC->InputFileProperties.VideoStreamType);
5693                    return M4MCS_WAR_MEDIATYPE_NOT_SUPPORTED;
5694            }
5695
5696            EncParams.FrameWidth = pC->EncodingWidth;
5697            EncParams.FrameHeight = pC->EncodingHeight;
5698            EncParams.Bitrate = pC->uiEncVideoBitrate;
5699            EncParams.bInternalRegulation =
5700                M4OSA_FALSE; /* do not constrain the I-frame */
5701            EncParams.FrameRate = pC->EncodingVideoFramerate;
5702
5703            /* Other encoding settings (quite all dummy...) */
5704            EncParams.uiHorizontalSearchRange = 0;    /* use default */
5705            EncParams.uiVerticalSearchRange = 0;      /* use default */
5706            EncParams.bErrorResilience = M4OSA_FALSE; /* no error resilience */
5707            EncParams.uiIVopPeriod = 0;               /* use default */
5708            EncParams.uiMotionEstimationTools =
5709                0; /* M4V_MOTION_EST_TOOLS_ALL */
5710            EncParams.bAcPrediction = M4OSA_TRUE;     /* use AC prediction */
5711            EncParams.uiStartingQuantizerValue = 5;   /* initial QP = 5 */
5712            EncParams.bDataPartitioning =
5713                M4OSA_FALSE; /* no data partitioning */
5714
5715            /* Rate factor */
5716            EncParams.uiTimeScale = pC->InputFileProperties.uiVideoTimeScale;
5717            EncParams.uiRateFactor = 1;
5718        }
5719    }
5720    else
5721    {
5722        M4OSA_TRACE3_0(
5723            "M4MCS_intPrepareVideoEncoder(): Normal encoding, set full config.");
5724
5725        /**
5726        * Set encoder shell parameters according to MCS settings */
5727        EncParams.Format = pC->EncodingVideoFormat;
5728        EncParams.InputFormat = M4ENCODER_kIYUV420;
5729
5730        /**
5731        * Video frame size */
5732        EncParams.FrameWidth = pC->EncodingWidth;
5733        EncParams.FrameHeight = pC->EncodingHeight;
5734
5735        /**
5736        * Video bitrate has been previously computed */
5737        EncParams.Bitrate = pC->uiEncVideoBitrate;
5738
5739        /**
5740        * MCS use the "true" core internal bitrate regulation */
5741        EncParams.bInternalRegulation = M4OSA_TRUE;
5742
5743        /**
5744        * Other encoder settings */
5745        if( M4OSA_TRUE == pC->bActivateEmp )
5746        {
5747            EncParams.uiHorizontalSearchRange = 15;   /* set value */
5748            EncParams.uiVerticalSearchRange = 15;     /* set value */
5749            EncParams.bErrorResilience = M4OSA_FALSE; /* no error resilience */
5750            EncParams.uiIVopPeriod = 15; /* one I frame every 15 frames */
5751            EncParams.uiMotionEstimationTools =
5752                1; /* M4V_MOTION_EST_TOOLS_NO_4MV */
5753            EncParams.bAcPrediction = M4OSA_FALSE;    /* no AC prediction */
5754            EncParams.uiStartingQuantizerValue = 10;  /* initial QP = 10 */
5755            EncParams.bDataPartitioning =
5756                M4OSA_FALSE; /* no data partitioning */
5757        }
5758        else
5759        {
5760            EncParams.uiHorizontalSearchRange = 0;    /* use default */
5761            EncParams.uiVerticalSearchRange = 0;      /* use default */
5762            EncParams.bErrorResilience = M4OSA_FALSE; /* no error resilience */
5763            EncParams.uiIVopPeriod = 0;               /* use default */
5764            EncParams.uiMotionEstimationTools =
5765                0; /* M4V_MOTION_EST_TOOLS_ALL */
5766            EncParams.bAcPrediction = M4OSA_TRUE;     /* use AC prediction */
5767            EncParams.uiStartingQuantizerValue = 10;  /* initial QP = 10 */
5768            EncParams.bDataPartitioning =
5769                M4OSA_FALSE; /* no data partitioning */
5770        }
5771
5772        /**
5773        * Video encoder frame rate and rate factor */
5774        EncParams.FrameRate = pC->EncodingVideoFramerate;
5775        EncParams.uiTimeScale = pC->outputVideoTimescale;
5776
5777        switch( pC->EncodingVideoFramerate )
5778        {
5779            case M4ENCODER_k5_FPS:
5780                dFrameRate = 5.0;
5781                break;
5782
5783            case M4ENCODER_k7_5_FPS:
5784                dFrameRate = 7.5;
5785                break;
5786
5787            case M4ENCODER_k10_FPS:
5788                dFrameRate = 10.0;
5789                break;
5790
5791            case M4ENCODER_k12_5_FPS:
5792                dFrameRate = 12.5;
5793                break;
5794
5795            case M4ENCODER_k15_FPS:
5796                dFrameRate = 15.0;
5797                break;
5798
5799            case M4ENCODER_k20_FPS: /**< MPEG-4 only */
5800                dFrameRate = 20.0;
5801                break;
5802
5803            case M4ENCODER_k25_FPS: /**< MPEG-4 only */
5804                dFrameRate = 25.0;
5805                break;
5806
5807            case M4ENCODER_k30_FPS:
5808                dFrameRate = 30.0;
5809                break;
5810
5811            default:
5812                M4OSA_TRACE1_1(
5813                    "M4MCS_intPrepareVideoEncoder: unknown encoding video frame rate\
5814                    (0x%x), returning M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FRAME_RATE",
5815                    pC->EncodingVideoFramerate);
5816                return M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FRAME_RATE;
5817        }
5818
5819        /**
5820        * Compute the number of milliseconds between two frames */
5821        if( M4ENCODER_kH263 == EncParams.Format )
5822        {
5823            pC->dCtsIncrement = 1001.0 / dFrameRate;
5824        }
5825        else /**< MPEG4 or H.264 */
5826        {
5827            pC->dCtsIncrement = 1000.0 / dFrameRate;
5828        }
5829    }
5830
5831    /**
5832    * Create video encoder */
5833    err = pC->pVideoEncoderGlobalFcts->pFctInit(&pC->pViEncCtxt,
5834        pC->pWriterDataFcts, \
5835        M4MCS_intApplyVPP, pC, pC->pCurrentVideoEncoderExternalAPI, \
5836        pC->pCurrentVideoEncoderUserData);
5837
5838    /**< We put the MCS context in place of the VPP context */
5839    if( M4NO_ERROR != err )
5840    {
5841        M4OSA_TRACE1_1(
5842            "M4MCS_intPrepareVideoEncoder: EncoderInt->pFctInit returns 0x%x",
5843            err);
5844        return err;
5845    }
5846
5847    pC->encoderState = M4MCS_kEncoderClosed;
5848
5849    if( M4OSA_TRUE == pC->bH264Trim )
5850        //if((M4ENCODER_kNULL == pC->EncodingVideoFormat)
5851        //    && (M4VIDEOEDITING_kH264 == pC->InputFileProperties.VideoStreamType))
5852    {
5853        EncParams1.InputFormat = EncParams.InputFormat;
5854        //EncParams1.InputFrameWidth = EncParams.InputFrameWidth;
5855        //EncParams1.InputFrameHeight = EncParams.InputFrameHeight;
5856        EncParams1.FrameWidth = EncParams.FrameWidth;
5857        EncParams1.FrameHeight = EncParams.FrameHeight;
5858        EncParams1.Bitrate = EncParams.Bitrate;
5859        EncParams1.FrameRate = EncParams.FrameRate;
5860        EncParams1.Format = M4ENCODER_kH264; //EncParams.Format;
5861
5862        err = pC->pVideoEncoderGlobalFcts->pFctOpen(pC->pViEncCtxt,
5863            &pC->WriterVideoAU, &EncParams1);
5864    }
5865    else
5866    {
5867        err = pC->pVideoEncoderGlobalFcts->pFctOpen(pC->pViEncCtxt,
5868            &pC->WriterVideoAU, &EncParams);
5869    }
5870
5871    if( M4NO_ERROR != err )
5872    {
5873        M4OSA_TRACE1_1(
5874            "M4MCS_intPrepareVideoEncoder: EncoderInt->pFctOpen returns 0x%x",
5875            err);
5876        return err;
5877    }
5878
5879    pC->encoderState = M4MCS_kEncoderStopped;
5880
5881    if( M4OSA_NULL != pC->pVideoEncoderGlobalFcts->pFctStart )
5882    {
5883        err = pC->pVideoEncoderGlobalFcts->pFctStart(pC->pViEncCtxt);
5884
5885        if( M4NO_ERROR != err )
5886        {
5887            M4OSA_TRACE1_1(
5888                "M4MCS_intPrepareVideoEncoder: EncoderInt->pFctStart returns 0x%x",
5889                err);
5890            return err;
5891        }
5892    }
5893
5894    pC->encoderState = M4MCS_kEncoderRunning;
5895
5896    /******************************/
5897    /* Video resize management    */
5898    /******************************/
5899    /**
5900    * Compare video input size and video output size to check if resize is needed */
5901    if( ( (M4OSA_UInt32)EncParams.FrameWidth
5902        != pC->pReaderVideoStream->m_videoWidth)
5903        || ((M4OSA_UInt32)EncParams.FrameHeight
5904        != pC->pReaderVideoStream->m_videoHeight) )
5905    {
5906        /**
5907        * Allocate the intermediate video plane that will receive the decoded image before
5908         resizing */
5909        pC->pPreResizeFrame =
5910            (M4VIFI_ImagePlane *)M4OSA_malloc(3 * sizeof(M4VIFI_ImagePlane),
5911            M4MCS, (M4OSA_Char *)"m_pPreResizeFrame");
5912
5913        if( M4OSA_NULL == pC->pPreResizeFrame )
5914        {
5915            M4OSA_TRACE1_0("M4MCS_intPrepareVideoEncoder():\
5916                           unable to allocate m_pPreResizeFrame, returning M4ERR_ALLOC");
5917            return M4ERR_ALLOC;
5918        }
5919
5920        pC->pPreResizeFrame[0].pac_data = M4OSA_NULL;
5921        pC->pPreResizeFrame[1].pac_data = M4OSA_NULL;
5922        pC->pPreResizeFrame[2].pac_data = M4OSA_NULL;
5923
5924        /**
5925        * Allocate the Y plane */
5926        pC->pPreResizeFrame[0].u_topleft = 0;
5927        pC->pPreResizeFrame[0].u_width = pC->pReaderVideoStream->
5928            m_videoWidth; /**< input width */
5929        pC->pPreResizeFrame[0].u_height = pC->pReaderVideoStream->
5930            m_videoHeight; /**< input height */
5931        pC->pPreResizeFrame[0].u_stride = pC->
5932            pPreResizeFrame[0].u_width; /**< simple case: stride equals width */
5933
5934        pC->pPreResizeFrame[0].pac_data =
5935            (M4VIFI_UInt8 *)M4OSA_malloc(pC->pPreResizeFrame[0].u_stride \
5936            *pC->pPreResizeFrame[0].u_height, M4MCS,
5937            (M4OSA_Char *)"m_pPreResizeFrame[0].pac_data");
5938
5939        if( M4OSA_NULL == pC->pPreResizeFrame[0].pac_data )
5940        {
5941            M4OSA_TRACE1_0(
5942                "M4MCS_intPrepareVideoEncoder():\
5943                     unable to allocate m_pPreResizeFrame[0].pac_data, returning M4ERR_ALLOC");
5944            return M4ERR_ALLOC;
5945        }
5946
5947        /**
5948        * Allocate the U plane */
5949        pC->pPreResizeFrame[1].u_topleft = 0;
5950        pC->pPreResizeFrame[1].u_width = pC->pPreResizeFrame[0].u_width
5951            >> 1; /**< U width is half the Y width */
5952        pC->pPreResizeFrame[1].u_height = pC->pPreResizeFrame[0].u_height
5953            >> 1; /**< U height is half the Y height */
5954        pC->pPreResizeFrame[1].u_stride = pC->
5955            pPreResizeFrame[1].u_width; /**< simple case: stride equals width */
5956
5957        pC->pPreResizeFrame[1].pac_data =
5958            (M4VIFI_UInt8 *)M4OSA_malloc(pC->pPreResizeFrame[1].u_stride \
5959            *pC->pPreResizeFrame[1].u_height, M4MCS,
5960            (M4OSA_Char *)"m_pPreResizeFrame[1].pac_data");
5961
5962        if( M4OSA_NULL == pC->pPreResizeFrame[1].pac_data )
5963        {
5964            M4OSA_TRACE1_0(
5965                "M4MCS_intPrepareVideoEncoder():\
5966                 unable to allocate m_pPreResizeFrame[1].pac_data, returning M4ERR_ALLOC");
5967            return M4ERR_ALLOC;
5968        }
5969
5970        /**
5971        * Allocate the V plane */
5972        pC->pPreResizeFrame[2].u_topleft = 0;
5973        pC->pPreResizeFrame[2].u_width = pC->
5974            pPreResizeFrame[1].u_width; /**< V width equals U width */
5975        pC->pPreResizeFrame[2].u_height = pC->
5976            pPreResizeFrame[1].u_height; /**< V height equals U height */
5977        pC->pPreResizeFrame[2].u_stride = pC->
5978            pPreResizeFrame[2].u_width; /**< simple case: stride equals width */
5979
5980        pC->pPreResizeFrame[2].pac_data =
5981            (M4VIFI_UInt8 *)M4OSA_malloc(pC->pPreResizeFrame[2].u_stride \
5982            *pC->pPreResizeFrame[2].u_height, M4MCS,
5983            (M4OSA_Char *)"m_pPreResizeFrame[1].pac_data");
5984
5985        if( M4OSA_NULL == pC->pPreResizeFrame[2].pac_data )
5986        {
5987            M4OSA_TRACE1_0(
5988                "M4MCS_intPrepareVideoEncoder():\
5989                 unable to allocate m_pPreResizeFrame[2].pac_data, returning M4ERR_ALLOC");
5990            return M4ERR_ALLOC;
5991        }
5992    }
5993
5994    /**
5995    * Return with no error */
5996    M4OSA_TRACE3_0("M4MCS_intPrepareVideoEncoder(): returning M4NO_ERROR");
5997    return M4NO_ERROR;
5998}
5999
6000/**
6001 ******************************************************************************
6002 * M4OSA_ERR M4MCS_intPrepareAudioProcessing(M4MCS_InternalContext* pC);
6003 * @brief    Prepare the AAC decoder, the SRC and the AMR-NB encoder and the MP3 encoder.
6004 * @param    pC          (IN) MCS private context
6005 * @return   M4NO_ERROR  No error
6006 * @return   Any error returned by an underlaying module
6007 ******************************************************************************
6008 */
6009static M4OSA_ERR M4MCS_intPrepareAudioProcessing( M4MCS_InternalContext *pC )
6010{
6011    M4OSA_ERR err;
6012
6013    SSRC_ReturnStatus_en
6014        ReturnStatus; /* Function return status                       */
6015    LVM_INT16 NrSamplesMin =
6016        0; /* Minimal number of samples on the input or on the output */
6017    LVM_INT32 ScratchSize; /* The size of the scratch memory               */
6018    LVM_INT16
6019        *pInputInScratch; /* Pointer to input in the scratch buffer       */
6020    LVM_INT16
6021        *pOutputInScratch; /* Pointer to the output in the scratch buffer  */
6022    SSRC_Params_t ssrcParams;          /* Memory for init parameters                    */
6023
6024#ifdef MCS_DUMP_PCM_TO_FILE
6025
6026    file_au_reader = fopen("mcs_ReaderOutput.raw", "wb");
6027    file_pcm_decoder = fopen("mcs_DecoderOutput.pcm", "wb");
6028    file_pcm_encoder = fopen("mcs_EncoderInput.pcm", "wb");
6029
6030#endif
6031
6032    if( pC->noaudio )
6033        return M4NO_ERROR;
6034
6035    if( pC->AudioEncParams.Format == M4ENCODER_kAudioNULL )
6036    {
6037        M4OSA_TRACE3_0(
6038            "M4MCS_intPrepareAudioProcessing(): Null encoding, do nothing.");
6039        return M4NO_ERROR;
6040    }
6041
6042    /* ________________________________ */
6043    /*|                                |*/
6044    /*| Create and "start" the decoder |*/
6045    /*|________________________________|*/
6046
6047    if( M4OSA_NULL == pC->m_pAudioDecoder )
6048    {
6049        M4OSA_TRACE1_0(
6050            "M4MCS_intPrepareAudioProcessing(): Fails to initiate the audio decoder.");
6051        return M4MCS_ERR_AUDIO_CONVERSION_FAILED;
6052    }
6053
6054    if( M4OSA_NULL == pC->pAudioDecCtxt )
6055    {
6056        err = pC->m_pAudioDecoder->m_pFctCreateAudioDec(&pC->pAudioDecCtxt,
6057            pC->pReaderAudioStream, pC->m_pCurrentAudioDecoderUserData);
6058
6059        if( M4NO_ERROR != err )
6060        {
6061            M4OSA_TRACE1_1(
6062                "M4MCS_intPrepareVideoDecoder: m_pAudioDecoder->m_pFctCreateAudioDec returns 0x%x",
6063                err);
6064            return err;
6065        }
6066    }
6067
6068    if( M4VIDEOEDITING_kAMR_NB == pC->InputFileProperties.AudioStreamType ) {
6069        /* AMR DECODER CONFIGURATION */
6070
6071        /* nothing specific to do */
6072    }
6073    else if( M4VIDEOEDITING_kEVRC == pC->InputFileProperties.AudioStreamType ) {
6074        /* EVRC DECODER CONFIGURATION */
6075
6076        /* nothing specific to do */
6077    }
6078    else if( M4VIDEOEDITING_kMP3 == pC->InputFileProperties.AudioStreamType ) {
6079        /* MP3 DECODER CONFIGURATION */
6080
6081        /* nothing specific to do */
6082    }
6083    else
6084    {
6085        /* AAC DECODER CONFIGURATION */
6086        M4_AacDecoderConfig AacDecParam;
6087
6088        AacDecParam.m_AACDecoderProfile = AAC_kAAC;
6089        AacDecParam.m_DownSamplingMode = AAC_kDS_OFF;
6090
6091        if( pC->AudioEncParams.Format == M4ENCODER_kAMRNB )
6092        {
6093            AacDecParam.m_OutputMode = AAC_kMono;
6094        }
6095        else
6096        {
6097            /* For this version, we encode only in AAC */
6098            if( M4ENCODER_kMono == pC->AudioEncParams.ChannelNum )
6099            {
6100                AacDecParam.m_OutputMode = AAC_kMono;
6101            }
6102            else
6103            {
6104                AacDecParam.m_OutputMode = AAC_kStereo;
6105            }
6106        }
6107
6108        pC->m_pAudioDecoder->m_pFctSetOptionAudioDec(pC->pAudioDecCtxt,
6109            M4AD_kOptionID_UserParam, (M4OSA_DataOption) &AacDecParam);
6110    }
6111
6112    if( pC->m_pAudioDecoder->m_pFctStartAudioDec != M4OSA_NULL )
6113    {
6114        /* Not implemented in all decoders */
6115        err = pC->m_pAudioDecoder->m_pFctStartAudioDec(pC->pAudioDecCtxt);
6116
6117        if( M4NO_ERROR != err )
6118        {
6119            M4OSA_TRACE1_1(
6120                "M4MCS_intPrepareVideoDecoder: m_pAudioDecoder->m_pFctStartAudioDec returns 0x%x",
6121                err);
6122            return err;
6123        }
6124    }
6125
6126    /**
6127    * Allocate output buffer for the audio decoder */
6128    pC->InputFileProperties.uiDecodedPcmSize =
6129        pC->pReaderAudioStream->m_byteFrameLength
6130        * pC->pReaderAudioStream->m_byteSampleSize
6131        * pC->pReaderAudioStream->m_nbChannels;
6132
6133    if( pC->InputFileProperties.uiDecodedPcmSize > 0 )
6134    {
6135        pC->AudioDecBufferOut.m_bufferSize =
6136            pC->InputFileProperties.uiDecodedPcmSize;
6137        pC->AudioDecBufferOut.m_dataAddress =
6138            (M4OSA_MemAddr8)M4OSA_malloc(pC->AudioDecBufferOut.m_bufferSize \
6139            *sizeof(short), M4MCS, (M4OSA_Char *)"AudioDecBufferOut.m_bufferSize");
6140    }
6141
6142    if( M4OSA_NULL == pC->AudioDecBufferOut.m_dataAddress )
6143    {
6144        M4OSA_TRACE1_0(
6145            "M4MCS_intPrepareVideoDecoder():\
6146             unable to allocate AudioDecBufferOut.m_dataAddress, returning M4ERR_ALLOC");
6147        return M4ERR_ALLOC;
6148    }
6149
6150    /* _________________________ */
6151    /*|                         |*/
6152    /*| Set the SSRC parameters |*/
6153    /*|_________________________|*/
6154
6155    switch( pC->pReaderAudioStream->m_samplingFrequency )
6156    {
6157        case 8000:
6158            ssrcParams.SSRC_Fs_In = LVM_FS_8000;
6159            break;
6160
6161        case 11025:
6162            ssrcParams.SSRC_Fs_In = LVM_FS_11025;
6163            break;
6164
6165        case 12000:
6166            ssrcParams.SSRC_Fs_In = LVM_FS_12000;
6167            break;
6168
6169        case 16000:
6170            ssrcParams.SSRC_Fs_In = LVM_FS_16000;
6171            break;
6172
6173        case 22050:
6174            ssrcParams.SSRC_Fs_In = LVM_FS_22050;
6175            break;
6176
6177        case 24000:
6178            ssrcParams.SSRC_Fs_In = LVM_FS_24000;
6179            break;
6180
6181        case 32000:
6182            ssrcParams.SSRC_Fs_In = LVM_FS_32000;
6183            break;
6184
6185        case 44100:
6186            ssrcParams.SSRC_Fs_In = LVM_FS_44100;
6187            break;
6188
6189        case 48000:
6190            ssrcParams.SSRC_Fs_In = LVM_FS_48000;
6191            break;
6192
6193        default:
6194            M4OSA_TRACE1_1(
6195                "M4MCS_intPrepareVideoDecoder: invalid input AAC sampling frequency (%d Hz),\
6196                 returning M4MCS_ERR_INVALID_AAC_SAMPLING_FREQUENCY",
6197                pC->pReaderAudioStream->m_samplingFrequency);
6198            return M4MCS_ERR_INVALID_AAC_SAMPLING_FREQUENCY;
6199    }
6200
6201    if( 1 == pC->pReaderAudioStream->m_nbChannels )
6202    {
6203        ssrcParams.SSRC_NrOfChannels = LVM_MONO;
6204    }
6205    else
6206    {
6207        ssrcParams.SSRC_NrOfChannels = LVM_STEREO;
6208    }
6209
6210    /*FlB 26.02.2009: add mp3 as output format*/
6211    if( pC->AudioEncParams.Format == M4ENCODER_kAAC
6212        || pC->AudioEncParams.Format == M4ENCODER_kMP3 )
6213    {
6214        switch( pC->AudioEncParams.Frequency )
6215        {
6216            case M4ENCODER_k8000Hz:
6217                ssrcParams.SSRC_Fs_Out = LVM_FS_8000;
6218                break;
6219
6220            case M4ENCODER_k11025Hz:
6221                ssrcParams.SSRC_Fs_Out = LVM_FS_11025;
6222                break;
6223
6224            case M4ENCODER_k12000Hz:
6225                ssrcParams.SSRC_Fs_Out = LVM_FS_12000;
6226                break;
6227
6228            case M4ENCODER_k16000Hz:
6229                ssrcParams.SSRC_Fs_Out = LVM_FS_16000;
6230                break;
6231
6232            case M4ENCODER_k22050Hz:
6233                ssrcParams.SSRC_Fs_Out = LVM_FS_22050;
6234                break;
6235
6236            case M4ENCODER_k24000Hz:
6237                ssrcParams.SSRC_Fs_Out = LVM_FS_24000;
6238                break;
6239
6240            case M4ENCODER_k32000Hz:
6241                ssrcParams.SSRC_Fs_Out = LVM_FS_32000;
6242                break;
6243
6244            case M4ENCODER_k44100Hz:
6245                ssrcParams.SSRC_Fs_Out = LVM_FS_44100;
6246                break;
6247
6248            case M4ENCODER_k48000Hz:
6249                ssrcParams.SSRC_Fs_Out = LVM_FS_48000;
6250                break;
6251
6252            default:
6253                M4OSA_TRACE1_1(
6254                    "M4MCS_intPrepareAudioProcessing: invalid output AAC sampling frequency \
6255                    (%d Hz), returning M4MCS_ERR_INVALID_AAC_SAMPLING_FREQUENCY",
6256                    pC->AudioEncParams.Frequency);
6257                return M4MCS_ERR_INVALID_AAC_SAMPLING_FREQUENCY;
6258                break;
6259        }
6260    }
6261    else
6262    {
6263        ssrcParams.SSRC_Fs_Out = LVM_FS_8000;
6264    }
6265
6266
6267
6268    ReturnStatus = 0;
6269
6270    switch( ssrcParams.SSRC_Fs_In )
6271    {
6272        case LVM_FS_8000:
6273            ssrcParams.NrSamplesIn = 320;
6274            break;
6275
6276        case LVM_FS_11025:
6277            ssrcParams.NrSamplesIn = 441;
6278            break;
6279
6280        case LVM_FS_12000:
6281            ssrcParams.NrSamplesIn = 480;
6282            break;
6283
6284        case LVM_FS_16000:
6285            ssrcParams.NrSamplesIn = 640;
6286            break;
6287
6288        case LVM_FS_22050:
6289            ssrcParams.NrSamplesIn = 882;
6290            break;
6291
6292        case LVM_FS_24000:
6293            ssrcParams.NrSamplesIn = 960;
6294            break;
6295
6296        case LVM_FS_32000:
6297            ssrcParams.NrSamplesIn = 1280;
6298            break;
6299
6300        case LVM_FS_44100:
6301            ssrcParams.NrSamplesIn = 1764;
6302            break;
6303
6304        case LVM_FS_48000:
6305            ssrcParams.NrSamplesIn = 1920;
6306            break;
6307
6308        default:
6309            ReturnStatus = -1;
6310            break;
6311    }
6312
6313    switch( ssrcParams.SSRC_Fs_Out )
6314    {
6315        case LVM_FS_8000:
6316            ssrcParams.NrSamplesOut = 320;
6317            break;
6318
6319        case LVM_FS_11025:
6320            ssrcParams.NrSamplesOut = 441;
6321            break;
6322
6323        case LVM_FS_12000:
6324            ssrcParams.NrSamplesOut = 480;
6325            break;
6326
6327        case LVM_FS_16000:
6328            ssrcParams.NrSamplesOut = 640;
6329            break;
6330
6331        case LVM_FS_22050:
6332            ssrcParams.NrSamplesOut = 882;
6333            break;
6334
6335        case LVM_FS_24000:
6336            ssrcParams.NrSamplesOut = 960;
6337            break;
6338
6339        case LVM_FS_32000:
6340            ssrcParams.NrSamplesOut = 1280;
6341            break;
6342
6343        case LVM_FS_44100:
6344            ssrcParams.NrSamplesOut = 1764;
6345            break;
6346
6347        case LVM_FS_48000:
6348            ssrcParams.NrSamplesOut = 1920;
6349            break;
6350
6351        default:
6352            ReturnStatus = -1;
6353            break;
6354    }
6355
6356
6357
6358    if( ReturnStatus != SSRC_OK )
6359    {
6360        M4OSA_TRACE1_1(
6361            "M4MCS_intPrepareAudioProcessing:\
6362             Error code %d returned by the SSRC_GetNrSamples function",
6363            ReturnStatus);
6364        return M4MCS_ERR_AUDIO_CONVERSION_FAILED;
6365    }
6366
6367    NrSamplesMin =
6368        (LVM_INT16)((ssrcParams.NrSamplesIn > ssrcParams.NrSamplesOut)
6369        ? ssrcParams.NrSamplesOut : ssrcParams.NrSamplesIn);
6370
6371    while( NrSamplesMin < M4MCS_SSRC_MINBLOCKSIZE )
6372    { /* Don't take blocks smaller that the minimal block size */
6373        ssrcParams.NrSamplesIn = (LVM_INT16)(ssrcParams.NrSamplesIn << 1);
6374        ssrcParams.NrSamplesOut = (LVM_INT16)(ssrcParams.NrSamplesOut << 1);
6375        NrSamplesMin = (LVM_INT16)(NrSamplesMin << 1);
6376    }
6377
6378
6379    pC->iSsrcNbSamplIn = (LVM_INT16)(
6380        ssrcParams.
6381        NrSamplesIn); /* multiplication by NrOfChannels is done below */
6382    pC->iSsrcNbSamplOut = (LVM_INT16)(ssrcParams.NrSamplesOut);
6383
6384    /**
6385    * Allocate buffer for the input of the SSRC */
6386    pC->pSsrcBufferIn =
6387        (M4OSA_MemAddr8)M4OSA_malloc(pC->iSsrcNbSamplIn * sizeof(short) \
6388        *pC->pReaderAudioStream->m_nbChannels, M4MCS,
6389        (M4OSA_Char *)"pSsrcBufferIn");
6390
6391    if( M4OSA_NULL == pC->pSsrcBufferIn )
6392    {
6393        M4OSA_TRACE1_0(
6394            "M4MCS_intPrepareVideoDecoder():\
6395             unable to allocate pSsrcBufferIn, returning M4ERR_ALLOC");
6396        return M4ERR_ALLOC;
6397    }
6398    pC->pPosInSsrcBufferIn = (M4OSA_MemAddr8)pC->pSsrcBufferIn;
6399
6400    /**
6401    * Allocate buffer for the output of the SSRC */
6402    pC->pSsrcBufferOut =
6403        (M4OSA_MemAddr8)M4OSA_malloc(pC->iSsrcNbSamplOut * sizeof(short) \
6404        *pC->pReaderAudioStream->m_nbChannels, M4MCS,
6405        (M4OSA_Char *)"pSsrcBufferOut");
6406
6407    if( M4OSA_NULL == pC->pSsrcBufferOut )
6408    {
6409        M4OSA_TRACE1_0(
6410            "M4MCS_intPrepareVideoDecoder():\
6411             unable to allocate pSsrcBufferOut, returning M4ERR_ALLOC");
6412        return M4ERR_ALLOC;
6413    }
6414
6415
6416    pC->pLVAudioResampler = LVAudioResamplerCreate(
6417        16, /*gInputParams.lvBTChannelCount*/
6418        (M4OSA_Int16)pC->InputFileProperties.uiNbChannels/*ssrcParams.SSRC_NrOfChannels*/,
6419        (M4OSA_Int32)(pC->AudioEncParams.Frequency)/*ssrcParams.SSRC_Fs_Out*/, 1);
6420
6421     if( M4OSA_NULL == pC->pLVAudioResampler)
6422     {
6423         return M4ERR_ALLOC;
6424     }
6425
6426    LVAudiosetSampleRate(pC->pLVAudioResampler,
6427        /*gInputParams.lvInSampleRate*/
6428        /*pC->pAddedClipCtxt->pSettings->ClipProperties.uiSamplingFrequency*/
6429        pC->InputFileProperties.uiSamplingFrequency/*ssrcParams.SSRC_Fs_In*/);
6430
6431    LVAudiosetVolume(pC->pLVAudioResampler, (M4OSA_Int16)(0x1000 /* 0x7fff */),
6432        (M4OSA_Int16)(0x1000/*0x7fff*/));
6433
6434
6435    /* ________________________ */
6436    /*|                        |*/
6437    /*| Init the audio encoder |*/
6438    /*|________________________|*/
6439
6440    /* Initialise the audio encoder */
6441
6442    err = pC->pAudioEncoderGlobalFcts->pFctInit(&pC->pAudioEncCtxt,
6443        pC->pCurrentAudioEncoderUserData);
6444
6445    if( M4NO_ERROR != err )
6446    {
6447        M4OSA_TRACE1_1(
6448            "M4MCS_intPrepareAudioProcessing: pAudioEncoderGlobalFcts->pFctInit returns 0x%x",
6449            err);
6450        return err;
6451    }
6452
6453    /* Open the audio encoder */
6454    err = pC->pAudioEncoderGlobalFcts->pFctOpen(pC->pAudioEncCtxt,
6455        &pC->AudioEncParams, &pC->pAudioEncDSI,
6456        M4OSA_NULL /* no grabbing */);
6457
6458    if( M4NO_ERROR != err )
6459    {
6460        M4OSA_TRACE1_1(
6461            "M4MCS_intPrepareAudioProcessing: pAudioEncoderGlobalFcts->pFctOpen returns 0x%x",
6462            err);
6463        return err;
6464    }
6465
6466    /* Allocate the input buffer for the audio encoder */
6467    switch( pC->AudioEncParams.Format )
6468    {
6469        case M4ENCODER_kAMRNB:
6470            pC->audioEncoderGranularity = M4MCS_PCM_AMR_GRANULARITY_SAMPLES;
6471            break;
6472
6473        case M4ENCODER_kAAC:
6474            pC->audioEncoderGranularity = M4MCS_PCM_AAC_GRANULARITY_SAMPLES;
6475            break;
6476
6477            /*FlB 26.02.2009: add mp3 as output format*/
6478        case M4ENCODER_kMP3:
6479            pC->audioEncoderGranularity = M4MCS_PCM_MP3_GRANULARITY_SAMPLES;
6480            break;
6481
6482         default:
6483         break;
6484    }
6485
6486    if( M4ENCODER_kMono == pC->AudioEncParams.ChannelNum )
6487        pC->audioEncoderGranularity *= sizeof(short);
6488    else
6489        pC->audioEncoderGranularity *= sizeof(short) * 2;
6490
6491    pC->pPosInAudioEncoderBuffer = M4OSA_NULL;
6492    pC->pAudioEncoderBuffer =
6493        (M4OSA_MemAddr8)M4OSA_malloc(pC->audioEncoderGranularity, M4MCS,
6494        (M4OSA_Char *)"pC->pAudioEncoderBuffer");
6495
6496    /**
6497    * Return with no error */
6498    M4OSA_TRACE3_0("M4MCS_intPrepareAudioProcessing(): returning M4NO_ERROR");
6499    return M4NO_ERROR;
6500}
6501
6502/**
6503 ******************************************************************************
6504 * M4OSA_ERR M4MCS_intPrepareWriter(M4MCS_InternalContext* pC);
6505 * @brief    Prepare the writer.
6506 * @param    pC          (IN) MCS private context
6507 * @return   M4NO_ERROR  No error
6508 * @return   Any error returned by an underlaying module
6509 ******************************************************************************
6510 */
6511static M4OSA_ERR M4MCS_intPrepareWriter( M4MCS_InternalContext *pC )
6512{
6513    M4OSA_ERR err;
6514    M4OSA_UInt32 uiVersion; /**< To write component version in 3gp writer */
6515    M4OSA_MemAddr8 pDSI = M4OSA_NULL; /**< To create the Decoder Specific Info */
6516    M4SYS_StreamIDValue optionValue; /**< For the setoption calls */
6517    M4OSA_UInt32 TargetedFileSize;
6518    M4OSA_Bool bMULPPSSPS = M4OSA_FALSE;
6519
6520    /**
6521    * Init the writer */
6522    err = pC->pWriterGlobalFcts->pFctOpen(&pC->pWriterContext, pC->pOutputFile,
6523        pC->pOsaFileWritPtr, pC->pTemporaryFile, pC->pOsaFileReadPtr);
6524
6525    if( M4NO_ERROR != err )
6526    {
6527        M4OSA_TRACE1_1(
6528            "M4MCS_intPrepareWriter: pWriterGlobalFcts->pFctOpen returns 0x%x",
6529            err);
6530        return err;
6531    }
6532
6533    /**
6534    * Link to the writer context in the writer interface */
6535    pC->pWriterDataFcts->pWriterContext = pC->pWriterContext;
6536
6537    /**
6538    * Set the product description string in the written file */
6539    err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
6540        M4WRITER_kEmbeddedString, (M4OSA_DataOption)"NXP-SW : MCS    ");
6541
6542    if( ( M4NO_ERROR != err) && (( (M4OSA_UInt32)M4ERR_BAD_OPTION_ID)
6543        != err) ) /* this option may not be implemented by some writers */
6544    {
6545        M4OSA_TRACE1_1(
6546            "M4MCS_intPrepareWriter:\
6547             pWriterGlobalFcts->pFctSetOption(M4WRITER_kEmbeddedString) returns 0x%x",
6548            err);
6549        return err;
6550    }
6551
6552    /**
6553    * Set the product version in the written file */
6554    uiVersion =
6555        M4VIDEOEDITING_VERSION_MAJOR * 100 + M4VIDEOEDITING_VERSION_MINOR * 10
6556        + M4VIDEOEDITING_VERSION_REVISION;
6557    err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
6558        M4WRITER_kEmbeddedVersion, (M4OSA_DataOption) &uiVersion);
6559
6560    if( ( M4NO_ERROR != err) && (( (M4OSA_UInt32)M4ERR_BAD_OPTION_ID)
6561        != err) ) /* this option may not be implemented by some writers */
6562    {
6563        M4OSA_TRACE1_1(
6564            "M4MCS_intPrepareWriter: \
6565            pWriterGlobalFcts->pFctSetOption(M4WRITER_kEmbeddedVersion) returns 0x%x",
6566            err);
6567        return err;
6568    }
6569
6570    /**
6571    * In case of EMP, we have to explicitely give an emp ftyp to the writer */
6572    if( M4OSA_TRUE == pC->bActivateEmp )
6573    {
6574        M4VIDEOEDITING_FtypBox ftyp;
6575
6576        ftyp.major_brand = M4VIDEOEDITING_BRAND_3GP4;
6577        ftyp.minor_version = M4VIDEOEDITING_BRAND_0000;
6578        ftyp.nbCompatibleBrands = 2;
6579        ftyp.compatible_brands[0] = M4VIDEOEDITING_BRAND_3GP4;
6580        ftyp.compatible_brands[1] = M4VIDEOEDITING_BRAND_EMP;
6581
6582        err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
6583            (M4OSA_UInt32)M4WRITER_kSetFtypBox, (M4OSA_DataOption) &ftyp);
6584
6585        if( M4NO_ERROR != err )
6586        {
6587            M4OSA_TRACE1_1(
6588                "M4MCS_intPrepareWriter:\
6589                 pWriterGlobalFcts->pFctSetOption(M4WRITER_kSetFtypBox) returns 0x%x!",
6590                err);
6591            return err;
6592        }
6593    }
6594
6595    /**
6596    * If there is a video input, allocate and fill the video stream structures for the writer */
6597    if( pC->novideo == M4OSA_FALSE )
6598    {
6599        /**
6600        * Fill Video properties structure for the AddStream method */
6601        pC->WriterVideoStreamInfo.height = pC->EncodingHeight;
6602        pC->WriterVideoStreamInfo.width = pC->EncodingWidth;
6603        pC->WriterVideoStreamInfo.fps =
6604            0; /**< Not used by the shell/core writer */
6605        pC->WriterVideoStreamInfo.Header.pBuf =
6606            M4OSA_NULL; /**< Will be updated later */
6607        pC->WriterVideoStreamInfo.Header.Size = 0; /**< Will be updated later */
6608
6609        /**
6610        * Fill Video stream description structure for the AddStream method */
6611        switch( pC->EncodingVideoFormat )
6612        {
6613            case M4ENCODER_kMPEG4:
6614                pC->WriterVideoStream.streamType = M4SYS_kMPEG_4;
6615                break;
6616
6617            case M4ENCODER_kH263:
6618                pC->WriterVideoStream.streamType = M4SYS_kH263;
6619                break;
6620
6621            case M4ENCODER_kH264:
6622                pC->WriterVideoStream.streamType = M4SYS_kH264;
6623                break;
6624
6625            case M4ENCODER_kNULL:
6626                switch( pC->InputFileProperties.VideoStreamType )
6627                {
6628                    case M4VIDEOEDITING_kMPEG4:
6629                    case M4VIDEOEDITING_kMPEG4_EMP: /* RC */
6630                        pC->WriterVideoStream.streamType = M4SYS_kMPEG_4;
6631                        break;
6632
6633                    case M4VIDEOEDITING_kH263:
6634                        pC->WriterVideoStream.streamType = M4SYS_kH263;
6635                        break;
6636
6637                    case M4VIDEOEDITING_kH264:
6638                        pC->WriterVideoStream.streamType = M4SYS_kH264;
6639                        break;
6640
6641                    default:
6642                        M4OSA_TRACE1_1(
6643                            "M4MCS_intPrepareWriter: case input=M4ENCODER_kNULL, \
6644                            unknown format (0x%x),\
6645                             returning M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FORMAT",
6646                            pC->EncodingVideoFormat);
6647                        return M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FORMAT;
6648                }
6649                break;
6650
6651            default: /**< It should never happen, already tested */
6652                M4OSA_TRACE1_1(
6653                    "M4MCS_intPrepareWriter: unknown format (0x%x),\
6654                     returning M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FORMAT",
6655                    pC->EncodingVideoFormat);
6656                return M4MCS_ERR_UNDEFINED_OUTPUT_VIDEO_FORMAT;
6657        }
6658
6659        /**
6660        * Video bitrate value will be the real value */
6661        pC->WriterVideoStream.averageBitrate =
6662            (M4OSA_Int32)pC->uiEncVideoBitrate;
6663        pC->WriterVideoStream.maxBitrate = (M4OSA_Int32)pC->uiEncVideoBitrate;
6664
6665        /**
6666        * most other parameters are "dummy" */
6667        pC->WriterVideoStream.streamID = M4MCS_WRITER_VIDEO_STREAM_ID;
6668        pC->WriterVideoStream.timeScale =
6669            0; /**< Not used by the shell/core writer */
6670        pC->WriterVideoStream.profileLevel =
6671            0; /**< Not used by the shell/core writer */
6672        pC->WriterVideoStream.duration =
6673            0; /**< Not used by the shell/core writer */
6674        pC->WriterVideoStream.decoderSpecificInfoSize =
6675            sizeof(M4WRITER_StreamVideoInfos);
6676        pC->WriterVideoStream.decoderSpecificInfo =
6677            (M4OSA_MemAddr32) &(pC->WriterVideoStreamInfo);
6678
6679        /**
6680        * Update Encoder Header properties for Video stream if needed */
6681        if( M4ENCODER_kH263 == pC->EncodingVideoFormat )
6682        {
6683            /**
6684            * Creates the H263 DSI */
6685            pC->WriterVideoStreamInfo.Header.Size =
6686                7; /**< H263 output DSI is always 7 bytes */
6687            pDSI = (M4OSA_MemAddr8)M4OSA_malloc(7, M4MCS, (M4OSA_Char
6688                *)"pC->WriterVideoStreamInfo.Header.pBuf (DSI H263)");
6689
6690            if( M4OSA_NULL == pDSI )
6691            {
6692                M4OSA_TRACE1_0("M4MCS_intPrepareWriter(): unable to allocate pDSI (H263),\
6693                               returning M4ERR_ALLOC");
6694                return M4ERR_ALLOC;
6695            }
6696
6697            /**
6698            * Vendor is NXP Software: N, X, P, S. */
6699            pDSI[0] = 'N';
6700            pDSI[1] = 'X';
6701            pDSI[2] = 'P';
6702            pDSI[3] = 'S';
6703
6704            /**
6705            * Decoder version is 0 */
6706            pDSI[4] = 0;
6707
6708            /**
6709            * Level is the sixth byte of the DSI. */
6710            switch( pC->EncodingWidth )
6711            {
6712                case M4ENCODER_SQCIF_Width:
6713                case M4ENCODER_QCIF_Width:
6714                    if( ( pC->uiEncVideoBitrate <= M4ENCODER_k64_KBPS)
6715                        && (pC->EncodingVideoFramerate <= M4ENCODER_k15_FPS) )
6716                    {
6717                        pDSI[5] = 10;
6718                    }
6719                    else if( ( pC->uiEncVideoBitrate <= M4ENCODER_k128_KBPS)
6720                        && (pC->EncodingVideoFramerate <= M4ENCODER_k15_FPS) )
6721                    {
6722                        pDSI[5] = 45;
6723                    }
6724                    else if( ( pC->uiEncVideoBitrate <= M4ENCODER_k128_KBPS)
6725                        && (pC->EncodingVideoFramerate <= M4ENCODER_k30_FPS) )
6726                    {
6727                        pDSI[5] = 20;
6728                    }
6729                    else if( ( pC->uiEncVideoBitrate <= M4ENCODER_k384_KBPS)
6730                        && (pC->EncodingVideoFramerate <= M4ENCODER_k30_FPS) )
6731                    {
6732                        pDSI[5] = 30;
6733                    }
6734                    else if( ( pC->uiEncVideoBitrate
6735                        <= M4ENCODER_k800_KBPS/*2048*/)
6736                        && (pC->EncodingVideoFramerate <= M4ENCODER_k30_FPS) )
6737                    {
6738                        pDSI[5] = 40;
6739                    }
6740                    break;
6741
6742                case M4ENCODER_CIF_Width:
6743                    if( ( pC->uiEncVideoBitrate <= M4ENCODER_k128_KBPS)
6744                        && (pC->EncodingVideoFramerate <= M4ENCODER_k15_FPS) )
6745                    {
6746                        pDSI[5] = 20;
6747                    }
6748                    else if( ( pC->uiEncVideoBitrate <= M4ENCODER_k384_KBPS)
6749                        && (pC->EncodingVideoFramerate <= M4ENCODER_k30_FPS) )
6750                    {
6751                        pDSI[5] = 30;
6752                    }
6753                    else if( ( pC->uiEncVideoBitrate
6754                        <= M4ENCODER_k800_KBPS/*2048*/)
6755                        && (pC->EncodingVideoFramerate <= M4ENCODER_k30_FPS) )
6756                    {
6757                        pDSI[5] = 40;
6758                    }
6759                    break;
6760
6761                    default:
6762                    break;
6763            }
6764
6765            /**
6766            * Profile is the seventh byte of the DSI. */
6767            pDSI[6] = 0;
6768
6769            pC->WriterVideoStreamInfo.Header.pBuf = pDSI;
6770        }
6771        else if( M4ENCODER_kNULL == pC->EncodingVideoFormat )
6772        {
6773#ifdef TIMESCALE_BUG
6774            /* if we are in "timescale mode", we need to know on how many bits the v
6775            op_time_increment is coded and to change the DSI */
6776
6777            if( pC->uiVideoTimescale == 0 )
6778            {
6779                /* If we copy the stream from the input, we copy its DSI */
6780                pC->WriterVideoStreamInfo.Header.Size = pC->pReaderVideoStream->
6781                    m_basicProperties.m_decoderSpecificInfoSize;
6782                pC->WriterVideoStreamInfo.Header.pBuf =
6783                    (M4OSA_MemAddr8)pC->pReaderVideoStream->
6784                    m_basicProperties.m_pDecoderSpecificInfo;
6785            }
6786            else
6787            {
6788                /* Allocate a new DSI */
6789                pC->WriterVideoStreamInfo.Header.Size = pC->pReaderVideoStream->
6790                    m_basicProperties.m_decoderSpecificInfoSize;
6791                pC->WriterVideoStreamInfo.Header.pBuf =
6792                    (M4OSA_Void
6793                    *)M4OSA_malloc(pC->WriterVideoStreamInfo.Header.Size,
6794                    M4MCS,
6795                    (M4OSA_Char
6796                    *)
6797                    "New decoder specific info for timescale modification");
6798
6799                if( pC->WriterVideoStreamInfo.Header.pBuf == M4OSA_NULL )
6800                {
6801                    M4OSA_TRACE1_0("M4MCS_intPrepareWriter: Allocation error\
6802                                   pC->WriterVideoStreamInfo.Header.pBuf");
6803                    return M4ERR_ALLOC;
6804                }
6805
6806                /* Copy Reading DSI to new DSI */
6807                memcpy((void *)pC->WriterVideoStreamInfo.Header.pBuf,
6808                    (void *)pC->pReaderVideoStream->
6809                    m_basicProperties.m_pDecoderSpecificInfo,
6810                    pC->WriterVideoStreamInfo.Header.Size);
6811
6812                /* Call a function to change DSI and to get the nb of bits on which the
6813                vop_time_increment is coded */
6814                err = M4MCS_intParseVideoDSI(pC);
6815            }
6816
6817#else
6818            /* If we copy the stream from the input, we copy its DSI */
6819
6820            pC->WriterVideoStreamInfo.Header.Size = pC->pReaderVideoStream->
6821                m_basicProperties.m_decoderSpecificInfoSize;
6822            pC->WriterVideoStreamInfo.Header.pBuf =
6823                (M4OSA_MemAddr8)pC->pReaderVideoStream->
6824                m_basicProperties.m_pDecoderSpecificInfo;
6825
6826#endif
6827
6828        }
6829        /* otherwise (MPEG4), the DSI will be recovered from the encoder later on. */
6830
6831        /*+CRLV6775 - H.264 Trimming  */
6832        if( pC->bH264Trim == M4OSA_TRUE )
6833        {
6834            bMULPPSSPS = M4OSA_TRUE;
6835            err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
6836                (M4OSA_UInt32)M4WRITER_kMUL_PPS_SPS,
6837                (M4OSA_DataOption) &bMULPPSSPS);
6838
6839            if( ( M4NO_ERROR != err)
6840                && (( (M4OSA_UInt32)M4ERR_BAD_OPTION_ID)
6841                != err) ) /* this option may not be implemented by some writers */
6842            {
6843                M4OSA_TRACE1_1(
6844                    "M4MCS_intPrepareWriter:\
6845                     pWriterGlobalFcts->pFctSetOption(M4WRITER_kMUL_PPS_SPS) returns 0x%x",
6846                    err);
6847                return err;
6848            }
6849        }
6850        /*-CRLV6775 - H.264 Trimming  */
6851        /**
6852        * Add the video stream */
6853        err = pC->pWriterGlobalFcts->pFctAddStream(pC->pWriterContext,
6854            &pC->WriterVideoStream);
6855
6856        if( M4NO_ERROR != err )
6857        {
6858            M4OSA_TRACE1_1(
6859                "M4MCS_intPrepareWriter: pWriterGlobalFcts->pFctAddStream(video) returns 0x%x!",
6860                err);
6861            return err;
6862        }
6863
6864        /**
6865        * Update AU properties for video stream */
6866        pC->WriterVideoAU.stream = &(pC->WriterVideoStream);
6867        pC->WriterVideoAU.dataAddress = M4OSA_NULL;
6868        pC->WriterVideoAU.size = 0;
6869        pC->WriterVideoAU.CTS = 0; /** Reset time */
6870        pC->WriterVideoAU.DTS = 0;
6871        pC->WriterVideoAU.attribute = AU_RAP;
6872        pC->WriterVideoAU.nbFrag = 0; /** No fragment */
6873        pC->WriterVideoAU.frag = M4OSA_NULL;
6874
6875        /**
6876        * Set the writer max video AU size */
6877        optionValue.streamID = M4MCS_WRITER_VIDEO_STREAM_ID;
6878        optionValue.value = pC->uiVideoMaxAuSize;
6879        err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
6880            (M4OSA_UInt32)M4WRITER_kMaxAUSize,
6881            (M4OSA_DataOption) &optionValue);
6882
6883        if( M4NO_ERROR != err )
6884        {
6885            M4OSA_TRACE1_1(
6886                "M4MCS_intPrepareWriter: \
6887                pWriterGlobalFcts->pFctSetOption(M4WRITER_kMaxAUSize, video) returns 0x%x!",
6888                err);
6889            return err;
6890        }
6891
6892        /**
6893        * Set the writer max video chunk size */
6894        optionValue.value = pC->uiVideoMaxChunckSize;
6895        err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
6896            (M4OSA_UInt32)M4WRITER_kMaxChunckSize,
6897            (M4OSA_DataOption) &optionValue);
6898
6899        if( ( M4NO_ERROR != err) && (( (M4OSA_UInt32)M4ERR_BAD_OPTION_ID)
6900            != err) ) /* this option may not be implemented by some writers */
6901        {
6902            M4OSA_TRACE1_1(
6903                "M4MCS_intPrepareWriter:\
6904                 pWriterGlobalFcts->pFctSetOption(M4WRITER_kMaxAUSize, video) returns 0x%x!",
6905                err);
6906            return err;
6907        }
6908    }
6909
6910    /**
6911    * If there is an audio input, allocate and fill the audio stream structures for the writer */
6912    if( pC->noaudio == M4OSA_FALSE )
6913    {
6914        M4WRITER_StreamAudioInfos streamAudioInfo;
6915
6916        streamAudioInfo.nbSamplesPerSec = 0; /**< unused by our shell writer */
6917        streamAudioInfo.nbBitsPerSample = 0; /**< unused by our shell writer */
6918        streamAudioInfo.nbChannels = 1;      /**< unused by our shell writer */
6919
6920        pC->WriterAudioStream.averageBitrate =
6921            0; /**< It is not used by the shell, the DSI is taken into account instead */
6922        pC->WriterAudioStream.maxBitrate =
6923            0; /**< Not used by the shell/core writer */
6924
6925        /**
6926        * Fill Audio stream description structure for the AddStream method */
6927        switch( pC->AudioEncParams.Format )
6928        {
6929            case M4ENCODER_kAMRNB:
6930                pC->WriterAudioStream.streamType = M4SYS_kAMR;
6931                break;
6932
6933            case M4ENCODER_kAAC:
6934                pC->WriterAudioStream.streamType = M4SYS_kAAC;
6935                pC->WriterAudioStream.averageBitrate =
6936                    pC->AudioEncParams.Bitrate;
6937                pC->WriterAudioStream.maxBitrate = pC->AudioEncParams.Bitrate;
6938                break;
6939
6940                /*FlB 26.02.2009: add mp3 as output format*/
6941            case M4ENCODER_kMP3:
6942                pC->WriterAudioStream.streamType = M4SYS_kMP3;
6943                break;
6944
6945            case M4ENCODER_kAudioNULL:
6946                switch( pC->InputFileProperties.AudioStreamType )
6947                {
6948                case M4VIDEOEDITING_kAMR_NB:
6949                    pC->WriterAudioStream.streamType = M4SYS_kAMR;
6950                    break;
6951                    /*FlB 26.02.2009: add mp3 as output format*/
6952                case M4VIDEOEDITING_kMP3:
6953                    pC->WriterAudioStream.streamType = M4SYS_kMP3;
6954                    break;
6955
6956                case M4VIDEOEDITING_kAAC:
6957                case M4VIDEOEDITING_kAACplus:
6958                case M4VIDEOEDITING_keAACplus:
6959                    pC->WriterAudioStream.streamType = M4SYS_kAAC;
6960                    pC->WriterAudioStream.averageBitrate =
6961                        pC->AudioEncParams.Bitrate;
6962                    pC->WriterAudioStream.maxBitrate =
6963                        pC->AudioEncParams.Bitrate;
6964                    break;
6965
6966                case M4VIDEOEDITING_kEVRC:
6967                    pC->WriterAudioStream.streamType = M4SYS_kEVRC;
6968                    break;
6969
6970                case M4VIDEOEDITING_kNoneAudio:
6971                case M4VIDEOEDITING_kPCM:
6972                case M4VIDEOEDITING_kNullAudio:
6973                case M4VIDEOEDITING_kUnsupportedAudio:
6974                    break;
6975                }
6976                break;
6977
6978            default: /**< It should never happen, already tested */
6979                M4OSA_TRACE1_1(
6980                    "M4MCS_intPrepareWriter: \
6981                    unknown format (0x%x), returning M4MCS_ERR_UNDEFINED_OUTPUT_AUDIO_FORMAT",
6982                    pC->AudioEncParams.Format);
6983                return M4MCS_ERR_UNDEFINED_OUTPUT_AUDIO_FORMAT;
6984        }
6985
6986        /**
6987        * MCS produces only AMR-NB output */
6988        pC->WriterAudioStream.streamID = M4MCS_WRITER_AUDIO_STREAM_ID;
6989        pC->WriterAudioStream.duration =
6990            0; /**< Not used by the shell/core writer */
6991        pC->WriterAudioStream.profileLevel =
6992            0; /**< Not used by the shell/core writer */
6993        pC->WriterAudioStream.timeScale = pC->AudioEncParams.Frequency;
6994
6995        if( pC->AudioEncParams.Format == M4ENCODER_kAudioNULL )
6996        {
6997            /* If we copy the stream from the input, we copy its DSI */
6998            streamAudioInfo.Header.Size = pC->pReaderAudioStream->
6999                m_basicProperties.m_decoderSpecificInfoSize;
7000            streamAudioInfo.Header.pBuf =
7001                (M4OSA_MemAddr8)pC->pReaderAudioStream->
7002                m_basicProperties.m_pDecoderSpecificInfo;
7003        }
7004        else
7005        {
7006            if( pC->pAudioEncDSI.pInfo != M4OSA_NULL )
7007            {
7008                /* Use the DSI given by the encoder open() */
7009                streamAudioInfo.Header.Size = pC->pAudioEncDSI.infoSize;
7010                streamAudioInfo.Header.pBuf = pC->pAudioEncDSI.pInfo;
7011            }
7012            else
7013            {
7014                /* Writer will put a default Philips DSI */
7015                streamAudioInfo.Header.Size = 0;
7016                streamAudioInfo.Header.pBuf = M4OSA_NULL;
7017            }
7018        }
7019
7020        /**
7021        * Our writer shell interface is a little tricky: we put M4WRITER_StreamAudioInfos
7022         in the DSI pointer... */
7023        pC->WriterAudioStream.decoderSpecificInfo =
7024            (M4OSA_MemAddr32) &streamAudioInfo;
7025
7026        /**
7027        * Add the audio stream to the writer */
7028        err = pC->pWriterGlobalFcts->pFctAddStream(pC->pWriterContext,
7029            &pC->WriterAudioStream);
7030
7031        if( M4NO_ERROR != err )
7032        {
7033            M4OSA_TRACE1_1(
7034                "M4MCS_intPrepareWriter: pWriterGlobalFcts->pFctAddStream(audio) returns 0x%x",
7035                err);
7036            return err;
7037        }
7038
7039        /**
7040        * Link the AU and the stream */
7041        pC->WriterAudioAU.stream = &(pC->WriterAudioStream);
7042        pC->WriterAudioAU.dataAddress = M4OSA_NULL;
7043        pC->WriterAudioAU.size = 0;
7044        pC->WriterAudioAU.CTS = 0; /** Reset time */
7045        pC->WriterAudioAU.DTS = 0;
7046        pC->WriterAudioAU.attribute = 0;
7047        pC->WriterAudioAU.nbFrag = 0; /** No fragment */
7048        pC->WriterAudioAU.frag = M4OSA_NULL;
7049
7050        /**
7051        * Set the writer audio max AU size */
7052        /* As max bitrate is now 320kbps instead of 128kbps, max AU
7053         * size has to be increased adapt the max AU size according to the stream type and the
7054         * channels numbers*/
7055        /* After tests, a margin of 3 is taken (2 was not enough and raises to memory overwrite)
7056         */
7057        //pC->uiAudioMaxAuSize = M4MCS_AUDIO_MAX_AU_SIZE;
7058        switch( pC->WriterAudioStream.streamType )
7059        {
7060            case M4SYS_kAMR:
7061                pC->uiAudioMaxAuSize = M4MCS_PCM_AMR_GRANULARITY_SAMPLES
7062                    * (( pC->InputFileProperties.uiNbChannels
7063                    * sizeof(short)) + 3);
7064                break;
7065
7066            case M4SYS_kMP3:
7067                pC->uiAudioMaxAuSize = M4MCS_PCM_MP3_GRANULARITY_SAMPLES
7068                    * (( pC->InputFileProperties.uiNbChannels
7069                    * sizeof(short)) + 3);
7070                break;
7071
7072            case M4SYS_kAAC:
7073                pC->uiAudioMaxAuSize = M4MCS_PCM_AAC_GRANULARITY_SAMPLES
7074                    * (( pC->InputFileProperties.uiNbChannels
7075                    * sizeof(short)) + 3);
7076                break;
7077                /*case M4SYS_kEVRC:
7078                pC->uiAudioMaxAuSize = M4MCS_PCM_EVRC_GRANULARITY_SAMPLES*
7079                ((pC->InputFileProperties.uiNbChannels * sizeof(short))+3);
7080                break;*/
7081            default: /**< It should never happen, already tested */
7082                M4OSA_TRACE1_1(
7083                    "M4MCS_intPrepareWriter: unknown format (0x%x),\
7084                     returning M4MCS_ERR_UNDEFINED_OUTPUT_AUDIO_FORMAT",
7085                    pC->WriterAudioStream.streamType);
7086                return M4MCS_ERR_UNDEFINED_OUTPUT_AUDIO_FORMAT;
7087        }
7088
7089        optionValue.streamID = M4MCS_WRITER_AUDIO_STREAM_ID;
7090        optionValue.value = pC->uiAudioMaxAuSize;
7091        err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
7092            (M4OSA_UInt32)M4WRITER_kMaxAUSize,
7093            (M4OSA_DataOption) &optionValue);
7094
7095        if( M4NO_ERROR != err )
7096        {
7097            M4OSA_TRACE1_1(
7098                "M4MCS_intPrepareWriter: pWriterGlobalFcts->pFctSetOption(audio,\
7099                M4WRITER_kMaxAUSize) returns 0x%x",
7100                err);
7101            return err;
7102        }
7103
7104        optionValue.value = M4MCS_AUDIO_MAX_CHUNK_SIZE;
7105        err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
7106            (M4OSA_UInt32)M4WRITER_kMaxChunckSize,
7107            (M4OSA_DataOption) &optionValue);
7108
7109        if( ( M4NO_ERROR != err) && (( (M4OSA_UInt32)M4ERR_BAD_OPTION_ID)
7110            != err) ) /* this option may not be implemented by some writers */
7111        {
7112            M4OSA_TRACE1_1(
7113                "M4MCS_intPrepareWriter: pWriterGlobalFcts->pFctSetOption(audio,\
7114                M4WRITER_kMaxChunckSize) returns 0x%x",
7115                err);
7116            return err;
7117        }
7118    }
7119
7120    /*
7121    * Set the limitation size of the writer */
7122    TargetedFileSize = pC->uiMaxFileSize;
7123    /* add 1 kB margin */
7124    if( TargetedFileSize > 8192 )
7125        TargetedFileSize -= 1024;
7126
7127    err = pC->pWriterGlobalFcts->pFctSetOption(pC->pWriterContext,
7128        (M4OSA_UInt32)M4WRITER_kMaxFileSize,
7129        (M4OSA_DataOption) &TargetedFileSize);
7130
7131    if( ( M4NO_ERROR != err) && (( (M4OSA_UInt32)M4ERR_BAD_OPTION_ID)
7132        != err) ) /* this option may not be implemented by some writers */
7133    {
7134        M4OSA_TRACE1_1(
7135            "M4MCS_intPrepareWriter: pWriterGlobalFcts->pFctSetOption\
7136            (M4WRITER_kMaxFileSize) returns 0x%x!",
7137            err);
7138        return err;
7139    }
7140
7141    /**
7142    * Close the stream registering in order to be ready to write data */
7143    err = pC->pWriterGlobalFcts->pFctStartWriting(pC->pWriterContext);
7144
7145    if( M4NO_ERROR != err )
7146    {
7147        M4OSA_TRACE1_1(
7148            "M4MCS_intPrepareWriter: pWriterGlobalFcts->pFctStartWriting returns 0x%x",
7149            err);
7150        return err;
7151    }
7152
7153    /**
7154    * Return with no error */
7155    M4OSA_TRACE3_0("M4MCS_intPrepareWriter(): returning M4NO_ERROR");
7156    return M4NO_ERROR;
7157}
7158
7159/**
7160 ******************************************************************************
7161 * M4OSA_ERR M4MCS_intPrepareAudioBeginCut(M4MCS_InternalContext* pC);
7162 * @brief    DO the audio begin cut.
7163 * @param    pC          (IN) MCS private context
7164 * @return   M4NO_ERROR  No error
7165 * @return   Any error returned by an underlaying module
7166 ******************************************************************************
7167 */
7168static M4OSA_ERR M4MCS_intPrepareAudioBeginCut( M4MCS_InternalContext *pC )
7169{
7170    M4OSA_ERR err;
7171    M4OSA_Int32 iCts;
7172    M4OSA_UInt32 uiFrameSize;
7173
7174    if( pC->noaudio )
7175        return M4NO_ERROR;
7176
7177    /**
7178    * Check if an audio begin cut is needed */
7179    if( ( M4OSA_NULL == pC->pReaderAudioStream) || (0 == pC->uiBeginCutTime) )
7180    {
7181        /**
7182        * Return with no error */
7183        M4OSA_TRACE3_0(
7184            "M4MCS_intPrepareAudioBeginCut(): returning M4NO_ERROR (a)");
7185        return M4NO_ERROR;
7186    }
7187
7188    /**
7189    * Jump at the begin cut time */
7190    iCts = pC->uiBeginCutTime;
7191    err = pC->m_pReader->m_pFctJump(pC->pReaderContext,
7192        (M4_StreamHandler *)pC->pReaderAudioStream, &iCts);
7193
7194    if( M4NO_ERROR != err )
7195    {
7196        M4OSA_TRACE1_1(
7197            "M4MCS_intPrepareAudioBeginCut: m_pFctJump(Audio) returns 0x%x!",
7198            err);
7199        return err;
7200    }
7201
7202    /**
7203    * Remember audio begin cut offset */
7204    pC->iAudioCtsOffset = iCts;
7205
7206    /**
7207    * AMR-NB & EVRC: there may be many frames per AU.
7208    * In that case we need to slice the first AU to keep the 20 ms cut precision */
7209    if( ( M4DA_StreamTypeAudioAmrNarrowBand
7210        == pC->pReaderAudioStream->m_basicProperties.m_streamType)
7211        || (M4DA_StreamTypeAudioEvrc
7212        == pC->pReaderAudioStream->m_basicProperties.m_streamType) )
7213    {
7214        /**
7215        * If the next frame CTS is lower than the begin cut time,
7216        * we must read the AU and parse its frames to reach the
7217        * nearest to the begin cut */
7218        if( ( iCts + 20) < (M4OSA_Int32)pC->uiBeginCutTime )
7219        {
7220            /**
7221            * Read the first audio AU after the jump */
7222            err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
7223                (M4_StreamHandler *)pC->pReaderAudioStream,
7224                &pC->ReaderAudioAU);
7225
7226            if( M4WAR_NO_MORE_AU == err )
7227            {
7228                M4OSA_TRACE1_0(
7229                    "M4MCS_intPrepareAudioBeginCut(): m_pReaderDataIt->m_pFctGetNextAu(audio)\
7230                     returns M4WAR_NO_MORE_AU! Returning M4NO_ERROR");
7231                return
7232                    M4NO_ERROR; /**< no fatal error here, we should be able to pursue */
7233            }
7234            else if( M4NO_ERROR != err )
7235            {
7236                M4OSA_TRACE1_1(
7237                    "M4MCS_intPrepareAudioBeginCut(): m_pReaderDataIt->m_pFctGetNextAu(Audio)\
7238                     returns 0x%x",
7239                    err);
7240                return err;
7241            }
7242
7243            /**
7244            * While the next AU has a lower CTS than the begin cut time, we advance to
7245            the next frame */
7246            while( ( iCts + 20) <= (M4OSA_Int32)pC->uiBeginCutTime )
7247            {
7248                /**
7249                * Get the size of the frame */
7250                switch( pC->pReaderAudioStream->m_basicProperties.m_streamType )
7251                {
7252                    case M4DA_StreamTypeAudioAmrNarrowBand:
7253                        uiFrameSize = M4MCS_intGetFrameSize_AMRNB(
7254                            pC->ReaderAudioAU.m_dataAddress);
7255                        break;
7256
7257                    case M4DA_StreamTypeAudioEvrc:
7258                        uiFrameSize = M4MCS_intGetFrameSize_EVRC(
7259                            pC->ReaderAudioAU.m_dataAddress);
7260                        break;
7261
7262                    default:
7263                        uiFrameSize = 0;
7264                        break;
7265                }
7266
7267                if( 0 == uiFrameSize )
7268                {
7269                    /**
7270                    * Corrupted frame! We get out of this mess!
7271                    * We don't want to crash here... */
7272                    M4OSA_TRACE1_0(
7273                        "M4MCS_intPrepareAudioBeginCut(): \
7274                        M4MCS_intGetFrameSize_xxx returns 0! Returning M4NO_ERROR");
7275                    return
7276                        M4NO_ERROR; /**< no fatal error here, we should be able to pursue */
7277                }
7278
7279                /**
7280                * Go to the next frame */
7281                pC->ReaderAudioAU.m_dataAddress += uiFrameSize;
7282                pC->ReaderAudioAU.m_size -= uiFrameSize;
7283
7284                /**
7285                * Get the CTS of the next frame */
7286                iCts += 20; /**< AMR, EVRC frame duration is always 20 ms */
7287                pC->ReaderAudioAU.m_CTS = iCts;
7288                pC->ReaderAudioAU.m_DTS = iCts;
7289            }
7290
7291            /**
7292            * Update the audio begin cut offset */
7293            pC->iAudioCtsOffset = iCts;
7294        }
7295    }
7296
7297    /**
7298    * Return with no error */
7299    M4OSA_TRACE3_0("M4MCS_intPrepareAudioBeginCut(): returning M4NO_ERROR");
7300    return M4NO_ERROR;
7301}
7302
7303/**
7304 ******************************************************************************
7305 * M4OSA_ERR M4MCS_intStepEncoding(M4MCS_InternalContext* pC, M4OSA_UInt8* pProgress)
7306 ******************************************************************************
7307 */
7308static M4OSA_ERR M4MCS_intStepEncoding( M4MCS_InternalContext *pC,
7309                                       M4OSA_UInt8 *pProgress )
7310{
7311    M4OSA_ERR err;
7312    M4OSA_UInt32 uiAudioStepCount = 0;
7313
7314    /* ---------- VIDEO TRANSCODING ---------- */
7315
7316    if( ( pC->novideo == M4OSA_FALSE) && (M4MCS_kStreamState_STARTED
7317        == pC->VideoState) ) /**< If the video encoding is going on */
7318    {
7319        if( pC->EncodingVideoFormat == M4ENCODER_kNULL )
7320        {
7321            err = M4MCS_intVideoNullEncoding(pC);
7322        }
7323        else
7324        {
7325            err = M4MCS_intVideoTranscoding(pC);
7326        }
7327
7328        /**
7329        * No more space, quit properly */
7330        if( M4WAR_WRITER_STOP_REQ == err )
7331        {
7332            *pProgress = (M4OSA_UInt8)(( ( (M4OSA_UInt32)pC->dViDecCurrentCts
7333                - pC->uiBeginCutTime) * 100)
7334                / (pC->uiEndCutTime - pC->uiBeginCutTime));
7335
7336            pC->State = M4MCS_kState_FINISHED;
7337
7338            /* bad file produced on very short 3gp file */
7339            if( pC->dViDecCurrentCts - pC->uiBeginCutTime == 0 )
7340            {
7341                /* Nothing has been encoded -> bad produced file -> error returned */
7342                M4OSA_TRACE2_0(
7343                    "M4MCS_intStepEncoding(): video transcoding returns\
7344                     M4MCS_ERR_OUTPUT_FILE_SIZE_TOO_SMALL");
7345                return M4MCS_ERR_OUTPUT_FILE_SIZE_TOO_SMALL;
7346            }
7347            else
7348            {
7349#ifndef M4MCS_AUDIOONLY
7350                /* clean AIR context needed to keep media aspect ratio*/
7351
7352                if( M4OSA_NULL != pC->m_air_context )
7353                {
7354                    err = M4AIR_cleanUp(pC->m_air_context);
7355
7356                    if( err != M4NO_ERROR )
7357                    {
7358                        M4OSA_TRACE1_1(
7359                            "M4xVSS_PictureCallbackFct: Error when cleaning AIR: 0x%x",
7360                            err);
7361                        return err;
7362                    }
7363                    pC->m_air_context = M4OSA_NULL;
7364                }
7365
7366#endif /*M4MCS_AUDIOONLY*/
7367
7368                M4OSA_TRACE2_0(
7369                    "M4MCS_intStepEncoding(): video transcoding returns M4MCS_ERR_NOMORE_SPACE");
7370                return M4MCS_ERR_NOMORE_SPACE;
7371            }
7372        }
7373
7374        /**< The input plane is null because the input image will be obtained by the
7375        VPP filter from the context */
7376        if( ( M4NO_ERROR != err) && (M4WAR_NO_MORE_AU != err) )
7377        {
7378            M4OSA_TRACE1_1(
7379                "M4MCS_intStepEncoding(): video transcoding returns 0x%x!",
7380                err);
7381            return err;
7382        }
7383    }
7384
7385    /* ---------- AUDIO TRANSCODING ---------- */
7386
7387    if( ( pC->noaudio == M4OSA_FALSE) && (M4MCS_kStreamState_STARTED
7388        == pC->AudioState) ) /**< If there is an audio stream */
7389    {
7390        while(
7391            /**< If the video encoding is running, encode audio until we reach video time */
7392            ( ( pC->novideo == M4OSA_FALSE)
7393            && (M4MCS_kStreamState_STARTED == pC->VideoState)
7394            && (pC->ReaderAudioAU.m_CTS
7395            + pC->m_audioAUDuration < pC->ReaderVideoAU.m_CTS)) ||
7396            /**< If the video encoding is not running, perform 1 step of audio encoding */
7397            (( M4MCS_kStreamState_STARTED == pC->AudioState)
7398            && (uiAudioStepCount < 1)) )
7399        {
7400            uiAudioStepCount++;
7401
7402            /**< check if an adio effect has to be applied*/
7403            err = M4MCS_intCheckAudioEffects(pC);
7404
7405            if( M4NO_ERROR != err )
7406            {
7407                M4OSA_TRACE1_1(
7408                    "M4MCS_intStepEncoding(): M4MCS_intCheckAudioEffects returns err: 0x%x",
7409                    err);
7410                return err;
7411            }
7412
7413            if( pC->AudioEncParams.Format == M4ENCODER_kAudioNULL )
7414            {
7415                err = M4MCS_intAudioNullEncoding(pC);
7416            }
7417            else /**< Audio transcoding */
7418            {
7419                err = M4MCS_intAudioTranscoding(pC);
7420            }
7421
7422            /**
7423            * No more space, quit properly */
7424            if( M4WAR_WRITER_STOP_REQ == err )
7425            {
7426                *pProgress =
7427                    (M4OSA_UInt8)(( ( (M4OSA_UInt32)pC->ReaderAudioAU.m_CTS
7428                    - pC->uiBeginCutTime) * 100)
7429                    / (pC->uiEndCutTime - pC->uiBeginCutTime));
7430
7431                pC->State = M4MCS_kState_FINISHED;
7432
7433                /* bad file produced on very short 3gp file */
7434                if( pC->ReaderAudioAU.m_CTS - pC->uiBeginCutTime == 0 )
7435                {
7436                    /* Nothing has been encoded -> bad produced file -> error returned */
7437                    M4OSA_TRACE2_0(
7438                        "M4MCS_intStepEncoding():\
7439                         audio transcoding returns M4MCS_ERR_OUTPUT_FILE_SIZE_TOO_SMALL");
7440                    return M4MCS_ERR_OUTPUT_FILE_SIZE_TOO_SMALL;
7441                }
7442                else
7443                {
7444#ifndef M4MCS_AUDIOONLY
7445                    /* clean AIR context needed to keep media aspect ratio*/
7446
7447                    if( M4OSA_NULL != pC->m_air_context )
7448                    {
7449                        err = M4AIR_cleanUp(pC->m_air_context);
7450
7451                        if( err != M4NO_ERROR )
7452                        {
7453                            M4OSA_TRACE1_1(
7454                                "M4xVSS_PictureCallbackFct: Error when cleaning AIR: 0x%x",
7455                                err);
7456                            return err;
7457                        }
7458                        pC->m_air_context = M4OSA_NULL;
7459                    }
7460
7461#endif /*M4MCS_AUDIOONLY*/
7462
7463                    M4OSA_TRACE2_0(
7464                        "M4MCS_intStepEncoding(): \
7465                        audio transcoding returns M4MCS_ERR_NOMORE_SPACE");
7466                    return M4MCS_ERR_NOMORE_SPACE;
7467                }
7468            }
7469
7470            if( M4WAR_NO_MORE_AU == err )
7471            {
7472                pC->AudioState = M4MCS_kStreamState_FINISHED;
7473                M4OSA_TRACE3_0(
7474                    "M4MCS_intStepEncoding(): audio transcoding returns M4WAR_NO_MORE_AU");
7475                break;
7476            }
7477            else if( M4NO_ERROR != err )
7478            {
7479                M4OSA_TRACE1_1(
7480                    "M4MCS_intStepEncoding(): audio transcoding returns 0x%x",
7481                    err);
7482                return err;
7483            }
7484
7485            /**
7486            * Check for end cut */
7487            /* We absolutely want to have less or same audio duration as video ->
7488            (2*pC->m_audioAUDuration) */
7489            if( (M4OSA_UInt32)pC->ReaderAudioAU.m_CTS
7490                + (2 *pC->m_audioAUDuration) > pC->uiEndCutTime )
7491            {
7492                pC->AudioState = M4MCS_kStreamState_FINISHED;
7493                break;
7494            }
7495        }
7496    }
7497
7498    /* ---------- PROGRESS MANAGEMENT ---------- */
7499
7500    /**
7501    * Compute progress */
7502    if( pC->novideo )
7503    {
7504        if( pC->ReaderAudioAU.m_CTS < pC->uiBeginCutTime )
7505        {
7506            *pProgress = 0;
7507        }
7508        else
7509        {
7510            *pProgress = (M4OSA_UInt8)(( ( (M4OSA_UInt32)pC->ReaderAudioAU.m_CTS
7511                - pC->uiBeginCutTime) * 100)
7512                / (pC->uiEndCutTime - pC->uiBeginCutTime));
7513        }
7514        //printf(": %6.0f\b\b\b\b\b\b\b\b", pC->ReaderAudioAU.m_CTS);
7515
7516    }
7517    else
7518    {
7519        if( pC->dViDecCurrentCts < pC->uiBeginCutTime )
7520        {
7521            *pProgress = 0;
7522        }
7523        else
7524        {
7525            *pProgress = (M4OSA_UInt8)(( ( (M4OSA_UInt32)pC->dViDecCurrentCts
7526                - pC->uiBeginCutTime) * 100)
7527                / (pC->uiEndCutTime - pC->uiBeginCutTime));
7528        }
7529        //printf(": %6.0f\b\b\b\b\b\b\b\b", pC->dViDecCurrentCts);
7530    }
7531
7532    /**
7533    * Sanity check */
7534    if( *pProgress > 99 )
7535    {
7536        *pProgress = 99;
7537    }
7538
7539    /**
7540    * Increment CTS for next step */
7541    if( pC->novideo == M4OSA_FALSE )
7542    {
7543        if( pC->EncodingVideoFormat == M4ENCODER_kNULL )
7544        {
7545           pC->dViDecCurrentCts +=  1;
7546        }
7547        else
7548        {
7549            pC->dViDecCurrentCts += pC->dCtsIncrement;
7550        }
7551    }
7552
7553    /**
7554    * The transcoding is finished when no stream is being encoded anymore */
7555    if( ( ( pC->novideo) || (M4MCS_kStreamState_FINISHED == pC->VideoState))
7556        && (( pC->noaudio) || (M4MCS_kStreamState_FINISHED == pC->AudioState)) )
7557    {
7558        /* the AIR part can only be used when video codecs are compiled*/
7559#ifndef M4MCS_AUDIOONLY
7560        /* clean AIR context needed to keep media aspect ratio*/
7561
7562        if( M4OSA_NULL != pC->m_air_context )
7563        {
7564            err = M4AIR_cleanUp(pC->m_air_context);
7565
7566            if( err != M4NO_ERROR )
7567            {
7568                M4OSA_TRACE1_1(
7569                    "M4xVSS_PictureCallbackFct: Error when cleaning AIR: 0x%x",
7570                    err);
7571                return err;
7572            }
7573            pC->m_air_context = M4OSA_NULL;
7574        }
7575
7576#endif /*M4MCS_AUDIOONLY*/
7577        /**/
7578
7579        *pProgress = 100;
7580        pC->State = M4MCS_kState_FINISHED;
7581        M4OSA_TRACE2_0(
7582            "M4MCS_intStepEncoding(): transcoding finished, returning M4MCS_WAR_TRANSCODING_DONE");
7583        return M4MCS_WAR_TRANSCODING_DONE;
7584    }
7585
7586    /**
7587    * Return with no error */
7588    M4OSA_TRACE3_0("M4MCS_intStepEncoding(): returning M4NO_ERROR");
7589    return M4NO_ERROR;
7590}
7591
7592/**
7593 ******************************************************************************
7594 * M4OSA_ERR M4MCS_intStepBeginVideoJump(M4MCS_InternalContext* pC)
7595 ******************************************************************************
7596 */
7597static M4OSA_ERR M4MCS_intStepBeginVideoJump( M4MCS_InternalContext *pC )
7598{
7599    M4OSA_ERR err;
7600    M4OSA_Int32 iCts;
7601
7602    if( pC->novideo )
7603    {
7604        pC->State = M4MCS_kState_BEGINVIDEODECODE;
7605        return M4NO_ERROR;
7606    }
7607
7608    /**
7609    * Jump to the previous RAP in the clip (first get the time, then jump) */
7610    iCts = (M4OSA_Int32)pC->dViDecStartingCts;
7611    err = pC->m_pReader->m_pFctGetPrevRapTime(pC->pReaderContext,
7612        (M4_StreamHandler *)pC->pReaderVideoStream, &iCts);
7613
7614    if( M4WAR_READER_INFORMATION_NOT_PRESENT == err )
7615    {
7616        /* No RAP table, jump backward and predecode */
7617        iCts = (M4OSA_Int32)pC->dViDecStartingCts - M4MCS_NO_STSS_JUMP_POINT;
7618
7619        if( iCts < 0 )
7620            iCts = 0;
7621    }
7622    else if( M4NO_ERROR != err )
7623    {
7624        M4OSA_TRACE1_1(
7625            "M4MCS_intStepBeginVideoJump: m_pFctGetPrevRapTime returns 0x%x!",
7626            err);
7627        return err;
7628    }
7629
7630    /* + CRLV6775 -H.264 Trimming */
7631
7632    if( M4OSA_TRUE == pC->bH264Trim )
7633    {
7634
7635        // Save jump time for safety, this fix should be generic
7636
7637        M4OSA_Int32 iCtsOri = iCts;
7638
7639
7640        err = pC->m_pReader->m_pFctJump(pC->pReaderContext,
7641            (M4_StreamHandler *)pC->pReaderVideoStream, &iCts);
7642
7643        if( M4NO_ERROR != err )
7644        {
7645            M4OSA_TRACE1_1(
7646                "M4MCS_intStepBeginVideoJump: m_pFctJump(V) returns 0x%x!",
7647                err);
7648            return err;
7649        }
7650
7651        if( pC->ReaderVideoAU1.m_structSize == 0 )
7652        {
7653            /**
7654            * Initializes an access Unit */
7655            err = pC->m_pReader->m_pFctFillAuStruct(pC->pReaderContext,
7656                (M4_StreamHandler *)pC->pReaderVideoStream,
7657                &pC->ReaderVideoAU1);
7658
7659            if( M4NO_ERROR != err )
7660            {
7661                M4OSA_TRACE1_1(
7662                    "M4MCS_open(): m_pReader->m_pFctFillAuStruct(video) returns 0x%x",
7663                    err);
7664                return err;
7665            }
7666            err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
7667                (M4_StreamHandler *)pC->pReaderVideoStream,
7668                &pC->ReaderVideoAU1);
7669
7670            if( M4WAR_NO_MORE_AU == err )
7671            {
7672                M4OSA_TRACE2_0(
7673                    "M4MCS_intVideoNullEncoding(): \
7674                    m_pReaderDataIt->m_pFctGetNextAu(video) returns M4WAR_NO_MORE_AU");
7675                /* The audio transcoding is finished */
7676                pC->VideoState = M4MCS_kStreamState_FINISHED;
7677                return err;
7678            }
7679            else if( M4NO_ERROR != err )
7680            {
7681                M4OSA_TRACE1_1(
7682                    "M4MCS_intVideoNullEncoding():\
7683                     m_pReaderDataIt->m_pFctGetNextAu(video) returns 0x%x",
7684                    err);
7685                return err;
7686            }
7687
7688            pC->ReaderVideoAU1.m_structSize = 0;
7689        }
7690
7691        err = H264MCS_ProcessSPS_PPS(pC->m_pInstance,
7692            (M4OSA_UInt8 *)pC->ReaderVideoAU1.m_dataAddress, pC->ReaderVideoAU1.m_size);
7693
7694        if( M4NO_ERROR != err )
7695        {
7696            M4OSA_TRACE1_1(
7697                "M4MCS_intStepBeginVideoJump: H264MCS_ProcessSPS_PPS returns 0x%x!",
7698                err);
7699            return err;
7700        }
7701
7702
7703        // Restore jump time for safety, this fix should be generic
7704
7705        iCts = iCtsOri;
7706
7707
7708    }
7709    /* - CRLV6775 -H.264 Trimming */
7710    err = pC->m_pReader->m_pFctJump(pC->pReaderContext,
7711        (M4_StreamHandler *)pC->pReaderVideoStream, &iCts);
7712
7713    if( M4NO_ERROR != err )
7714    {
7715        M4OSA_TRACE1_1(
7716            "M4MCS_intStepBeginVideoJump: m_pFctJump(V) returns 0x%x!", err);
7717        return err;
7718    }
7719
7720    /**
7721    * Decode one step */
7722    pC->dViDecCurrentCts = (M4OSA_Double)(iCts + pC->iVideoBeginDecIncr);
7723
7724    /**
7725    * Be sure we don't decode too far */
7726    if( pC->dViDecCurrentCts > pC->dViDecStartingCts )
7727    {
7728        pC->dViDecCurrentCts = pC->dViDecStartingCts;
7729    }
7730
7731    /**
7732    * Decode at least once with the bJump flag to true */
7733    M4OSA_TRACE3_1(
7734        "M4VSS3GPP_intClipDecodeVideoUpToCts: Decoding upTo CTS %.3f",
7735        pC->dViDecCurrentCts);
7736    pC->isRenderDup = M4OSA_FALSE;
7737    err =
7738        pC->m_pVideoDecoder->m_pFctDecode(pC->pViDecCtxt, &pC->dViDecCurrentCts,
7739        M4OSA_TRUE);
7740
7741    if( ( M4NO_ERROR != err) && (M4WAR_NO_MORE_AU != err)
7742        && (err != M4WAR_VIDEORENDERER_NO_NEW_FRAME) )
7743    {
7744        M4OSA_TRACE1_1(
7745            "M4MCS_intStepBeginVideoJump: m_pFctDecode returns 0x%x!", err);
7746        return err;
7747    }
7748
7749    if( err == M4WAR_VIDEORENDERER_NO_NEW_FRAME )
7750    {
7751        M4OSA_TRACE2_0("Decoding output the same frame as before 1");
7752        pC->isRenderDup = M4OSA_TRUE;
7753    }
7754
7755    /**
7756    * Increment decoding cts for the next step */
7757    pC->dViDecCurrentCts += (M4OSA_Double)pC->iVideoBeginDecIncr;
7758
7759    /**
7760    * Update state automaton */
7761    if( pC->dViDecCurrentCts > pC->dViDecStartingCts )
7762    {
7763        /**
7764        * Be sure we don't decode too far */
7765        pC->dViDecCurrentCts = pC->dViDecStartingCts;
7766        pC->State = M4MCS_kState_PROCESSING;
7767    }
7768    else
7769    {
7770        pC->State = M4MCS_kState_BEGINVIDEODECODE;
7771    }
7772
7773    /**
7774    * Return with no error */
7775    M4OSA_TRACE3_0("M4MCS_intStepBeginVideoJump(): returning M4NO_ERROR");
7776    return M4NO_ERROR;
7777}
7778
7779/**
7780 ******************************************************************************
7781 * M4OSA_ERR M4MCS_intStepBeginVideoDecode(M4MCS_InternalContext* pC)
7782 ******************************************************************************
7783 */
7784static M4OSA_ERR M4MCS_intStepBeginVideoDecode( M4MCS_InternalContext *pC )
7785{
7786    M4OSA_ERR err;
7787    M4_MediaTime dDecTarget;
7788
7789    if( pC->novideo )
7790    {
7791        pC->State = M4MCS_kState_PROCESSING;
7792        return M4NO_ERROR;
7793    }
7794
7795    /**
7796    * Decode */
7797    dDecTarget = pC->dViDecCurrentCts;
7798    M4OSA_TRACE3_1("M4MCS_intStepBeginDecode: Decoding upTo CTS %.3f",
7799        pC->dViDecCurrentCts);
7800    pC->isRenderDup = M4OSA_FALSE;
7801    err = pC->m_pVideoDecoder->m_pFctDecode(pC->pViDecCtxt, &dDecTarget,
7802        M4OSA_FALSE);
7803
7804    if( ( M4NO_ERROR != err) && (M4WAR_NO_MORE_AU != err)
7805        && (err != M4WAR_VIDEORENDERER_NO_NEW_FRAME) )
7806    {
7807        M4OSA_TRACE1_1(
7808            "M4MCS_intStepBeginVideoDecode: m_pFctDecode returns 0x%x!", err);
7809        return err;
7810    }
7811
7812    if( err == M4WAR_VIDEORENDERER_NO_NEW_FRAME )
7813    {
7814        M4OSA_TRACE2_0("Decoding output the same frame as before 2");
7815        pC->isRenderDup = M4OSA_TRUE;
7816    }
7817
7818    /**
7819    * Increment decoding cts for the next step */
7820    pC->dViDecCurrentCts += (M4OSA_Double)pC->iVideoBeginDecIncr;
7821
7822    /**
7823    * Update state automaton, if needed */
7824    if( ( (M4OSA_UInt32)pC->dViDecCurrentCts > pC->dViDecStartingCts)
7825        || (M4WAR_NO_MORE_AU == err) )
7826    {
7827        /**
7828        * Be sure we don't decode too far */
7829        pC->dViDecCurrentCts = (M4OSA_Double)pC->dViDecStartingCts;
7830        pC->State = M4MCS_kState_PROCESSING;
7831    }
7832
7833    /**
7834    * Return with no error */
7835    M4OSA_TRACE3_0("M4MCS_intStepBeginVideoDecode(): returning M4NO_ERROR");
7836    return M4NO_ERROR;
7837}
7838
7839/*****************************/
7840/* define AMR silence frames */
7841/*****************************/
7842
7843#define M4VSS3GPP_AMR_AU_SILENCE_FRAME_048_SIZE 13
7844#define M4VSS3GPP_AMR_AU_SILENCE_FRAME_048_DURATION 160
7845
7846#ifdef M4VSS3GPP_SILENCE_FRAMES
7847
7848const M4OSA_UInt8 M4VSS3GPP_AMR_AU_SILENCE_FRAME_048[
7849    M4VSS3GPP_AMR_AU_SILENCE_FRAME_048_SIZE] =
7850    {
7851        0x04, 0xFF, 0x18, 0xC7, 0xF0, 0x0D, 0x04, 0x33, 0xFF, 0xE0, 0x00, 0x00, 0x00
7852    };
7853#else
7854
7855extern
7856const
7857M4OSA_UInt8
7858M4VSS3GPP_AMR_AU_SILENCE_FRAME_048[M4VSS3GPP_AMR_AU_SILENCE_FRAME_048_SIZE];
7859
7860#endif
7861
7862/*****************************/
7863/* define AAC silence frames */
7864/*****************************/
7865
7866#define M4VSS3GPP_AAC_AU_SILENCE_MONO_SIZE      4
7867
7868#ifdef M4VSS3GPP_SILENCE_FRAMES
7869
7870const M4OSA_UInt8 M4VSS3GPP_AAC_AU_SILENCE_MONO[
7871    M4VSS3GPP_AAC_AU_SILENCE_MONO_SIZE] =
7872    {
7873        0x00, 0xC8, 0x20, 0x07
7874    };
7875#else
7876
7877extern const M4OSA_UInt8
7878M4VSS3GPP_AAC_AU_SILENCE_MONO[M4VSS3GPP_AAC_AU_SILENCE_MONO_SIZE];
7879
7880#endif
7881
7882#define M4VSS3GPP_AAC_AU_SILENCE_STEREO_SIZE        6
7883
7884#ifdef M4VSS3GPP_SILENCE_FRAMES
7885
7886const M4OSA_UInt8 M4VSS3GPP_AAC_AU_SILENCE_STEREO[
7887    M4VSS3GPP_AAC_AU_SILENCE_STEREO_SIZE] =
7888    {
7889        0x21, 0x10, 0x03, 0x20, 0x54, 0x1C
7890    };
7891#else
7892
7893extern const
7894M4OSA_UInt8
7895M4VSS3GPP_AAC_AU_SILENCE_STEREO[M4VSS3GPP_AAC_AU_SILENCE_STEREO_SIZE];
7896
7897#endif
7898
7899/**
7900 ******************************************************************************
7901 * M4OSA_ERR M4MCS_intAudioNullEncoding(M4MCS_InternalContext* pC)
7902 * @return   M4NO_ERROR:         No error
7903 ******************************************************************************
7904 */
7905
7906static M4OSA_ERR M4MCS_intAudioNullEncoding( M4MCS_InternalContext *pC )
7907{
7908    M4OSA_ERR err;
7909
7910    if( pC->noaudio )
7911        return M4NO_ERROR;
7912
7913    /* Check if all audio frame has been written (happens at begin cut) */
7914    if( pC->ReaderAudioAU.m_size == 0 )
7915    {
7916        /**
7917        * Initializes a new AU if needed */
7918        if( pC->ReaderAudioAU1.m_structSize == 0 )
7919        {
7920            /**
7921            * Initializes an access Unit */
7922            err = pC->m_pReader->m_pFctFillAuStruct(pC->pReaderContext,
7923                (M4_StreamHandler *)pC->pReaderAudioStream,
7924                &pC->ReaderAudioAU1);
7925
7926            if( M4NO_ERROR != err )
7927            {
7928                M4OSA_TRACE1_1(
7929                    "M4MCS_open(): m_pReader->m_pFctFillAuStruct(audio) returns 0x%x",
7930                    err);
7931                return err;
7932            }
7933
7934            pC->m_pDataAddress1 =
7935                (M4OSA_MemAddr8)M4OSA_malloc(pC->ReaderAudioAU1.m_maxsize,
7936                M4MCS, (M4OSA_Char *)"Temporary AU1 buffer");
7937
7938            if( pC->m_pDataAddress1 == M4OSA_NULL )
7939            {
7940                M4OSA_TRACE1_0(
7941                    "M4MCS_intAudioNullEncoding(): allocation error");
7942                return M4ERR_ALLOC;
7943            }
7944
7945            err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
7946                (M4_StreamHandler *)pC->pReaderAudioStream,
7947                &pC->ReaderAudioAU1);
7948
7949            if( M4WAR_NO_MORE_AU == err )
7950            {
7951                M4OSA_TRACE2_0(
7952                    "M4MCS_intAudioNullEncoding():\
7953                     m_pReaderDataIt->m_pFctGetNextAu(audio) returns M4WAR_NO_MORE_AU");
7954                /* The audio transcoding is finished */
7955                pC->AudioState = M4MCS_kStreamState_FINISHED;
7956                return err;
7957            }
7958            else if( M4NO_ERROR != err )
7959            {
7960                M4OSA_TRACE1_1(
7961                    "M4MCS_intAudioNullEncoding(): \
7962                    m_pReaderDataIt->m_pFctGetNextAu(Audio) returns 0x%x",
7963                    err);
7964                return err;
7965            }
7966            /*FB 2009.04.02: PR surnxp#616: Crash in MCS while Audio AU copying ,
7967             constant memory reader case*/
7968            if( pC->ReaderAudioAU1.m_maxsize
7969        > pC->pReaderAudioStream->m_basicProperties.m_maxAUSize )
7970            {
7971                /* Constant memory reader case, we need to reallocate the temporary buffers */
7972                M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
7973                    *) &(pC->m_pDataAddress1), pC->ReaderAudioAU1.m_maxsize);
7974                /* pC->m_pDataAddress1 and
7975                pC->m_pDataAddress2 must be reallocated at the same time */
7976                /* because pC->pReaderAudioStream->m_basicProperties.m_maxAUSize take
7977                 maximum value. Then the test "if(pC->ReaderAudioAU?.m_maxsize >
7978                  pC->pReaderAudioStream->m_basicProperties.m_maxAUSize)" is never true */
7979                /* and the size of the second buffer is never changed. */
7980                M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
7981                    *) &(pC->m_pDataAddress2), pC->ReaderAudioAU1.m_maxsize);
7982                /* pC->m_pDataAddress1 and
7983                pC->m_pDataAddress2 must be reallocated at the same time */
7984                /* Update stream properties */
7985                pC->pReaderAudioStream->m_basicProperties.m_maxAUSize =
7986                    pC->ReaderAudioAU1.m_maxsize;
7987            }
7988            /**/
7989            memcpy((void *)pC->m_pDataAddress1,
7990                (void *)pC->ReaderAudioAU1.m_dataAddress,
7991                pC->ReaderAudioAU1.m_size);
7992        }
7993
7994        if( pC->ReaderAudioAU2.m_structSize == 0 )
7995        {
7996            /**
7997            * Initializes an access Unit */
7998            err = pC->m_pReader->m_pFctFillAuStruct(pC->pReaderContext,
7999                (M4_StreamHandler *)pC->pReaderAudioStream,
8000                &pC->ReaderAudioAU2);
8001
8002            if( M4NO_ERROR != err )
8003            {
8004                M4OSA_TRACE1_1(
8005                    "M4MCS_open(): m_pReader->m_pFctFillAuStruct(audio) returns 0x%x",
8006                    err);
8007                return err;
8008            }
8009            pC->m_pDataAddress2 =
8010                (M4OSA_MemAddr8)M4OSA_malloc(pC->ReaderAudioAU2.m_maxsize,
8011                M4MCS, (M4OSA_Char *)"Temporary AU buffer");
8012
8013            if( pC->m_pDataAddress2 == M4OSA_NULL )
8014            {
8015                M4OSA_TRACE1_0(
8016                    "M4MCS_intAudioNullEncoding(): allocation error");
8017                return M4ERR_ALLOC;
8018            }
8019        }
8020        /**
8021        * Read the next audio AU in the input file */
8022        if( pC->ReaderAudioAU2.m_CTS > pC->ReaderAudioAU1.m_CTS )
8023        {
8024            memcpy((void *) &pC->ReaderAudioAU,
8025                (void *) &pC->ReaderAudioAU2, sizeof(M4_AccessUnit));
8026            err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
8027                (M4_StreamHandler *)pC->pReaderAudioStream,
8028                &pC->ReaderAudioAU1);
8029
8030            if( pC->ReaderAudioAU1.m_maxsize
8031                > pC->pReaderAudioStream->m_basicProperties.m_maxAUSize )
8032            {
8033                /* Constant memory reader case, we need to reallocate the temporary buffers */
8034                M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
8035                    *) &(pC->m_pDataAddress1), pC->ReaderAudioAU1.m_maxsize);
8036                /*   pC->m_pDataAddress1
8037                 * and pC->m_pDataAddress2 must be reallocated at the same time *
8038                 * because pC->pReaderAudioStream->m_basicProperties.m_maxAUSize take
8039                 * maximum value. Then the test "if(pC->ReaderAudioAU?.m_maxsize >
8040                 * pC->pReaderAudioStream->m_basicProperties.m_maxAUSize)" is never true *
8041                 * and the size of the second buffer is never changed.
8042                 */
8043                M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
8044                    *) &(pC->m_pDataAddress2), pC->ReaderAudioAU1.m_maxsize);
8045                /* pC->m_pDataAddress1 and
8046                 * pC->m_pDataAddress2 must be reallocated at the same time
8047                 * Update stream properties
8048                 */
8049                pC->pReaderAudioStream->m_basicProperties.m_maxAUSize =
8050                    pC->ReaderAudioAU1.m_maxsize;
8051            }
8052            /**/
8053            memcpy((void *)pC->m_pDataAddress1,
8054                (void *)pC->ReaderAudioAU1.m_dataAddress,
8055                pC->ReaderAudioAU1.m_size);
8056            pC->m_audioAUDuration =
8057                pC->ReaderAudioAU1.m_CTS - pC->ReaderAudioAU2.m_CTS;
8058            pC->ReaderAudioAU.m_dataAddress = pC->m_pDataAddress2;
8059        }
8060        else
8061        {
8062            memcpy((void *) &pC->ReaderAudioAU,
8063                (void *) &pC->ReaderAudioAU1, sizeof(M4_AccessUnit));
8064            err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
8065                (M4_StreamHandler *)pC->pReaderAudioStream,
8066                &pC->ReaderAudioAU2);
8067            /* Crash in MCS while Audio AU copying ,
8068             * constant memory reader case
8069             */
8070            if( pC->ReaderAudioAU2.m_maxsize
8071                > pC->pReaderAudioStream->m_basicProperties.m_maxAUSize )
8072            {
8073                /* Constant memory reader case, we need to reallocate the temporary buffers */
8074                M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
8075                    *) &(pC->m_pDataAddress2), pC->ReaderAudioAU2.m_maxsize);
8076                /* pC->m_pDataAddress1 and
8077                 * pC->m_pDataAddress2 must be reallocated at the same time
8078                 * because pC->pReaderAudioStream->m_basicProperties.m_maxAUSize take maximum
8079                 * value. Then the test "if(pC->ReaderAudioAU?.m_maxsize > pC->pReaderAudioStream->
8080                 * m_basicProperties.m_maxAUSize)" is never true
8081                 * and the size of the second buffer is never changed.
8082                 */
8083                M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
8084                    *) &(pC->m_pDataAddress1), pC->ReaderAudioAU2.m_maxsize);
8085                /* [ END ] 20091008  JFV PR fix surnxpsw#1071: pC->m_pDataAddress1 and
8086                 pC->m_pDataAddress2 must be reallocated at the same time */
8087                /* Update stream properties */
8088                pC->pReaderAudioStream->m_basicProperties.m_maxAUSize =
8089                    pC->ReaderAudioAU2.m_maxsize;
8090            }
8091            /**/
8092            memcpy((void *)pC->m_pDataAddress2,
8093                (void *)pC->ReaderAudioAU2.m_dataAddress,
8094                pC->ReaderAudioAU2.m_size);
8095            pC->m_audioAUDuration =
8096                pC->ReaderAudioAU2.m_CTS - pC->ReaderAudioAU1.m_CTS;
8097            pC->ReaderAudioAU.m_dataAddress = pC->m_pDataAddress1;
8098        }
8099
8100        if( M4WAR_NO_MORE_AU == err )
8101        {
8102            M4OSA_TRACE2_0(
8103                "M4MCS_intAudioNullEncoding(): \
8104                m_pReaderDataIt->m_pFctGetNextAu(audio) returns M4WAR_NO_MORE_AU");
8105            /* The audio transcoding is finished */
8106            pC->AudioState = M4MCS_kStreamState_FINISHED;
8107            return err;
8108        }
8109        else if( M4NO_ERROR != err )
8110        {
8111            M4OSA_TRACE1_1(
8112                "M4MCS_intAudioNullEncoding(): \
8113                m_pReaderDataIt->m_pFctGetNextAu(Audio) returns 0x%x",
8114                err);
8115            return err;
8116        }
8117    }
8118
8119    /**
8120    * Prepare the writer AU */
8121    err = pC->pWriterDataFcts->pStartAU(pC->pWriterContext,
8122        M4MCS_WRITER_AUDIO_STREAM_ID, &pC->WriterAudioAU);
8123
8124    if( M4NO_ERROR != err )
8125    {
8126        M4OSA_TRACE1_1(
8127            "M4MCS_intAudioNullEncoding(): pWriterDataFcts->pStartAU(Audio) returns 0x%x",
8128            err);
8129        return err;
8130    }
8131
8132    if( pC->uiAudioAUCount
8133        == 0 ) /* If it is the first AU, we set it to silence
8134        (else, errors 0x3841, 0x3847 in our AAC decoder) */
8135    {
8136        if( pC->InputFileProperties.AudioStreamType == M4VIDEOEDITING_kAAC
8137            || pC->InputFileProperties.AudioStreamType
8138            == M4VIDEOEDITING_kAACplus
8139            || pC->InputFileProperties.AudioStreamType
8140            == M4VIDEOEDITING_keAACplus )
8141        {
8142            if( pC->InputFileProperties.uiNbChannels == 1 )
8143            {
8144                pC->WriterAudioAU.size = M4VSS3GPP_AAC_AU_SILENCE_MONO_SIZE;
8145                memcpy((void *)pC->WriterAudioAU.dataAddress,
8146                    (void *)M4VSS3GPP_AAC_AU_SILENCE_MONO,
8147                    pC->WriterAudioAU.size);
8148            }
8149            else if( pC->InputFileProperties.uiNbChannels == 2 )
8150            {
8151                pC->WriterAudioAU.size = M4VSS3GPP_AAC_AU_SILENCE_STEREO_SIZE;
8152                memcpy((void *)pC->WriterAudioAU.dataAddress,
8153                    (void *)M4VSS3GPP_AAC_AU_SILENCE_STEREO,
8154                    pC->WriterAudioAU.size);
8155            }
8156            else
8157            {
8158                /* Must never happen ...*/
8159                M4OSA_TRACE1_0(
8160                    "M4MCS_intAudioNullEncoding: Bad number of channels in audio input");
8161                return M4MCS_ERR_INVALID_INPUT_FILE;
8162            }
8163        }
8164        else if( pC->InputFileProperties.AudioStreamType
8165            == M4VIDEOEDITING_kAMR_NB )
8166        {
8167            pC->WriterAudioAU.size = M4VSS3GPP_AMR_AU_SILENCE_FRAME_048_SIZE;
8168            memcpy((void *)pC->WriterAudioAU.dataAddress,
8169                (void *)M4VSS3GPP_AMR_AU_SILENCE_FRAME_048,
8170                pC->WriterAudioAU.size);
8171            /* Some remaining AMR AU needs to be copied */
8172            if( pC->ReaderAudioAU.m_size != 0 )
8173            {
8174                /* Update Writer AU */
8175                pC->WriterAudioAU.size += pC->ReaderAudioAU.m_size;
8176                memcpy((void *)(pC->WriterAudioAU.dataAddress
8177                    + M4VSS3GPP_AMR_AU_SILENCE_FRAME_048_SIZE),
8178                    (void *)pC->ReaderAudioAU.m_dataAddress,
8179                    pC->ReaderAudioAU.m_size);
8180            }
8181        }
8182        else
8183        {
8184            /*MP3 case: copy the AU*/
8185            M4OSA_TRACE3_1(
8186                "M4MCS_intAudioNullEncoding(): Copying audio AU: size=%d",
8187                pC->ReaderAudioAU.m_size);
8188            memcpy((void *)pC->WriterAudioAU.dataAddress,
8189                (void *)pC->ReaderAudioAU.m_dataAddress,
8190                pC->ReaderAudioAU.m_size);
8191            pC->WriterAudioAU.size = pC->ReaderAudioAU.m_size;
8192        }
8193    }
8194    else
8195    {
8196        /**
8197        * Copy audio data from reader AU to writer AU */
8198        M4OSA_TRACE3_1(
8199            "M4MCS_intAudioNullEncoding(): Copying audio AU: size=%d",
8200            pC->ReaderAudioAU.m_size);
8201        memcpy((void *)pC->WriterAudioAU.dataAddress,
8202            (void *)pC->ReaderAudioAU.m_dataAddress,
8203            pC->ReaderAudioAU.m_size);
8204        pC->WriterAudioAU.size = pC->ReaderAudioAU.m_size;
8205    }
8206
8207    /**
8208    * Convert CTS unit from milliseconds to timescale */
8209    pC->WriterAudioAU.CTS =
8210        (M4OSA_Time)((( pC->ReaderAudioAU.m_CTS - pC->iAudioCtsOffset)
8211        * (pC->WriterAudioStream.timeScale / 1000.0)));
8212
8213    if( pC->InputFileProperties.AudioStreamType == M4VIDEOEDITING_kAMR_NB
8214        && pC->uiAudioAUCount == 0 )
8215    {
8216        pC->iAudioCtsOffset -=
8217            20; /* Duration of a silence AMR AU, to handle the duration of the added
8218                silence frame */
8219    }
8220    pC->WriterAudioAU.nbFrag = 0;
8221    M4OSA_TRACE3_1("M4MCS_intAudioNullEncoding(): audio AU: CTS=%d ms",
8222        pC->WriterAudioAU.CTS);
8223
8224    /**
8225    * Write it to the output file */
8226    pC->uiAudioAUCount++;
8227    err = pC->pWriterDataFcts->pProcessAU(pC->pWriterContext,
8228        M4MCS_WRITER_AUDIO_STREAM_ID, &pC->WriterAudioAU);
8229
8230    if( M4NO_ERROR != err )
8231    {
8232        M4OSA_TRACE1_1(
8233            "M4MCS_intAudioNullEncoding(): pWriterDataFcts->pProcessAU(Audio) returns 0x%x",
8234            err);
8235        return err;
8236    }
8237
8238    /* All the audio has been written */
8239    pC->ReaderAudioAU.m_size = 0;
8240
8241    /**
8242    * Return with no error */
8243    M4OSA_TRACE3_0("M4MCS_intAudioNullEncoding(): returning M4NO_ERROR");
8244    return M4NO_ERROR;
8245}
8246
8247/**
8248 ******************************************************************************
8249 * @brief    Init Audio Transcoding
8250 * @return   M4NO_ERROR:         No error
8251 ******************************************************************************
8252 */
8253static M4OSA_ERR M4MCS_intAudioTranscoding( M4MCS_InternalContext *pC )
8254{
8255    M4OSA_ERR err;                        /**< General error */
8256
8257    M4OSA_UInt32
8258        uiBytesDec; /**< Nb of bytes available in the decoder OUT buffer */
8259    M4OSA_UInt32
8260        uiDecoder2Ssrc_NbBytes; /**< Nb of bytes copied into the ssrc IN buffer */
8261
8262    int ssrcErr;                          /**< Error while ssrc processing */
8263    M4OSA_UInt32 uiSsrcInSize; /**< Size in bytes of ssrc intput buffer */
8264    M4OSA_UInt32
8265        uiSsrcInRoom; /**< Nb of bytes available in the ssrc IN buffer */
8266    M4OSA_MemAddr8
8267        pSsrcInput; /**< Pointer to the good buffer location for ssrc input */
8268    M4OSA_UInt32 uiSsrcOutSize; /**< Size in bytes of ssrc output buffer */
8269    M4OSA_UInt32
8270        uiBytesSsrc; /**< Nb of bytes available in the ssrc OUT buffer */
8271
8272    M4OSA_UInt8
8273        needChannelConversion; /**< Flag to indicate if a stereo <-> mono conversion is needed */
8274    M4OSA_UInt32
8275        uiChannelConvertorCoeff; /**< Multiplicative coefficient if stereo
8276                                    <-> mono conversion is applied */
8277    M4OSA_MemAddr8 pChannelConvertorInput =
8278        M4OSA_NULL; /**< Pointer to the good buffer location for channel convertor input */
8279    M4OSA_UInt32 uiChannelConvertorNbSamples =
8280        0; /**< Nb of pcm samples to convert in channel convertor */
8281    M4OSA_MemAddr8 pChannelConvertorOutput =
8282        M4OSA_NULL; /**< Pointer to the good buffer location for channel convertor output */
8283
8284    M4OSA_Time
8285        frameTimeDelta; /**< Duration of the encoded (then written) data */
8286    M4OSA_UInt32
8287        uiEncoderInRoom; /**< Nb of bytes available in the encoder IN buffer */
8288    M4OSA_UInt32
8289        uiSsrc2Encoder_NbBytes; /**< Nb of bytes copied from the ssrc OUT buffer */
8290    M4OSA_MemAddr8
8291        pEncoderInput; /**< Pointer to the good buffer location for encoder input */
8292    M4ENCODER_AudioBuffer pEncInBuffer;   /**< Encoder input buffer for api */
8293    M4ENCODER_AudioBuffer pEncOutBuffer;  /**< Encoder output buffer for api */
8294
8295    M4OSA_Int16 *tempBuffOut = M4OSA_NULL;
8296    /*FlB 2009.03.04: apply audio effects if an effect is active*/
8297    M4OSA_Int8 *pActiveEffectNumber = &(pC->pActiveEffectNumber);
8298
8299    if( pC->noaudio )
8300        return M4NO_ERROR;
8301
8302    /* _________________ */
8303    /*|                 |*/
8304    /*| READ AND DECODE |*/
8305    /*|_________________|*/
8306
8307    /* Check if we have to empty the decoder out buffer first */
8308    if( M4OSA_NULL != pC->pPosInDecBufferOut )
8309    {
8310        goto m4mcs_intaudiotranscoding_feed_resampler;
8311    }
8312
8313    /* Check if all audio frame has been decoded */
8314    if( pC->ReaderAudioAU.m_size == 0 )
8315    {
8316        /**
8317        * Read the next audio AU in the input file */
8318        err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
8319            (M4_StreamHandler *)pC->pReaderAudioStream, &pC->ReaderAudioAU);
8320
8321#ifdef MCS_DUMP_PCM_TO_FILE
8322
8323        fwrite(pC->ReaderAudioAU.m_dataAddress, pC->ReaderAudioAU.m_size, 1,
8324            file_au_reader);
8325        fwrite("____", 4, 1, file_au_reader);
8326
8327#endif
8328
8329        if( M4WAR_NO_MORE_AU == err ) /**< The audio transcoding is finished */
8330        {
8331            pC->AudioState = M4MCS_kStreamState_FINISHED;
8332            M4OSA_TRACE2_0(
8333                "M4MCS_intAudioTranscoding():\
8334                 m_pReaderDataIt->m_pFctGetNextAu(audio) returns M4WAR_NO_MORE_AU");
8335            return err;
8336        }
8337        else if( M4NO_ERROR != err )
8338        {
8339            M4OSA_TRACE1_1(
8340                "M4MCS_intAudioTranscoding():\
8341                 m_pReaderDataIt->m_pFctGetNextAu(Audio) returns 0x%x",
8342                err);
8343            return err;
8344        }
8345    }
8346
8347    /**
8348    * Decode the AU */
8349    pC->AudioDecBufferIn.m_dataAddress = pC->ReaderAudioAU.m_dataAddress;
8350    pC->AudioDecBufferIn.m_bufferSize = pC->ReaderAudioAU.m_size;
8351
8352    err = pC->m_pAudioDecoder->m_pFctStepAudioDec(pC->pAudioDecCtxt,
8353        &pC->AudioDecBufferIn, &pC->AudioDecBufferOut, M4OSA_FALSE);
8354
8355    if( M4NO_ERROR != err )
8356    {
8357        M4OSA_TRACE1_1(
8358            "M4MCS_intAudioTranscoding(): m_pAudioDecoder->m_pFctStepAudio returns 0x%x",
8359            err);
8360        return err;
8361    }
8362
8363#ifdef MCS_DUMP_PCM_TO_FILE
8364
8365    fwrite(pC->AudioDecBufferOut.m_dataAddress,
8366        pC->AudioDecBufferOut.m_bufferSize, 1, file_pcm_decoder);
8367
8368#endif
8369
8370    /* update the part of audio that has been decoded into the frame */
8371
8372    pC->ReaderAudioAU.m_dataAddress += pC->AudioDecBufferIn.m_bufferSize;
8373    pC->ReaderAudioAU.m_size -= pC->AudioDecBufferIn.m_bufferSize;
8374
8375    /* Set the current position in the decoder out buffer */
8376    pC->pPosInDecBufferOut = pC->AudioDecBufferOut.m_dataAddress;
8377
8378    /* ________________ */
8379    /*|                |*/
8380    /*| FEED RESAMPLER |*/
8381    /*|________________|*/
8382
8383m4mcs_intaudiotranscoding_feed_resampler:
8384
8385    /* Check if we have to empty the ssrc out buffer first */
8386    if( M4OSA_NULL != pC->pPosInSsrcBufferOut )
8387    {
8388        goto m4mcs_intaudiotranscoding_prepare_input_buffer;
8389    }
8390
8391    /* Compute number of bytes remaining in the decoder buffer */
8392    uiSsrcInSize = pC->iSsrcNbSamplIn * sizeof(short)
8393        * pC->pReaderAudioStream->m_nbChannels;
8394    uiBytesDec = ( pC->AudioDecBufferOut.m_dataAddress
8395        + pC->AudioDecBufferOut.m_bufferSize) - pC->pPosInDecBufferOut;
8396
8397    /* Check if we can feed directly the Ssrc with the decoder out buffer */
8398    if( ( pC->pPosInSsrcBufferIn == pC->pSsrcBufferIn)
8399        && (uiBytesDec >= uiSsrcInSize) )
8400    {
8401        pSsrcInput = pC->pPosInDecBufferOut;
8402
8403        /* update data consumed into decoder buffer after resampling */
8404        if( uiBytesDec == uiSsrcInSize )
8405            pC->pPosInDecBufferOut = M4OSA_NULL;
8406        else
8407            pC->pPosInDecBufferOut += uiSsrcInSize;
8408
8409        goto m4mcs_intaudiotranscoding_do_resampling;
8410    }
8411
8412    /**
8413    * Compute remaining space in Ssrc buffer in */
8414    uiSsrcInRoom = ( pC->pSsrcBufferIn + uiSsrcInSize) - pC->pPosInSsrcBufferIn;
8415
8416    /**
8417    * Nb of bytes copied is the minimum between nb of bytes remaining in
8418    * decoder out buffer and space remaining in ssrc in buffer */
8419    uiDecoder2Ssrc_NbBytes =
8420        (uiSsrcInRoom < uiBytesDec) ? uiSsrcInRoom : uiBytesDec;
8421
8422    /**
8423    * Copy from the decoder out buffer into the Ssrc in buffer */
8424    memcpy((void *)pC->pPosInSsrcBufferIn, (void *)pC->pPosInDecBufferOut,
8425        uiDecoder2Ssrc_NbBytes);
8426
8427    /**
8428    * Update the position in the decoder out buffer */
8429    pC->pPosInDecBufferOut += uiDecoder2Ssrc_NbBytes;
8430
8431    /**
8432    * Update the position in the Ssrc in buffer */
8433    pC->pPosInSsrcBufferIn += uiDecoder2Ssrc_NbBytes;
8434
8435    /**
8436    * Check if the decoder buffer out is empty */
8437    if( ( pC->pPosInDecBufferOut - pC->AudioDecBufferOut.m_dataAddress)
8438        == (M4OSA_Int32)pC->AudioDecBufferOut.m_bufferSize )
8439    {
8440        pC->pPosInDecBufferOut = M4OSA_NULL;
8441    }
8442
8443    /* Check if the Ssrc in buffer is ready (= full) */
8444    if( ( pC->pPosInSsrcBufferIn - pC->pSsrcBufferIn)
8445        < (M4OSA_Int32)uiSsrcInSize )
8446    {
8447        goto m4mcs_intaudiotranscoding_end;
8448    }
8449
8450    pSsrcInput = pC->pSsrcBufferIn;
8451
8452    /* update data consumed into ssrc buffer in after resampling (empty) */
8453    pC->pPosInSsrcBufferIn = pC->pSsrcBufferIn;
8454
8455    /* ___________________ */
8456    /*|                   |*/
8457    /*| DO THE RESAMPLING |*/
8458    /*|___________________|*/
8459
8460m4mcs_intaudiotranscoding_do_resampling:
8461
8462    /**
8463    * No need for memcopy, we can feed Ssrc directly with the data in the audio
8464    decoder out buffer*/
8465
8466    ssrcErr = 0;
8467
8468    if( pC->pReaderAudioStream->m_nbChannels == 1 )
8469    {
8470        tempBuffOut =
8471            (short *)M4OSA_malloc((pC->iSsrcNbSamplOut * sizeof(short) * 2
8472            * ((*pC).InputFileProperties).uiNbChannels),
8473            M4VSS3GPP,(M4OSA_Char *) "tempBuffOut");
8474        memset((void *)tempBuffOut, 0,(pC->iSsrcNbSamplOut * sizeof(short) * 2
8475            * ((*pC).InputFileProperties).uiNbChannels));
8476
8477        LVAudioresample_LowQuality((short *)tempBuffOut, (short *)pSsrcInput,
8478            pC->iSsrcNbSamplOut, pC->pLVAudioResampler);
8479    }
8480    else
8481    {
8482        memset((void *)pC->pSsrcBufferOut, 0, (pC->iSsrcNbSamplOut * sizeof(short)
8483            * ((*pC).InputFileProperties).uiNbChannels));
8484
8485        LVAudioresample_LowQuality((short *)pC->pSsrcBufferOut,
8486            (short *)pSsrcInput, pC->iSsrcNbSamplOut, pC->pLVAudioResampler);
8487    }
8488
8489    if( pC->pReaderAudioStream->m_nbChannels == 1 )
8490    {
8491        From2iToMono_16((short *)tempBuffOut, (short *)pC->pSsrcBufferOut,
8492            (short)pC->iSsrcNbSamplOut);
8493        M4OSA_free((M4OSA_MemAddr32)tempBuffOut);
8494    }
8495
8496
8497    if( 0 != ssrcErr )
8498    {
8499        M4OSA_TRACE1_1(
8500            "M4MCS_intAudioTranscoding: SSRC_Process returns 0x%x, \
8501            returning M4MCS_ERR_AUDIO_CONVERSION_FAILED",
8502            ssrcErr);
8503        return M4MCS_ERR_AUDIO_CONVERSION_FAILED;
8504    }
8505
8506    pC->pPosInSsrcBufferOut = pC->pSsrcBufferOut;
8507
8508    /* ______________________ */
8509    /*|                      |*/
8510    /*| PREPARE INPUT BUFFER |*/
8511    /*|______________________|*/
8512
8513m4mcs_intaudiotranscoding_prepare_input_buffer:
8514
8515    /* Set the flag for channel conversion requirement */
8516    if( ( pC->AudioEncParams.ChannelNum == M4ENCODER_kMono)
8517        && (pC->pReaderAudioStream->m_nbChannels == 2) )
8518    {
8519        needChannelConversion = 1;
8520        uiChannelConvertorCoeff = 4;
8521    }
8522    else if( ( pC->AudioEncParams.ChannelNum == M4ENCODER_kStereo)
8523        && (pC->pReaderAudioStream->m_nbChannels == 1) )
8524    {
8525        needChannelConversion = 2;
8526        uiChannelConvertorCoeff = 1;
8527    }
8528    else
8529    {
8530        needChannelConversion = 0;
8531        uiChannelConvertorCoeff = 2;
8532    }
8533
8534    /* Compute number of bytes remaining in the Ssrc buffer */
8535    uiSsrcOutSize = pC->iSsrcNbSamplOut * sizeof(short)
8536        * pC->pReaderAudioStream->m_nbChannels;
8537    uiBytesSsrc =
8538        ( pC->pSsrcBufferOut + uiSsrcOutSize) - pC->pPosInSsrcBufferOut;
8539
8540    /* Check if the ssrc buffer is full */
8541    if( pC->pPosInSsrcBufferOut == pC->pSsrcBufferOut )
8542    {
8543        uiSsrc2Encoder_NbBytes =
8544            pC->audioEncoderGranularity * uiChannelConvertorCoeff / 2;
8545
8546        /* Check if we can feed directly the encoder with the ssrc out buffer */
8547        if( ( pC->pPosInAudioEncoderBuffer == M4OSA_NULL)
8548            && (uiBytesSsrc >= uiSsrc2Encoder_NbBytes) )
8549        {
8550            /* update position in ssrc out buffer after encoding */
8551            if( uiBytesSsrc == uiSsrc2Encoder_NbBytes )
8552                pC->pPosInSsrcBufferOut = M4OSA_NULL;
8553            else
8554                pC->pPosInSsrcBufferOut += uiSsrc2Encoder_NbBytes;
8555
8556            /* mark the encoder buffer ready (= full) */
8557            pC->pPosInAudioEncoderBuffer =
8558                pC->pAudioEncoderBuffer + pC->audioEncoderGranularity;
8559
8560            if( needChannelConversion > 0 )
8561            {
8562                /* channel convertor writes directly into encoder buffer */
8563                pEncoderInput = pC->pAudioEncoderBuffer;
8564
8565                pChannelConvertorInput = pC->pSsrcBufferOut;
8566                pChannelConvertorOutput = pC->pAudioEncoderBuffer;
8567                uiChannelConvertorNbSamples =
8568                    uiSsrc2Encoder_NbBytes / sizeof(short);
8569
8570                goto m4mcs_intaudiotranscoding_channel_convertor;
8571            }
8572            else
8573            {
8574                /* encode directly from ssrc out buffer */
8575                pEncoderInput = pC->pSsrcBufferOut;
8576
8577                goto m4mcs_intaudiotranscoding_encode_and_write;
8578            }
8579        }
8580    }
8581
8582    /**
8583    * Compute remaining space in encoder buffer in */
8584    if( pC->pPosInAudioEncoderBuffer == M4OSA_NULL )
8585    {
8586        pC->pPosInAudioEncoderBuffer = pC->pAudioEncoderBuffer;
8587    }
8588
8589    uiEncoderInRoom = ( pC->pAudioEncoderBuffer + pC->audioEncoderGranularity)
8590        - pC->pPosInAudioEncoderBuffer;
8591    pEncoderInput = pC->pAudioEncoderBuffer;
8592
8593    /**
8594    * Nb of bytes copied is the minimum between nb of bytes remaining in
8595    * decoder out buffer and space remaining in ssrc in buffer */
8596    uiSsrc2Encoder_NbBytes =
8597        (( uiEncoderInRoom * uiChannelConvertorCoeff / 2) < uiBytesSsrc)
8598        ? (uiEncoderInRoom * uiChannelConvertorCoeff / 2) : uiBytesSsrc;
8599
8600    if( needChannelConversion > 0 )
8601    {
8602        /* channel convertor writes directly into encoder buffer */
8603        pChannelConvertorInput = pC->pPosInSsrcBufferOut;
8604        pChannelConvertorOutput = pC->pPosInAudioEncoderBuffer;
8605        uiChannelConvertorNbSamples = uiSsrc2Encoder_NbBytes / sizeof(short);
8606    }
8607    else
8608    {
8609        /* copy from the ssrc out buffer into the encoder in buffer */
8610        memcpy((void *)pC->pPosInAudioEncoderBuffer, (void *)pC->pPosInSsrcBufferOut,
8611            uiSsrc2Encoder_NbBytes);
8612    }
8613
8614    /* Update position in ssrc out buffer after encoding */
8615    pC->pPosInSsrcBufferOut += uiSsrc2Encoder_NbBytes;
8616
8617    /* Update the position in the encoder in buffer */
8618    pC->pPosInAudioEncoderBuffer +=
8619        uiSsrc2Encoder_NbBytes * 2 / uiChannelConvertorCoeff;
8620
8621    /* Check if the ssrc buffer out is empty */
8622    if( ( pC->pPosInSsrcBufferOut - pC->pSsrcBufferOut)
8623        == (M4OSA_Int32)uiSsrcOutSize )
8624    {
8625        pC->pPosInSsrcBufferOut = M4OSA_NULL;
8626    }
8627
8628    /* go to next statement */
8629    if( needChannelConversion > 0 )
8630        goto m4mcs_intaudiotranscoding_channel_convertor;
8631    else
8632        goto m4mcs_intaudiotranscoding_encode_and_write;
8633
8634    /* _________________ */
8635    /*|                 |*/
8636    /*| STEREO <-> MONO |*/
8637    /*|_________________|*/
8638
8639m4mcs_intaudiotranscoding_channel_convertor:
8640
8641    /* convert the input pcm stream to mono or to stereo */
8642    switch( needChannelConversion )
8643    {
8644        case 1: /* stereo to mono */
8645            From2iToMono_16((short *)pChannelConvertorInput,
8646                (short *)pChannelConvertorOutput,
8647                (short)(uiChannelConvertorNbSamples / 2));
8648            break;
8649
8650        case 2: /* mono to stereo */
8651            MonoTo2I_16((short *)pChannelConvertorInput,
8652                (short *)pChannelConvertorOutput,
8653                (short)uiChannelConvertorNbSamples);
8654            break;
8655    }
8656
8657    /* __________________ */
8658    /*|                  |*/
8659    /*| ENCODE AND WRITE |*/
8660    /*|__________________|*/
8661
8662m4mcs_intaudiotranscoding_encode_and_write:
8663
8664    /* Check if the encoder in buffer is ready (= full) */
8665    if( ( pC->pPosInAudioEncoderBuffer - pC->pAudioEncoderBuffer)
8666        < (M4OSA_Int32)pC->audioEncoderGranularity )
8667    {
8668        goto m4mcs_intaudiotranscoding_end;
8669    }
8670
8671    /* [Mono] or [Stereo interleaved] : all is in one buffer */
8672    pEncInBuffer.pTableBuffer[0] = pEncoderInput;
8673    pEncInBuffer.pTableBufferSize[0] = pC->audioEncoderGranularity;
8674    pEncInBuffer.pTableBuffer[1] = M4OSA_NULL;
8675    pEncInBuffer.pTableBufferSize[1] = 0;
8676
8677    /* Time in ms from data size, because it is PCM16 samples */
8678    frameTimeDelta =
8679        ( pEncInBuffer.pTableBufferSize[0] * uiChannelConvertorCoeff / 2)
8680        / sizeof(short) / pC->pReaderAudioStream->m_nbChannels;
8681
8682    /**
8683    * Prepare the writer AU */
8684    err = pC->pWriterDataFcts->pStartAU(pC->pWriterContext,
8685        M4MCS_WRITER_AUDIO_STREAM_ID, &pC->WriterAudioAU);
8686
8687    if( M4NO_ERROR != err )
8688    {
8689        M4OSA_TRACE1_1(
8690            "M4MCS_intAudioTranscoding(): pWriterDataFcts->pStartAU(Audio) returns 0x%x",
8691            err);
8692        return err;
8693    }
8694
8695    /*FlB 2009.03.04: apply audio effects if an effect is active*/
8696    if( *pActiveEffectNumber >= 0 && *pActiveEffectNumber < pC->nbEffects )
8697    {
8698        if( pC->pEffects[*pActiveEffectNumber].ExtAudioEffectFct != M4OSA_NULL )
8699        {
8700            M4MCS_ExternalProgress pProgress;
8701            M4OSA_UInt64 tempProgress = 0;
8702            pProgress.uiClipTime = (M4OSA_UInt32)pC->ReaderAudioAU.m_CTS;
8703
8704            pProgress.uiOutputTime = ( pC->WriterAudioAU.CTS * 1000)
8705                / pC->WriterAudioStream.timeScale;
8706            tempProgress = ( (M4OSA_UInt64)pC->ReaderAudioAU.m_CTS
8707                - pC->pEffects[*pActiveEffectNumber].uiStartTime
8708                - pC->uiBeginCutTime) * 1000;
8709            pProgress.uiProgress =
8710                (M4OSA_UInt32)(tempProgress / (M4OSA_UInt64)pC->pEffects[
8711                    *pActiveEffectNumber].uiDuration);
8712
8713                    err = pC->pEffects[*pActiveEffectNumber].ExtAudioEffectFct(
8714                        pC->pEffects[*pActiveEffectNumber].pExtAudioEffectFctCtxt,
8715                        (M4OSA_Int16 *)pEncInBuffer.pTableBuffer[0],
8716                        pEncInBuffer.pTableBufferSize[0], &pProgress);
8717
8718                    if( err != M4NO_ERROR )
8719                    {
8720                        M4OSA_TRACE1_1(
8721                            "M4MCS_intAudioTranscoding(): ExtAudioEffectFct() returns 0x%x",
8722                            err);
8723                        return err;
8724                    }
8725        }
8726    }
8727
8728    /**
8729    * Prepare output buffer */
8730    pEncOutBuffer.pTableBuffer[0] =
8731        (M4OSA_MemAddr8)pC->WriterAudioAU.dataAddress;
8732    pEncOutBuffer.pTableBufferSize[0] = 0;
8733
8734#ifdef MCS_DUMP_PCM_TO_FILE
8735
8736    fwrite(pEncInBuffer.pTableBuffer[0], pEncInBuffer.pTableBufferSize[0], 1,
8737        file_pcm_encoder);
8738
8739#endif
8740
8741    if( M4OSA_FALSE == pC->b_isRawWriter )
8742    {
8743        /* This allow to write PCM data to file and to encode AMR data,
8744         when output file is not RAW */
8745        if( pC->pOutputPCMfile != M4OSA_NULL )
8746        {
8747            pC->pOsaFileWritPtr->writeData(pC->pOutputPCMfile,
8748                pEncInBuffer.pTableBuffer[0], pEncInBuffer.pTableBufferSize[0]);
8749        }
8750
8751        /**
8752        * Encode the PCM audio */
8753        err = pC->pAudioEncoderGlobalFcts->pFctStep(pC->pAudioEncCtxt,
8754            &pEncInBuffer, &pEncOutBuffer);
8755
8756        if( M4NO_ERROR != err )
8757        {
8758            M4OSA_TRACE1_1(
8759                "M4MCS_intAudioTranscoding(): pAudioEncoderGlobalFcts->pFctStep returns 0x%x",
8760                err);
8761            return err;
8762        }
8763
8764        /* update data consumed into encoder buffer in after encoding (empty) */
8765        pC->pPosInAudioEncoderBuffer = M4OSA_NULL;
8766
8767        /**
8768        * Set AU cts and size */
8769        pC->WriterAudioAU.size =
8770            pEncOutBuffer.
8771            pTableBufferSize[0]; /**< Get the size of encoded data */
8772        pC->WriterAudioAU.CTS += frameTimeDelta;
8773
8774        /**
8775        * Update duration of the encoded AU */
8776        pC->m_audioAUDuration =
8777            ( frameTimeDelta * 1000) / pC->WriterAudioStream.timeScale;
8778
8779        /**
8780        * Write the encoded AU to the output file */
8781        pC->uiAudioAUCount++;
8782        err = pC->pWriterDataFcts->pProcessAU(pC->pWriterContext,
8783            M4MCS_WRITER_AUDIO_STREAM_ID, &pC->WriterAudioAU);
8784
8785        if( M4NO_ERROR != err )
8786        {
8787            M4OSA_TRACE1_1(
8788                "M4MCS_intAudioTranscoding(): pWriterDataFcts->pProcessAU(Audio) returns 0x%x",
8789                err);
8790            return err;
8791        }
8792    }
8793    else
8794    {
8795        /* update data consumed into encoder buffer in after encoding (empty) */
8796        pC->pPosInAudioEncoderBuffer = M4OSA_NULL;
8797
8798        pC->WriterAudioAU.dataAddress =
8799            (M4OSA_MemAddr32)
8800            pEncoderInput; /* will be converted back to u8* in file write */
8801        pC->WriterAudioAU.size = pC->audioEncoderGranularity;
8802        pC->uiAudioAUCount++;
8803
8804        err = pC->pWriterDataFcts->pProcessAU(pC->pWriterContext,
8805            M4MCS_WRITER_AUDIO_STREAM_ID, &pC->WriterAudioAU);
8806
8807        if( M4NO_ERROR != err )
8808        {
8809            M4OSA_TRACE1_1(
8810                "M4MCS_intAudioTranscoding(): pWriterDataFcts->pProcessAU(Audio) returns 0x%x",
8811                err);
8812            return err;
8813        }
8814    }
8815
8816    /* _______________ */
8817    /*|               |*/
8818    /*| ONE PASS DONE |*/
8819    /*|_______________|*/
8820
8821m4mcs_intaudiotranscoding_end:
8822
8823    /**
8824    * Return with no error */
8825    M4OSA_TRACE3_0("M4MCS_intAudioTranscoding(): returning M4NO_ERROR");
8826    return M4NO_ERROR;
8827}
8828
8829/**
8830 ******************************************************************************
8831 * M4OSA_ERR M4MCS_intReallocTemporaryAU(M4OSA_MemAddr8* addr, M4OSA_UInt32 newSize)
8832 * Used only in case of 3GP constant memory reader, to be able to realloc temporary AU
8833 * because max AU size can be reevaluated during reading
8834 * @return   M4NO_ERROR:         No error
8835 ******************************************************************************
8836 */
8837static M4OSA_ERR M4MCS_intReallocTemporaryAU( M4OSA_MemAddr8 *addr,
8838                                             M4OSA_UInt32 newSize )
8839{
8840    if( *addr != M4OSA_NULL )
8841    {
8842        M4OSA_free(( M4OSA_MemAddr32) * addr);
8843        *addr = (M4OSA_MemAddr8)M4OSA_malloc(newSize, M4MCS,
8844            (M4OSA_Char *)"Reallocation of temporary AU buffer");
8845
8846        if( *addr == M4OSA_NULL )
8847        {
8848            return M4ERR_ALLOC;
8849        }
8850    }
8851
8852    return M4NO_ERROR;
8853}
8854
8855/**
8856 ******************************************************************************
8857 * M4OSA_ERR M4MCS_intVideoNullEncoding(M4MCS_InternalContext* pC)
8858 * @author   Alexis Vapillon (NXP Software Vision)
8859 * @return   M4NO_ERROR:         No error
8860 ******************************************************************************
8861 */
8862static M4OSA_ERR M4MCS_intVideoNullEncoding( M4MCS_InternalContext *pC )
8863{
8864    M4OSA_ERR err = M4NO_ERROR;
8865    /* Duration of the AU (find the next AU duration
8866     * to obtain a more precise video end cut)
8867     */
8868    M4OSA_UInt32 videoAUDuration = 0;
8869
8870    M4OSA_MemAddr8 WritebufferAdd = M4OSA_NULL;
8871    M4OSA_Int32 lastdecodedCTS = 0;
8872    M4_AccessUnit lReaderVideoAU; /**< Read video access unit */
8873
8874    if( pC->novideo )
8875        return M4NO_ERROR;
8876
8877    /* H.264 Trimming */
8878    if( ( ( pC->bH264Trim == M4OSA_TRUE)
8879        && (pC->uiVideoAUCount < pC->m_pInstance->clip_sps.num_ref_frames)
8880        && (pC->uiBeginCutTime > 0))
8881        || (( pC->uiVideoAUCount == 0) && (pC->uiBeginCutTime > 0)) )
8882    {
8883        err = M4MCS_intVideoTranscoding(pC);
8884        return err;
8885    }
8886
8887
8888    if((pC->bLastDecodedFrameCTS == M4OSA_FALSE) && (pC->uiBeginCutTime > 0))
8889    {
8890        // StageFright encoder does prefetch, the one frame we requested will not be written until
8891        // the encoder is closed, so do it now rather than in MCS_close
8892        if( ( M4NO_ERROR != err)
8893            || (M4MCS_kEncoderRunning != pC->encoderState) )
8894        {
8895            M4OSA_TRACE1_2(
8896                "!!! M4MCS_intVideoNullEncoding ERROR : M4MCS_intVideoTranscoding "
8897                "returns 0x%X w/ encState=%d", err, pC->encoderState);
8898
8899            return err;
8900        }
8901
8902        /* Stop and close the encoder now to flush the frame (prefetch) */
8903        if( pC->pVideoEncoderGlobalFcts->pFctStop != M4OSA_NULL )
8904        {
8905            err = pC->pVideoEncoderGlobalFcts->pFctStop(pC->pViEncCtxt);
8906
8907            if( M4NO_ERROR != err )
8908            {
8909                M4OSA_TRACE1_1(
8910                    "!!! M4MCS_intVideoNullEncoding ERROR : encoder stop returns 0x%X",
8911                    err);
8912                return err;
8913            }
8914        }
8915        pC->encoderState = M4MCS_kEncoderStopped;
8916        err = pC->pVideoEncoderGlobalFcts->pFctClose(pC->pViEncCtxt);
8917
8918        if( M4NO_ERROR != err )
8919        {
8920            M4OSA_TRACE1_1(
8921                "!!! M4MCS_intVideoNullEncoding ERROR : encoder close returns 0x%X",
8922                err);
8923            return err;
8924        }
8925        pC->encoderState = M4MCS_kEncoderClosed;
8926    }
8927
8928
8929    if( ( pC->bH264Trim == M4OSA_TRUE)
8930        && (pC->bLastDecodedFrameCTS == M4OSA_FALSE)
8931        && (pC->uiBeginCutTime > 0) )
8932    {
8933
8934        pC->bLastDecodedFrameCTS = M4OSA_TRUE;
8935        err = pC->m_pVideoDecoder->m_pFctGetOption(pC->pViDecCtxt,
8936            M4DECODER_kOptionID_AVCLastDecodedFrameCTS, &lastdecodedCTS);
8937
8938        if( M4NO_ERROR != err )
8939        {
8940            M4OSA_TRACE1_1(
8941                "M4MCS_intVideoNullEncoding: m_pVideoDecoder->m_pFctGetOption returns 0x%x!",
8942                err);
8943            return err;
8944        }
8945
8946        err = pC->m_pReader->m_pFctJump(pC->pReaderContext,
8947            (M4_StreamHandler *)pC->pReaderVideoStream, &lastdecodedCTS);
8948
8949        if( M4NO_ERROR != err )
8950        {
8951            M4OSA_TRACE1_1(
8952                "M4MCS_intStepBeginVideoJump: m_pFctJump(V) returns 0x%x!",
8953                err);
8954            return err;
8955        }
8956
8957
8958        /* Initializes an access Unit */
8959
8960        err = pC->m_pReader->m_pFctFillAuStruct(pC->pReaderContext,
8961            (M4_StreamHandler *)pC->pReaderVideoStream, &lReaderVideoAU);
8962
8963        if( M4NO_ERROR != err )
8964        {
8965            M4OSA_TRACE1_1(
8966                "M4MCS_open(): m_pReader->m_pFctFillAuStruct(video) returns 0x%x",
8967                err);
8968            return err;
8969        }
8970
8971        err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
8972            (M4_StreamHandler *)pC->pReaderVideoStream, &lReaderVideoAU);
8973
8974        if( M4WAR_NO_MORE_AU == err )
8975        {
8976            M4OSA_TRACE2_0(
8977                "M4MCS_intVideoNullEncoding():\
8978                 m_pReaderDataIt->m_pFctGetNextAu(video) returns M4WAR_NO_MORE_AU");
8979            /* The audio transcoding is finished */
8980            pC->VideoState = M4MCS_kStreamState_FINISHED;
8981            return err;
8982        }
8983        else if( M4NO_ERROR != err )
8984        {
8985            M4OSA_TRACE1_1(
8986                "M4MCS_intVideoNullEncoding():\
8987                 m_pReaderDataIt->m_pFctGetNextAu(video) returns 0x%x",
8988                err);
8989            return err;
8990        }
8991
8992        M4OSA_TRACE1_1(
8993            "### [TS_CHECK] M4MCS_intVideoNullEncoding  video AU CTS: %d ",
8994            lReaderVideoAU.m_CTS);
8995
8996
8997    }
8998
8999
9000    pC->bLastDecodedFrameCTS = M4OSA_TRUE;
9001
9002    /* - CRLV6775 -H.264 Trimming */
9003
9004    /* commented,this part is done further on one of the temporary video AU (video AU1 or video AU2)*/
9005#if 0
9006    /**
9007    * Read the next video AU in the input file */
9008
9009    err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
9010        (M4_StreamHandler *)pC->pReaderVideoStream, &pC->ReaderVideoAU);
9011#endif
9012
9013    /* Find the next AU duration to obtain a more precise video end cut*/
9014    /**
9015    * Initializes a new AU if needed */
9016
9017    if( pC->ReaderVideoAU1.m_structSize == 0 )
9018    {
9019        /**
9020        * Initializes an access Unit */
9021        err = pC->m_pReader->m_pFctFillAuStruct(pC->pReaderContext,
9022            (M4_StreamHandler *)pC->pReaderVideoStream,
9023            &pC->ReaderVideoAU1);
9024
9025        if( M4NO_ERROR != err )
9026        {
9027            M4OSA_TRACE1_1(
9028                "M4MCS_open(): m_pReader->m_pFctFillAuStruct(video) returns 0x%x",
9029                err);
9030            return err;
9031        }
9032
9033        pC->m_pDataVideoAddress1 =
9034            (M4OSA_MemAddr8)M4OSA_malloc(pC->ReaderVideoAU1.m_maxsize, M4MCS,
9035            (M4OSA_Char *)"Temporary video AU1 buffer");
9036
9037        if( pC->m_pDataVideoAddress1 == M4OSA_NULL )
9038        {
9039            M4OSA_TRACE1_0("M4MCS_intVideoNullEncoding(): allocation error");
9040            return M4ERR_ALLOC;
9041        }
9042
9043        err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
9044            (M4_StreamHandler *)pC->pReaderVideoStream,
9045            &pC->ReaderVideoAU1);
9046
9047        if( M4WAR_NO_MORE_AU == err )
9048        {
9049            M4OSA_TRACE2_0(
9050                "M4MCS_intVideoNullEncoding():\
9051                 m_pReaderDataIt->m_pFctGetNextAu(video) returns M4WAR_NO_MORE_AU");
9052            /* The audio transcoding is finished */
9053            pC->VideoState = M4MCS_kStreamState_FINISHED;
9054            return err;
9055        }
9056        else if( M4NO_ERROR != err )
9057        {
9058            M4OSA_TRACE1_1(
9059                "M4MCS_intVideoNullEncoding(): m_pReaderDataIt->m_pFctGetNextAu(video)\
9060                 returns 0x%x", err);
9061            return err;
9062        }
9063
9064        if( pC->ReaderVideoAU1.m_maxsize
9065            > pC->pReaderVideoStream->m_basicProperties.m_maxAUSize )
9066        {
9067            /* Constant memory reader case, we need to reallocate the temporary buffers */
9068            M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
9069                *) &(pC->m_pDataVideoAddress1), pC->ReaderVideoAU1.m_maxsize);
9070            /* pC->m_pDataVideoAddress1
9071            and pC->m_pDataVideoAddress2 must be reallocated at the same time */
9072            /* because pC->pReaderVideoStream->m_basicProperties.m_maxAUSize take maximum value.
9073             Then the test "if(pC->ReaderVideoAU?.m_maxsize > pC->pReaderVideoStream->
9074             m_basicProperties.m_maxAUSize)" is never true */
9075            /* and the size of the second buffer is never changed. */
9076            M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
9077                *) &(pC->m_pDataVideoAddress2), pC->ReaderVideoAU1.m_maxsize);
9078            /* pC->m_pDataVideoAddress1 and
9079            pC->m_pDataVideoAddress2 must be reallocated at the same time */
9080            /* Update stream properties */
9081            pC->pReaderVideoStream->m_basicProperties.m_maxAUSize =
9082                pC->ReaderVideoAU1.m_maxsize;
9083        }
9084        memcpy((void *)pC->m_pDataVideoAddress1,
9085            (void *)pC->ReaderVideoAU1.m_dataAddress,
9086            pC->ReaderVideoAU1.m_size);
9087    }
9088
9089    if( pC->ReaderVideoAU2.m_structSize == 0 )
9090    {
9091        /**
9092        * Initializes an access Unit */
9093        err = pC->m_pReader->m_pFctFillAuStruct(pC->pReaderContext,
9094            (M4_StreamHandler *)pC->pReaderVideoStream,
9095            &pC->ReaderVideoAU2);
9096
9097        if( M4NO_ERROR != err )
9098        {
9099            M4OSA_TRACE1_1(
9100                "M4MCS_open(): m_pReader->m_pFctFillAuStruct(video) returns 0x%x",
9101                err);
9102            return err;
9103        }
9104        pC->m_pDataVideoAddress2 =
9105            (M4OSA_MemAddr8)M4OSA_malloc(pC->ReaderVideoAU2.m_maxsize, M4MCS,
9106            (M4OSA_Char *)"Temporary video AU buffer");
9107
9108        if( pC->m_pDataVideoAddress2 == M4OSA_NULL )
9109        {
9110            M4OSA_TRACE1_0("M4MCS_intVideoNullEncoding(): allocation error");
9111            return M4ERR_ALLOC;
9112        }
9113    }
9114    /**
9115    * Read the next video AU in the input file */
9116    if( pC->ReaderVideoAU2.m_CTS > pC->ReaderVideoAU1.m_CTS )
9117    {
9118        memcpy((void *) &pC->ReaderVideoAU,
9119            (void *) &pC->ReaderVideoAU2, sizeof(M4_AccessUnit));
9120        err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
9121            (M4_StreamHandler *)pC->pReaderVideoStream,
9122            &pC->ReaderVideoAU1);
9123
9124        if( pC->ReaderVideoAU1.m_maxsize
9125            > pC->pReaderVideoStream->m_basicProperties.m_maxAUSize )
9126        {
9127            /* Constant memory reader case, we need to reallocate the temporary buffers */
9128            M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
9129                *) &(pC->m_pDataVideoAddress1), pC->ReaderVideoAU1.m_maxsize);
9130            /* pC->m_pDataVideoAddress1 and
9131             pC->m_pDataVideoAddress2 must be reallocated at the same time */
9132            /* because pC->pReaderVideoStream->m_basicProperties.m_maxAUSize take maximum value.
9133             Then the test "if(pC->ReaderVideoAU?.m_maxsize > pC->pReaderVideoStream->
9134             m_basicProperties.m_maxAUSize)" is never true */
9135            /* and the size of the second buffer is never changed. */
9136            M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
9137                *) &(pC->m_pDataVideoAddress2), pC->ReaderVideoAU1.m_maxsize);
9138            /* pC->m_pDataVideoAddress1 and
9139            pC->m_pDataVideoAddress2 must be reallocated at the same time */
9140            /* Update stream properties */
9141            pC->pReaderVideoStream->m_basicProperties.m_maxAUSize =
9142                pC->ReaderVideoAU1.m_maxsize;
9143        }
9144        memcpy((void *)pC->m_pDataVideoAddress1,
9145            (void *)pC->ReaderVideoAU1.m_dataAddress,
9146            pC->ReaderVideoAU1.m_size);
9147        videoAUDuration = pC->ReaderVideoAU1.m_CTS - pC->ReaderVideoAU2.m_CTS;
9148        pC->ReaderVideoAU.m_dataAddress = pC->m_pDataVideoAddress2;
9149    }
9150    else
9151    {
9152        memcpy((void *) &pC->ReaderVideoAU,
9153            (void *) &pC->ReaderVideoAU1, sizeof(M4_AccessUnit));
9154        err = pC->m_pReaderDataIt->m_pFctGetNextAu(pC->pReaderContext,
9155            (M4_StreamHandler *)pC->pReaderVideoStream,
9156            &pC->ReaderVideoAU2);
9157
9158        if( pC->ReaderVideoAU2.m_maxsize
9159            > pC->pReaderVideoStream->m_basicProperties.m_maxAUSize )
9160        {
9161            /* Constant memory reader case, we need to reallocate the temporary buffers */
9162            M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
9163                *) &(pC->m_pDataVideoAddress2), pC->ReaderVideoAU2.m_maxsize);
9164            /* pC->m_pDataVideoAddress1 and
9165             pC->m_pDataVideoAddress2 must be reallocated at the same time */
9166            /* because pC->pReaderVideoStream->m_basicProperties.m_maxAUSize take maximum value.
9167             Then the test "if(pC->ReaderVideoAU?.m_maxsize > pC->pReaderVideoStream->
9168             m_basicProperties.m_maxAUSize)" is never true */
9169            /* and the size of the second buffer is never changed. */
9170            M4MCS_intReallocTemporaryAU((M4OSA_MemAddr8
9171                *) &(pC->m_pDataVideoAddress1), pC->ReaderVideoAU2.m_maxsize);
9172            /* pC->m_pDataVideoAddress1 and
9173            pC->m_pDataVideoAddress2 must be reallocated at the same time */
9174            /* Update stream properties */
9175            pC->pReaderVideoStream->m_basicProperties.m_maxAUSize =
9176                pC->ReaderVideoAU2.m_maxsize;
9177        }
9178        memcpy((void *)pC->m_pDataVideoAddress2,
9179            (void *)pC->ReaderVideoAU2.m_dataAddress,
9180            pC->ReaderVideoAU2.m_size);
9181        videoAUDuration = pC->ReaderVideoAU2.m_CTS - pC->ReaderVideoAU1.m_CTS;
9182        pC->ReaderVideoAU.m_dataAddress = pC->m_pDataVideoAddress1;
9183    }
9184
9185    if( M4WAR_NO_MORE_AU == err )
9186    {
9187        M4OSA_TRACE2_0(
9188            "M4MCS_intVideoNullEncoding():\
9189             m_pReaderDataIt->m_pFctGetNextAu(video) returns M4WAR_NO_MORE_AU");
9190        /* The video transcoding is finished */
9191        pC->VideoState = M4MCS_kStreamState_FINISHED;
9192        return err;
9193    }
9194    else if( M4NO_ERROR != err )
9195    {
9196        M4OSA_TRACE1_1(
9197            "M4MCS_intVideoNullEncoding(): m_pReaderDataIt->m_pFctGetNextAu(Video) returns 0x%x",
9198            err);
9199        return err;
9200    }
9201    else
9202    {
9203        /**
9204        * Prepare the writer AU */
9205        err = pC->pWriterDataFcts->pStartAU(pC->pWriterContext,
9206            M4MCS_WRITER_VIDEO_STREAM_ID, &pC->WriterVideoAU);
9207
9208        if( M4NO_ERROR != err )
9209        {
9210            M4OSA_TRACE1_1(
9211                "M4MCS_intVideoNullEncoding(): pWriterDataFcts->pStartAU(Video) returns 0x%x",
9212                err);
9213            return err;
9214        }
9215#ifdef TIMESCALE_BUG
9216        /* If we are in timescale modification mode or classic copy mode */
9217
9218        if( pC->uiVideoTimescale != 0 )
9219        {
9220            /**
9221            * Copy video data from reader AU to writer AU */
9222            //memcpy((M4OSA_MemAddr8)pC->WriterVideoAU.dataAddress,
9223            //(M4OSA_MemAddr8)pC->ReaderVideoAU.m_dataAddress, pC->ReaderVideoAU.m_size);
9224            pC->WriterVideoAU.size = pC->ReaderVideoAU.m_size;
9225
9226            /* Call internal function to change AU timescale */
9227            err = M4MCS_intChangeAUVideoTimescale(pC);
9228
9229            /**
9230            * Convert CTS unit from milliseconds to timescale */
9231            pC->WriterVideoAU.CTS =
9232                (M4OSA_Time)((( pC->ReaderVideoAU.m_CTS - pC->dViDecStartingCts)
9233                * (pC->WriterVideoStream.timeScale / 1000.0)));
9234            pC->WriterVideoAU.nbFrag = 0;
9235            pC->WriterVideoAU.attribute = pC->ReaderVideoAU.m_attribute;
9236        }
9237        else
9238
9239#endif
9240
9241        {
9242            /**
9243            * Copy video data from reader AU to writer AU */
9244            M4OSA_TRACE3_1(
9245                "M4MCS_intVideoNullEncoding(): Copying video AU: size=%d",
9246                pC->ReaderVideoAU.m_size);
9247            /* + CRLV6775 -H.264 Trimming */
9248            if( M4OSA_TRUE == pC->bH264Trim )
9249            {
9250                if( pC->H264MCSTempBufferSize
9251                    < (pC->ReaderVideoAU.m_size + 2048) )
9252                {
9253                    pC->H264MCSTempBufferSize =
9254                        (pC->ReaderVideoAU.m_size + 2048);
9255
9256                    if( pC->H264MCSTempBuffer != M4OSA_NULL )
9257                    {
9258                        M4OSA_free((M4OSA_MemAddr32)pC->H264MCSTempBuffer);
9259                    }
9260                    pC->H264MCSTempBuffer =
9261                        (M4OSA_UInt8 *)M4OSA_malloc(pC->H264MCSTempBufferSize,
9262                        M4MCS, (M4OSA_Char *)"pC->H264MCSTempBuffer");
9263
9264                    if( pC->H264MCSTempBuffer == M4OSA_NULL )
9265                    {
9266                        M4OSA_TRACE1_0(
9267                            "M4MCS_intVideoNullEncoding(): allocation error");
9268                        return M4ERR_ALLOC;
9269                    }
9270                }
9271
9272                pC->H264MCSTempBufferDataSize = pC->H264MCSTempBufferSize;
9273
9274                err = H264MCS_ProcessNALU(pC->m_pInstance,
9275                    (M4OSA_UInt8 *)pC->ReaderVideoAU.m_dataAddress,
9276                    pC->ReaderVideoAU.m_size, pC->H264MCSTempBuffer,
9277                    (M4OSA_Int32 *)&pC->H264MCSTempBufferDataSize);
9278
9279                if( pC->m_pInstance->is_done == 1 )
9280                {
9281                    M4MCS_convetFromByteStreamtoNALStream(
9282                        (M4OSA_UInt8 *)pC->ReaderVideoAU.m_dataAddress ,
9283                        pC->ReaderVideoAU.m_size);
9284
9285                    memcpy((void *)pC->WriterVideoAU.dataAddress,
9286                        (void *)(pC->ReaderVideoAU.m_dataAddress + 4),
9287                        pC->ReaderVideoAU.m_size - 4);
9288                    pC->WriterVideoAU.size = pC->ReaderVideoAU.m_size - 4;
9289                    WritebufferAdd =
9290                        (M4OSA_MemAddr8)pC->WriterVideoAU.dataAddress;
9291                }
9292                else
9293                {
9294                    memcpy((void *)pC->WriterVideoAU.dataAddress,
9295                        (void *)(pC->H264MCSTempBuffer + 4),
9296                        pC->H264MCSTempBufferDataSize - 4);
9297                    pC->WriterVideoAU.size = pC->H264MCSTempBufferDataSize - 4;
9298                    WritebufferAdd =
9299                        (M4OSA_MemAddr8)pC->WriterVideoAU.dataAddress;
9300                }
9301            }
9302            /* H.264 Trimming */
9303            else
9304            {
9305                memcpy((void *)pC->WriterVideoAU.dataAddress,
9306                    (void *)pC->ReaderVideoAU.m_dataAddress,
9307                    pC->ReaderVideoAU.m_size);
9308                pC->WriterVideoAU.size = pC->ReaderVideoAU.m_size;
9309            }
9310            /**
9311            * Convert CTS unit from milliseconds to timescale */
9312            pC->WriterVideoAU.CTS =
9313                (M4OSA_Time)((( pC->ReaderVideoAU.m_CTS - pC->dViDecStartingCts)
9314                * (pC->WriterVideoStream.timeScale / 1000.0)));
9315            pC->WriterVideoAU.nbFrag = 0;
9316            pC->WriterVideoAU.attribute = pC->ReaderVideoAU.m_attribute;
9317
9318            M4OSA_TRACE3_1("M4MCS_intVideoNullEncoding(): video AU: CTS=%d ms",
9319                pC->WriterVideoAU.CTS);
9320        }
9321
9322        /**
9323        * Write it to the output file */
9324        pC->uiVideoAUCount++;
9325        err = pC->pWriterDataFcts->pProcessAU(pC->pWriterContext,
9326            M4MCS_WRITER_VIDEO_STREAM_ID, &pC->WriterVideoAU);
9327
9328        if( M4NO_ERROR != err )
9329        {
9330            M4OSA_TRACE1_1(
9331                "M4MCS_intVideoNullEncoding(): pWriterDataFcts->pProcessAU(Video) returns 0x%x",
9332                err);
9333            return err;
9334        }
9335        /* + CRLV6775 -H.264 Trimming */
9336        if( M4OSA_TRUE == pC->bH264Trim )
9337        {
9338            if( pC->m_pInstance->is_done == 1 )
9339            {
9340                memcpy((void *)(WritebufferAdd - 4),
9341                    (void *)(pC->ReaderVideoAU.m_dataAddress), 4);
9342            }
9343            else
9344            {
9345                memcpy((void *)(WritebufferAdd - 4),
9346                    (void *)(pC->H264MCSTempBuffer), 4);
9347            }
9348        } /* H.264 Trimming */
9349    }
9350    /**
9351    * Check for end cut. */
9352    /* Bug fix 11/12/2008: We absolutely want to have less or same video duration ->
9353    (2*videoAUDuration) to have a more precise end cut*/
9354    if( pC->ReaderVideoAU.m_CTS + (2 *videoAUDuration) > pC->uiEndCutTime )
9355    {
9356        pC->VideoState = M4MCS_kStreamState_FINISHED;
9357    }
9358
9359    /**
9360    * Return with no error */
9361    M4OSA_TRACE3_0("M4MCS_intVideoNullEncoding(): returning M4NO_ERROR");
9362    return M4NO_ERROR;
9363}
9364
9365/**
9366 ******************************************************************************
9367 * M4OSA_ERR M4MCS_intVideoTranscoding(M4MCS_InternalContext* pC)
9368 * @author   Alexis Vapillon (NXP Software Vision)
9369 * @return   M4NO_ERROR:         No error
9370 ******************************************************************************
9371 */
9372static M4OSA_ERR M4MCS_intVideoTranscoding( M4MCS_InternalContext *pC )
9373{
9374    M4OSA_ERR err = M4NO_ERROR;
9375    M4_MediaTime mtTranscodedTime = 0.0;
9376    M4ENCODER_FrameMode FrameMode;
9377    M4OSA_Int32 derive = 0;
9378
9379    /**
9380    * Get video CTS to decode */
9381    mtTranscodedTime = pC->dViDecCurrentCts;
9382    FrameMode = M4ENCODER_kNormalFrame;
9383
9384    /**
9385    * Decode video */
9386    M4OSA_TRACE3_1(
9387        "M4MCS_intVideoTranscoding(): Calling m_pVideoDecoder->m_pFctDecode(%.2f)",
9388        mtTranscodedTime);
9389    pC->isRenderDup = M4OSA_FALSE;
9390    err = pC->m_pVideoDecoder->m_pFctDecode(pC->pViDecCtxt, &mtTranscodedTime,
9391        M4OSA_FALSE);
9392
9393    if( M4WAR_NO_MORE_AU == err )
9394    {
9395        FrameMode =
9396            M4ENCODER_kLastFrame; /**< We will give this value to the encoder to
9397            ask for the end of the encoding */
9398        pC->VideoState = M4MCS_kStreamState_FINISHED;
9399    }
9400    else if( err == M4WAR_VIDEORENDERER_NO_NEW_FRAME )
9401    {
9402        M4OSA_TRACE2_0("Decoding output the same frame as before 3");
9403        pC->isRenderDup = M4OSA_TRUE;
9404    }
9405    else if( M4NO_ERROR != err )
9406    {
9407        M4OSA_TRACE1_1(
9408            "M4MCS_intVideoTranscoding(): m_pVideoDecoder->m_pFctDecode returns 0x%x!",
9409            err);
9410        return err;
9411    }
9412
9413    /**
9414    * Check for end cut.
9415    * We must check here if the end cut is reached, because in that case we must
9416    * call the last encode step (-> bLastFrame set to true) */
9417    if( ( pC->dViDecCurrentCts + pC->dCtsIncrement ) >= (pC->uiEndCutTime
9418        + M4MCS_ABS(pC->dViDecStartingCts - pC->uiBeginCutTime)) )
9419    {
9420        FrameMode =
9421            M4ENCODER_kLastFrame; /**< We will give this value to the encoder to
9422            ask for the end of the encoding */
9423        pC->VideoState = M4MCS_kStreamState_FINISHED;
9424        derive = (M4OSA_Int32)(( pC->dViDecCurrentCts + pC->dCtsIncrement + 0.5)
9425            - (pC->uiEndCutTime
9426            + M4MCS_ABS(pC->dViDecStartingCts - pC->uiBeginCutTime)));
9427    }
9428
9429    /* Update starting CTS to have a more precise value (
9430    the begin cut is not a real CTS)*/
9431    if( pC->uiVideoAUCount == 0 )
9432    {
9433        pC->dViDecStartingCts = mtTranscodedTime;
9434        pC->dViDecCurrentCts = pC->dViDecStartingCts;
9435    }
9436
9437    /**
9438    * Encode video */
9439    M4OSA_TRACE3_1(
9440        "M4MCS_intVideoTranscoding(): Calling pVideoEncoderGlobalFcts->pFctEncode with videoCts\
9441         = %.2f",pC->ReaderVideoAU.m_CTS);
9442    pC->uiVideoAUCount++;
9443    /* update the given duration (the begin cut is not a real CTS)*/
9444    err = pC->pVideoEncoderGlobalFcts->pFctEncode(pC->pViEncCtxt, M4OSA_NULL,
9445        (pC->dViDecCurrentCts - pC->dViDecStartingCts - (derive >> 1)),
9446        FrameMode);
9447
9448    return err;
9449}
9450
9451/**
9452 ******************************************************************************
9453 * M4OSA_ERR M4MCS_intGetInputClipProperties(M4MCS_InternalContext* pContext)
9454 * @author   Dounya Manai (NXP Software Vision)
9455 * @brief    Retrieve the properties of the audio and video streams from the input file.
9456 * @param    pContext            (IN) MCS context
9457 * @return   M4NO_ERROR:         No error
9458 * @return   M4ERR_PARAMETER:    pContext is M4OSA_NULL (If Debug Level >= 2)
9459 ******************************************************************************
9460 */
9461static M4OSA_ERR M4MCS_intGetInputClipProperties( M4MCS_InternalContext *pC )
9462{
9463    M4DECODER_MPEG4_DecoderConfigInfo DecConfInfo;
9464    M4READER_3GP_H263Properties H263prop;
9465    M4OSA_ERR err;
9466    M4OSA_UInt32 videoBitrate;
9467    M4DECODER_AVCProfileLevel AVCProfle;
9468#ifdef M4VSS_ENABLE_EXTERNAL_DECODERS
9469
9470    M4DECODER_VideoSize videoSize;
9471
9472#endif /* M4VSS_ENABLE_EXTERNAL_DECODERS */
9473
9474    M4_AACType iAacType = 0;
9475
9476    /**
9477    * Check input parameters */
9478    M4OSA_DEBUG_IF2(M4OSA_NULL == pC, M4ERR_PARAMETER,
9479        "M4MCS_intGetInputClipProperties: pC is M4OSA_NULL");
9480
9481    /**
9482    * Reset common characteristics */
9483    pC->InputFileProperties.bAnalysed = M4OSA_FALSE;
9484    pC->InputFileProperties.FileType = 0;
9485    pC->InputFileProperties.Version[0] = M4VIDEOEDITING_VERSION_MAJOR;
9486    pC->InputFileProperties.Version[1] = M4VIDEOEDITING_VERSION_MINOR;
9487    pC->InputFileProperties.Version[2] = M4VIDEOEDITING_VERSION_REVISION;
9488    pC->InputFileProperties.uiClipDuration = 0;
9489
9490    memset((void *) &pC->InputFileProperties.ftyp,
9491        0, sizeof(M4VIDEOEDITING_FtypBox));
9492
9493    /**
9494    * Reset video characteristics */
9495    pC->InputFileProperties.VideoStreamType = M4VIDEOEDITING_kNoneVideo;
9496    pC->InputFileProperties.uiClipVideoDuration = 0;
9497    pC->InputFileProperties.uiVideoBitrate = 0;
9498    pC->InputFileProperties.uiVideoMaxAuSize = 0;
9499    pC->InputFileProperties.uiVideoWidth = 0;
9500    pC->InputFileProperties.uiVideoHeight = 0;
9501    pC->InputFileProperties.uiVideoTimeScale = 0;
9502    pC->InputFileProperties.fAverageFrameRate = 0.0;
9503    pC->InputFileProperties.ProfileAndLevel =
9504        M4VIDEOEDITING_kProfile_and_Level_Out_Of_Range;
9505    pC->InputFileProperties.uiH263level = 0;
9506    pC->InputFileProperties.uiVideoProfile = 0;
9507    pC->InputFileProperties.bMPEG4dataPartition = M4OSA_FALSE;
9508    pC->InputFileProperties.bMPEG4rvlc = M4OSA_FALSE;
9509    pC->InputFileProperties.bMPEG4resynchMarker = M4OSA_FALSE;
9510
9511    /**
9512    * Reset audio characteristics */
9513    pC->InputFileProperties.AudioStreamType = M4VIDEOEDITING_kNoneAudio;
9514    pC->InputFileProperties.uiClipAudioDuration = 0;
9515    pC->InputFileProperties.uiAudioBitrate = 0;
9516    pC->InputFileProperties.uiAudioMaxAuSize = 0;
9517    pC->InputFileProperties.uiNbChannels = 0;
9518    pC->InputFileProperties.uiSamplingFrequency = 0;
9519    pC->InputFileProperties.uiExtendedSamplingFrequency = 0;
9520    pC->InputFileProperties.uiDecodedPcmSize = 0;
9521
9522    /* Reset compatibility chart (not used in MCS) */
9523    pC->InputFileProperties.bVideoIsEditable = M4OSA_FALSE;
9524    pC->InputFileProperties.bAudioIsEditable = M4OSA_FALSE;
9525    pC->InputFileProperties.bVideoIsCompatibleWithMasterClip = M4OSA_FALSE;
9526    pC->InputFileProperties.bAudioIsCompatibleWithMasterClip = M4OSA_FALSE;
9527
9528    /**
9529    * Video stream properties */
9530    if( M4OSA_NULL != pC->pReaderVideoStream )
9531    {
9532        switch( pC->pReaderVideoStream->m_basicProperties.m_streamType )
9533        {
9534            case M4DA_StreamTypeVideoMpeg4:
9535                pC->InputFileProperties.VideoStreamType = M4VIDEOEDITING_kMPEG4;
9536                break;
9537
9538            case M4DA_StreamTypeVideoH263:
9539                pC->InputFileProperties.VideoStreamType = M4VIDEOEDITING_kH263;
9540                break;
9541
9542            case M4DA_StreamTypeVideoMpeg4Avc:
9543                pC->InputFileProperties.VideoStreamType = M4VIDEOEDITING_kH264;
9544                break;
9545
9546            case M4DA_StreamTypeUnknown:
9547            default:
9548                pC->InputFileProperties.VideoStreamType =
9549                    M4VIDEOEDITING_kUnsupportedVideo;
9550                break;
9551        }
9552
9553        /* if bitrate not available retrieve an estimation of the overall bitrate */
9554        pC->InputFileProperties.uiVideoBitrate =
9555            pC->pReaderVideoStream->m_basicProperties.m_averageBitRate;
9556
9557        if( 0 == pC->InputFileProperties.uiVideoBitrate )
9558        {
9559            pC->m_pReader->m_pFctGetOption(pC->pReaderContext,
9560                M4READER_kOptionID_Bitrate, &videoBitrate);
9561
9562            if( M4OSA_NULL != pC->pReaderAudioStream )
9563            {
9564                /* we get the overall bitrate, substract the audio bitrate if any */
9565                videoBitrate -=
9566                    pC->pReaderAudioStream->m_basicProperties.m_averageBitRate;
9567            }
9568            pC->InputFileProperties.uiVideoBitrate = videoBitrate;
9569        }
9570
9571        /**
9572        * Retrieve the Profile & Level */
9573        if( ( M4VIDEOEDITING_kH263 != pC->InputFileProperties.VideoStreamType)
9574            && (M4VIDEOEDITING_kH264
9575            != pC->InputFileProperties.VideoStreamType) )
9576        {
9577#ifdef M4VSS_ENABLE_EXTERNAL_DECODERS
9578            /* Use the DSI parsing function from the external video shell decoder.
9579            See the comments in M4VSS3GPP_ClipAnalysis.c, it's pretty much the
9580            same issue. */
9581
9582            err = M4DECODER_EXTERNAL_ParseVideoDSI(pC->pReaderVideoStream->
9583                m_basicProperties.m_pDecoderSpecificInfo,
9584                pC->pReaderVideoStream->
9585                m_basicProperties.m_decoderSpecificInfoSize,
9586                &DecConfInfo, &videoSize);
9587
9588            if( M4NO_ERROR != err )
9589            {
9590                M4OSA_TRACE1_1(
9591                    "M4MCS_intGetInputClipProperties():\
9592                     M4DECODER_EXTERNAL_ParseVideoDSI returns 0x%08X",
9593                    err);
9594                return err;
9595            }
9596
9597            pC->pReaderVideoStream->m_videoWidth = videoSize.m_uiWidth;
9598            pC->pReaderVideoStream->m_videoHeight = videoSize.m_uiHeight;
9599
9600#else
9601            /*FB 2009-02-09: add a check on the video decoder context to
9602            avoid crash when the MCS is used only with audio codecs compilated*/
9603
9604            if( pC->m_pVideoDecoder != M4OSA_NULL )
9605            {
9606                if( M4OSA_NULL == pC->pViDecCtxt )
9607                {
9608                    err = pC->m_pVideoDecoder->m_pFctCreate(&pC->pViDecCtxt,
9609                        &pC->pReaderVideoStream->m_basicProperties,
9610                        pC->m_pReaderDataIt, &pC->ReaderVideoAU,
9611                        M4OSA_NULL);
9612
9613                    if( M4NO_ERROR != err )
9614                    {
9615                        M4OSA_TRACE1_1(
9616                            "M4MCS_intGetInputClipProperties:\
9617                             m_pVideoDecoder->m_pFctCreate returns 0x%x!",
9618                            err);
9619                        return err;
9620                    }
9621                }
9622
9623                err = pC->m_pVideoDecoder->m_pFctGetOption(pC->pViDecCtxt,
9624                    M4DECODER_MPEG4_kOptionID_DecoderConfigInfo,
9625                    &DecConfInfo);
9626
9627                if( M4NO_ERROR != err )
9628                {
9629                    M4OSA_TRACE1_1(
9630                        "M4MCS_intGetInputClipProperties:\
9631                         m_pVideoDecoder->m_pFctGetOption returns 0x%x!",
9632                        err);
9633                    return err;
9634                }
9635            }
9636
9637#endif /* M4VSS_ENABLE_EXTERNAL_DECODERS */
9638
9639            pC->InputFileProperties.uiVideoProfile = DecConfInfo.uiProfile;
9640            pC->InputFileProperties.uiVideoTimeScale = DecConfInfo.uiTimeScale;
9641            pC->InputFileProperties.bMPEG4dataPartition =
9642                DecConfInfo.bDataPartition;
9643            pC->InputFileProperties.bMPEG4rvlc = DecConfInfo.bUseOfRVLC;
9644            pC->InputFileProperties.bMPEG4resynchMarker =
9645                DecConfInfo.uiUseOfResynchMarker;
9646
9647            /* Supported enum value for profile and level */
9648            switch( pC->InputFileProperties.uiVideoProfile )
9649            {
9650                case 0x08:
9651                    pC->InputFileProperties.ProfileAndLevel =
9652                        M4VIDEOEDITING_kMPEG4_SP_Level_0;
9653                    break;
9654
9655                case 0x09:
9656                    pC->InputFileProperties.ProfileAndLevel =
9657                        M4VIDEOEDITING_kMPEG4_SP_Level_0b;
9658                    break;
9659
9660                case 0x01:
9661                    pC->InputFileProperties.ProfileAndLevel =
9662                        M4VIDEOEDITING_kMPEG4_SP_Level_1;
9663                    break;
9664
9665                case 0x02:
9666                    pC->InputFileProperties.ProfileAndLevel =
9667                        M4VIDEOEDITING_kMPEG4_SP_Level_2;
9668                    break;
9669
9670                case 0x03:
9671                    pC->InputFileProperties.ProfileAndLevel =
9672                        M4VIDEOEDITING_kMPEG4_SP_Level_3;
9673                    break;
9674
9675                case 0x04:
9676                    pC->InputFileProperties.ProfileAndLevel =
9677                        M4VIDEOEDITING_kMPEG4_SP_Level_4a;
9678                    break;
9679
9680                case 0x05:
9681                    pC->InputFileProperties.ProfileAndLevel =
9682                        M4VIDEOEDITING_kMPEG4_SP_Level_5;
9683                    break;
9684            }
9685        }
9686        else if( M4VIDEOEDITING_kH263
9687            == pC->InputFileProperties.VideoStreamType )
9688        {
9689            err = pC->m_pReader->m_pFctGetOption(pC->pReaderContext,
9690                M4READER_3GP_kOptionID_H263Properties, &H263prop);
9691
9692            if( M4NO_ERROR != err )
9693            {
9694                M4OSA_TRACE1_1(
9695                    "M4MCS_intGetInputClipProperties: m_pReader->m_pFctGetOption returns 0x%x!",
9696                    err);
9697                return err;
9698            }
9699
9700            pC->InputFileProperties.uiH263level = H263prop.uiLevel;
9701            pC->InputFileProperties.uiVideoProfile = H263prop.uiProfile;
9702
9703            /* Supported enum value for profile and level */
9704            if( pC->InputFileProperties.uiVideoProfile == 0 )
9705            {
9706                switch( pC->InputFileProperties.uiH263level )
9707                {
9708                    case 10:
9709                        pC->InputFileProperties.ProfileAndLevel =
9710                            M4VIDEOEDITING_kH263_Profile_0_Level_10;
9711                        break;
9712
9713                    case 20:
9714                        pC->InputFileProperties.ProfileAndLevel =
9715                            M4VIDEOEDITING_kH263_Profile_0_Level_20;
9716                        break;
9717
9718                    case 30:
9719                        pC->InputFileProperties.ProfileAndLevel =
9720                            M4VIDEOEDITING_kH263_Profile_0_Level_30;
9721                        break;
9722
9723                    case 40:
9724                        pC->InputFileProperties.ProfileAndLevel =
9725                            M4VIDEOEDITING_kH263_Profile_0_Level_40;
9726                        break;
9727
9728                    case 45:
9729                        pC->InputFileProperties.ProfileAndLevel =
9730                            M4VIDEOEDITING_kH263_Profile_0_Level_45;
9731                        break;
9732                }
9733            }
9734
9735            /* For h263 set default timescale : 30000:1001 */
9736            pC->InputFileProperties.uiVideoTimeScale = 30000;
9737        }
9738        else if( M4VIDEOEDITING_kH264
9739            == pC->InputFileProperties.VideoStreamType )
9740        {
9741            AVCProfle = M4DECODER_AVC_kProfile_and_Level_Out_Of_Range;
9742            pC->InputFileProperties.uiVideoTimeScale = 30000;
9743#ifdef M4VSS_ENABLE_EXTERNAL_DECODERS
9744
9745            err = M4DECODER_EXTERNAL_ParseAVCDSI(pC->pReaderVideoStream->
9746                m_basicProperties.m_pDecoderSpecificInfo,
9747                pC->pReaderVideoStream->
9748                m_basicProperties.m_decoderSpecificInfoSize,
9749                &AVCProfle);
9750
9751            if( M4NO_ERROR != err )
9752            {
9753                M4OSA_TRACE1_1(
9754                    "M4MCS_intGetInputClipProperties():\
9755                     M4DECODER_EXTERNAL_ParseAVCDSI returns 0x%08X",
9756                    err);
9757                return err;
9758            }
9759
9760#else
9761
9762            if( pC->m_pVideoDecoder != M4OSA_NULL )
9763            {
9764                if( M4OSA_NULL == pC->pViDecCtxt )
9765                {
9766                    err = pC->m_pVideoDecoder->m_pFctCreate(&pC->pViDecCtxt,
9767                        &pC->pReaderVideoStream->m_basicProperties,
9768                        pC->m_pReaderDataIt, &pC->ReaderVideoAU,
9769                        M4OSA_NULL);
9770
9771                    if( M4NO_ERROR != err )
9772                    {
9773                        M4OSA_TRACE1_1(
9774                            "M4MCS_intGetInputClipProperties:\
9775                             m_pVideoDecoder->m_pFctCreate returns 0x%x!",
9776                            err);
9777                        return err;
9778                    }
9779                }
9780                err = pC->m_pVideoDecoder->m_pFctGetOption(pC->pViDecCtxt,
9781                    M4DECODER_kOptionID_AVCProfileAndLevel, &AVCProfle);
9782
9783                if( M4NO_ERROR != err )
9784                {
9785                    M4OSA_TRACE1_1(
9786                        "M4MCS_intGetInputClipProperties:\
9787                         m_pVideoDecoder->m_pFctGetOption returns 0x%x!",
9788                        err);
9789                    return err;
9790                }
9791            }
9792
9793#endif /* M4VSS_ENABLE_EXTERNAL_DECODERS */
9794
9795            switch( AVCProfle )
9796            {
9797                case M4DECODER_AVC_kProfile_0_Level_1:
9798                    pC->InputFileProperties.ProfileAndLevel =
9799                        M4VIDEOEDITING_kH264_Profile_0_Level_1;
9800                    break;
9801
9802                case M4DECODER_AVC_kProfile_0_Level_1b:
9803                    pC->InputFileProperties.ProfileAndLevel =
9804                        M4VIDEOEDITING_kH264_Profile_0_Level_1b;
9805                    break;
9806
9807                case M4DECODER_AVC_kProfile_0_Level_1_1:
9808                    pC->InputFileProperties.ProfileAndLevel =
9809                        M4VIDEOEDITING_kH264_Profile_0_Level_1_1;
9810                    break;
9811
9812                case M4DECODER_AVC_kProfile_0_Level_1_2:
9813                    pC->InputFileProperties.ProfileAndLevel =
9814                        M4VIDEOEDITING_kH264_Profile_0_Level_1_2;
9815                    break;
9816
9817                case M4DECODER_AVC_kProfile_0_Level_1_3:
9818                    pC->InputFileProperties.ProfileAndLevel =
9819                        M4VIDEOEDITING_kH264_Profile_0_Level_1_3;
9820                    break;
9821
9822                case M4DECODER_AVC_kProfile_0_Level_2:
9823                    pC->InputFileProperties.ProfileAndLevel =
9824                        M4VIDEOEDITING_kH264_Profile_0_Level_2;
9825                    break;
9826
9827                case M4DECODER_AVC_kProfile_0_Level_2_1:
9828                    pC->InputFileProperties.ProfileAndLevel =
9829                        M4VIDEOEDITING_kH264_Profile_0_Level_2_1;
9830                    break;
9831
9832                case M4DECODER_AVC_kProfile_0_Level_2_2:
9833                    pC->InputFileProperties.ProfileAndLevel =
9834                        M4VIDEOEDITING_kH264_Profile_0_Level_2_2;
9835                    break;
9836
9837                case M4DECODER_AVC_kProfile_0_Level_3:
9838                    pC->InputFileProperties.ProfileAndLevel =
9839                        M4VIDEOEDITING_kH264_Profile_0_Level_3;
9840                    break;
9841
9842                case M4DECODER_AVC_kProfile_0_Level_3_1:
9843                    pC->InputFileProperties.ProfileAndLevel =
9844                        M4VIDEOEDITING_kH264_Profile_0_Level_3_1;
9845                    break;
9846
9847                case M4DECODER_AVC_kProfile_0_Level_3_2:
9848                    pC->InputFileProperties.ProfileAndLevel =
9849                        M4VIDEOEDITING_kH264_Profile_0_Level_3_2;
9850                    break;
9851
9852                case M4DECODER_AVC_kProfile_0_Level_4:
9853                    pC->InputFileProperties.ProfileAndLevel =
9854                        M4VIDEOEDITING_kH264_Profile_0_Level_4;
9855                    break;
9856
9857                case M4DECODER_AVC_kProfile_0_Level_4_1:
9858                    pC->InputFileProperties.ProfileAndLevel =
9859                        M4VIDEOEDITING_kH264_Profile_0_Level_4_1;
9860                    break;
9861
9862                case M4DECODER_AVC_kProfile_0_Level_4_2:
9863                    pC->InputFileProperties.ProfileAndLevel =
9864                        M4VIDEOEDITING_kH264_Profile_0_Level_4_2;
9865                    break;
9866
9867                case M4DECODER_AVC_kProfile_0_Level_5:
9868                    pC->InputFileProperties.ProfileAndLevel =
9869                        M4VIDEOEDITING_kH264_Profile_0_Level_5;
9870                    break;
9871
9872                case M4DECODER_AVC_kProfile_0_Level_5_1:
9873                    pC->InputFileProperties.ProfileAndLevel =
9874                        M4VIDEOEDITING_kH264_Profile_0_Level_5_1;
9875                    break;
9876
9877                case M4DECODER_AVC_kProfile_and_Level_Out_Of_Range:
9878                default:
9879                    pC->InputFileProperties.ProfileAndLevel =
9880                        M4VIDEOEDITING_kProfile_and_Level_Out_Of_Range;
9881            }
9882        }
9883
9884        /* Here because width x height is correct only after dsi parsing
9885        (done in create decoder) */
9886        pC->InputFileProperties.uiVideoHeight =
9887            pC->pReaderVideoStream->m_videoHeight;
9888        pC->InputFileProperties.uiVideoWidth =
9889            pC->pReaderVideoStream->m_videoWidth;
9890        pC->InputFileProperties.uiClipVideoDuration =
9891            (M4OSA_UInt32)pC->pReaderVideoStream->m_basicProperties.m_duration;
9892        pC->InputFileProperties.fAverageFrameRate =
9893            pC->pReaderVideoStream->m_averageFrameRate;
9894        pC->InputFileProperties.uiVideoMaxAuSize =
9895            pC->pReaderVideoStream->m_basicProperties.m_maxAUSize;
9896    }
9897    else
9898    {
9899        if( M4OSA_TRUE == pC->bUnsupportedVideoFound )
9900        {
9901            pC->InputFileProperties.VideoStreamType =
9902                M4VIDEOEDITING_kUnsupportedVideo;
9903        }
9904        else
9905        {
9906            pC->InputFileProperties.VideoStreamType = M4VIDEOEDITING_kNoneVideo;
9907        }
9908    }
9909
9910    /**
9911    * Audio stream properties */
9912    if( M4OSA_NULL != pC->pReaderAudioStream )
9913    {
9914        switch( pC->pReaderAudioStream->m_basicProperties.m_streamType )
9915        {
9916            case M4DA_StreamTypeAudioAmrNarrowBand:
9917                pC->InputFileProperties.AudioStreamType =
9918                    M4VIDEOEDITING_kAMR_NB;
9919                break;
9920
9921            case M4DA_StreamTypeAudioAac:
9922                pC->InputFileProperties.AudioStreamType = M4VIDEOEDITING_kAAC;
9923                break;
9924
9925            case M4DA_StreamTypeAudioMp3:
9926                pC->InputFileProperties.AudioStreamType = M4VIDEOEDITING_kMP3;
9927                break;
9928
9929            case M4DA_StreamTypeAudioEvrc:
9930                pC->InputFileProperties.AudioStreamType = M4VIDEOEDITING_kEVRC;
9931                break;
9932
9933            case M4DA_StreamTypeUnknown:
9934            default:
9935                pC->InputFileProperties.AudioStreamType =
9936                    M4VIDEOEDITING_kUnsupportedAudio;
9937                break;
9938        }
9939
9940        if( ( M4OSA_NULL != pC->m_pAudioDecoder)
9941            && (M4OSA_NULL == pC->pAudioDecCtxt) )
9942        {
9943            M4OSA_TRACE3_1(
9944                "M4MCS_intGetInputClipProperties: calling CreateAudioDecoder, userData= 0x%x",
9945                pC->m_pCurrentAudioDecoderUserData);
9946            /* Trick, I use pUserData to retrieve aac properties, waiting for some
9947             better implementation... */
9948            if( M4DA_StreamTypeAudioAac
9949                == pC->pReaderAudioStream->m_basicProperties.m_streamType )
9950            {
9951                if( M4OSA_FALSE == pC->bExtOMXAudDecoder )
9952                    err = pC->m_pAudioDecoder->m_pFctCreateAudioDec(
9953                    &pC->pAudioDecCtxt,
9954                    pC->pReaderAudioStream, &(pC->AacProperties));
9955                else
9956                {
9957                    err = pC->m_pAudioDecoder->m_pFctCreateAudioDec(
9958                        &pC->pAudioDecCtxt, pC->pReaderAudioStream,
9959                        pC->m_pCurrentAudioDecoderUserData);
9960
9961                    if( M4NO_ERROR == err )
9962                    {
9963                        /* AAC properties*/
9964                        //get from Reader; temporary, till Audio decoder shell API available to
9965                        //get the AAC properties
9966                        pC->AacProperties.aNumChan =
9967                            pC->pReaderAudioStream->m_nbChannels;
9968                        pC->AacProperties.aSampFreq =
9969                            pC->pReaderAudioStream->m_samplingFrequency;
9970
9971                        err = pC->m_pAudioDecoder->m_pFctGetOptionAudioDec(
9972                            pC->pAudioDecCtxt, M4AD_kOptionID_StreamType,
9973                            (M4OSA_DataOption) &iAacType);
9974
9975                        if( M4NO_ERROR != err )
9976                        {
9977                            M4OSA_TRACE1_1(
9978                                "M4MCS_intGetInputClipProperties:\
9979                                 m_pAudioDecoder->m_pFctGetOptionAudioDec returns err 0x%x",
9980                                err);
9981                            iAacType = M4_kAAC; //set to default
9982                            err = M4NO_ERROR;
9983                        }
9984                        else
9985                        {
9986                            M4OSA_TRACE3_1(
9987                                "M4MCS_intGetInputClipProperties:\
9988                                 m_pAudioDecoder->m_pFctGetOptionAudioDec returns streamType %d",
9989                                iAacType);
9990                        }
9991
9992                        switch( iAacType )
9993                        {
9994                            case M4_kAAC:
9995                                pC->AacProperties.aSBRPresent = 0;
9996                                pC->AacProperties.aPSPresent = 0;
9997                                break;
9998
9999                            case M4_kAACplus:
10000                                pC->AacProperties.aSBRPresent = 1;
10001                                pC->AacProperties.aPSPresent = 0;
10002                                pC->AacProperties.aExtensionSampFreq =
10003                                    pC->pReaderAudioStream->
10004                                    m_samplingFrequency; //TODO
10005                                break;
10006
10007                            case M4_keAACplus:
10008                                pC->AacProperties.aSBRPresent = 1;
10009                                pC->AacProperties.aPSPresent = 1;
10010                                pC->AacProperties.aExtensionSampFreq =
10011                                    pC->pReaderAudioStream->
10012                                    m_samplingFrequency; //TODO
10013                                break;
10014                              case M4_kUnknown:
10015                              break;
10016                              default:
10017                              break;
10018                            }
10019                            M4OSA_TRACE3_2(
10020                                "M4MCS_intGetInputClipProperties: AAC NBChans=%d, SamplFreq=%d",
10021                                pC->AacProperties.aNumChan,
10022                                pC->AacProperties.aSampFreq);
10023                    }
10024                }
10025            }
10026            else
10027                err = pC->m_pAudioDecoder->m_pFctCreateAudioDec(
10028                &pC->pAudioDecCtxt, pC->pReaderAudioStream,
10029                pC->m_pCurrentAudioDecoderUserData);
10030
10031            if( M4NO_ERROR != err )
10032            {
10033                M4OSA_TRACE1_1(
10034                    "M4MCS_intGetInputClipProperties:\
10035                     m_pAudioDecoder->m_pFctCreateAudioDec returns 0x%x",
10036                    err);
10037                return err;
10038            }
10039        }
10040
10041        //EVRC
10042        if( pC->pReaderAudioStream->m_basicProperties.m_streamType
10043            == M4DA_StreamTypeAudioEvrc )
10044        {
10045            /* decoder not implemented yet, provide some default values for the null encoding */
10046            pC->pReaderAudioStream->m_nbChannels = 1;
10047            pC->pReaderAudioStream->m_samplingFrequency = 8000;
10048        }
10049
10050        /**
10051        * Bugfix P4ME00001128: With some IMTC files, the AMR bit rate is 0 kbps according
10052         the GetProperties function */
10053        if( 0 == pC->pReaderAudioStream->m_basicProperties.m_averageBitRate )
10054        {
10055            if( M4VIDEOEDITING_kAMR_NB
10056                == pC->InputFileProperties.AudioStreamType )
10057            {
10058                /**
10059                * Better returning a guessed 12.2 kbps value than a sure-to-be-false
10060                0 kbps value! */
10061                pC->InputFileProperties.uiAudioBitrate =
10062                    M4VIDEOEDITING_k12_2_KBPS;
10063            }
10064            else if( M4VIDEOEDITING_kEVRC
10065                == pC->InputFileProperties.AudioStreamType )
10066            {
10067                /**
10068                * Better returning a guessed 8.5 kbps value than a sure-to-be-false
10069                0 kbps value! */
10070                pC->InputFileProperties.uiAudioBitrate =
10071                    M4VIDEOEDITING_k9_2_KBPS;
10072            }
10073            else
10074            {
10075                M4OSA_UInt32 FileBitrate;
10076
10077                /* Can happen also for aac, in this case we calculate an approximative */
10078                /* value from global bitrate and video bitrate */
10079                err = pC->m_pReader->m_pFctGetOption(pC->pReaderContext,
10080                    M4READER_kOptionID_Bitrate,
10081                    (M4OSA_DataOption) &FileBitrate);
10082
10083                if( M4NO_ERROR != err )
10084                {
10085                    M4OSA_TRACE1_1(
10086                        "M4MCS_intGetInputClipProperties: M4READER_kOptionID_Bitrate returns 0x%x",
10087                        err);
10088                    return err;
10089                }
10090                pC->InputFileProperties.uiAudioBitrate =
10091                    FileBitrate
10092                    - pC->
10093                    InputFileProperties.
10094                    uiVideoBitrate /* normally setted to 0, if no video */;
10095            }
10096        }
10097        else
10098        {
10099            pC->InputFileProperties.uiAudioBitrate =
10100                pC->pReaderAudioStream->m_basicProperties.m_averageBitRate;
10101        }
10102
10103        pC->InputFileProperties.uiNbChannels =
10104            pC->pReaderAudioStream->m_nbChannels;
10105        pC->InputFileProperties.uiSamplingFrequency =
10106            pC->pReaderAudioStream->m_samplingFrequency;
10107        pC->InputFileProperties.uiClipAudioDuration =
10108            (M4OSA_UInt32)pC->pReaderAudioStream->m_basicProperties.m_duration;
10109        pC->InputFileProperties.uiAudioMaxAuSize =
10110            pC->pReaderAudioStream->m_basicProperties.m_maxAUSize;
10111
10112        /* Bug: with aac, value is 0 until decoder start() is called */
10113        pC->InputFileProperties.uiDecodedPcmSize =
10114            pC->pReaderAudioStream->m_byteFrameLength
10115            * pC->pReaderAudioStream->m_byteSampleSize
10116            * pC->pReaderAudioStream->m_nbChannels;
10117
10118        /* New aac properties */
10119        if( M4DA_StreamTypeAudioAac
10120            == pC->pReaderAudioStream->m_basicProperties.m_streamType )
10121        {
10122            pC->InputFileProperties.uiNbChannels = pC->AacProperties.aNumChan;
10123            pC->InputFileProperties.uiSamplingFrequency =
10124                pC->AacProperties.aSampFreq;
10125
10126            if( pC->AacProperties.aSBRPresent )
10127            {
10128                pC->InputFileProperties.AudioStreamType =
10129                    M4VIDEOEDITING_kAACplus;
10130                pC->InputFileProperties.uiExtendedSamplingFrequency =
10131                    pC->AacProperties.aExtensionSampFreq;
10132            }
10133
10134            if( pC->AacProperties.aPSPresent )
10135            {
10136                pC->InputFileProperties.AudioStreamType =
10137                    M4VIDEOEDITING_keAACplus;
10138            }
10139        }
10140    }
10141    else
10142    {
10143        if( M4OSA_TRUE == pC->bUnsupportedAudioFound )
10144        {
10145            pC->InputFileProperties.AudioStreamType =
10146                M4VIDEOEDITING_kUnsupportedAudio;
10147        }
10148        else
10149        {
10150            pC->InputFileProperties.AudioStreamType = M4VIDEOEDITING_kNoneAudio;
10151        }
10152    }
10153
10154    /* Get 'ftyp' atom */
10155    err = pC->m_pReader->m_pFctGetOption(pC->pReaderContext,
10156        M4READER_kOptionID_3gpFtypBox, &pC->InputFileProperties.ftyp);
10157
10158    if( M4NO_ERROR == err )
10159    {
10160        M4OSA_UInt8 i;
10161
10162        for ( i = 0; i < pC->InputFileProperties.ftyp.nbCompatibleBrands; i++ )
10163            if( M4VIDEOEDITING_BRAND_EMP
10164                == pC->InputFileProperties.ftyp.compatible_brands[i] )
10165                pC->InputFileProperties.VideoStreamType =
10166                M4VIDEOEDITING_kMPEG4_EMP;
10167    }
10168
10169    /* Analysis is successful */
10170    if( pC->InputFileProperties.uiClipVideoDuration
10171        > pC->InputFileProperties.uiClipAudioDuration )
10172        pC->InputFileProperties.uiClipDuration =
10173        pC->InputFileProperties.uiClipVideoDuration;
10174    else
10175        pC->InputFileProperties.uiClipDuration =
10176        pC->InputFileProperties.uiClipAudioDuration;
10177
10178    pC->InputFileProperties.FileType = pC->InputFileType;
10179    pC->InputFileProperties.bAnalysed = M4OSA_TRUE;
10180
10181    return M4NO_ERROR;
10182}
10183
10184/**
10185 ******************************************************************************
10186 * M4OSA_UInt32 M4MCS_intGetFrameSize_AMRNB(M4OSA_MemAddr8 pAudioFrame)
10187 * @brief   Return the length, in bytes, of the AMR Narrow-Band frame contained in the given buffer
10188 * @note
10189 * @param   pCpAudioFrame   (IN) AMRNB frame
10190 * @return  M4NO_ERROR: No error
10191 ******************************************************************************
10192 */
10193static M4OSA_UInt32 M4MCS_intGetFrameSize_AMRNB( M4OSA_MemAddr8 pAudioFrame )
10194{
10195    M4OSA_UInt32 frameSize = 0;
10196    M4OSA_UInt32 frameType = ( ( *pAudioFrame) &(0xF << 3)) >> 3;
10197
10198    switch( frameType )
10199    {
10200        case 0:
10201            frameSize = 95;
10202            break; /*  4750 bps */
10203
10204        case 1:
10205            frameSize = 103;
10206            break; /*  5150 bps */
10207
10208        case 2:
10209            frameSize = 118;
10210            break; /*  5900 bps */
10211
10212        case 3:
10213            frameSize = 134;
10214            break; /*  6700 bps */
10215
10216        case 4:
10217            frameSize = 148;
10218            break; /*  7400 bps */
10219
10220        case 5:
10221            frameSize = 159;
10222            break; /*  7950 bps */
10223
10224        case 6:
10225            frameSize = 204;
10226            break; /* 10200 bps */
10227
10228        case 7:
10229            frameSize = 244;
10230            break; /* 12000 bps */
10231
10232        case 8:
10233            frameSize = 39;
10234            break; /* SID (Silence) */
10235
10236        case 15:
10237            frameSize = 0;
10238            break; /* No data */
10239
10240        default:
10241            M4OSA_TRACE3_0(
10242                "M4MCS_intGetFrameSize_AMRNB(): Corrupted AMR frame! returning 0.");
10243            return 0;
10244    }
10245
10246    return (1 + (( frameSize + 7) / 8));
10247}
10248
10249/**
10250 ******************************************************************************
10251 * M4OSA_UInt32 M4MCS_intGetFrameSize_EVRC(M4OSA_MemAddr8 pAudioFrame)
10252 * @brief   Return the length, in bytes, of the EVRC frame contained in the given buffer
10253 * @note
10254 *     0 1 2 3
10255 *    +-+-+-+-+
10256 *    |fr type|              RFC 3558
10257 *    +-+-+-+-+
10258 *
10259 * Frame Type: 4 bits
10260 *    The frame type indicates the type of the corresponding codec data
10261 *    frame in the RTP packet.
10262 *
10263 * For EVRC and SMV codecs, the frame type values and size of the
10264 * associated codec data frame are described in the table below:
10265 *
10266 * Value   Rate      Total codec data frame size (in octets)
10267 * ---------------------------------------------------------
10268 *   0     Blank      0    (0 bit)
10269 *   1     1/8        2    (16 bits)
10270 *   2     1/4        5    (40 bits; not valid for EVRC)
10271 *   3     1/2       10    (80 bits)
10272 *   4     1         22    (171 bits; 5 padded at end with zeros)
10273 *   5     Erasure    0    (SHOULD NOT be transmitted by sender)
10274 *
10275 * @param   pCpAudioFrame   (IN) EVRC frame
10276 * @return  M4NO_ERROR: No error
10277 ******************************************************************************
10278 */
10279static M4OSA_UInt32 M4MCS_intGetFrameSize_EVRC( M4OSA_MemAddr8 pAudioFrame )
10280{
10281    M4OSA_UInt32 frameSize = 0;
10282    M4OSA_UInt32 frameType = ( *pAudioFrame) &0x0F;
10283
10284    switch( frameType )
10285    {
10286        case 0:
10287            frameSize = 0;
10288            break; /*  blank */
10289
10290        case 1:
10291            frameSize = 16;
10292            break; /*  1/8 */
10293
10294        case 2:
10295            frameSize = 40;
10296            break; /*  1/4 */
10297
10298        case 3:
10299            frameSize = 80;
10300            break; /*  1/2 */
10301
10302        case 4:
10303            frameSize = 171;
10304            break; /*  1 */
10305
10306        case 5:
10307            frameSize = 0;
10308            break; /*  erasure */
10309
10310        default:
10311            M4OSA_TRACE3_0(
10312                "M4MCS_intGetFrameSize_EVRC(): Corrupted EVRC frame! returning 0.");
10313            return 0;
10314    }
10315
10316    return (1 + (( frameSize + 7) / 8));
10317}
10318
10319/**
10320 ******************************************************************************
10321 * M4OSA_ERR M4MCS_intCheckMaxFileSize(M4MCS_Context pContext)
10322 * @brief    Check if max file size is greater enough to encode a file with the
10323 *           current selected bitrates and duration.
10324 * @param    pContext            (IN) MCS context
10325 * @return   M4NO_ERROR
10326 * @return   M4MCS_ERR_MAXFILESIZE_TOO_SMALL
10327 ******************************************************************************
10328 */
10329static M4OSA_ERR M4MCS_intCheckMaxFileSize( M4MCS_Context pContext )
10330{
10331    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
10332
10333    M4OSA_UInt32 duration;
10334    M4OSA_UInt32 audiobitrate;
10335    M4OSA_UInt32 videobitrate;
10336
10337    /* free file size : OK */
10338    if( pC->uiMaxFileSize == 0 )
10339        return M4NO_ERROR;
10340
10341    /* duration */
10342    if( pC->uiEndCutTime == 0 )
10343    {
10344        duration = pC->InputFileProperties.uiClipDuration - pC->uiBeginCutTime;
10345    }
10346    else
10347    {
10348        duration = pC->uiEndCutTime - pC->uiBeginCutTime;
10349    }
10350
10351    /* audio bitrate */
10352    if( pC->noaudio )
10353    {
10354        audiobitrate = 0;
10355    }
10356    else if( pC->AudioEncParams.Format == M4ENCODER_kAudioNULL )
10357    {
10358        audiobitrate = pC->InputFileProperties.uiAudioBitrate;
10359    }
10360    else if( pC->uiAudioBitrate == M4VIDEOEDITING_kUndefinedBitrate )
10361    {
10362        switch( pC->AudioEncParams.Format )
10363        {
10364            case M4ENCODER_kAMRNB:
10365                audiobitrate = M4VIDEOEDITING_k12_2_KBPS;
10366                break;
10367                //EVRC
10368                //            case M4ENCODER_kEVRC:
10369                //                audiobitrate = M4VIDEOEDITING_k9_2_KBPS;
10370                //                break;
10371
10372            default: /* AAC and MP3*/
10373                audiobitrate =
10374                    (pC->AudioEncParams.ChannelNum == M4ENCODER_kMono)
10375                    ? M4VIDEOEDITING_k16_KBPS : M4VIDEOEDITING_k32_KBPS;
10376                break;
10377        }
10378    }
10379    else
10380    {
10381        audiobitrate = pC->uiAudioBitrate;
10382    }
10383
10384    /* video bitrate */
10385    if( pC->novideo )
10386    {
10387        videobitrate = 0;
10388    }
10389    else if( pC->EncodingVideoFormat == M4ENCODER_kNULL )
10390    {
10391        videobitrate = pC->InputFileProperties.uiVideoBitrate;
10392    }
10393    else if( pC->uiVideoBitrate == M4VIDEOEDITING_kUndefinedBitrate )
10394    {
10395        videobitrate = M4VIDEOEDITING_k16_KBPS;
10396    }
10397    else
10398    {
10399        videobitrate = pC->uiVideoBitrate;
10400    }
10401
10402    /* max file size */
10403    if( (M4OSA_UInt32)pC->uiMaxFileSize
10404        < (M4OSA_UInt32)(M4MCS_MOOV_OVER_FILESIZE_RATIO
10405        * (audiobitrate + videobitrate) * (duration / 8000.0)) )
10406        return M4MCS_ERR_MAXFILESIZE_TOO_SMALL;
10407    else
10408        return M4NO_ERROR;
10409}
10410
10411/**
10412 ******************************************************************************
10413 * M4VIDEOEDITING_Bitrate M4MCS_intGetNearestBitrate(M4OSA_UInt32 freebitrate, M4OSA_Int8 mode)
10414 * @brief    Returns the closest bitrate value from the enum list of type M4VIDEOEDITING_Bitrate
10415 * @param    freebitrate: unsigned int value
10416 * @param    mode: -1:previous,0:current,1:next
10417 * @return   bitrate value in enum list M4VIDEOEDITING_Bitrate
10418 ******************************************************************************
10419 */
10420static M4VIDEOEDITING_Bitrate
10421M4MCS_intGetNearestBitrate( M4OSA_Int32 freebitrate, M4OSA_Int8 mode )
10422{
10423    M4OSA_Int32 bitarray [] =
10424    {
10425        0, M4VIDEOEDITING_k16_KBPS, M4VIDEOEDITING_k24_KBPS,
10426        M4VIDEOEDITING_k32_KBPS, M4VIDEOEDITING_k48_KBPS,
10427        M4VIDEOEDITING_k64_KBPS, M4VIDEOEDITING_k96_KBPS,
10428        M4VIDEOEDITING_k128_KBPS, M4VIDEOEDITING_k192_KBPS,
10429        M4VIDEOEDITING_k256_KBPS, M4VIDEOEDITING_k288_KBPS,
10430        M4VIDEOEDITING_k384_KBPS, M4VIDEOEDITING_k512_KBPS,
10431        M4VIDEOEDITING_k800_KBPS, M4VIDEOEDITING_k2_MBPS,
10432        M4VIDEOEDITING_k5_MBPS,
10433        M4VIDEOEDITING_k8_MBPS, /*+ New Encoder bitrates */
10434        M4OSA_INT32_MAX
10435    };
10436
10437    const M4OSA_UInt32 nbbitrates = 14;
10438    M4OSA_UInt32 i;
10439
10440    for ( i = 0; freebitrate >= bitarray[i]; i++ );
10441
10442    switch( mode )
10443    {
10444        case -1: /* previous */
10445            if( i <= 2 )
10446                return 0;
10447            else
10448                return bitarray[i - 2];
10449            break;
10450
10451        case 0: /* current */
10452            if( i <= 1 )
10453                return 0;
10454            else
10455                return bitarray[i - 1];
10456            break;
10457
10458        case 1: /* next */
10459            if( i >= nbbitrates )
10460                return M4OSA_INT32_MAX;
10461            else
10462                return bitarray[i];
10463            break;
10464    }
10465
10466    return 0;
10467}
10468
10469/**
10470 ******************************************************************************
10471 * M4OSA_ERR M4MCS_intCleanUp_ReadersDecoders(M4MCS_InternalContext* pC);
10472 * @brief    Free all resources allocated by M4MCS_open()
10473 * @param    pContext            (IN) MCS context
10474 * @return   M4NO_ERROR:         No error
10475 ******************************************************************************
10476 */
10477static M4OSA_ERR M4MCS_intCleanUp_ReadersDecoders( M4MCS_InternalContext *pC )
10478{
10479    M4OSA_ERR err = M4NO_ERROR;
10480
10481    M4OSA_TRACE2_1("M4MCS_intCleanUp_ReadersDecoders called with pC=0x%x", pC);
10482
10483    /* ----- Free reader stuff, if needed ----- */
10484
10485    if( M4OSA_NULL != pC->
10486        pReaderContext ) /**< may be M4OSA_NULL if M4MCS_open was not called */
10487    {
10488        err = pC->m_pReader->m_pFctClose(pC->pReaderContext);
10489
10490        if( M4NO_ERROR != err )
10491        {
10492            M4OSA_TRACE1_1("M4MCS_cleanUp: m_pReader->m_pFctClose returns 0x%x",
10493                err);
10494            /**< don't return, we still have stuff to free */
10495        }
10496
10497        err = pC->m_pReader->m_pFctDestroy(pC->pReaderContext);
10498        pC->pReaderContext = M4OSA_NULL;
10499
10500        if( M4NO_ERROR != err )
10501        {
10502            M4OSA_TRACE1_1(
10503                "M4MCS_cleanUp: m_pReader->m_pFctDestroy returns 0x%x", err);
10504            /**< don't return, we still have stuff to free */
10505        }
10506    }
10507
10508    if( pC->m_pDataAddress1 != M4OSA_NULL )
10509    {
10510        M4OSA_free((M4OSA_MemAddr32)pC->m_pDataAddress1);
10511        pC->m_pDataAddress1 = M4OSA_NULL;
10512    }
10513
10514    if( pC->m_pDataAddress2 != M4OSA_NULL )
10515    {
10516        M4OSA_free((M4OSA_MemAddr32)pC->m_pDataAddress2);
10517        pC->m_pDataAddress2 = M4OSA_NULL;
10518    }
10519    /*Bug fix 11/12/2008 (to obtain more precise video end cut)*/
10520    if( pC->m_pDataVideoAddress1 != M4OSA_NULL )
10521    {
10522        M4OSA_free((M4OSA_MemAddr32)pC->m_pDataVideoAddress1);
10523        pC->m_pDataVideoAddress1 = M4OSA_NULL;
10524    }
10525
10526    if( pC->m_pDataVideoAddress2 != M4OSA_NULL )
10527    {
10528        M4OSA_free((M4OSA_MemAddr32)pC->m_pDataVideoAddress2);
10529        pC->m_pDataVideoAddress2 = M4OSA_NULL;
10530    }
10531    /**/
10532    /* ----- Free video decoder stuff, if needed ----- */
10533
10534    if( M4OSA_NULL != pC->pViDecCtxt )
10535    {
10536        err = pC->m_pVideoDecoder->m_pFctDestroy(pC->pViDecCtxt);
10537        pC->pViDecCtxt = M4OSA_NULL;
10538
10539        if( M4NO_ERROR != err )
10540        {
10541            M4OSA_TRACE1_1(
10542                "M4MCS_cleanUp: m_pVideoDecoder->pFctDestroy returns 0x%x",
10543                err);
10544            /**< don't return, we still have stuff to free */
10545        }
10546    }
10547
10548    /* ----- Free the audio decoder stuff ----- */
10549
10550    if( M4OSA_NULL != pC->pAudioDecCtxt )
10551    {
10552        err = pC->m_pAudioDecoder->m_pFctDestroyAudioDec(pC->pAudioDecCtxt);
10553        pC->pAudioDecCtxt = M4OSA_NULL;
10554
10555        if( M4NO_ERROR != err )
10556        {
10557            M4OSA_TRACE1_1(
10558                "M4MCS_cleanUp: m_pAudioDecoder->m_pFctDestroyAudioDec returns 0x%x",
10559                err);
10560            /**< don't return, we still have stuff to free */
10561        }
10562    }
10563
10564    if( M4OSA_NULL != pC->AudioDecBufferOut.m_dataAddress )
10565    {
10566        M4OSA_free((M4OSA_MemAddr32)pC->AudioDecBufferOut.m_dataAddress);
10567        pC->AudioDecBufferOut.m_dataAddress = M4OSA_NULL;
10568    }
10569
10570    return M4NO_ERROR;
10571}
10572
10573
10574/**
10575
10576 ******************************************************************************
10577 * M4OSA_ERR M4MCS_open_normalMode(M4MCS_Context pContext, M4OSA_Void* pFileIn,
10578 *                             M4OSA_Void* pFileOut, M4OSA_Void* pTempFile);
10579 * @brief   Set the MCS input and output files. It is the same as M4MCS_open without
10580 *                                M4MCS_WITH_FAST_OPEN flag
10581It is used in VideoArtist
10582 * @note    It opens the input file, but the output file is not created yet.
10583 * @param   pContext            (IN) MCS context
10584 * @param   pFileIn             (IN) Input file to transcode (The type of this parameter
10585 *                                    (URL, pipe...) depends on the OSAL implementation).
10586 * @param   mediaType           (IN) Container type (.3gp,.amr, ...) of input file.
10587 * @param   pFileOut            (IN) Output file to create  (The type of this parameter
10588 *                                (URL, pipe...) depends on the OSAL implementation).
10589 * @param   pTempFile           (IN) Temporary file for the constant memory writer to store
10590 *                                 metadata ("moov.bin").
10591 * @return  M4NO_ERROR:         No error
10592 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (debug only)
10593 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
10594 * @return  M4ERR_ALLOC:        There is no more available memory
10595 * @return  M4ERR_FILE_NOT_FOUND:   The input file has not been found
10596 * @return  M4MCS_ERR_INVALID_INPUT_FILE:   The input file is not a valid file, or is corrupted
10597 * @return  M4MCS_ERR_INPUT_FILE_CONTAINS_NO_SUPPORTED_STREAM:  The input file contains no
10598 *                                                         supported audio or video stream
10599 ******************************************************************************
10600 */
10601M4OSA_ERR M4MCS_open_normalMode(M4MCS_Context pContext, M4OSA_Void* pFileIn,
10602                                 M4VIDEOEDITING_FileType InputFileType,
10603                                  M4OSA_Void* pFileOut, M4OSA_Void* pTempFile)
10604{
10605    M4MCS_InternalContext *pC = (M4MCS_InternalContext*)(pContext);
10606    M4OSA_ERR err;
10607
10608    M4READER_MediaFamily mediaFamily;
10609    M4_StreamHandler* pStreamHandler;
10610
10611    M4OSA_TRACE2_3("M4MCS_open_normalMode called with pContext=0x%x, pFileIn=0x%x,\
10612     pFileOut=0x%x", pContext, pFileIn, pFileOut);
10613
10614    /**
10615    * Check input parameters */
10616    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
10617     "M4MCS_open_normalMode: pContext is M4OSA_NULL");
10618    M4OSA_DEBUG_IF2((M4OSA_NULL == pFileIn) , M4ERR_PARAMETER,
10619     "M4MCS_open_normalMode: pFileIn is M4OSA_NULL");
10620
10621    if ((InputFileType == M4VIDEOEDITING_kFileType_JPG)
10622        ||(InputFileType == M4VIDEOEDITING_kFileType_PNG)
10623        ||(InputFileType == M4VIDEOEDITING_kFileType_GIF)
10624        ||(InputFileType == M4VIDEOEDITING_kFileType_BMP))
10625    {
10626        M4OSA_TRACE1_0("M4MCS_open_normalMode: Still picture is not\
10627             supported with this function");
10628        return M4MCS_ERR_INPUT_FILE_CONTAINS_NO_SUPPORTED_STREAM;
10629    }
10630
10631    /**
10632    * Check state automaton */
10633    if (M4MCS_kState_CREATED != pC->State)
10634    {
10635        M4OSA_TRACE1_1("M4MCS_open_normalMode(): Wrong State (%d), returning M4ERR_STATE",
10636             pC->State);
10637        return M4ERR_STATE;
10638    }
10639
10640    /* Copy function input parameters into our context */
10641    pC->pInputFile     = pFileIn;
10642    pC->InputFileType  = InputFileType;
10643    pC->pOutputFile    = pFileOut;
10644    pC->pTemporaryFile = pTempFile;
10645
10646    /***********************************/
10647    /* Open input file with the reader */
10648    /***********************************/
10649
10650    err = M4MCS_setCurrentReader(pContext, pC->InputFileType);
10651    M4ERR_CHECK_RETURN(err);
10652
10653    /**
10654    * Reset reader related variables */
10655    pC->VideoState          = M4MCS_kStreamState_NOSTREAM;
10656    pC->AudioState          = M4MCS_kStreamState_NOSTREAM;
10657    pC->pReaderVideoStream  = M4OSA_NULL;
10658    pC->pReaderAudioStream  = M4OSA_NULL;
10659
10660    /*******************************************************/
10661    /* Initializes the reader shell and open the data file */
10662    /*******************************************************/
10663    err = pC->m_pReader->m_pFctCreate(&pC->pReaderContext);
10664    if (M4NO_ERROR != err)
10665    {
10666        M4OSA_TRACE1_1("M4MCS_open_normalMode(): m_pReader->m_pFctCreate returns 0x%x", err);
10667        return err;
10668    }
10669
10670    /**
10671    * Link the reader interface to the reader context */
10672    pC->m_pReaderDataIt->m_readerContext = pC->pReaderContext;
10673
10674    /**
10675    * Set the reader shell file access functions */
10676    err = pC->m_pReader->m_pFctSetOption(pC->pReaderContext,
10677         M4READER_kOptionID_SetOsaFileReaderFctsPtr,
10678        (M4OSA_DataOption)pC->pOsaFileReadPtr);
10679    if (M4NO_ERROR != err)
10680    {
10681        M4OSA_TRACE1_1("M4MCS_open_normalMode(): m_pReader->m_pFctSetOption returns 0x%x", err);
10682        return err;
10683    }
10684
10685    /**
10686    * Open the input file */
10687    err = pC->m_pReader->m_pFctOpen(pC->pReaderContext, pC->pInputFile);
10688    if (M4NO_ERROR != err)
10689    {
10690        M4OSA_UInt32 uiDummy, uiCoreId;
10691        M4OSA_TRACE1_1("M4MCS_open_normalMode(): m_pReader->m_pFctOpen returns 0x%x", err);
10692
10693        if (err == ((M4OSA_UInt32)M4ERR_UNSUPPORTED_MEDIA_TYPE)) {
10694            M4OSA_TRACE1_0("M4MCS_open_normalMode(): returning M4MCS_ERR_FILE_DRM_PROTECTED");
10695            return M4MCS_ERR_FILE_DRM_PROTECTED;
10696        } else {
10697            /**
10698            * If the error is from the core reader, we change it to a public VXS error */
10699            M4OSA_ERR_SPLIT(err, uiDummy, uiCoreId, uiDummy);
10700            if (M4MP4_READER == uiCoreId)
10701            {
10702                M4OSA_TRACE1_0("M4MCS_open_normalMode(): returning M4MCS_ERR_INVALID_INPUT_FILE");
10703                return M4MCS_ERR_INVALID_INPUT_FILE;
10704            }
10705        }
10706        return err;
10707    }
10708
10709    /**
10710    * Get the streams from the input file */
10711    while (M4NO_ERROR == err)
10712    {
10713        err = pC->m_pReader->m_pFctGetNextStream(pC->pReaderContext, &mediaFamily,
10714            &pStreamHandler);
10715
10716        /**
10717        * In case we found a BIFS stream or something else...*/
10718        if((err == ((M4OSA_UInt32)M4ERR_READER_UNKNOWN_STREAM_TYPE))
10719            || (err == ((M4OSA_UInt32)M4WAR_TOO_MUCH_STREAMS)))
10720        {
10721            err = M4NO_ERROR;
10722            continue;
10723        }
10724
10725        if (M4NO_ERROR == err) /**< One stream found */
10726        {
10727            /**
10728            * Found the first video stream */
10729            if ((M4READER_kMediaFamilyVideo == mediaFamily) \
10730                && (M4OSA_NULL == pC->pReaderVideoStream))
10731            {
10732                if ((M4DA_StreamTypeVideoH263==pStreamHandler->m_streamType) ||
10733                    (M4DA_StreamTypeVideoMpeg4==pStreamHandler->m_streamType)
10734#ifdef M4VSS_SUPPORT_VIDEO_AVC
10735                    ||(M4DA_StreamTypeVideoMpeg4Avc==pStreamHandler->m_streamType))
10736#else
10737                    ||((M4DA_StreamTypeVideoMpeg4Avc==pStreamHandler->m_streamType)
10738                    &&(pC->m_pVideoDecoderItTable[M4DECODER_kVideoTypeAVC] != M4OSA_NULL)))
10739#endif
10740                {
10741                    M4OSA_TRACE3_0("M4MCS_open_normalMode():\
10742                     Found a H263 or MPEG-4 video stream in input 3gpp clip");
10743
10744                    /**
10745                    * Keep pointer to the video stream */
10746                    pC->pReaderVideoStream = (M4_VideoStreamHandler*)pStreamHandler;
10747                    pC->bUnsupportedVideoFound = M4OSA_FALSE;
10748                    pStreamHandler->m_bStreamIsOK = M4OSA_TRUE;
10749
10750                    /**
10751                    * Init our video stream state variable */
10752                    pC->VideoState = M4MCS_kStreamState_STARTED;
10753
10754                    /**
10755                    * Reset the stream reader */
10756                    err = pC->m_pReader->m_pFctReset(pC->pReaderContext,
10757                         (M4_StreamHandler*)pC->pReaderVideoStream);
10758                    if (M4NO_ERROR != err)
10759                    {
10760                        M4OSA_TRACE1_1("M4MCS_open_normalMode():\
10761                             m_pReader->m_pFctReset(video) returns 0x%x", err);
10762                        return err;
10763                    }
10764
10765                    /**
10766                    * Initializes an access Unit */
10767                    err = pC->m_pReader->m_pFctFillAuStruct(pC->pReaderContext, pStreamHandler,
10768                         &pC->ReaderVideoAU);
10769                    if (M4NO_ERROR != err)
10770                    {
10771                        M4OSA_TRACE1_1("M4MCS_open_normalMode():\
10772                             m_pReader->m_pFctFillAuStruct(video) returns 0x%x", err);
10773                        return err;
10774                    }
10775                }
10776                else /**< Not H263 or MPEG-4 (H264, etc.) */
10777                {
10778                    M4OSA_TRACE1_1("M4MCS_open_normalMode():\
10779                         Found an unsupported video stream (0x%x) in input 3gpp clip",
10780                             pStreamHandler->m_streamType);
10781
10782                    pC->bUnsupportedVideoFound = M4OSA_TRUE;
10783                    pStreamHandler->m_bStreamIsOK = M4OSA_FALSE;
10784                }
10785            }
10786            /**
10787            * Found the first audio stream */
10788            else if ((M4READER_kMediaFamilyAudio == mediaFamily)
10789                && (M4OSA_NULL == pC->pReaderAudioStream))
10790            {
10791                if ((M4DA_StreamTypeAudioAmrNarrowBand==pStreamHandler->m_streamType) ||
10792                    (M4DA_StreamTypeAudioAac==pStreamHandler->m_streamType) ||
10793                    (M4DA_StreamTypeAudioMp3==pStreamHandler->m_streamType) ||
10794                    (M4DA_StreamTypeAudioEvrc==pStreamHandler->m_streamType) )
10795                {
10796                    M4OSA_TRACE3_0("M4MCS_open_normalMode(): Found an AMR-NB, AAC \
10797                        or MP3 audio stream in input clip");
10798
10799                    /**
10800                    * Keep pointer to the audio stream */
10801                    pC->pReaderAudioStream = (M4_AudioStreamHandler*)pStreamHandler;
10802                    pStreamHandler->m_bStreamIsOK = M4OSA_TRUE;
10803                    pC->bUnsupportedAudioFound = M4OSA_FALSE;
10804
10805                    /**
10806                    * Init our audio stream state variable */
10807                    pC->AudioState = M4MCS_kStreamState_STARTED;
10808
10809                    /**
10810                    * Reset the stream reader */
10811                    err = pC->m_pReader->m_pFctReset(pC->pReaderContext,
10812                         (M4_StreamHandler*)pC->pReaderAudioStream);
10813                    if (M4NO_ERROR != err)
10814                    {
10815                        M4OSA_TRACE1_1("M4MCS_open_normalMode():\
10816                             m_pReader->m_pFctReset(audio) returns 0x%x", err);
10817                        return err;
10818                    }
10819
10820                    /**
10821                    * Initializes an access Unit */
10822                    err = pC->m_pReader->m_pFctFillAuStruct(pC->pReaderContext, pStreamHandler,
10823                         &pC->ReaderAudioAU);
10824                    if (M4NO_ERROR != err)
10825                    {
10826                        M4OSA_TRACE1_1("M4MCS_open_normalMode(): \
10827                            m_pReader->m_pFctFillAuStruct(audio) returns 0x%x", err);
10828                        return err;
10829                    }
10830
10831                    /**
10832                    * Output max AU size is equal to input max AU size (this value
10833                    * will be changed if there is audio transcoding) */
10834                    pC->uiAudioMaxAuSize = pStreamHandler->m_maxAUSize;
10835
10836                }
10837                else
10838                {
10839                    /**< Not AMR-NB, AAC, MP3 nor EVRC (AMR-WB, WAV...) */
10840                    M4OSA_TRACE1_1("M4MCS_open_normalMode(): Found an unsupported audio stream\
10841                         (0x%x) in input 3gpp clip", pStreamHandler->m_streamType);
10842
10843                    pC->bUnsupportedAudioFound = M4OSA_TRUE;
10844                    pStreamHandler->m_bStreamIsOK = M4OSA_FALSE;
10845                }
10846            }
10847        }
10848    } /**< end of while (M4NO_ERROR == err) */
10849
10850    /**
10851    * Check we found at least one supported stream */
10852    if((M4OSA_NULL == pC->pReaderVideoStream) && (M4OSA_NULL == pC->pReaderAudioStream))
10853    {
10854        M4OSA_TRACE1_0("M4MCS_open_normalMode(): returning \
10855            M4MCS_ERR_INPUT_FILE_CONTAINS_NO_SUPPORTED_STREAM");
10856        return M4MCS_ERR_INPUT_FILE_CONTAINS_NO_SUPPORTED_STREAM;
10857    }
10858
10859#ifndef M4VSS_ENABLE_EXTERNAL_DECODERS
10860    if(pC->VideoState == M4MCS_kStreamState_STARTED)
10861    {
10862        err = M4MCS_setCurrentVideoDecoder(pContext,
10863            pC->pReaderVideoStream->m_basicProperties.m_streamType);
10864        M4ERR_CHECK_RETURN(err);
10865    }
10866#endif
10867
10868    if(pC->AudioState == M4MCS_kStreamState_STARTED)
10869    {
10870        //EVRC
10871        if(M4DA_StreamTypeAudioEvrc != pStreamHandler->m_streamType)
10872         /* decoder not supported yet, but allow to do null encoding */
10873        {
10874            err = M4MCS_setCurrentAudioDecoder(pContext,
10875                 pC->pReaderAudioStream->m_basicProperties.m_streamType);
10876            M4ERR_CHECK_RETURN(err);
10877        }
10878    }
10879
10880    /**
10881    * Get the audio and video stream properties */
10882    err = M4MCS_intGetInputClipProperties(pC);
10883    if (M4NO_ERROR != err)
10884    {
10885        M4OSA_TRACE1_1("M4MCS_open_normalMode():\
10886             M4MCS_intGetInputClipProperties returns 0x%x", err);
10887        return err;
10888    }
10889
10890    /**
10891    * Set the begin cut decoding increment according to the input frame rate */
10892    if (0. != pC->InputFileProperties.fAverageFrameRate) /**< sanity check */
10893    {
10894        pC->iVideoBeginDecIncr = (M4OSA_Int32)(3000. \
10895            / pC->InputFileProperties.fAverageFrameRate); /**< about 3 frames */
10896    }
10897    else
10898    {
10899        pC->iVideoBeginDecIncr = 200; /**< default value: 200 milliseconds (3 frames @ 15fps)*/
10900    }
10901
10902    /**
10903    * Update state automaton */
10904    pC->State = M4MCS_kState_OPENED;
10905
10906    /**
10907    * Return with no error */
10908    M4OSA_TRACE3_0("M4MCS_open_normalMode(): returning M4NO_ERROR");
10909    return M4NO_ERROR;
10910}
10911
10912
10913M4OSA_ERR M4MCS_registerExternalVideoDecoder( M4MCS_Context pContext,
10914                                             M4VD_VideoType decoderType,
10915                                             M4VD_Interface *pDecoderInterface,
10916                                             M4OSA_Void *pUserData )
10917{
10918#ifdef M4VSS_ENABLE_EXTERNAL_DECODERS
10919
10920    M4OSA_ERR err = M4NO_ERROR;
10921    M4DECODER_VideoInterface *shellInterface;
10922    M4DECODER_VideoType nativeType;
10923    M4DECODER_EXTERNAL_UserDataType shellUserData;
10924
10925    switch( decoderType )
10926    {
10927        case M4VD_kMpeg4VideoDec:
10928        case M4VD_kH263VideoDec:
10929            nativeType = M4DECODER_kVideoTypeMPEG4;
10930            break;
10931
10932        case M4VD_kH264VideoDec:
10933            nativeType = M4DECODER_kVideoTypeAVC;
10934            break;
10935
10936        default:
10937            M4OSA_TRACE1_1(
10938                "M4MCS_registerExternalVideoDecoder: unknown decoderType %d",
10939                decoderType);
10940            return M4ERR_PARAMETER;
10941            break;
10942    }
10943
10944    shellUserData =
10945        (M4DECODER_EXTERNAL_UserDataType)M4OSA_malloc(sizeof(*shellUserData),
10946        M4MCS,
10947        (M4OSA_Char *)"userData structure for the external shell decoder");
10948
10949    if( M4OSA_NULL == shellUserData )
10950    {
10951        M4OSA_TRACE1_0(
10952            "M4MCS_registerExternalVideoDecoder:\
10953                 failed to allocate userData structure for the external shell decoder");
10954        return M4ERR_ALLOC;
10955    }
10956
10957    shellUserData->externalFuncs = pDecoderInterface;
10958    shellUserData->externalUserData = pUserData;
10959
10960    err = M4DECODER_EXTERNAL_getInterface(&shellInterface);
10961
10962    if( M4NO_ERROR != err )
10963    {
10964        M4OSA_TRACE1_1(
10965            "M4MCS_registerExternalVideoDecoder:\
10966                 M4DECODER_EXTERNAL_getInterface failed with error 0x%08X",
10967            err);
10968        M4OSA_free((M4OSA_MemAddr32)shellUserData);
10969        return err;
10970    }
10971
10972    err = M4MCS_registerVideoDecoder(pContext, nativeType, shellInterface);
10973
10974    if( M4NO_ERROR != err )
10975    {
10976        M4OSA_TRACE1_1(
10977            "M4MCS_registerExternalVideoDecoder:\
10978                 M4MCS_registerVideoDecoder failed with error 0x%08X",
10979            err);
10980        M4OSA_free((M4OSA_MemAddr32)shellInterface);
10981        M4OSA_free((M4OSA_MemAddr32)shellUserData);
10982        return err;
10983    }
10984
10985    ( (M4MCS_InternalContext
10986        *)pContext)->m_pVideoDecoderUserDataTable[nativeType] = shellUserData;
10987
10988    return M4NO_ERROR;
10989#else
10990
10991    return M4ERR_NOT_IMPLEMENTED;
10992
10993#endif /* M4VSS_ENABLE_EXTERNAL_DECODERS */
10994
10995}
10996
10997M4OSA_ERR M4MCS_registerExternalVideoEncoder( M4MCS_Context pContext,
10998                                             M4VE_EncoderType encoderType,
10999                                             M4VE_Interface *pEncoderInterface,
11000                                             M4OSA_Void *pUserData )
11001{
11002#ifdef M4VSS_ENABLE_EXTERNAL_ENCODERS
11003
11004    M4OSA_ERR err = M4NO_ERROR;
11005    M4ENCODER_GlobalInterface *shellInterface;
11006    M4ENCODER_Format nativeType;
11007
11008    switch( encoderType )
11009    {
11010        case M4VE_kH263VideoEnc:
11011            err = M4EGE_H263_getInterfaces(&nativeType, &shellInterface,
11012                M4ENCODER_OPEN_ADVANCED);
11013
11014            break;
11015
11016        case M4VE_kMpeg4VideoEnc:
11017            err = M4EGE_MPEG4_getInterfaces(&nativeType, &shellInterface,
11018                M4ENCODER_OPEN_ADVANCED);
11019            break;
11020
11021        case M4VE_kH264VideoEnc:
11022            M4OSA_TRACE1_0(
11023                "M4MCS_registerExternalVideoEncoder: H264 encoder type not implemented yet");
11024            return M4ERR_NOT_IMPLEMENTED;
11025            break;
11026
11027        default:
11028            M4OSA_TRACE1_1(
11029                "M4MCS_registerExternalVideoEncoder: unknown encoderType %d",
11030                encoderType);
11031            return M4ERR_PARAMETER;
11032            break;
11033    }
11034
11035    if( M4NO_ERROR != err )
11036    {
11037        M4OSA_TRACE1_1(
11038            "M4MCS_registerExternalVideoDecoder: M4EGE_getInterface failed with error 0x%08X",
11039            err);
11040        return err;
11041    }
11042
11043    err = M4MCS_registerVideoEncoder(pContext, nativeType, shellInterface);
11044
11045    if( M4NO_ERROR != err )
11046    {
11047        M4OSA_TRACE1_1(
11048            "M4MCS_registerExternalVideoEncoder:\
11049                 M4MCS_registerVideoEncoder failed with error 0x%08X",
11050            err);
11051        M4OSA_free((M4OSA_MemAddr32)shellInterface);
11052        return err;
11053    }
11054
11055    ( (M4MCS_InternalContext
11056        *)pContext)->pVideoEncoderExternalAPITable[nativeType]
11057    = pEncoderInterface;
11058    ( (M4MCS_InternalContext
11059        *)pContext)->pVideoEncoderUserDataTable[nativeType] = pUserData;
11060
11061    return M4NO_ERROR;
11062
11063#else
11064
11065    return M4ERR_NOT_IMPLEMENTED;
11066
11067#endif
11068
11069}
11070
11071/**
11072 ************************************************************************
11073 * M4OSA_ERR M4MCS_registerExternalAudioDecoder(M4MCS_Context pContext,
11074 *                                    M4AD_Type decoderType,
11075 *                                    M4AD_Interface *pDecoderInterface);
11076 * @brief    This function will register a specific external audio decoder.
11077 * @note    According to the decoderType, this function will store in the internal context the
11078 *                decoder interface.
11079 * @param    context                (IN/OUT) MCS context.
11080 * @param    decoderType            (IN) Audio decoder type
11081 * @param    pDecoderInterface    (IN) Audio decoder interface.
11082 * @return    M4NO_ERROR:            No error
11083 * @return    M4ERR_PARAMETER:    A parameter is null, or the decoder type is invalid
11084 *                                (in DEBUG only)
11085 ************************************************************************
11086 */
11087M4OSA_ERR M4MCS_registerExternalAudioDecoder( M4MCS_Context pContext,
11088                                             M4AD_Type decoderType,
11089                                             M4AD_Interface *pDecoderInterface )
11090{
11091    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)pContext;
11092
11093    M4OSA_DEBUG_IF1((M4OSA_NULL == pC), M4ERR_PARAMETER,
11094        "M4MCS_registerExternalAudioDecoder: invalid context pointer");
11095    M4OSA_DEBUG_IF1((M4OSA_NULL == pDecoderInterface), M4ERR_PARAMETER,
11096        "M4MCS_registerExternalAudioDecoder: invalid pointer on decoder interface");
11097
11098    if( M4MCS_kState_CREATED != pC->State )
11099    {
11100        M4OSA_TRACE1_1(
11101            "M4MCS_registerExternalAudioDecoder(): Wrong State (%d), returning M4ERR_STATE",
11102            pC->State);
11103        return M4ERR_STATE;
11104    }
11105
11106    if( decoderType >= M4AD_kType_NB )
11107    {
11108        M4OSA_DEBUG_IF1(M4OSA_TRUE, M4ERR_PARAMETER,
11109            "M4MCS_registerExternalAudioDecoder: Invalid audio decoder type");
11110        return M4ERR_PARAMETER;
11111    }
11112
11113    if( pC->m_pAudioDecoderFlagTable[decoderType] == M4OSA_TRUE
11114        && pC->m_pAudioDecoderItTable[decoderType] != M4OSA_NULL )
11115    {
11116        M4OSA_TRACE1_1(
11117            "M4MCS_registerExternalAudioDecoder: error parameter: an external decoder of type\
11118                 %i is already registered",
11119            decoderType);
11120        return M4ERR_PARAMETER;
11121    }
11122
11123    if( pC->m_pAudioDecoderItTable[decoderType] != M4OSA_NULL )
11124    {
11125        M4OSA_free((M4OSA_MemAddr32)pC->m_pAudioDecoderItTable[decoderType]);
11126        pC->m_pAudioDecoderItTable[decoderType] = M4OSA_NULL;
11127    }
11128
11129    pC->m_pAudioDecoderItTable[decoderType] = pDecoderInterface;
11130    pC->m_pAudioDecoderFlagTable[decoderType] =
11131        M4OSA_TRUE; /* external decoder */
11132
11133    return M4NO_ERROR;
11134}
11135
11136/**
11137 ******************************************************************************
11138 * M4OSA_ERR   M4MCS_registerExternalAudioEncoder(M4MCS_Context pContext,
11139 *                                             M4ENCODER_AudioFormat mediaType,
11140 *                                             M4ENCODER_AudioGlobalInterface *pEncGlobalInterface)
11141 * @brief    This function will register a specific external audio encoder.
11142 * @note    According to the Mediatype, this function will store in the internal context the
11143 *             encoder context.
11144 * @param    pContext:                (IN) Execution context.
11145 * @param    mediaType:                (IN) The media type.
11146 * @param    pEncGlobalInterface:    (OUT) the encoder interface functions.
11147 * @return    M4NO_ERROR: there is no error
11148 * @return    M4ERR_PARAMETER: pContext or pEncGlobalInterface is M4OSA_NULL (debug only)
11149 ******************************************************************************
11150 */
11151M4OSA_ERR M4MCS_registerExternalAudioEncoder( M4MCS_Context pContext,
11152                                             M4ENCODER_AudioFormat MediaType,
11153                                             M4ENCODER_AudioGlobalInterface *pEncGlobalInterface )
11154{
11155    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)pContext;
11156
11157    /**
11158    *    Check input parameters */
11159    M4OSA_DEBUG_IF2((pC == M4OSA_NULL), M4ERR_PARAMETER,
11160        "MCS: context is M4OSA_NULL in M4MCS_registerExternalAudioEncoder");
11161    M4OSA_DEBUG_IF2((pEncGlobalInterface == M4OSA_NULL), M4ERR_PARAMETER,
11162        "pEncGlobalInterface is M4OSA_NULL in M4MCS_registerExternalAudioEncoder");
11163
11164    M4OSA_TRACE3_2(
11165        "MCS: M4MCS_registerExternalAudioEncoder called with pContext=0x%x, \
11166        pEncGlobalInterface=0x%x",
11167        pC, pEncGlobalInterface);
11168
11169    if( M4MCS_kState_CREATED != pC->State )
11170    {
11171        M4OSA_TRACE1_1(
11172            "M4MCS_registerExternalAudioEncoder(): Wrong State (%d), returning M4ERR_STATE",
11173            pC->State);
11174        return M4ERR_STATE;
11175    }
11176
11177    if( MediaType >= M4ENCODER_kAudio_NB )
11178    {
11179        M4OSA_DEBUG_IF1(M4OSA_TRUE, M4ERR_PARAMETER,
11180            "M4MCS_registerExternalAudioEncoder(): Invalid audio encoder type");
11181        return M4ERR_PARAMETER;
11182    }
11183
11184    if( pC->pAudioEncoderFlag[MediaType] == M4OSA_TRUE
11185        && pC->pAudioEncoderInterface[MediaType] != M4OSA_NULL )
11186    {
11187        M4OSA_TRACE1_1(
11188            "M4MCS_registerExternalAudioEncoder: error parameter:\
11189             an external encoder of type %i is already registered",
11190            MediaType);
11191        return M4ERR_PARAMETER;
11192    }
11193
11194    if( pC->pAudioEncoderInterface[MediaType] != M4OSA_NULL )
11195    {
11196        M4OSA_free((M4OSA_MemAddr32)pC->pAudioEncoderInterface[MediaType]);
11197        pC->pAudioEncoderInterface[MediaType] = M4OSA_NULL;
11198    }
11199
11200    /*
11201    * Save encoder interface in context */
11202    pC->pAudioEncoderInterface[MediaType] = pEncGlobalInterface;
11203    pC->pAudioEncoderFlag[MediaType] = M4OSA_TRUE; /* external encoder */
11204
11205    return M4NO_ERROR;
11206}
11207
11208/**
11209 ******************************************************************************
11210 * M4OSA_ERR M4MCS_getExifInfo(M4MCS_Context pContext);
11211 * @brief    Retrieve the EXIF tags informations from a Still picture
11212 * @note    This function will allocate and fill a Exif tag struct
11213 *            exifTags structure must be allocated/deallocated by the user
11214 *            exifTags members will point to internal SPE information, user should not try
11215 *             to modify or deallocate them
11216 * @param    pContext            (IN) MCS context
11217 * @return    M4NO_ERROR:            No error
11218 * @return    M4ERR_PARAMETER:    pContext is M4OSA_NULL
11219 ******************************************************************************
11220 */
11221M4OSA_ERR M4MCS_getExifInfo( M4MCS_Context pContext, M4MCS_ExifInfos *exifTags )
11222{
11223    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)(pContext);
11224    M4OSA_ERR err;
11225
11226    M4OSA_TRACE2_1("M4MCS_getExifInfo called with pContext=0x%x", pContext);
11227
11228    /**
11229    * Check input parameters */
11230    M4OSA_DEBUG_IF2((M4OSA_NULL == pContext), M4ERR_PARAMETER,
11231        "M4MCS_getExifInfo: pContext is M4OSA_NULL");
11232
11233#ifdef M4MCS_SUPPORT_STILL_PICTURE
11234
11235    if( pC->m_bIsStillPicture )
11236    {
11237        /**
11238        * Call the corresponding still picture MCS function*/
11239        return M4MCS_stillPicGetExifInfo(pC, exifTags);
11240    }
11241
11242#endif /*M4MCS_SUPPORT_STILL_PICTURE*/
11243
11244    return M4ERR_NOT_IMPLEMENTED;
11245}
11246
11247/**
11248 ******************************************************************************
11249 * M4OSA_ERR M4MCS_registerVideoDecoderExtended(M4MCS_Context    context,
11250M4DECODER_VideoType        decoderType,
11251M4DECODER_VideoInterface    *pDecoderInterface,
11252M4OSA_Void* pUserData)
11253 * @brief    Registers an external Video decoder
11254 * @note This is much different from the external video decoder to cope up with specific
11255 *        requirement of OMX codec implementation.
11256So we use M4DECODER_VideoInterface instead of M4VD_Interface.
11257 * @param  pContext           (IN) MCS context
11258 * @param  decoderType        (IN) Type of decoder (MPEG4 ...)
11259 * @param  pVidDecoderInterface  (IN) Decoder interface of type 'M4DECODER_VideoInterface'
11260 * @param  pUserData          (IN) Pointer on a user data to give to external decoder
11261 * @return  M4NO_ERROR:         No error
11262 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (debug only)
11263 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
11264 ******************************************************************************
11265 */
11266M4OSA_ERR M4MCS_registerVideoDecoderExtended( M4MCS_Context context,
11267                                             M4VD_VideoType decoderType,
11268                                             M4OSA_Context pVidDecoderInterface,
11269                                             M4OSA_Void *pUserData )
11270{
11271    M4OSA_ERR err = M4NO_ERROR;
11272    M4DECODER_VideoType nativeType;
11273    M4DECODER_EXTERNAL_UserDataType shellUserData;
11274    M4DECODER_VideoInterface *pDecoderInterface =
11275        (M4DECODER_VideoInterface *)pVidDecoderInterface;
11276    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)context;
11277    M4OSA_Bool bResetCurrentVideoDecoder = M4OSA_FALSE;
11278    M4_StreamType mediaType = M4DA_StreamTypeUnknown;
11279
11280    M4OSA_TRACE3_1(
11281        "M4MCS_registerVideoDecoderExtended invoked with context = 0x%x",
11282        context);
11283
11284    switch( decoderType )
11285    {
11286        case M4VD_kMpeg4VideoDec:
11287        case M4VD_kH263VideoDec:
11288            nativeType = M4DECODER_kVideoTypeMPEG4;
11289            mediaType = M4DA_StreamTypeVideoMpeg4;
11290            break;
11291
11292        case M4VD_kH264VideoDec:
11293            nativeType = M4DECODER_kVideoTypeAVC;
11294            mediaType = M4DA_StreamTypeVideoMpeg4Avc;
11295            break;
11296
11297        default:
11298            M4OSA_TRACE1_1(
11299                "M4MCS_registerVideoDecoderExtended: unknown decoderType %d",
11300                decoderType);
11301            return M4ERR_PARAMETER;
11302    }
11303
11304    if( M4OSA_NULL != pC->m_pVideoDecoder )
11305    {
11306        M4OSA_TRACE3_0(
11307            "M4MCS_registerVideoDecoderExtended: pC->m_pVideoDecoder already set to \
11308            previous registered dec shell");
11309
11310        if( ( ( ( pC->pReaderVideoStream->m_basicProperties.m_streamType
11311            == M4DA_StreamTypeVideoH263)
11312            || (pC->pReaderVideoStream->m_basicProperties.m_streamType
11313            == M4DA_StreamTypeVideoMpeg4))
11314            && (mediaType == M4DA_StreamTypeVideoMpeg4))
11315            || (( pC->pReaderVideoStream->m_basicProperties.m_streamType
11316            == M4DA_StreamTypeVideoMpeg4Avc)
11317            && (mediaType == M4DA_StreamTypeVideoMpeg4Avc)) )
11318            bResetCurrentVideoDecoder = M4OSA_TRUE;
11319    }
11320
11321    err = M4MCS_registerVideoDecoder(context, nativeType, pDecoderInterface);
11322
11323    /** Provide the application user data back to the interface functions. **
11324    * For now we donot provide 'M4DECODER_EXTERNAL_UserDataType' **/
11325    ( (M4MCS_InternalContext
11326        *)context)->m_pVideoDecoderUserDataTable[nativeType] = pUserData;
11327
11328    if( ( M4NO_ERROR == err) && (M4OSA_TRUE == bResetCurrentVideoDecoder) )
11329    {
11330        err = M4MCS_setCurrentVideoDecoder(context, mediaType);
11331        M4OSA_TRACE3_1(
11332            "M4MCS_registerVideoDecoderExtended: M4MCS_setCurrentVideoDecoder returned 0x%x",
11333            err);
11334    }
11335    M4OSA_TRACE1_1(
11336        "M4MCS_registerVideoDecoderExtended returning with error  = 0x%x", err);
11337    return err;
11338}
11339
11340/**
11341 ******************************************************************************
11342 * M4OSA_ERR M4MCS_registerVideoEncoderExtended()
11343 * @brief    Registers an external Video encoder
11344 * @note This is much different from the external video encoder to cope up with specific
11345 *            requirement of OMX codec implementation.
11346So we use M4ENCODER_GlobalInterface instead of M4VE_Interface.
11347 * @param  pContext           (IN) MCS context
11348 * @param  encoderType        (IN) Type of encoder (MPEG4 ...)
11349 * @param  pEncoderInterface  (IN) Encoder interface of type 'M4ENCODER_VideoInterface'
11350 * @param  pUserData          (IN) Pointer on a user data to give to external encoder
11351 * @return  M4NO_ERROR:         No error
11352 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (debug only)
11353 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
11354 ******************************************************************************
11355 */
11356M4OSA_ERR M4MCS_registerVideoEncoderExtended( M4MCS_Context pContext,
11357                                             M4VE_EncoderType encoderType,
11358                                             M4OSA_Context pEncoderInterface,
11359                                             M4OSA_Void *pUserData )
11360{
11361    M4OSA_ERR err = M4NO_ERROR;
11362    M4ENCODER_Format nativeType;
11363    M4ENCODER_GlobalInterface *pEncShellInterface =
11364        (M4ENCODER_GlobalInterface *)pEncoderInterface;
11365    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)pContext;
11366    M4OSA_Bool bResetCurrentVideoEncoder = M4OSA_FALSE;
11367    M4VIDEOEDITING_VideoFormat mediaType = M4VIDEOEDITING_kNoneVideo;
11368
11369    M4OSA_TRACE3_1(
11370        "M4MCS_registerVideoEncoderExtended invoked with context = 0x%x",
11371        pContext);
11372
11373    switch( encoderType )
11374    {
11375        case M4VE_kMpeg4VideoEnc:
11376            nativeType = M4ENCODER_kMPEG4;
11377            mediaType = M4VIDEOEDITING_kMPEG4;
11378            break;
11379
11380        case M4VE_kH263VideoEnc:
11381            nativeType = M4ENCODER_kH263;
11382            mediaType = M4VIDEOEDITING_kH263;
11383            break;
11384
11385        case M4VE_kH264VideoEnc:
11386            nativeType = M4ENCODER_kH264;
11387            mediaType = M4VIDEOEDITING_kH264;
11388            break;
11389
11390        default:
11391            M4OSA_TRACE1_1(
11392                "M4MCS_registerVideoEncoderExtended: unknown encoderType %d",
11393                encoderType);
11394            return M4ERR_PARAMETER;
11395    }
11396
11397    if( M4OSA_NULL != pC->pVideoEncoderGlobalFcts )
11398    {
11399        M4OSA_TRACE3_0(
11400            "M4MCS_registerVideoEncoderExtended:\
11401                 pC->pVideoEncoderGlobalFcts already set to previous registered Enc shell");
11402
11403        if( pC->EncodingVideoFormat == nativeType )
11404            bResetCurrentVideoEncoder = M4OSA_TRUE;
11405    }
11406
11407    err = M4MCS_registerVideoEncoder(pContext, nativeType, pEncShellInterface);
11408
11409    ( (M4MCS_InternalContext
11410        *)pContext)->pVideoEncoderExternalAPITable[nativeType]
11411    = pEncoderInterface;
11412    ( (M4MCS_InternalContext
11413        *)pContext)->pVideoEncoderUserDataTable[nativeType] = pUserData;
11414
11415    if( ( M4NO_ERROR == err) && (M4OSA_TRUE == bResetCurrentVideoEncoder) )
11416    {
11417        err = M4MCS_setCurrentVideoEncoder(pContext, mediaType);
11418        M4OSA_TRACE3_1(
11419            "M4MCS_registerVideoEncoderExtended: M4MCS_setCurrentVideoEncoder returned 0x%x",
11420            err);
11421    }
11422    M4OSA_TRACE1_1(
11423        "M4MCS_registerVideoEncoderExtended returning with error  = 0x%x", err);
11424    return err;
11425}
11426
11427/**
11428 ******************************************************************************
11429 * M4OSA_ERR M4MCS_registerAudioEncoderExtended(M4MCS_Context pContext,
11430M4ENCODER_AudioFormat encoderType,
11431M4ENCODER_AudioGlobalInterface    *pEncoderInterface,
11432M4OSA_Void* pUserData);
11433 * @brief    Registers an external Audio Encoder
11434 * @note This is much different from the external audio encoder to cope up with specific
11435 *        requirement of OMX codec implementation.
11436 * @param  pContext           (IN) MCS context
11437 * @param  encoderType        (IN) Type of encoder
11438 * @param  pEncoderInterface  (IN) Encoder interface to OMX shell function
11439 * @param  pUserData          (IN) Pointer on a user data to give to external encoder
11440 *                              (OMX Core Context)
11441 * @return  M4NO_ERROR:         No error
11442 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (debug only)
11443 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
11444 ******************************************************************************
11445 */
11446M4OSA_ERR M4MCS_registerAudioEncoderExtended( M4MCS_Context pContext,
11447                                             M4ENCODER_AudioFormat encoderType,
11448                                             M4ENCODER_AudioGlobalInterface *pEncoderInterface,
11449                                             M4OSA_Void *pUserData )
11450{
11451    M4OSA_ERR err = M4NO_ERROR;
11452    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)pContext;
11453    M4OSA_Bool bResetCurrentAudioEncoder = M4OSA_FALSE;
11454    M4VIDEOEDITING_AudioFormat mediaType = M4VIDEOEDITING_kNoneAudio;
11455
11456    switch( encoderType )
11457    {
11458        case M4ENCODER_kAMRNB:
11459            mediaType = M4VIDEOEDITING_kAMR_NB;
11460            break;
11461
11462        case M4ENCODER_kAAC:
11463            mediaType = M4VIDEOEDITING_kAAC;
11464            break;
11465
11466        case M4ENCODER_MP3:
11467            mediaType = M4VIDEOEDITING_kMP3;
11468            break;
11469
11470        default:
11471            M4OSA_TRACE1_1(
11472                "M4MCS_registerAudioEncoderExtended: unknown encoderType %d",
11473                encoderType);
11474            return M4ERR_PARAMETER;
11475    }
11476
11477    if( M4OSA_NULL != pC->pAudioEncoderGlobalFcts )
11478    {
11479        M4OSA_TRACE3_0(
11480            "M4MCS_registerAudioEncoderExtended: pC->pAudioEncoderGlobalFcts already set to \
11481                previous registered Enc shell");
11482
11483        if( pC->AudioEncParams.Format == encoderType )
11484            bResetCurrentAudioEncoder = M4OSA_TRUE;
11485    }
11486
11487    err = M4MCS_registerAudioEncoder(pContext, encoderType, pEncoderInterface);
11488
11489    if( M4NO_ERROR != err )
11490    {
11491        M4OSA_TRACE1_1(
11492            "M4MCS_registerAudioEncoderExtended: \
11493                M4MCS_registerAudioEncoder failed with error 0x%08X",
11494            err);
11495        M4OSA_free((M4OSA_MemAddr32)pEncoderInterface);
11496        return err;
11497    }
11498
11499    ( (M4MCS_InternalContext
11500        *)pContext)->pAudioEncoderInterface[encoderType] = pEncoderInterface;
11501    ( (M4MCS_InternalContext
11502        *)pContext)->pAudioEncoderUserDataTable[encoderType] = pUserData;
11503
11504    if( ( M4NO_ERROR == err) && (M4OSA_TRUE == bResetCurrentAudioEncoder) )
11505    {
11506        err = M4MCS_setCurrentAudioEncoder(pContext, mediaType);
11507        M4OSA_TRACE3_1(
11508            "M4MCS_registerAudioEncoderExtended: M4MCS_setCurrentAudioEncoder returned 0x%x",
11509            err);
11510    }
11511    return err;
11512}
11513
11514/**
11515 ******************************************************************************
11516 * M4OSA_ERR M4MCS_registerAudioDecoderExtended(M4MCS_Context pContext,
11517M4AD_Type decoderType,
11518M4AD_Interface    *pDecoderInterface,
11519M4OSA_Void* pUserData);
11520 * @brief    Registers an external Audio Decoder
11521 * @note This is much different from the external audio decoder to cope up with specific
11522 *             requirement of OMX codec implementation.
11523 * @param  pContext           (IN) MCS context
11524 * @param  decoderType        (IN) Type of decoder
11525 * @param  pDecoderInterface  (IN) Decoder interface to OMX shell function
11526 * @param  pUserData          (IN) Pointer on a user data to give to external decoder
11527 *                                (OMX Core Context)
11528 * @return  M4NO_ERROR:         No error
11529 * @return  M4ERR_PARAMETER:    At least one parameter is M4OSA_NULL (debug only)
11530 * @return  M4ERR_STATE:        MCS is not in an appropriate state for this function to be called
11531 ******************************************************************************
11532 */
11533M4OSA_ERR M4MCS_registerAudioDecoderExtended( M4MCS_Context pContext,
11534                                             M4AD_Type decoderType,
11535                                             M4AD_Interface *pDecoderInterface,
11536                                             M4OSA_Void *pUserData )
11537{
11538    M4OSA_ERR err = M4NO_ERROR;
11539    M4MCS_InternalContext *pC = (M4MCS_InternalContext *)pContext;
11540    M4OSA_Bool bResetCurrentAudioDecoder = M4OSA_FALSE;
11541    M4_StreamType mediaType = M4DA_StreamTypeUnknown;
11542
11543    switch( decoderType )
11544    {
11545        case M4AD_kTypeAMRNB:
11546            mediaType = M4DA_StreamTypeAudioAmrNarrowBand;
11547            break;
11548
11549        case M4AD_kTypeAAC:
11550            mediaType = M4DA_StreamTypeAudioAac;
11551            break;
11552
11553        case M4AD_kTypeMP3:
11554            mediaType = M4DA_StreamTypeAudioMp3;
11555            break;
11556
11557        default:
11558            M4OSA_TRACE1_1(
11559                "M4MCS_registerAudioDecoderExtended: unknown decoder type %d",
11560                decoderType);
11561            return M4ERR_PARAMETER;
11562    }
11563
11564    if( M4OSA_NULL != pC->m_pAudioDecoder )
11565    {
11566        M4OSA_TRACE3_0(
11567            "M4MCS_registerAudioDecoderExtended:\
11568                 pC->m_pAudioDecoder already set to previous registered Dec shell");
11569
11570        if( pC->pReaderAudioStream->m_basicProperties.m_streamType
11571            == mediaType )
11572            bResetCurrentAudioDecoder = M4OSA_TRUE;
11573
11574        /* Audio decoder may be created for getting input Clip properties.
11575         In that case, previous audio dec context needs to be destroyed*
11576        * before registering new decoder shell */
11577        if( M4OSA_NULL != pC->pAudioDecCtxt )
11578        {
11579            err = pC->m_pAudioDecoder->m_pFctDestroyAudioDec(pC->pAudioDecCtxt);
11580            pC->pAudioDecCtxt = M4OSA_NULL;
11581
11582            if( M4NO_ERROR != err )
11583            {
11584                M4OSA_TRACE1_1(
11585                    "M4MCS_registerAudioDecoderExtended:\
11586                         m_pAudioDecoder->m_pFctDestroyAudioDec returns 0x%x",
11587                    err);
11588            }
11589        }
11590    }
11591
11592    err = M4MCS_registerAudioDecoder(pContext, decoderType, pDecoderInterface);
11593
11594    if( M4NO_ERROR != err )
11595    {
11596        M4OSA_TRACE1_1(
11597            "M4MCS_registerAudioDecoderExtended:\
11598                 M4MCS_registerAudioDecoder failed with error 0x%08X",
11599            err);
11600        M4OSA_free((M4OSA_MemAddr32)pDecoderInterface);
11601        return err;
11602    }
11603
11604    ( (M4MCS_InternalContext
11605        *)pContext)->m_pAudioDecoderItTable[decoderType] = pDecoderInterface;
11606    ( (M4MCS_InternalContext
11607        *)pContext)->m_pAudioDecoderUserDataTable[decoderType] = pUserData;
11608
11609    ( (M4MCS_InternalContext *)pContext)->bExtOMXAudDecoder = M4OSA_TRUE;
11610
11611    if( ( M4NO_ERROR == err) && (M4OSA_TRUE == bResetCurrentAudioDecoder) )
11612    {
11613        err = M4MCS_setCurrentAudioDecoder(pContext, mediaType);
11614        M4OSA_TRACE3_1(
11615            "M4MCS_registerAudioDecoderExtended: M4MCS_setCurrentAudioDecoder returned 0x%x",
11616            err);
11617    }
11618    return err;
11619}
11620