1 /*
2  * RTMP network protocol
3  * Copyright (c) 2010 Howard Chu
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 /**
23  * @file
24  * RTMP protocol based on http://rtmpdump.mplayerhq.hu/ librtmp
25  */
26 
27 #include "libavutil/avstring.h"
28 #include "libavutil/bprint.h"
29 #include "libavutil/mathematics.h"
30 #include "libavutil/opt.h"
31 #include "avformat.h"
32 #if CONFIG_NETWORK
33 #include "network.h"
34 #endif
35 #include "url.h"
36 
37 #include <librtmp/rtmp.h>
38 #include <librtmp/log.h>
39 
40 typedef struct LibRTMPContext {
41     const AVClass *class;
42     AVBPrint filename;
43     RTMP rtmp;
44     char *app;
45     char *conn;
46     char *subscribe;
47     char *playpath;
48     char *tcurl;
49     char *flashver;
50     char *swfurl;
51     char *swfverify;
52     char *pageurl;
53     char *client_buffer_time;
54     int live;
55     int buffer_size;
56 } LibRTMPContext;
57 
rtmp_log(int level, const char *fmt, va_list args)58 static void rtmp_log(int level, const char *fmt, va_list args)
59 {
60     switch (level) {
61     default:
62     case RTMP_LOGCRIT:    level = AV_LOG_FATAL;   break;
63     case RTMP_LOGERROR:   level = AV_LOG_ERROR;   break;
64     case RTMP_LOGWARNING: level = AV_LOG_WARNING; break;
65     case RTMP_LOGINFO:    level = AV_LOG_INFO;    break;
66     case RTMP_LOGDEBUG:   level = AV_LOG_VERBOSE; break;
67     case RTMP_LOGDEBUG2:  level = AV_LOG_DEBUG;   break;
68     }
69 
70     av_vlog(NULL, level, fmt, args);
71     av_log(NULL, level, "\n");
72 }
73 
rtmp_close(URLContext *s)74 static int rtmp_close(URLContext *s)
75 {
76     LibRTMPContext *ctx = s->priv_data;
77     RTMP *r = &ctx->rtmp;
78 
79     RTMP_Close(r);
80     av_bprint_finalize(&ctx->filename, NULL);
81     return 0;
82 }
83 
84 /**
85  * Open RTMP connection and verify that the stream can be played.
86  *
87  * URL syntax: rtmp://server[:port][/app][/playpath][ keyword=value]...
88  *             where 'app' is first one or two directories in the path
89  *             (e.g. /ondemand/, /flash/live/, etc.)
90  *             and 'playpath' is a file name (the rest of the path,
91  *             may be prefixed with "mp4:")
92  *
93  *             Additional RTMP library options may be appended as
94  *             space-separated key-value pairs.
95  */
rtmp_open(URLContext *s, const char *uri, int flags)96 static int rtmp_open(URLContext *s, const char *uri, int flags)
97 {
98     LibRTMPContext *ctx = s->priv_data;
99     RTMP *r = &ctx->rtmp;
100     int rc = 0, level;
101     /* This needs to stay allocated for as long as the RTMP context exists. */
102     av_bprint_init(&ctx->filename, 0, AV_BPRINT_SIZE_UNLIMITED);
103 
104     switch (av_log_get_level()) {
105     default:
106     case AV_LOG_FATAL:   level = RTMP_LOGCRIT;    break;
107     case AV_LOG_ERROR:   level = RTMP_LOGERROR;   break;
108     case AV_LOG_WARNING: level = RTMP_LOGWARNING; break;
109     case AV_LOG_INFO:    level = RTMP_LOGINFO;    break;
110     case AV_LOG_VERBOSE: level = RTMP_LOGDEBUG;   break;
111     case AV_LOG_DEBUG:   level = RTMP_LOGDEBUG2;  break;
112     }
113     RTMP_LogSetLevel(level);
114     RTMP_LogSetCallback(rtmp_log);
115 
116     av_bprintf(&ctx->filename, "%s", s->filename);
117     if (ctx->app)
118         av_bprintf(&ctx->filename, " app=%s", ctx->app);
119     if (ctx->tcurl)
120         av_bprintf(&ctx->filename, " tcUrl=%s", ctx->tcurl);
121     if (ctx->pageurl)
122         av_bprintf(&ctx->filename, " pageUrl=%s", ctx->pageurl);
123     if (ctx->swfurl)
124         av_bprintf(&ctx->filename, " swfUrl=%s", ctx->swfurl);
125     if (ctx->flashver)
126         av_bprintf(&ctx->filename, " flashVer=%s", ctx->flashver);
127     if (ctx->conn) {
128         char *sep, *p = ctx->conn;
129         while (p) {
130             av_bprintf(&ctx->filename,  " conn=");
131             p += strspn(p, " ");
132             if (!*p)
133                 break;
134             sep = strchr(p, ' ');
135             if (sep)
136                 *sep = '\0';
137             av_bprintf(&ctx->filename, "%s", p);
138 
139             if (sep)
140                 p = sep + 1;
141             else
142                 break;
143         }
144     }
145     if (ctx->playpath)
146         av_bprintf(&ctx->filename, " playpath=%s", ctx->playpath);
147     if (ctx->live)
148         av_bprintf(&ctx->filename, " live=1");
149     if (ctx->subscribe)
150         av_bprintf(&ctx->filename, " subscribe=%s", ctx->subscribe);
151     if (ctx->client_buffer_time)
152         av_bprintf(&ctx->filename, " buffer=%s", ctx->client_buffer_time);
153     if (ctx->swfurl || ctx->swfverify) {
154         if (ctx->swfverify)
155             av_bprintf(&ctx->filename, " swfUrl=%s swfVfy=1", ctx->swfverify);
156         else
157             av_bprintf(&ctx->filename, " swfUrl=%s", ctx->swfurl);
158     }
159 
160     if (!av_bprint_is_complete(&ctx->filename)) {
161         av_bprint_finalize(&ctx->filename, NULL);
162         return AVERROR(ENOMEM);
163     }
164 
165     RTMP_Init(r);
166     /* This will modify filename by null terminating the URL portion */
167     if (!RTMP_SetupURL(r, ctx->filename.str)) {
168         rc = AVERROR_UNKNOWN;
169         goto fail;
170     }
171 
172     if (flags & AVIO_FLAG_WRITE)
173         RTMP_EnableWrite(r);
174 
175     if (!RTMP_Connect(r, NULL) || !RTMP_ConnectStream(r, 0)) {
176         rc = AVERROR_UNKNOWN;
177         goto fail;
178     }
179 
180 #if CONFIG_NETWORK
181     if (ctx->buffer_size >= 0 && (flags & AVIO_FLAG_WRITE)) {
182         int tmp = ctx->buffer_size;
183         if (setsockopt(r->m_sb.sb_socket, SOL_SOCKET, SO_SNDBUF, &tmp, sizeof(tmp))) {
184             rc = AVERROR_EXTERNAL;
185             goto fail;
186         }
187     }
188 #endif
189 
190     s->is_streamed = 1;
191     return 0;
192 fail:
193 
194     if (rc)
195         RTMP_Close(r);
196     av_bprint_finalize(&ctx->filename, NULL);
197 
198     return rc;
199 }
200 
rtmp_write(URLContext *s, const uint8_t *buf, int size)201 static int rtmp_write(URLContext *s, const uint8_t *buf, int size)
202 {
203     LibRTMPContext *ctx = s->priv_data;
204     RTMP *r = &ctx->rtmp;
205 
206     int ret = RTMP_Write(r, buf, size);
207     if (!ret)
208         return AVERROR_EOF;
209     return ret;
210 }
211 
rtmp_read(URLContext *s, uint8_t *buf, int size)212 static int rtmp_read(URLContext *s, uint8_t *buf, int size)
213 {
214     LibRTMPContext *ctx = s->priv_data;
215     RTMP *r = &ctx->rtmp;
216 
217     int ret = RTMP_Read(r, buf, size);
218     if (!ret)
219         return AVERROR_EOF;
220     return ret;
221 }
222 
rtmp_read_pause(URLContext *s, int pause)223 static int rtmp_read_pause(URLContext *s, int pause)
224 {
225     LibRTMPContext *ctx = s->priv_data;
226     RTMP *r = &ctx->rtmp;
227 
228     if (!RTMP_Pause(r, pause))
229         return AVERROR_UNKNOWN;
230     return 0;
231 }
232 
rtmp_read_seek(URLContext *s, int stream_index, int64_t timestamp, int flags)233 static int64_t rtmp_read_seek(URLContext *s, int stream_index,
234                               int64_t timestamp, int flags)
235 {
236     LibRTMPContext *ctx = s->priv_data;
237     RTMP *r = &ctx->rtmp;
238 
239     if (flags & AVSEEK_FLAG_BYTE)
240         return AVERROR(ENOSYS);
241 
242     /* seeks are in milliseconds */
243     if (stream_index < 0)
244         timestamp = av_rescale_rnd(timestamp, 1000, AV_TIME_BASE,
245             flags & AVSEEK_FLAG_BACKWARD ? AV_ROUND_DOWN : AV_ROUND_UP);
246 
247     if (!RTMP_SendSeek(r, timestamp))
248         return AVERROR_UNKNOWN;
249     return timestamp;
250 }
251 
rtmp_get_file_handle(URLContext *s)252 static int rtmp_get_file_handle(URLContext *s)
253 {
254     LibRTMPContext *ctx = s->priv_data;
255     RTMP *r = &ctx->rtmp;
256 
257     return RTMP_Socket(r);
258 }
259 
260 #define OFFSET(x) offsetof(LibRTMPContext, x)
261 #define DEC AV_OPT_FLAG_DECODING_PARAM
262 #define ENC AV_OPT_FLAG_ENCODING_PARAM
263 static const AVOption options[] = {
264     {"rtmp_app", "Name of application to connect to on the RTMP server", OFFSET(app), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
265     {"rtmp_buffer", "Set buffer time in milliseconds. The default is 3000.", OFFSET(client_buffer_time), AV_OPT_TYPE_STRING, {.str = "3000"}, 0, 0, DEC|ENC},
266     {"rtmp_conn", "Append arbitrary AMF data to the Connect message", OFFSET(conn), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
267     {"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},
268     {"rtmp_live", "Specify that the media is a live stream.", OFFSET(live), AV_OPT_TYPE_INT, {.i64 = 0}, INT_MIN, INT_MAX, DEC, "rtmp_live"},
269     {"any", "both", 0, AV_OPT_TYPE_CONST, {.i64 = -2}, 0, 0, DEC, "rtmp_live"},
270     {"live", "live stream", 0, AV_OPT_TYPE_CONST, {.i64 = -1}, 0, 0, DEC, "rtmp_live"},
271     {"recorded", "recorded stream", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, DEC, "rtmp_live"},
272     {"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},
273     {"rtmp_playpath", "Stream identifier to play or to publish", OFFSET(playpath), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC|ENC},
274     {"rtmp_subscribe", "Name of live stream to subscribe to. Defaults to rtmp_playpath.", OFFSET(subscribe), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC},
275     {"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},
276     {"rtmp_swfverify", "URL to player swf file, compute hash/size automatically. (unimplemented)", OFFSET(swfverify), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC},
277     {"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},
278 #if CONFIG_NETWORK
279     {"rtmp_buffer_size", "set buffer size in bytes", OFFSET(buffer_size), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, DEC|ENC },
280 #endif
281     { NULL },
282 };
283 
284 #define RTMP_CLASS(flavor)\
285 static const AVClass lib ## flavor ## _class = {\
286     .class_name = "lib" #flavor " protocol",\
287     .item_name  = av_default_item_name,\
288     .option     = options,\
289     .version    = LIBAVUTIL_VERSION_INT,\
290 };
291 
292 RTMP_CLASS(rtmp)
293 const URLProtocol ff_librtmp_protocol = {
294     .name                = "rtmp",
295     .url_open            = rtmp_open,
296     .url_read            = rtmp_read,
297     .url_write           = rtmp_write,
298     .url_close           = rtmp_close,
299     .url_read_pause      = rtmp_read_pause,
300     .url_read_seek       = rtmp_read_seek,
301     .url_get_file_handle = rtmp_get_file_handle,
302     .priv_data_size      = sizeof(LibRTMPContext),
303     .priv_data_class     = &librtmp_class,
304     .flags               = URL_PROTOCOL_FLAG_NETWORK,
305 };
306 
307 RTMP_CLASS(rtmpt)
308 const URLProtocol ff_librtmpt_protocol = {
309     .name                = "rtmpt",
310     .url_open            = rtmp_open,
311     .url_read            = rtmp_read,
312     .url_write           = rtmp_write,
313     .url_close           = rtmp_close,
314     .url_read_pause      = rtmp_read_pause,
315     .url_read_seek       = rtmp_read_seek,
316     .url_get_file_handle = rtmp_get_file_handle,
317     .priv_data_size      = sizeof(LibRTMPContext),
318     .priv_data_class     = &librtmpt_class,
319     .flags               = URL_PROTOCOL_FLAG_NETWORK,
320 };
321 
322 RTMP_CLASS(rtmpe)
323 const URLProtocol ff_librtmpe_protocol = {
324     .name                = "rtmpe",
325     .url_open            = rtmp_open,
326     .url_read            = rtmp_read,
327     .url_write           = rtmp_write,
328     .url_close           = rtmp_close,
329     .url_read_pause      = rtmp_read_pause,
330     .url_read_seek       = rtmp_read_seek,
331     .url_get_file_handle = rtmp_get_file_handle,
332     .priv_data_size      = sizeof(LibRTMPContext),
333     .priv_data_class     = &librtmpe_class,
334     .flags               = URL_PROTOCOL_FLAG_NETWORK,
335 };
336 
337 RTMP_CLASS(rtmpte)
338 const URLProtocol ff_librtmpte_protocol = {
339     .name                = "rtmpte",
340     .url_open            = rtmp_open,
341     .url_read            = rtmp_read,
342     .url_write           = rtmp_write,
343     .url_close           = rtmp_close,
344     .url_read_pause      = rtmp_read_pause,
345     .url_read_seek       = rtmp_read_seek,
346     .url_get_file_handle = rtmp_get_file_handle,
347     .priv_data_size      = sizeof(LibRTMPContext),
348     .priv_data_class     = &librtmpte_class,
349     .flags               = URL_PROTOCOL_FLAG_NETWORK,
350 };
351 
352 RTMP_CLASS(rtmps)
353 const URLProtocol ff_librtmps_protocol = {
354     .name                = "rtmps",
355     .url_open            = rtmp_open,
356     .url_read            = rtmp_read,
357     .url_write           = rtmp_write,
358     .url_close           = rtmp_close,
359     .url_read_pause      = rtmp_read_pause,
360     .url_read_seek       = rtmp_read_seek,
361     .url_get_file_handle = rtmp_get_file_handle,
362     .priv_data_size      = sizeof(LibRTMPContext),
363     .priv_data_class     = &librtmps_class,
364     .flags               = URL_PROTOCOL_FLAG_NETWORK,
365 };
366