Android(2.3+)源码分析MediaPlayer之RTSP

在前面的博客中有简单介绍MediaPlayer,最近又开始研究这块东西,在此把阅读代码的理解记录下来方便以后快速查阅。

播放普通文件传入的url是一个本地的绝对路径,但是流媒体的话传入的就是一个网络地址如以"http://“开头的流媒体和以"rtsp://"开头的流媒体协议。

下面从源码中的Awesomeplayer.cpp finishSetDataSource_l函数入手(也相当与mediaplayer调用了prepare后,开始做一些准备工作,如音频流和视频流都要准备好)

[cpp]  view plain  copy
  1. status_t AwesomePlayer::finishSetDataSource_l() {  
  2.     sp<DataSource> dataSource;  
  3.   
  4.     bool isM3u8 = false;  
  5.     String8 surfix;  
  6.     surfix.setTo(mUri.string() + (mUri.size() - 5));  
  7.     isM3u8 = !strncasecmp(".m3u8", surfix, 5);  
  8.     if (!strncasecmp("http://", mUri.string(), 7) && (!isM3u8)) {  
  9.         mConnectingDataSource = new NuHTTPDataSource;  
  10.   
  11.         mLock.unlock();  
  12.         status_t err = mConnectingDataSource->connect(mUri, &mUriHeaders);  
  13. ...  
  14. else if (!strncasecmp("rtsp://", mUri.string(), 7)) {  
  15.         if (mLooper == NULL) {  
  16.             mLooper = new ALooper;  
  17.             mLooper->setName("rtsp");  
  18.             mLooper->start();  
  19.         }  
  20.         mRTSPController = new ARTSPController(mLooper);  
  21.         status_t err = mRTSPController->connect(mUri.string());  
  22.   
  23.         LOGI("ARTSPController::connect returned %d", err);  
  24.   
  25.         if (err != OK) {  
  26.             mRTSPController.clear();  
  27.             return err;  
  28.         }  
  29.   
  30.         sp<MediaExtractor> extractor = mRTSPController.get();  
  31.         return setDataSource_l(extractor);  
  32.     }   

首先awesomeplayer会对url进行解析,由此来区分创建不同的媒体提取器(MediaExtractor),相当于将mp4文件打开并且解析了它里面有哪些流信息(音,视频,字幕等)而RTSP则当然是要和用户所输入的网络地址建立连接准备好随时接受媒体数据。


重点是在ARTSPController的connect函数

[cpp]  view plain  copy
  1. status_t ARTSPController::connect(const char *url) {  
  2.     Mutex::Autolock autoLock(mLock);  
  3.   
  4.     if (mState != DISCONNECTED) {  
  5.         return ERROR_ALREADY_CONNECTED;  
  6.     }  
  7.   
  8.     sp<AMessage> msg = new AMessage(kWhatConnectDone, mReflector->id());  
  9.   
  10.     mHandler = new MyHandler(url, mLooper);  
  11.   
  12.     mState = CONNECTING;  
  13.   
  14.     mHandler->connect(msg);  
  15.   
  16.     while (mState == CONNECTING) {  
  17.         mCondition.wait(mLock);  
  18.     }  
  19.   
  20.     if (mState != CONNECTED) {  
  21.         mHandler.clear();  
  22.     }  
  23.   
  24.     return mConnectionResult;  
  25. }  

可以看到函数里面有一个

 while (mState == CONNECTING) {
        mCondition.wait(mLock);
    }

在等待状态变成CONNECTED此函数才会返回。

我们需要清除状态是如何变化的:

首先创建了一个sp<AMessage> msg = new AMessage(kWhatConnectDone, mReflector->id()); 对象类型是kWhatConnectDone,id是mReflector->id()

这个id十分关键,它确定了此消息的最终接收对象,我们看mReflector的由来,

[cpp]  view plain  copy
  1. ARTSPController::ARTSPController(const sp<ALooper> &looper)  
  2.     : mState(DISCONNECTED),  
  3.       mLooper(looper),  
  4.       mSeekDoneCb(NULL),  
  5.       mSeekDoneCookie(NULL),  
  6.       mLastSeekCompletedTimeUs(-1) {  
  7.     mReflector = new AHandlerReflector<ARTSPController>(this);  
  8.     looper->registerHandler(mReflector);  
  9. }  
它是在ARTSPController的构造函数中创建的,并且被注册到了looper里面,这个looper不知道的可以自己看下源码,简单解释下就是一个循环的消息队列,它里面保存了一个handler列表(每个handler有唯一的id,也就是上面我们提到的id),当消息被触发时就会通过id来找到对应的handler。

紧接着我们再看MyHandler的connect函数

[cpp]  view plain  copy
  1. void connect(const sp<AMessage> &doneMsg) {  
  2.         mDoneMsg = doneMsg;  
  3.   
  4.         mLooper->registerHandler(this);  
  5.         mLooper->registerHandler(mConn);  
  6.         (1 ? mNetLooper : mLooper)->registerHandler(mRTPConn);  
  7.   
  8.         sp<AMessage> notify = new AMessage('biny', id());  
  9.         mConn->observeBinaryData(notify);  
  10.   
  11.         sp<AMessage> reply = new AMessage('conn', id());  
  12.         mConn->connect(mOriginalSessionURL.c_str(), reply);  
  13.     }  
它传入的参数实际就是上面的sp<AMessage> msg = new AMessage(kWhatConnectDone, mReflector->id());

也就是什么时候完成连接的动作就会触发此message

两个重要的地方

sp<AMessage> notify = new AMessage('biny', id());
        mConn->observeBinaryData(notify);

[cpp]  view plain  copy
  1. void ARTSPConnection::observeBinaryData(const sp<AMessage> &reply) {  
  2.     sp<AMessage> msg = new AMessage(kWhatObserveBinaryData, id());  
  3.     msg->setMessage("reply", reply);  
  4.     msg->post();  
  5. }  
此消息通过id可以看出是发送给ARTSPConnection自己的,注意setMessage参数reply,字面上理解是回复,也就是说执行完此消息后需要回复的调用reply,而这里的reply就是

AMessage('biny', id());

[cpp]  view plain  copy
  1. void ARTSPConnection::onMessageReceived(const sp<AMessage> &msg) {  
  2.     switch (msg->what()) {  
  3.         case kWhatConnect:  
  4.             onConnect(msg);  
  5.             break;  
  6.   
  7.         case kWhatDisconnect:  
  8.             onDisconnect(msg);  
  9.             break;  
  10.   
  11.         case kWhatCompleteConnection:  
  12.             onCompleteConnection(msg);  
  13.             break;  
  14.   
  15.         case kWhatSendRequest:  
  16.             onSendRequest(msg);  
  17.             break;  
  18.   
  19.         case kWhatReceiveResponse:  
  20.             onReceiveResponse();  
  21.             break;  
  22.   
  23.         case kWhatObserveBinaryData:  
  24.         {  
  25.             CHECK(msg->findMessage("reply", &mObserveBinaryMessage));  
  26.             break;  
  27.         }  
  28.   
  29.         default:  
  30.             TRESPASS();  
  31.             break;  
  32.     }  
  33. }  

在 ARTSPConnection::onMessageReceived可以找到kWhatObserveBinaryData,然后将reply的值保存在了mObserveBinaryMessage中,此消息在后面的receiveRTSPReponse会调用到。我们先看下一个重点的地方
sp<AMessage> reply = new AMessage('conn', id());
        mConn->connect(mOriginalSessionURL.c_str(), reply);

这个才是连接的关键
首先reply绑定的id是MyHandler的id,也就是说最终会回到MyHandler的onMessageReceived  case 'conn':中来。

[cpp]  view plain  copy
  1. void ARTSPConnection::connect(const char *url, const sp<AMessage> &reply) {  
  2.     sp<AMessage> msg = new AMessage(kWhatConnect, id());  
  3.     msg->setString("url", url);  
  4.     msg->setMessage("reply", reply);  
  5.     msg->post();  
  6. }  

此处发出了一个kWhatConnect的消息给自己,在onMessageReceived中收到后调用

[cpp]  view plain  copy
  1. void ARTSPConnection::onConnect(const sp<AMessage> &msg) {  
  2.     ++mConnectionID;  
  3.   
  4.     if (mState != DISCONNECTED) {  
  5.         close(mSocket);  
  6.         mSocket = -1;  
  7.   
  8.         flushPendingRequests();  
  9.     }  
  10.   
  11.     mState = CONNECTING;  
  12.   
  13.     AString url;  
  14.     CHECK(msg->findString("url", &url));  
  15.   
  16.     sp<AMessage> reply;  
  17.     CHECK(msg->findMessage("reply", &reply));  
  18.   
  19.     AString host, path;  
  20.     unsigned port;  
  21.     if (!ParseURL(url.c_str(), &host, &port, &path, &mUser, &mPass)  
  22.             || (mUser.size() > 0 && mPass.size() == 0)) {  
  23.         // If we have a user name but no password we have to give up  
  24.         // right here, since we currently have no way of asking the user  
  25.         // for this information.  
  26.   
  27.         LOGE("Malformed rtsp url %s", url.c_str());  
  28.   
  29.         reply->setInt32("result", ERROR_MALFORMED);  
  30.         reply->post();  
  31.   
  32.         mState = DISCONNECTED;  
  33.         return;  
  34.     }  
  35.   
  36.     if (mUser.size() > 0) {  
  37.         LOGV("user = '%s', pass = '%s'", mUser.c_str(), mPass.c_str());  
  38.     }  
  39.   
  40.     struct hostent *ent = gethostbyname(host.c_str());  
  41.     if (ent == NULL) {  
  42.         LOGE("Unknown host %s", host.c_str());  
  43.   
  44.         reply->setInt32("result", -ENOENT);  
  45.         reply->post();  
  46.   
  47.         mState = DISCONNECTED;  
  48.         return;  
  49.     }  
  50.   
  51.     mSocket = socket(AF_INET, SOCK_STREAM, 0);  
  52.   
  53.     MakeSocketBlocking(mSocket, false);  
  54.   
  55.     struct sockaddr_in remote;  
  56.     memset(remote.sin_zero, 0, sizeof(remote.sin_zero));  
  57.     remote.sin_family = AF_INET;  
  58.     remote.sin_addr.s_addr = *(in_addr_t *)ent->h_addr;  
  59.     remote.sin_port = htons(port);  
  60.   
  61.     int err = ::connect(  
  62.             mSocket, (const struct sockaddr *)&remote, sizeof(remote));  
  63.   
  64.     reply->setInt32("server-ip", ntohl(remote.sin_addr.s_addr));  
  65.   
  66.     if (err < 0) {  
  67.         if (errno == EINPROGRESS) {  
  68.             sp<AMessage> msg = new AMessage(kWhatCompleteConnection, id());  
  69.             msg->setMessage("reply", reply);  
  70.             msg->setInt32("connection-id", mConnectionID);  
  71.             msg->post();  
  72.             return;  
  73.         }  
  74.   
  75.         reply->setInt32("result", -errno);  
  76.         mState = DISCONNECTED;  
  77.   
  78.         close(mSocket);  
  79.         mSocket = -1;  
  80.     } else {  
  81.         reply->setInt32("result", OK);  
  82.         mState = CONNECTED;  
  83.         mNextCSeq = 1;  
  84.   
  85.         postReceiveReponseEvent();  
  86.     }  
  87.   
  88.     reply->post();  
  89. }  


在connect中会解析url得到ip port等,然后通过socket连接到此ip

 int err = ::connect(
            mSocket, (const struct sockaddr *)&remote, sizeof(remote));

连接成功以后ARTSPConnection中的状态变为 mState = CONNECTED;

并且调用postReceiveReponseEvent函数:

[cpp]  view plain  copy
  1. void ARTSPConnection::postReceiveReponseEvent() {  
  2.     if (mReceiveResponseEventPending) {  
  3.         return;  
  4.     }  
  5.   
  6.     sp<AMessage> msg = new AMessage(kWhatReceiveResponse, id());  
  7.     msg->post();  
  8.   
  9.     mReceiveResponseEventPending = true;  
  10. }  
发送kWhatReceiveResponse消息给自己

最终在

[cpp]  view plain  copy
  1. void ARTSPConnection::onReceiveResponse() {  
  2.     mReceiveResponseEventPending = false;  
  3.   
  4.     if (mState != CONNECTED) {  
  5.         return;  
  6.     }  
  7.   
  8.     struct timeval tv;  
  9.     tv.tv_sec = 0;  
  10.     tv.tv_usec = kSelectTimeoutUs;  
  11.   
  12.     fd_set rs;  
  13.     FD_ZERO(&rs);  
  14.     FD_SET(mSocket, &rs);  
  15.   
  16.     int res = select(mSocket + 1, &rs, NULL, NULL, &tv);  
  17.     CHECK_GE(res, 0);  
  18.   
  19.     if (res == 1) {  
  20.         MakeSocketBlocking(mSocket, true);  
  21.   
  22.         bool success = receiveRTSPReponse();  
  23.   
  24.         MakeSocketBlocking(mSocket, false);  
  25.   
  26.         if (!success) {  
  27.             // Something horrible, irreparable has happened.  
  28.             flushPendingRequests();  
  29.             return;  
  30.         }  
  31.     }  
  32.   
  33.     postReceiveReponseEvent();  
  34. }  

中通过select监听本地的mSocket,看socket中是否有可读数据,也就是看remote是否有发送数据过来。

当有数据过来时res == 1

就通过receiveRTSPReponse函数来接受发送过来的数据

大家可能有印象,这个函数在之前有遇到请查找kWhatObserveBinaryData就知道了。

postReceiveReponseEvent之后会调用 reply->post();注意这个就是前面MyHandler中发送出来的AMessage('conn', id());

此时代码将回到MyHandler的onMessageReceived case 'conn':中来。

这里有 sp<AMessage> reply = new AMessage('desc', id());
                    mConn->sendRequest(request.c_str(), reply);

原理同之前的一样也是发送请求并且有reply

有接触过SIP的知道有SDP这个协议,这个是在会话建立以前双方用来协商媒体信息的。

不重复解释,直接看case 'desc': 这里通过与对方的协商,回复的response code ,大家都知道如果http的话回复200则代表访问成功,这里也是一样的
我们看200里面的操作:

[cpp]  view plain  copy
  1. if (response->mStatusCode != 200) {  
  2.     result = UNKNOWN_ERROR;  
  3. else {  
  4.     mSessionDesc = new ASessionDescription;  
  5.   
  6.     mSessionDesc->setTo(  
  7.             response->mContent->data(),  
  8.             response->mContent->size());  
  9.   
  10.     if (!mSessionDesc->isValid()) {  
  11.         LOGE("Failed to parse session description.");  
  12.         result = ERROR_MALFORMED;  
  13.     } else {  
  14.         ssize_t i = response->mHeaders.indexOfKey("content-base");  
  15.         if (i >= 0) {  
  16.             mBaseURL = response->mHeaders.valueAt(i);  
  17.         } else {  
  18.             i = response->mHeaders.indexOfKey("content-location");  
  19.             if (i >= 0) {  
  20.                 mBaseURL = response->mHeaders.valueAt(i);  
  21.             } else {  
  22.                 mBaseURL = mSessionURL;  
  23.             }  
  24.         }  
  25.   
  26.         if (!mBaseURL.startsWith("rtsp://")) {  
  27.             // Some misbehaving servers specify a relative  
  28.             // URL in one of the locations above, combine  
  29.             // it with the absolute session URL to get  
  30.             // something usable...  
  31.   
  32.             LOGW("Server specified a non-absolute base URL"  
  33.                  ", combining it with the session URL to "  
  34.                  "get something usable...");  
  35.   
  36.             AString tmp;  
  37.             CHECK(MakeURL(  
  38.                         mSessionURL.c_str(),  
  39.                         mBaseURL.c_str(),  
  40.                         &tmp));  
  41.   
  42.             mBaseURL = tmp;  
  43.         }  
  44.   
  45.         CHECK_GT(mSessionDesc->countTracks(), 1u);  
  46.         setupTrack(1);  
  47.     }  
  48. }  

首先一点是将协商后的sdp信息存储起来放到ASessionDescription里面。

然后再看setupTrack(1),这里还不确定有几个track,只是先设置track 1:

[cpp]  view plain  copy
  1. void setupTrack(size_t index) {  
  2.        sp<APacketSource> source =  
  3.            new APacketSource(mSessionDesc, index);  
  4.   
  5.        if (source->initCheck() != OK) {  
  6.            LOGW("Unsupported format. Ignoring track #%d.", index);  
  7.   
  8.            sp<AMessage> reply = new AMessage('setu', id());  
  9.            reply->setSize("index", index);  
  10.            reply->setInt32("result", ERROR_UNSUPPORTED);  
  11.            reply->post();  
  12.            return;  
  13.        }  
  14.   
  15.        AString url;  
  16.        CHECK(mSessionDesc->findAttribute(index, "a=control", &url));  
  17.   
  18.        AString trackURL;  
  19.        CHECK(MakeURL(mBaseURL.c_str(), url.c_str(), &trackURL));  
  20.   
  21.        mTracks.push(TrackInfo());  
  22.        TrackInfo *info = &mTracks.editItemAt(mTracks.size() - 1);  
  23.        info->mURL = trackURL;  
  24.        info->mPacketSource = source;  
  25.        info->mUsingInterleavedTCP = false;  
  26.        info->mFirstSeqNumInSegment = 0;  
  27.        info->mNewSegment = true;  
  28.   
  29.        LOGV("track #%d URL=%s", mTracks.size(), trackURL.c_str());  
  30.   
  31.        AString request = "SETUP ";  
  32.        request.append(trackURL);  
  33.        request.append(" RTSP/1.0\r\n");  
  34.   
  35.        if (mTryTCPInterleaving) {  
  36.            size_t interleaveIndex = 2 * (mTracks.size() - 1);  
  37.            info->mUsingInterleavedTCP = true;  
  38.            info->mRTPSocket = interleaveIndex;  
  39.            info->mRTCPSocket = interleaveIndex + 1;  
  40.   
  41.            request.append("Transport: RTP/AVP/TCP;interleaved=");  
  42.            request.append(interleaveIndex);  
  43.            request.append("-");  
  44.            request.append(interleaveIndex + 1);  
  45.        } else {  
  46.            unsigned rtpPort;  
  47.            ARTPConnection::MakePortPair(  
  48.                    &info->mRTPSocket, &info->mRTCPSocket, &rtpPort);  
  49.   
  50.            request.append("Transport: RTP/AVP/UDP;unicast;client_port=");  
  51.            request.append(rtpPort);  
  52.            request.append("-");  
  53.            request.append(rtpPort + 1);  
  54.        }  
  55.   
  56.        request.append("\r\n");  
  57.   
  58.        if (index > 1) {  
  59.            request.append("Session: ");  
  60.            request.append(mSessionID);  
  61.            request.append("\r\n");  
  62.        }  
  63.   
  64.        request.append("\r\n");  
  65.   
  66.        sp<AMessage> reply = new AMessage('setu', id());  
  67.        reply->setSize("index", index);  
  68.        reply->setSize("track-index", mTracks.size() - 1);  
  69.        mConn->sendRequest(request.c_str(), reply);  
  70.    }  

根据mSessionDesc创建了一个APacketSource对象,setupTrack唯一的参数是index,此参数标记了是第几个track,这里的track实际相当与一个媒体源,音频流/视频流

当track 1设置完成后又发送setu给自己然后设置第二个track ......

设置完的track会mRTPConn->addStream(
                                track->mRTPSocket, track->mRTCPSocket,
                                mSessionDesc, index,
                                notify, track->mUsingInterleavedTCP);

将track的流信息加入到ARTPConnection中,ARTPConnection相当于是对外的接口

注意这里传进去的sp<AMessage> notify = new AMessage('accu', id());
                        notify->setSize("track-index", trackIndex);

这个也是一个回复的消息。

[cpp]  view plain  copy
  1. void ARTPConnection::addStream(  
  2.         int rtpSocket, int rtcpSocket,  
  3.         const sp<ASessionDescription> &sessionDesc,  
  4.         size_t index,  
  5.         const sp<AMessage> ¬ify,  
  6.         bool injected) {  
  7.     sp<AMessage> msg = new AMessage(kWhatAddStream, id());  
  8.     msg->setInt32("rtp-socket", rtpSocket);  
  9.     msg->setInt32("rtcp-socket", rtcpSocket);  
  10.     msg->setObject("session-desc", sessionDesc);  
  11.     msg->setSize("index", index);  
  12.     msg->setMessage("notify", notify);  
  13.     msg->setInt32("injected", injected);  
  14.     msg->post();  
  15. }  

再看ARTPConnection的case:kWhatAddStream 

[cpp]  view plain  copy
  1. void ARTPConnection::onAddStream(const sp<AMessage> &msg) {  
  2.     mStreams.push_back(StreamInfo());  
  3.     StreamInfo *info = &*--mStreams.end();  
  4.   
  5.     int32_t s;  
  6.     CHECK(msg->findInt32("rtp-socket", &s));  
  7.     info->mRTPSocket = s;  
  8.     CHECK(msg->findInt32("rtcp-socket", &s));  
  9.     info->mRTCPSocket = s;  
  10.   
  11.     int32_t injected;  
  12.     CHECK(msg->findInt32("injected", &injected));  
  13.   
  14.     info->mIsInjected = injected;  
  15.   
  16.     sp<RefBase> obj;  
  17.     CHECK(msg->findObject("session-desc", &obj));  
  18.     info->mSessionDesc = static_cast<ASessionDescription *>(obj.get());  
  19.   
  20.     CHECK(msg->findSize("index", &info->mIndex));  
  21.     CHECK(msg->findMessage("notify", &info->mNotifyMsg));  
  22.   
  23.     info->mNumRTCPPacketsReceived = 0;  
  24.     info->mNumRTPPacketsReceived = 0;  
  25.     memset(&info->mRemoteRTCPAddr, 0, sizeof(info->mRemoteRTCPAddr));  
  26.   
  27.     if (!injected) {  
  28.         postPollEvent();  
  29.     }  
  30. }  

此处在List<StreamInfo> mStreams;Stream列表中加入了一条stream并且进行了初始化操作(rtp socket   rtcp socket)

以及对info->mNotifyMsg的赋值(记住这个是AMessage('accu', id());)

在最后 调用了postPollEvent函数

这个函数实际是等待对方发来多媒体数据的:

[cpp]  view plain  copy
  1. void ARTPConnection::onPollStreams() {  
  2.     mPollEventPending = false;  
  3.   
  4.     if (mStreams.empty()) {  
  5.         return;  
  6.     }  
  7.   
  8.     struct timeval tv;  
  9.     tv.tv_sec = 0;  
  10.     tv.tv_usec = kSelectTimeoutUs;  
  11.   
  12.     fd_set rs;  
  13.     FD_ZERO(&rs);  
  14.   
  15.     int maxSocket = -1;  
  16.     for (List<StreamInfo>::iterator it = mStreams.begin();  
  17.          it != mStreams.end(); ++it) {  
  18.         if ((*it).mIsInjected) {  
  19.             continue;  
  20.         }  
  21.   
  22.         FD_SET(it->mRTPSocket, &rs);  
  23.         FD_SET(it->mRTCPSocket, &rs);  
  24.   
  25.         if (it->mRTPSocket > maxSocket) {  
  26.             maxSocket = it->mRTPSocket;  
  27.         }  
  28.         if (it->mRTCPSocket > maxSocket) {  
  29.             maxSocket = it->mRTCPSocket;  
  30.         }  
  31.     }  
  32.   
  33.     if (maxSocket == -1) {  
  34.         return;  
  35.     }  
  36.   
  37.     int res = select(maxSocket + 1, &rs, NULL, NULL, &tv);  
  38.     CHECK_GE(res, 0);  
  39.   
  40.     if (res > 0) {  
  41.         for (List<StreamInfo>::iterator it = mStreams.begin();  
  42.              it != mStreams.end(); ++it) {  
  43.             if ((*it).mIsInjected) {  
  44.                 continue;  
  45.             }  
  46.   
  47.             if (FD_ISSET(it->mRTPSocket, &rs)) {  
  48.                 receive(&*it, true);  
  49.             }  
  50.             if (FD_ISSET(it->mRTCPSocket, &rs)) {  
  51.                 receive(&*it, false);  
  52.             }  
  53.         }  
  54.     }  
  55.   
  56.     postPollEvent();  
  57.   
  58.     int64_t nowUs = ALooper::GetNowUs();  
  59.     if (mLastReceiverReportTimeUs <= 0  
  60.             || mLastReceiverReportTimeUs + 5000000ll <= nowUs) {  
  61.         sp<ABuffer> buffer = new ABuffer(kMaxUDPSize);  
  62.         for (List<StreamInfo>::iterator it = mStreams.begin();  
  63.              it != mStreams.end(); ++it) {  
  64.             StreamInfo *s = &*it;  
  65.   
  66.             if (s->mIsInjected) {  
  67.                 continue;  
  68.             }  
  69.   
  70.             if (s->mNumRTCPPacketsReceived == 0) {  
  71.                 // We have never received any RTCP packets on this stream,  
  72.                 // we don't even know where to send a report.  
  73.                 continue;  
  74.             }  
  75.   
  76.             buffer->setRange(0, 0);  
  77.   
  78.             for (size_t i = 0; i < s->mSources.size(); ++i) {  
  79.                 sp<ARTPSource> source = s->mSources.valueAt(i);  
  80.   
  81.                 source->addReceiverReport(buffer);  
  82.   
  83.                 if (mFlags & kRegularlyRequestFIR) {  
  84.                     source->addFIR(buffer);  
  85.                 }  
  86.             }  
  87.   
  88.             if (buffer->size() > 0) {  
  89.                 LOGV("Sending RR...");  
  90.   
  91.                 ssize_t n = sendto(  
  92.                         s->mRTCPSocket, buffer->data(), buffer->size(), 0,  
  93.                         (const struct sockaddr *)&s->mRemoteRTCPAddr,  
  94.                         sizeof(s->mRemoteRTCPAddr));  
  95.                 CHECK_EQ(n, (ssize_t)buffer->size());  
  96.   
  97.                 mLastReceiverReportTimeUs = nowUs;  
  98.             }  
  99.         }  
  100.     }  
  101. }  

此函数十分关键,在int res = select(maxSocket + 1, &rs, NULL, NULL, &tv);中监听了rtp socket和rtcp socket ,看这两个套接字中是否有数据可读,当发现有数据可读时就调用:

[cpp]  view plain  copy
  1. status_t ARTPConnection::receive(StreamInfo *s, bool receiveRTP) {  
  2.     LOGV("receiving %s", receiveRTP ? "RTP" : "RTCP");  
  3.   
  4.     CHECK(!s->mIsInjected);  
  5.   
  6.     sp<ABuffer> buffer = new ABuffer(65536);  
  7.   
  8.     socklen_t remoteAddrLen =  
  9.         (!receiveRTP && s->mNumRTCPPacketsReceived == 0)  
  10.             ? sizeof(s->mRemoteRTCPAddr) : 0;  
  11.   
  12.     ssize_t nbytes = recvfrom(  
  13.             receiveRTP ? s->mRTPSocket : s->mRTCPSocket,  
  14.             buffer->data(),  
  15.             buffer->capacity(),  
  16.             0,  
  17.             remoteAddrLen > 0 ? (struct sockaddr *)&s->mRemoteRTCPAddr : NULL,  
  18.             remoteAddrLen > 0 ? &remoteAddrLen : NULL);  
  19.   
  20.     if (nbytes < 0) {  
  21.         return -1;  
  22.     }  
  23.   
  24.     buffer->setRange(0, nbytes);  
  25.   
  26.     // LOGI("received %d bytes.", buffer->size());  
  27.   
  28.     status_t err;  
  29.     if (receiveRTP) {  
  30.         err = parseRTP(s, buffer);  
  31.     } else {  
  32.         err = parseRTCP(s, buffer);  
  33.     }  
  34.   
  35.     return err;  
  36. }  

来进行接受接受到RTP数据后通过parseRTP来解析,在解析的第一句话就是

if (s->mNumRTPPacketsReceived++ == 0) {
        sp<AMessage> notify = s->mNotifyMsg->dup();
        notify->setInt32("first-rtp", true);
        notify->post();
    }

这就是收到的第一个rtp包,然后就触发了前面的AMessage('accu', id());)消息,进而回到

MyHandler的 case 'accu':

而在这里面有这么一句话十分关键:

if (mFirstAccessUnit) {
                    mDoneMsg->setInt32("result", OK);
                    mDoneMsg->post();
                    mDoneMsg = NULL;


                    mFirstAccessUnit = false;
                    mFirstAccessUnitNTP = ntpTime;
                }

大家或许早就忘记这个mDoneMsg是什么东西,你可以前面的ARTSPController::connect函数中找到答案,没错!它就是kWhatConnectDone

[cpp]  view plain  copy
  1. case kWhatConnectDone:  
  2.        {  
  3.            Mutex::Autolock autoLock(mLock);  
  4.   
  5.            CHECK(msg->findInt32("result", &mConnectionResult));  
  6.            mState = (mConnectionResult == OK) ? CONNECTED : DISCONNECTED;  
  7.   
  8.            mCondition.signal();  
  9.            break;  
  10.        }  

看到没有 mCondition.signal(); 发送唤醒消息,这时候 ARTSPController::connect 才能真正返回。

前面看似很简单的一个函数mRTSPController->connect(mUri.string());竟然经历了这么多才回来!!!!!!


总结一下:

1.ARTSPController主要控制流媒体的连接,断开和快进,但是真正做事的是它的成员变量MyHandler

2.MyHandler类里面的ARTSPConnection负责流媒体的收发操作。

3.ARTSPConnection首先解析URL,得到主机的地址和端口号,然后建立socket 连接到远端的主机,并且建立监听机制等待远端主机发送过来的数据

先通过sdp的形式和远端主机协商媒体类型,然后根据类型建立不同的StreamInfo包括音频和视频的(并且每一个StreamInfo都有一个rtp socket 和一个rtcp socket)

并且监听这些socket,当有第一个rtp数据传过来时,我们就认为socket连接建立并返回。


前面这些都是RTSP里面所完成的,RTSP也属于stagefright框架中的一部分,所以它的一些类都是继承的stagefright中的基本类

struct APacketSource : public MediaSource 

struct ARTSPController : public MediaExtractor 

ARTSPController 在调用finishSetDataSource_l后被设置为数据源。


[cpp]  view plain  copy
  1. status_t AwesomePlayer::setDataSource_l(const sp<MediaExtractor> &extractor) {  
  2.     // Attempt to approximate overall stream bitrate by summing all  
  3.     // tracks' individual bitrates, if not all of them advertise bitrate,  
  4.     // we have to fail.  
  5.   
  6.     int64_t totalBitRate = 0;  
  7.   
  8.     for (size_t i = 0; i < extractor->countTracks(); ++i) {  
  9.         sp<MetaData> meta = extractor->getTrackMetaData(i);  
  10.   
  11.         int32_t bitrate;  
  12.         if (!meta->findInt32(kKeyBitRate, &bitrate)) {  
  13.             totalBitRate = -1;  
  14.             break;  
  15.         }  
  16.   
  17.         totalBitRate += bitrate;  
  18.     }  
  19.   
  20.     mBitrate = totalBitRate;  
  21.   
  22.     LOGV("mBitrate = %lld bits/sec", mBitrate);  
  23.   
  24.     bool haveAudio = false;  
  25.     bool haveVideo = false;  
  26.     for (size_t i = 0; i < extractor->countTracks(); ++i) {  
  27.         sp<MetaData> meta = extractor->getTrackMetaData(i);  
  28.   
  29.         const char *mime;  
  30.         CHECK(meta->findCString(kKeyMIMEType, &mime));  
  31.   
  32.         if (!haveVideo && !strncasecmp(mime, "video/", 6)) {  
  33.             setVideoSource(extractor->getTrack(i));  
  34.             haveVideo = true;  
  35.         } else if (!haveAudio && !strncasecmp(mime, "audio/", 6)) {  
  36.             setAudioSource(extractor->getTrack(i));  
  37.             haveAudio = true;  
  38.   
  39.             if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) {  
  40.                 // Only do this for vorbis audio, none of the other audio  
  41.                 // formats even support this ringtone specific hack and  
  42.                 // retrieving the metadata on some extractors may turn out  
  43.                 // to be very expensive.  
  44.                 sp<MetaData> fileMeta = extractor->getMetaData();  
  45.                 int32_t loop;  
  46.                 if (fileMeta != NULL  
  47.                         && fileMeta->findInt32(kKeyAutoLoop, &loop) && loop != 0) {  
  48.                     mFlags |= AUTO_LOOPING;  
  49.                 }  
  50.             }  
  51.         }  
  52.   
  53.         if (haveAudio && haveVideo) {  
  54.             break;  
  55.         }  
  56.     }  
  57.   
  58.     if (!haveAudio && !haveVideo) {  
  59.         return UNKNOWN_ERROR;  
  60.     }  
  61.   
  62.     mExtractorFlags = extractor->flags();  
  63.   
  64.     return OK;  
  65. }  
并且将音频视频流都提取出来,然后

[cpp]  view plain  copy
  1. void AwesomePlayer::onPrepareAsyncEvent() {  
  2.     Mutex::Autolock autoLock(mLock);  
  3.   
  4.     if (mFlags & PREPARE_CANCELLED) {  
  5.         LOGI("prepare was cancelled before doing anything");  
  6.         abortPrepare(UNKNOWN_ERROR);  
  7.         return;  
  8.     }  
  9.   
  10.     if (mUri.size() > 0) {  
  11.         status_t err = finishSetDataSource_l();  
  12.   
  13.         if (err != OK) {  
  14.             abortPrepare(err);  
  15.             return;  
  16.         }  
  17.     }  
  18.   
  19.     if (mVideoTrack != NULL && mVideoSource == NULL) {  
  20.         status_t err = initVideoDecoder();  
  21.   
  22.         if (err != OK) {  
  23.             abortPrepare(err);  
  24.             return;  
  25.         }  
  26.     }  
  27.   
  28.     if (mAudioTrack != NULL && mAudioSource == NULL) {  
  29.         status_t err = initAudioDecoder();  
  30.   
  31.         if (err != OK) {  
  32.             abortPrepare(err);  
  33.             return;  
  34.         }  
  35.     }  
  36.   
  37.     if (mCachedSource != NULL || mRTSPController != NULL) {  
  38.         postBufferingEvent_l();  
  39.     } else {  
  40.         finishAsyncPrepare_l();  
  41.     }  
  42. }  

初始化音视频解码器,这样就完成了整个prepare的动作。

后面用户调用play实际就是开始接收数据,解码,然后播放渲染。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值