]> git.sesse.net Git - vlc/blob - modules/stream_filter/decomp.c
da86731ecea2bd1091e0d0fe5bc8bb13e002def3
[vlc] / modules / stream_filter / decomp.c
1 /*****************************************************************************
2  * decomp.c : Decompression module for vlc
3  *****************************************************************************
4  * Copyright © 2008 Rémi Denis-Courmont
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as published by
8  * the Free Software Foundation; either version 2.1 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
19  *****************************************************************************/
20
21 #ifdef HAVE_CONFIG_H
22 # include "config.h"
23 #endif
24
25 #include <vlc_common.h>
26 #include <vlc_plugin.h>
27 #include <vlc_stream.h>
28 #include <vlc_network.h>
29 #include <unistd.h>
30 #ifndef _POSIX_SPAWN
31 # define _POSIX_SPAWN (-1)
32 #endif
33 #include <fcntl.h>
34 #include <spawn.h>
35 #include <sys/wait.h>
36 #include <sys/ioctl.h>
37 #if defined (__linux__) && defined (HAVE_VMSPLICE)
38 # include <sys/uio.h>
39 # include <sys/mman.h>
40 #else
41 # undef HAVE_VMSPLICE
42 #endif
43
44 static int  OpenGzip (vlc_object_t *);
45 static int  OpenBzip2 (vlc_object_t *);
46 static void Close (vlc_object_t *);
47
48 vlc_module_begin ()
49     set_description (N_("Decompression"))
50     set_category (CAT_INPUT)
51     set_subcategory (SUBCAT_INPUT_STREAM_FILTER)
52     set_capability ("stream_filter", 20)
53     set_callbacks (OpenBzip2, Close)
54     /* TODO: access shortnames for stream_UrlNew() */
55
56     add_submodule ()
57     set_callbacks (OpenGzip, Close)
58 vlc_module_end ()
59
60 struct stream_sys_t
61 {
62     block_t      *peeked;
63     uint64_t     offset;
64     vlc_thread_t thread;
65     pid_t        pid;
66     int          write_fd, read_fd;
67 };
68
69 static void cloexec (int fd)
70 {
71     int flags = fcntl (fd, F_GETFD);
72     fcntl (fd, F_SETFD, FD_CLOEXEC | ((flags != -1) ? flags : 0));
73 }
74
75 extern char **environ;
76
77 static const size_t bufsize = 65536;
78 #ifdef HAVE_VMSPLICE
79 static void cleanup_mmap (void *addr)
80 {
81     munmap (addr, bufsize);
82 }
83 #endif
84
85 static void *Thread (void *data)
86 {
87     stream_t *stream = data;
88     stream_sys_t *p_sys = stream->p_sys;
89 #ifdef HAVE_VMSPLICE
90     ssize_t page_mask = sysconf (_SC_PAGE_SIZE) - 1;
91 #endif
92     int fd = p_sys->write_fd;
93     bool error = false;
94
95     do
96     {
97         ssize_t len;
98         int canc = vlc_savecancel ();
99 #ifdef HAVE_VMSPLICE
100         unsigned char *buf = mmap (NULL, bufsize, PROT_READ|PROT_WRITE,
101                                    MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
102         vlc_cleanup_push (cleanup_mmap, buf);
103 #else
104         unsigned char buf[bufsize];
105 #endif
106
107         len = stream_Read (stream->p_source, buf, bufsize);
108         vlc_restorecancel (canc);
109         error = len <= 0;
110
111         for (ssize_t i = 0, j; i < len; i += j)
112         {
113 #ifdef HAVE_VMSPLICE
114             if ((len - i) <= page_mask) /* incomplete last page */
115                 j = write (fd, buf + i, len - i);
116             else
117             {
118                 struct iovec iov = { buf + i, (len - i) & ~page_mask, };
119                 j = vmsplice (fd, &iov, 1, SPLICE_F_GIFT);
120             }
121 #else
122             j = write (fd, buf + i, len - i);
123 #endif
124             if (j <= 0)
125             {
126                 if (j == 0)
127                     errno = EPIPE;
128                 msg_Err (stream, "cannot write data (%m)");
129                 error = true;
130                 break;
131             }
132         }
133 #ifdef HAVE_VMSPLICE
134         vlc_cleanup_run (); /* munmap (buf, bufsize) */
135 #endif
136     }
137     while (!error);
138
139     msg_Dbg (stream, "compressed stream at EOF");
140     return NULL;
141 }
142
143
144 #define MIN_BLOCK (1 << 10)
145 #define MAX_BLOCK (1 << 20)
146 /**
147  * Reads decompressed from the decompression program
148  * @return -1 for EAGAIN, 0 for EOF, byte count otherwise.
149  */
150 static int Read (stream_t *stream, void *buf, unsigned int buflen)
151 {
152     stream_sys_t *p_sys = stream->p_sys;
153     block_t *peeked;
154     size_t bonus = 0;
155     ssize_t length;
156
157     if ((peeked = p_sys->peeked) != NULL)
158     {
159         bonus = (buflen > peeked->i_buffer) ? peeked->i_buffer : buflen;
160         memcpy (buf, peeked->p_buffer, bonus);
161         peeked->p_buffer += bonus;
162         peeked->i_buffer -= bonus;
163         if (peeked->i_buffer == 0)
164         {
165             block_Release (peeked);
166             p_sys->peeked = NULL;
167         }
168     }
169
170     length = net_Read (stream, p_sys->read_fd, NULL, buf, buflen, false);
171     if (length < 0)
172         return 0;
173     length += bonus;
174     p_sys->offset += length;
175     return length;
176 }
177
178 /**
179  *
180  */
181 static int Peek (stream_t *stream, const uint8_t **pbuf, unsigned int len)
182 {
183     stream_sys_t *p_sys = stream->p_sys;
184     block_t *peeked = p_sys->peeked;
185     size_t curlen = 0;
186     int fd = p_sys->read_fd;
187
188     if (peeked == NULL)
189         peeked = block_Alloc (len);
190     else if ((curlen = peeked->i_buffer) < len)
191         peeked = block_Realloc (peeked, 0, len);
192
193     if ((p_sys->peeked = peeked) == NULL)
194         return 0;
195
196     if (curlen < len)
197     {
198         ssize_t val = net_Read (stream, fd, NULL, peeked->p_buffer + curlen,
199                                 len - curlen, true);
200         if (val >= 0)
201         {
202             curlen += val;
203             peeked->i_buffer = curlen;
204         }
205     }
206     *pbuf = peeked->p_buffer;
207     return curlen;
208 }
209
210 /**
211  *
212  */
213 static int Control (stream_t *stream, int query, va_list args)
214 {
215     stream_sys_t *p_sys = stream->p_sys;
216
217     switch (query)
218     {
219         case STREAM_CAN_SEEK:
220         case STREAM_CAN_FASTSEEK:
221             *(va_arg (args, bool *)) = false;
222             break;
223         case STREAM_GET_POSITION:
224             *(va_arg (args, int64_t *)) = p_sys->offset;
225             break;
226         case STREAM_GET_SIZE:
227             *(va_arg (args, int64_t *)) = 0;
228             break;
229         case STREAM_GET_MTU:
230             *(va_arg (args, int *)) = 0;
231             break;
232         default:
233             return VLC_EGENERIC;
234     }
235     return VLC_SUCCESS;
236 }
237
238 /**
239  * Pipe data through an external executable.
240  * @param stream the stream filter object.
241  * @param path path to the executable.
242  */
243 static int Open (stream_t *stream, const char *path)
244 {
245     stream_sys_t *p_sys = stream->p_sys = malloc (sizeof (*p_sys));
246     if (p_sys == NULL)
247         return VLC_ENOMEM;
248
249     stream->pf_read = Read;
250     stream->pf_peek = Peek;
251     stream->pf_control = Control;
252     p_sys->peeked = NULL;
253     p_sys->offset = 0;
254     p_sys->pid = -1;
255
256     /* I am not a big fan of the pyramid style, but I cannot think of anything
257      * better here. There are too many failure cases. */
258     int ret = VLC_EGENERIC;
259     int comp[2];
260
261     /* We use two pipes rather than one stream socket pair, so that we can
262      * use vmsplice() on Linux. */
263     if (pipe (comp) == 0)
264     {
265         cloexec (comp[1]);
266         p_sys->write_fd = comp[1];
267
268         int uncomp[2];
269         if (pipe (uncomp) == 0)
270         {
271             cloexec (uncomp[0]);
272             p_sys->read_fd = uncomp[0];
273
274 #if (_POSIX_SPAWN >= 0)
275             posix_spawn_file_actions_t actions;
276             if (posix_spawn_file_actions_init (&actions) == 0)
277             {
278                 char *const argv[] = { (char *)path, NULL };
279
280                 if (!posix_spawn_file_actions_adddup2 (&actions, comp[0], 0)
281                  && !posix_spawn_file_actions_addclose (&actions, comp[0])
282                  && !posix_spawn_file_actions_adddup2 (&actions, uncomp[1], 1)
283                  && !posix_spawn_file_actions_addclose (&actions, uncomp[1])
284                  && !posix_spawnp (&p_sys->pid, path, &actions, NULL, argv,
285                                    environ))
286                 {
287                     if (vlc_clone (&p_sys->thread, Thread, stream,
288                                    VLC_THREAD_PRIORITY_INPUT) == 0)
289                         ret = VLC_SUCCESS;
290                 }
291                 else
292                 {
293                     msg_Err (stream, "Cannot execute %s", path);
294                     p_sys->pid = -1;
295                 }
296                 posix_spawn_file_actions_destroy (&actions);
297             }
298 #else /* _POSIX_SPAWN */
299             switch (p_sys->pid = fork ())
300             {
301                 case -1:
302                     msg_Err (stream, "Cannot fork (%m)");
303                     break;
304                 case 0:
305                     dup2 (comp[0], 0);
306                     close (comp[0]);
307                     dup2 (uncomp[1], 1);
308                     close (uncomp[1]);
309                     execlp (path, path, (char *)NULL);
310                     exit (1); /* if we get, execlp() failed! */
311                 default:
312                     if (vlc_clone (&p_sys->thread, Thread, stream,
313                                    VLC_THREAD_PRIORITY_INPUT) == 0)
314                         ret = VLC_SUCCESS;
315             }
316 #endif /* _POSIX_SPAWN < 0 */
317             close (uncomp[1]);
318             if (ret != VLC_SUCCESS)
319                 close (uncomp[0]);
320         }
321         close (comp[0]);
322         if (ret != VLC_SUCCESS)
323         {
324             close (comp[1]);
325             if (p_sys->pid != -1)
326                 while (waitpid (p_sys->pid, &(int){ 0 }, 0) == -1);
327         }
328     }
329     return ret;
330 }
331
332
333 /**
334  * Releases allocate resources.
335  */
336 static void Close (vlc_object_t *obj)
337 {
338     stream_t *stream = (stream_t *)obj;
339     stream_sys_t *p_sys = stream->p_sys;
340     int status;
341
342     vlc_cancel (p_sys->thread);
343     close (p_sys->read_fd);
344     vlc_join (p_sys->thread, NULL);
345     close (p_sys->write_fd);
346
347     msg_Dbg (obj, "waiting for PID %u", (unsigned)p_sys->pid);
348     while (waitpid (p_sys->pid, &status, 0) == -1);
349     msg_Dbg (obj, "exit status %d", status);
350
351     if (p_sys->peeked)
352         block_Release (p_sys->peeked);
353     free (p_sys);
354 }
355
356
357 /**
358  * Detects gzip file format
359  */
360 static int OpenGzip (vlc_object_t *obj)
361 {
362     stream_t      *stream = (stream_t *)obj;
363     const uint8_t *peek;
364
365     if (stream_Peek (stream->p_source, &peek, 3) < 3)
366         return VLC_EGENERIC;
367
368     if (memcmp (peek, "\x1f\x8b\x08", 3))
369         return VLC_EGENERIC;
370
371     msg_Dbg (obj, "detected gzip compressed stream");
372     return Open (stream, "zcat");
373 }
374
375
376 /**
377  * Detects bzip2 file format
378  */
379 static int OpenBzip2 (vlc_object_t *obj)
380 {
381     stream_t      *stream = (stream_t *)obj;
382     const uint8_t *peek;
383
384     /* (Try to) parse the bzip2 header */
385     if (stream_Peek (stream->p_source, &peek, 10) < 10)
386         return VLC_EGENERIC;
387
388     if (memcmp (peek, "BZh", 3) || (peek[3] < '1') || (peek[3] > '9')
389      || memcmp (peek + 4, "\x31\x41\x59\x26\x53\x59", 6))
390         return VLC_EGENERIC;
391
392     msg_Dbg (obj, "detected bzip2 compressed stream");
393     return Open (stream, "bzcat");
394 }
395