RTSPClient.hh 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. /**********
  2. This library is free software; you can redistribute it and/or modify it under
  3. the terms of the GNU Lesser General Public License as published by the
  4. Free Software Foundation; either version 3 of the License, or (at your
  5. option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
  6. This library is distributed in the hope that it will be useful, but WITHOUT
  7. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  8. FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
  9. more details.
  10. You should have received a copy of the GNU Lesser General Public License
  11. along with this library; if not, write to the Free Software Foundation, Inc.,
  12. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  13. **********/
  14. // "liveMedia"
  15. // Copyright (c) 1996-2019 Live Networks, Inc. All rights reserved.
  16. // A generic RTSP client - for a single "rtsp://" URL
  17. // C++ header
  18. #ifndef _RTSP_CLIENT_HH
  19. #define _RTSP_CLIENT_HH
  20. #ifndef _MEDIA_SESSION_HH
  21. #include "MediaSession.hh"
  22. #endif
  23. #ifndef _NET_ADDRESS_HH
  24. #include "NetAddress.hh"
  25. #endif
  26. #ifndef _DIGEST_AUTHENTICATION_HH
  27. #include "DigestAuthentication.hh"
  28. #endif
  29. #ifndef OMIT_REGISTER_HANDLING
  30. #ifndef _RTSP_SERVER_HH
  31. #include "RTSPServer.hh" // For the optional "HandlerForREGISTERCommand" mini-server
  32. #endif
  33. #endif
  34. class RTSPClient: public Medium {
  35. public:
  36. static RTSPClient* createNew(UsageEnvironment& env, char const* rtspURL,
  37. int verbosityLevel = 0,
  38. char const* applicationName = NULL,
  39. portNumBits tunnelOverHTTPPortNum = 0,
  40. int socketNumToServer = -1);
  41. // If "tunnelOverHTTPPortNum" is non-zero, we tunnel RTSP (and RTP)
  42. // over a HTTP connection with the given port number, using the technique
  43. // described in Apple's document <http://developer.apple.com/documentation/QuickTime/QTSS/Concepts/chapter_2_section_14.html>
  44. // If "socketNumToServer" is >= 0, then it is the socket number of an already-existing TCP connection to the server.
  45. // (In this case, "rtspURL" must point to the socket's endpoint, so that it can be accessed via the socket.)
  46. typedef void (responseHandler)(RTSPClient* rtspClient,
  47. int resultCode, char* resultString);
  48. // A function that is called in response to a RTSP command. The parameters are as follows:
  49. // "rtspClient": The "RTSPClient" object on which the original command was issued.
  50. // "resultCode": If zero, then the command completed successfully. If non-zero, then the command did not complete
  51. // successfully, and "resultCode" indicates the error, as follows:
  52. // A positive "resultCode" is a RTSP error code (for example, 404 means "not found")
  53. // A negative "resultCode" indicates a socket/network error; 0-"resultCode" is the standard "errno" code.
  54. // "resultString": A ('\0'-terminated) string returned along with the response, or else NULL.
  55. // In particular:
  56. // "resultString" for a successful "DESCRIBE" command will be the media session's SDP description.
  57. // "resultString" for a successful "OPTIONS" command will be a list of allowed commands.
  58. // Note that this string can be present (i.e., not NULL) even if "resultCode" is non-zero - i.e., an error message.
  59. // Also, "resultString" can be NULL, even if "resultCode" is zero (e.g., if the RTSP command succeeded, but without
  60. // including an appropriate result header).
  61. // Note also that this string is dynamically allocated, and must be freed by the handler (or the caller)
  62. // - using "delete[]".
  63. unsigned sendDescribeCommand(responseHandler* responseHandler, Authenticator* authenticator = NULL);
  64. // Issues a RTSP "DESCRIBE" command, then returns the "CSeq" sequence number that was used in the command.
  65. // The (programmer-supplied) "responseHandler" function is called later to handle the response
  66. // (or is called immediately - with an error code - if the command cannot be sent).
  67. // "authenticator" (optional) is used for access control. If you have username and password strings, you can use this by
  68. // passing an actual parameter that you created by creating an "Authenticator(username, password) object".
  69. // (Note that if you supply a non-NULL "authenticator" parameter, you need do this only for the first command you send.)
  70. unsigned sendOptionsCommand(responseHandler* responseHandler, Authenticator* authenticator = NULL);
  71. // Issues a RTSP "OPTIONS" command, then returns the "CSeq" sequence number that was used in the command.
  72. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  73. unsigned sendAnnounceCommand(char const* sdpDescription, responseHandler* responseHandler, Authenticator* authenticator = NULL);
  74. // Issues a RTSP "ANNOUNCE" command (with "sdpDescription" as parameter),
  75. // then returns the "CSeq" sequence number that was used in the command.
  76. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  77. unsigned sendSetupCommand(MediaSubsession& subsession, responseHandler* responseHandler,
  78. Boolean streamOutgoing = False,
  79. Boolean streamUsingTCP = False,
  80. Boolean forceMulticastOnUnspecified = False,
  81. Authenticator* authenticator = NULL);
  82. // Issues a RTSP "SETUP" command, then returns the "CSeq" sequence number that was used in the command.
  83. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  84. unsigned sendPlayCommand(MediaSession& session, responseHandler* responseHandler,
  85. double start = 0.0f, double end = -1.0f, float scale = 1.0f,
  86. Authenticator* authenticator = NULL);
  87. // Issues an aggregate RTSP "PLAY" command on "session", then returns the "CSeq" sequence number that was used in the command.
  88. // (Note: start=-1 means 'resume'; end=-1 means 'play to end')
  89. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  90. unsigned sendPlayCommand(MediaSubsession& subsession, responseHandler* responseHandler,
  91. double start = 0.0f, double end = -1.0f, float scale = 1.0f,
  92. Authenticator* authenticator = NULL);
  93. // Issues a RTSP "PLAY" command on "subsession", then returns the "CSeq" sequence number that was used in the command.
  94. // (Note: start=-1 means 'resume'; end=-1 means 'play to end')
  95. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  96. // Alternative forms of "sendPlayCommand()", used to send "PLAY" commands that include an 'absolute' time range:
  97. // (The "absStartTime" string (and "absEndTime" string, if present) *must* be of the form
  98. // "YYYYMMDDTHHMMSSZ" or "YYYYMMDDTHHMMSS.<frac>Z")
  99. unsigned sendPlayCommand(MediaSession& session, responseHandler* responseHandler,
  100. char const* absStartTime, char const* absEndTime = NULL, float scale = 1.0f,
  101. Authenticator* authenticator = NULL);
  102. unsigned sendPlayCommand(MediaSubsession& subsession, responseHandler* responseHandler,
  103. char const* absStartTime, char const* absEndTime = NULL, float scale = 1.0f,
  104. Authenticator* authenticator = NULL);
  105. unsigned sendPauseCommand(MediaSession& session, responseHandler* responseHandler, Authenticator* authenticator = NULL);
  106. // Issues an aggregate RTSP "PAUSE" command on "session", then returns the "CSeq" sequence number that was used in the command.
  107. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  108. unsigned sendPauseCommand(MediaSubsession& subsession, responseHandler* responseHandler, Authenticator* authenticator = NULL);
  109. // Issues a RTSP "PAUSE" command on "subsession", then returns the "CSeq" sequence number that was used in the command.
  110. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  111. unsigned sendRecordCommand(MediaSession& session, responseHandler* responseHandler, Authenticator* authenticator = NULL);
  112. // Issues an aggregate RTSP "RECORD" command on "session", then returns the "CSeq" sequence number that was used in the command.
  113. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  114. unsigned sendRecordCommand(MediaSubsession& subsession, responseHandler* responseHandler, Authenticator* authenticator = NULL);
  115. // Issues a RTSP "RECORD" command on "subsession", then returns the "CSeq" sequence number that was used in the command.
  116. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  117. unsigned sendTeardownCommand(MediaSession& session, responseHandler* responseHandler, Authenticator* authenticator = NULL);
  118. // Issues an aggregate RTSP "TEARDOWN" command on "session", then returns the "CSeq" sequence number that was used in the command.
  119. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  120. unsigned sendTeardownCommand(MediaSubsession& subsession, responseHandler* responseHandler, Authenticator* authenticator = NULL);
  121. // Issues a RTSP "TEARDOWN" command on "subsession", then returns the "CSeq" sequence number that was used in the command.
  122. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  123. unsigned sendSetParameterCommand(MediaSession& session, responseHandler* responseHandler,
  124. char const* parameterName, char const* parameterValue,
  125. Authenticator* authenticator = NULL);
  126. // Issues an aggregate RTSP "SET_PARAMETER" command on "session", then returns the "CSeq" sequence number that was used in the command.
  127. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  128. unsigned sendGetParameterCommand(MediaSession& session, responseHandler* responseHandler, char const* parameterName,
  129. Authenticator* authenticator = NULL);
  130. // Issues an aggregate RTSP "GET_PARAMETER" command on "session", then returns the "CSeq" sequence number that was used in the command.
  131. // (The "responseHandler" and "authenticator" parameters are as described for "sendDescribeCommand".)
  132. void sendDummyUDPPackets(MediaSession& session, unsigned numDummyPackets = 2);
  133. void sendDummyUDPPackets(MediaSubsession& subsession, unsigned numDummyPackets = 2);
  134. // Sends short 'dummy' (i.e., non-RTP or RTCP) UDP packets towards the server, to increase
  135. // the likelihood of RTP/RTCP packets from the server reaching us if we're behind a NAT.
  136. // (If we requested RTP-over-TCP streaming, then these functions have no effect.)
  137. // Our implementation automatically does this just prior to sending each "PLAY" command;
  138. // You should not call these functions yourself unless you know what you're doing.
  139. void setSpeed(MediaSession& session, float speed = 1.0f);
  140. // Set (recorded) media download speed to given value to support faster download using 'Speed:'
  141. // option on 'PLAY' command.
  142. Boolean changeResponseHandler(unsigned cseq, responseHandler* newResponseHandler);
  143. // Changes the response handler for the previously-performed command (whose operation returned "cseq").
  144. // (To turn off any response handling for the command, use a "newResponseHandler" value of NULL. This might be done as part
  145. // of an implementation of a 'timeout handler' on the command, for example.)
  146. // This function returns True iff "cseq" was for a valid previously-performed command (whose response is still unhandled).
  147. int socketNum() const { return fInputSocketNum; }
  148. static Boolean lookupByName(UsageEnvironment& env,
  149. char const* sourceName,
  150. RTSPClient*& resultClient);
  151. static Boolean parseRTSPURL(UsageEnvironment& env, char const* url,
  152. char*& username, char*& password, NetAddress& address, portNumBits& portNum, char const** urlSuffix = NULL);
  153. // Parses "url" as "rtsp://[<username>[:<password>]@]<server-address-or-name>[:<port>][/<stream-name>]"
  154. // (Note that the returned "username" and "password" are either NULL, or heap-allocated strings that the caller must later delete[].)
  155. void setUserAgentString(char const* userAgentName);
  156. // sets an alternative string to be used in RTSP "User-Agent:" headers
  157. void disallowBasicAuthentication() { fAllowBasicAuthentication = False; }
  158. // call this if you don't want the server to request 'Basic' authentication
  159. // (which would cause the client to send usernames and passwords over the net).
  160. unsigned sessionTimeoutParameter() const { return fSessionTimeoutParameter; }
  161. char const* url() const { return fBaseURL; }
  162. static unsigned responseBufferSize;
  163. public: // Some compilers complain if this is "private:"
  164. // The state of a request-in-progress:
  165. class RequestRecord {
  166. public:
  167. RequestRecord(unsigned cseq, char const* commandName, responseHandler* handler,
  168. MediaSession* session = NULL, MediaSubsession* subsession = NULL, u_int32_t booleanFlags = 0,
  169. double start = 0.0f, double end = -1.0f, float scale = 1.0f, char const* contentStr = NULL);
  170. RequestRecord(unsigned cseq, responseHandler* handler,
  171. char const* absStartTime, char const* absEndTime = NULL, float scale = 1.0f,
  172. MediaSession* session = NULL, MediaSubsession* subsession = NULL);
  173. // alternative constructor for creating "PLAY" requests that include 'absolute' time values
  174. virtual ~RequestRecord();
  175. RequestRecord*& next() { return fNext; }
  176. unsigned& cseq() { return fCSeq; }
  177. char const* commandName() const { return fCommandName; }
  178. MediaSession* session() const { return fSession; }
  179. MediaSubsession* subsession() const { return fSubsession; }
  180. u_int32_t booleanFlags() const { return fBooleanFlags; }
  181. double start() const { return fStart; }
  182. double end() const { return fEnd; }
  183. char const* absStartTime() const { return fAbsStartTime; }
  184. char const* absEndTime() const { return fAbsEndTime; }
  185. float scale() const { return fScale; }
  186. char* contentStr() const { return fContentStr; }
  187. responseHandler*& handler() { return fHandler; }
  188. private:
  189. RequestRecord* fNext;
  190. unsigned fCSeq;
  191. char const* fCommandName;
  192. MediaSession* fSession;
  193. MediaSubsession* fSubsession;
  194. u_int32_t fBooleanFlags;
  195. double fStart, fEnd;
  196. char *fAbsStartTime, *fAbsEndTime; // used for optional 'absolute' (i.e., "time=") range specifications
  197. float fScale;
  198. char* fContentStr;
  199. responseHandler* fHandler;
  200. };
  201. protected:
  202. RTSPClient(UsageEnvironment& env, char const* rtspURL,
  203. int verbosityLevel, char const* applicationName, portNumBits tunnelOverHTTPPortNum, int socketNumToServer);
  204. // called only by createNew();
  205. virtual ~RTSPClient();
  206. void reset();
  207. void setBaseURL(char const* url);
  208. int grabSocket(); // allows a subclass to reuse our input socket, so that it won't get closed when we're deleted
  209. virtual unsigned sendRequest(RequestRecord* request);
  210. virtual Boolean setRequestFields(RequestRecord* request,
  211. char*& cmdURL, Boolean& cmdURLWasAllocated,
  212. char const*& protocolStr,
  213. char*& extraHeaders, Boolean& extraHeadersWereAllocated);
  214. // used to implement "sendRequest()"; subclasses may reimplement this (e.g., when implementing a new command name)
  215. virtual int connectToServer(int socketNum, portNumBits remotePortNum); // used to implement "openConnection()"; result values: -1: failure; 0: pending; 1: success
  216. private: // redefined virtual functions
  217. virtual Boolean isRTSPClient() const;
  218. private:
  219. class RequestQueue {
  220. public:
  221. RequestQueue();
  222. RequestQueue(RequestQueue& origQueue); // moves the queue contents to the new queue
  223. virtual ~RequestQueue();
  224. void enqueue(RequestRecord* request); // "request" must not be NULL
  225. RequestRecord* dequeue();
  226. void putAtHead(RequestRecord* request); // "request" must not be NULL
  227. RequestRecord* findByCSeq(unsigned cseq);
  228. Boolean isEmpty() const { return fHead == NULL; }
  229. void reset();
  230. private:
  231. RequestRecord* fHead;
  232. RequestRecord* fTail;
  233. };
  234. void resetTCPSockets();
  235. void resetResponseBuffer();
  236. int openConnection(); // result values: -1: failure; 0: pending; 1: success
  237. char* createAuthenticatorString(char const* cmd, char const* url);
  238. char* createBlocksizeString(Boolean streamUsingTCP);
  239. void handleRequestError(RequestRecord* request);
  240. Boolean parseResponseCode(char const* line, unsigned& responseCode, char const*& responseString);
  241. void handleIncomingRequest();
  242. static Boolean checkForHeader(char const* line, char const* headerName, unsigned headerNameLength, char const*& headerParams);
  243. Boolean parseTransportParams(char const* paramsStr,
  244. char*& serverAddressStr, portNumBits& serverPortNum,
  245. unsigned char& rtpChannelId, unsigned char& rtcpChannelId);
  246. Boolean parseScaleParam(char const* paramStr, float& scale);
  247. Boolean parseSpeedParam(char const* paramStr, float& speed);
  248. Boolean parseRTPInfoParams(char const*& paramStr, u_int16_t& seqNum, u_int32_t& timestamp);
  249. Boolean handleSETUPResponse(MediaSubsession& subsession, char const* sessionParamsStr, char const* transportParamsStr,
  250. Boolean streamUsingTCP);
  251. Boolean handlePLAYResponse(MediaSession* session, MediaSubsession* subsession,
  252. char const* scaleParamsStr, const char* speedParamsStr,
  253. char const* rangeParamsStr, char const* rtpInfoParamsStr);
  254. Boolean handleTEARDOWNResponse(MediaSession& session, MediaSubsession& subsession);
  255. Boolean handleGET_PARAMETERResponse(char const* parameterName, char*& resultValueString, char* resultValueStringEnd);
  256. Boolean handleAuthenticationFailure(char const* wwwAuthenticateParamsStr);
  257. Boolean resendCommand(RequestRecord* request);
  258. char const* sessionURL(MediaSession const& session) const;
  259. static void handleAlternativeRequestByte(void*, u_int8_t requestByte);
  260. void handleAlternativeRequestByte1(u_int8_t requestByte);
  261. void constructSubsessionURL(MediaSubsession const& subsession,
  262. char const*& prefix,
  263. char const*& separator,
  264. char const*& suffix);
  265. // Support for tunneling RTSP-over-HTTP:
  266. Boolean setupHTTPTunneling1(); // send the HTTP "GET"
  267. static void responseHandlerForHTTP_GET(RTSPClient* rtspClient, int responseCode, char* responseString);
  268. void responseHandlerForHTTP_GET1(int responseCode, char* responseString);
  269. Boolean setupHTTPTunneling2(); // send the HTTP "POST"
  270. // Support for asynchronous connections to the server:
  271. static void connectionHandler(void*, int /*mask*/);
  272. void connectionHandler1();
  273. // Support for handling data sent back by a server:
  274. static void incomingDataHandler(void*, int /*mask*/);
  275. void incomingDataHandler1();
  276. void handleResponseBytes(int newBytesRead);
  277. public:
  278. u_int16_t desiredMaxIncomingPacketSize;
  279. // If set to a value >0, then a "Blocksize:" header with this value (minus an allowance for
  280. // IP, UDP, and RTP headers) will be sent with each "SETUP" request.
  281. protected:
  282. int fVerbosityLevel;
  283. unsigned fCSeq; // sequence number, used in consecutive requests
  284. Authenticator fCurrentAuthenticator;
  285. Boolean fAllowBasicAuthentication;
  286. netAddressBits fServerAddress;
  287. private:
  288. portNumBits fTunnelOverHTTPPortNum;
  289. char* fUserAgentHeaderStr;
  290. unsigned fUserAgentHeaderStrLen;
  291. int fInputSocketNum, fOutputSocketNum;
  292. char* fBaseURL;
  293. unsigned char fTCPStreamIdCount; // used for (optional) RTP/TCP
  294. char* fLastSessionId;
  295. unsigned fSessionTimeoutParameter; // optionally set in response "Session:" headers
  296. char* fResponseBuffer;
  297. unsigned fResponseBytesAlreadySeen, fResponseBufferBytesLeft;
  298. RequestQueue fRequestsAwaitingConnection, fRequestsAwaitingHTTPTunneling, fRequestsAwaitingResponse;
  299. // Support for tunneling RTSP-over-HTTP:
  300. char fSessionCookie[33];
  301. unsigned fSessionCookieCounter;
  302. Boolean fHTTPTunnelingConnectionIsPending;
  303. };
  304. #ifndef OMIT_REGISTER_HANDLING
  305. ////////// HandlerServerForREGISTERCommand /////////
  306. // A simple server that creates a new "RTSPClient" object whenever a "REGISTER" request arrives (specifying the "rtsp://" URL
  307. // of a stream). The new "RTSPClient" object will be created with the specified URL, and passed to the provided handler function.
  308. typedef void onRTSPClientCreationFunc(RTSPClient* newRTSPClient, Boolean requestStreamingOverTCP);
  309. class HandlerServerForREGISTERCommand: public RTSPServer {
  310. public:
  311. static HandlerServerForREGISTERCommand* createNew(UsageEnvironment& env, onRTSPClientCreationFunc* creationFunc,
  312. Port ourPort = 0, UserAuthenticationDatabase* authDatabase = NULL,
  313. int verbosityLevel = 0, char const* applicationName = NULL);
  314. // If ourPort.num() == 0, we'll choose the port number ourself. (Use the following function to get it.)
  315. portNumBits serverPortNum() const { return ntohs(fServerPort.num()); }
  316. protected:
  317. HandlerServerForREGISTERCommand(UsageEnvironment& env, onRTSPClientCreationFunc* creationFunc, int ourSocket, Port ourPort,
  318. UserAuthenticationDatabase* authDatabase, int verbosityLevel, char const* applicationName);
  319. // called only by createNew();
  320. virtual ~HandlerServerForREGISTERCommand();
  321. virtual RTSPClient* createNewRTSPClient(char const* rtspURL, int verbosityLevel, char const* applicationName,
  322. int socketNumToServer);
  323. // This function - by default - creates a (base) "RTSPClient" object. If you want to create a subclass
  324. // of "RTSPClient" instead, then subclass this class, and redefine this virtual function.
  325. protected: // redefined virtual functions
  326. virtual char const* allowedCommandNames(); // "OPTIONS", "REGISTER", and (perhaps) "DEREGISTER" only
  327. virtual Boolean weImplementREGISTER(char const* cmd/*"REGISTER" or "DEREGISTER"*/,
  328. char const* proxyURLSuffix, char*& responseStr);
  329. // redefined to return True (for cmd=="REGISTER")
  330. virtual void implementCmd_REGISTER(char const* cmd/*"REGISTER" or "DEREGISTER"*/,
  331. char const* url, char const* urlSuffix, int socketToRemoteServer,
  332. Boolean deliverViaTCP, char const* proxyURLSuffix);
  333. private:
  334. onRTSPClientCreationFunc* fCreationFunc;
  335. int fVerbosityLevel;
  336. char* fApplicationName;
  337. };
  338. #endif
  339. #endif