media: miscellaneous fixes to VT contribution

- fix MediaSource.h path
- fix setDataSource binder code
- use MediaCodecConstants instead of OMX/ACodec constants
- fix spacing
- fix typos
- remove unused code
- commented some tricky code segments
- AAVC/HEVCAssembler: re-read next buffer if buffer was deleted
- RTPSource: pull out constants kMinVideoBitrate and kBufferingPollIntervalUs
- RTPSource: check state early in prepareAsync
- RTPSource: fix potential null dereference in setSource
- ARTPAssembler: make showing queue runtime configurable via debug.stagefright.rtp bool property
- ARTPWriter: fix security issues: protect against reading OOB in
  sendSPSPPSIfIFrame and StripStartcode
- ARTPWriter: free buffers early in destructor
- ARTPWriter: create PPS buffer only if there is PPS
- ARTPConnection: fix security issues: protect against reading OOB in
  parseRTPExt, parseTSFB, and parsePSFB. Also remove remote null-dereference.
- AHEVCAssembler: fix security issues: protect against reading OOB in
  addFragmentedNALUnit

Bug: 121230209
Test: build
Merged-in: Iada8b878e396452c1d281c60f3754e13e34bcddb
Change-Id: Iada8b878e396452c1d281c60f3754e13e34bcddb
diff --git a/media/libmedia/IMediaPlayer.cpp b/media/libmedia/IMediaPlayer.cpp
index 134e6fe..8a4b17c 100644
--- a/media/libmedia/IMediaPlayer.cpp
+++ b/media/libmedia/IMediaPlayer.cpp
@@ -697,7 +697,7 @@
         }
         case SET_DATA_SOURCE_RTP: {
             CHECK_INTERFACE(IMediaPlayer, data, reply);
-            const String8& rtpParams = data.readString8();
+            String8 rtpParams = data.readString8();
             reply->writeInt32(setDataSource(rtpParams));
             return NO_ERROR;
         }
diff --git a/media/libmedia/include/media/mediarecorder.h b/media/libmedia/include/media/mediarecorder.h
index 41b1d2e..fbcdb28 100644
--- a/media/libmedia/include/media/mediarecorder.h
+++ b/media/libmedia/include/media/mediarecorder.h
@@ -292,7 +292,7 @@
     Mutex                       mLock;
     Mutex                       mNotifyLock;
 
-    int                         mOutputFormat;
+    output_format               mOutputFormat;
 };
 
 };  // namespace android
diff --git a/media/libmedia/mediarecorder.cpp b/media/libmedia/mediarecorder.cpp
index 87c9377..d9d1f25 100644
--- a/media/libmedia/mediarecorder.cpp
+++ b/media/libmedia/mediarecorder.cpp
@@ -244,7 +244,7 @@
         mCurrentState = MEDIA_RECORDER_ERROR;
         return ret;
     }
-    mOutputFormat = of;
+    mOutputFormat = (output_format)of;
     mCurrentState = MEDIA_RECORDER_DATASOURCE_CONFIGURED;
     return ret;
 }
@@ -745,7 +745,7 @@
     mIsAudioEncoderSet = false;
     mIsVideoEncoderSet = false;
     mIsOutputFileSet   = false;
-    mOutputFormat      = 0;
+    mOutputFormat      = OUTPUT_FORMAT_DEFAULT;
 }
 
 // Release should be OK in any state
diff --git a/media/libmediaplayerservice/StagefrightRecorder.cpp b/media/libmediaplayerservice/StagefrightRecorder.cpp
index 1238f6b..f6a3728 100644
--- a/media/libmediaplayerservice/StagefrightRecorder.cpp
+++ b/media/libmediaplayerservice/StagefrightRecorder.cpp
@@ -44,6 +44,7 @@
 #include <media/stagefright/CameraSourceTimeLapse.h>
 #include <media/stagefright/MPEG2TSWriter.h>
 #include <media/stagefright/MPEG4Writer.h>
+#include <media/stagefright/MediaCodecConstants.h>
 #include <media/stagefright/MediaDefs.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/MediaCodecSource.h>
@@ -577,10 +578,10 @@
     mVideoBitRate = bitRate;
 
     // A new bitrate(TMMBR) should be applied on runtime as well if OutputFormat is RTP_AVP
