本文在linux环境下编译live555工程,并用cgdb调试工具对live555工程中的testProgs目录下的openRTSP的执行过程进行了跟踪分析,直到将从socket端读取视频数据并保存为对应的视频和音频数据为止。

进入testProgs目录,执行./openRTSP rtsp://xxxx/test.mp4

对于RTSP协议的处理部分,可设置断点在setupStreams函数中,并跟踪即可进行分析。

这里主要分析进入如下的while(1)循环中的代码

  1. void BasicTaskScheduler0::doEventLoop(char* watchVariable)
  2. {
  3. // Repeatedly loop, handling readble sockets and timed events:
  4. while (1)
  5. {
  6. if (watchVariable != NULL && *watchVariable != 0) break;
  7. SingleStep();
  8. }
  9. }

从这里可知,live555在客户端处理数据实际上是单线程的程序,不断执行SingleStep()函数中的代码。通过查看该函数代码里,下面一句代码为重点

  1. (*handler->handlerProc)(handler->clientData, resultConditionSet);

其中该条代码出现了两次,通过调试跟踪它的执行轨迹,第一次出现调用的函数是为了处理和RTSP服务器的通信协议的商定,而第二次出现调用的函数才是处理真正的视频和音频数据。对于RTSP通信协议的分析我们暂且不讨论,而直接进入第二次调用该函数的部分。

在我们的调试过程中在执行到上面的函数时就直接调用到livemedia目录下的如下函数

  1. void MultiFramedRTPSource::networkReadHandler(MultiFramedRTPSource* source, int /*mask*/)
  2. {
  3. source->networkReadHandler1();
  4. }

//下面这个函数实现的主要功能就是从socket端读取数据并存储数据

  1. void MultiFramedRTPSource::networkReadHandler1()
  2. {
  3. BufferedPacket* bPacket = fPacketReadInProgress;
  4. if (bPacket == NULL)
  5. {
  6. // Normal case: Get a free BufferedPacket descriptor to hold the new network packet:
  7. //分配一块新的存储空间来存储从socket端读取的数据
  8. bPacket = fReorderingBuffer->getFreePacket(this);
  9. }
  10. // Read the network packet, and perform sanity checks on the RTP header:
  11. Boolean readSuccess = False;
  12. do
  13. {
  14. Boolean packetReadWasIncomplete = fPacketReadInProgress != NULL;
  15. //fillInData()函数封装了从socket端获取数据的过程,到此函数执行完已经将数据保存到了bPacket对象中
  16. if (!bPacket->fillInData(fRTPInterface, packetReadWasIncomplete))
  17. {
  18. if (bPacket->bytesAvailable() == 0)
  19. {
  20. envir() << "MultiFramedRTPSource error: Hit limit when reading incoming packet over TCP. Increase \"MAX_PACKET_SIZE\"\n";
  21. }
  22. break;
  23. }
  24. if (packetReadWasIncomplete)
  25. {
  26. // We need additional read(s) before we can process the incoming packet:
  27. fPacketReadInProgress = bPacket;
  28. return;
  29. } else
  30. {
  31. fPacketReadInProgress = NULL;
  32. }
  33. //省略关于RTP包的处理
  34. ...
  35. ...
  36. ...
  37. //fReorderingBuffer为MultiFramedRTPSource类中的对象,该对象建立了一个存储Packet数据包对象的链表
  38. //下面的storePacket()函数即将上面获取的数据包存储在链表中
  39. if (!fReorderingBuffer->storePacket(bPacket)) break;
  40. readSuccess = True;
  41. } while (0);
  42. if (!readSuccess) fReorderingBuffer->freePacket(bPacket);
  43. doGetNextFrame1();
  44. // If we didn't get proper data this time, we'll get another chance
  45. }

//下面的这个函数则实现从上面函数中介绍的存储数据包链表的对象(即fReorderingBuffer)中取出数据包并调用相应函数使用它

