Blame view

trunk/src/app/srs_app_avc_aac.cpp 20.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*
The MIT License (MIT)

Copyright (c) 2013-2014 winlin

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <srs_app_avc_aac.hpp>

#include <srs_kernel_error.hpp>
#include <srs_kernel_log.hpp>
#include <srs_kernel_stream.hpp>
29
#include <srs_protocol_amf0.hpp>
30
#include <srs_app_utility.hpp>
31
#include <srs_protocol_utility.hpp>
32
33
SrsCodecSampleUnit::SrsCodecSampleUnit()
34 35 36 37 38
{
    size = 0;
    bytes = NULL;
}
39
SrsCodecSampleUnit::~SrsCodecSampleUnit()
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
{
}

SrsCodecSample::SrsCodecSample()
{
    clear();
}

SrsCodecSample::~SrsCodecSample()
{
}

void SrsCodecSample::clear()
{
    is_video = false;
55
    nb_sample_units = 0;
56 57 58 59 60 61 62 63 64 65 66

    cts = 0;
    frame_type = SrsCodecVideoAVCFrameReserved;
    avc_packet_type = SrsCodecVideoAVCTypeReserved;
    
    sound_rate = SrsCodecAudioSampleRateReserved;
    sound_size = SrsCodecAudioSampleSizeReserved;
    sound_type = SrsCodecAudioSoundTypeReserved;
    aac_packet_type = SrsCodecAudioTypeReserved;
}
67
int SrsCodecSample::add_sample_unit(char* bytes, int size)
68 69 70
{
    int ret = ERROR_SUCCESS;
    
winlin authored
71
    if (nb_sample_units >= __SRS_SRS_MAX_CODEC_SAMPLE) {
72 73
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode samples error, "
winlin authored
74
            "exceed the max count: %d, ret=%d", __SRS_SRS_MAX_CODEC_SAMPLE, ret);
75 76 77
        return ret;
    }
    
78 79 80
    SrsCodecSampleUnit* sample_unit = &sample_units[nb_sample_units++];
    sample_unit->bytes = bytes;
    sample_unit->size = size;
81 82 83 84 85 86
    
    return ret;
}

SrsAvcAacCodec::SrsAvcAacCodec()
{
winlin authored
87 88 89 90 91 92 93 94 95 96 97 98
    width                       = 0;
    height                      = 0;
    duration                    = 0;
    NAL_unit_length             = 0;
    frame_rate                  = 0;
    video_data_rate             = 0;
    video_codec_id              = 0;
    audio_data_rate             = 0;
    audio_codec_id              = 0;
    avc_profile                 = 0;
    avc_level                   = 0;
    aac_profile                 = 0;
winlin authored
99
    aac_sample_rate             = __SRS_AAC_SAMPLE_RATE_UNSET; // sample rate ignored
winlin authored
100 101 102 103 104 105
    aac_channels                = 0;
    avc_extra_size              = 0;
    avc_extra_data              = NULL;
    aac_extra_size              = 0;
    aac_extra_data              = NULL;
    sequenceParameterSetLength  = 0;
106
    sequenceParameterSetNALUnit = NULL;
winlin authored
107 108
    pictureParameterSetLength   = 0;
    pictureParameterSetNALUnit  = NULL;
109 110 111 112 113 114 115 116 117 118 119 120 121 122

    stream = new SrsStream();
}

