matroskablock.c 16.3 KB
Newer Older
1 2
/*
 * $Id$
3
 * Copyright (c) 2010-2011, Matroska (non-profit organisation)
4 5 6 7 8 9 10 11 12
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
13
 *     * Neither the name of the Matroska assocation nor the
14 15 16
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
17
 * THIS SOFTWARE IS PROVIDED BY the Matroska association ``AS IS'' AND ANY
18 19 20 21 22 23 24 25 26 27 28
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL The Matroska Foundation BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "matroska/matroska.h"
29
#include "matroska/matroska_sem.h"
30
#include "matroska/matroska_internal.h"
31 32 33 34 35
#if defined(CONFIG_CODEC_HELPER)
#include "ivorbiscodec.h"
#include "codec_internal.h"
#include "misc.h"
#endif
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

static int A_MPEG_freq[4][4] =
{
// v2.5   *    v2    v1
  {11025, 0, 22050, 44100},
  {12000, 0, 24000, 48000},
  { 8000, 0, 16000, 32000},
  {    0, 0,     0,     0}
};

static int A_MPEG_samples[4][4] =
{
// v2.5   *    v2    v1
  {   0,  0,    0,    0}, // unknown layer
  { 576,  0,  576, 1152}, // layer III
  {1152,  0, 1152, 1152}, // layer II
  { 384,  0,  384,  384}  // layer I
};

55 56 57 58 59 60 61 62 63 64
static const int A_AC3_freq[3][4] =
{
    {48000, 44100, 32000, 0}, // EEEE<=8
    {24000, 22050, 16000, 0}, // EEEE=9
    {12000, 11025,  8000, 0}, // EEEE=10
};

static const int A_EAC3_freq[6] = { 48000, 44100, 32000, 24000, 22050, 16000 };
static const int A_EAC3_samples[4] = { 256, 512, 768, 1536 };

65 66 67 68
static const int A_DTS_freq[16] = {
   0, 8000, 16000, 32000, 0, 0, 11025, 22050, 44100, 0, 0, 12000, 24000, 48000, 0, 0
};

69

70
err_t MATROSKA_BlockProcessFrameDurations(matroska_block *Block, stream *Input)
71
{
72 73
    ebml_master *Track=NULL;
    ebml_element *Elt;
74 75 76 77 78
    tchar_t CodecID[MAXPATH];
    err_t Err;
    bool_t ReadData;
    uint8_t *Cursor;
    size_t Frame;
79
    int Version, Layer, SampleRate, Samples, fscod, fscod2;
80

81
    Err = Node_GET(Block,MATROSKA_BLOCK_READ_TRACK,&Track);
82 83 84
    if (Err==ERR_NONE)
    {
        assert(Track!=NULL);
Steve Lhomme's avatar
Steve Lhomme committed
85
        Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextTrackType);
86
        if (!Elt || EBML_IntegerValue((ebml_integer*)Elt)!=TRACK_TYPE_AUDIO) // other track types not supported for now
87 88 89 90 91 92 93
            Err = ERR_INVALID_DATA;
        else
        {
            if (Block->FirstFrameLocation==0)
                Err = ERR_READ;
            else
            {
Steve Lhomme's avatar
Steve Lhomme committed
94
                Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextCodecID);
95 96 97 98 99 100 101 102 103 104 105 106 107 108
                if (!Elt) // missing codec ID
                    Err = ERR_INVALID_DATA;
                else
                {
                    EBML_StringGet((ebml_string*)Elt,CodecID,TSIZEOF(CodecID));
                    ReadData = 0;
                    if (!ArraySize(&Block->Data))
                    {
                        Err = MATROSKA_BlockReadData(Block,Input);
                        if (Err!=ERR_NONE)
                            goto exit;
                        ReadData = 1;
                    }

109
                    if (tcsisame_ascii(CodecID,T("A_MPEG/L3")) || tcsisame_ascii(CodecID,T("A_MPEG/L2")) || tcsisame_ascii(CodecID,T("A_MPEG/L1")))
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
                    {
                        Block->IsKeyframe = 1; // safety
                        ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0);
                        Cursor = ARRAYBEGIN(Block->Data,uint8_t);
                        for (Frame=0;Frame<ARRAYCOUNT(Block->SizeList,int32_t);++Frame)
                        {
                            Version = (Cursor[1] >> 3) & 3;
                            Layer = (Cursor[1] >> 1) & 3;
                            SampleRate = (Cursor[2] >> 2) & 3;

                            Samples = A_MPEG_samples[Layer][Version];
                            SampleRate = A_MPEG_freq[SampleRate][Version];
                            if (SampleRate!=0 && Samples!=0)
                                ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,Samples,SampleRate);
                            else
                            {
                                Err = ERR_INVALID_DATA;
                                ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = INVALID_TIMECODE_T;
                                //goto exit;
                            }

                            Cursor += ARRAYBEGIN(Block->SizeList,int32_t)[Frame];
                        }
                    }
134 135 136 137 138 139 140 141 142
                    else if (tcsisame_ascii(CodecID,T("A_AC3")))
                    {
                        Block->IsKeyframe = 1; // safety
                        ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0);
                        Cursor = ARRAYBEGIN(Block->Data,uint8_t);
                        for (Frame=0;Frame<ARRAYCOUNT(Block->SizeList,int32_t);++Frame)
                        {
                            fscod =  Cursor[5] >> 3;
                            SampleRate = Cursor[4] >> 6;
143
                            if (fscod > 10 || fscod < 8)
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
                            {
                                Err = ERR_INVALID_DATA;
                                ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = INVALID_TIMECODE_T;
                                //goto exit;
                            }
                            else
                            {
                                SampleRate = A_AC3_freq[fscod-8][SampleRate];
                                ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,1536,SampleRate);
                            }
                            Cursor += ARRAYBEGIN(Block->SizeList,int32_t)[Frame];
                        }
                    }
                    else if (tcsisame_ascii(CodecID,T("A_EAC3")))
                    {
                        Block->IsKeyframe = 1; // safety
                        ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0);
                        Cursor = ARRAYBEGIN(Block->Data,uint8_t);
                        for (Frame=0;Frame<ARRAYCOUNT(Block->SizeList,int32_t);++Frame)
                        {
                            fscod =  Cursor[4] >> 6;
                            fscod2 = (Cursor[4] >> 4) & 0x03;
                            if ((0x03 == fscod) && (0x03 == fscod2))
                            {
                                Err = ERR_INVALID_DATA;
                                ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = INVALID_TIMECODE_T;
                                //goto exit;
                            }
                            else
                            {
                                SampleRate = A_EAC3_freq[0x03 == fscod ? 3 + fscod2 : fscod];
                                Samples = (0x03 == fscod) ? 1536 : A_EAC3_samples[fscod2];
                                ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,Samples,SampleRate);
                            }
                            Cursor += ARRAYBEGIN(Block->SizeList,int32_t)[Frame];
                        }
                    }
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
                    else if (tcsisame_ascii(CodecID,T("A_DTS")))
                    {
                        Block->IsKeyframe = 1; // safety
                        ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0);
                        Cursor = ARRAYBEGIN(Block->Data,uint8_t);
                        for (Frame=0;Frame<ARRAYCOUNT(Block->SizeList,int32_t);++Frame)
                        {
                            Samples = (((Cursor[4] & 1) << 7) + (Cursor[5] >> 2) + 1) * 32;
                            // TODO: handle the frame termination
                            SampleRate = A_DTS_freq[(Cursor[8] >> 2) & 0x0F];
                            if (Samples==0 || SampleRate==0)
                            {
                                Err = ERR_INVALID_DATA;
                                ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = INVALID_TIMECODE_T;
                                //goto exit;
                            }
                            else
                                ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,Samples,SampleRate);
                            Cursor += ARRAYBEGIN(Block->SizeList,int32_t)[Frame];
                        }
                    }
202 203 204
                    else if (tcsisame_ascii(CodecID,T("A_AAC")) || tcsncmp(CodecID,T("A_AAC/"),6)==0)
                    {
                        Block->IsKeyframe = 1; // safety
Steve Lhomme's avatar
Steve Lhomme committed
205
                        Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextAudio);
206 207
                        if (Elt)
                        {
Steve Lhomme's avatar
Steve Lhomme committed
208
                            Elt = EBML_MasterFindChild((ebml_master*)Elt,&MATROSKA_ContextSamplingFrequency);
209 210 211 212 213 214 215 216 217 218
                            if (Elt)
                            {
                                ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0);
                                Samples = 1024;
                                SampleRate = (int)((ebml_float*)Elt)->Value;
                                for (Frame=0;Frame<ARRAYCOUNT(Block->SizeList,int32_t);++Frame)
                                    ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,Samples,SampleRate);
                            }
                        }
                    }
219 220 221 222
#if defined(CONFIG_CODEC_HELPER)
                    else if (tcsisame_ascii(CodecID,T("A_VORBIS")))
                    {
                        Block->IsKeyframe = 1; // safety
Steve Lhomme's avatar
Steve Lhomme committed
223
                        Elt = EBML_MasterFindChild(Track,&MATROSKA_ContextCodecPrivate);
224 225 226 227 228 229 230 231 232 233 234 235 236 237
                        if (Elt)
                        {
                            vorbis_info vi;
                            vorbis_comment vc;
                            ogg_packet OggPacket;
                        	ogg_reference OggRef;
                        	ogg_buffer OggBuffer;
                            int n,i,j;
                            codec_setup_info *ci;

		                    vorbis_info_init(&vi);
		                    vorbis_comment_init(&vc);
                            memset(&OggPacket,0,sizeof(ogg_packet));

238
		                    OggBuffer.data = (uint8_t*)EBML_BinaryGetData((ebml_binary*)Elt);
239
		                    OggBuffer.size = (long)Elt->DataSize;
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
		                    OggBuffer.refcount = 1;

                            memset(&OggRef,0,sizeof(OggRef));
		                    OggRef.buffer = &OggBuffer;
		                    OggRef.next = NULL;

		                    OggPacket.packet = &OggRef;
		                    OggPacket.packetno = -1; 

		                    n = OggBuffer.data[0];
		                    i = 1+n;
		                    j = 1;

		                    while (OggPacket.packetno < 3 && n>=j)
		                    {
			                    OggRef.begin = i;
			                    OggRef.length = 0;
			                    do
			                    {
				                    OggRef.length += OggBuffer.data[j];
			                    }
			                    while (OggBuffer.data[j++] == 255 && n>=j);
			                    i += OggRef.length;

			                    if (i > OggBuffer.size)
				                    return ERR_INVALID_DATA;

	                            ++OggPacket.packetno;
	                            OggPacket.b_o_s = OggPacket.packetno == 0;
	                            OggPacket.bytes = OggPacket.packet->length;
			                    if (!(vorbis_synthesis_headerin(&vi,&vc,&OggPacket) >= 0) && OggPacket.packetno==0)
				                    return ERR_INVALID_DATA;
		                    }

		                    if (OggPacket.packetno < 3)
		                    {
			                    OggRef.begin = i;
			                    OggRef.length = OggBuffer.size - i; 

	                            ++OggPacket.packetno;
	                            OggPacket.b_o_s = OggPacket.packetno == 0;
	                            OggPacket.bytes = OggPacket.packet->length;

                                if (!(vorbis_synthesis_headerin(&vi,&vc,&OggPacket) >= 0) && OggPacket.packetno==0)
				                    return ERR_INVALID_DATA;
                            }

                            SampleRate = vi.rate;
                            ArrayResize(&Block->Durations,sizeof(timecode_t)*ARRAYCOUNT(Block->SizeList,int32_t),0);
                            Cursor = ARRAYBEGIN(Block->Data,uint8_t);
                            ci = vi.codec_setup;
                            for (Frame=0;Frame<ARRAYCOUNT(Block->SizeList,int32_t);++Frame)
                            {
                                fscod = _ilog(ci->modes-1);
                                fscod = (Cursor[0] & 0x7F) >> (7-fscod);
                                if (fscod > ci->modes)
                                {
                                    Err = ERR_INVALID_DATA;
                                    ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = INVALID_TIMECODE_T;
                                    //goto exit;
                                }
                                else
                                {
                                    Samples = ci->blocksizes[ci->mode_param[fscod]->blockflag];
                                    ARRAYBEGIN(Block->Durations,timecode_t)[Frame] = Scale64(1000000000,Samples,SampleRate);
                                }
                                Cursor += ARRAYBEGIN(Block->SizeList,int32_t)[Frame];
                            }
308 309
                            vorbis_comment_clear(&vc);
                            vorbis_info_clear(&vi);
310 311 312
                        }
                    }
#endif
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

                    if (ReadData)
                    {
                        ArrayClear(&Block->Data);
                        Block->Base.Base.bValueIsSet = 0;
                    }
                }
            }
        }
    }
exit:
    return Err;
}

size_t MATROSKA_BlockGetFrameCount(const matroska_block *Block)
{
    return ARRAYCOUNT(Block->SizeList,int32_t);
}

332 333 334 335 336 337 338
size_t MATROSKA_BlockGetLength(const matroska_block *Block, size_t FrameNum)
{
	if (FrameNum >= ARRAYCOUNT(Block->SizeList,int32_t))
		return 0;
	return ARRAYBEGIN(Block->SizeList,int32_t)[FrameNum];
}

339 340 341 342 343 344 345 346 347 348 349 350 351 352
timecode_t MATROSKA_BlockGetFrameDuration(const matroska_block *Block, size_t FrameNum)
{
    if (FrameNum >= ARRAYCOUNT(Block->Durations,timecode_t))
        return INVALID_TIMECODE_T;
    return ARRAYBEGIN(Block->Durations,timecode_t)[FrameNum];
}

timecode_t MATROSKA_BlockGetFrameStart(const matroska_block *Block, size_t FrameNum)
{
    if (FrameNum >= ARRAYCOUNT(Block->Durations,timecode_t))
        return INVALID_TIMECODE_T;
    else
    {
        size_t i;
353
        timecode_t Start = MATROSKA_BlockTimecode((matroska_block*)Block);
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
        if (Start!=INVALID_TIMECODE_T)
        {
            for (i=0;i<FrameNum;++i)
            {
                if (ARRAYBEGIN(Block->Durations,timecode_t)[i]==INVALID_TIMECODE_T)
                    return INVALID_TIMECODE_T;
                Start += ARRAYBEGIN(Block->Durations,timecode_t)[i];
            }
        }
        return Start;
    }
}

timecode_t MATROSKA_BlockGetFrameEnd(const matroska_block *Block, size_t FrameNum)
{
    timecode_t Result = MATROSKA_BlockGetFrameStart(Block,FrameNum), a;
    if (Result==INVALID_TIMECODE_T)
        return INVALID_TIMECODE_T;
    a = MATROSKA_BlockGetFrameDuration(Block,FrameNum);
    if (a==INVALID_TIMECODE_T)
        return INVALID_TIMECODE_T;
    return Result + a;
}