//代码1.1

  1. void MultiFramedRTPSource::doGetNextFrame1()
  2. {
  3. while (fNeedDelivery)
  4. {
  5. // If we already have packet data available, then deliver it now.
  6. Boolean packetLossPrecededThis;
  7. //从fReorderingBuffer对象中取出一个数据包
  8. BufferedPacket* nextPacket
  9. = fReorderingBuffer->getNextCompletedPacket(packetLossPrecededThis);
  10. if (nextPacket == NULL) break;
  11. fNeedDelivery = False;
  12. if (nextPacket->useCount() == 0)
  13. {
  14. // Before using the packet, check whether it has a special header
  15. // that needs to be processed:
  16. unsigned specialHeaderSize;
  17. if (!processSpecialHeader(nextPacket, specialHeaderSize))
  18. {
  19. // Something's wrong with the header; reject the packet:
  20. fReorderingBuffer->releaseUsedPacket(nextPacket);
  21. fNeedDelivery = True;
  22. break;
  23. }
  24. nextPacket->skip(specialHeaderSize);
  25. }
  26. // Check whether we're part of a multi-packet frame, and whether
  27. // there was packet loss that would render this packet unusable:
  28. if (fCurrentPacketBeginsFrame)
  29. {
  30. if (packetLossPrecededThis || fPacketLossInFragmentedFrame)
  31. {
  32. // We didn't get all of the previous frame.
  33. // Forget any data that we used from it:
  34. fTo = fSavedTo; fMaxSize = fSavedMaxSize;
  35. fFrameSize = 0;
  36. }
  37. fPacketLossInFragmentedFrame = False;
  38. } else if (packetLossPrecededThis)
  39. {
  40. // We're in a multi-packet frame, with preceding packet loss
  41. fPacketLossInFragmentedFrame = True;
  42. }
  43. if (fPacketLossInFragmentedFrame)
  44. {
  45. // This packet is unusable; reject it:
  46. fReorderingBuffer->releaseUsedPacket(nextPacket);
  47. fNeedDelivery = True;
  48. break;
  49. }
  50. // The packet is usable. Deliver all or part of it to our caller:
  51. unsigned frameSize;
  52. //将上面取出的数据包拷贝到fTo指针所指向的地址
  53. nextPacket->use(fTo, fMaxSize, frameSize, fNumTruncatedBytes,
  54. fCurPacketRTPSeqNum, fCurPacketRTPTimestamp,
  55. fPresentationTime, fCurPacketHasBeenSynchronizedUsingRTCP,
  56. fCurPacketMarkerBit);
  57. fFrameSize += frameSize;
  58. if (!nextPacket->hasUsableData())
  59. {
  60. // We're completely done with this packet now
  61. fReorderingBuffer->releaseUsedPacket(nextPacket);
  62. }
  63. if (fCurrentPacketCompletesFrame) //如果完整的取出了一帧数据,则可调用需要该帧数据的函数去处理它
  64. {
  65. // We have all the data that the client wants.
  66. if (fNumTruncatedBytes > 0)
  67. {
  68. envir() << "MultiFramedRTPSource::doGetNextFrame1(): The total received frame size exceeds the client's buffer size ("
  69. << fSavedMaxSize << ").  "
  70. << fNumTruncatedBytes << " bytes of trailing data will be dropped!\n";
  71. }
  72. // Call our own 'after getting' function, so that the downstream object can consume the data:
  73. if (fReorderingBuffer->isEmpty())
  74. {
  75. // Common case optimization: There are no more queued incoming packets, so this code will not get
  76. // executed again without having first returned to the event loop.  Call our 'after getting' function
  77. // directly, because there's no risk of a long chain of recursion (and thus stack overflow):
  78. afterGetting(this);  //调用函数去处理取出的数据帧
  79. } else
  80. {
  81. // Special case: Call our 'after getting' function via the event loop.
  82. nextTask() = envir().taskScheduler().scheduleDelayedTask(0,
  83. (TaskFunc*)FramedSource::afterGetting, this);
  84. }
  85. }
  86. else
  87. {
  88. // This packet contained fragmented data, and does not complete
  89. // the data that the client wants.  Keep getting data:
  90. fTo += frameSize; fMaxSize -= frameSize;
  91. fNeedDelivery = True;
  92. }
  93. }
  94. }