SrsAvcAacCodec::~SrsAvcAacCodec()
{
    srs_freep(avc_extra_data);
    srs_freep(aac_extra_data);

    srs_freep(stream);
    srs_freep(sequenceParameterSetNALUnit);
    srs_freep(pictureParameterSetNALUnit);
}
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
int SrsAvcAacCodec::metadata_demux(SrsAmf0Object* metadata)
{
    int ret = ERROR_SUCCESS;
    
    srs_assert(metadata);
    
    SrsAmf0Object* obj = metadata;
    
    //    finger out the codec info from metadata if possible.
    SrsAmf0Any* prop = NULL;

    if ((prop = obj->get_property("duration")) != NULL && prop->is_number()) {
        duration = (int)prop->to_number();
    }
    if ((prop = obj->get_property("width")) != NULL && prop->is_number()) {
        width = (int)prop->to_number();
    }
    if ((prop = obj->get_property("height")) != NULL && prop->is_number()) {
        height = (int)prop->to_number();
    }
    if ((prop = obj->get_property("framerate")) != NULL && prop->is_number()) {
        frame_rate = (int)prop->to_number();
    }
    if ((prop = obj->get_property("videocodecid")) != NULL && prop->is_number()) {
        video_codec_id = (int)prop->to_number();
    }
    if ((prop = obj->get_property("videodatarate")) != NULL && prop->is_number()) {
        video_data_rate = (int)(1000 * prop->to_number());
    }
    
    if ((prop = obj->get_property("audiocodecid")) != NULL && prop->is_number()) {
        audio_codec_id = (int)prop->to_number();
    }
    if ((prop = obj->get_property("audiodatarate")) != NULL && prop->is_number()) {
        audio_data_rate = (int)(1000 * prop->to_number());
    }
    
    // ignore the following, for each flv/rtmp packet contains them:
    // audiosamplerate, sample->sound_rate
    // audiosamplesize, sample->sound_size
    // stereo,             sample->sound_type
    
    return ret;
}
168
int SrsAvcAacCodec::audio_aac_demux(char* data, int size, SrsCodecSample* sample)
169 170 171 172 173 174 175 176 177 178
{
    int ret = ERROR_SUCCESS;
    
    sample->is_video = false;
    
    if (!data || size <= 0) {
        srs_trace("no audio present, hls ignore it.");
        return ret;
    }
    
179
    if ((ret = stream->initialize(data, size)) != ERROR_SUCCESS) {
180 181 182 183 184 185 186 187 188 189
        return ret;
    }

    // audio decode
    if (!stream->require(1)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode audio sound_format failed. ret=%d", ret);
        return ret;
    }
    
190
    // @see: E.4.2 Audio Tags, video_file_format_spec_v10_1.pdf, page 76
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    int8_t sound_format = stream->read_1bytes();
    
    int8_t sound_type = sound_format & 0x01;
    int8_t sound_size = (sound_format >> 1) & 0x01;
    int8_t sound_rate = (sound_format >> 2) & 0x03;
    sound_format = (sound_format >> 4) & 0x0f;
    
    audio_codec_id = sound_format;
    sample->sound_type = (SrsCodecAudioSoundType)sound_type;
    sample->sound_rate = (SrsCodecAudioSampleRate)sound_rate;
    sample->sound_size = (SrsCodecAudioSampleSize)sound_size;
    
    // only support aac
    if (audio_codec_id != SrsCodecAudioAAC) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls only support audio aac codec. actual=%d, ret=%d", audio_codec_id, ret);
        return ret;
    }

    if (!stream->require(1)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode audio aac_packet_type failed. ret=%d", ret);
        return ret;
    }
    
    int8_t aac_packet_type = stream->read_1bytes();
    sample->aac_packet_type = (SrsCodecAudioType)aac_packet_type;
    
    if (aac_packet_type == SrsCodecAudioTypeSequenceHeader) {
        // AudioSpecificConfig
        // 1.6.2.1 AudioSpecificConfig, in aac-mp4a-format-ISO_IEC_14496-3+2001.pdf, page 33.
222
        aac_extra_size = stream->size() - stream->pos();
223 224 225
        if (aac_extra_size > 0) {
            srs_freep(aac_extra_data);
            aac_extra_data = new char[aac_extra_size];
226
            memcpy(aac_extra_data, stream->data() + stream->pos(), aac_extra_size);
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
        }
        
        // only need to decode the first 2bytes:
        // audioObjectType, aac_profile, 5bits.
        // samplingFrequencyIndex, aac_sample_rate, 4bits.
        // channelConfiguration, aac_channels, 4bits
        if (!stream->require(2)) {
            ret = ERROR_HLS_DECODE_ERROR;
            srs_error("hls decode audio aac sequence header failed. ret=%d", ret);
            return ret;
        }
        aac_profile = stream->read_1bytes();
        aac_sample_rate = stream->read_1bytes();
        
        aac_channels = (aac_sample_rate >> 3) & 0x0f;
        aac_sample_rate = ((aac_profile << 1) & 0x0e) | ((aac_sample_rate >> 7) & 0x01);
        aac_profile = (aac_profile >> 3) & 0x1f;
        
        if (aac_profile == 0 || aac_profile == 0x1f) {
            ret = ERROR_HLS_DECODE_ERROR;
            srs_error("hls decode audio aac sequence header failed, "
                "adts object=%d invalid. ret=%d", aac_profile, ret);
            return ret;
        }
        
252 253
        // TODO: FIXME: to support aac he/he-v2, see: ngx_rtmp_codec_parse_aac_header
        // @see: https://github.com/winlinvip/nginx-rtmp-module/commit/3a5f9eea78fc8d11e8be922aea9ac349b9dcbfc2
254 255 256 257
        // 
        // donot force to LC, @see: https://github.com/winlinvip/simple-rtmp-server/issues/81
        // the source will print the sequence header info.
        //if (aac_profile > 3) {
258 259 260
            // Mark all extended profiles as LC
            // to make Android as happy as possible.
            // @see: ngx_rtmp_hls_parse_aac_header
261 262
            //aac_profile = 1;
        //}
263 264 265 266 267 268 269 270 271 272
    } else if (aac_packet_type == SrsCodecAudioTypeRawData) {
        // ensure the sequence header demuxed
        if (aac_extra_size <= 0 || !aac_extra_data) {
            ret = ERROR_HLS_DECODE_ERROR;
            srs_error("hls decode audio aac failed, sequence header not found. ret=%d", ret);
            return ret;
        }
        
        // Raw AAC frame data in UI8 []
        // 6.3 Raw Data, aac-iso-13818-7.pdf, page 28
273
        if ((ret = sample->add_sample_unit(stream->data() + stream->pos(), stream->size() - stream->pos())) != ERROR_SUCCESS) {
274 275 276 277 278 279 280
            srs_error("hls add audio sample failed. ret=%d", ret);
            return ret;
        }
    } else {
        // ignored.
    }
    