-    if (mOutputFormat == OUTPUT_FORMAT_RTP_AVP &&  mStarted && mPauseStartTimeUs == 0) {
-        /* Regular I frames overloads on the network so we should consider about it.
-         * Discounted encoding bitrate will be margins for the overloads.
-         * But applied bitrate reply(TMMBN) must be sent as same as TMMBR */
+    if (mOutputFormat == OUTPUT_FORMAT_RTP_AVP && mStarted && mPauseStartTimeUs == 0) {
+        // Regular I frames may overload the network so we reduce the bitrate to allow
+        // margins for the I frame overruns.
+        // Still send requested bitrate (TMMBR) in the reply (TMMBN).
         const float coefficient = 0.8f;
         mVideoBitRate = (bitRate * coefficient) / 1000 * 1000;
         mVideoEncoderSource->setEncodingBitrate(mVideoBitRate);
@@ -593,6 +594,7 @@
 
 status_t StagefrightRecorder::setParamVideoBitRateMode(int32_t bitRateMode) {
     ALOGV("setParamVideoBitRateMode: %d", bitRateMode);
+    // TODO: clarify what bitrate mode of -1 is as these start from 0
     if (bitRateMode < -1) {
         ALOGE("Unsupported video bitrate mode: %d", bitRateMode);
         return BAD_VALUE;
@@ -1990,7 +1992,6 @@
     }
 
     format->setInt32("bitrate", mVideoBitRate);
-    // OMX encoder option how to control bitrate
     format->setInt32("bitrate-mode", mVideoBitRateMode);
     format->setInt32("frame-rate", mFrameRate);
     format->setInt32("i-frame-interval", mIFramesIntervalSec);
@@ -2414,8 +2415,8 @@
     mVideoHeight   = 144;
     mFrameRate     = -1;
     mVideoBitRate  = 192000;
-    // Following ACodec's default
-    mVideoBitRateMode = OMX_Video_ControlRateVariable;
+    // Following MediaCodec's default
+    mVideoBitRateMode = BITRATE_MODE_VBR;
     mSampleRate    = 8000;
     mAudioChannels = 1;
     mAudioBitRate  = 12200;
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index a16b6be..4e7daa5 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -1928,8 +1928,6 @@
 
     format->setInt32("priority", 0 /* realtime */);
 
-    AString mime;
-    format->findString("mime", &mime);
     if (mDataSourceType == DATA_SOURCE_TYPE_RTP) {
         ALOGV("instantiateDecoder: set decoder error free on stream corrupt.");
         format->setInt32("corrupt-free", true);
diff --git a/media/libmediaplayerservice/nuplayer/RTPSource.cpp b/media/libmediaplayerservice/nuplayer/RTPSource.cpp
index 7e77456..a6601cd 100644
--- a/media/libmediaplayerservice/nuplayer/RTPSource.cpp
+++ b/media/libmediaplayerservice/nuplayer/RTPSource.cpp
@@ -80,6 +80,9 @@
         mLooper->registerHandler(mRTPConn);
     }
 
+    CHECK_EQ(mState, (int)DISCONNECTED);
+    mState = CONNECTING;
+
     setParameters(mRTPParams);
 
     TrackInfo *info = NULL;
@@ -111,7 +114,7 @@
         // index(i) should be started from 1. 0 is reserved for [root]
         mRTPConn->addStream(sockRtp, sockRtcp, desc, i + 1, notify, false);
         mRTPConn->setSelfID(info->mSelfID);
-        mRTPConn->setMinMaxBitrate(videoMinBitrate, info->mAS * 1000);
+        mRTPConn->setMinMaxBitrate(kMinVideoBitrate, info->mAS * 1000 /* kbps */);
 
         info->mRTPSocket = sockRtp;
         info->mRTCPSocket = sockRtcp;
@@ -139,9 +142,6 @@
         info->mSource = source;
     }
 
-    CHECK_EQ(mState, (int)DISCONNECTED);
-    mState = CONNECTING;
-
     if (mInPreparationPhase) {
         mInPreparationPhase = false;
         notifyPrepared();
@@ -340,7 +340,7 @@
 
 void NuPlayer::RTPSource::schedulePollBuffering() {
     sp<AMessage> msg = new AMessage(kWhatPollBuffering, this);
-    msg->post(1000000ll); // 1 second intervals
+    msg->post(kBufferingPollIntervalUs); // 1 second intervals
 }
 
 void NuPlayer::RTPSource::onPollBuffering() {
@@ -412,6 +412,8 @@
                 break;
             }
 
+            // Implicitly assert on valid trackIndex here, which we ensure by
+            // never removing tracks.
             TrackInfo *info = &mTracks.editItemAt(trackIndex);
 
             sp<AnotherPacketSource> source = info->mSource;
@@ -492,6 +494,8 @@
     ALOGV("onTimeUpdate track %d, rtpTime = 0x%08x, ntpTime = %#016llx",
          trackIndex, rtpTime, (long long)ntpTime);
 
+    // convert ntpTime in Q32 seconds to microseconds. Note: this will not lose precision
+    // because ntpTimeUs is at most 52 bits (double holds 53 bits)
     int64_t ntpTimeUs = (int64_t)(ntpTime * 1E6 / (1ll << 32));
 
     TrackInfo *track = &mTracks.editItemAt(trackIndex);
@@ -659,10 +663,10 @@
 
         const char *mime = value.string();
         const char *delimiter = strchr(mime, '/');
-        info->mCodecName = (delimiter + 1);
+        info->mCodecName = delimiter ? (delimiter + 1) : "<none>";
 
         ALOGV("rtp-param-mime-type: mMimeType (%s) => mCodecName (%s)",
-            info->mMimeType.string(), info->mCodecName.string());
+                info->mMimeType.string(), info->mCodecName.string());
     } else if (key == "video-param-decoder-profile") {
         info->mCodecProfile = atoi(value);
     } else if (key == "video-param-decoder-level") {
diff --git a/media/libmediaplayerservice/nuplayer/RTPSource.h b/media/libmediaplayerservice/nuplayer/RTPSource.h
index 7666087..5085a7e 100644
--- a/media/libmediaplayerservice/nuplayer/RTPSource.h
+++ b/media/libmediaplayerservice/nuplayer/RTPSource.h
@@ -46,8 +46,6 @@
 struct ALooper;
 struct AnotherPacketSource;
 
-const int32_t videoMinBitrate = 192000;
-
 struct NuPlayer::RTPSource : public NuPlayer::Source {
     RTPSource(
             const sp<AMessage> &notify,
@@ -96,6 +94,9 @@
         kWhatSetBufferingSettings = 'sBuS',
     };
 
+    const int64_t kBufferingPollIntervalUs = 1000000ll;
+    const int32_t kMinVideoBitrate = 192000; /* bps */
+
     enum State {
         DISCONNECTED,
         CONNECTING,
diff --git a/media/libstagefright/include/media/stagefright/MediaCodecSource.h b/media/libstagefright/include/media/stagefright/MediaCodecSource.h
index 2d8ca52..0f7b535 100644
--- a/media/libstagefright/include/media/stagefright/MediaCodecSource.h
+++ b/media/libstagefright/include/media/stagefright/MediaCodecSource.h
@@ -64,7 +64,7 @@
 
     // MediaBufferObserver
     virtual void signalBufferReturned(MediaBufferBase *buffer);
-    virtual status_t setEncodingBitrate(int32_t bitRate);
+    virtual status_t setEncodingBitrate(int32_t bitRate /* bps */);
 
     // for AHandlerReflector
     void onMessageReceived(const sp<AMessage> &msg);
diff --git a/media/libstagefright/include/media/stagefright/MetaDataBase.h b/media/libstagefright/include/media/stagefright/MetaDataBase.h
index 6c505ac..fd6cc70 100644
--- a/media/libstagefright/include/media/stagefright/MetaDataBase.h
+++ b/media/libstagefright/include/media/stagefright/MetaDataBase.h
@@ -247,8 +247,8 @@
 
     // Treat empty track as malformed for MediaRecorder.
     kKeyEmptyTrackMalFormed = 'nemt', // bool (int32_t)
-    kKeySps              = 'sSps', // int32_t, indicates that a buffer is sps.
-    kKeyPps              = 'sPps', // int32_t, indicates that a buffer is pps.
+    kKeySps              = 'sSps', // int32_t, indicates that a buffer is sps (value ignored).
+    kKeyPps              = 'sPps', // int32_t, indicates that a buffer is pps (value ignored).
     kKeySelfID           = 'sfid', // int32_t, source ID to identify itself on RTP protocol.
     kKeyPayloadType      = 'pTyp', // int32_t, SDP negotiated payload type.
     kKeyRtpExtMap        = 'extm', // int32_t, rtp extension ID for cvo on RTP protocol.
diff --git a/media/libstagefright/rtsp/AAVCAssembler.cpp b/media/libstagefright/rtsp/AAVCAssembler.cpp
index 1d78438..0164040 100644
--- a/media/libstagefright/rtsp/AAVCAssembler.cpp
+++ b/media/libstagefright/rtsp/AAVCAssembler.cpp
@@ -65,7 +65,7 @@
     bool isTooLate200 = expiredTimeInJb < (playedTimeRtp - jitterTime);
     bool isTooLate300 = expiredTimeInJb < (playedTimeRtp - (jitterTime * 3 / 2));
 
-    if (mShowQueueCnt < 20) {
+    if (mShowQueue && mShowQueueCnt < 20) {
         showCurrentQueue(queue);
         ALOGD("start=%lld, now=%lld, played=%lld", (long long)startTime,
                 (long long)nowTime, (long long)playedTime);
@@ -130,6 +130,8 @@
         }
     }
 
+    buffer = *queue->begin();
+
     if (!mNextExpectedSeqNoValid) {
         mNextExpectedSeqNoValid = true;
         mNextExpectedSeqNo = (uint32_t)buffer->int32Data();
diff --git a/media/libstagefright/rtsp/AHEVCAssembler.cpp b/media/libstagefright/rtsp/AHEVCAssembler.cpp
index c316471..93869fb 100644
--- a/media/libstagefright/rtsp/AHEVCAssembler.cpp
+++ b/media/libstagefright/rtsp/AHEVCAssembler.cpp
@@ -97,6 +97,8 @@
         }
     }
 
+    buffer = *queue->begin();
+
     if (!mNextExpectedSeqNoValid) {
         mNextExpectedSeqNoValid = true;
         mNextExpectedSeqNo = (uint32_t)buffer->int32Data();
@@ -225,7 +227,7 @@
 
     CHECK((indicator & H265_NALU_MASK) == H265_NALU_FU);
 
-    if (size < 2) {
+    if (size < 3) {
         ALOGV("Ignoring malformed FU buffer (size = %zu)", size);
 
         queue->erase(queue->begin());
diff --git a/media/libstagefright/rtsp/ARTPAssembler.cpp b/media/libstagefright/rtsp/ARTPAssembler.cpp
index a63c89f..52aa3a0 100644
--- a/media/libstagefright/rtsp/ARTPAssembler.cpp
+++ b/media/libstagefright/rtsp/ARTPAssembler.cpp
@@ -22,12 +22,16 @@
 #include <media/stagefright/foundation/ALooper.h>
 #include <media/stagefright/foundation/AMessage.h>
 
+#include <android-base/properties.h>
+
 #include <stdint.h>
 
 namespace android {
 
 ARTPAssembler::ARTPAssembler()
-    : mShowQueueCnt(0), mFirstFailureTimeUs(-1) {
+    : mShowQueueCnt(0),
+      mFirstFailureTimeUs(-1) {
+    mShowQueue = android::base::GetBoolProperty("debug.stagefright.rtp", false);
 }
 
 void ARTPAssembler::onPacketReceived(const sp<ARTPSource> &source) {
diff --git a/media/libstagefright/rtsp/ARTPAssembler.h b/media/libstagefright/rtsp/ARTPAssembler.h
index b8072c7..191f08e 100644
--- a/media/libstagefright/rtsp/ARTPAssembler.h
+++ b/media/libstagefright/rtsp/ARTPAssembler.h
@@ -56,9 +56,11 @@
     static sp<ABuffer> MakeCompoundFromPackets(
             const List<sp<ABuffer> > &frames);
 
-    int32_t mShowQueueCnt;
     void showCurrentQueue(List<sp<ABuffer> > *queue);
 
+    bool mShowQueue;
+    int32_t mShowQueueCnt;
+
 private:
     int64_t mFirstFailureTimeUs;
 
diff --git a/media/libstagefright/rtsp/ARTPConnection.cpp b/media/libstagefright/rtsp/ARTPConnection.cpp
index 2665bd2..9e4635d 100644
--- a/media/libstagefright/rtsp/ARTPConnection.cpp
+++ b/media/libstagefright/rtsp/ARTPConnection.cpp
@@ -615,7 +615,7 @@
         return -1;
     }
 
-    if ((data[1] & 0x7f) == 20) {
+    if ((data[1] & 0x7f) == 20 /* decimal */) {
         // Unassigned payload type
         return -1;
     }
@@ -708,6 +708,7 @@
     }
 
     const uint8_t *extPayload = extHeader + 4;
+    extLen -= 4;
     size_t offset = 0; //start from first payload of rtp extension.
     // one-byte header parser
     while (isOnebyteHeader && offset < extLen) {
@@ -716,12 +717,13 @@
         offset++;
 
         // padding case
-        if(extmapId == 0)
+        if (extmapId == 0)
             continue;
 
-        uint8_t data[length];
-        for (uint8_t j = 0; j < length; j++)
+        uint8_t data[16]; // maximum length value
+        for (uint8_t j = 0; offset + j <= extLen && j < length; j++) {
             data[j] = extPayload[offset + j];
+        }
 
         offset += length;
 
@@ -872,14 +874,14 @@
 
 status_t ARTPConnection::parseTSFB(
         StreamInfo *s, const uint8_t *data, size_t size) {
-    uint8_t msgType = data[0] & 0x1f;
-    uint32_t id = u32at(&data[4]);
-
     if (size < 12) {
         // broken packet
         return -1;
     }
 
+    uint8_t msgType = data[0] & 0x1f;
+    uint32_t id = u32at(&data[4]);
+
     const uint8_t *ptr = &data[12];
     size -= 12;
 
@@ -954,21 +956,25 @@
 
 status_t ARTPConnection::parsePSFB(
         StreamInfo *s, const uint8_t *data, size_t size) {
-    uint8_t msgType = data[0] & 0x1f;
-    uint32_t id = u32at(&data[4]);
-
     if (size < 12) {
         // broken packet
         return -1;
     }
 
+    uint8_t msgType = data[0] & 0x1f;
+    uint32_t id = u32at(&data[4]);
+
+    const uint8_t *ptr = &data[12];
     size -= 12;
 
     using namespace std;
     switch(msgType) {
         case 1:     // Picture Loss Indication (PLI)
         {
-            CHECK(size == 0);   // PLI does not need parameters
+            if (size > 0) {
+                // PLI does not need parameters
+                break;
+            };
             sp<AMessage> notify = s->mNotifyMsg->dup();
             notify->setInt32("rtcp-event", 1);
             notify->setInt32("payload-type", 206);
@@ -980,7 +986,10 @@
         }
         case 4:     // Full Intra Request (FIR)
         {
-            uint32_t requestedId = u32at(&data[12]);
+            if (size < 4) {
+                break;
+            }
+            uint32_t requestedId = u32at(&ptr[0]);
             if (requestedId == (uint32_t)mSelfID) {
                 sp<AMessage> notify = s->mNotifyMsg->dup();
                 notify->setInt32("rtcp-event", 1);
@@ -1126,4 +1135,3 @@
 }
 
 }  // namespace android
-
diff --git a/media/libstagefright/rtsp/ARTPSource.cpp b/media/libstagefright/rtsp/ARTPSource.cpp
index 01fa898..bbe9d94 100644
--- a/media/libstagefright/rtsp/ARTPSource.cpp
+++ b/media/libstagefright/rtsp/ARTPSource.cpp
@@ -322,8 +322,8 @@
 }
 
 void ARTPSource::addTMMBR(const sp<ABuffer> &buffer) {
-    if (buffer->size() + 32 > buffer->capacity()) {
-        ALOGW("RTCP buffer too small to accomodate RR.");
+    if (buffer->size() + 20 > buffer->capacity()) {
+        ALOGW("RTCP buffer too small to accommodate RR.");
         return;
     }
 
@@ -415,5 +415,3 @@
     mNumBuffersReceived -= cnt;
 }
 }  // namespace android
-
-
diff --git a/media/libstagefright/rtsp/ARTPWriter.cpp b/media/libstagefright/rtsp/ARTPWriter.cpp
index 309e5cf..70d34de 100644
--- a/media/libstagefright/rtsp/ARTPWriter.cpp
+++ b/media/libstagefright/rtsp/ARTPWriter.cpp
@@ -147,6 +147,16 @@
 }
 
 ARTPWriter::~ARTPWriter() {
+    if (mSPSBuf != NULL) {
+        mSPSBuf->release();
+        mSPSBuf = NULL;
+    }
+
+    if (mPPSBuf != NULL) {
+        mPPSBuf->release();
+        mPPSBuf = NULL;
+    }
+
 #if LOG_TO_FILES
     close(mRTCPFd);
     mRTCPFd = -1;
@@ -163,16 +173,6 @@
 
     close(mFd);
     mFd = -1;
-
-    if(mSPSBuf != NULL) {
-        mSPSBuf->release();
-        mSPSBuf = NULL;
-    }
-
-    if(mPPSBuf != NULL) {
-        mPPSBuf->release();
-        mPPSBuf = NULL;
-    }
 }
 
 status_t ARTPWriter::addSource(const sp<MediaSource> &source) {
@@ -212,27 +212,27 @@
     CHECK(mSource->getFormat()->findCString(kKeyMIMEType, &mime));
 
     int32_t selfID = 0;
-    if(params->findInt32(kKeySelfID, &selfID))
+    if (params->findInt32(kKeySelfID, &selfID))
         mSourceID = selfID;
 
     int32_t payloadType = 0;
-    if(params->findInt32(kKeyPayloadType, &payloadType))
+    if (params->findInt32(kKeyPayloadType, &payloadType))
         mPayloadType = payloadType;
 
     int32_t rtpExtMap = 0;
-    if(params->findInt32(kKeyRtpExtMap, &rtpExtMap))
+    if (params->findInt32(kKeyRtpExtMap, &rtpExtMap))
         mRTPCVOExtMap = rtpExtMap;
 
     int32_t rtpCVODegrees = 0;
-    if(params->findInt32(kKeyRtpCvoDegrees, &rtpCVODegrees))
+    if (params->findInt32(kKeyRtpCvoDegrees, &rtpCVODegrees))
         mRTPCVODegrees = rtpCVODegrees;
 
     int32_t dscp = 0;
-    if(params->findInt32(kKeyRtpDscp, &dscp))
+    if (params->findInt32(kKeyRtpDscp, &dscp))
         updateSocketDscp(dscp);
 
     int64_t sockNetwork = 0;
-    if(params->findInt64(kKeySocketNetwork, &sockNetwork))
+    if (params->findInt64(kKeySocketNetwork, &sockNetwork))
         updateSocketNetwork(sockNetwork);
 
     mMode = INVALID;
@@ -295,8 +295,8 @@
 
     ptr = (const uint8_t *)buffer->data() + buffer->range_offset();
 
-    if ((*ptr & H264_NALU_MASK) == H264_NALU_SPS) {
-        for (uint32_t i = 0; i < buffer->range_length(); i++) {
+    if (buffer->range_length() > 0 && (*ptr & H264_NALU_MASK) == H264_NALU_SPS) {
+        for (uint32_t i = 1; i + 4 <= buffer->range_length(); i++) {
 
             if (!memcmp(ptr + i, "\x00\x00\x00\x01", 4)) {
                 // Now, we found one more NAL unit in the media buffer.
@@ -316,28 +316,28 @@
     if (mediaBuffer == NULL || mediaBuffer->range_length() < 4)
         return;
 
-    if((*spsBuffer) != NULL) {
+    if ((*spsBuffer) != NULL) {
         (*spsBuffer)->release();
         (*spsBuffer) = NULL;
     }
 
-    if((*ppsBuffer) != NULL) {
+    if ((*ppsBuffer) != NULL) {
         (*ppsBuffer)->release();
         (*ppsBuffer) = NULL;
     }
 
     // we got sps/pps but startcode of sps is striped.
     (*spsBuffer) = MediaBufferBase::Create(spsSize);
-    int32_t ppsSize = mediaBuffer->range_length() - spsSize - 4/*startcode*/;
-    (*ppsBuffer) = MediaBufferBase::Create(ppsSize);
     memcpy((*spsBuffer)->data(),
             (const uint8_t *)mediaBuffer->data() + mediaBuffer->range_offset(),
             spsSize);
 
+    int32_t ppsSize = mediaBuffer->range_length() - spsSize - 4 /*startcode*/;
     if (ppsSize > 0) {
+        (*ppsBuffer) = MediaBufferBase::Create(ppsSize);
         ALOGV("PPS found. size=%d", (int)ppsSize);
-        mediaBuffer->set_range(mediaBuffer->range_offset() + spsSize + 4/*startcode*/,
-                mediaBuffer->range_length() - spsSize - 4/*startcode*/);
+        mediaBuffer->set_range(mediaBuffer->range_offset() + spsSize + 4 /*startcode*/,
+                mediaBuffer->range_length() - spsSize - 4 /*startcode*/);
         memcpy((*ppsBuffer)->data(),
                 (const uint8_t *)mediaBuffer->data() + mediaBuffer->range_offset(),
                 ppsSize);
@@ -612,7 +612,7 @@
 
 void ARTPWriter::addTMMBN(const sp<ABuffer> &buffer) {
     if (buffer->size() + 20 > buffer->capacity()) {
-        ALOGW("RTCP buffer too small to accomodate SR.");
+        ALOGW("RTCP buffer too small to accommodate SR.");
         return;
     }
     if (mOpponentID == 0)
@@ -810,7 +810,8 @@
     const uint8_t *mediaData =
         (const uint8_t *)mediaBuf->data() + mediaBuf->range_offset();
 
-    if ((mediaData[0] & H264_NALU_MASK) != H264_NALU_IFRAME)
+    if (mediaBuf->range_length() == 0
+            || (mediaData[0] & H264_NALU_MASK) != H264_NALU_IFRAME)
         return;
 
     if (mSPSBuf != NULL) {
@@ -1194,10 +1195,10 @@
                 (int *)&mRtpLayer3Dscp, sizeof(mRtpLayer3Dscp)) < 0) {
         ALOGE("failed to set dscp on rtpsock. err=%s", strerror(errno));
     } else {
-        ALOGD("success to set dscp on rtpsock. opt=%d", mRtpLayer3Dscp);
+        ALOGD("successfully set dscp on rtpsock. opt=%d", mRtpLayer3Dscp);
         setsockopt(mRTCPSocket, IPPROTO_IP, IP_TOS,
                 (int *)&mRtpLayer3Dscp, sizeof(mRtpLayer3Dscp));
-        ALOGD("success to set dscp on rtcpsock. opt=%d", mRtpLayer3Dscp);
+        ALOGD("successfully set dscp on rtcpsock. opt=%d", mRtpLayer3Dscp);
     }
 }
 
@@ -1408,4 +1409,3 @@
 }
 
 }  // namespace android
-
diff --git a/media/libstagefright/rtsp/ASessionDescription.cpp b/media/libstagefright/rtsp/ASessionDescription.cpp
index 63f39f4..4502f62 100644
--- a/media/libstagefright/rtsp/ASessionDescription.cpp
+++ b/media/libstagefright/rtsp/ASessionDescription.cpp
@@ -392,10 +392,11 @@
     sdp.append("\r\n");
 
     sdp.append("c= IN IP");
-    if(isIPv4)
-     sdp.append("4 ");
-    else
-     sdp.append("6 ");
+    if (isIPv4) {
+        sdp.append("4 ");
+    } else {
+        sdp.append("6 ");
+    }
     sdp.append(ip);
     sdp.append("\r\n");
 
@@ -411,7 +412,7 @@
     sdp.append(isAudio ? "8000" : "90000");
     sdp.append("\r\n");
 
-    if(fmtp != NULL) {
+    if (fmtp != NULL) {
         sdp.append("a=fmtp:");
         sdp.append(payloadType);
         sdp.append(" ");
@@ -419,7 +420,7 @@
         sdp.append("\r\n");
     }
 
-    if(width > 0 && height > 0) {
+    if (width > 0 && height > 0) {
         sdp.append("a=framesize:");
         sdp.append(payloadType);
         sdp.append(" ");
@@ -429,7 +430,7 @@
         sdp.append("\r\n");
     }
 
-    if(cvoExtMap > 0) {
+    if (cvoExtMap > 0) {
         sdp.append("a=extmap:");
         sdp.append(cvoExtMap);
         sdp.append(" ");