//下面这个函数即开始调用执行需要该帧数据的函数

  1. void FramedSource::afterGetting(FramedSource* source)
  2. {
  3. source->fIsCurrentlyAwaitingData = False;
  4. // indicates that we can be read again
  5. // Note that this needs to be done here, in case the "fAfterFunc"
  6. // called below tries to read another frame (which it usually will)
  7. if (source->fAfterGettingFunc != NULL)
  1. {
  2. (*(source->fAfterGettingFunc))(source->fAfterGettingClientData,
  3. source->fFrameSize, source->fNumTruncatedBytes,
  4. source->fPresentationTime,
  5. source->fDurationInMicroseconds);
  6. }
  7. }

上面的fAfterGettingFunc为我们自己注册的函数,如果运行的是testProgs中的openRTSP实例,则该函数指向下列代码中通过调用getNextFrame()注册的afterGettingFrame()函数

  1. Boolean FileSink::continuePlaying()
  2. {
  3. if (fSource == NULL) return False;
  4. fSource->getNextFrame(fBuffer, fBufferSize,
  5. afterGettingFrame, this,
  6. onSourceClosure, this);
  7. return True;
  8. }

如果运行的是testProgs中的testRTSPClient中的实例,则该函数指向这里注册的afterGettingFrame()函数

  1. Boolean DummySink::continuePlaying()
  2. {
  3. if (fSource == NULL) return False; // sanity check (should not happen)
  4. // Request the next frame of data from our input source.  "afterGettingFrame()" will get called later, when it arrives:
  5. fSource->getNextFrame(fReceiveBuffer, DUMMY_SINK_RECEIVE_BUFFER_SIZE,
  6. afterGettingFrame, this,
  7. onSourceClosure, this);
  8. return True;
  9. }

从上面的代码中可以看到getNextFrame()函数的第一个参数为分别在各自类中定义的buffer,我们继续以openRTSP为运行程序来分析,fBuffer为FileSink类里定义的指针:unsigned char* fBuffer;

这里我们先绕一个弯,看看getNextFrame()函数里做了什么

  1. void FramedSource::getNextFrame(unsigned char* to, unsigned maxSize,
  2. afterGettingFunc* afterGettingFunc,
  3. void* afterGettingClientData,
  4. onCloseFunc* onCloseFunc,
  5. void* onCloseClientData)
  6. {
  7. // Make sure we're not already being read:
  8. if (fIsCurrentlyAwaitingData)
  9. {
  10. envir() << "FramedSource[" << this << "]::getNextFrame(): attempting to read more than once at the same time!\n";
  11. envir().internalError();
  12. }
  13. fTo = to;
  14. fMaxSize = maxSize;
  15. fNumTruncatedBytes = 0; // by default; could be changed by doGetNextFrame()
  16. fDurationInMicroseconds = 0; // by default; could be changed by doGetNextFrame()
  17. fAfterGettingFunc = afterGettingFunc;
  18. fAfterGettingClientData = afterGettingClientData;
  19. fOnCloseFunc = onCloseFunc;
  20. fOnCloseClientData = onCloseClientData;
  21. fIsCurrentlyAwaitingData = True;
  22. doGetNextFrame();
  23. }

从代码可以知道上面getNextFrame()中传入的第一个参数fBuffer指向了指针fTo,而我们在前面分析代码1.1中的void MultiFramedRTPSource::doGetNextFrame1()函数中有下面一段代码:

  1. //将上面取出的数据包拷贝到fTo指针所指向的地址
  2. nextPacket->use(fTo, fMaxSize, frameSize, fNumTruncatedBytes,
  3. fCurPacketRTPSeqNum, fCurPacketRTPTimestamp,
  4. fPresentationTime, fCurPacketHasBeenSynchronizedUsingRTCP,
  5. fCurPacketMarkerBit);