281
    // reset the sample rate by sequence header
winlin authored
282
    if (aac_sample_rate != __SRS_AAC_SAMPLE_RATE_UNSET) {
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        static int aac_sample_rates[] = {
            96000, 88200, 64000, 48000,
            44100, 32000, 24000, 22050,
            16000, 12000, 11025,  8000,
            7350,     0,     0,    0
        };
        switch (aac_sample_rates[aac_sample_rate]) {
            case 11025:
                sample->sound_rate = SrsCodecAudioSampleRate11025;
                break;
            case 22050:
                sample->sound_rate = SrsCodecAudioSampleRate22050;
                break;
            case 44100:
                sample->sound_rate = SrsCodecAudioSampleRate44100;
                break;
299 300
            default:
                break;
301 302 303
        };
    }
    
304 305 306 307 308 309
    srs_info("audio decoded, type=%d, codec=%d, asize=%d, rate=%d, format=%d, size=%d", 
        sound_type, audio_codec_id, sound_size, sound_rate, sound_format, size);
    
    return ret;
}
310
int SrsAvcAacCodec::video_avc_demux(char* data, int size, SrsCodecSample* sample)
311 312 313 314 315 316 317 318 319 320
{
    int ret = ERROR_SUCCESS;
    
    sample->is_video = true;
    
    if (!data || size <= 0) {
        srs_trace("no video present, hls ignore it.");
        return ret;
    }
    
321
    if ((ret = stream->initialize(data, size)) != ERROR_SUCCESS) {
322 323 324 325 326 327 328 329 330 331
        return ret;
    }

    // video decode
    if (!stream->require(1)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video frame_type failed. ret=%d", ret);
        return ret;
    }
    
332
    // @see: E.4.3 Video Tags, video_file_format_spec_v10_1.pdf, page 78
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    int8_t frame_type = stream->read_1bytes();
    int8_t codec_id = frame_type & 0x0f;
    frame_type = (frame_type >> 4) & 0x0f;
    
    sample->frame_type = (SrsCodecVideoAVCFrame)frame_type;
    
    // only support h.264/avc
    if (codec_id != SrsCodecVideoAVC) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls only support video h.264/avc codec. actual=%d, ret=%d", codec_id, ret);
        return ret;
    }
    video_codec_id = codec_id;
    
    if (!stream->require(4)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video avc_packet_type failed. ret=%d", ret);
        return ret;
    }
    int8_t avc_packet_type = stream->read_1bytes();
    int32_t composition_time = stream->read_3bytes();
    
    // pts = dts + cts.
    sample->cts = composition_time;
    sample->avc_packet_type = (SrsCodecVideoAVCType)avc_packet_type;
    
    if (avc_packet_type == SrsCodecVideoAVCTypeSequenceHeader) {
360 361
        if ((ret = avc_demux_sps_pps(stream)) != ERROR_SUCCESS) {
            return ret;
362
        }
363 364 365
    } else if (avc_packet_type == SrsCodecVideoAVCTypeNALU){
        // ensure the sequence header demuxed
        if (avc_extra_size <= 0 || !avc_extra_data) {
366
            ret = ERROR_HLS_DECODE_ERROR;
367
            srs_error("hls decode video avc failed, sequence header not found. ret=%d", ret);
368 369
            return ret;
        }
370
        
371 372 373 374 375 376 377 378 379 380 381 382 383
        // One or more NALUs (Full frames are required)
        // try  "AnnexB" from H.264-AVC-ISO_IEC_14496-10.pdf, page 211.
        if ((ret = avc_demux_annexb_format(stream, sample)) != ERROR_SUCCESS) {
            // stop try when system error.
            if (ret != ERROR_HLS_AVC_TRY_OTHERS) {
                srs_error("avc demux for annexb failed. ret=%d", ret);
                return ret;
            }
            
            // try "ISO Base Media File Format" from H.264-AVC-ISO_IEC_14496-15.pdf, page 20
            if ((ret = avc_demux_ibmf_format(stream, sample)) != ERROR_SUCCESS) {
                return ret;
            }
384
        }
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
    } else {
        // ignored.
    }
    
    srs_info("video decoded, type=%d, codec=%d, avc=%d, time=%d, size=%d", 
        frame_type, video_codec_id, avc_packet_type, composition_time, size);
    
    return ret;
}

