]> git.sesse.net Git - ffmpeg/blob - libavformat/mmsh.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavformat / mmsh.c
1 /*
2  * MMS protocol over HTTP
3  * Copyright (c) 2010 Zhentan Feng <spyfeng at gmail dot com>
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  * Reference
24  * Windows Media HTTP Streaming Protocol.
25  * http://msdn.microsoft.com/en-us/library/cc251059(PROT.10).aspx
26  */
27
28 #include <string.h>
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/opt.h"
32 #include "internal.h"
33 #include "mms.h"
34 #include "asf.h"
35 #include "http.h"
36 #include "url.h"
37
38 #define CHUNK_HEADER_LENGTH 4   // 2bytes chunk type and 2bytes chunk length.
39 #define EXT_HEADER_LENGTH   8   // 4bytes sequence, 2bytes useless and 2bytes chunk length.
40
41 // see Ref 2.2.1.8
42 #define USERAGENT  "User-Agent: NSPlayer/4.1.0.3856\r\n"
43 // see Ref 2.2.1.4.33
44 // the guid value can be changed to any valid value.
45 #define CLIENTGUID "Pragma: xClientGUID={c77e7400-738a-11d2-9add-0020af0a3278}\r\n"
46
47 // see Ref 2.2.3 for packet type define:
48 // chunk type contains 2 fields: Frame and PacketID.
49 // Frame is 0x24 or 0xA4(rarely), different PacketID indicates different packet type.
50 typedef enum {
51     CHUNK_TYPE_DATA          = 0x4424,
52     CHUNK_TYPE_ASF_HEADER    = 0x4824,
53     CHUNK_TYPE_END           = 0x4524,
54     CHUNK_TYPE_STREAM_CHANGE = 0x4324,
55 } ChunkType;
56
57 typedef struct {
58     MMSContext mms;
59     uint8_t location[1024];
60     int request_seq;  ///< request packet sequence
61     int chunk_seq;    ///< data packet sequence
62 } MMSHContext;
63
64 static int mmsh_close(URLContext *h)
65 {
66     MMSHContext *mmsh = (MMSHContext *)h->priv_data;
67     MMSContext *mms   = &mmsh->mms;
68     if (mms->mms_hd)
69         ffurl_close(mms->mms_hd);
70     av_free(mms->streams);
71     av_free(mms->asf_header);
72     av_freep(&h->priv_data);
73     return 0;
74 }
75
76 static ChunkType get_chunk_header(MMSHContext *mmsh, int *len)
77 {
78     MMSContext *mms = &mmsh->mms;
79     uint8_t chunk_header[CHUNK_HEADER_LENGTH];
80     uint8_t ext_header[EXT_HEADER_LENGTH];
81     ChunkType chunk_type;
82     int chunk_len, res, ext_header_len;
83
84     res = ffurl_read_complete(mms->mms_hd, chunk_header, CHUNK_HEADER_LENGTH);
85     if (res != CHUNK_HEADER_LENGTH) {
86         av_log(NULL, AV_LOG_ERROR, "Read data packet header failed!\n");
87         return AVERROR(EIO);
88     }
89     chunk_type = AV_RL16(chunk_header);
90     chunk_len  = AV_RL16(chunk_header + 2);
91
92     switch (chunk_type) {
93     case CHUNK_TYPE_END:
94     case CHUNK_TYPE_STREAM_CHANGE:
95         ext_header_len = 4;
96         break;
97     case CHUNK_TYPE_ASF_HEADER:
98     case CHUNK_TYPE_DATA:
99         ext_header_len = 8;
100         break;
101     default:
102         av_log(NULL, AV_LOG_ERROR, "Strange chunk type %d\n", chunk_type);
103         return AVERROR_INVALIDDATA;
104     }
105
106     res = ffurl_read_complete(mms->mms_hd, ext_header, ext_header_len);
107     if (res != ext_header_len) {
108         av_log(NULL, AV_LOG_ERROR, "Read ext header failed!\n");
109         return AVERROR(EIO);
110     }
111     *len = chunk_len - ext_header_len;
112     if (chunk_type == CHUNK_TYPE_END || chunk_type == CHUNK_TYPE_DATA)
113         mmsh->chunk_seq = AV_RL32(ext_header);
114     return chunk_type;
115 }
116
117 static int read_data_packet(MMSHContext *mmsh, const int len)
118 {
119     MMSContext *mms   = &mmsh->mms;
120     int res;
121     if (len > sizeof(mms->in_buffer)) {
122         av_log(NULL, AV_LOG_ERROR,
123                "Data packet length %d exceeds the in_buffer size %zu\n",
124                len, sizeof(mms->in_buffer));
125         return AVERROR(EIO);
126     }
127     res = ffurl_read_complete(mms->mms_hd, mms->in_buffer, len);
128     av_dlog(NULL, "Data packet len = %d\n", len);
129     if (res != len) {
130         av_log(NULL, AV_LOG_ERROR, "Read data packet failed!\n");
131         return AVERROR(EIO);
132     }
133     if (len > mms->asf_packet_len) {
134         av_log(NULL, AV_LOG_ERROR,
135                "Chunk length %d exceed packet length %d\n",len, mms->asf_packet_len);
136         return AVERROR_INVALIDDATA;
137     } else {
138         memset(mms->in_buffer + len, 0, mms->asf_packet_len - len); // padding
139     }
140     mms->read_in_ptr      = mms->in_buffer;
141     mms->remaining_in_len = mms->asf_packet_len;
142     return 0;
143 }
144
145 static int get_http_header_data(MMSHContext *mmsh)
146 {
147     MMSContext *mms = &mmsh->mms;
148     int res, len;
149     ChunkType chunk_type;
150
151     for (;;) {
152         len = 0;
153         res = chunk_type = get_chunk_header(mmsh, &len);
154         if (res < 0) {
155             return res;
156         } else if (chunk_type == CHUNK_TYPE_ASF_HEADER){
157             // get asf header and stored it
158             if (!mms->header_parsed) {
159                 if (mms->asf_header) {
160                     if (len != mms->asf_header_size) {
161                         mms->asf_header_size = len;
162                         av_dlog(NULL, "Header len changed from %d to %d\n",
163                                 mms->asf_header_size, len);
164                         av_freep(&mms->asf_header);
165                     }
166                 }
167                 mms->asf_header = av_mallocz(len);
168                 if (!mms->asf_header) {
169                     return AVERROR(ENOMEM);
170                 }
171                 mms->asf_header_size = len;
172             }
173             if (len > mms->asf_header_size) {
174                 av_log(NULL, AV_LOG_ERROR,
175                        "Asf header packet len = %d exceed the asf header buf size %d\n",
176                        len, mms->asf_header_size);
177                 return AVERROR(EIO);
178             }
179             res = ffurl_read_complete(mms->mms_hd, mms->asf_header, len);
180             if (res != len) {
181                 av_log(NULL, AV_LOG_ERROR,
182                        "Recv asf header data len %d != expected len %d\n", res, len);
183                 return AVERROR(EIO);
184             }
185             mms->asf_header_size = len;
186             if (!mms->header_parsed) {
187                 res = ff_mms_asf_header_parser(mms);
188                 mms->header_parsed = 1;
189                 return res;
190             }
191         } else if (chunk_type == CHUNK_TYPE_DATA) {
192             // read data packet and do padding
193             return read_data_packet(mmsh, len);
194         } else {
195             if (len) {
196                 if (len > sizeof(mms->in_buffer)) {
197                     av_log(NULL, AV_LOG_ERROR,
198                            "Other packet len = %d exceed the in_buffer size %zu\n",
199                            len, sizeof(mms->in_buffer));
200                     return AVERROR(EIO);
201                 }
202                 res = ffurl_read_complete(mms->mms_hd, mms->in_buffer, len);
203                 if (res != len) {
204                     av_log(NULL, AV_LOG_ERROR, "Read other chunk type data failed!\n");
205                     return AVERROR(EIO);
206                 } else {
207                     av_dlog(NULL, "Skip chunk type %d \n", chunk_type);
208                     continue;
209                 }
210             }
211         }
212     }
213 }
214
215 static int mmsh_open_internal(URLContext *h, const char *uri, int flags, int timestamp, int64_t pos)
216 {
217     int i, port, err;
218     char httpname[256], path[256], host[128];
219     char *stream_selection = NULL;
220     char headers[1024];
221     MMSHContext *mmsh;
222     MMSContext *mms;
223
224     mmsh = h->priv_data = av_mallocz(sizeof(MMSHContext));
225     if (!h->priv_data)
226         return AVERROR(ENOMEM);
227     mmsh->request_seq = h->is_streamed = 1;
228     mms = &mmsh->mms;
229     av_strlcpy(mmsh->location, uri, sizeof(mmsh->location));
230
231     av_url_split(NULL, 0, NULL, 0,
232         host, sizeof(host), &port, path, sizeof(path), mmsh->location);
233     if (port<0)
234         port = 80; // default mmsh protocol port
235     ff_url_join(httpname, sizeof(httpname), "http", NULL, host, port, "%s", path);
236
237     if (ffurl_alloc(&mms->mms_hd, httpname, AVIO_FLAG_READ,
238                     &h->interrupt_callback) < 0) {
239         return AVERROR(EIO);
240     }
241
242     snprintf(headers, sizeof(headers),
243              "Accept: */*\r\n"
244              USERAGENT
245              "Host: %s:%d\r\n"
246              "Pragma: no-cache,rate=1.000000,stream-time=0,"
247              "stream-offset=0:0,request-context=%u,max-duration=0\r\n"
248              CLIENTGUID
249              "Connection: Close\r\n",
250              host, port, mmsh->request_seq++);
251     av_opt_set(mms->mms_hd->priv_data, "headers", headers, 0);
252
253     err = ffurl_connect(mms->mms_hd, NULL);
254     if (err) {
255         goto fail;
256     }
257     err = get_http_header_data(mmsh);
258     if (err) {
259         av_log(NULL, AV_LOG_ERROR, "Get http header data failed!\n");
260         goto fail;
261     }
262
263     // close the socket and then reopen it for sending the second play request.
264     ffurl_close(mms->mms_hd);
265     memset(headers, 0, sizeof(headers));
266     if (ffurl_alloc(&mms->mms_hd, httpname, AVIO_FLAG_READ,
267                     &h->interrupt_callback) < 0) {
268         return AVERROR(EIO);
269     }
270     stream_selection = av_mallocz(mms->stream_num * 19 + 1);
271     if (!stream_selection)
272         return AVERROR(ENOMEM);
273     for (i = 0; i < mms->stream_num; i++) {
274         char tmp[20];
275         err = snprintf(tmp, sizeof(tmp), "ffff:%d:0 ", mms->streams[i].id);
276         if (err < 0)
277             goto fail;
278         av_strlcat(stream_selection, tmp, mms->stream_num * 19 + 1);
279     }
280     // send play request
281     err = snprintf(headers, sizeof(headers),
282                    "Accept: */*\r\n"
283                    USERAGENT
284                    "Host: %s:%d\r\n"
285                    "Pragma: no-cache,rate=1.000000,request-context=%u\r\n"
286                    "Pragma: xPlayStrm=1\r\n"
287                    CLIENTGUID
288                    "Pragma: stream-switch-count=%d\r\n"
289                    "Pragma: stream-switch-entry=%s\r\n"
290                    "Pragma: no-cache,rate=1.000000,stream-time=%u"
291                    "Connection: Close\r\n",
292                    host, port, mmsh->request_seq++, mms->stream_num, stream_selection, timestamp);
293     av_freep(&stream_selection);
294     if (err < 0) {
295         av_log(NULL, AV_LOG_ERROR, "Build play request failed!\n");
296         goto fail;
297     }
298     av_dlog(NULL, "out_buffer is %s", headers);
299     av_opt_set(mms->mms_hd->priv_data, "headers", headers, 0);
300
301     err = ffurl_connect(mms->mms_hd, NULL);
302     if (err) {
303           goto fail;
304     }
305
306     err = get_http_header_data(mmsh);
307     if (err) {
308         av_log(NULL, AV_LOG_ERROR, "Get http header data failed!\n");
309         goto fail;
310     }
311
312     av_dlog(NULL, "Connection successfully open\n");
313     return 0;
314 fail:
315     av_freep(&stream_selection);
316     mmsh_close(h);
317     av_dlog(NULL, "Connection failed with error %d\n", err);
318     return err;
319 }
320
321 static int mmsh_open(URLContext *h, const char *uri, int flags)
322 {
323     return mmsh_open_internal(h, uri, flags, 0, 0);
324 }
325
326 static int handle_chunk_type(MMSHContext *mmsh)
327 {
328     MMSContext *mms = &mmsh->mms;
329     int res, len = 0;
330     ChunkType chunk_type;
331     chunk_type = get_chunk_header(mmsh, &len);
332
333     switch (chunk_type) {
334     case CHUNK_TYPE_END:
335         mmsh->chunk_seq = 0;
336         av_log(NULL, AV_LOG_ERROR, "Stream ended!\n");
337         return AVERROR(EIO);
338     case CHUNK_TYPE_STREAM_CHANGE:
339         mms->header_parsed = 0;
340         if (res = get_http_header_data(mmsh)) {
341             av_log(NULL, AV_LOG_ERROR,"Stream changed! Failed to get new header!\n");
342             return res;
343         }
344         break;
345     case CHUNK_TYPE_DATA:
346         return read_data_packet(mmsh, len);
347     default:
348         av_log(NULL, AV_LOG_ERROR, "Recv other type packet %d\n", chunk_type);
349         return AVERROR_INVALIDDATA;
350     }
351     return 0;
352 }
353
354 static int mmsh_read(URLContext *h, uint8_t *buf, int size)
355 {
356     int res = 0;
357     MMSHContext *mmsh = h->priv_data;
358     MMSContext *mms   = &mmsh->mms;
359     do {
360         if (mms->asf_header_read_size < mms->asf_header_size) {
361             // copy asf header into buffer
362             res = ff_mms_read_header(mms, buf, size);
363         } else {
364             if (!mms->remaining_in_len && (res = handle_chunk_type(mmsh)))
365                 return res;
366             res = ff_mms_read_data(mms, buf, size);
367         }
368     } while (!res);
369     return res;
370 }
371
372 static int64_t mmsh_read_seek(URLContext *h, int stream_index,
373                         int64_t timestamp, int flags)
374 {
375     MMSHContext *mmsh = h->priv_data;
376     MMSContext *mms   = &mmsh->mms;
377     int ret;
378
379     ret= mmsh_open_internal(h, mmsh->location, 0, FFMAX(timestamp, 0), 0);
380
381     if(ret>=0){
382         if (mms->mms_hd)
383             ffurl_close(mms->mms_hd);
384         av_freep(&mms->streams);
385         av_freep(&mms->asf_header);
386         av_free(mmsh);
387         mmsh = h->priv_data;
388         mms   = &mmsh->mms;
389         mms->asf_header_read_size= mms->asf_header_size;
390     }else
391         h->priv_data= mmsh;
392     return ret;
393 }
394
395 static int64_t mmsh_seek(URLContext *h, int64_t pos, int whence)
396 {
397     MMSHContext *mmsh = h->priv_data;
398     MMSContext *mms   = &mmsh->mms;
399
400     if(pos == 0 && whence == SEEK_CUR)
401         return mms->asf_header_read_size + mms->remaining_in_len + mmsh->chunk_seq * mms->asf_packet_len;
402     return AVERROR(ENOSYS);
403 }
404
405 URLProtocol ff_mmsh_protocol = {
406     .name      = "mmsh",
407     .url_open  = mmsh_open,
408     .url_read  = mmsh_read,
409     .url_seek  = mmsh_seek,
410     .url_close = mmsh_close,
411     .url_read_seek  = mmsh_read_seek,
412 };