实际上现在应该明白了,从getNextFrame()函数中传入的第一个参数fBuffer最终存储的即是从数据包链表对象中取出的数据,并且在调用上面的use()函数后就可以使用了。
而在void MultiFramedRTPSource::doGetNextFrame1()函数中代码显示的最终调用我们注册的void FileSink::afterGettingFrame()正好是在use()函数调用之后的afterGetting(this)中调用。我们再看看afterGettingFrame()做了什么处理:

  1. void FileSink::afterGettingFrame(void* clientData, unsigned frameSize,
  2. unsigned numTruncatedBytes,
  3. struct timeval presentationTime,
  4. unsigned /*durationInMicroseconds*/)
  5. {
  6. FileSink* sink = (FileSink*)clientData;
  7. sink->afterGettingFrame(frameSize, numTruncatedBytes, presentationTime);
  8. }
  9. void FileSink::afterGettingFrame(unsigned frameSize,
  10. unsigned numTruncatedBytes,
  11. struct timeval presentationTime)
  12. {
  13. if (numTruncatedBytes > 0)
  14. {
  15. envir() << "FileSink::afterGettingFrame(): The input frame data was too large for our buffer size ("
  16. << fBufferSize << ").  "
  17. << numTruncatedBytes << " bytes of trailing data was dropped!  Correct this by increasing the \"bufferSize\" parameter in the \"createNew()\" call to at least "
  18. << fBufferSize + numTruncatedBytes << "\n";
  19. }
  20. addData(fBuffer, frameSize, presentationTime);
  21. if (fOutFid == NULL || fflush(fOutFid) == EOF)
  22. {
  23. // The output file has closed.  Handle this the same way as if the
  24. // input source had closed:
  25. onSourceClosure(this);
  26. stopPlaying();
  27. return;
  28. }
  29. if (fPerFrameFileNameBuffer != NULL)
  30. {
  31. if (fOutFid != NULL) { fclose(fOutFid); fOutFid = NULL; }
  32. }
  33. // Then try getting the next frame:
  34. continuePlaying();
  35. }

从上面代码可以看到调用了addData()函数将数据保存到文件中,然后继续continuePlaying()又去获取下一帧数据然后处理,直到遇到循环结束然后依次退出调用函数。最后看看addData()函数的实现即可知:

  1. void FileSink::addData(unsigned char const* data, unsigned dataSize,
  2. struct timeval presentationTime)
  3. {
  4. if (fPerFrameFileNameBuffer != NULL)
  5. {
  6. // Special case: Open a new file on-the-fly for this frame
  7. sprintf(fPerFrameFileNameBuffer, "%s-%lu.%06lu", fPerFrameFileNamePrefix,
  8. presentationTime.tv_sec, presentationTime.tv_usec);
  9. fOutFid = OpenOutputFile(envir(), fPerFrameFileNameBuffer);
  10. }
  11. // Write to our file:
  12. #ifdef TEST_LOSS
  13. static unsigned const framesPerPacket = 10;
  14. static unsigned const frameCount = 0;
  15. static Boolean const packetIsLost;
  16. if ((frameCount++)%framesPerPacket == 0)
  17. {
  18. packetIsLost = (our_random()%10 == 0); // simulate 10% packet loss #####
  19. }
  20. if (!packetIsLost)
  21. #endif
  22. if (fOutFid != NULL && data != NULL)
  23. {
  24. fwrite(data, 1, dataSize, fOutFid);
  25. }
  26. }

最后调用系统函数fwrite()实现写入文件功能。

总结:从上面的分析可知,如果要取得从RTSP服务器端接收并保存的数据帧,我们只需要定义一个类并实现如下格式两个的函数,并声明一个指针地址buffer用于指向数据帧,再在continuePlaying()函数中调用getNextFrame(buffer,...)即可。

  1. unsigned numTruncatedBytes,
  2. struct timeval presentationTime,
  3. unsigned durationInMicroseconds);
  4. typedef void (onCloseFunc)(void* clientData);

然后再在afterGettingFunc的函数中即可使用buffer。.