int SrsAvcAacCodec::avc_demux_sps_pps(SrsStream* stream)
{
    int ret = ERROR_SUCCESS;
    
    // AVCDecoderConfigurationRecord
    // 5.2.4.1.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
    avc_extra_size = stream->size() - stream->pos();
    if (avc_extra_size > 0) {
        srs_freep(avc_extra_data);
        avc_extra_data = new char[avc_extra_size];
        memcpy(avc_extra_data, stream->data() + stream->pos(), avc_extra_size);
    }
    
    if (!stream->require(6)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video avc sequenc header failed. ret=%d", ret);
        return ret;
    }
    //int8_t configurationVersion = stream->read_1bytes();
    stream->read_1bytes();
    //int8_t AVCProfileIndication = stream->read_1bytes();
    avc_profile = stream->read_1bytes();
    //int8_t profile_compatibility = stream->read_1bytes();
    stream->read_1bytes();
    //int8_t AVCLevelIndication = stream->read_1bytes();
    avc_level = stream->read_1bytes();
    
    // parse the NALU size.
    int8_t lengthSizeMinusOne = stream->read_1bytes();
    lengthSizeMinusOne &= 0x03;
    NAL_unit_length = lengthSizeMinusOne;
    
    // 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
    // 5.2.4.1 AVC decoder configuration record
    // 5.2.4.1.2 Semantics
    // The value of this field shall be one of 0, 1, or 3 corresponding to a
    // length encoded with 1, 2, or 4 bytes, respectively.
    if (NAL_unit_length == 2) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("sps lengthSizeMinusOne should never be 2. ret=%d", ret);
        return ret;
    }
    
    // 1 sps
    if (!stream->require(1)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video avc sequenc header sps failed. ret=%d", ret);
        return ret;
    }
    int8_t numOfSequenceParameterSets = stream->read_1bytes();
    numOfSequenceParameterSets &= 0x1f;
    if (numOfSequenceParameterSets != 1) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video avc sequenc header sps failed. ret=%d", ret);
        return ret;
    }
    if (!stream->require(2)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video avc sequenc header sps size failed. ret=%d", ret);
        return ret;
    }
    sequenceParameterSetLength = stream->read_2bytes();
    if (!stream->require(sequenceParameterSetLength)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video avc sequenc header sps data failed. ret=%d", ret);
        return ret;
    }
    if (sequenceParameterSetLength > 0) {
        srs_freep(sequenceParameterSetNALUnit);
        sequenceParameterSetNALUnit = new char[sequenceParameterSetLength];
        memcpy(sequenceParameterSetNALUnit, stream->data() + stream->pos(), sequenceParameterSetLength);
        stream->skip(sequenceParameterSetLength);
    }
    // 1 pps
    if (!stream->require(1)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video avc sequenc header pps failed. ret=%d", ret);
        return ret;
    }
    int8_t numOfPictureParameterSets = stream->read_1bytes();
    numOfPictureParameterSets &= 0x1f;
    if (numOfPictureParameterSets != 1) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video avc sequenc header pps failed. ret=%d", ret);
        return ret;
    }
    if (!stream->require(2)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video avc sequenc header pps size failed. ret=%d", ret);
        return ret;
    }
    pictureParameterSetLength = stream->read_2bytes();
    if (!stream->require(pictureParameterSetLength)) {
        ret = ERROR_HLS_DECODE_ERROR;
        srs_error("hls decode video avc sequenc header pps data failed. ret=%d", ret);
        return ret;
    }
    if (pictureParameterSetLength > 0) {
        srs_freep(pictureParameterSetNALUnit);
        pictureParameterSetNALUnit = new char[pictureParameterSetLength];
        memcpy(pictureParameterSetNALUnit, stream->data() + stream->pos(), pictureParameterSetLength);
        stream->skip(pictureParameterSetLength);
    }
    
    return ret;
}

