You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3110 lines
103KB

  1. /*
  2. * RTMP network protocol
  3. * Copyright (c) 2009 Konstantin Shishkov
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * RTMP protocol
  24. */
  25. #include "libavcodec/bytestream.h"
  26. #include "libavutil/avstring.h"
  27. #include "libavutil/base64.h"
  28. #include "libavutil/hmac.h"
  29. #include "libavutil/intfloat.h"
  30. #include "libavutil/lfg.h"
  31. #include "libavutil/md5.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/random_seed.h"
  34. #include "avformat.h"
  35. #include "internal.h"
  36. #include "network.h"
  37. #include "flv.h"
  38. #include "rtmp.h"
  39. #include "rtmpcrypt.h"
  40. #include "rtmppkt.h"
  41. #include "url.h"
  42. #if CONFIG_ZLIB
  43. #include <zlib.h>
  44. #endif
  45. #define APP_MAX_LENGTH 128
  46. #define PLAYPATH_MAX_LENGTH 256
  47. #define TCURL_MAX_LENGTH 512
  48. #define FLASHVER_MAX_LENGTH 64
  49. #define RTMP_PKTDATA_DEFAULT_SIZE 4096
  50. #define RTMP_HEADER 11
  51. /** RTMP protocol handler state */
  52. typedef enum {
  53. STATE_START, ///< client has not done anything yet
  54. STATE_HANDSHAKED, ///< client has performed handshake
  55. STATE_FCPUBLISH, ///< client FCPublishing stream (for output)
  56. STATE_PLAYING, ///< client has started receiving multimedia data from server
  57. STATE_SEEKING, ///< client has started the seek operation. Back on STATE_PLAYING when the time comes
  58. STATE_PUBLISHING, ///< client has started sending multimedia data to server (for output)
  59. STATE_RECEIVING, ///< received a publish command (for input)
  60. STATE_SENDING, ///< received a play command (for output)
  61. STATE_STOPPED, ///< the broadcast has been stopped
  62. } ClientState;
  63. typedef struct TrackedMethod {
  64. char *name;
  65. int id;
  66. } TrackedMethod;
  67. /** protocol handler context */
  68. typedef struct RTMPContext {
  69. const AVClass *class;
  70. URLContext* stream; ///< TCP stream used in interactions with RTMP server
  71. RTMPPacket *prev_pkt[2]; ///< packet history used when reading and sending packets ([0] for reading, [1] for writing)
  72. int nb_prev_pkt[2]; ///< number of elements in prev_pkt
  73. int in_chunk_size; ///< size of the chunks incoming RTMP packets are divided into
  74. int out_chunk_size; ///< size of the chunks outgoing RTMP packets are divided into
  75. int is_input; ///< input/output flag
  76. char *playpath; ///< stream identifier to play (with possible "mp4:" prefix)
  77. int live; ///< 0: recorded, -1: live, -2: both
  78. char *app; ///< name of application
  79. char *conn; ///< append arbitrary AMF data to the Connect message
  80. ClientState state; ///< current state
  81. int stream_id; ///< ID assigned by the server for the stream
  82. uint8_t* flv_data; ///< buffer with data for demuxer
  83. int flv_size; ///< current buffer size
  84. int flv_off; ///< number of bytes read from current buffer
  85. int flv_nb_packets; ///< number of flv packets published
  86. RTMPPacket out_pkt; ///< rtmp packet, created from flv a/v or metadata (for output)
  87. uint32_t client_report_size; ///< number of bytes after which client should report to server
  88. uint32_t bytes_read; ///< number of bytes read from server
  89. uint32_t last_bytes_read; ///< number of bytes read last reported to server
  90. uint32_t last_timestamp; ///< last timestamp received in a packet
  91. int skip_bytes; ///< number of bytes to skip from the input FLV stream in the next write call
  92. int has_audio; ///< presence of audio data
  93. int has_video; ///< presence of video data
  94. int received_metadata; ///< Indicates if we have received metadata about the streams
  95. uint8_t flv_header[RTMP_HEADER]; ///< partial incoming flv packet header
  96. int flv_header_bytes; ///< number of initialized bytes in flv_header
  97. int nb_invokes; ///< keeps track of invoke messages
  98. char* tcurl; ///< url of the target stream
  99. char* flashver; ///< version of the flash plugin
  100. char* swfhash; ///< SHA256 hash of the decompressed SWF file (32 bytes)
  101. int swfhash_len; ///< length of the SHA256 hash
  102. int swfsize; ///< size of the decompressed SWF file
  103. char* swfurl; ///< url of the swf player
  104. char* swfverify; ///< URL to player swf file, compute hash/size automatically
  105. char swfverification[42]; ///< hash of the SWF verification
  106. char* pageurl; ///< url of the web page
  107. char* subscribe; ///< name of live stream to subscribe
  108. int server_bw; ///< server bandwidth
  109. int client_buffer_time; ///< client buffer time in ms
  110. int flush_interval; ///< number of packets flushed in the same request (RTMPT only)
  111. int encrypted; ///< use an encrypted connection (RTMPE only)
  112. TrackedMethod*tracked_methods; ///< tracked methods buffer
  113. int nb_tracked_methods; ///< number of tracked methods
  114. int tracked_methods_size; ///< size of the tracked methods buffer
  115. int listen; ///< listen mode flag
  116. int listen_timeout; ///< listen timeout to wait for new connections
  117. int nb_streamid; ///< The next stream id to return on createStream calls
  118. double duration; ///< Duration of the stream in seconds as returned by the server (only valid if non-zero)
  119. char username[50];
  120. char password[50];
  121. char auth_params[500];
  122. int do_reconnect;
  123. int auth_tried;
  124. } RTMPContext;
  125. #define PLAYER_KEY_OPEN_PART_LEN 30 ///< length of partial key used for first client digest signing
  126. /** Client key used for digest signing */
  127. static const uint8_t rtmp_player_key[] = {
  128. 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
  129. 'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1',
  130. 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
  131. 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
  132. 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
  133. };
  134. #define SERVER_KEY_OPEN_PART_LEN 36 ///< length of partial key used for first server digest signing
  135. /** Key used for RTMP server digest signing */
  136. static const uint8_t rtmp_server_key[] = {
  137. 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
  138. 'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ',
  139. 'S', 'e', 'r', 'v', 'e', 'r', ' ', '0', '0', '1',
  140. 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
  141. 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
  142. 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
  143. };
  144. static int handle_chunk_size(URLContext *s, RTMPPacket *pkt);
  145. static int add_tracked_method(RTMPContext *rt, const char *name, int id)
  146. {
  147. int err;
  148. if (rt->nb_tracked_methods + 1 > rt->tracked_methods_size) {
  149. rt->tracked_methods_size = (rt->nb_tracked_methods + 1) * 2;
  150. if ((err = av_reallocp(&rt->tracked_methods, rt->tracked_methods_size *
  151. sizeof(*rt->tracked_methods))) < 0) {
  152. rt->nb_tracked_methods = 0;
  153. rt->tracked_methods_size = 0;
  154. return err;
  155. }
  156. }
  157. rt->tracked_methods[rt->nb_tracked_methods].name = av_strdup(name);
  158. if (!rt->tracked_methods[rt->nb_tracked_methods].name)
  159. return AVERROR(ENOMEM);
  160. rt->tracked_methods[rt->nb_tracked_methods].id = id;
  161. rt->nb_tracked_methods++;
  162. return 0;
  163. }
  164. static void del_tracked_method(RTMPContext *rt, int index)
  165. {
  166. memmove(&rt->tracked_methods[index], &rt->tracked_methods[index + 1],
  167. sizeof(*rt->tracked_methods) * (rt->nb_tracked_methods - index - 1));
  168. rt->nb_tracked_methods--;
  169. }
  170. static int find_tracked_method(URLContext *s, RTMPPacket *pkt, int offset,
  171. char **tracked_method)
  172. {
  173. RTMPContext *rt = s->priv_data;
  174. GetByteContext gbc;
  175. double pkt_id;
  176. int ret;
  177. int i;
  178. bytestream2_init(&gbc, pkt->data + offset, pkt->size - offset);
  179. if ((ret = ff_amf_read_number(&gbc, &pkt_id)) < 0)
  180. return ret;
  181. for (i = 0; i < rt->nb_tracked_methods; i++) {
  182. if (rt->tracked_methods[i].id != pkt_id)
  183. continue;
  184. *tracked_method = rt->tracked_methods[i].name;
  185. del_tracked_method(rt, i);
  186. break;
  187. }
  188. return 0;
  189. }
  190. static void free_tracked_methods(RTMPContext *rt)
  191. {
  192. int i;
  193. for (i = 0; i < rt->nb_tracked_methods; i ++)
  194. av_free(rt->tracked_methods[i].name);
  195. av_free(rt->tracked_methods);
  196. rt->tracked_methods = NULL;
  197. rt->tracked_methods_size = 0;
  198. rt->nb_tracked_methods = 0;
  199. }
  200. static int rtmp_send_packet(RTMPContext *rt, RTMPPacket *pkt, int track)
  201. {
  202. int ret;
  203. if (pkt->type == RTMP_PT_INVOKE && track) {
  204. GetByteContext gbc;
  205. char name[128];
  206. double pkt_id;
  207. int len;
  208. bytestream2_init(&gbc, pkt->data, pkt->size);
  209. if ((ret = ff_amf_read_string(&gbc, name, sizeof(name), &len)) < 0)
  210. goto fail;
  211. if ((ret = ff_amf_read_number(&gbc, &pkt_id)) < 0)
  212. goto fail;
  213. if ((ret = add_tracked_method(rt, name, pkt_id)) < 0)
  214. goto fail;
  215. }
  216. ret = ff_rtmp_packet_write(rt->stream, pkt, rt->out_chunk_size,
  217. &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
  218. fail:
  219. ff_rtmp_packet_destroy(pkt);
  220. return ret;
  221. }
  222. static int rtmp_write_amf_data(URLContext *s, char *param, uint8_t **p)
  223. {
  224. char *field, *value;
  225. char type;
  226. /* The type must be B for Boolean, N for number, S for string, O for
  227. * object, or Z for null. For Booleans the data must be either 0 or 1 for
  228. * FALSE or TRUE, respectively. Likewise for Objects the data must be
  229. * 0 or 1 to end or begin an object, respectively. Data items in subobjects
  230. * may be named, by prefixing the type with 'N' and specifying the name
  231. * before the value (ie. NB:myFlag:1). This option may be used multiple times
  232. * to construct arbitrary AMF sequences. */
  233. if (param[0] && param[1] == ':') {
  234. type = param[0];
  235. value = param + 2;
  236. } else if (param[0] == 'N' && param[1] && param[2] == ':') {
  237. type = param[1];
  238. field = param + 3;
  239. value = strchr(field, ':');
  240. if (!value)
  241. goto fail;
  242. *value = '\0';
  243. value++;
  244. ff_amf_write_field_name(p, field);
  245. } else {
  246. goto fail;
  247. }
  248. switch (type) {
  249. case 'B':
  250. ff_amf_write_bool(p, value[0] != '0');
  251. break;
  252. case 'S':
  253. ff_amf_write_string(p, value);
  254. break;
  255. case 'N':
  256. ff_amf_write_number(p, strtod(value, NULL));
  257. break;
  258. case 'Z':
  259. ff_amf_write_null(p);
  260. break;
  261. case 'O':
  262. if (value[0] != '0')
  263. ff_amf_write_object_start(p);
  264. else
  265. ff_amf_write_object_end(p);
  266. break;
  267. default:
  268. goto fail;
  269. break;
  270. }
  271. return 0;
  272. fail:
  273. av_log(s, AV_LOG_ERROR, "Invalid AMF parameter: %s\n", param);
  274. return AVERROR(EINVAL);
  275. }
  276. /**
  277. * Generate 'connect' call and send it to the server.
  278. */
  279. static int gen_connect(URLContext *s, RTMPContext *rt)
  280. {
  281. RTMPPacket pkt;
  282. uint8_t *p;
  283. int ret;
  284. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  285. 0, 4096)) < 0)
  286. return ret;
  287. p = pkt.data;
  288. ff_amf_write_string(&p, "connect");
  289. ff_amf_write_number(&p, ++rt->nb_invokes);
  290. ff_amf_write_object_start(&p);
  291. ff_amf_write_field_name(&p, "app");
  292. ff_amf_write_string2(&p, rt->app, rt->auth_params);
  293. if (!rt->is_input) {
  294. ff_amf_write_field_name(&p, "type");
  295. ff_amf_write_string(&p, "nonprivate");
  296. }
  297. ff_amf_write_field_name(&p, "flashVer");
  298. ff_amf_write_string(&p, rt->flashver);
  299. if (rt->swfurl) {
  300. ff_amf_write_field_name(&p, "swfUrl");
  301. ff_amf_write_string(&p, rt->swfurl);
  302. }
  303. ff_amf_write_field_name(&p, "tcUrl");
  304. ff_amf_write_string2(&p, rt->tcurl, rt->auth_params);
  305. if (rt->is_input) {
  306. ff_amf_write_field_name(&p, "fpad");
  307. ff_amf_write_bool(&p, 0);
  308. ff_amf_write_field_name(&p, "capabilities");
  309. ff_amf_write_number(&p, 15.0);
  310. /* Tell the server we support all the audio codecs except
  311. * SUPPORT_SND_INTEL (0x0008) and SUPPORT_SND_UNUSED (0x0010)
  312. * which are unused in the RTMP protocol implementation. */
  313. ff_amf_write_field_name(&p, "audioCodecs");
  314. ff_amf_write_number(&p, 4071.0);
  315. ff_amf_write_field_name(&p, "videoCodecs");
  316. ff_amf_write_number(&p, 252.0);
  317. ff_amf_write_field_name(&p, "videoFunction");
  318. ff_amf_write_number(&p, 1.0);
  319. if (rt->pageurl) {
  320. ff_amf_write_field_name(&p, "pageUrl");
  321. ff_amf_write_string(&p, rt->pageurl);
  322. }
  323. }
  324. ff_amf_write_object_end(&p);
  325. if (rt->conn) {
  326. char *param = rt->conn;
  327. // Write arbitrary AMF data to the Connect message.
  328. while (param) {
  329. char *sep;
  330. param += strspn(param, " ");
  331. if (!*param)
  332. break;
  333. sep = strchr(param, ' ');
  334. if (sep)
  335. *sep = '\0';
  336. if ((ret = rtmp_write_amf_data(s, param, &p)) < 0) {
  337. // Invalid AMF parameter.
  338. ff_rtmp_packet_destroy(&pkt);
  339. return ret;
  340. }
  341. if (sep)
  342. param = sep + 1;
  343. else
  344. break;
  345. }
  346. }
  347. pkt.size = p - pkt.data;
  348. return rtmp_send_packet(rt, &pkt, 1);
  349. }
  350. static int read_connect(URLContext *s, RTMPContext *rt)
  351. {
  352. RTMPPacket pkt = { 0 };
  353. uint8_t *p;
  354. const uint8_t *cp;
  355. int ret;
  356. char command[64];
  357. int stringlen;
  358. double seqnum;
  359. uint8_t tmpstr[256];
  360. GetByteContext gbc;
  361. if ((ret = ff_rtmp_packet_read(rt->stream, &pkt, rt->in_chunk_size,
  362. &rt->prev_pkt[0], &rt->nb_prev_pkt[0])) < 0)
  363. return ret;
  364. if (pkt.type == RTMP_PT_CHUNK_SIZE) {
  365. if ((ret = handle_chunk_size(s, &pkt)) < 0)
  366. return ret;
  367. ff_rtmp_packet_destroy(&pkt);
  368. if ((ret = ff_rtmp_packet_read(rt->stream, &pkt, rt->in_chunk_size,
  369. &rt->prev_pkt[0], &rt->nb_prev_pkt[0])) < 0)
  370. return ret;
  371. }
  372. cp = pkt.data;
  373. bytestream2_init(&gbc, cp, pkt.size);
  374. if (ff_amf_read_string(&gbc, command, sizeof(command), &stringlen)) {
  375. av_log(s, AV_LOG_ERROR, "Unable to read command string\n");
  376. ff_rtmp_packet_destroy(&pkt);
  377. return AVERROR_INVALIDDATA;
  378. }
  379. if (strcmp(command, "connect")) {
  380. av_log(s, AV_LOG_ERROR, "Expecting connect, got %s\n", command);
  381. ff_rtmp_packet_destroy(&pkt);
  382. return AVERROR_INVALIDDATA;
  383. }
  384. ret = ff_amf_read_number(&gbc, &seqnum);
  385. if (ret)
  386. av_log(s, AV_LOG_WARNING, "SeqNum not found\n");
  387. /* Here one could parse an AMF Object with data as flashVers and others. */
  388. ret = ff_amf_get_field_value(gbc.buffer,
  389. gbc.buffer + bytestream2_get_bytes_left(&gbc),
  390. "app", tmpstr, sizeof(tmpstr));
  391. if (ret)
  392. av_log(s, AV_LOG_WARNING, "App field not found in connect\n");
  393. if (!ret && strcmp(tmpstr, rt->app))
  394. av_log(s, AV_LOG_WARNING, "App field don't match up: %s <-> %s\n",
  395. tmpstr, rt->app);
  396. ff_rtmp_packet_destroy(&pkt);
  397. // Send Window Acknowledgement Size (as defined in specification)
  398. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
  399. RTMP_PT_SERVER_BW, 0, 4)) < 0)
  400. return ret;
  401. p = pkt.data;
  402. bytestream_put_be32(&p, rt->server_bw);
  403. pkt.size = p - pkt.data;
  404. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  405. &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
  406. ff_rtmp_packet_destroy(&pkt);
  407. if (ret < 0)
  408. return ret;
  409. // Send Peer Bandwidth
  410. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
  411. RTMP_PT_CLIENT_BW, 0, 5)) < 0)
  412. return ret;
  413. p = pkt.data;
  414. bytestream_put_be32(&p, rt->server_bw);
  415. bytestream_put_byte(&p, 2); // dynamic
  416. pkt.size = p - pkt.data;
  417. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  418. &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
  419. ff_rtmp_packet_destroy(&pkt);
  420. if (ret < 0)
  421. return ret;
  422. // Ping request
  423. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
  424. RTMP_PT_PING, 0, 6)) < 0)
  425. return ret;
  426. p = pkt.data;
  427. bytestream_put_be16(&p, 0); // 0 -> Stream Begin
  428. bytestream_put_be32(&p, 0);
  429. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  430. &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
  431. ff_rtmp_packet_destroy(&pkt);
  432. if (ret < 0)
  433. return ret;
  434. // Chunk size
  435. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL,
  436. RTMP_PT_CHUNK_SIZE, 0, 4)) < 0)
  437. return ret;
  438. p = pkt.data;
  439. bytestream_put_be32(&p, rt->out_chunk_size);
  440. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  441. &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
  442. ff_rtmp_packet_destroy(&pkt);
  443. if (ret < 0)
  444. return ret;
  445. // Send _result NetConnection.Connect.Success to connect
  446. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL,
  447. RTMP_PT_INVOKE, 0,
  448. RTMP_PKTDATA_DEFAULT_SIZE)) < 0)
  449. return ret;
  450. p = pkt.data;
  451. ff_amf_write_string(&p, "_result");
  452. ff_amf_write_number(&p, seqnum);
  453. ff_amf_write_object_start(&p);
  454. ff_amf_write_field_name(&p, "fmsVer");
  455. ff_amf_write_string(&p, "FMS/3,0,1,123");
  456. ff_amf_write_field_name(&p, "capabilities");
  457. ff_amf_write_number(&p, 31);
  458. ff_amf_write_object_end(&p);
  459. ff_amf_write_object_start(&p);
  460. ff_amf_write_field_name(&p, "level");
  461. ff_amf_write_string(&p, "status");
  462. ff_amf_write_field_name(&p, "code");
  463. ff_amf_write_string(&p, "NetConnection.Connect.Success");
  464. ff_amf_write_field_name(&p, "description");
  465. ff_amf_write_string(&p, "Connection succeeded.");
  466. ff_amf_write_field_name(&p, "objectEncoding");
  467. ff_amf_write_number(&p, 0);
  468. ff_amf_write_object_end(&p);
  469. pkt.size = p - pkt.data;
  470. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  471. &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
  472. ff_rtmp_packet_destroy(&pkt);
  473. if (ret < 0)
  474. return ret;
  475. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL,
  476. RTMP_PT_INVOKE, 0, 30)) < 0)
  477. return ret;
  478. p = pkt.data;
  479. ff_amf_write_string(&p, "onBWDone");
  480. ff_amf_write_number(&p, 0);
  481. ff_amf_write_null(&p);
  482. ff_amf_write_number(&p, 8192);
  483. pkt.size = p - pkt.data;
  484. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  485. &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
  486. ff_rtmp_packet_destroy(&pkt);
  487. return ret;
  488. }
  489. /**
  490. * Generate 'releaseStream' call and send it to the server. It should make
  491. * the server release some channel for media streams.
  492. */
  493. static int gen_release_stream(URLContext *s, RTMPContext *rt)
  494. {
  495. RTMPPacket pkt;
  496. uint8_t *p;
  497. int ret;
  498. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  499. 0, 29 + strlen(rt->playpath))) < 0)
  500. return ret;
  501. av_log(s, AV_LOG_DEBUG, "Releasing stream...\n");
  502. p = pkt.data;
  503. ff_amf_write_string(&p, "releaseStream");
  504. ff_amf_write_number(&p, ++rt->nb_invokes);
  505. ff_amf_write_null(&p);
  506. ff_amf_write_string(&p, rt->playpath);
  507. return rtmp_send_packet(rt, &pkt, 1);
  508. }
  509. /**
  510. * Generate 'FCPublish' call and send it to the server. It should make
  511. * the server prepare for receiving media streams.
  512. */
  513. static int gen_fcpublish_stream(URLContext *s, RTMPContext *rt)
  514. {
  515. RTMPPacket pkt;
  516. uint8_t *p;
  517. int ret;
  518. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  519. 0, 25 + strlen(rt->playpath))) < 0)
  520. return ret;
  521. av_log(s, AV_LOG_DEBUG, "FCPublish stream...\n");
  522. p = pkt.data;
  523. ff_amf_write_string(&p, "FCPublish");
  524. ff_amf_write_number(&p, ++rt->nb_invokes);
  525. ff_amf_write_null(&p);
  526. ff_amf_write_string(&p, rt->playpath);
  527. return rtmp_send_packet(rt, &pkt, 1);
  528. }
  529. /**
  530. * Generate 'FCUnpublish' call and send it to the server. It should make
  531. * the server destroy stream.
  532. */
  533. static int gen_fcunpublish_stream(URLContext *s, RTMPContext *rt)
  534. {
  535. RTMPPacket pkt;
  536. uint8_t *p;
  537. int ret;
  538. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  539. 0, 27 + strlen(rt->playpath))) < 0)
  540. return ret;
  541. av_log(s, AV_LOG_DEBUG, "UnPublishing stream...\n");
  542. p = pkt.data;
  543. ff_amf_write_string(&p, "FCUnpublish");
  544. ff_amf_write_number(&p, ++rt->nb_invokes);
  545. ff_amf_write_null(&p);
  546. ff_amf_write_string(&p, rt->playpath);
  547. return rtmp_send_packet(rt, &pkt, 0);
  548. }
  549. /**
  550. * Generate 'createStream' call and send it to the server. It should make
  551. * the server allocate some channel for media streams.
  552. */
  553. static int gen_create_stream(URLContext *s, RTMPContext *rt)
  554. {
  555. RTMPPacket pkt;
  556. uint8_t *p;
  557. int ret;
  558. av_log(s, AV_LOG_DEBUG, "Creating stream...\n");
  559. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  560. 0, 25)) < 0)
  561. return ret;
  562. p = pkt.data;
  563. ff_amf_write_string(&p, "createStream");
  564. ff_amf_write_number(&p, ++rt->nb_invokes);
  565. ff_amf_write_null(&p);
  566. return rtmp_send_packet(rt, &pkt, 1);
  567. }
  568. /**
  569. * Generate 'deleteStream' call and send it to the server. It should make
  570. * the server remove some channel for media streams.
  571. */
  572. static int gen_delete_stream(URLContext *s, RTMPContext *rt)
  573. {
  574. RTMPPacket pkt;
  575. uint8_t *p;
  576. int ret;
  577. av_log(s, AV_LOG_DEBUG, "Deleting stream...\n");
  578. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  579. 0, 34)) < 0)
  580. return ret;
  581. p = pkt.data;
  582. ff_amf_write_string(&p, "deleteStream");
  583. ff_amf_write_number(&p, ++rt->nb_invokes);
  584. ff_amf_write_null(&p);
  585. ff_amf_write_number(&p, rt->stream_id);
  586. return rtmp_send_packet(rt, &pkt, 0);
  587. }
  588. /**
  589. * Generate 'getStreamLength' call and send it to the server. If the server
  590. * knows the duration of the selected stream, it will reply with the duration
  591. * in seconds.
  592. */
  593. static int gen_get_stream_length(URLContext *s, RTMPContext *rt)
  594. {
  595. RTMPPacket pkt;
  596. uint8_t *p;
  597. int ret;
  598. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE,
  599. 0, 31 + strlen(rt->playpath))) < 0)
  600. return ret;
  601. p = pkt.data;
  602. ff_amf_write_string(&p, "getStreamLength");
  603. ff_amf_write_number(&p, ++rt->nb_invokes);
  604. ff_amf_write_null(&p);
  605. ff_amf_write_string(&p, rt->playpath);
  606. return rtmp_send_packet(rt, &pkt, 1);
  607. }
  608. /**
  609. * Generate client buffer time and send it to the server.
  610. */
  611. static int gen_buffer_time(URLContext *s, RTMPContext *rt)
  612. {
  613. RTMPPacket pkt;
  614. uint8_t *p;
  615. int ret;
  616. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING,
  617. 1, 10)) < 0)
  618. return ret;
  619. p = pkt.data;
  620. bytestream_put_be16(&p, 3);
  621. bytestream_put_be32(&p, rt->stream_id);
  622. bytestream_put_be32(&p, rt->client_buffer_time);
  623. return rtmp_send_packet(rt, &pkt, 0);
  624. }
  625. /**
  626. * Generate 'play' call and send it to the server, then ping the server
  627. * to start actual playing.
  628. */
  629. static int gen_play(URLContext *s, RTMPContext *rt)
  630. {
  631. RTMPPacket pkt;
  632. uint8_t *p;
  633. int ret;
  634. av_log(s, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
  635. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE,
  636. 0, 29 + strlen(rt->playpath))) < 0)
  637. return ret;
  638. pkt.extra = rt->stream_id;
  639. p = pkt.data;
  640. ff_amf_write_string(&p, "play");
  641. ff_amf_write_number(&p, ++rt->nb_invokes);
  642. ff_amf_write_null(&p);
  643. ff_amf_write_string(&p, rt->playpath);
  644. ff_amf_write_number(&p, rt->live * 1000);
  645. return rtmp_send_packet(rt, &pkt, 1);
  646. }
  647. static int gen_seek(URLContext *s, RTMPContext *rt, int64_t timestamp)
  648. {
  649. RTMPPacket pkt;
  650. uint8_t *p;
  651. int ret;
  652. av_log(s, AV_LOG_DEBUG, "Sending seek command for timestamp %"PRId64"\n",
  653. timestamp);
  654. if ((ret = ff_rtmp_packet_create(&pkt, 3, RTMP_PT_INVOKE, 0, 26)) < 0)
  655. return ret;
  656. pkt.extra = rt->stream_id;
  657. p = pkt.data;
  658. ff_amf_write_string(&p, "seek");
  659. ff_amf_write_number(&p, 0); //no tracking back responses
  660. ff_amf_write_null(&p); //as usual, the first null param
  661. ff_amf_write_number(&p, timestamp); //where we want to jump
  662. return rtmp_send_packet(rt, &pkt, 1);
  663. }
  664. /**
  665. * Generate a pause packet that either pauses or unpauses the current stream.
  666. */
  667. static int gen_pause(URLContext *s, RTMPContext *rt, int pause, uint32_t timestamp)
  668. {
  669. RTMPPacket pkt;
  670. uint8_t *p;
  671. int ret;
  672. av_log(s, AV_LOG_DEBUG, "Sending pause command for timestamp %d\n",
  673. timestamp);
  674. if ((ret = ff_rtmp_packet_create(&pkt, 3, RTMP_PT_INVOKE, 0, 29)) < 0)
  675. return ret;
  676. pkt.extra = rt->stream_id;
  677. p = pkt.data;
  678. ff_amf_write_string(&p, "pause");
  679. ff_amf_write_number(&p, 0); //no tracking back responses
  680. ff_amf_write_null(&p); //as usual, the first null param
  681. ff_amf_write_bool(&p, pause); // pause or unpause
  682. ff_amf_write_number(&p, timestamp); //where we pause the stream
  683. return rtmp_send_packet(rt, &pkt, 1);
  684. }
  685. /**
  686. * Generate 'publish' call and send it to the server.
  687. */
  688. static int gen_publish(URLContext *s, RTMPContext *rt)
  689. {
  690. RTMPPacket pkt;
  691. uint8_t *p;
  692. int ret;
  693. av_log(s, AV_LOG_DEBUG, "Sending publish command for '%s'\n", rt->playpath);
  694. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE,
  695. 0, 30 + strlen(rt->playpath))) < 0)
  696. return ret;
  697. pkt.extra = rt->stream_id;
  698. p = pkt.data;
  699. ff_amf_write_string(&p, "publish");
  700. ff_amf_write_number(&p, ++rt->nb_invokes);
  701. ff_amf_write_null(&p);
  702. ff_amf_write_string(&p, rt->playpath);
  703. ff_amf_write_string(&p, "live");
  704. return rtmp_send_packet(rt, &pkt, 1);
  705. }
  706. /**
  707. * Generate ping reply and send it to the server.
  708. */
  709. static int gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
  710. {
  711. RTMPPacket pkt;
  712. uint8_t *p;
  713. int ret;
  714. if (ppkt->size < 6) {
  715. av_log(s, AV_LOG_ERROR, "Too short ping packet (%d)\n",
  716. ppkt->size);
  717. return AVERROR_INVALIDDATA;
  718. }
  719. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING,
  720. ppkt->timestamp + 1, 6)) < 0)
  721. return ret;
  722. p = pkt.data;
  723. bytestream_put_be16(&p, 7);
  724. bytestream_put_be32(&p, AV_RB32(ppkt->data+2));
  725. return rtmp_send_packet(rt, &pkt, 0);
  726. }
  727. /**
  728. * Generate SWF verification message and send it to the server.
  729. */
  730. static int gen_swf_verification(URLContext *s, RTMPContext *rt)
  731. {
  732. RTMPPacket pkt;
  733. uint8_t *p;
  734. int ret;
  735. av_log(s, AV_LOG_DEBUG, "Sending SWF verification...\n");
  736. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING,
  737. 0, 44)) < 0)
  738. return ret;
  739. p = pkt.data;
  740. bytestream_put_be16(&p, 27);
  741. memcpy(p, rt->swfverification, 42);
  742. return rtmp_send_packet(rt, &pkt, 0);
  743. }
  744. /**
  745. * Generate server bandwidth message and send it to the server.
  746. */
  747. static int gen_server_bw(URLContext *s, RTMPContext *rt)
  748. {
  749. RTMPPacket pkt;
  750. uint8_t *p;
  751. int ret;
  752. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_SERVER_BW,
  753. 0, 4)) < 0)
  754. return ret;
  755. p = pkt.data;
  756. bytestream_put_be32(&p, rt->server_bw);
  757. return rtmp_send_packet(rt, &pkt, 0);
  758. }
  759. /**
  760. * Generate check bandwidth message and send it to the server.
  761. */
  762. static int gen_check_bw(URLContext *s, RTMPContext *rt)
  763. {
  764. RTMPPacket pkt;
  765. uint8_t *p;
  766. int ret;
  767. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  768. 0, 21)) < 0)
  769. return ret;
  770. p = pkt.data;
  771. ff_amf_write_string(&p, "_checkbw");
  772. ff_amf_write_number(&p, ++rt->nb_invokes);
  773. ff_amf_write_null(&p);
  774. return rtmp_send_packet(rt, &pkt, 1);
  775. }
  776. /**
  777. * Generate report on bytes read so far and send it to the server.
  778. */
  779. static int gen_bytes_read(URLContext *s, RTMPContext *rt, uint32_t ts)
  780. {
  781. RTMPPacket pkt;
  782. uint8_t *p;
  783. int ret;
  784. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_BYTES_READ,
  785. ts, 4)) < 0)
  786. return ret;
  787. p = pkt.data;
  788. bytestream_put_be32(&p, rt->bytes_read);
  789. return rtmp_send_packet(rt, &pkt, 0);
  790. }
  791. static int gen_fcsubscribe_stream(URLContext *s, RTMPContext *rt,
  792. const char *subscribe)
  793. {
  794. RTMPPacket pkt;
  795. uint8_t *p;
  796. int ret;
  797. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  798. 0, 27 + strlen(subscribe))) < 0)
  799. return ret;
  800. p = pkt.data;
  801. ff_amf_write_string(&p, "FCSubscribe");
  802. ff_amf_write_number(&p, ++rt->nb_invokes);
  803. ff_amf_write_null(&p);
  804. ff_amf_write_string(&p, subscribe);
  805. return rtmp_send_packet(rt, &pkt, 1);
  806. }
  807. int ff_rtmp_calc_digest(const uint8_t *src, int len, int gap,
  808. const uint8_t *key, int keylen, uint8_t *dst)
  809. {
  810. AVHMAC *hmac;
  811. hmac = av_hmac_alloc(AV_HMAC_SHA256);
  812. if (!hmac)
  813. return AVERROR(ENOMEM);
  814. av_hmac_init(hmac, key, keylen);
  815. if (gap <= 0) {
  816. av_hmac_update(hmac, src, len);
  817. } else { //skip 32 bytes used for storing digest
  818. av_hmac_update(hmac, src, gap);
  819. av_hmac_update(hmac, src + gap + 32, len - gap - 32);
  820. }
  821. av_hmac_final(hmac, dst, 32);
  822. av_hmac_free(hmac);
  823. return 0;
  824. }
  825. int ff_rtmp_calc_digest_pos(const uint8_t *buf, int off, int mod_val,
  826. int add_val)
  827. {
  828. int i, digest_pos = 0;
  829. for (i = 0; i < 4; i++)
  830. digest_pos += buf[i + off];
  831. digest_pos = digest_pos % mod_val + add_val;
  832. return digest_pos;
  833. }
  834. /**
  835. * Put HMAC-SHA2 digest of packet data (except for the bytes where this digest
  836. * will be stored) into that packet.
  837. *
  838. * @param buf handshake data (1536 bytes)
  839. * @param encrypted use an encrypted connection (RTMPE)
  840. * @return offset to the digest inside input data
  841. */
  842. static int rtmp_handshake_imprint_with_digest(uint8_t *buf, int encrypted)
  843. {
  844. int ret, digest_pos;
  845. if (encrypted)
  846. digest_pos = ff_rtmp_calc_digest_pos(buf, 772, 728, 776);
  847. else
  848. digest_pos = ff_rtmp_calc_digest_pos(buf, 8, 728, 12);
  849. ret = ff_rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
  850. rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
  851. buf + digest_pos);
  852. if (ret < 0)
  853. return ret;
  854. return digest_pos;
  855. }
  856. /**
  857. * Verify that the received server response has the expected digest value.
  858. *
  859. * @param buf handshake data received from the server (1536 bytes)
  860. * @param off position to search digest offset from
  861. * @return 0 if digest is valid, digest position otherwise
  862. */
  863. static int rtmp_validate_digest(uint8_t *buf, int off)
  864. {
  865. uint8_t digest[32];
  866. int ret, digest_pos;
  867. digest_pos = ff_rtmp_calc_digest_pos(buf, off, 728, off + 4);
  868. ret = ff_rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
  869. rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
  870. digest);
  871. if (ret < 0)
  872. return ret;
  873. if (!memcmp(digest, buf + digest_pos, 32))
  874. return digest_pos;
  875. return 0;
  876. }
  877. static int rtmp_calc_swf_verification(URLContext *s, RTMPContext *rt,
  878. uint8_t *buf)
  879. {
  880. uint8_t *p;
  881. int ret;
  882. if (rt->swfhash_len != 32) {
  883. av_log(s, AV_LOG_ERROR,
  884. "Hash of the decompressed SWF file is not 32 bytes long.\n");
  885. return AVERROR(EINVAL);
  886. }
  887. p = &rt->swfverification[0];
  888. bytestream_put_byte(&p, 1);
  889. bytestream_put_byte(&p, 1);
  890. bytestream_put_be32(&p, rt->swfsize);
  891. bytestream_put_be32(&p, rt->swfsize);
  892. if ((ret = ff_rtmp_calc_digest(rt->swfhash, 32, 0, buf, 32, p)) < 0)
  893. return ret;
  894. return 0;
  895. }
  896. #if CONFIG_ZLIB
  897. static int rtmp_uncompress_swfplayer(uint8_t *in_data, int64_t in_size,
  898. uint8_t **out_data, int64_t *out_size)
  899. {
  900. z_stream zs = { 0 };
  901. void *ptr;
  902. int size;
  903. int ret = 0;
  904. zs.avail_in = in_size;
  905. zs.next_in = in_data;
  906. ret = inflateInit(&zs);
  907. if (ret != Z_OK)
  908. return AVERROR_UNKNOWN;
  909. do {
  910. uint8_t tmp_buf[16384];
  911. zs.avail_out = sizeof(tmp_buf);
  912. zs.next_out = tmp_buf;
  913. ret = inflate(&zs, Z_NO_FLUSH);
  914. if (ret != Z_OK && ret != Z_STREAM_END) {
  915. ret = AVERROR_UNKNOWN;
  916. goto fail;
  917. }
  918. size = sizeof(tmp_buf) - zs.avail_out;
  919. if (!(ptr = av_realloc(*out_data, *out_size + size))) {
  920. ret = AVERROR(ENOMEM);
  921. goto fail;
  922. }
  923. *out_data = ptr;
  924. memcpy(*out_data + *out_size, tmp_buf, size);
  925. *out_size += size;
  926. } while (zs.avail_out == 0);
  927. fail:
  928. inflateEnd(&zs);
  929. return ret;
  930. }
  931. #endif
  932. static int rtmp_calc_swfhash(URLContext *s)
  933. {
  934. RTMPContext *rt = s->priv_data;
  935. uint8_t *in_data = NULL, *out_data = NULL, *swfdata;
  936. int64_t in_size, out_size;
  937. URLContext *stream;
  938. char swfhash[32];
  939. int swfsize;
  940. int ret = 0;
  941. /* Get the SWF player file. */
  942. if ((ret = ffurl_open(&stream, rt->swfverify, AVIO_FLAG_READ,
  943. &s->interrupt_callback, NULL, s->protocols, s)) < 0) {
  944. av_log(s, AV_LOG_ERROR, "Cannot open connection %s.\n", rt->swfverify);
  945. goto fail;
  946. }
  947. if ((in_size = ffurl_seek(stream, 0, AVSEEK_SIZE)) < 0) {
  948. ret = AVERROR(EIO);
  949. goto fail;
  950. }
  951. if (!(in_data = av_malloc(in_size))) {
  952. ret = AVERROR(ENOMEM);
  953. goto fail;
  954. }
  955. if ((ret = ffurl_read_complete(stream, in_data, in_size)) < 0)
  956. goto fail;
  957. if (in_size < 3) {
  958. ret = AVERROR_INVALIDDATA;
  959. goto fail;
  960. }
  961. if (!memcmp(in_data, "CWS", 3)) {
  962. /* Decompress the SWF player file using Zlib. */
  963. if (!(out_data = av_malloc(8))) {
  964. ret = AVERROR(ENOMEM);
  965. goto fail;
  966. }
  967. *in_data = 'F'; // magic stuff
  968. memcpy(out_data, in_data, 8);
  969. out_size = 8;
  970. #if CONFIG_ZLIB
  971. if ((ret = rtmp_uncompress_swfplayer(in_data + 8, in_size - 8,
  972. &out_data, &out_size)) < 0)
  973. goto fail;
  974. #else
  975. av_log(s, AV_LOG_ERROR,
  976. "Zlib is required for decompressing the SWF player file.\n");
  977. ret = AVERROR(EINVAL);
  978. goto fail;
  979. #endif
  980. swfsize = out_size;
  981. swfdata = out_data;
  982. } else {
  983. swfsize = in_size;
  984. swfdata = in_data;
  985. }
  986. /* Compute the SHA256 hash of the SWF player file. */
  987. if ((ret = ff_rtmp_calc_digest(swfdata, swfsize, 0,
  988. "Genuine Adobe Flash Player 001", 30,
  989. swfhash)) < 0)
  990. goto fail;
  991. /* Set SWFVerification parameters. */
  992. av_opt_set_bin(rt, "rtmp_swfhash", swfhash, 32, 0);
  993. rt->swfsize = swfsize;
  994. fail:
  995. av_freep(&in_data);
  996. av_freep(&out_data);
  997. ffurl_close(stream);
  998. return ret;
  999. }
  1000. /**
  1001. * Perform handshake with the server by means of exchanging pseudorandom data
  1002. * signed with HMAC-SHA2 digest.
  1003. *
  1004. * @return 0 if handshake succeeds, negative value otherwise
  1005. */
  1006. static int rtmp_handshake(URLContext *s, RTMPContext *rt)
  1007. {
  1008. AVLFG rnd;
  1009. uint8_t tosend [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
  1010. 3, // unencrypted data
  1011. 0, 0, 0, 0, // client uptime
  1012. RTMP_CLIENT_VER1,
  1013. RTMP_CLIENT_VER2,
  1014. RTMP_CLIENT_VER3,
  1015. RTMP_CLIENT_VER4,
  1016. };
  1017. uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
  1018. uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
  1019. int i;
  1020. int server_pos, client_pos;
  1021. uint8_t digest[32], signature[32];
  1022. int ret, type = 0;
  1023. av_log(s, AV_LOG_DEBUG, "Handshaking...\n");
  1024. av_lfg_init(&rnd, 0xDEADC0DE);
  1025. // generate handshake packet - 1536 bytes of pseudorandom data
  1026. for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
  1027. tosend[i] = av_lfg_get(&rnd) >> 24;
  1028. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1029. /* When the client wants to use RTMPE, we have to change the command
  1030. * byte to 0x06 which means to use encrypted data and we have to set
  1031. * the flash version to at least 9.0.115.0. */
  1032. tosend[0] = 6;
  1033. tosend[5] = 128;
  1034. tosend[6] = 0;
  1035. tosend[7] = 3;
  1036. tosend[8] = 2;
  1037. /* Initialize the Diffie-Hellmann context and generate the public key
  1038. * to send to the server. */
  1039. if ((ret = ff_rtmpe_gen_pub_key(rt->stream, tosend + 1)) < 0)
  1040. return ret;
  1041. }
  1042. client_pos = rtmp_handshake_imprint_with_digest(tosend + 1, rt->encrypted);
  1043. if (client_pos < 0)
  1044. return client_pos;
  1045. if ((ret = ffurl_write(rt->stream, tosend,
  1046. RTMP_HANDSHAKE_PACKET_SIZE + 1)) < 0) {
  1047. av_log(s, AV_LOG_ERROR, "Cannot write RTMP handshake request\n");
  1048. return ret;
  1049. }
  1050. if ((ret = ffurl_read_complete(rt->stream, serverdata,
  1051. RTMP_HANDSHAKE_PACKET_SIZE + 1)) < 0) {
  1052. av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
  1053. return ret;
  1054. }
  1055. if ((ret = ffurl_read_complete(rt->stream, clientdata,
  1056. RTMP_HANDSHAKE_PACKET_SIZE)) < 0) {
  1057. av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
  1058. return ret;
  1059. }
  1060. av_log(s, AV_LOG_DEBUG, "Type answer %d\n", serverdata[0]);
  1061. av_log(s, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
  1062. serverdata[5], serverdata[6], serverdata[7], serverdata[8]);
  1063. if (rt->is_input && serverdata[5] >= 3) {
  1064. server_pos = rtmp_validate_digest(serverdata + 1, 772);
  1065. if (server_pos < 0)
  1066. return server_pos;
  1067. if (!server_pos) {
  1068. type = 1;
  1069. server_pos = rtmp_validate_digest(serverdata + 1, 8);
  1070. if (server_pos < 0)
  1071. return server_pos;
  1072. if (!server_pos) {
  1073. av_log(s, AV_LOG_ERROR, "Server response validating failed\n");
  1074. return AVERROR(EIO);
  1075. }
  1076. }
  1077. /* Generate SWFVerification token (SHA256 HMAC hash of decompressed SWF,
  1078. * key are the last 32 bytes of the server handshake. */
  1079. if (rt->swfsize) {
  1080. if ((ret = rtmp_calc_swf_verification(s, rt, serverdata + 1 +
  1081. RTMP_HANDSHAKE_PACKET_SIZE - 32)) < 0)
  1082. return ret;
  1083. }
  1084. ret = ff_rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
  1085. rtmp_server_key, sizeof(rtmp_server_key),
  1086. digest);
  1087. if (ret < 0)
  1088. return ret;
  1089. ret = ff_rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE - 32,
  1090. 0, digest, 32, signature);
  1091. if (ret < 0)
  1092. return ret;
  1093. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1094. /* Compute the shared secret key sent by the server and initialize
  1095. * the RC4 encryption. */
  1096. if ((ret = ff_rtmpe_compute_secret_key(rt->stream, serverdata + 1,
  1097. tosend + 1, type)) < 0)
  1098. return ret;
  1099. /* Encrypt the signature received by the server. */
  1100. ff_rtmpe_encrypt_sig(rt->stream, signature, digest, serverdata[0]);
  1101. }
  1102. if (memcmp(signature, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
  1103. av_log(s, AV_LOG_ERROR, "Signature mismatch\n");
  1104. return AVERROR(EIO);
  1105. }
  1106. for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
  1107. tosend[i] = av_lfg_get(&rnd) >> 24;
  1108. ret = ff_rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
  1109. rtmp_player_key, sizeof(rtmp_player_key),
  1110. digest);
  1111. if (ret < 0)
  1112. return ret;
  1113. ret = ff_rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
  1114. digest, 32,
  1115. tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
  1116. if (ret < 0)
  1117. return ret;
  1118. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1119. /* Encrypt the signature to be send to the server. */
  1120. ff_rtmpe_encrypt_sig(rt->stream, tosend +
  1121. RTMP_HANDSHAKE_PACKET_SIZE - 32, digest,
  1122. serverdata[0]);
  1123. }
  1124. // write reply back to the server
  1125. if ((ret = ffurl_write(rt->stream, tosend,
  1126. RTMP_HANDSHAKE_PACKET_SIZE)) < 0)
  1127. return ret;
  1128. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1129. /* Set RC4 keys for encryption and update the keystreams. */
  1130. if ((ret = ff_rtmpe_update_keystream(rt->stream)) < 0)
  1131. return ret;
  1132. }
  1133. } else {
  1134. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1135. /* Compute the shared secret key sent by the server and initialize
  1136. * the RC4 encryption. */
  1137. if ((ret = ff_rtmpe_compute_secret_key(rt->stream, serverdata + 1,
  1138. tosend + 1, 1)) < 0)
  1139. return ret;
  1140. if (serverdata[0] == 9) {
  1141. /* Encrypt the signature received by the server. */
  1142. ff_rtmpe_encrypt_sig(rt->stream, signature, digest,
  1143. serverdata[0]);
  1144. }
  1145. }
  1146. if ((ret = ffurl_write(rt->stream, serverdata + 1,
  1147. RTMP_HANDSHAKE_PACKET_SIZE)) < 0)
  1148. return ret;
  1149. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1150. /* Set RC4 keys for encryption and update the keystreams. */
  1151. if ((ret = ff_rtmpe_update_keystream(rt->stream)) < 0)
  1152. return ret;
  1153. }
  1154. }
  1155. return 0;
  1156. }
  1157. static int rtmp_receive_hs_packet(RTMPContext* rt, uint32_t *first_int,
  1158. uint32_t *second_int, char *arraydata,
  1159. int size)
  1160. {
  1161. int inoutsize;
  1162. inoutsize = ffurl_read_complete(rt->stream, arraydata,
  1163. RTMP_HANDSHAKE_PACKET_SIZE);
  1164. if (inoutsize <= 0)
  1165. return AVERROR(EIO);
  1166. if (inoutsize != RTMP_HANDSHAKE_PACKET_SIZE) {
  1167. av_log(rt, AV_LOG_ERROR, "Erroneous Message size %d"
  1168. " not following standard\n", (int)inoutsize);
  1169. return AVERROR(EINVAL);
  1170. }
  1171. *first_int = AV_RB32(arraydata);
  1172. *second_int = AV_RB32(arraydata + 4);
  1173. return 0;
  1174. }
  1175. static int rtmp_send_hs_packet(RTMPContext* rt, uint32_t first_int,
  1176. uint32_t second_int, char *arraydata, int size)
  1177. {
  1178. int inoutsize;
  1179. AV_WB32(arraydata, first_int);
  1180. AV_WB32(arraydata + 4, second_int);
  1181. inoutsize = ffurl_write(rt->stream, arraydata,
  1182. RTMP_HANDSHAKE_PACKET_SIZE);
  1183. if (inoutsize != RTMP_HANDSHAKE_PACKET_SIZE) {
  1184. av_log(rt, AV_LOG_ERROR, "Unable to write answer\n");
  1185. return AVERROR(EIO);
  1186. }
  1187. return 0;
  1188. }
  1189. /**
  1190. * rtmp handshake server side
  1191. */
  1192. static int rtmp_server_handshake(URLContext *s, RTMPContext *rt)
  1193. {
  1194. uint8_t buffer[RTMP_HANDSHAKE_PACKET_SIZE];
  1195. uint32_t hs_epoch;
  1196. uint32_t hs_my_epoch;
  1197. uint8_t hs_c1[RTMP_HANDSHAKE_PACKET_SIZE];
  1198. uint8_t hs_s1[RTMP_HANDSHAKE_PACKET_SIZE];
  1199. uint32_t zeroes;
  1200. uint32_t temp = 0;
  1201. int randomidx = 0;
  1202. int inoutsize = 0;
  1203. int ret;
  1204. inoutsize = ffurl_read_complete(rt->stream, buffer, 1); // Receive C0
  1205. if (inoutsize <= 0) {
  1206. av_log(s, AV_LOG_ERROR, "Unable to read handshake\n");
  1207. return AVERROR(EIO);
  1208. }
  1209. // Check Version
  1210. if (buffer[0] != 3) {
  1211. av_log(s, AV_LOG_ERROR, "RTMP protocol version mismatch\n");
  1212. return AVERROR(EIO);
  1213. }
  1214. if (ffurl_write(rt->stream, buffer, 1) <= 0) { // Send S0
  1215. av_log(s, AV_LOG_ERROR,
  1216. "Unable to write answer - RTMP S0\n");
  1217. return AVERROR(EIO);
  1218. }
  1219. /* Receive C1 */
  1220. ret = rtmp_receive_hs_packet(rt, &hs_epoch, &zeroes, hs_c1,
  1221. RTMP_HANDSHAKE_PACKET_SIZE);
  1222. if (ret) {
  1223. av_log(s, AV_LOG_ERROR, "RTMP Handshake C1 Error\n");
  1224. return ret;
  1225. }
  1226. /* Send S1 */
  1227. /* By now same epoch will be sent */
  1228. hs_my_epoch = hs_epoch;
  1229. /* Generate random */
  1230. for (randomidx = 8; randomidx < (RTMP_HANDSHAKE_PACKET_SIZE);
  1231. randomidx += 4)
  1232. AV_WB32(hs_s1 + randomidx, av_get_random_seed());
  1233. ret = rtmp_send_hs_packet(rt, hs_my_epoch, 0, hs_s1,
  1234. RTMP_HANDSHAKE_PACKET_SIZE);
  1235. if (ret) {
  1236. av_log(s, AV_LOG_ERROR, "RTMP Handshake S1 Error\n");
  1237. return ret;
  1238. }
  1239. /* Send S2 */
  1240. ret = rtmp_send_hs_packet(rt, hs_epoch, 0, hs_c1,
  1241. RTMP_HANDSHAKE_PACKET_SIZE);
  1242. if (ret) {
  1243. av_log(s, AV_LOG_ERROR, "RTMP Handshake S2 Error\n");
  1244. return ret;
  1245. }
  1246. /* Receive C2 */
  1247. ret = rtmp_receive_hs_packet(rt, &temp, &zeroes, buffer,
  1248. RTMP_HANDSHAKE_PACKET_SIZE);
  1249. if (ret) {
  1250. av_log(s, AV_LOG_ERROR, "RTMP Handshake C2 Error\n");
  1251. return ret;
  1252. }
  1253. if (temp != hs_my_epoch)
  1254. av_log(s, AV_LOG_WARNING,
  1255. "Erroneous C2 Message epoch does not match up with C1 epoch\n");
  1256. if (memcmp(buffer + 8, hs_s1 + 8,
  1257. RTMP_HANDSHAKE_PACKET_SIZE - 8))
  1258. av_log(s, AV_LOG_WARNING,
  1259. "Erroneous C2 Message random does not match up\n");
  1260. return 0;
  1261. }
  1262. static int handle_chunk_size(URLContext *s, RTMPPacket *pkt)
  1263. {
  1264. RTMPContext *rt = s->priv_data;
  1265. int ret;
  1266. if (pkt->size < 4) {
  1267. av_log(s, AV_LOG_ERROR,
  1268. "Too short chunk size change packet (%d)\n",
  1269. pkt->size);
  1270. return AVERROR_INVALIDDATA;
  1271. }
  1272. if (!rt->is_input) {
  1273. /* Send the same chunk size change packet back to the server,
  1274. * setting the outgoing chunk size to the same as the incoming one. */
  1275. if ((ret = ff_rtmp_packet_write(rt->stream, pkt, rt->out_chunk_size,
  1276. &rt->prev_pkt[1], &rt->nb_prev_pkt[1])) < 0)
  1277. return ret;
  1278. rt->out_chunk_size = AV_RB32(pkt->data);
  1279. }
  1280. rt->in_chunk_size = AV_RB32(pkt->data);
  1281. if (rt->in_chunk_size <= 0) {
  1282. av_log(s, AV_LOG_ERROR, "Incorrect chunk size %d\n",
  1283. rt->in_chunk_size);
  1284. return AVERROR_INVALIDDATA;
  1285. }
  1286. av_log(s, AV_LOG_DEBUG, "New incoming chunk size = %d\n",
  1287. rt->in_chunk_size);
  1288. return 0;
  1289. }
  1290. static int handle_ping(URLContext *s, RTMPPacket *pkt)
  1291. {
  1292. RTMPContext *rt = s->priv_data;
  1293. int t, ret;
  1294. if (pkt->size < 2) {
  1295. av_log(s, AV_LOG_ERROR, "Too short ping packet (%d)\n",
  1296. pkt->size);
  1297. return AVERROR_INVALIDDATA;
  1298. }
  1299. t = AV_RB16(pkt->data);
  1300. if (t == 6) {
  1301. if ((ret = gen_pong(s, rt, pkt)) < 0)
  1302. return ret;
  1303. } else if (t == 26) {
  1304. if (rt->swfsize) {
  1305. if ((ret = gen_swf_verification(s, rt)) < 0)
  1306. return ret;
  1307. } else {
  1308. av_log(s, AV_LOG_WARNING, "Ignoring SWFVerification request.\n");
  1309. }
  1310. }
  1311. return 0;
  1312. }
  1313. static int handle_client_bw(URLContext *s, RTMPPacket *pkt)
  1314. {
  1315. RTMPContext *rt = s->priv_data;
  1316. if (pkt->size < 4) {
  1317. av_log(s, AV_LOG_ERROR,
  1318. "Client bandwidth report packet is less than 4 bytes long (%d)\n",
  1319. pkt->size);
  1320. return AVERROR_INVALIDDATA;
  1321. }
  1322. rt->client_report_size = AV_RB32(pkt->data);
  1323. if (rt->client_report_size <= 0) {
  1324. av_log(s, AV_LOG_ERROR, "Incorrect client bandwidth %d\n",
  1325. rt->client_report_size);
  1326. return AVERROR_INVALIDDATA;
  1327. }
  1328. av_log(s, AV_LOG_DEBUG, "Client bandwidth = %d\n", rt->client_report_size);
  1329. rt->client_report_size >>= 1;
  1330. return 0;
  1331. }
  1332. static int handle_server_bw(URLContext *s, RTMPPacket *pkt)
  1333. {
  1334. RTMPContext *rt = s->priv_data;
  1335. if (pkt->size < 4) {
  1336. av_log(s, AV_LOG_ERROR,
  1337. "Too short server bandwidth report packet (%d)\n",
  1338. pkt->size);
  1339. return AVERROR_INVALIDDATA;
  1340. }
  1341. rt->server_bw = AV_RB32(pkt->data);
  1342. if (rt->server_bw <= 0) {
  1343. av_log(s, AV_LOG_ERROR, "Incorrect server bandwidth %d\n",
  1344. rt->server_bw);
  1345. return AVERROR_INVALIDDATA;
  1346. }
  1347. av_log(s, AV_LOG_DEBUG, "Server bandwidth = %d\n", rt->server_bw);
  1348. return 0;
  1349. }
  1350. static int do_adobe_auth(RTMPContext *rt, const char *user, const char *salt,
  1351. const char *opaque, const char *challenge)
  1352. {
  1353. uint8_t hash[16];
  1354. char hashstr[AV_BASE64_SIZE(sizeof(hash))], challenge2[10];
  1355. struct AVMD5 *md5 = av_md5_alloc();
  1356. if (!md5)
  1357. return AVERROR(ENOMEM);
  1358. snprintf(challenge2, sizeof(challenge2), "%08x", av_get_random_seed());
  1359. av_md5_init(md5);
  1360. av_md5_update(md5, user, strlen(user));
  1361. av_md5_update(md5, salt, strlen(salt));
  1362. av_md5_update(md5, rt->password, strlen(rt->password));
  1363. av_md5_final(md5, hash);
  1364. av_base64_encode(hashstr, sizeof(hashstr), hash,
  1365. sizeof(hash));
  1366. av_md5_init(md5);
  1367. av_md5_update(md5, hashstr, strlen(hashstr));
  1368. if (opaque)
  1369. av_md5_update(md5, opaque, strlen(opaque));
  1370. else if (challenge)
  1371. av_md5_update(md5, challenge, strlen(challenge));
  1372. av_md5_update(md5, challenge2, strlen(challenge2));
  1373. av_md5_final(md5, hash);
  1374. av_base64_encode(hashstr, sizeof(hashstr), hash,
  1375. sizeof(hash));
  1376. snprintf(rt->auth_params, sizeof(rt->auth_params),
  1377. "?authmod=%s&user=%s&challenge=%s&response=%s",
  1378. "adobe", user, challenge2, hashstr);
  1379. if (opaque)
  1380. av_strlcatf(rt->auth_params, sizeof(rt->auth_params),
  1381. "&opaque=%s", opaque);
  1382. av_free(md5);
  1383. return 0;
  1384. }
  1385. static int do_llnw_auth(RTMPContext *rt, const char *user, const char *nonce)
  1386. {
  1387. uint8_t hash[16];
  1388. char hashstr1[33], hashstr2[33];
  1389. const char *realm = "live";
  1390. const char *method = "publish";
  1391. const char *qop = "auth";
  1392. const char *nc = "00000001";
  1393. char cnonce[10];
  1394. struct AVMD5 *md5 = av_md5_alloc();
  1395. if (!md5)
  1396. return AVERROR(ENOMEM);
  1397. snprintf(cnonce, sizeof(cnonce), "%08x", av_get_random_seed());
  1398. av_md5_init(md5);
  1399. av_md5_update(md5, user, strlen(user));
  1400. av_md5_update(md5, ":", 1);
  1401. av_md5_update(md5, realm, strlen(realm));
  1402. av_md5_update(md5, ":", 1);
  1403. av_md5_update(md5, rt->password, strlen(rt->password));
  1404. av_md5_final(md5, hash);
  1405. ff_data_to_hex(hashstr1, hash, 16, 1);
  1406. hashstr1[32] = '\0';
  1407. av_md5_init(md5);
  1408. av_md5_update(md5, method, strlen(method));
  1409. av_md5_update(md5, ":/", 2);
  1410. av_md5_update(md5, rt->app, strlen(rt->app));
  1411. if (!strchr(rt->app, '/'))
  1412. av_md5_update(md5, "/_definst_", strlen("/_definst_"));
  1413. av_md5_final(md5, hash);
  1414. ff_data_to_hex(hashstr2, hash, 16, 1);
  1415. hashstr2[32] = '\0';
  1416. av_md5_init(md5);
  1417. av_md5_update(md5, hashstr1, strlen(hashstr1));
  1418. av_md5_update(md5, ":", 1);
  1419. if (nonce)
  1420. av_md5_update(md5, nonce, strlen(nonce));
  1421. av_md5_update(md5, ":", 1);
  1422. av_md5_update(md5, nc, strlen(nc));
  1423. av_md5_update(md5, ":", 1);
  1424. av_md5_update(md5, cnonce, strlen(cnonce));
  1425. av_md5_update(md5, ":", 1);
  1426. av_md5_update(md5, qop, strlen(qop));
  1427. av_md5_update(md5, ":", 1);
  1428. av_md5_update(md5, hashstr2, strlen(hashstr2));
  1429. av_md5_final(md5, hash);
  1430. ff_data_to_hex(hashstr1, hash, 16, 1);
  1431. snprintf(rt->auth_params, sizeof(rt->auth_params),
  1432. "?authmod=%s&user=%s&nonce=%s&cnonce=%s&nc=%s&response=%s",
  1433. "llnw", user, nonce, cnonce, nc, hashstr1);
  1434. av_free(md5);
  1435. return 0;
  1436. }
  1437. static int handle_connect_error(URLContext *s, const char *desc)
  1438. {
  1439. RTMPContext *rt = s->priv_data;
  1440. char buf[300], *ptr, authmod[15];
  1441. int i = 0, ret = 0;
  1442. const char *user = "", *salt = "", *opaque = NULL,
  1443. *challenge = NULL, *cptr = NULL, *nonce = NULL;
  1444. if (!(cptr = strstr(desc, "authmod=adobe")) &&
  1445. !(cptr = strstr(desc, "authmod=llnw"))) {
  1446. av_log(s, AV_LOG_ERROR,
  1447. "Unknown connect error (unsupported authentication method?)\n");
  1448. return AVERROR_UNKNOWN;
  1449. }
  1450. cptr += strlen("authmod=");
  1451. while (*cptr && *cptr != ' ' && i < sizeof(authmod) - 1)
  1452. authmod[i++] = *cptr++;
  1453. authmod[i] = '\0';
  1454. if (!rt->username[0] || !rt->password[0]) {
  1455. av_log(s, AV_LOG_ERROR, "No credentials set\n");
  1456. return AVERROR_UNKNOWN;
  1457. }
  1458. if (strstr(desc, "?reason=authfailed")) {
  1459. av_log(s, AV_LOG_ERROR, "Incorrect username/password\n");
  1460. return AVERROR_UNKNOWN;
  1461. } else if (strstr(desc, "?reason=nosuchuser")) {
  1462. av_log(s, AV_LOG_ERROR, "Incorrect username\n");
  1463. return AVERROR_UNKNOWN;
  1464. }
  1465. if (rt->auth_tried) {
  1466. av_log(s, AV_LOG_ERROR, "Authentication failed\n");
  1467. return AVERROR_UNKNOWN;
  1468. }
  1469. rt->auth_params[0] = '\0';
  1470. if (strstr(desc, "code=403 need auth")) {
  1471. snprintf(rt->auth_params, sizeof(rt->auth_params),
  1472. "?authmod=%s&user=%s", authmod, rt->username);
  1473. return 0;
  1474. }
  1475. if (!(cptr = strstr(desc, "?reason=needauth"))) {
  1476. av_log(s, AV_LOG_ERROR, "No auth parameters found\n");
  1477. return AVERROR_UNKNOWN;
  1478. }
  1479. av_strlcpy(buf, cptr + 1, sizeof(buf));
  1480. ptr = buf;
  1481. while (ptr) {
  1482. char *next = strchr(ptr, '&');
  1483. char *value = strchr(ptr, '=');
  1484. if (next)
  1485. *next++ = '\0';
  1486. if (value)
  1487. *value++ = '\0';
  1488. if (!strcmp(ptr, "user")) {
  1489. user = value;
  1490. } else if (!strcmp(ptr, "salt")) {
  1491. salt = value;
  1492. } else if (!strcmp(ptr, "opaque")) {
  1493. opaque = value;
  1494. } else if (!strcmp(ptr, "challenge")) {
  1495. challenge = value;
  1496. } else if (!strcmp(ptr, "nonce")) {
  1497. nonce = value;
  1498. }
  1499. ptr = next;
  1500. }
  1501. if (!strcmp(authmod, "adobe")) {
  1502. if ((ret = do_adobe_auth(rt, user, salt, opaque, challenge)) < 0)
  1503. return ret;
  1504. } else {
  1505. if ((ret = do_llnw_auth(rt, user, nonce)) < 0)
  1506. return ret;
  1507. }
  1508. rt->auth_tried = 1;
  1509. return 0;
  1510. }
  1511. static int handle_invoke_error(URLContext *s, RTMPPacket *pkt)
  1512. {
  1513. RTMPContext *rt = s->priv_data;
  1514. const uint8_t *data_end = pkt->data + pkt->size;
  1515. char *tracked_method = NULL;
  1516. int level = AV_LOG_ERROR;
  1517. uint8_t tmpstr[256];
  1518. int ret;
  1519. if ((ret = find_tracked_method(s, pkt, 9, &tracked_method)) < 0)
  1520. return ret;
  1521. if (!ff_amf_get_field_value(pkt->data + 9, data_end,
  1522. "description", tmpstr, sizeof(tmpstr))) {
  1523. if (tracked_method && (!strcmp(tracked_method, "_checkbw") ||
  1524. !strcmp(tracked_method, "releaseStream") ||
  1525. !strcmp(tracked_method, "FCSubscribe") ||
  1526. !strcmp(tracked_method, "FCPublish"))) {
  1527. /* Gracefully ignore Adobe-specific historical artifact errors. */
  1528. level = AV_LOG_WARNING;
  1529. ret = 0;
  1530. } else if (tracked_method && !strcmp(tracked_method, "getStreamLength")) {
  1531. level = rt->live ? AV_LOG_DEBUG : AV_LOG_WARNING;
  1532. ret = 0;
  1533. } else if (tracked_method && !strcmp(tracked_method, "connect")) {
  1534. ret = handle_connect_error(s, tmpstr);
  1535. if (!ret) {
  1536. rt->do_reconnect = 1;
  1537. level = AV_LOG_VERBOSE;
  1538. }
  1539. } else
  1540. ret = AVERROR_UNKNOWN;
  1541. av_log(s, level, "Server error: %s\n", tmpstr);
  1542. }
  1543. av_free(tracked_method);
  1544. return ret;
  1545. }
  1546. static int write_begin(URLContext *s)
  1547. {
  1548. RTMPContext *rt = s->priv_data;
  1549. PutByteContext pbc;
  1550. RTMPPacket spkt = { 0 };
  1551. int ret;
  1552. // Send Stream Begin 1
  1553. if ((ret = ff_rtmp_packet_create(&spkt, RTMP_NETWORK_CHANNEL,
  1554. RTMP_PT_PING, 0, 6)) < 0) {
  1555. av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
  1556. return ret;
  1557. }
  1558. bytestream2_init_writer(&pbc, spkt.data, spkt.size);
  1559. bytestream2_put_be16(&pbc, 0); // 0 -> Stream Begin
  1560. bytestream2_put_be32(&pbc, rt->nb_streamid);
  1561. ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
  1562. &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
  1563. ff_rtmp_packet_destroy(&spkt);
  1564. return ret;
  1565. }
  1566. static int write_status(URLContext *s, RTMPPacket *pkt,
  1567. const char *status, const char *filename)
  1568. {
  1569. RTMPContext *rt = s->priv_data;
  1570. RTMPPacket spkt = { 0 };
  1571. char statusmsg[128];
  1572. uint8_t *pp;
  1573. int ret;
  1574. if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,
  1575. RTMP_PT_INVOKE, 0,
  1576. RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {
  1577. av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
  1578. return ret;
  1579. }
  1580. pp = spkt.data;
  1581. spkt.extra = pkt->extra;
  1582. ff_amf_write_string(&pp, "onStatus");
  1583. ff_amf_write_number(&pp, 0);
  1584. ff_amf_write_null(&pp);
  1585. ff_amf_write_object_start(&pp);
  1586. ff_amf_write_field_name(&pp, "level");
  1587. ff_amf_write_string(&pp, "status");
  1588. ff_amf_write_field_name(&pp, "code");
  1589. ff_amf_write_string(&pp, status);
  1590. ff_amf_write_field_name(&pp, "description");
  1591. snprintf(statusmsg, sizeof(statusmsg),
  1592. "%s is now published", filename);
  1593. ff_amf_write_string(&pp, statusmsg);
  1594. ff_amf_write_field_name(&pp, "details");
  1595. ff_amf_write_string(&pp, filename);
  1596. ff_amf_write_field_name(&pp, "clientid");
  1597. snprintf(statusmsg, sizeof(statusmsg), "%s", LIBAVFORMAT_IDENT);
  1598. ff_amf_write_string(&pp, statusmsg);
  1599. ff_amf_write_object_end(&pp);
  1600. spkt.size = pp - spkt.data;
  1601. ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
  1602. &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
  1603. ff_rtmp_packet_destroy(&spkt);
  1604. return ret;
  1605. }
  1606. static int send_invoke_response(URLContext *s, RTMPPacket *pkt)
  1607. {
  1608. RTMPContext *rt = s->priv_data;
  1609. double seqnum;
  1610. char filename[64];
  1611. char command[64];
  1612. int stringlen;
  1613. char *pchar;
  1614. const uint8_t *p = pkt->data;
  1615. uint8_t *pp = NULL;
  1616. RTMPPacket spkt = { 0 };
  1617. GetByteContext gbc;
  1618. int ret;
  1619. bytestream2_init(&gbc, p, pkt->size);
  1620. if (ff_amf_read_string(&gbc, command, sizeof(command),
  1621. &stringlen)) {
  1622. av_log(s, AV_LOG_ERROR, "Error in PT_INVOKE\n");
  1623. return AVERROR_INVALIDDATA;
  1624. }
  1625. ret = ff_amf_read_number(&gbc, &seqnum);
  1626. if (ret)
  1627. return ret;
  1628. ret = ff_amf_read_null(&gbc);
  1629. if (ret)
  1630. return ret;
  1631. if (!strcmp(command, "FCPublish") ||
  1632. !strcmp(command, "publish")) {
  1633. ret = ff_amf_read_string(&gbc, filename,
  1634. sizeof(filename), &stringlen);
  1635. // check with url
  1636. if (s->filename) {
  1637. pchar = strrchr(s->filename, '/');
  1638. if (!pchar) {
  1639. av_log(s, AV_LOG_WARNING,
  1640. "Unable to find / in url %s, bad format\n",
  1641. s->filename);
  1642. pchar = s->filename;
  1643. }
  1644. pchar++;
  1645. if (strcmp(pchar, filename))
  1646. av_log(s, AV_LOG_WARNING, "Unexpected stream %s, expecting"
  1647. " %s\n", filename, pchar);
  1648. }
  1649. rt->state = STATE_RECEIVING;
  1650. }
  1651. if (!strcmp(command, "FCPublish")) {
  1652. if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,
  1653. RTMP_PT_INVOKE, 0,
  1654. RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {
  1655. av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
  1656. return ret;
  1657. }
  1658. pp = spkt.data;
  1659. ff_amf_write_string(&pp, "onFCPublish");
  1660. } else if (!strcmp(command, "publish")) {
  1661. ret = write_begin(s);
  1662. if (ret < 0)
  1663. return ret;
  1664. // Send onStatus(NetStream.Publish.Start)
  1665. return write_status(s, pkt, "NetStream.Publish.Start",
  1666. filename);
  1667. } else if (!strcmp(command, "play")) {
  1668. ret = write_begin(s);
  1669. if (ret < 0)
  1670. return ret;
  1671. rt->state = STATE_SENDING;
  1672. return write_status(s, pkt, "NetStream.Play.Start",
  1673. filename);
  1674. } else {
  1675. if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,
  1676. RTMP_PT_INVOKE, 0,
  1677. RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {
  1678. av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
  1679. return ret;
  1680. }
  1681. pp = spkt.data;
  1682. ff_amf_write_string(&pp, "_result");
  1683. ff_amf_write_number(&pp, seqnum);
  1684. ff_amf_write_null(&pp);
  1685. if (!strcmp(command, "createStream")) {
  1686. rt->nb_streamid++;
  1687. if (rt->nb_streamid == 0 || rt->nb_streamid == 2)
  1688. rt->nb_streamid++; /* Values 0 and 2 are reserved */
  1689. ff_amf_write_number(&pp, rt->nb_streamid);
  1690. /* By now we don't control which streams are removed in
  1691. * deleteStream. There is no stream creation control
  1692. * if a client creates more than 2^32 - 2 streams. */
  1693. }
  1694. }
  1695. spkt.size = pp - spkt.data;
  1696. ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
  1697. &rt->prev_pkt[1], &rt->nb_prev_pkt[1]);
  1698. ff_rtmp_packet_destroy(&spkt);
  1699. return ret;
  1700. }
  1701. /**
  1702. * Read the AMF_NUMBER response ("_result") to a function call
  1703. * (e.g. createStream()). This response should be made up of the AMF_STRING
  1704. * "result", a NULL object and then the response encoded as AMF_NUMBER. On a
  1705. * successful response, we will return set the value to number (otherwise number
  1706. * will not be changed).
  1707. *
  1708. * @return 0 if reading the value succeeds, negative value otherwise
  1709. */
  1710. static int read_number_result(RTMPPacket *pkt, double *number)
  1711. {
  1712. // We only need to fit "_result" in this.
  1713. uint8_t strbuffer[8];
  1714. int stringlen;
  1715. double numbuffer;
  1716. GetByteContext gbc;
  1717. bytestream2_init(&gbc, pkt->data, pkt->size);
  1718. // Value 1/4: "_result" as AMF_STRING
  1719. if (ff_amf_read_string(&gbc, strbuffer, sizeof(strbuffer), &stringlen))
  1720. return AVERROR_INVALIDDATA;
  1721. if (strcmp(strbuffer, "_result"))
  1722. return AVERROR_INVALIDDATA;
  1723. // Value 2/4: The callee reference number
  1724. if (ff_amf_read_number(&gbc, &numbuffer))
  1725. return AVERROR_INVALIDDATA;
  1726. // Value 3/4: Null
  1727. if (ff_amf_read_null(&gbc))
  1728. return AVERROR_INVALIDDATA;
  1729. // Value 4/4: The response as AMF_NUMBER
  1730. if (ff_amf_read_number(&gbc, &numbuffer))
  1731. return AVERROR_INVALIDDATA;
  1732. else
  1733. *number = numbuffer;
  1734. return 0;
  1735. }
  1736. static int handle_invoke_result(URLContext *s, RTMPPacket *pkt)
  1737. {
  1738. RTMPContext *rt = s->priv_data;
  1739. char *tracked_method = NULL;
  1740. int ret = 0;
  1741. if ((ret = find_tracked_method(s, pkt, 10, &tracked_method)) < 0)
  1742. return ret;
  1743. if (!tracked_method) {
  1744. /* Ignore this reply when the current method is not tracked. */
  1745. return ret;
  1746. }
  1747. if (!strcmp(tracked_method, "connect")) {
  1748. if (!rt->is_input) {
  1749. if ((ret = gen_release_stream(s, rt)) < 0)
  1750. goto fail;
  1751. if ((ret = gen_fcpublish_stream(s, rt)) < 0)
  1752. goto fail;
  1753. } else {
  1754. if ((ret = gen_server_bw(s, rt)) < 0)
  1755. goto fail;
  1756. }
  1757. if ((ret = gen_create_stream(s, rt)) < 0)
  1758. goto fail;
  1759. if (rt->is_input) {
  1760. /* Send the FCSubscribe command when the name of live
  1761. * stream is defined by the user or if it's a live stream. */
  1762. if (rt->subscribe) {
  1763. if ((ret = gen_fcsubscribe_stream(s, rt, rt->subscribe)) < 0)
  1764. goto fail;
  1765. } else if (rt->live == -1) {
  1766. if ((ret = gen_fcsubscribe_stream(s, rt, rt->playpath)) < 0)
  1767. goto fail;
  1768. }
  1769. }
  1770. } else if (!strcmp(tracked_method, "createStream")) {
  1771. double stream_id;
  1772. if (read_number_result(pkt, &stream_id)) {
  1773. av_log(s, AV_LOG_WARNING, "Unexpected reply on connect()\n");
  1774. } else {
  1775. rt->stream_id = stream_id;
  1776. }
  1777. if (!rt->is_input) {
  1778. if ((ret = gen_publish(s, rt)) < 0)
  1779. goto fail;
  1780. } else {
  1781. if (rt->live != -1) {
  1782. if ((ret = gen_get_stream_length(s, rt)) < 0)
  1783. goto fail;
  1784. }
  1785. if ((ret = gen_play(s, rt)) < 0)
  1786. goto fail;
  1787. if ((ret = gen_buffer_time(s, rt)) < 0)
  1788. goto fail;
  1789. }
  1790. } else if (!strcmp(tracked_method, "getStreamLength")) {
  1791. if (read_number_result(pkt, &rt->duration)) {
  1792. av_log(s, AV_LOG_WARNING, "Unexpected reply on getStreamLength()\n");
  1793. }
  1794. }
  1795. fail:
  1796. av_free(tracked_method);
  1797. return ret;
  1798. }
  1799. static int handle_invoke_status(URLContext *s, RTMPPacket *pkt)
  1800. {
  1801. RTMPContext *rt = s->priv_data;
  1802. const uint8_t *data_end = pkt->data + pkt->size;
  1803. const uint8_t *ptr = pkt->data + RTMP_HEADER;
  1804. uint8_t tmpstr[256];
  1805. int i, t;
  1806. for (i = 0; i < 2; i++) {
  1807. t = ff_amf_tag_size(ptr, data_end);
  1808. if (t < 0)
  1809. return 1;
  1810. ptr += t;
  1811. }
  1812. t = ff_amf_get_field_value(ptr, data_end, "level", tmpstr, sizeof(tmpstr));
  1813. if (!t && !strcmp(tmpstr, "error")) {
  1814. t = ff_amf_get_field_value(ptr, data_end,
  1815. "description", tmpstr, sizeof(tmpstr));
  1816. if (t || !tmpstr[0])
  1817. t = ff_amf_get_field_value(ptr, data_end, "code",
  1818. tmpstr, sizeof(tmpstr));
  1819. if (!t)
  1820. av_log(s, AV_LOG_ERROR, "Server error: %s\n", tmpstr);
  1821. return -1;
  1822. }
  1823. t = ff_amf_get_field_value(ptr, data_end, "code", tmpstr, sizeof(tmpstr));
  1824. if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) rt->state = STATE_PLAYING;
  1825. if (!t && !strcmp(tmpstr, "NetStream.Play.Stop")) rt->state = STATE_STOPPED;
  1826. if (!t && !strcmp(tmpstr, "NetStream.Play.UnpublishNotify")) rt->state = STATE_STOPPED;
  1827. if (!t && !strcmp(tmpstr, "NetStream.Publish.Start")) rt->state = STATE_PUBLISHING;
  1828. if (!t && !strcmp(tmpstr, "NetStream.Seek.Notify")) rt->state = STATE_PLAYING;
  1829. return 0;
  1830. }
  1831. static int handle_invoke(URLContext *s, RTMPPacket *pkt)
  1832. {
  1833. RTMPContext *rt = s->priv_data;
  1834. int ret = 0;
  1835. //TODO: check for the messages sent for wrong state?
  1836. if (ff_amf_match_string(pkt->data, pkt->size, "_error")) {
  1837. if ((ret = handle_invoke_error(s, pkt)) < 0)
  1838. return ret;
  1839. } else if (ff_amf_match_string(pkt->data, pkt->size, "_result")) {
  1840. if ((ret = handle_invoke_result(s, pkt)) < 0)
  1841. return ret;
  1842. } else if (ff_amf_match_string(pkt->data, pkt->size, "onStatus")) {
  1843. if ((ret = handle_invoke_status(s, pkt)) < 0)
  1844. return ret;
  1845. } else if (ff_amf_match_string(pkt->data, pkt->size, "onBWDone")) {
  1846. if ((ret = gen_check_bw(s, rt)) < 0)
  1847. return ret;
  1848. } else if (ff_amf_match_string(pkt->data, pkt->size, "releaseStream") ||
  1849. ff_amf_match_string(pkt->data, pkt->size, "FCPublish") ||
  1850. ff_amf_match_string(pkt->data, pkt->size, "publish") ||
  1851. ff_amf_match_string(pkt->data, pkt->size, "play") ||
  1852. ff_amf_match_string(pkt->data, pkt->size, "_checkbw") ||
  1853. ff_amf_match_string(pkt->data, pkt->size, "createStream")) {
  1854. if ((ret = send_invoke_response(s, pkt)) < 0)
  1855. return ret;
  1856. }
  1857. return ret;
  1858. }
  1859. static int update_offset(RTMPContext *rt, int size)
  1860. {
  1861. int old_flv_size;
  1862. // generate packet header and put data into buffer for FLV demuxer
  1863. if (rt->flv_off < rt->flv_size) {
  1864. // There is old unread data in the buffer, thus append at the end
  1865. old_flv_size = rt->flv_size;
  1866. rt->flv_size += size;
  1867. } else {
  1868. // All data has been read, write the new data at the start of the buffer
  1869. old_flv_size = 0;
  1870. rt->flv_size = size;
  1871. rt->flv_off = 0;
  1872. }
  1873. return old_flv_size;
  1874. }
  1875. static int append_flv_data(RTMPContext *rt, RTMPPacket *pkt, int skip)
  1876. {
  1877. int old_flv_size, ret;
  1878. PutByteContext pbc;
  1879. const uint8_t *data = pkt->data + skip;
  1880. const int size = pkt->size - skip;
  1881. uint32_t ts = pkt->timestamp;
  1882. if (pkt->type == RTMP_PT_AUDIO) {
  1883. rt->has_audio = 1;
  1884. } else if (pkt->type == RTMP_PT_VIDEO) {
  1885. rt->has_video = 1;
  1886. }
  1887. old_flv_size = update_offset(rt, size + 15);
  1888. if ((ret = av_reallocp(&rt->flv_data, rt->flv_size)) < 0) {
  1889. rt->flv_size = rt->flv_off = 0;
  1890. return ret;
  1891. }
  1892. bytestream2_init_writer(&pbc, rt->flv_data, rt->flv_size);
  1893. bytestream2_skip_p(&pbc, old_flv_size);
  1894. bytestream2_put_byte(&pbc, pkt->type);
  1895. bytestream2_put_be24(&pbc, size);
  1896. bytestream2_put_be24(&pbc, ts);
  1897. bytestream2_put_byte(&pbc, ts >> 24);
  1898. bytestream2_put_be24(&pbc, 0);
  1899. bytestream2_put_buffer(&pbc, data, size);
  1900. bytestream2_put_be32(&pbc, size + RTMP_HEADER);
  1901. return 0;
  1902. }
  1903. static int handle_notify(URLContext *s, RTMPPacket *pkt)
  1904. {
  1905. RTMPContext *rt = s->priv_data;
  1906. uint8_t commandbuffer[64];
  1907. char statusmsg[128];
  1908. int stringlen, ret, skip = 0;
  1909. GetByteContext gbc;
  1910. bytestream2_init(&gbc, pkt->data, pkt->size);
  1911. if (ff_amf_read_string(&gbc, commandbuffer, sizeof(commandbuffer),
  1912. &stringlen))
  1913. return AVERROR_INVALIDDATA;
  1914. if (!strcmp(commandbuffer, "onMetaData")) {
  1915. // metadata properties should be stored in a mixed array
  1916. if (bytestream2_get_byte(&gbc) == AMF_DATA_TYPE_MIXEDARRAY) {
  1917. // We have found a metaData Array so flv can determine the streams
  1918. // from this.
  1919. rt->received_metadata = 1;
  1920. // skip 32-bit max array index
  1921. bytestream2_skip(&gbc, 4);
  1922. while (bytestream2_get_bytes_left(&gbc) > 3) {
  1923. if (ff_amf_get_string(&gbc, statusmsg, sizeof(statusmsg),
  1924. &stringlen))
  1925. return AVERROR_INVALIDDATA;
  1926. // We do not care about the content of the property (yet).
  1927. stringlen = ff_amf_tag_size(gbc.buffer, gbc.buffer_end);
  1928. if (stringlen < 0)
  1929. return AVERROR_INVALIDDATA;
  1930. bytestream2_skip(&gbc, stringlen);
  1931. // The presence of the following properties indicates that the
  1932. // respective streams are present.
  1933. if (!strcmp(statusmsg, "videocodecid")) {
  1934. rt->has_video = 1;
  1935. }
  1936. if (!strcmp(statusmsg, "audiocodecid")) {
  1937. rt->has_audio = 1;
  1938. }
  1939. }
  1940. if (bytestream2_get_be24(&gbc) != AMF_END_OF_OBJECT)
  1941. return AVERROR_INVALIDDATA;
  1942. }
  1943. }
  1944. // Skip the @setDataFrame string and validate it is a notification
  1945. if (!strcmp(commandbuffer, "@setDataFrame")) {
  1946. skip = gbc.buffer - pkt->data;
  1947. ret = ff_amf_read_string(&gbc, statusmsg,
  1948. sizeof(statusmsg), &stringlen);
  1949. if (ret < 0)
  1950. return AVERROR_INVALIDDATA;
  1951. }
  1952. return append_flv_data(rt, pkt, skip);
  1953. }
  1954. /**
  1955. * Parse received packet and possibly perform some action depending on
  1956. * the packet contents.
  1957. * @return 0 for no errors, negative values for serious errors which prevent
  1958. * further communications, positive values for uncritical errors
  1959. */
  1960. static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
  1961. {
  1962. int ret;
  1963. #ifdef DEBUG
  1964. ff_rtmp_packet_dump(s, pkt);
  1965. #endif
  1966. switch (pkt->type) {
  1967. case RTMP_PT_BYTES_READ:
  1968. av_log(s, AV_LOG_TRACE, "received bytes read report\n");
  1969. break;
  1970. case RTMP_PT_CHUNK_SIZE:
  1971. if ((ret = handle_chunk_size(s, pkt)) < 0)
  1972. return ret;
  1973. break;
  1974. case RTMP_PT_PING:
  1975. if ((ret = handle_ping(s, pkt)) < 0)
  1976. return ret;
  1977. break;
  1978. case RTMP_PT_CLIENT_BW:
  1979. if ((ret = handle_client_bw(s, pkt)) < 0)
  1980. return ret;
  1981. break;
  1982. case RTMP_PT_SERVER_BW:
  1983. if ((ret = handle_server_bw(s, pkt)) < 0)
  1984. return ret;
  1985. break;
  1986. case RTMP_PT_INVOKE:
  1987. if ((ret = handle_invoke(s, pkt)) < 0)
  1988. return ret;
  1989. break;
  1990. case RTMP_PT_VIDEO:
  1991. case RTMP_PT_AUDIO:
  1992. case RTMP_PT_METADATA:
  1993. case RTMP_PT_NOTIFY:
  1994. /* Audio, Video and Metadata packets are parsed in get_packet() */
  1995. break;
  1996. default:
  1997. av_log(s, AV_LOG_VERBOSE, "Unknown packet type received 0x%02X\n", pkt->type);
  1998. break;
  1999. }
  2000. return 0;
  2001. }
  2002. static int handle_metadata(RTMPContext *rt, RTMPPacket *pkt)
  2003. {
  2004. int ret, old_flv_size, type;
  2005. const uint8_t *next;
  2006. uint8_t *p;
  2007. uint32_t size;
  2008. uint32_t ts, cts, pts = 0;
  2009. old_flv_size = update_offset(rt, pkt->size);
  2010. if ((ret = av_reallocp(&rt->flv_data, rt->flv_size)) < 0) {
  2011. rt->flv_size = rt->flv_off = 0;
  2012. return ret;
  2013. }
  2014. next = pkt->data;
  2015. p = rt->flv_data + old_flv_size;
  2016. /* copy data while rewriting timestamps */
  2017. ts = pkt->timestamp;
  2018. while (next - pkt->data < pkt->size - RTMP_HEADER) {
  2019. type = bytestream_get_byte(&next);
  2020. size = bytestream_get_be24(&next);
  2021. cts = bytestream_get_be24(&next);
  2022. cts |= bytestream_get_byte(&next) << 24;
  2023. if (!pts)
  2024. pts = cts;
  2025. ts += cts - pts;
  2026. pts = cts;
  2027. if (size + 3 + 4 > pkt->data + pkt->size - next)
  2028. break;
  2029. bytestream_put_byte(&p, type);
  2030. bytestream_put_be24(&p, size);
  2031. bytestream_put_be24(&p, ts);
  2032. bytestream_put_byte(&p, ts >> 24);
  2033. memcpy(p, next, size + 3 + 4);
  2034. p += size + 3;
  2035. bytestream_put_be32(&p, size + RTMP_HEADER);
  2036. next += size + 3 + 4;
  2037. }
  2038. if (p != rt->flv_data + rt->flv_size) {
  2039. av_log(NULL, AV_LOG_WARNING, "Incomplete flv packets in "
  2040. "RTMP_PT_METADATA packet\n");
  2041. rt->flv_size = p - rt->flv_data;
  2042. }
  2043. return 0;
  2044. }
  2045. /**
  2046. * Interact with the server by receiving and sending RTMP packets until
  2047. * there is some significant data (media data or expected status notification).
  2048. *
  2049. * @param s reading context
  2050. * @param for_header non-zero value tells function to work until it
  2051. * gets notification from the server that playing has been started,
  2052. * otherwise function will work until some media data is received (or
  2053. * an error happens)
  2054. * @return 0 for successful operation, negative value in case of error
  2055. */
  2056. static int get_packet(URLContext *s, int for_header)
  2057. {
  2058. RTMPContext *rt = s->priv_data;
  2059. int ret;
  2060. if (rt->state == STATE_STOPPED)
  2061. return AVERROR_EOF;
  2062. for (;;) {
  2063. RTMPPacket rpkt = { 0 };
  2064. if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt,
  2065. rt->in_chunk_size, &rt->prev_pkt[0],
  2066. &rt->nb_prev_pkt[0])) <= 0) {
  2067. if (ret == 0) {
  2068. return AVERROR(EAGAIN);
  2069. } else {
  2070. return AVERROR(EIO);
  2071. }
  2072. }
  2073. // Track timestamp for later use
  2074. rt->last_timestamp = rpkt.timestamp;
  2075. rt->bytes_read += ret;
  2076. if (rt->bytes_read > rt->last_bytes_read + rt->client_report_size) {
  2077. av_log(s, AV_LOG_DEBUG, "Sending bytes read report\n");
  2078. if ((ret = gen_bytes_read(s, rt, rpkt.timestamp + 1)) < 0)
  2079. return ret;
  2080. rt->last_bytes_read = rt->bytes_read;
  2081. }
  2082. ret = rtmp_parse_result(s, rt, &rpkt);
  2083. // At this point we must check if we are in the seek state and continue
  2084. // with the next packet. handle_invoke will get us out of this state
  2085. // when the right message is encountered
  2086. if (rt->state == STATE_SEEKING) {
  2087. ff_rtmp_packet_destroy(&rpkt);
  2088. // We continue, let the natural flow of things happen:
  2089. // AVERROR(EAGAIN) or handle_invoke gets us out of here
  2090. continue;
  2091. }
  2092. if (ret < 0) {//serious error in current packet
  2093. ff_rtmp_packet_destroy(&rpkt);
  2094. return ret;
  2095. }
  2096. if (rt->do_reconnect && for_header) {
  2097. ff_rtmp_packet_destroy(&rpkt);
  2098. return 0;
  2099. }
  2100. if (rt->state == STATE_STOPPED) {
  2101. ff_rtmp_packet_destroy(&rpkt);
  2102. return AVERROR_EOF;
  2103. }
  2104. if (for_header && (rt->state == STATE_PLAYING ||
  2105. rt->state == STATE_PUBLISHING ||
  2106. rt->state == STATE_SENDING ||
  2107. rt->state == STATE_RECEIVING)) {
  2108. ff_rtmp_packet_destroy(&rpkt);
  2109. return 0;
  2110. }
  2111. if (!rpkt.size || !rt->is_input) {
  2112. ff_rtmp_packet_destroy(&rpkt);
  2113. continue;
  2114. }
  2115. if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO) {
  2116. ret = append_flv_data(rt, &rpkt, 0);
  2117. ff_rtmp_packet_destroy(&rpkt);
  2118. return ret;
  2119. } else if (rpkt.type == RTMP_PT_NOTIFY) {
  2120. ret = handle_notify(s, &rpkt);
  2121. ff_rtmp_packet_destroy(&rpkt);
  2122. return ret;
  2123. } else if (rpkt.type == RTMP_PT_METADATA) {
  2124. ret = handle_metadata(rt, &rpkt);
  2125. ff_rtmp_packet_destroy(&rpkt);
  2126. return 0;
  2127. }
  2128. ff_rtmp_packet_destroy(&rpkt);
  2129. }
  2130. }
  2131. static int rtmp_close(URLContext *h)
  2132. {
  2133. RTMPContext *rt = h->priv_data;
  2134. int ret = 0, i, j;
  2135. if (!rt->is_input) {
  2136. rt->flv_data = NULL;
  2137. if (rt->out_pkt.size)
  2138. ff_rtmp_packet_destroy(&rt->out_pkt);
  2139. if (rt->state > STATE_FCPUBLISH)
  2140. ret = gen_fcunpublish_stream(h, rt);
  2141. }
  2142. if (rt->state > STATE_HANDSHAKED)
  2143. ret = gen_delete_stream(h, rt);
  2144. for (i = 0; i < 2; i++) {
  2145. for (j = 0; j < rt->nb_prev_pkt[i]; j++)
  2146. ff_rtmp_packet_destroy(&rt->prev_pkt[i][j]);
  2147. av_freep(&rt->prev_pkt[i]);
  2148. }
  2149. free_tracked_methods(rt);
  2150. av_freep(&rt->flv_data);
  2151. ffurl_close(rt->stream);
  2152. return ret;
  2153. }
  2154. /**
  2155. * Insert a fake onMetadata packet into the FLV stream to notify the FLV
  2156. * demuxer about the duration of the stream.
  2157. *
  2158. * This should only be done if there was no real onMetadata packet sent by the
  2159. * server at the start of the stream and if we were able to retrieve a valid
  2160. * duration via a getStreamLength call.
  2161. *
  2162. * @return 0 for successful operation, negative value in case of error
  2163. */
  2164. static int inject_fake_duration_metadata(RTMPContext *rt)
  2165. {
  2166. // We need to insert the metadata packet directly after the FLV
  2167. // header, i.e. we need to move all other already read data by the
  2168. // size of our fake metadata packet.
  2169. uint8_t* p;
  2170. // Keep old flv_data pointer
  2171. uint8_t* old_flv_data = rt->flv_data;
  2172. // Allocate a new flv_data pointer with enough space for the additional package
  2173. if (!(rt->flv_data = av_malloc(rt->flv_size + 55))) {
  2174. rt->flv_data = old_flv_data;
  2175. return AVERROR(ENOMEM);
  2176. }
  2177. // Copy FLV header
  2178. memcpy(rt->flv_data, old_flv_data, 13);
  2179. // Copy remaining packets
  2180. memcpy(rt->flv_data + 13 + 55, old_flv_data + 13, rt->flv_size - 13);
  2181. // Increase the size by the injected packet
  2182. rt->flv_size += 55;
  2183. // Delete the old FLV data
  2184. av_free(old_flv_data);
  2185. p = rt->flv_data + 13;
  2186. bytestream_put_byte(&p, FLV_TAG_TYPE_META);
  2187. bytestream_put_be24(&p, 40); // size of data part (sum of all parts below)
  2188. bytestream_put_be24(&p, 0); // timestamp
  2189. bytestream_put_be32(&p, 0); // reserved
  2190. // first event name as a string
  2191. bytestream_put_byte(&p, AMF_DATA_TYPE_STRING);
  2192. // "onMetaData" as AMF string
  2193. bytestream_put_be16(&p, 10);
  2194. bytestream_put_buffer(&p, "onMetaData", 10);
  2195. // mixed array (hash) with size and string/type/data tuples
  2196. bytestream_put_byte(&p, AMF_DATA_TYPE_MIXEDARRAY);
  2197. bytestream_put_be32(&p, 1); // metadata_count
  2198. // "duration" as AMF string
  2199. bytestream_put_be16(&p, 8);
  2200. bytestream_put_buffer(&p, "duration", 8);
  2201. bytestream_put_byte(&p, AMF_DATA_TYPE_NUMBER);
  2202. bytestream_put_be64(&p, av_double2int(rt->duration));
  2203. // Finalise object
  2204. bytestream_put_be16(&p, 0); // Empty string
  2205. bytestream_put_byte(&p, AMF_END_OF_OBJECT);
  2206. bytestream_put_be32(&p, 40 + RTMP_HEADER); // size of data part (sum of all parts above)
  2207. return 0;
  2208. }
  2209. /**
  2210. * Open RTMP connection and verify that the stream can be played.
  2211. *
  2212. * URL syntax: rtmp://server[:port][/app][/playpath]
  2213. * where 'app' is first one or two directories in the path
  2214. * (e.g. /ondemand/, /flash/live/, etc.)
  2215. * and 'playpath' is a file name (the rest of the path,
  2216. * may be prefixed with "mp4:")
  2217. */
  2218. static int rtmp_open(URLContext *s, const char *uri, int flags)
  2219. {
  2220. RTMPContext *rt = s->priv_data;
  2221. char proto[8], hostname[256], path[1024], auth[100], *fname;
  2222. char *old_app, *qmark, fname_buffer[1024];
  2223. uint8_t buf[2048];
  2224. int port;
  2225. AVDictionary *opts = NULL;
  2226. int ret;
  2227. if (rt->listen_timeout > 0)
  2228. rt->listen = 1;
  2229. rt->is_input = !(flags & AVIO_FLAG_WRITE);
  2230. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  2231. hostname, sizeof(hostname), &port,
  2232. path, sizeof(path), s->filename);
  2233. if (strchr(path, ' ')) {
  2234. av_log(s, AV_LOG_WARNING,
  2235. "Detected librtmp style URL parameters, these aren't supported "
  2236. "by the libavformat internal RTMP handler currently enabled. "
  2237. "See the documentation for the correct way to pass parameters.\n");
  2238. }
  2239. if (auth[0]) {
  2240. char *ptr = strchr(auth, ':');
  2241. if (ptr) {
  2242. *ptr = '\0';
  2243. av_strlcpy(rt->username, auth, sizeof(rt->username));
  2244. av_strlcpy(rt->password, ptr + 1, sizeof(rt->password));
  2245. }
  2246. }
  2247. if (rt->listen && strcmp(proto, "rtmp")) {
  2248. av_log(s, AV_LOG_ERROR, "rtmp_listen not available for %s\n",
  2249. proto);
  2250. return AVERROR(EINVAL);
  2251. }
  2252. if (!strcmp(proto, "rtmpt") || !strcmp(proto, "rtmpts")) {
  2253. if (!strcmp(proto, "rtmpts"))
  2254. av_dict_set(&opts, "ffrtmphttp_tls", "1", 1);
  2255. /* open the http tunneling connection */
  2256. ff_url_join(buf, sizeof(buf), "ffrtmphttp", NULL, hostname, port, NULL);
  2257. } else if (!strcmp(proto, "rtmps")) {
  2258. /* open the tls connection */
  2259. if (port < 0)
  2260. port = RTMPS_DEFAULT_PORT;
  2261. ff_url_join(buf, sizeof(buf), "tls", NULL, hostname, port, NULL);
  2262. } else if (!strcmp(proto, "rtmpe") || (!strcmp(proto, "rtmpte"))) {
  2263. if (!strcmp(proto, "rtmpte"))
  2264. av_dict_set(&opts, "ffrtmpcrypt_tunneling", "1", 1);
  2265. /* open the encrypted connection */
  2266. ff_url_join(buf, sizeof(buf), "ffrtmpcrypt", NULL, hostname, port, NULL);
  2267. rt->encrypted = 1;
  2268. } else {
  2269. /* open the tcp connection */
  2270. if (port < 0)
  2271. port = RTMP_DEFAULT_PORT;
  2272. if (rt->listen)
  2273. ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port,
  2274. "?listen&listen_timeout=%d",
  2275. rt->listen_timeout * 1000);
  2276. else
  2277. ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
  2278. }
  2279. reconnect:
  2280. if ((ret = ffurl_open(&rt->stream, buf, AVIO_FLAG_READ_WRITE,
  2281. &s->interrupt_callback, &opts, s->protocols, s)) < 0) {
  2282. av_log(s , AV_LOG_ERROR, "Cannot open connection %s\n", buf);
  2283. goto fail;
  2284. }
  2285. if (rt->swfverify) {
  2286. if ((ret = rtmp_calc_swfhash(s)) < 0)
  2287. goto fail;
  2288. }
  2289. rt->state = STATE_START;
  2290. if (!rt->listen && (ret = rtmp_handshake(s, rt)) < 0)
  2291. goto fail;
  2292. if (rt->listen && (ret = rtmp_server_handshake(s, rt)) < 0)
  2293. goto fail;
  2294. rt->out_chunk_size = 128;
  2295. rt->in_chunk_size = 128; // Probably overwritten later
  2296. rt->state = STATE_HANDSHAKED;
  2297. // Keep the application name when it has been defined by the user.
  2298. old_app = rt->app;
  2299. rt->app = av_malloc(APP_MAX_LENGTH);
  2300. if (!rt->app) {
  2301. ret = AVERROR(ENOMEM);
  2302. goto fail;
  2303. }
  2304. //extract "app" part from path
  2305. qmark = strchr(path, '?');
  2306. if (qmark && strstr(qmark, "slist=")) {
  2307. char* amp;
  2308. // After slist we have the playpath, the full path is used as app
  2309. av_strlcpy(rt->app, path + 1, APP_MAX_LENGTH);
  2310. fname = strstr(path, "slist=") + 6;
  2311. // Strip any further query parameters from fname
  2312. amp = strchr(fname, '&');
  2313. if (amp) {
  2314. av_strlcpy(fname_buffer, fname, FFMIN(amp - fname + 1,
  2315. sizeof(fname_buffer)));
  2316. fname = fname_buffer;
  2317. }
  2318. } else if (!strncmp(path, "/ondemand/", 10)) {
  2319. fname = path + 10;
  2320. memcpy(rt->app, "ondemand", 9);
  2321. } else {
  2322. char *next = *path ? path + 1 : path;
  2323. char *p = strchr(next, '/');
  2324. if (!p) {
  2325. fname = next;
  2326. rt->app[0] = '\0';
  2327. } else {
  2328. // make sure we do not mismatch a playpath for an application instance
  2329. char *c = strchr(p + 1, ':');
  2330. fname = strchr(p + 1, '/');
  2331. if (!fname || (c && c < fname)) {
  2332. fname = p + 1;
  2333. av_strlcpy(rt->app, path + 1, FFMIN(p - path, APP_MAX_LENGTH));
  2334. } else {
  2335. fname++;
  2336. av_strlcpy(rt->app, path + 1, FFMIN(fname - path - 1, APP_MAX_LENGTH));
  2337. }
  2338. }
  2339. }
  2340. if (old_app) {
  2341. // The name of application has been defined by the user, override it.
  2342. av_free(rt->app);
  2343. rt->app = old_app;
  2344. }
  2345. if (!rt->playpath) {
  2346. int len = strlen(fname);
  2347. rt->playpath = av_malloc(PLAYPATH_MAX_LENGTH);
  2348. if (!rt->playpath) {
  2349. ret = AVERROR(ENOMEM);
  2350. goto fail;
  2351. }
  2352. if (!strchr(fname, ':') && len >= 4 &&
  2353. (!strcmp(fname + len - 4, ".f4v") ||
  2354. !strcmp(fname + len - 4, ".mp4"))) {
  2355. memcpy(rt->playpath, "mp4:", 5);
  2356. } else {
  2357. if (len >= 4 && !strcmp(fname + len - 4, ".flv"))
  2358. fname[len - 4] = '\0';
  2359. rt->playpath[0] = 0;
  2360. }
  2361. av_strlcat(rt->playpath, fname, PLAYPATH_MAX_LENGTH);
  2362. }
  2363. if (!rt->tcurl) {
  2364. rt->tcurl = av_malloc(TCURL_MAX_LENGTH);
  2365. if (!rt->tcurl) {
  2366. ret = AVERROR(ENOMEM);
  2367. goto fail;
  2368. }
  2369. ff_url_join(rt->tcurl, TCURL_MAX_LENGTH, proto, NULL, hostname,
  2370. port, "/%s", rt->app);
  2371. }
  2372. if (!rt->flashver) {
  2373. rt->flashver = av_malloc(FLASHVER_MAX_LENGTH);
  2374. if (!rt->flashver) {
  2375. ret = AVERROR(ENOMEM);
  2376. goto fail;
  2377. }
  2378. if (rt->is_input) {
  2379. snprintf(rt->flashver, FLASHVER_MAX_LENGTH, "%s %d,%d,%d,%d",
  2380. RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1, RTMP_CLIENT_VER2,
  2381. RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);
  2382. } else {
  2383. snprintf(rt->flashver, FLASHVER_MAX_LENGTH,
  2384. "FMLE/3.0 (compatible; %s)", LIBAVFORMAT_IDENT);
  2385. }
  2386. }
  2387. rt->client_report_size = 1048576;
  2388. rt->bytes_read = 0;
  2389. rt->has_audio = 0;
  2390. rt->has_video = 0;
  2391. rt->received_metadata = 0;
  2392. rt->last_bytes_read = 0;
  2393. rt->server_bw = 2500000;
  2394. rt->duration = 0;
  2395. av_log(s, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",
  2396. proto, path, rt->app, rt->playpath);
  2397. if (!rt->listen) {
  2398. if ((ret = gen_connect(s, rt)) < 0)
  2399. goto fail;
  2400. } else {
  2401. if ((ret = read_connect(s, s->priv_data)) < 0)
  2402. goto fail;
  2403. }
  2404. do {
  2405. ret = get_packet(s, 1);
  2406. } while (ret == AVERROR(EAGAIN));
  2407. if (ret < 0)
  2408. goto fail;
  2409. if (rt->do_reconnect) {
  2410. int i;
  2411. ffurl_close(rt->stream);
  2412. rt->stream = NULL;
  2413. rt->do_reconnect = 0;
  2414. rt->nb_invokes = 0;
  2415. for (i = 0; i < 2; i++)
  2416. memset(rt->prev_pkt[i], 0,
  2417. sizeof(**rt->prev_pkt) * rt->nb_prev_pkt[i]);
  2418. free_tracked_methods(rt);
  2419. goto reconnect;
  2420. }
  2421. if (rt->is_input) {
  2422. // generate FLV header for demuxer
  2423. rt->flv_size = 13;
  2424. if ((ret = av_reallocp(&rt->flv_data, rt->flv_size)) < 0)
  2425. goto fail;
  2426. rt->flv_off = 0;
  2427. memcpy(rt->flv_data, "FLV\1\0\0\0\0\011\0\0\0\0", rt->flv_size);
  2428. // Read packets until we reach the first A/V packet or read metadata.
  2429. // If there was a metadata package in front of the A/V packets, we can
  2430. // build the FLV header from this. If we do not receive any metadata,
  2431. // the FLV decoder will allocate the needed streams when their first
  2432. // audio or video packet arrives.
  2433. while (!rt->has_audio && !rt->has_video && !rt->received_metadata) {
  2434. if ((ret = get_packet(s, 0)) < 0)
  2435. goto fail;
  2436. }
  2437. // Either after we have read the metadata or (if there is none) the
  2438. // first packet of an A/V stream, we have a better knowledge about the
  2439. // streams, so set the FLV header accordingly.
  2440. if (rt->has_audio) {
  2441. rt->flv_data[4] |= FLV_HEADER_FLAG_HASAUDIO;
  2442. }
  2443. if (rt->has_video) {
  2444. rt->flv_data[4] |= FLV_HEADER_FLAG_HASVIDEO;
  2445. }
  2446. // If we received the first packet of an A/V stream and no metadata but
  2447. // the server returned a valid duration, create a fake metadata packet
  2448. // to inform the FLV decoder about the duration.
  2449. if (!rt->received_metadata && rt->duration > 0) {
  2450. if ((ret = inject_fake_duration_metadata(rt)) < 0)
  2451. goto fail;
  2452. }
  2453. } else {
  2454. rt->flv_size = 0;
  2455. rt->flv_data = NULL;
  2456. rt->flv_off = 0;
  2457. rt->skip_bytes = 13;
  2458. }
  2459. s->max_packet_size = rt->stream->max_packet_size;
  2460. s->is_streamed = 1;
  2461. return 0;
  2462. fail:
  2463. av_dict_free(&opts);
  2464. rtmp_close(s);
  2465. return ret;
  2466. }
  2467. static int rtmp_read(URLContext *s, uint8_t *buf, int size)
  2468. {
  2469. RTMPContext *rt = s->priv_data;
  2470. int orig_size = size;
  2471. int ret;
  2472. while (size > 0) {
  2473. int data_left = rt->flv_size - rt->flv_off;
  2474. if (data_left >= size) {
  2475. memcpy(buf, rt->flv_data + rt->flv_off, size);
  2476. rt->flv_off += size;
  2477. return orig_size;
  2478. }
  2479. if (data_left > 0) {
  2480. memcpy(buf, rt->flv_data + rt->flv_off, data_left);
  2481. buf += data_left;
  2482. size -= data_left;
  2483. rt->flv_off = rt->flv_size;
  2484. return data_left;
  2485. }
  2486. if ((ret = get_packet(s, 0)) < 0)
  2487. return ret;
  2488. }
  2489. return orig_size;
  2490. }
  2491. static int64_t rtmp_seek(URLContext *s, int stream_index, int64_t timestamp,
  2492. int flags)
  2493. {
  2494. RTMPContext *rt = s->priv_data;
  2495. int ret;
  2496. av_log(s, AV_LOG_DEBUG,
  2497. "Seek on stream index %d at timestamp %"PRId64" with flags %08x\n",
  2498. stream_index, timestamp, flags);
  2499. if ((ret = gen_seek(s, rt, timestamp)) < 0) {
  2500. av_log(s, AV_LOG_ERROR,
  2501. "Unable to send seek command on stream index %d at timestamp "
  2502. "%"PRId64" with flags %08x\n",
  2503. stream_index, timestamp, flags);
  2504. return ret;
  2505. }
  2506. rt->flv_off = rt->flv_size;
  2507. rt->state = STATE_SEEKING;
  2508. return timestamp;
  2509. }
  2510. static int rtmp_pause(URLContext *s, int pause)
  2511. {
  2512. RTMPContext *rt = s->priv_data;
  2513. int ret;
  2514. av_log(s, AV_LOG_DEBUG, "Pause at timestamp %d\n",
  2515. rt->last_timestamp);
  2516. if ((ret = gen_pause(s, rt, pause, rt->last_timestamp)) < 0) {
  2517. av_log(s, AV_LOG_ERROR, "Unable to send pause command at timestamp %d\n",
  2518. rt->last_timestamp);
  2519. return ret;
  2520. }
  2521. return 0;
  2522. }
  2523. static int rtmp_write(URLContext *s, const uint8_t *buf, int size)
  2524. {
  2525. RTMPContext *rt = s->priv_data;
  2526. int size_temp = size;
  2527. int pktsize, pkttype, copy;
  2528. uint32_t ts;
  2529. const uint8_t *buf_temp = buf;
  2530. uint8_t c;
  2531. int ret;
  2532. do {
  2533. if (rt->skip_bytes) {
  2534. int skip = FFMIN(rt->skip_bytes, size_temp);
  2535. buf_temp += skip;
  2536. size_temp -= skip;
  2537. rt->skip_bytes -= skip;
  2538. continue;
  2539. }
  2540. if (rt->flv_header_bytes < RTMP_HEADER) {
  2541. const uint8_t *header = rt->flv_header;
  2542. int channel = RTMP_AUDIO_CHANNEL;
  2543. copy = FFMIN(RTMP_HEADER - rt->flv_header_bytes, size_temp);
  2544. bytestream_get_buffer(&buf_temp, rt->flv_header + rt->flv_header_bytes, copy);
  2545. rt->flv_header_bytes += copy;
  2546. size_temp -= copy;
  2547. if (rt->flv_header_bytes < RTMP_HEADER)
  2548. break;
  2549. pkttype = bytestream_get_byte(&header);
  2550. pktsize = bytestream_get_be24(&header);
  2551. ts = bytestream_get_be24(&header);
  2552. ts |= bytestream_get_byte(&header) << 24;
  2553. bytestream_get_be24(&header);
  2554. rt->flv_size = pktsize;
  2555. if (pkttype == RTMP_PT_VIDEO)
  2556. channel = RTMP_VIDEO_CHANNEL;
  2557. if (((pkttype == RTMP_PT_VIDEO || pkttype == RTMP_PT_AUDIO) && ts == 0) ||
  2558. pkttype == RTMP_PT_NOTIFY) {
  2559. if ((ret = ff_rtmp_check_alloc_array(&rt->prev_pkt[1],
  2560. &rt->nb_prev_pkt[1],
  2561. channel)) < 0)
  2562. return ret;
  2563. // Force sending a full 12 bytes header by clearing the
  2564. // channel id, to make it not match a potential earlier
  2565. // packet in the same channel.
  2566. rt->prev_pkt[1][channel].channel_id = 0;
  2567. }
  2568. //this can be a big packet, it's better to send it right here
  2569. if ((ret = ff_rtmp_packet_create(&rt->out_pkt, channel,
  2570. pkttype, ts, pktsize)) < 0)
  2571. return ret;
  2572. rt->out_pkt.extra = rt->stream_id;
  2573. rt->flv_data = rt->out_pkt.data;
  2574. }
  2575. copy = FFMIN(rt->flv_size - rt->flv_off, size_temp);
  2576. bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, copy);
  2577. rt->flv_off += copy;
  2578. size_temp -= copy;
  2579. if (rt->flv_off == rt->flv_size) {
  2580. rt->skip_bytes = 4;
  2581. if (rt->out_pkt.type == RTMP_PT_NOTIFY) {
  2582. // For onMetaData and |RtmpSampleAccess packets, we want
  2583. // @setDataFrame prepended to the packet before it gets sent.
  2584. // However, not all RTMP_PT_NOTIFY packets (e.g., onTextData
  2585. // and onCuePoint).
  2586. uint8_t commandbuffer[64];
  2587. int stringlen = 0;
  2588. GetByteContext gbc;
  2589. bytestream2_init(&gbc, rt->flv_data, rt->flv_size);
  2590. if (!ff_amf_read_string(&gbc, commandbuffer, sizeof(commandbuffer),
  2591. &stringlen)) {
  2592. if (!strcmp(commandbuffer, "onMetaData") ||
  2593. !strcmp(commandbuffer, "|RtmpSampleAccess")) {
  2594. uint8_t *ptr;
  2595. if ((ret = av_reallocp(&rt->out_pkt.data, rt->out_pkt.size + 16)) < 0) {
  2596. rt->flv_size = rt->flv_off = rt->flv_header_bytes = 0;
  2597. return ret;
  2598. }
  2599. memmove(rt->out_pkt.data + 16, rt->out_pkt.data, rt->out_pkt.size);
  2600. rt->out_pkt.size += 16;
  2601. ptr = rt->out_pkt.data;
  2602. ff_amf_write_string(&ptr, "@setDataFrame");
  2603. }
  2604. }
  2605. }
  2606. if ((ret = rtmp_send_packet(rt, &rt->out_pkt, 0)) < 0)
  2607. return ret;
  2608. rt->flv_size = 0;
  2609. rt->flv_off = 0;
  2610. rt->flv_header_bytes = 0;
  2611. rt->flv_nb_packets++;
  2612. }
  2613. } while (buf_temp - buf < size);
  2614. if (rt->flv_nb_packets < rt->flush_interval)
  2615. return size;
  2616. rt->flv_nb_packets = 0;
  2617. /* set stream into nonblocking mode */
  2618. rt->stream->flags |= AVIO_FLAG_NONBLOCK;
  2619. /* try to read one byte from the stream */
  2620. ret = ffurl_read(rt->stream, &c, 1);
  2621. /* switch the stream back into blocking mode */
  2622. rt->stream->flags &= ~AVIO_FLAG_NONBLOCK;
  2623. if (ret == AVERROR(EAGAIN)) {
  2624. /* no incoming data to handle */
  2625. return size;
  2626. } else if (ret < 0) {
  2627. return ret;
  2628. } else if (ret == 1) {
  2629. RTMPPacket rpkt = { 0 };
  2630. if ((ret = ff_rtmp_packet_read_internal(rt->stream, &rpkt,
  2631. rt->in_chunk_size,
  2632. &rt->prev_pkt[0],
  2633. &rt->nb_prev_pkt[0], c)) <= 0)
  2634. return ret;
  2635. if ((ret = rtmp_parse_result(s, rt, &rpkt)) < 0)
  2636. return ret;
  2637. ff_rtmp_packet_destroy(&rpkt);
  2638. }
  2639. return size;
  2640. }
  2641. #define OFFSET(x) offsetof(RTMPContext, x)
  2642. #define DEC AV_OPT_FLAG_DECODING_PARAM
  2643. #define ENC AV_OPT_FLAG_ENCODING_PARAM
  2644. static const AVOption rtmp_options[] = {
  2645. {"rtmp_app", "Name of application to connect to on the RTMP server", OFFSET(app), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
  2646. {"rtmp_buffer", "Set buffer time in milliseconds. The default is 3000.", OFFSET(client_buffer_time), AV_OPT_TYPE_INT, {.i64 = 3000}, 0, INT_MAX, DEC|ENC},
  2647. {"rtmp_conn", "Append arbitrary AMF data to the Connect message", OFFSET(conn), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
  2648. {"rtmp_flashver", "Version of the Flash plugin used to run the SWF player.", OFFSET(flashver), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
  2649. {"rtmp_flush_interval", "Number of packets flushed in the same request (RTMPT only).", OFFSET(flush_interval), AV_OPT_TYPE_INT, {.i64 = 10}, 0, INT_MAX, ENC},
  2650. {"rtmp_live", "Specify that the media is a live stream.", OFFSET(live), AV_OPT_TYPE_INT, {.i64 = -2}, INT_MIN, INT_MAX, DEC, "rtmp_live"},
  2651. {"any", "both", 0, AV_OPT_TYPE_CONST, {.i64 = -2}, 0, 0, DEC, "rtmp_live"},
  2652. {"live", "live stream", 0, AV_OPT_TYPE_CONST, {.i64 = -1}, 0, 0, DEC, "rtmp_live"},
  2653. {"recorded", "recorded stream", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, DEC, "rtmp_live"},
  2654. {"rtmp_pageurl", "URL of the web page in which the media was embedded. By default no value will be sent.", OFFSET(pageurl), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC},
  2655. {"rtmp_playpath", "Stream identifier to play or to publish", OFFSET(playpath), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
  2656. {"rtmp_subscribe", "Name of live stream to subscribe to. Defaults to rtmp_playpath.", OFFSET(subscribe), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC},
  2657. {"rtmp_swfhash", "SHA256 hash of the decompressed SWF file (32 bytes).", OFFSET(swfhash), AV_OPT_TYPE_BINARY, .flags = DEC},
  2658. {"rtmp_swfsize", "Size of the decompressed SWF file, required for SWFVerification.", OFFSET(swfsize), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC},
  2659. {"rtmp_swfurl", "URL of the SWF player. By default no value will be sent", OFFSET(swfurl), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
  2660. {"rtmp_swfverify", "URL to player swf file, compute hash/size automatically.", OFFSET(swfverify), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC},
  2661. {"rtmp_tcurl", "URL of the target stream. Defaults to proto://host[:port]/app.", OFFSET(tcurl), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
  2662. {"rtmp_listen", "Listen for incoming rtmp connections", OFFSET(listen), AV_OPT_TYPE_INT, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtmp_listen" },
  2663. {"listen", "Listen for incoming rtmp connections", OFFSET(listen), AV_OPT_TYPE_INT, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtmp_listen" },
  2664. {"timeout", "Maximum timeout (in seconds) to wait for incoming connections. -1 is infinite. Implies -rtmp_listen 1", OFFSET(listen_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, INT_MIN, INT_MAX, DEC, "rtmp_listen" },
  2665. { NULL },
  2666. };
  2667. #define RTMP_PROTOCOL(flavor) \
  2668. static const AVClass flavor##_class = { \
  2669. .class_name = #flavor, \
  2670. .item_name = av_default_item_name, \
  2671. .option = rtmp_options, \
  2672. .version = LIBAVUTIL_VERSION_INT, \
  2673. }; \
  2674. \
  2675. const URLProtocol ff_##flavor##_protocol = { \
  2676. .name = #flavor, \
  2677. .url_open = rtmp_open, \
  2678. .url_read = rtmp_read, \
  2679. .url_read_seek = rtmp_seek, \
  2680. .url_read_pause = rtmp_pause, \
  2681. .url_write = rtmp_write, \
  2682. .url_close = rtmp_close, \
  2683. .priv_data_size = sizeof(RTMPContext), \
  2684. .flags = URL_PROTOCOL_FLAG_NETWORK, \
  2685. .priv_data_class= &flavor##_class, \
  2686. };
  2687. RTMP_PROTOCOL(rtmp)
  2688. RTMP_PROTOCOL(rtmpe)
  2689. RTMP_PROTOCOL(rtmps)
  2690. RTMP_PROTOCOL(rtmpt)
  2691. RTMP_PROTOCOL(rtmpte)
  2692. RTMP_PROTOCOL(rtmpts)