(转)live555从RTSP服务器读取数据到使用接收到的数据流程分析的更多相关文章

  1. live555从RTSP服务器读取数据到使用接收到的数据流程分析

    本文在linux环境下编译live555工程,并用cgdb调试工具对live555工程中的testProgs目录下的openRTSP的执行过程进行了跟踪分析,直到将从socket端读取视频数据并保存为 ...

  2. vue.js组件之间的通讯-----父亲向儿子传递数据,儿子接收父亲的数据

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. 【VS开发】【Live555-rtsp】RTSP服务器实例live555源代码分析

    原文地址:RTSP服务器实例live555源代码分析作者:mozheer 1. RTSP连接的建立过程 RTSPServer类用于构建一个RTSP服务器,该类同时在其内部定义了一个RTSPClient ...

  4. 从零开始写一个发送h264的rtsp服务器(上)

    转自:http://blog.csdn.net/jychen105/article/details/47006345 一.什么是RTSP 通常所说的rtsp协议其实包含三个协议: rtsp协议, rt ...

  5. 搭建USB摄像头转RTSP服务器的多种方法

    USB摄像头与网络摄像头相比,可选择范围广.种类多.成本低,但是实际使用时需要通过rtsp流来访问,起到直播的效果,因此在摄像头采集终端上构建rtsp流媒体服务器,将USB摄像头数据转化为rtsp,可 ...

  6. 服务器放在不同省份的IDC机房,数据如何同步?一个域名如何动态解析到不同IP的服务器

    服务器放在不同省份的IDC机房,数据如何同步?淘宝的做法是不同IDC机房之间拉光纤,异地容灾和性能无关,异地容灾是应对断电.地震这种不可抗拒因素的 同城分流,异地容灾 是什么意思?你比如说公司的业务涉 ...

  7. 一个I/O线程可以并发处理N个客户端连接和读写操作 I/O复用模型 基于Buf操作NIO可以读取任意位置的数据 Channel中读取数据到Buffer中或将数据 Buffer 中写入到 Channel 事件驱动消息通知观察者模式

    Tomcat那些事儿 https://mp.weixin.qq.com/s?__biz=MzI3MTEwODc5Ng==&mid=2650860016&idx=2&sn=549 ...

  8. node 创建静态web服务器(下)(处理异步获取数据的两种方式)

    接上一章. 上一章我们说创建的静态web服务器只能识别html,css,js文件,功能较为单一,且图片格式为text/html,这是不合理的. 本章,我们将解决该问题. 这里,我们先准备好一个json ...

  9. 基于LIVE555的RTSP QoS实现

    如何从OnDemandServerMediaSubsession类以及继承类对象中获取RTCP信息(句柄) OnDemandServerMediaSubsession.cpp void StreamS ...

随机推荐

  1. Jenkins 使用学习笔记

    3.1    Jenkins安装    2 3.1.1    Jenkins下载    2 3.1.2    Jenkins 安装    2 3.1.3    Jenkins 目录结构    3 3. ...

  2. AngularJS概述-3D

    最近工作需要用到,接触的比较多,在此系统学习一下. angular.js 是新一代web MVC开发框架,对应 模型,视图,控制器.,相比 jquery 模式,这种新玩意竟然不需要开发者直接去操作do ...

  3. Android Spans介绍(转)

    在做一个 TODO 类的软件,使用开源软件 MaterialCalendarView 的时候,发现了需要往日历中添加待办事宜的标记,用到了 MaterialCalendarView 中的 DotSpa ...

  4. OSGi中的ServletContext

    在OSGi中,不能的bundle分属不同的装载器(Class Loader), 在J2EE 应用中,不同BUNDLE 中的JSP 所相应的ServletContext对象不同,这与通常情况下的应用是不 ...

  5. cocos2d-x 父节点和子节点执行不同动作

    Test6::Test6() { CCSprite* sp1 = CCSprite::create(s_pPathSister1); CCSprite* sp11 = CCSprite::create ...

  6. jenkins结合脚本实现代码自动化部署及一键回滚至上一版本

    持续集成之⑤:jenkins结合脚本实现代码自动化部署及一键回滚至上一版本 一:本文通过jenkins调用shell脚本的的方式完成从Git服务器获取代码.打包.部署到web服务器.将web服务器从负 ...

  7. ny788 又见Alice and Bob

    又见Alice and Bob 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述 集训生活如此乏味,于是Alice和Bob发明了一个新游戏.规则如下:首先,他们得到一个 ...

  8. yii2 关系...

    link($name) 会使用..get$name...即有hasmany和hasone... // update lazily loaded related objects if (!$relati ...

  9. Solr 数字字符不能搜索的一个问题

    问题一: 测试人员告诉我数字不能被搜索.于是开始找原因: <fields> ***<field name="productName" type="tex ...

  10. springmvc集成Freemarke配置的几点

    项目结构图 废话不多说, 集成步骤: 1.web.xml  spring-mvc配置 <?xml version="1.0" encoding="UTF-8&quo ...