int SrsAvcAacCodec::avc_demux_annexb_format(SrsStream* stream, SrsCodecSample* sample)
{
    int ret = ERROR_SUCCESS;
    
    // not annexb, try others
    if (!srs_avc_startswith_annexb(stream, NULL)) {
        return ERROR_HLS_AVC_TRY_OTHERS;
    }
    
    // AnnexB
    // B.1.1 Byte stream NAL unit syntax,
    // H.264-AVC-ISO_IEC_14496-10.pdf, page 211.
    while (!stream->empty()) {
        // find start code
        int nb_start_code = 0;
        if (!srs_avc_startswith_annexb(stream, &nb_start_code)) {
518 519
            return ret;
        }
520 521 522 523

        // skip the start code.
        if (nb_start_code > 0) {
            stream->skip(nb_start_code);
524
        }
525 526 527 528 529 530
        
        // the NALU start bytes.
        char* p = stream->data() + stream->pos();
        
        // get the last matched NALU
        while (!stream->empty()) {
531
            if (srs_avc_startswith_annexb(stream, NULL)) {
532 533 534 535
                break;
            }
            
            stream->skip(1);
536
        }
537 538 539 540 541 542
        
        char* pp = stream->data() + stream->pos();
        
        // skip the empty.
        if (pp - p <= 0) {
            continue;
543
        }
544 545 546 547
        
        // got the NALU.
        if ((ret = sample->add_sample_unit(p, pp - p)) != ERROR_SUCCESS) {
            srs_error("annexb add video sample failed. ret=%d", ret);
548 549
            return ret;
        }
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
    }
    
    return ret;
}

int SrsAvcAacCodec::avc_demux_ibmf_format(SrsStream* stream, SrsCodecSample* sample)
{
    int ret = ERROR_SUCCESS;
    
    int PictureLength = stream->size() - stream->pos();
    
    // 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 16
    // 5.2.4.1 AVC decoder configuration record
    // 5.2.4.1.2 Semantics
    // The value of this field shall be one of 0, 1, or 3 corresponding to a
    // length encoded with 1, 2, or 4 bytes, respectively.
    srs_assert(NAL_unit_length != 2);
    
    // 5.3.4.2.1 Syntax, H.264-AVC-ISO_IEC_14496-15.pdf, page 20
    for (int i = 0; i < PictureLength;) {
        // unsigned int((NAL_unit_length+1)*8) NALUnitLength;
        if (!stream->require(NAL_unit_length + 1)) {
572
            ret = ERROR_HLS_DECODE_ERROR;
573
            srs_error("hls decode video avc NALU size failed. ret=%d", ret);
574 575
            return ret;
        }
576 577 578 579 580 581 582 583 584 585 586 587
        int32_t NALUnitLength = 0;
        if (NAL_unit_length == 3) {
            NALUnitLength = stream->read_4bytes();
        } else if (NAL_unit_length == 1) {
            NALUnitLength = stream->read_2bytes();
        } else {
            NALUnitLength = stream->read_1bytes();
        }
        
        // maybe stream is invalid format.
        // see: https://github.com/winlinvip/simple-rtmp-server/issues/183
        if (NALUnitLength < 0) {
588
            ret = ERROR_HLS_DECODE_ERROR;
589
            srs_error("maybe stream is AnnexB format. ret=%d", ret);
590 591
            return ret;
        }
592 593 594
        
        // NALUnit
        if (!stream->require(NALUnitLength)) {
595
            ret = ERROR_HLS_DECODE_ERROR;
596
            srs_error("hls decode video avc NALU data failed. ret=%d", ret);
597 598
            return ret;
        }
599 600 601
        // 7.3.1 NAL unit syntax, H.264-AVC-ISO_IEC_14496-10.pdf, page 44.
        if ((ret = sample->add_sample_unit(stream->data() + stream->pos(), NALUnitLength)) != ERROR_SUCCESS) {
            srs_error("hls add video sample failed. ret=%d", ret);
602 603
            return ret;
        }
604
        stream->skip(NALUnitLength);
605
        
606
        i += NAL_unit_length + 1 + NALUnitLength;
607 608 609 610
    }
    
    return ret;
}
611