rtmpproto.c 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460
  1. /*
  2. * RTMP network protocol
  3. * Copyright (c) 2009 Kostya Shishkov
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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/intfloat.h"
  28. #include "libavutil/lfg.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/random_seed.h"
  31. #include "libavutil/sha.h"
  32. #include "avformat.h"
  33. #include "internal.h"
  34. #include "network.h"
  35. #include "flv.h"
  36. #include "rtmp.h"
  37. #include "rtmpcrypt.h"
  38. #include "rtmppkt.h"
  39. #include "url.h"
  40. #if CONFIG_ZLIB
  41. #include <zlib.h>
  42. #endif
  43. //#define DEBUG
  44. #define APP_MAX_LENGTH 1024
  45. #define PLAYPATH_MAX_LENGTH 256
  46. #define TCURL_MAX_LENGTH 512
  47. #define FLASHVER_MAX_LENGTH 64
  48. #define RTMP_PKTDATA_DEFAULT_SIZE 4096
  49. /** RTMP protocol handler state */
  50. typedef enum {
  51. STATE_START, ///< client has not done anything yet
  52. STATE_HANDSHAKED, ///< client has performed handshake
  53. STATE_FCPUBLISH, ///< client FCPublishing stream (for output)
  54. STATE_PLAYING, ///< client has started receiving multimedia data from server
  55. STATE_PUBLISHING, ///< client has started sending multimedia data to server (for output)
  56. STATE_RECEIVING, ///< received a publish command (for input)
  57. STATE_STOPPED, ///< the broadcast has been stopped
  58. } ClientState;
  59. typedef struct TrackedMethod {
  60. char *name;
  61. int id;
  62. } TrackedMethod;
  63. /** protocol handler context */
  64. typedef struct RTMPContext {
  65. const AVClass *class;
  66. URLContext* stream; ///< TCP stream used in interactions with RTMP server
  67. RTMPPacket prev_pkt[2][RTMP_CHANNELS]; ///< packet history used when reading and sending packets
  68. int in_chunk_size; ///< size of the chunks incoming RTMP packets are divided into
  69. int out_chunk_size; ///< size of the chunks outgoing RTMP packets are divided into
  70. int is_input; ///< input/output flag
  71. char *playpath; ///< stream identifier to play (with possible "mp4:" prefix)
  72. int live; ///< 0: recorded, -1: live, -2: both
  73. char *app; ///< name of application
  74. char *conn; ///< append arbitrary AMF data to the Connect message
  75. ClientState state; ///< current state
  76. int main_channel_id; ///< an additional channel ID which is used for some invocations
  77. uint8_t* flv_data; ///< buffer with data for demuxer
  78. int flv_size; ///< current buffer size
  79. int flv_off; ///< number of bytes read from current buffer
  80. int flv_nb_packets; ///< number of flv packets published
  81. RTMPPacket out_pkt; ///< rtmp packet, created from flv a/v or metadata (for output)
  82. uint32_t client_report_size; ///< number of bytes after which client should report to server
  83. uint32_t bytes_read; ///< number of bytes read from server
  84. uint32_t last_bytes_read; ///< number of bytes read last reported to server
  85. int skip_bytes; ///< number of bytes to skip from the input FLV stream in the next write call
  86. uint8_t flv_header[11]; ///< partial incoming flv packet header
  87. int flv_header_bytes; ///< number of initialized bytes in flv_header
  88. int nb_invokes; ///< keeps track of invoke messages
  89. char* tcurl; ///< url of the target stream
  90. char* flashver; ///< version of the flash plugin
  91. char* swfhash; ///< SHA256 hash of the decompressed SWF file (32 bytes)
  92. int swfhash_len; ///< length of the SHA256 hash
  93. int swfsize; ///< size of the decompressed SWF file
  94. char* swfurl; ///< url of the swf player
  95. char* swfverify; ///< URL to player swf file, compute hash/size automatically
  96. char swfverification[42]; ///< hash of the SWF verification
  97. char* pageurl; ///< url of the web page
  98. char* subscribe; ///< name of live stream to subscribe
  99. int server_bw; ///< server bandwidth
  100. int client_buffer_time; ///< client buffer time in ms
  101. int flush_interval; ///< number of packets flushed in the same request (RTMPT only)
  102. int encrypted; ///< use an encrypted connection (RTMPE only)
  103. TrackedMethod*tracked_methods; ///< tracked methods buffer
  104. int nb_tracked_methods; ///< number of tracked methods
  105. int tracked_methods_size; ///< size of the tracked methods buffer
  106. int listen; ///< listen mode flag
  107. int listen_timeout; ///< listen timeout to wait for new connections
  108. int nb_streamid; ///< The next stream id to return on createStream calls
  109. } RTMPContext;
  110. #define PLAYER_KEY_OPEN_PART_LEN 30 ///< length of partial key used for first client digest signing
  111. /** Client key used for digest signing */
  112. static const uint8_t rtmp_player_key[] = {
  113. 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
  114. 'F', 'l', 'a', 's', 'h', ' ', 'P', 'l', 'a', 'y', 'e', 'r', ' ', '0', '0', '1',
  115. 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
  116. 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
  117. 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
  118. };
  119. #define SERVER_KEY_OPEN_PART_LEN 36 ///< length of partial key used for first server digest signing
  120. /** Key used for RTMP server digest signing */
  121. static const uint8_t rtmp_server_key[] = {
  122. 'G', 'e', 'n', 'u', 'i', 'n', 'e', ' ', 'A', 'd', 'o', 'b', 'e', ' ',
  123. 'F', 'l', 'a', 's', 'h', ' ', 'M', 'e', 'd', 'i', 'a', ' ',
  124. 'S', 'e', 'r', 'v', 'e', 'r', ' ', '0', '0', '1',
  125. 0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8, 0x2E, 0x00, 0xD0, 0xD1, 0x02,
  126. 0x9E, 0x7E, 0x57, 0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB, 0x93, 0xB8,
  127. 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
  128. };
  129. static int add_tracked_method(RTMPContext *rt, const char *name, int id)
  130. {
  131. void *ptr;
  132. if (rt->nb_tracked_methods + 1 > rt->tracked_methods_size) {
  133. rt->tracked_methods_size = (rt->nb_tracked_methods + 1) * 2;
  134. ptr = av_realloc(rt->tracked_methods,
  135. rt->tracked_methods_size * sizeof(*rt->tracked_methods));
  136. if (!ptr)
  137. return AVERROR(ENOMEM);
  138. rt->tracked_methods = ptr;
  139. }
  140. rt->tracked_methods[rt->nb_tracked_methods].name = av_strdup(name);
  141. if (!rt->tracked_methods[rt->nb_tracked_methods].name)
  142. return AVERROR(ENOMEM);
  143. rt->tracked_methods[rt->nb_tracked_methods].id = id;
  144. rt->nb_tracked_methods++;
  145. return 0;
  146. }
  147. static void del_tracked_method(RTMPContext *rt, int index)
  148. {
  149. memmove(&rt->tracked_methods[index], &rt->tracked_methods[index + 1],
  150. sizeof(*rt->tracked_methods) * (rt->nb_tracked_methods - index - 1));
  151. rt->nb_tracked_methods--;
  152. }
  153. static int find_tracked_method(URLContext *s, RTMPPacket *pkt, int offset,
  154. char **tracked_method)
  155. {
  156. RTMPContext *rt = s->priv_data;
  157. GetByteContext gbc;
  158. double pkt_id;
  159. int ret;
  160. int i;
  161. bytestream2_init(&gbc, pkt->data + offset, pkt->data_size - offset);
  162. if ((ret = ff_amf_read_number(&gbc, &pkt_id)) < 0)
  163. return ret;
  164. for (i = 0; i < rt->nb_tracked_methods; i++) {
  165. if (rt->tracked_methods[i].id != pkt_id)
  166. continue;
  167. *tracked_method = rt->tracked_methods[i].name;
  168. del_tracked_method(rt, i);
  169. break;
  170. }
  171. return 0;
  172. }
  173. static void free_tracked_methods(RTMPContext *rt)
  174. {
  175. int i;
  176. for (i = 0; i < rt->nb_tracked_methods; i ++)
  177. av_free(rt->tracked_methods[i].name);
  178. av_free(rt->tracked_methods);
  179. }
  180. static int rtmp_send_packet(RTMPContext *rt, RTMPPacket *pkt, int track)
  181. {
  182. int ret;
  183. if (pkt->type == RTMP_PT_INVOKE && track) {
  184. GetByteContext gbc;
  185. char name[128];
  186. double pkt_id;
  187. int len;
  188. bytestream2_init(&gbc, pkt->data, pkt->data_size);
  189. if ((ret = ff_amf_read_string(&gbc, name, sizeof(name), &len)) < 0)
  190. goto fail;
  191. if ((ret = ff_amf_read_number(&gbc, &pkt_id)) < 0)
  192. goto fail;
  193. if ((ret = add_tracked_method(rt, name, pkt_id)) < 0)
  194. goto fail;
  195. }
  196. ret = ff_rtmp_packet_write(rt->stream, pkt, rt->out_chunk_size,
  197. rt->prev_pkt[1]);
  198. fail:
  199. ff_rtmp_packet_destroy(pkt);
  200. return ret;
  201. }
  202. static int rtmp_write_amf_data(URLContext *s, char *param, uint8_t **p)
  203. {
  204. char *field, *value;
  205. char type;
  206. /* The type must be B for Boolean, N for number, S for string, O for
  207. * object, or Z for null. For Booleans the data must be either 0 or 1 for
  208. * FALSE or TRUE, respectively. Likewise for Objects the data must be
  209. * 0 or 1 to end or begin an object, respectively. Data items in subobjects
  210. * may be named, by prefixing the type with 'N' and specifying the name
  211. * before the value (ie. NB:myFlag:1). This option may be used multiple times
  212. * to construct arbitrary AMF sequences. */
  213. if (param[0] && param[1] == ':') {
  214. type = param[0];
  215. value = param + 2;
  216. } else if (param[0] == 'N' && param[1] && param[2] == ':') {
  217. type = param[1];
  218. field = param + 3;
  219. value = strchr(field, ':');
  220. if (!value)
  221. goto fail;
  222. *value = '\0';
  223. value++;
  224. if (!field || !value)
  225. goto fail;
  226. ff_amf_write_field_name(p, field);
  227. } else {
  228. goto fail;
  229. }
  230. switch (type) {
  231. case 'B':
  232. ff_amf_write_bool(p, value[0] != '0');
  233. break;
  234. case 'S':
  235. ff_amf_write_string(p, value);
  236. break;
  237. case 'N':
  238. ff_amf_write_number(p, strtod(value, NULL));
  239. break;
  240. case 'Z':
  241. ff_amf_write_null(p);
  242. break;
  243. case 'O':
  244. if (value[0] != '0')
  245. ff_amf_write_object_start(p);
  246. else
  247. ff_amf_write_object_end(p);
  248. break;
  249. default:
  250. goto fail;
  251. break;
  252. }
  253. return 0;
  254. fail:
  255. av_log(s, AV_LOG_ERROR, "Invalid AMF parameter: %s\n", param);
  256. return AVERROR(EINVAL);
  257. }
  258. /**
  259. * Generate 'connect' call and send it to the server.
  260. */
  261. static int gen_connect(URLContext *s, RTMPContext *rt)
  262. {
  263. RTMPPacket pkt;
  264. uint8_t *p;
  265. int ret;
  266. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  267. 0, 4096 + APP_MAX_LENGTH)) < 0)
  268. return ret;
  269. p = pkt.data;
  270. ff_amf_write_string(&p, "connect");
  271. ff_amf_write_number(&p, ++rt->nb_invokes);
  272. ff_amf_write_object_start(&p);
  273. ff_amf_write_field_name(&p, "app");
  274. ff_amf_write_string(&p, rt->app);
  275. if (!rt->is_input) {
  276. ff_amf_write_field_name(&p, "type");
  277. ff_amf_write_string(&p, "nonprivate");
  278. }
  279. ff_amf_write_field_name(&p, "flashVer");
  280. ff_amf_write_string(&p, rt->flashver);
  281. if (rt->swfurl) {
  282. ff_amf_write_field_name(&p, "swfUrl");
  283. ff_amf_write_string(&p, rt->swfurl);
  284. }
  285. ff_amf_write_field_name(&p, "tcUrl");
  286. ff_amf_write_string(&p, rt->tcurl);
  287. if (rt->is_input) {
  288. ff_amf_write_field_name(&p, "fpad");
  289. ff_amf_write_bool(&p, 0);
  290. ff_amf_write_field_name(&p, "capabilities");
  291. ff_amf_write_number(&p, 15.0);
  292. /* Tell the server we support all the audio codecs except
  293. * SUPPORT_SND_INTEL (0x0008) and SUPPORT_SND_UNUSED (0x0010)
  294. * which are unused in the RTMP protocol implementation. */
  295. ff_amf_write_field_name(&p, "audioCodecs");
  296. ff_amf_write_number(&p, 4071.0);
  297. ff_amf_write_field_name(&p, "videoCodecs");
  298. ff_amf_write_number(&p, 252.0);
  299. ff_amf_write_field_name(&p, "videoFunction");
  300. ff_amf_write_number(&p, 1.0);
  301. if (rt->pageurl) {
  302. ff_amf_write_field_name(&p, "pageUrl");
  303. ff_amf_write_string(&p, rt->pageurl);
  304. }
  305. }
  306. ff_amf_write_object_end(&p);
  307. if (rt->conn) {
  308. char *param = rt->conn;
  309. // Write arbitrary AMF data to the Connect message.
  310. while (param != NULL) {
  311. char *sep;
  312. param += strspn(param, " ");
  313. if (!*param)
  314. break;
  315. sep = strchr(param, ' ');
  316. if (sep)
  317. *sep = '\0';
  318. if ((ret = rtmp_write_amf_data(s, param, &p)) < 0) {
  319. // Invalid AMF parameter.
  320. ff_rtmp_packet_destroy(&pkt);
  321. return ret;
  322. }
  323. if (sep)
  324. param = sep + 1;
  325. else
  326. break;
  327. }
  328. }
  329. pkt.data_size = p - pkt.data;
  330. return rtmp_send_packet(rt, &pkt, 1);
  331. }
  332. static int read_connect(URLContext *s, RTMPContext *rt)
  333. {
  334. RTMPPacket pkt = { 0 };
  335. uint8_t *p;
  336. const uint8_t *cp;
  337. int ret;
  338. char command[64];
  339. int stringlen;
  340. double seqnum;
  341. uint8_t tmpstr[256];
  342. GetByteContext gbc;
  343. if ((ret = ff_rtmp_packet_read(rt->stream, &pkt, rt->in_chunk_size,
  344. rt->prev_pkt[1])) < 0)
  345. return ret;
  346. cp = pkt.data;
  347. bytestream2_init(&gbc, cp, pkt.data_size);
  348. if (ff_amf_read_string(&gbc, command, sizeof(command), &stringlen)) {
  349. av_log(s, AV_LOG_ERROR, "Unable to read command string\n");
  350. ff_rtmp_packet_destroy(&pkt);
  351. return AVERROR_INVALIDDATA;
  352. }
  353. if (strcmp(command, "connect")) {
  354. av_log(s, AV_LOG_ERROR, "Expecting connect, got %s\n", command);
  355. ff_rtmp_packet_destroy(&pkt);
  356. return AVERROR_INVALIDDATA;
  357. }
  358. ret = ff_amf_read_number(&gbc, &seqnum);
  359. if (ret)
  360. av_log(s, AV_LOG_WARNING, "SeqNum not found\n");
  361. /* Here one could parse an AMF Object with data as flashVers and others. */
  362. ret = ff_amf_get_field_value(gbc.buffer,
  363. gbc.buffer + bytestream2_get_bytes_left(&gbc),
  364. "app", tmpstr, sizeof(tmpstr));
  365. if (ret)
  366. av_log(s, AV_LOG_WARNING, "App field not found in connect\n");
  367. if (!ret && strcmp(tmpstr, rt->app))
  368. av_log(s, AV_LOG_WARNING, "App field don't match up: %s <-> %s\n",
  369. tmpstr, rt->app);
  370. ff_rtmp_packet_destroy(&pkt);
  371. // Send Window Acknowledgement Size (as defined in speficication)
  372. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
  373. RTMP_PT_SERVER_BW, 0, 4)) < 0)
  374. return ret;
  375. p = pkt.data;
  376. bytestream_put_be32(&p, rt->server_bw);
  377. pkt.data_size = p - pkt.data;
  378. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  379. rt->prev_pkt[1]);
  380. ff_rtmp_packet_destroy(&pkt);
  381. if (ret < 0)
  382. return ret;
  383. // Send Peer Bandwidth
  384. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
  385. RTMP_PT_CLIENT_BW, 0, 5)) < 0)
  386. return ret;
  387. p = pkt.data;
  388. bytestream_put_be32(&p, rt->server_bw);
  389. bytestream_put_byte(&p, 2); // dynamic
  390. pkt.data_size = p - pkt.data;
  391. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  392. rt->prev_pkt[1]);
  393. ff_rtmp_packet_destroy(&pkt);
  394. if (ret < 0)
  395. return ret;
  396. // Ping request
  397. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL,
  398. RTMP_PT_PING, 0, 6)) < 0)
  399. return ret;
  400. p = pkt.data;
  401. bytestream_put_be16(&p, 0); // 0 -> Stream Begin
  402. bytestream_put_be32(&p, 0);
  403. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  404. rt->prev_pkt[1]);
  405. ff_rtmp_packet_destroy(&pkt);
  406. if (ret < 0)
  407. return ret;
  408. // Chunk size
  409. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL,
  410. RTMP_PT_CHUNK_SIZE, 0, 4)) < 0)
  411. return ret;
  412. p = pkt.data;
  413. bytestream_put_be32(&p, rt->out_chunk_size);
  414. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  415. rt->prev_pkt[1]);
  416. ff_rtmp_packet_destroy(&pkt);
  417. if (ret < 0)
  418. return ret;
  419. // Send result_ NetConnection.Connect.Success to connect
  420. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL,
  421. RTMP_PT_INVOKE, 0,
  422. RTMP_PKTDATA_DEFAULT_SIZE)) < 0)
  423. return ret;
  424. p = pkt.data;
  425. ff_amf_write_string(&p, "_result");
  426. ff_amf_write_number(&p, seqnum);
  427. ff_amf_write_object_start(&p);
  428. ff_amf_write_field_name(&p, "fmsVer");
  429. ff_amf_write_string(&p, "FMS/3,0,1,123");
  430. ff_amf_write_field_name(&p, "capabilities");
  431. ff_amf_write_number(&p, 31);
  432. ff_amf_write_object_end(&p);
  433. ff_amf_write_object_start(&p);
  434. ff_amf_write_field_name(&p, "level");
  435. ff_amf_write_string(&p, "status");
  436. ff_amf_write_field_name(&p, "code");
  437. ff_amf_write_string(&p, "NetConnection.Connect.Success");
  438. ff_amf_write_field_name(&p, "description");
  439. ff_amf_write_string(&p, "Connection succeeded.");
  440. ff_amf_write_field_name(&p, "objectEncoding");
  441. ff_amf_write_number(&p, 0);
  442. ff_amf_write_object_end(&p);
  443. pkt.data_size = p - pkt.data;
  444. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  445. rt->prev_pkt[1]);
  446. ff_rtmp_packet_destroy(&pkt);
  447. if (ret < 0)
  448. return ret;
  449. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL,
  450. RTMP_PT_INVOKE, 0, 30)) < 0)
  451. return ret;
  452. p = pkt.data;
  453. ff_amf_write_string(&p, "onBWDone");
  454. ff_amf_write_number(&p, 0);
  455. ff_amf_write_null(&p);
  456. ff_amf_write_number(&p, 8192);
  457. pkt.data_size = p - pkt.data;
  458. ret = ff_rtmp_packet_write(rt->stream, &pkt, rt->out_chunk_size,
  459. rt->prev_pkt[1]);
  460. ff_rtmp_packet_destroy(&pkt);
  461. return ret;
  462. }
  463. /**
  464. * Generate 'releaseStream' call and send it to the server. It should make
  465. * the server release some channel for media streams.
  466. */
  467. static int gen_release_stream(URLContext *s, RTMPContext *rt)
  468. {
  469. RTMPPacket pkt;
  470. uint8_t *p;
  471. int ret;
  472. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  473. 0, 29 + strlen(rt->playpath))) < 0)
  474. return ret;
  475. av_log(s, AV_LOG_DEBUG, "Releasing stream...\n");
  476. p = pkt.data;
  477. ff_amf_write_string(&p, "releaseStream");
  478. ff_amf_write_number(&p, ++rt->nb_invokes);
  479. ff_amf_write_null(&p);
  480. ff_amf_write_string(&p, rt->playpath);
  481. return rtmp_send_packet(rt, &pkt, 1);
  482. }
  483. /**
  484. * Generate 'FCPublish' call and send it to the server. It should make
  485. * the server preapare for receiving media streams.
  486. */
  487. static int gen_fcpublish_stream(URLContext *s, RTMPContext *rt)
  488. {
  489. RTMPPacket pkt;
  490. uint8_t *p;
  491. int ret;
  492. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  493. 0, 25 + strlen(rt->playpath))) < 0)
  494. return ret;
  495. av_log(s, AV_LOG_DEBUG, "FCPublish stream...\n");
  496. p = pkt.data;
  497. ff_amf_write_string(&p, "FCPublish");
  498. ff_amf_write_number(&p, ++rt->nb_invokes);
  499. ff_amf_write_null(&p);
  500. ff_amf_write_string(&p, rt->playpath);
  501. return rtmp_send_packet(rt, &pkt, 1);
  502. }
  503. /**
  504. * Generate 'FCUnpublish' call and send it to the server. It should make
  505. * the server destroy stream.
  506. */
  507. static int gen_fcunpublish_stream(URLContext *s, RTMPContext *rt)
  508. {
  509. RTMPPacket pkt;
  510. uint8_t *p;
  511. int ret;
  512. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  513. 0, 27 + strlen(rt->playpath))) < 0)
  514. return ret;
  515. av_log(s, AV_LOG_DEBUG, "UnPublishing stream...\n");
  516. p = pkt.data;
  517. ff_amf_write_string(&p, "FCUnpublish");
  518. ff_amf_write_number(&p, ++rt->nb_invokes);
  519. ff_amf_write_null(&p);
  520. ff_amf_write_string(&p, rt->playpath);
  521. return rtmp_send_packet(rt, &pkt, 0);
  522. }
  523. /**
  524. * Generate 'createStream' call and send it to the server. It should make
  525. * the server allocate some channel for media streams.
  526. */
  527. static int gen_create_stream(URLContext *s, RTMPContext *rt)
  528. {
  529. RTMPPacket pkt;
  530. uint8_t *p;
  531. int ret;
  532. av_log(s, AV_LOG_DEBUG, "Creating stream...\n");
  533. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  534. 0, 25)) < 0)
  535. return ret;
  536. p = pkt.data;
  537. ff_amf_write_string(&p, "createStream");
  538. ff_amf_write_number(&p, ++rt->nb_invokes);
  539. ff_amf_write_null(&p);
  540. return rtmp_send_packet(rt, &pkt, 1);
  541. }
  542. /**
  543. * Generate 'deleteStream' call and send it to the server. It should make
  544. * the server remove some channel for media streams.
  545. */
  546. static int gen_delete_stream(URLContext *s, RTMPContext *rt)
  547. {
  548. RTMPPacket pkt;
  549. uint8_t *p;
  550. int ret;
  551. av_log(s, AV_LOG_DEBUG, "Deleting stream...\n");
  552. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  553. 0, 34)) < 0)
  554. return ret;
  555. p = pkt.data;
  556. ff_amf_write_string(&p, "deleteStream");
  557. ff_amf_write_number(&p, ++rt->nb_invokes);
  558. ff_amf_write_null(&p);
  559. ff_amf_write_number(&p, rt->main_channel_id);
  560. return rtmp_send_packet(rt, &pkt, 0);
  561. }
  562. /**
  563. * Generate client buffer time and send it to the server.
  564. */
  565. static int gen_buffer_time(URLContext *s, RTMPContext *rt)
  566. {
  567. RTMPPacket pkt;
  568. uint8_t *p;
  569. int ret;
  570. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING,
  571. 1, 10)) < 0)
  572. return ret;
  573. p = pkt.data;
  574. bytestream_put_be16(&p, 3);
  575. bytestream_put_be32(&p, rt->main_channel_id);
  576. bytestream_put_be32(&p, rt->client_buffer_time);
  577. return rtmp_send_packet(rt, &pkt, 0);
  578. }
  579. /**
  580. * Generate 'play' call and send it to the server, then ping the server
  581. * to start actual playing.
  582. */
  583. static int gen_play(URLContext *s, RTMPContext *rt)
  584. {
  585. RTMPPacket pkt;
  586. uint8_t *p;
  587. int ret;
  588. av_log(s, AV_LOG_DEBUG, "Sending play command for '%s'\n", rt->playpath);
  589. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_VIDEO_CHANNEL, RTMP_PT_INVOKE,
  590. 0, 29 + strlen(rt->playpath))) < 0)
  591. return ret;
  592. pkt.extra = rt->main_channel_id;
  593. p = pkt.data;
  594. ff_amf_write_string(&p, "play");
  595. ff_amf_write_number(&p, ++rt->nb_invokes);
  596. ff_amf_write_null(&p);
  597. ff_amf_write_string(&p, rt->playpath);
  598. ff_amf_write_number(&p, rt->live);
  599. return rtmp_send_packet(rt, &pkt, 1);
  600. }
  601. /**
  602. * Generate 'publish' call and send it to the server.
  603. */
  604. static int gen_publish(URLContext *s, RTMPContext *rt)
  605. {
  606. RTMPPacket pkt;
  607. uint8_t *p;
  608. int ret;
  609. av_log(s, AV_LOG_DEBUG, "Sending publish command for '%s'\n", rt->playpath);
  610. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SOURCE_CHANNEL, RTMP_PT_INVOKE,
  611. 0, 30 + strlen(rt->playpath))) < 0)
  612. return ret;
  613. pkt.extra = rt->main_channel_id;
  614. p = pkt.data;
  615. ff_amf_write_string(&p, "publish");
  616. ff_amf_write_number(&p, ++rt->nb_invokes);
  617. ff_amf_write_null(&p);
  618. ff_amf_write_string(&p, rt->playpath);
  619. ff_amf_write_string(&p, "live");
  620. return rtmp_send_packet(rt, &pkt, 1);
  621. }
  622. /**
  623. * Generate ping reply and send it to the server.
  624. */
  625. static int gen_pong(URLContext *s, RTMPContext *rt, RTMPPacket *ppkt)
  626. {
  627. RTMPPacket pkt;
  628. uint8_t *p;
  629. int ret;
  630. if (ppkt->data_size < 6) {
  631. av_log(s, AV_LOG_ERROR, "Too short ping packet (%d)\n",
  632. ppkt->data_size);
  633. return AVERROR_INVALIDDATA;
  634. }
  635. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING,
  636. ppkt->timestamp + 1, 6)) < 0)
  637. return ret;
  638. p = pkt.data;
  639. bytestream_put_be16(&p, 7);
  640. bytestream_put_be32(&p, AV_RB32(ppkt->data+2));
  641. return rtmp_send_packet(rt, &pkt, 0);
  642. }
  643. /**
  644. * Generate SWF verification message and send it to the server.
  645. */
  646. static int gen_swf_verification(URLContext *s, RTMPContext *rt)
  647. {
  648. RTMPPacket pkt;
  649. uint8_t *p;
  650. int ret;
  651. av_log(s, AV_LOG_DEBUG, "Sending SWF verification...\n");
  652. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_PING,
  653. 0, 44)) < 0)
  654. return ret;
  655. p = pkt.data;
  656. bytestream_put_be16(&p, 27);
  657. memcpy(p, rt->swfverification, 42);
  658. return rtmp_send_packet(rt, &pkt, 0);
  659. }
  660. /**
  661. * Generate server bandwidth message and send it to the server.
  662. */
  663. static int gen_server_bw(URLContext *s, RTMPContext *rt)
  664. {
  665. RTMPPacket pkt;
  666. uint8_t *p;
  667. int ret;
  668. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_SERVER_BW,
  669. 0, 4)) < 0)
  670. return ret;
  671. p = pkt.data;
  672. bytestream_put_be32(&p, rt->server_bw);
  673. return rtmp_send_packet(rt, &pkt, 0);
  674. }
  675. /**
  676. * Generate check bandwidth message and send it to the server.
  677. */
  678. static int gen_check_bw(URLContext *s, RTMPContext *rt)
  679. {
  680. RTMPPacket pkt;
  681. uint8_t *p;
  682. int ret;
  683. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  684. 0, 21)) < 0)
  685. return ret;
  686. p = pkt.data;
  687. ff_amf_write_string(&p, "_checkbw");
  688. ff_amf_write_number(&p, ++rt->nb_invokes);
  689. ff_amf_write_null(&p);
  690. return rtmp_send_packet(rt, &pkt, 1);
  691. }
  692. /**
  693. * Generate report on bytes read so far and send it to the server.
  694. */
  695. static int gen_bytes_read(URLContext *s, RTMPContext *rt, uint32_t ts)
  696. {
  697. RTMPPacket pkt;
  698. uint8_t *p;
  699. int ret;
  700. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_NETWORK_CHANNEL, RTMP_PT_BYTES_READ,
  701. ts, 4)) < 0)
  702. return ret;
  703. p = pkt.data;
  704. bytestream_put_be32(&p, rt->bytes_read);
  705. return rtmp_send_packet(rt, &pkt, 0);
  706. }
  707. static int gen_fcsubscribe_stream(URLContext *s, RTMPContext *rt,
  708. const char *subscribe)
  709. {
  710. RTMPPacket pkt;
  711. uint8_t *p;
  712. int ret;
  713. if ((ret = ff_rtmp_packet_create(&pkt, RTMP_SYSTEM_CHANNEL, RTMP_PT_INVOKE,
  714. 0, 27 + strlen(subscribe))) < 0)
  715. return ret;
  716. p = pkt.data;
  717. ff_amf_write_string(&p, "FCSubscribe");
  718. ff_amf_write_number(&p, ++rt->nb_invokes);
  719. ff_amf_write_null(&p);
  720. ff_amf_write_string(&p, subscribe);
  721. return rtmp_send_packet(rt, &pkt, 1);
  722. }
  723. int ff_rtmp_calc_digest(const uint8_t *src, int len, int gap,
  724. const uint8_t *key, int keylen, uint8_t *dst)
  725. {
  726. struct AVSHA *sha;
  727. uint8_t hmac_buf[64+32] = {0};
  728. int i;
  729. sha = av_mallocz(av_sha_size);
  730. if (!sha)
  731. return AVERROR(ENOMEM);
  732. if (keylen < 64) {
  733. memcpy(hmac_buf, key, keylen);
  734. } else {
  735. av_sha_init(sha, 256);
  736. av_sha_update(sha,key, keylen);
  737. av_sha_final(sha, hmac_buf);
  738. }
  739. for (i = 0; i < 64; i++)
  740. hmac_buf[i] ^= HMAC_IPAD_VAL;
  741. av_sha_init(sha, 256);
  742. av_sha_update(sha, hmac_buf, 64);
  743. if (gap <= 0) {
  744. av_sha_update(sha, src, len);
  745. } else { //skip 32 bytes used for storing digest
  746. av_sha_update(sha, src, gap);
  747. av_sha_update(sha, src + gap + 32, len - gap - 32);
  748. }
  749. av_sha_final(sha, hmac_buf + 64);
  750. for (i = 0; i < 64; i++)
  751. hmac_buf[i] ^= HMAC_IPAD_VAL ^ HMAC_OPAD_VAL; //reuse XORed key for opad
  752. av_sha_init(sha, 256);
  753. av_sha_update(sha, hmac_buf, 64+32);
  754. av_sha_final(sha, dst);
  755. av_free(sha);
  756. return 0;
  757. }
  758. int ff_rtmp_calc_digest_pos(const uint8_t *buf, int off, int mod_val,
  759. int add_val)
  760. {
  761. int i, digest_pos = 0;
  762. for (i = 0; i < 4; i++)
  763. digest_pos += buf[i + off];
  764. digest_pos = digest_pos % mod_val + add_val;
  765. return digest_pos;
  766. }
  767. /**
  768. * Put HMAC-SHA2 digest of packet data (except for the bytes where this digest
  769. * will be stored) into that packet.
  770. *
  771. * @param buf handshake data (1536 bytes)
  772. * @param encrypted use an encrypted connection (RTMPE)
  773. * @return offset to the digest inside input data
  774. */
  775. static int rtmp_handshake_imprint_with_digest(uint8_t *buf, int encrypted)
  776. {
  777. int ret, digest_pos;
  778. if (encrypted)
  779. digest_pos = ff_rtmp_calc_digest_pos(buf, 772, 728, 776);
  780. else
  781. digest_pos = ff_rtmp_calc_digest_pos(buf, 8, 728, 12);
  782. ret = ff_rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
  783. rtmp_player_key, PLAYER_KEY_OPEN_PART_LEN,
  784. buf + digest_pos);
  785. if (ret < 0)
  786. return ret;
  787. return digest_pos;
  788. }
  789. /**
  790. * Verify that the received server response has the expected digest value.
  791. *
  792. * @param buf handshake data received from the server (1536 bytes)
  793. * @param off position to search digest offset from
  794. * @return 0 if digest is valid, digest position otherwise
  795. */
  796. static int rtmp_validate_digest(uint8_t *buf, int off)
  797. {
  798. uint8_t digest[32];
  799. int ret, digest_pos;
  800. digest_pos = ff_rtmp_calc_digest_pos(buf, off, 728, off + 4);
  801. ret = ff_rtmp_calc_digest(buf, RTMP_HANDSHAKE_PACKET_SIZE, digest_pos,
  802. rtmp_server_key, SERVER_KEY_OPEN_PART_LEN,
  803. digest);
  804. if (ret < 0)
  805. return ret;
  806. if (!memcmp(digest, buf + digest_pos, 32))
  807. return digest_pos;
  808. return 0;
  809. }
  810. static int rtmp_calc_swf_verification(URLContext *s, RTMPContext *rt,
  811. uint8_t *buf)
  812. {
  813. uint8_t *p;
  814. int ret;
  815. if (rt->swfhash_len != 32) {
  816. av_log(s, AV_LOG_ERROR,
  817. "Hash of the decompressed SWF file is not 32 bytes long.\n");
  818. return AVERROR(EINVAL);
  819. }
  820. p = &rt->swfverification[0];
  821. bytestream_put_byte(&p, 1);
  822. bytestream_put_byte(&p, 1);
  823. bytestream_put_be32(&p, rt->swfsize);
  824. bytestream_put_be32(&p, rt->swfsize);
  825. if ((ret = ff_rtmp_calc_digest(rt->swfhash, 32, 0, buf, 32, p)) < 0)
  826. return ret;
  827. return 0;
  828. }
  829. #if CONFIG_ZLIB
  830. static int rtmp_uncompress_swfplayer(uint8_t *in_data, int64_t in_size,
  831. uint8_t **out_data, int64_t *out_size)
  832. {
  833. z_stream zs = { 0 };
  834. void *ptr;
  835. int size;
  836. int ret = 0;
  837. zs.avail_in = in_size;
  838. zs.next_in = in_data;
  839. ret = inflateInit(&zs);
  840. if (ret != Z_OK)
  841. return AVERROR_UNKNOWN;
  842. do {
  843. uint8_t tmp_buf[16384];
  844. zs.avail_out = sizeof(tmp_buf);
  845. zs.next_out = tmp_buf;
  846. ret = inflate(&zs, Z_NO_FLUSH);
  847. if (ret != Z_OK && ret != Z_STREAM_END) {
  848. ret = AVERROR_UNKNOWN;
  849. goto fail;
  850. }
  851. size = sizeof(tmp_buf) - zs.avail_out;
  852. if (!(ptr = av_realloc(*out_data, *out_size + size))) {
  853. ret = AVERROR(ENOMEM);
  854. goto fail;
  855. }
  856. *out_data = ptr;
  857. memcpy(*out_data + *out_size, tmp_buf, size);
  858. *out_size += size;
  859. } while (zs.avail_out == 0);
  860. fail:
  861. inflateEnd(&zs);
  862. return ret;
  863. }
  864. #endif
  865. static int rtmp_calc_swfhash(URLContext *s)
  866. {
  867. RTMPContext *rt = s->priv_data;
  868. uint8_t *in_data = NULL, *out_data = NULL, *swfdata;
  869. int64_t in_size, out_size;
  870. URLContext *stream;
  871. char swfhash[32];
  872. int swfsize;
  873. int ret = 0;
  874. /* Get the SWF player file. */
  875. if ((ret = ffurl_open(&stream, rt->swfverify, AVIO_FLAG_READ,
  876. &s->interrupt_callback, NULL)) < 0) {
  877. av_log(s, AV_LOG_ERROR, "Cannot open connection %s.\n", rt->swfverify);
  878. goto fail;
  879. }
  880. if ((in_size = ffurl_seek(stream, 0, AVSEEK_SIZE)) < 0) {
  881. ret = AVERROR(EIO);
  882. goto fail;
  883. }
  884. if (!(in_data = av_malloc(in_size))) {
  885. ret = AVERROR(ENOMEM);
  886. goto fail;
  887. }
  888. if ((ret = ffurl_read_complete(stream, in_data, in_size)) < 0)
  889. goto fail;
  890. if (in_size < 3) {
  891. ret = AVERROR_INVALIDDATA;
  892. goto fail;
  893. }
  894. if (!memcmp(in_data, "CWS", 3)) {
  895. /* Decompress the SWF player file using Zlib. */
  896. if (!(out_data = av_malloc(8))) {
  897. ret = AVERROR(ENOMEM);
  898. goto fail;
  899. }
  900. *in_data = 'F'; // magic stuff
  901. memcpy(out_data, in_data, 8);
  902. out_size = 8;
  903. #if CONFIG_ZLIB
  904. if ((ret = rtmp_uncompress_swfplayer(in_data + 8, in_size - 8,
  905. &out_data, &out_size)) < 0)
  906. goto fail;
  907. #else
  908. av_log(s, AV_LOG_ERROR,
  909. "Zlib is required for decompressing the SWF player file.\n");
  910. ret = AVERROR(EINVAL);
  911. goto fail;
  912. #endif
  913. swfsize = out_size;
  914. swfdata = out_data;
  915. } else {
  916. swfsize = in_size;
  917. swfdata = in_data;
  918. }
  919. /* Compute the SHA256 hash of the SWF player file. */
  920. if ((ret = ff_rtmp_calc_digest(swfdata, swfsize, 0,
  921. "Genuine Adobe Flash Player 001", 30,
  922. swfhash)) < 0)
  923. goto fail;
  924. /* Set SWFVerification parameters. */
  925. av_opt_set_bin(rt, "rtmp_swfhash", swfhash, 32, 0);
  926. rt->swfsize = swfsize;
  927. fail:
  928. av_freep(&in_data);
  929. av_freep(&out_data);
  930. ffurl_close(stream);
  931. return ret;
  932. }
  933. /**
  934. * Perform handshake with the server by means of exchanging pseudorandom data
  935. * signed with HMAC-SHA2 digest.
  936. *
  937. * @return 0 if handshake succeeds, negative value otherwise
  938. */
  939. static int rtmp_handshake(URLContext *s, RTMPContext *rt)
  940. {
  941. AVLFG rnd;
  942. uint8_t tosend [RTMP_HANDSHAKE_PACKET_SIZE+1] = {
  943. 3, // unencrypted data
  944. 0, 0, 0, 0, // client uptime
  945. RTMP_CLIENT_VER1,
  946. RTMP_CLIENT_VER2,
  947. RTMP_CLIENT_VER3,
  948. RTMP_CLIENT_VER4,
  949. };
  950. uint8_t clientdata[RTMP_HANDSHAKE_PACKET_SIZE];
  951. uint8_t serverdata[RTMP_HANDSHAKE_PACKET_SIZE+1];
  952. int i;
  953. int server_pos, client_pos;
  954. uint8_t digest[32], signature[32];
  955. int ret, type = 0;
  956. av_log(s, AV_LOG_DEBUG, "Handshaking...\n");
  957. av_lfg_init(&rnd, 0xDEADC0DE);
  958. // generate handshake packet - 1536 bytes of pseudorandom data
  959. for (i = 9; i <= RTMP_HANDSHAKE_PACKET_SIZE; i++)
  960. tosend[i] = av_lfg_get(&rnd) >> 24;
  961. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  962. /* When the client wants to use RTMPE, we have to change the command
  963. * byte to 0x06 which means to use encrypted data and we have to set
  964. * the flash version to at least 9.0.115.0. */
  965. tosend[0] = 6;
  966. tosend[5] = 128;
  967. tosend[6] = 0;
  968. tosend[7] = 3;
  969. tosend[8] = 2;
  970. /* Initialize the Diffie-Hellmann context and generate the public key
  971. * to send to the server. */
  972. if ((ret = ff_rtmpe_gen_pub_key(rt->stream, tosend + 1)) < 0)
  973. return ret;
  974. }
  975. client_pos = rtmp_handshake_imprint_with_digest(tosend + 1, rt->encrypted);
  976. if (client_pos < 0)
  977. return client_pos;
  978. if ((ret = ffurl_write(rt->stream, tosend,
  979. RTMP_HANDSHAKE_PACKET_SIZE + 1)) < 0) {
  980. av_log(s, AV_LOG_ERROR, "Cannot write RTMP handshake request\n");
  981. return ret;
  982. }
  983. if ((ret = ffurl_read_complete(rt->stream, serverdata,
  984. RTMP_HANDSHAKE_PACKET_SIZE + 1)) < 0) {
  985. av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
  986. return ret;
  987. }
  988. if ((ret = ffurl_read_complete(rt->stream, clientdata,
  989. RTMP_HANDSHAKE_PACKET_SIZE)) < 0) {
  990. av_log(s, AV_LOG_ERROR, "Cannot read RTMP handshake response\n");
  991. return ret;
  992. }
  993. av_log(s, AV_LOG_DEBUG, "Type answer %d\n", serverdata[0]);
  994. av_log(s, AV_LOG_DEBUG, "Server version %d.%d.%d.%d\n",
  995. serverdata[5], serverdata[6], serverdata[7], serverdata[8]);
  996. if (rt->is_input && serverdata[5] >= 3) {
  997. server_pos = rtmp_validate_digest(serverdata + 1, 772);
  998. if (server_pos < 0)
  999. return server_pos;
  1000. if (!server_pos) {
  1001. type = 1;
  1002. server_pos = rtmp_validate_digest(serverdata + 1, 8);
  1003. if (server_pos < 0)
  1004. return server_pos;
  1005. if (!server_pos) {
  1006. av_log(s, AV_LOG_ERROR, "Server response validating failed\n");
  1007. return AVERROR(EIO);
  1008. }
  1009. }
  1010. /* Generate SWFVerification token (SHA256 HMAC hash of decompressed SWF,
  1011. * key are the last 32 bytes of the server handshake. */
  1012. if (rt->swfsize) {
  1013. if ((ret = rtmp_calc_swf_verification(s, rt, serverdata + 1 +
  1014. RTMP_HANDSHAKE_PACKET_SIZE - 32)) < 0)
  1015. return ret;
  1016. }
  1017. ret = ff_rtmp_calc_digest(tosend + 1 + client_pos, 32, 0,
  1018. rtmp_server_key, sizeof(rtmp_server_key),
  1019. digest);
  1020. if (ret < 0)
  1021. return ret;
  1022. ret = ff_rtmp_calc_digest(clientdata, RTMP_HANDSHAKE_PACKET_SIZE - 32,
  1023. 0, digest, 32, signature);
  1024. if (ret < 0)
  1025. return ret;
  1026. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1027. /* Compute the shared secret key sent by the server and initialize
  1028. * the RC4 encryption. */
  1029. if ((ret = ff_rtmpe_compute_secret_key(rt->stream, serverdata + 1,
  1030. tosend + 1, type)) < 0)
  1031. return ret;
  1032. /* Encrypt the signature received by the server. */
  1033. ff_rtmpe_encrypt_sig(rt->stream, signature, digest, serverdata[0]);
  1034. }
  1035. if (memcmp(signature, clientdata + RTMP_HANDSHAKE_PACKET_SIZE - 32, 32)) {
  1036. av_log(s, AV_LOG_ERROR, "Signature mismatch\n");
  1037. return AVERROR(EIO);
  1038. }
  1039. for (i = 0; i < RTMP_HANDSHAKE_PACKET_SIZE; i++)
  1040. tosend[i] = av_lfg_get(&rnd) >> 24;
  1041. ret = ff_rtmp_calc_digest(serverdata + 1 + server_pos, 32, 0,
  1042. rtmp_player_key, sizeof(rtmp_player_key),
  1043. digest);
  1044. if (ret < 0)
  1045. return ret;
  1046. ret = ff_rtmp_calc_digest(tosend, RTMP_HANDSHAKE_PACKET_SIZE - 32, 0,
  1047. digest, 32,
  1048. tosend + RTMP_HANDSHAKE_PACKET_SIZE - 32);
  1049. if (ret < 0)
  1050. return ret;
  1051. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1052. /* Encrypt the signature to be send to the server. */
  1053. ff_rtmpe_encrypt_sig(rt->stream, tosend +
  1054. RTMP_HANDSHAKE_PACKET_SIZE - 32, digest,
  1055. serverdata[0]);
  1056. }
  1057. // write reply back to the server
  1058. if ((ret = ffurl_write(rt->stream, tosend,
  1059. RTMP_HANDSHAKE_PACKET_SIZE)) < 0)
  1060. return ret;
  1061. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1062. /* Set RC4 keys for encryption and update the keystreams. */
  1063. if ((ret = ff_rtmpe_update_keystream(rt->stream)) < 0)
  1064. return ret;
  1065. }
  1066. } else {
  1067. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1068. /* Compute the shared secret key sent by the server and initialize
  1069. * the RC4 encryption. */
  1070. if ((ret = ff_rtmpe_compute_secret_key(rt->stream, serverdata + 1,
  1071. tosend + 1, 1)) < 0)
  1072. return ret;
  1073. if (serverdata[0] == 9) {
  1074. /* Encrypt the signature received by the server. */
  1075. ff_rtmpe_encrypt_sig(rt->stream, signature, digest,
  1076. serverdata[0]);
  1077. }
  1078. }
  1079. if ((ret = ffurl_write(rt->stream, serverdata + 1,
  1080. RTMP_HANDSHAKE_PACKET_SIZE)) < 0)
  1081. return ret;
  1082. if (CONFIG_FFRTMPCRYPT_PROTOCOL && rt->encrypted) {
  1083. /* Set RC4 keys for encryption and update the keystreams. */
  1084. if ((ret = ff_rtmpe_update_keystream(rt->stream)) < 0)
  1085. return ret;
  1086. }
  1087. }
  1088. return 0;
  1089. }
  1090. static int rtmp_receive_hs_packet(RTMPContext* rt, uint32_t *first_int,
  1091. uint32_t *second_int, char *arraydata,
  1092. int size)
  1093. {
  1094. int inoutsize;
  1095. inoutsize = ffurl_read_complete(rt->stream, arraydata,
  1096. RTMP_HANDSHAKE_PACKET_SIZE);
  1097. if (inoutsize <= 0)
  1098. return AVERROR(EIO);
  1099. if (inoutsize != RTMP_HANDSHAKE_PACKET_SIZE) {
  1100. av_log(rt, AV_LOG_ERROR, "Erroneous Message size %d"
  1101. " not following standard\n", (int)inoutsize);
  1102. return AVERROR(EINVAL);
  1103. }
  1104. *first_int = AV_RB32(arraydata);
  1105. *second_int = AV_RB32(arraydata + 4);
  1106. return 0;
  1107. }
  1108. static int rtmp_send_hs_packet(RTMPContext* rt, uint32_t first_int,
  1109. uint32_t second_int, char *arraydata, int size)
  1110. {
  1111. int inoutsize;
  1112. AV_WB32(arraydata, first_int);
  1113. AV_WB32(arraydata + 4, first_int);
  1114. inoutsize = ffurl_write(rt->stream, arraydata,
  1115. RTMP_HANDSHAKE_PACKET_SIZE);
  1116. if (inoutsize != RTMP_HANDSHAKE_PACKET_SIZE) {
  1117. av_log(rt, AV_LOG_ERROR, "Unable to write answer\n");
  1118. return AVERROR(EIO);
  1119. }
  1120. return 0;
  1121. }
  1122. /**
  1123. * rtmp handshake server side
  1124. */
  1125. static int rtmp_server_handshake(URLContext *s, RTMPContext *rt)
  1126. {
  1127. uint8_t buffer[RTMP_HANDSHAKE_PACKET_SIZE];
  1128. uint32_t hs_epoch;
  1129. uint32_t hs_my_epoch;
  1130. uint8_t hs_c1[RTMP_HANDSHAKE_PACKET_SIZE];
  1131. uint8_t hs_s1[RTMP_HANDSHAKE_PACKET_SIZE];
  1132. uint32_t zeroes;
  1133. uint32_t temp = 0;
  1134. int randomidx = 0;
  1135. int inoutsize = 0;
  1136. int ret;
  1137. inoutsize = ffurl_read_complete(rt->stream, buffer, 1); // Receive C0
  1138. if (inoutsize <= 0) {
  1139. av_log(s, AV_LOG_ERROR, "Unable to read handshake\n");
  1140. return AVERROR(EIO);
  1141. }
  1142. // Check Version
  1143. if (buffer[0] != 3) {
  1144. av_log(s, AV_LOG_ERROR, "RTMP protocol version mismatch\n");
  1145. return AVERROR(EIO);
  1146. }
  1147. if (ffurl_write(rt->stream, buffer, 1) <= 0) { // Send S0
  1148. av_log(s, AV_LOG_ERROR,
  1149. "Unable to write answer - RTMP S0\n");
  1150. return AVERROR(EIO);
  1151. }
  1152. /* Receive C1 */
  1153. ret = rtmp_receive_hs_packet(rt, &hs_epoch, &zeroes, hs_c1,
  1154. RTMP_HANDSHAKE_PACKET_SIZE);
  1155. if (ret) {
  1156. av_log(s, AV_LOG_ERROR, "RTMP Handshake C1 Error\n");
  1157. return ret;
  1158. }
  1159. if (zeroes)
  1160. av_log(s, AV_LOG_WARNING, "Erroneous C1 Message zero != 0\n");
  1161. /* Send S1 */
  1162. /* By now same epoch will be sent */
  1163. hs_my_epoch = hs_epoch;
  1164. /* Generate random */
  1165. for (randomidx = 0; randomidx < (RTMP_HANDSHAKE_PACKET_SIZE);
  1166. randomidx += 4)
  1167. AV_WB32(hs_s1 + 8 + randomidx, av_get_random_seed());
  1168. ret = rtmp_send_hs_packet(rt, hs_my_epoch, 0, hs_s1,
  1169. RTMP_HANDSHAKE_PACKET_SIZE);
  1170. if (ret) {
  1171. av_log(s, AV_LOG_ERROR, "RTMP Handshake S1 Error\n");
  1172. return ret;
  1173. }
  1174. /* Send S2 */
  1175. ret = rtmp_send_hs_packet(rt, hs_epoch, 0, hs_c1,
  1176. RTMP_HANDSHAKE_PACKET_SIZE);
  1177. if (ret) {
  1178. av_log(s, AV_LOG_ERROR, "RTMP Handshake S2 Error\n");
  1179. return ret;
  1180. }
  1181. /* Receive C2 */
  1182. ret = rtmp_receive_hs_packet(rt, &temp, &zeroes, buffer,
  1183. RTMP_HANDSHAKE_PACKET_SIZE);
  1184. if (ret) {
  1185. av_log(s, AV_LOG_ERROR, "RTMP Handshake C2 Error\n");
  1186. return ret;
  1187. }
  1188. if (temp != hs_my_epoch)
  1189. av_log(s, AV_LOG_WARNING,
  1190. "Erroneous C2 Message epoch does not match up with C1 epoch\n");
  1191. if (memcmp(buffer + 8, hs_s1 + 8,
  1192. RTMP_HANDSHAKE_PACKET_SIZE - 8))
  1193. av_log(s, AV_LOG_WARNING,
  1194. "Erroneous C2 Message random does not match up\n");
  1195. return 0;
  1196. }
  1197. static int handle_chunk_size(URLContext *s, RTMPPacket *pkt)
  1198. {
  1199. RTMPContext *rt = s->priv_data;
  1200. int ret;
  1201. if (pkt->data_size < 4) {
  1202. av_log(s, AV_LOG_ERROR,
  1203. "Too short chunk size change packet (%d)\n",
  1204. pkt->data_size);
  1205. return AVERROR_INVALIDDATA;
  1206. }
  1207. if (!rt->is_input) {
  1208. /* Send the same chunk size change packet back to the server,
  1209. * setting the outgoing chunk size to the same as the incoming one. */
  1210. if ((ret = ff_rtmp_packet_write(rt->stream, pkt, rt->out_chunk_size,
  1211. rt->prev_pkt[1])) < 0)
  1212. return ret;
  1213. rt->out_chunk_size = AV_RB32(pkt->data);
  1214. }
  1215. rt->in_chunk_size = AV_RB32(pkt->data);
  1216. if (rt->in_chunk_size <= 0) {
  1217. av_log(s, AV_LOG_ERROR, "Incorrect chunk size %d\n",
  1218. rt->in_chunk_size);
  1219. return AVERROR_INVALIDDATA;
  1220. }
  1221. av_log(s, AV_LOG_DEBUG, "New incoming chunk size = %d\n",
  1222. rt->in_chunk_size);
  1223. return 0;
  1224. }
  1225. static int handle_ping(URLContext *s, RTMPPacket *pkt)
  1226. {
  1227. RTMPContext *rt = s->priv_data;
  1228. int t, ret;
  1229. if (pkt->data_size < 2) {
  1230. av_log(s, AV_LOG_ERROR, "Too short ping packet (%d)\n",
  1231. pkt->data_size);
  1232. return AVERROR_INVALIDDATA;
  1233. }
  1234. t = AV_RB16(pkt->data);
  1235. if (t == 6) {
  1236. if ((ret = gen_pong(s, rt, pkt)) < 0)
  1237. return ret;
  1238. } else if (t == 26) {
  1239. if (rt->swfsize) {
  1240. if ((ret = gen_swf_verification(s, rt)) < 0)
  1241. return ret;
  1242. } else {
  1243. av_log(s, AV_LOG_WARNING, "Ignoring SWFVerification request.\n");
  1244. }
  1245. }
  1246. return 0;
  1247. }
  1248. static int handle_client_bw(URLContext *s, RTMPPacket *pkt)
  1249. {
  1250. RTMPContext *rt = s->priv_data;
  1251. if (pkt->data_size < 4) {
  1252. av_log(s, AV_LOG_ERROR,
  1253. "Client bandwidth report packet is less than 4 bytes long (%d)\n",
  1254. pkt->data_size);
  1255. return AVERROR_INVALIDDATA;
  1256. }
  1257. rt->client_report_size = AV_RB32(pkt->data);
  1258. if (rt->client_report_size <= 0) {
  1259. av_log(s, AV_LOG_ERROR, "Incorrect client bandwidth %d\n",
  1260. rt->client_report_size);
  1261. return AVERROR_INVALIDDATA;
  1262. }
  1263. av_log(s, AV_LOG_DEBUG, "Client bandwidth = %d\n", rt->client_report_size);
  1264. rt->client_report_size >>= 1;
  1265. return 0;
  1266. }
  1267. static int handle_server_bw(URLContext *s, RTMPPacket *pkt)
  1268. {
  1269. RTMPContext *rt = s->priv_data;
  1270. if (pkt->data_size < 4) {
  1271. av_log(s, AV_LOG_ERROR,
  1272. "Too short server bandwidth report packet (%d)\n",
  1273. pkt->data_size);
  1274. return AVERROR_INVALIDDATA;
  1275. }
  1276. rt->server_bw = AV_RB32(pkt->data);
  1277. if (rt->server_bw <= 0) {
  1278. av_log(s, AV_LOG_ERROR, "Incorrect server bandwidth %d\n",
  1279. rt->server_bw);
  1280. return AVERROR_INVALIDDATA;
  1281. }
  1282. av_log(s, AV_LOG_DEBUG, "Server bandwidth = %d\n", rt->server_bw);
  1283. return 0;
  1284. }
  1285. static int handle_invoke_error(URLContext *s, RTMPPacket *pkt)
  1286. {
  1287. const uint8_t *data_end = pkt->data + pkt->data_size;
  1288. char *tracked_method = NULL;
  1289. int level = AV_LOG_ERROR;
  1290. uint8_t tmpstr[256];
  1291. int ret;
  1292. if ((ret = find_tracked_method(s, pkt, 9, &tracked_method)) < 0)
  1293. return ret;
  1294. if (!ff_amf_get_field_value(pkt->data + 9, data_end,
  1295. "description", tmpstr, sizeof(tmpstr))) {
  1296. if (tracked_method && (!strcmp(tracked_method, "_checkbw") ||
  1297. !strcmp(tracked_method, "releaseStream") ||
  1298. !strcmp(tracked_method, "FCSubscribe") ||
  1299. !strcmp(tracked_method, "FCPublish"))) {
  1300. /* Gracefully ignore Adobe-specific historical artifact errors. */
  1301. level = AV_LOG_WARNING;
  1302. ret = 0;
  1303. } else
  1304. ret = -1;
  1305. av_log(s, level, "Server error: %s\n", tmpstr);
  1306. }
  1307. av_free(tracked_method);
  1308. return ret;
  1309. }
  1310. static int send_invoke_response(URLContext *s, RTMPPacket *pkt)
  1311. {
  1312. RTMPContext *rt = s->priv_data;
  1313. double seqnum;
  1314. char filename[64];
  1315. char command[64];
  1316. char statusmsg[128];
  1317. int stringlen;
  1318. char *pchar;
  1319. const uint8_t *p = pkt->data;
  1320. uint8_t *pp = NULL;
  1321. RTMPPacket spkt = { 0 };
  1322. GetByteContext gbc;
  1323. int ret;
  1324. bytestream2_init(&gbc, p, pkt->data_size);
  1325. if (ff_amf_read_string(&gbc, command, sizeof(command),
  1326. &stringlen)) {
  1327. av_log(s, AV_LOG_ERROR, "Error in PT_INVOKE\n");
  1328. return AVERROR_INVALIDDATA;
  1329. }
  1330. ret = ff_amf_read_number(&gbc, &seqnum);
  1331. if (ret)
  1332. return ret;
  1333. ret = ff_amf_read_null(&gbc);
  1334. if (ret)
  1335. return ret;
  1336. if (!strcmp(command, "FCPublish") ||
  1337. !strcmp(command, "publish")) {
  1338. ret = ff_amf_read_string(&gbc, filename,
  1339. sizeof(filename), &stringlen);
  1340. // check with url
  1341. if (s->filename) {
  1342. pchar = strrchr(s->filename, '/');
  1343. if (!pchar) {
  1344. av_log(s, AV_LOG_WARNING,
  1345. "Unable to find / in url %s, bad format\n",
  1346. s->filename);
  1347. pchar = s->filename;
  1348. }
  1349. pchar++;
  1350. if (strcmp(pchar, filename))
  1351. av_log(s, AV_LOG_WARNING, "Unexpected stream %s, expecting"
  1352. " %s\n", filename, pchar);
  1353. }
  1354. rt->state = STATE_RECEIVING;
  1355. }
  1356. if (!strcmp(command, "FCPublish")) {
  1357. if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,
  1358. RTMP_PT_INVOKE, 0,
  1359. RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {
  1360. av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
  1361. return ret;
  1362. }
  1363. pp = spkt.data;
  1364. ff_amf_write_string(&pp, "onFCPublish");
  1365. } else if (!strcmp(command, "publish")) {
  1366. PutByteContext pbc;
  1367. // Send Stream Begin 1
  1368. if ((ret = ff_rtmp_packet_create(&spkt, RTMP_NETWORK_CHANNEL,
  1369. RTMP_PT_PING, 0, 6)) < 0) {
  1370. av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
  1371. return ret;
  1372. }
  1373. pp = spkt.data;
  1374. bytestream2_init_writer(&pbc, pp, spkt.data_size);
  1375. bytestream2_put_be16(&pbc, 0); // 0 -> Stream Begin
  1376. bytestream2_put_be32(&pbc, rt->nb_streamid);
  1377. ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
  1378. rt->prev_pkt[1]);
  1379. ff_rtmp_packet_destroy(&spkt);
  1380. if (ret < 0)
  1381. return ret;
  1382. // Send onStatus(NetStream.Publish.Start)
  1383. if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,
  1384. RTMP_PT_INVOKE, 0,
  1385. RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {
  1386. av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
  1387. return ret;
  1388. }
  1389. spkt.extra = pkt->extra;
  1390. pp = spkt.data;
  1391. ff_amf_write_string(&pp, "onStatus");
  1392. ff_amf_write_number(&pp, 0);
  1393. ff_amf_write_null(&pp);
  1394. ff_amf_write_object_start(&pp);
  1395. ff_amf_write_field_name(&pp, "level");
  1396. ff_amf_write_string(&pp, "status");
  1397. ff_amf_write_field_name(&pp, "code");
  1398. ff_amf_write_string(&pp, "NetStream.Publish.Start");
  1399. ff_amf_write_field_name(&pp, "description");
  1400. snprintf(statusmsg, sizeof(statusmsg),
  1401. "%s is now published", filename);
  1402. ff_amf_write_string(&pp, statusmsg);
  1403. ff_amf_write_field_name(&pp, "details");
  1404. ff_amf_write_string(&pp, filename);
  1405. ff_amf_write_field_name(&pp, "clientid");
  1406. snprintf(statusmsg, sizeof(statusmsg), "%s", LIBAVFORMAT_IDENT);
  1407. ff_amf_write_string(&pp, statusmsg);
  1408. ff_amf_write_object_end(&pp);
  1409. } else {
  1410. if ((ret = ff_rtmp_packet_create(&spkt, RTMP_SYSTEM_CHANNEL,
  1411. RTMP_PT_INVOKE, 0,
  1412. RTMP_PKTDATA_DEFAULT_SIZE)) < 0) {
  1413. av_log(s, AV_LOG_ERROR, "Unable to create response packet\n");
  1414. return ret;
  1415. }
  1416. pp = spkt.data;
  1417. ff_amf_write_string(&pp, "_result");
  1418. ff_amf_write_number(&pp, seqnum);
  1419. ff_amf_write_null(&pp);
  1420. if (!strcmp(command, "createStream")) {
  1421. rt->nb_streamid++;
  1422. if (rt->nb_streamid == 0 || rt->nb_streamid == 2)
  1423. rt->nb_streamid++; /* Values 0 and 2 are reserved */
  1424. ff_amf_write_number(&pp, rt->nb_streamid);
  1425. /* By now we don't control which streams are removed in
  1426. * deleteStream. There is no stream creation control
  1427. * if a client creates more than 2^32 - 2 streams. */
  1428. }
  1429. }
  1430. spkt.data_size = pp - spkt.data;
  1431. ret = ff_rtmp_packet_write(rt->stream, &spkt, rt->out_chunk_size,
  1432. rt->prev_pkt[1]);
  1433. ff_rtmp_packet_destroy(&spkt);
  1434. return ret;
  1435. }
  1436. static int handle_invoke_result(URLContext *s, RTMPPacket *pkt)
  1437. {
  1438. RTMPContext *rt = s->priv_data;
  1439. char *tracked_method = NULL;
  1440. int ret = 0;
  1441. if ((ret = find_tracked_method(s, pkt, 10, &tracked_method)) < 0)
  1442. return ret;
  1443. if (!tracked_method) {
  1444. /* Ignore this reply when the current method is not tracked. */
  1445. return ret;
  1446. }
  1447. if (!memcmp(tracked_method, "connect", 7)) {
  1448. if (!rt->is_input) {
  1449. if ((ret = gen_release_stream(s, rt)) < 0)
  1450. goto fail;
  1451. if ((ret = gen_fcpublish_stream(s, rt)) < 0)
  1452. goto fail;
  1453. } else {
  1454. if ((ret = gen_server_bw(s, rt)) < 0)
  1455. goto fail;
  1456. }
  1457. if ((ret = gen_create_stream(s, rt)) < 0)
  1458. goto fail;
  1459. if (rt->is_input) {
  1460. /* Send the FCSubscribe command when the name of live
  1461. * stream is defined by the user or if it's a live stream. */
  1462. if (rt->subscribe) {
  1463. if ((ret = gen_fcsubscribe_stream(s, rt, rt->subscribe)) < 0)
  1464. goto fail;
  1465. } else if (rt->live == -1) {
  1466. if ((ret = gen_fcsubscribe_stream(s, rt, rt->playpath)) < 0)
  1467. goto fail;
  1468. }
  1469. }
  1470. } else if (!memcmp(tracked_method, "createStream", 12)) {
  1471. //extract a number from the result
  1472. if (pkt->data[10] || pkt->data[19] != 5 || pkt->data[20]) {
  1473. av_log(s, AV_LOG_WARNING, "Unexpected reply on connect()\n");
  1474. } else {
  1475. rt->main_channel_id = av_int2double(AV_RB64(pkt->data + 21));
  1476. }
  1477. if (!rt->is_input) {
  1478. if ((ret = gen_publish(s, rt)) < 0)
  1479. goto fail;
  1480. } else {
  1481. if ((ret = gen_play(s, rt)) < 0)
  1482. goto fail;
  1483. if ((ret = gen_buffer_time(s, rt)) < 0)
  1484. goto fail;
  1485. }
  1486. }
  1487. fail:
  1488. av_free(tracked_method);
  1489. return ret;
  1490. }
  1491. static int handle_invoke_status(URLContext *s, RTMPPacket *pkt)
  1492. {
  1493. RTMPContext *rt = s->priv_data;
  1494. const uint8_t *data_end = pkt->data + pkt->data_size;
  1495. const uint8_t *ptr = pkt->data + 11;
  1496. uint8_t tmpstr[256];
  1497. int i, t;
  1498. for (i = 0; i < 2; i++) {
  1499. t = ff_amf_tag_size(ptr, data_end);
  1500. if (t < 0)
  1501. return 1;
  1502. ptr += t;
  1503. }
  1504. t = ff_amf_get_field_value(ptr, data_end, "level", tmpstr, sizeof(tmpstr));
  1505. if (!t && !strcmp(tmpstr, "error")) {
  1506. if (!ff_amf_get_field_value(ptr, data_end,
  1507. "description", tmpstr, sizeof(tmpstr)))
  1508. av_log(s, AV_LOG_ERROR, "Server error: %s\n", tmpstr);
  1509. return -1;
  1510. }
  1511. t = ff_amf_get_field_value(ptr, data_end, "code", tmpstr, sizeof(tmpstr));
  1512. if (!t && !strcmp(tmpstr, "NetStream.Play.Start")) rt->state = STATE_PLAYING;
  1513. if (!t && !strcmp(tmpstr, "NetStream.Play.Stop")) rt->state = STATE_STOPPED;
  1514. if (!t && !strcmp(tmpstr, "NetStream.Play.UnpublishNotify")) rt->state = STATE_STOPPED;
  1515. if (!t && !strcmp(tmpstr, "NetStream.Publish.Start")) rt->state = STATE_PUBLISHING;
  1516. return 0;
  1517. }
  1518. static int handle_invoke(URLContext *s, RTMPPacket *pkt)
  1519. {
  1520. RTMPContext *rt = s->priv_data;
  1521. int ret = 0;
  1522. //TODO: check for the messages sent for wrong state?
  1523. if (!memcmp(pkt->data, "\002\000\006_error", 9)) {
  1524. if ((ret = handle_invoke_error(s, pkt)) < 0)
  1525. return ret;
  1526. } else if (!memcmp(pkt->data, "\002\000\007_result", 10)) {
  1527. if ((ret = handle_invoke_result(s, pkt)) < 0)
  1528. return ret;
  1529. } else if (!memcmp(pkt->data, "\002\000\010onStatus", 11)) {
  1530. if ((ret = handle_invoke_status(s, pkt)) < 0)
  1531. return ret;
  1532. } else if (!memcmp(pkt->data, "\002\000\010onBWDone", 11)) {
  1533. if ((ret = gen_check_bw(s, rt)) < 0)
  1534. return ret;
  1535. } else if (!memcmp(pkt->data, "\002\000\015releaseStream", 16) ||
  1536. !memcmp(pkt->data, "\002\000\011FCPublish", 12) ||
  1537. !memcmp(pkt->data, "\002\000\007publish", 10) ||
  1538. !memcmp(pkt->data, "\002\000\010_checkbw", 11) ||
  1539. !memcmp(pkt->data, "\002\000\014createStream", 15)) {
  1540. if ((ret = send_invoke_response(s, pkt)) < 0)
  1541. return ret;
  1542. }
  1543. return ret;
  1544. }
  1545. static int handle_notify(URLContext *s, RTMPPacket *pkt) {
  1546. RTMPContext *rt = s->priv_data;
  1547. const uint8_t *p = NULL;
  1548. uint8_t *cp = NULL;
  1549. uint8_t commandbuffer[64];
  1550. char statusmsg[128];
  1551. int stringlen;
  1552. GetByteContext gbc;
  1553. PutByteContext pbc;
  1554. uint32_t ts;
  1555. int old_flv_size;
  1556. const uint8_t *datatowrite;
  1557. unsigned datatowritelength;
  1558. p = pkt->data;
  1559. bytestream2_init(&gbc, p, pkt->data_size);
  1560. if (ff_amf_read_string(&gbc, commandbuffer, sizeof(commandbuffer),
  1561. &stringlen))
  1562. return AVERROR_INVALIDDATA;
  1563. if (!strcmp(commandbuffer, "@setDataFrame")) {
  1564. datatowrite = gbc.buffer;
  1565. datatowritelength = bytestream2_get_bytes_left(&gbc);
  1566. if (ff_amf_read_string(&gbc, statusmsg,
  1567. sizeof(statusmsg), &stringlen))
  1568. return AVERROR_INVALIDDATA;
  1569. if (strcmp(statusmsg, "onMetaData")) {
  1570. av_log(s, AV_LOG_INFO, "Expecting onMetadata but got %s\n",
  1571. statusmsg);
  1572. return 0;
  1573. }
  1574. /* Provide ECMAArray to flv */
  1575. ts = pkt->timestamp;
  1576. // generate packet header and put data into buffer for FLV demuxer
  1577. if (rt->flv_off < rt->flv_size) {
  1578. old_flv_size = rt->flv_size;
  1579. rt->flv_size += datatowritelength + 15;
  1580. } else {
  1581. old_flv_size = 0;
  1582. rt->flv_size = datatowritelength + 15;
  1583. rt->flv_off = 0;
  1584. }
  1585. cp = av_realloc(rt->flv_data, rt->flv_size);
  1586. if (!cp)
  1587. return AVERROR(ENOMEM);
  1588. rt->flv_data = cp;
  1589. bytestream2_init_writer(&pbc, cp, rt->flv_size);
  1590. bytestream2_skip_p(&pbc, old_flv_size);
  1591. bytestream2_put_byte(&pbc, pkt->type);
  1592. bytestream2_put_be24(&pbc, datatowritelength);
  1593. bytestream2_put_be24(&pbc, ts);
  1594. bytestream2_put_byte(&pbc, ts >> 24);
  1595. bytestream2_put_be24(&pbc, 0);
  1596. bytestream2_put_buffer(&pbc, datatowrite, datatowritelength);
  1597. bytestream2_put_be32(&pbc, 0);
  1598. }
  1599. return 0;
  1600. }
  1601. /**
  1602. * Parse received packet and possibly perform some action depending on
  1603. * the packet contents.
  1604. * @return 0 for no errors, negative values for serious errors which prevent
  1605. * further communications, positive values for uncritical errors
  1606. */
  1607. static int rtmp_parse_result(URLContext *s, RTMPContext *rt, RTMPPacket *pkt)
  1608. {
  1609. int ret;
  1610. #ifdef DEBUG
  1611. ff_rtmp_packet_dump(s, pkt);
  1612. #endif
  1613. switch (pkt->type) {
  1614. case RTMP_PT_BYTES_READ:
  1615. av_dlog(s, "received bytes read report\n");
  1616. break;
  1617. case RTMP_PT_CHUNK_SIZE:
  1618. if ((ret = handle_chunk_size(s, pkt)) < 0)
  1619. return ret;
  1620. break;
  1621. case RTMP_PT_PING:
  1622. if ((ret = handle_ping(s, pkt)) < 0)
  1623. return ret;
  1624. break;
  1625. case RTMP_PT_CLIENT_BW:
  1626. if ((ret = handle_client_bw(s, pkt)) < 0)
  1627. return ret;
  1628. break;
  1629. case RTMP_PT_SERVER_BW:
  1630. if ((ret = handle_server_bw(s, pkt)) < 0)
  1631. return ret;
  1632. break;
  1633. case RTMP_PT_INVOKE:
  1634. if ((ret = handle_invoke(s, pkt)) < 0)
  1635. return ret;
  1636. break;
  1637. case RTMP_PT_VIDEO:
  1638. case RTMP_PT_AUDIO:
  1639. case RTMP_PT_METADATA:
  1640. case RTMP_PT_NOTIFY:
  1641. /* Audio, Video and Metadata packets are parsed in get_packet() */
  1642. break;
  1643. default:
  1644. av_log(s, AV_LOG_VERBOSE, "Unknown packet type received 0x%02X\n", pkt->type);
  1645. break;
  1646. }
  1647. return 0;
  1648. }
  1649. /**
  1650. * Interact with the server by receiving and sending RTMP packets until
  1651. * there is some significant data (media data or expected status notification).
  1652. *
  1653. * @param s reading context
  1654. * @param for_header non-zero value tells function to work until it
  1655. * gets notification from the server that playing has been started,
  1656. * otherwise function will work until some media data is received (or
  1657. * an error happens)
  1658. * @return 0 for successful operation, negative value in case of error
  1659. */
  1660. static int get_packet(URLContext *s, int for_header)
  1661. {
  1662. RTMPContext *rt = s->priv_data;
  1663. int ret;
  1664. uint8_t *p;
  1665. const uint8_t *next;
  1666. uint32_t data_size;
  1667. uint32_t ts, cts, pts=0;
  1668. if (rt->state == STATE_STOPPED)
  1669. return AVERROR_EOF;
  1670. for (;;) {
  1671. RTMPPacket rpkt = { 0 };
  1672. if ((ret = ff_rtmp_packet_read(rt->stream, &rpkt,
  1673. rt->in_chunk_size, rt->prev_pkt[0])) <= 0) {
  1674. if (ret == 0) {
  1675. return AVERROR(EAGAIN);
  1676. } else {
  1677. return AVERROR(EIO);
  1678. }
  1679. }
  1680. rt->bytes_read += ret;
  1681. if (rt->bytes_read - rt->last_bytes_read > rt->client_report_size) {
  1682. av_log(s, AV_LOG_DEBUG, "Sending bytes read report\n");
  1683. if ((ret = gen_bytes_read(s, rt, rpkt.timestamp + 1)) < 0)
  1684. return ret;
  1685. rt->last_bytes_read = rt->bytes_read;
  1686. }
  1687. ret = rtmp_parse_result(s, rt, &rpkt);
  1688. if (ret < 0) {//serious error in current packet
  1689. ff_rtmp_packet_destroy(&rpkt);
  1690. return ret;
  1691. }
  1692. if (rt->state == STATE_STOPPED) {
  1693. ff_rtmp_packet_destroy(&rpkt);
  1694. return AVERROR_EOF;
  1695. }
  1696. if (for_header && (rt->state == STATE_PLAYING ||
  1697. rt->state == STATE_PUBLISHING ||
  1698. rt->state == STATE_RECEIVING)) {
  1699. ff_rtmp_packet_destroy(&rpkt);
  1700. return 0;
  1701. }
  1702. if (!rpkt.data_size || !rt->is_input) {
  1703. ff_rtmp_packet_destroy(&rpkt);
  1704. continue;
  1705. }
  1706. if (rpkt.type == RTMP_PT_VIDEO || rpkt.type == RTMP_PT_AUDIO ||
  1707. (rpkt.type == RTMP_PT_NOTIFY && !memcmp("\002\000\012onMetaData", rpkt.data, 13))) {
  1708. ts = rpkt.timestamp;
  1709. // generate packet header and put data into buffer for FLV demuxer
  1710. rt->flv_off = 0;
  1711. rt->flv_size = rpkt.data_size + 15;
  1712. rt->flv_data = p = av_realloc(rt->flv_data, rt->flv_size);
  1713. bytestream_put_byte(&p, rpkt.type);
  1714. bytestream_put_be24(&p, rpkt.data_size);
  1715. bytestream_put_be24(&p, ts);
  1716. bytestream_put_byte(&p, ts >> 24);
  1717. bytestream_put_be24(&p, 0);
  1718. bytestream_put_buffer(&p, rpkt.data, rpkt.data_size);
  1719. bytestream_put_be32(&p, 0);
  1720. ff_rtmp_packet_destroy(&rpkt);
  1721. return 0;
  1722. } else if (rpkt.type == RTMP_PT_NOTIFY) {
  1723. ret = handle_notify(s, &rpkt);
  1724. ff_rtmp_packet_destroy(&rpkt);
  1725. if (ret) {
  1726. av_log(s, AV_LOG_ERROR, "Handle notify error\n");
  1727. return ret;
  1728. }
  1729. return 0;
  1730. } else if (rpkt.type == RTMP_PT_METADATA) {
  1731. // we got raw FLV data, make it available for FLV demuxer
  1732. rt->flv_off = 0;
  1733. rt->flv_size = rpkt.data_size;
  1734. rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
  1735. /* rewrite timestamps */
  1736. next = rpkt.data;
  1737. ts = rpkt.timestamp;
  1738. while (next - rpkt.data < rpkt.data_size - 11) {
  1739. next++;
  1740. data_size = bytestream_get_be24(&next);
  1741. p=next;
  1742. cts = bytestream_get_be24(&next);
  1743. cts |= bytestream_get_byte(&next) << 24;
  1744. if (pts==0)
  1745. pts=cts;
  1746. ts += cts - pts;
  1747. pts = cts;
  1748. bytestream_put_be24(&p, ts);
  1749. bytestream_put_byte(&p, ts >> 24);
  1750. next += data_size + 3 + 4;
  1751. }
  1752. memcpy(rt->flv_data, rpkt.data, rpkt.data_size);
  1753. ff_rtmp_packet_destroy(&rpkt);
  1754. return 0;
  1755. }
  1756. ff_rtmp_packet_destroy(&rpkt);
  1757. }
  1758. }
  1759. static int rtmp_close(URLContext *h)
  1760. {
  1761. RTMPContext *rt = h->priv_data;
  1762. int ret = 0;
  1763. if (!rt->is_input) {
  1764. rt->flv_data = NULL;
  1765. if (rt->out_pkt.data_size)
  1766. ff_rtmp_packet_destroy(&rt->out_pkt);
  1767. if (rt->state > STATE_FCPUBLISH)
  1768. ret = gen_fcunpublish_stream(h, rt);
  1769. }
  1770. if (rt->state > STATE_HANDSHAKED)
  1771. ret = gen_delete_stream(h, rt);
  1772. free_tracked_methods(rt);
  1773. av_freep(&rt->flv_data);
  1774. ffurl_close(rt->stream);
  1775. return ret;
  1776. }
  1777. /**
  1778. * Open RTMP connection and verify that the stream can be played.
  1779. *
  1780. * URL syntax: rtmp://server[:port][/app][/playpath]
  1781. * where 'app' is first one or two directories in the path
  1782. * (e.g. /ondemand/, /flash/live/, etc.)
  1783. * and 'playpath' is a file name (the rest of the path,
  1784. * may be prefixed with "mp4:")
  1785. */
  1786. static int rtmp_open(URLContext *s, const char *uri, int flags)
  1787. {
  1788. RTMPContext *rt = s->priv_data;
  1789. char proto[8], hostname[256], path[1024], *fname;
  1790. char *old_app;
  1791. uint8_t buf[2048];
  1792. int port;
  1793. AVDictionary *opts = NULL;
  1794. int ret;
  1795. if (rt->listen_timeout > 0)
  1796. rt->listen = 1;
  1797. rt->is_input = !(flags & AVIO_FLAG_WRITE);
  1798. av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
  1799. path, sizeof(path), s->filename);
  1800. if (rt->listen && strcmp(proto, "rtmp")) {
  1801. av_log(s, AV_LOG_ERROR, "rtmp_listen not available for %s\n",
  1802. proto);
  1803. return AVERROR(EINVAL);
  1804. }
  1805. if (!strcmp(proto, "rtmpt") || !strcmp(proto, "rtmpts")) {
  1806. if (!strcmp(proto, "rtmpts"))
  1807. av_dict_set(&opts, "ffrtmphttp_tls", "1", 1);
  1808. /* open the http tunneling connection */
  1809. ff_url_join(buf, sizeof(buf), "ffrtmphttp", NULL, hostname, port, NULL);
  1810. } else if (!strcmp(proto, "rtmps")) {
  1811. /* open the tls connection */
  1812. if (port < 0)
  1813. port = RTMPS_DEFAULT_PORT;
  1814. ff_url_join(buf, sizeof(buf), "tls", NULL, hostname, port, NULL);
  1815. } else if (!strcmp(proto, "rtmpe") || (!strcmp(proto, "rtmpte"))) {
  1816. if (!strcmp(proto, "rtmpte"))
  1817. av_dict_set(&opts, "ffrtmpcrypt_tunneling", "1", 1);
  1818. /* open the encrypted connection */
  1819. ff_url_join(buf, sizeof(buf), "ffrtmpcrypt", NULL, hostname, port, NULL);
  1820. rt->encrypted = 1;
  1821. } else {
  1822. /* open the tcp connection */
  1823. if (port < 0)
  1824. port = RTMP_DEFAULT_PORT;
  1825. if (rt->listen)
  1826. ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port,
  1827. "?listen&listen_timeout=%d",
  1828. rt->listen_timeout * 1000);
  1829. else
  1830. ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
  1831. }
  1832. if ((ret = ffurl_open(&rt->stream, buf, AVIO_FLAG_READ_WRITE,
  1833. &s->interrupt_callback, &opts)) < 0) {
  1834. av_log(s , AV_LOG_ERROR, "Cannot open connection %s\n", buf);
  1835. goto fail;
  1836. }
  1837. if (rt->swfverify) {
  1838. if ((ret = rtmp_calc_swfhash(s)) < 0)
  1839. goto fail;
  1840. }
  1841. rt->state = STATE_START;
  1842. if (!rt->listen && (ret = rtmp_handshake(s, rt)) < 0)
  1843. goto fail;
  1844. if (rt->listen && (ret = rtmp_server_handshake(s, rt)) < 0)
  1845. goto fail;
  1846. rt->out_chunk_size = 128;
  1847. rt->in_chunk_size = 128; // Probably overwritten later
  1848. rt->state = STATE_HANDSHAKED;
  1849. // Keep the application name when it has been defined by the user.
  1850. old_app = rt->app;
  1851. rt->app = av_malloc(APP_MAX_LENGTH);
  1852. if (!rt->app) {
  1853. ret = AVERROR(ENOMEM);
  1854. goto fail;
  1855. }
  1856. //extract "app" part from path
  1857. if (!strncmp(path, "/ondemand/", 10)) {
  1858. fname = path + 10;
  1859. memcpy(rt->app, "ondemand", 9);
  1860. } else {
  1861. char *next = *path ? path + 1 : path;
  1862. char *p = strchr(next, '/');
  1863. if (!p) {
  1864. fname = next;
  1865. rt->app[0] = '\0';
  1866. } else {
  1867. // make sure we do not mismatch a playpath for an application instance
  1868. char *c = strchr(p + 1, ':');
  1869. fname = strchr(p + 1, '/');
  1870. if (!fname || (c && c < fname)) {
  1871. fname = p + 1;
  1872. av_strlcpy(rt->app, path + 1, FFMIN(p - path, APP_MAX_LENGTH));
  1873. } else {
  1874. fname++;
  1875. av_strlcpy(rt->app, path + 1, FFMIN(fname - path - 1, APP_MAX_LENGTH));
  1876. }
  1877. }
  1878. }
  1879. if (old_app) {
  1880. // The name of application has been defined by the user, override it.
  1881. if (strlen(old_app) >= APP_MAX_LENGTH) {
  1882. ret = AVERROR(EINVAL);
  1883. goto fail;
  1884. }
  1885. av_free(rt->app);
  1886. rt->app = old_app;
  1887. }
  1888. if (!rt->playpath) {
  1889. int len = strlen(fname);
  1890. rt->playpath = av_malloc(PLAYPATH_MAX_LENGTH);
  1891. if (!rt->playpath) {
  1892. ret = AVERROR(ENOMEM);
  1893. goto fail;
  1894. }
  1895. if (!strchr(fname, ':') && len >= 4 &&
  1896. (!strcmp(fname + len - 4, ".f4v") ||
  1897. !strcmp(fname + len - 4, ".mp4"))) {
  1898. memcpy(rt->playpath, "mp4:", 5);
  1899. } else if (len >= 4 && !strcmp(fname + len - 4, ".flv")) {
  1900. fname[len - 4] = '\0';
  1901. } else {
  1902. rt->playpath[0] = 0;
  1903. }
  1904. strncat(rt->playpath, fname, PLAYPATH_MAX_LENGTH - 5);
  1905. }
  1906. if (!rt->tcurl) {
  1907. rt->tcurl = av_malloc(TCURL_MAX_LENGTH);
  1908. if (!rt->tcurl) {
  1909. ret = AVERROR(ENOMEM);
  1910. goto fail;
  1911. }
  1912. ff_url_join(rt->tcurl, TCURL_MAX_LENGTH, proto, NULL, hostname,
  1913. port, "/%s", rt->app);
  1914. }
  1915. if (!rt->flashver) {
  1916. rt->flashver = av_malloc(FLASHVER_MAX_LENGTH);
  1917. if (!rt->flashver) {
  1918. ret = AVERROR(ENOMEM);
  1919. goto fail;
  1920. }
  1921. if (rt->is_input) {
  1922. snprintf(rt->flashver, FLASHVER_MAX_LENGTH, "%s %d,%d,%d,%d",
  1923. RTMP_CLIENT_PLATFORM, RTMP_CLIENT_VER1, RTMP_CLIENT_VER2,
  1924. RTMP_CLIENT_VER3, RTMP_CLIENT_VER4);
  1925. } else {
  1926. snprintf(rt->flashver, FLASHVER_MAX_LENGTH,
  1927. "FMLE/3.0 (compatible; %s)", LIBAVFORMAT_IDENT);
  1928. }
  1929. }
  1930. rt->client_report_size = 1048576;
  1931. rt->bytes_read = 0;
  1932. rt->last_bytes_read = 0;
  1933. rt->server_bw = 2500000;
  1934. av_log(s, AV_LOG_DEBUG, "Proto = %s, path = %s, app = %s, fname = %s\n",
  1935. proto, path, rt->app, rt->playpath);
  1936. if (!rt->listen) {
  1937. if ((ret = gen_connect(s, rt)) < 0)
  1938. goto fail;
  1939. } else {
  1940. if (read_connect(s, s->priv_data) < 0)
  1941. goto fail;
  1942. rt->is_input = 1;
  1943. }
  1944. do {
  1945. ret = get_packet(s, 1);
  1946. } while (ret == EAGAIN);
  1947. if (ret < 0)
  1948. goto fail;
  1949. if (rt->is_input) {
  1950. // generate FLV header for demuxer
  1951. rt->flv_size = 13;
  1952. rt->flv_data = av_realloc(rt->flv_data, rt->flv_size);
  1953. rt->flv_off = 0;
  1954. memcpy(rt->flv_data, "FLV\1\5\0\0\0\011\0\0\0\0", rt->flv_size);
  1955. } else {
  1956. rt->flv_size = 0;
  1957. rt->flv_data = NULL;
  1958. rt->flv_off = 0;
  1959. rt->skip_bytes = 13;
  1960. }
  1961. s->max_packet_size = rt->stream->max_packet_size;
  1962. s->is_streamed = 1;
  1963. return 0;
  1964. fail:
  1965. av_dict_free(&opts);
  1966. rtmp_close(s);
  1967. return ret;
  1968. }
  1969. static int rtmp_read(URLContext *s, uint8_t *buf, int size)
  1970. {
  1971. RTMPContext *rt = s->priv_data;
  1972. int orig_size = size;
  1973. int ret;
  1974. while (size > 0) {
  1975. int data_left = rt->flv_size - rt->flv_off;
  1976. if (data_left >= size) {
  1977. memcpy(buf, rt->flv_data + rt->flv_off, size);
  1978. rt->flv_off += size;
  1979. return orig_size;
  1980. }
  1981. if (data_left > 0) {
  1982. memcpy(buf, rt->flv_data + rt->flv_off, data_left);
  1983. buf += data_left;
  1984. size -= data_left;
  1985. rt->flv_off = rt->flv_size;
  1986. return data_left;
  1987. }
  1988. if ((ret = get_packet(s, 0)) < 0)
  1989. return ret;
  1990. }
  1991. return orig_size;
  1992. }
  1993. static int rtmp_write(URLContext *s, const uint8_t *buf, int size)
  1994. {
  1995. RTMPContext *rt = s->priv_data;
  1996. int size_temp = size;
  1997. int pktsize, pkttype;
  1998. uint32_t ts;
  1999. const uint8_t *buf_temp = buf;
  2000. uint8_t c;
  2001. int ret;
  2002. do {
  2003. if (rt->skip_bytes) {
  2004. int skip = FFMIN(rt->skip_bytes, size_temp);
  2005. buf_temp += skip;
  2006. size_temp -= skip;
  2007. rt->skip_bytes -= skip;
  2008. continue;
  2009. }
  2010. if (rt->flv_header_bytes < 11) {
  2011. const uint8_t *header = rt->flv_header;
  2012. int copy = FFMIN(11 - rt->flv_header_bytes, size_temp);
  2013. bytestream_get_buffer(&buf_temp, rt->flv_header + rt->flv_header_bytes, copy);
  2014. rt->flv_header_bytes += copy;
  2015. size_temp -= copy;
  2016. if (rt->flv_header_bytes < 11)
  2017. break;
  2018. pkttype = bytestream_get_byte(&header);
  2019. pktsize = bytestream_get_be24(&header);
  2020. ts = bytestream_get_be24(&header);
  2021. ts |= bytestream_get_byte(&header) << 24;
  2022. bytestream_get_be24(&header);
  2023. rt->flv_size = pktsize;
  2024. //force 12bytes header
  2025. if (((pkttype == RTMP_PT_VIDEO || pkttype == RTMP_PT_AUDIO) && ts == 0) ||
  2026. pkttype == RTMP_PT_NOTIFY) {
  2027. if (pkttype == RTMP_PT_NOTIFY)
  2028. pktsize += 16;
  2029. rt->prev_pkt[1][RTMP_SOURCE_CHANNEL].channel_id = 0;
  2030. }
  2031. //this can be a big packet, it's better to send it right here
  2032. if ((ret = ff_rtmp_packet_create(&rt->out_pkt, RTMP_SOURCE_CHANNEL,
  2033. pkttype, ts, pktsize)) < 0)
  2034. return ret;
  2035. rt->out_pkt.extra = rt->main_channel_id;
  2036. rt->flv_data = rt->out_pkt.data;
  2037. if (pkttype == RTMP_PT_NOTIFY)
  2038. ff_amf_write_string(&rt->flv_data, "@setDataFrame");
  2039. }
  2040. if (rt->flv_size - rt->flv_off > size_temp) {
  2041. bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, size_temp);
  2042. rt->flv_off += size_temp;
  2043. size_temp = 0;
  2044. } else {
  2045. bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, rt->flv_size - rt->flv_off);
  2046. size_temp -= rt->flv_size - rt->flv_off;
  2047. rt->flv_off += rt->flv_size - rt->flv_off;
  2048. }
  2049. if (rt->flv_off == rt->flv_size) {
  2050. rt->skip_bytes = 4;
  2051. if ((ret = rtmp_send_packet(rt, &rt->out_pkt, 0)) < 0)
  2052. return ret;
  2053. rt->flv_size = 0;
  2054. rt->flv_off = 0;
  2055. rt->flv_header_bytes = 0;
  2056. rt->flv_nb_packets++;
  2057. }
  2058. } while (buf_temp - buf < size);
  2059. if (rt->flv_nb_packets < rt->flush_interval)
  2060. return size;
  2061. rt->flv_nb_packets = 0;
  2062. /* set stream into nonblocking mode */
  2063. rt->stream->flags |= AVIO_FLAG_NONBLOCK;
  2064. /* try to read one byte from the stream */
  2065. ret = ffurl_read(rt->stream, &c, 1);
  2066. /* switch the stream back into blocking mode */
  2067. rt->stream->flags &= ~AVIO_FLAG_NONBLOCK;
  2068. if (ret == AVERROR(EAGAIN)) {
  2069. /* no incoming data to handle */
  2070. return size;
  2071. } else if (ret < 0) {
  2072. return ret;
  2073. } else if (ret == 1) {
  2074. RTMPPacket rpkt = { 0 };
  2075. if ((ret = ff_rtmp_packet_read_internal(rt->stream, &rpkt,
  2076. rt->in_chunk_size,
  2077. rt->prev_pkt[0], c)) <= 0)
  2078. return ret;
  2079. if ((ret = rtmp_parse_result(s, rt, &rpkt)) < 0)
  2080. return ret;
  2081. ff_rtmp_packet_destroy(&rpkt);
  2082. }
  2083. return size;
  2084. }
  2085. #define OFFSET(x) offsetof(RTMPContext, x)
  2086. #define DEC AV_OPT_FLAG_DECODING_PARAM
  2087. #define ENC AV_OPT_FLAG_ENCODING_PARAM
  2088. static const AVOption rtmp_options[] = {
  2089. {"rtmp_app", "Name of application to connect to on the RTMP server", OFFSET(app), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
  2090. {"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},
  2091. {"rtmp_conn", "Append arbitrary AMF data to the Connect message", OFFSET(conn), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
  2092. {"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},
  2093. {"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},
  2094. {"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"},
  2095. {"any", "both", 0, AV_OPT_TYPE_CONST, {.i64 = -2}, 0, 0, DEC, "rtmp_live"},
  2096. {"live", "live stream", 0, AV_OPT_TYPE_CONST, {.i64 = -1}, 0, 0, DEC, "rtmp_live"},
  2097. {"recorded", "recorded stream", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, DEC, "rtmp_live"},
  2098. {"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},
  2099. {"rtmp_playpath", "Stream identifier to play or to publish", OFFSET(playpath), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
  2100. {"rtmp_subscribe", "Name of live stream to subscribe to. Defaults to rtmp_playpath.", OFFSET(subscribe), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC},
  2101. {"rtmp_swfhash", "SHA256 hash of the decompressed SWF file (32 bytes).", OFFSET(swfhash), AV_OPT_TYPE_BINARY, .flags = DEC},
  2102. {"rtmp_swfsize", "Size of the decompressed SWF file, required for SWFVerification.", OFFSET(swfsize), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC},
  2103. {"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},
  2104. {"rtmp_swfverify", "URL to player swf file, compute hash/size automatically.", OFFSET(swfverify), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC},
  2105. {"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},
  2106. {"rtmp_listen", "Listen for incoming rtmp connections", OFFSET(listen), AV_OPT_TYPE_INT, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtmp_listen" },
  2107. {"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" },
  2108. { NULL },
  2109. };
  2110. #define RTMP_PROTOCOL(flavor) \
  2111. static const AVClass flavor##_class = { \
  2112. .class_name = #flavor, \
  2113. .item_name = av_default_item_name, \
  2114. .option = rtmp_options, \
  2115. .version = LIBAVUTIL_VERSION_INT, \
  2116. }; \
  2117. \
  2118. URLProtocol ff_##flavor##_protocol = { \
  2119. .name = #flavor, \
  2120. .url_open = rtmp_open, \
  2121. .url_read = rtmp_read, \
  2122. .url_write = rtmp_write, \
  2123. .url_close = rtmp_close, \
  2124. .priv_data_size = sizeof(RTMPContext), \
  2125. .flags = URL_PROTOCOL_FLAG_NETWORK, \
  2126. .priv_data_class= &flavor##_class, \
  2127. };
  2128. RTMP_PROTOCOL(rtmp)
  2129. RTMP_PROTOCOL(rtmpe)
  2130. RTMP_PROTOCOL(rtmps)
  2131. RTMP_PROTOCOL(rtmpt)
  2132. RTMP_PROTOCOL(rtmpte)
  2133. RTMP_PROTOCOL(rtmpts)