never throw stream errors in case of MPEG 1 or MPEG 2 streams
[gst-plugin-dvbmediasink.git] / src / gstdvbvideosink.c
1 /*
2  * GStreamer DVB Media Sink
3  * Copyright 2006 Felix Domke <tmbinc@elitedvb.net>
4  * based on code by:
5  * Copyright 2005 Thomas Vander Stichele <thomas@apestaart.org>
6  * Copyright 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
7  * 
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the "Software"),
10  * to deal in the Software without restriction, including without limitation
11  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12  * and/or sell copies of the Software, and to permit persons to whom the
13  * Software is furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24  * DEALINGS IN THE SOFTWARE.
25  *
26  * Alternatively, the contents of this file may be used under the
27  * GNU Lesser General Public License Version 2.1 (the "LGPL"), in
28  * which case the following provisions apply instead of the ones
29  * mentioned above:
30  *
31  * This library is free software; you can redistribute it and/or
32  * modify it under the terms of the GNU Library General Public
33  * License as published by the Free Software Foundation; either
34  * version 2 of the License, or (at your option) any later version.
35  *
36  * This library is distributed in the hope that it will be useful,
37  * but WITHOUT ANY WARRANTY; without even the implied warranty of
38  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
39  * Library General Public License for more details.
40  *
41  * You should have received a copy of the GNU Library General Public
42  * License along with this library; if not, write to the
43  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
44  * Boston, MA 02111-1307, USA.
45  */
46
47 /**
48  * SECTION:element-plugin
49  *
50  * <refsect2>
51  * <title>Example launch line</title>
52  * <para>
53  * <programlisting>
54  * gst-launch -v -m audiotestsrc ! plugin ! fakesink silent=TRUE
55  * </programlisting>
56  * </para>
57  * </refsect2>
58  */
59
60 #ifdef HAVE_CONFIG_H
61 #include <config.h>
62 #endif
63 #include <unistd.h>
64 #include <sys/ioctl.h>
65 #include <sys/socket.h>
66 #include <linux/dvb/video.h>
67 #include <fcntl.h>
68 #include <string.h>
69
70 #include <gst/gst.h>
71
72 #include "gstdvbvideosink.h"
73
74 #ifndef VIDEO_GET_PTS
75 #define VIDEO_GET_PTS              _IOR('o', 57, gint64)
76 #endif
77
78 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
79 struct bitstream
80 {
81         guint8 *data;
82         guint8 last;
83         int avail;
84 };
85
86 void bitstream_init(struct bitstream *bit, const void *buffer, gboolean wr)
87 {
88         bit->data = (guint8*) buffer;
89         if (wr) {
90                 bit->avail = 0;
91                 bit->last = 0;
92         }
93         else {
94                 bit->avail = 8;
95                 bit->last = *bit->data++;
96         }
97 }
98
99 unsigned long bitstream_get(struct bitstream *bit, int bits)
100 {
101         unsigned long res=0;
102         while (bits)
103         {
104                 unsigned int d=bits;
105                 if (!bit->avail) {
106                         bit->last = *bit->data++;
107                         bit->avail = 8;
108                 }
109                 if (d > bit->avail)
110                         d=bit->avail;
111                 res<<=d;
112                 res|=(bit->last>>(bit->avail-d))&~(-1<<d);
113                 bit->avail-=d;
114                 bits-=d;
115         }
116         return res;
117 }
118
119 void bitstream_put(struct bitstream *bit, unsigned long val, int bits)
120 {
121         while (bits)
122         {
123                 bit->last |= ((val & (1 << (bits-1))) ? 1 : 0) << (7 - bit->avail);
124                 if (++bit->avail == 8) {
125                         *bit->data = bit->last;
126                         ++bit->data;
127                         bit->last = 0;
128                         bit->avail = 0;
129                 }
130                 --bits;
131         }
132 }
133 #endif
134
135 /* We add a control socket as in fdsrc to make it shutdown quickly when it's blocking on the fd.
136  * Select is used to determine when the fd is ready for use. When the element state is changed,
137  * it happens from another thread while fdsink is select'ing on the fd. The state-change thread 
138  * sends a control message, so fdsink wakes up and changes state immediately otherwise
139  * it would stay blocked until it receives some data. */
140
141 /* the select call is also performed on the control sockets, that way
142  * we can send special commands to unblock the select call */
143 #define CONTROL_STOP                                            'S'              /* stop the select call */
144 #define CONTROL_SOCKETS(sink)    sink->control_sock
145 #define WRITE_SOCKET(sink)                      sink->control_sock[1]
146 #define READ_SOCKET(sink)                        sink->control_sock[0]
147
148 #define SEND_COMMAND(sink, command)                                     \
149 G_STMT_START {                                                                                                                  \
150         unsigned char c; c = command;                                            \
151         write (WRITE_SOCKET(sink), &c, 1);                               \
152 } G_STMT_END
153
154 #define READ_COMMAND(sink, command, res)                                \
155 G_STMT_START {                                                                                                                           \
156         res = read(READ_SOCKET(sink), &command, 1);      \
157 } G_STMT_END
158
159 GST_DEBUG_CATEGORY_STATIC (dvbvideosink_debug);
160 #define GST_CAT_DEFAULT dvbvideosink_debug
161
162 /* Filter signals and args */
163 enum {
164         /* FILL ME */
165         LAST_SIGNAL
166 };
167
168 enum {
169         ARG_0,
170         ARG_SILENT
171 };
172
173 #define COMMON_VIDEO_CAPS \
174   "width = (int) [ 16, 4096 ], " \
175   "height = (int) [ 16, 4096 ], " \
176   "framerate = (fraction) [ 0, MAX ]"
177
178 static GstStaticPadTemplate sink_factory =
179 GST_STATIC_PAD_TEMPLATE (
180         "sink",
181         GST_PAD_SINK,
182         GST_PAD_ALWAYS,
183         GST_STATIC_CAPS ("video/mpeg, "
184                 "mpegversion = (int) { 1, 2, 4 }, "
185                 "systemstream = (boolean) false, "
186         COMMON_VIDEO_CAPS "; "
187                 "video/x-wmv, "
188         COMMON_VIDEO_CAPS "; "
189                 "video/x-h264, "
190         COMMON_VIDEO_CAPS "; "
191                 "video/x-h263, "
192         COMMON_VIDEO_CAPS "; "
193                 "video/x-divx, "
194         COMMON_VIDEO_CAPS ", divxversion = (int) [ 3, 5 ]; "
195                 "video/x-xvid, " COMMON_VIDEO_CAPS )
196 );
197
198 #define DEBUG_INIT(bla) \
199         GST_DEBUG_CATEGORY_INIT (dvbvideosink_debug, "dvbvideosink", 0, "dvbvideosink element");
200
201 GST_BOILERPLATE_FULL (GstDVBVideoSink, gst_dvbvideosink, GstBaseSink,
202         GST_TYPE_BASE_SINK, DEBUG_INIT);
203
204 static void     gst_dvbvideosink_set_property (GObject *object, guint prop_id,
205                                                                                                                                                                                                         const GValue *value,
206                                                                                                                                                                                                         GParamSpec *pspec);
207 static void     gst_dvbvideosink_get_property (GObject *object, guint prop_id,
208                                                                                                                                                                                                         GValue *value,
209                                                                                                                                                                                                         GParamSpec *pspec);
210
211 static gboolean gst_dvbvideosink_start (GstBaseSink * sink);
212 static gboolean gst_dvbvideosink_stop (GstBaseSink * sink);
213 static gboolean gst_dvbvideosink_event (GstBaseSink * sink, GstEvent * event);
214 static GstFlowReturn gst_dvbvideosink_render (GstBaseSink * sink,
215         GstBuffer * buffer);
216 static gboolean gst_dvbvideosink_query (GstPad * pad, GstQuery * query);
217 static gboolean gst_dvbvideosink_set_caps (GstPad * pad, GstCaps * vscaps);
218 static gboolean gst_dvbvideosink_unlock (GstBaseSink * basesink);
219
220 static void
221 gst_dvbvideosink_base_init (gpointer klass)
222 {
223         static GstElementDetails element_details = {
224                 "A DVB video sink",
225                 "Generic/DVBVideoSink",
226                 "Output video PES / ES into a DVB video device for hardware playback",
227                 "Felix Domke <tmbinc@elitedvb.net>"
228         };
229         GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
230
231         gst_element_class_add_pad_template (element_class,
232                 gst_static_pad_template_get (&sink_factory));
233         gst_element_class_set_details (element_class, &element_details);
234 }
235
236 /* initialize the plugin's class */
237 static void
238 gst_dvbvideosink_class_init (GstDVBVideoSinkClass *klass)
239 {
240         GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
241         GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
242         
243         gobject_class->set_property = gst_dvbvideosink_set_property;
244         gobject_class->get_property = gst_dvbvideosink_get_property;
245         
246         gobject_class = G_OBJECT_CLASS (klass);
247         g_object_class_install_property (gobject_class, ARG_SILENT,
248                 g_param_spec_boolean ("silent", "Silent", "Produce verbose output ?",
249                                                                                                         FALSE, G_PARAM_READWRITE));
250
251         gstbasesink_class->get_times = NULL;
252         gstbasesink_class->start = GST_DEBUG_FUNCPTR (gst_dvbvideosink_start);
253         gstbasesink_class->stop = GST_DEBUG_FUNCPTR (gst_dvbvideosink_stop);
254         gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_dvbvideosink_render);
255         gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_dvbvideosink_event);
256         gstbasesink_class->unlock = GST_DEBUG_FUNCPTR (gst_dvbvideosink_unlock);
257 }
258
259 /* initialize the new element
260  * instantiate pads and add them to element
261  * set functions
262  * initialize structure
263  */
264 static void
265 gst_dvbvideosink_init (GstDVBVideoSink *klass,
266                 GstDVBVideoSinkClass * gclass)
267 {
268         GstPad *pad = GST_BASE_SINK_PAD (klass);
269         
270         gst_pad_set_setcaps_function (pad, GST_DEBUG_FUNCPTR (gst_dvbvideosink_set_caps));
271         gst_pad_set_query_function (pad, GST_DEBUG_FUNCPTR (gst_dvbvideosink_query));
272         
273         klass->silent = FALSE;
274         klass->divx311_header = NULL;
275         klass->must_send_header = FALSE;
276         klass->codec_data = NULL;
277 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
278         klass->must_pack_bitstream = 0;
279         klass->num_non_keyframes = 0;
280         klass->prev_frame = NULL;
281 #endif
282         GST_BASE_SINK (klass)->sync = FALSE;
283 }
284
285 static void
286 gst_dvbvideosink_set_property (GObject *object, guint prop_id,
287                                                                                                                                         const GValue *value, GParamSpec *pspec)
288 {
289         GstDVBVideoSink *filter;
290
291         g_return_if_fail (GST_IS_DVBVIDEOSINK (object));
292         filter = GST_DVBVIDEOSINK (object);
293
294         switch (prop_id)
295         {
296         case ARG_SILENT:
297                 filter->silent = g_value_get_boolean (value);
298                 break;
299         default:
300                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
301                 break;
302         }
303 }
304
305 static void
306 gst_dvbvideosink_get_property (GObject *object, guint prop_id,
307                                                                                                                                         GValue *value, GParamSpec *pspec)
308 {
309         GstDVBVideoSink *filter;
310
311         g_return_if_fail (GST_IS_DVBVIDEOSINK (object));
312         filter = GST_DVBVIDEOSINK (object);
313
314         switch (prop_id) {
315         case ARG_SILENT:
316                 g_value_set_boolean (value, filter->silent);
317                 break;
318         default:
319                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
320                 break;
321         }
322 }
323
324 static gboolean
325 gst_dvbvideosink_query (GstPad * pad, GstQuery * query)
326 {
327         GstDVBVideoSink *self = GST_DVBVIDEOSINK (GST_PAD_PARENT (pad));
328 //      GstFormat format;
329         
330         printf("QUERY: type: %d\n", GST_QUERY_TYPE(query));
331         switch (GST_QUERY_TYPE (query)) {
332         case GST_QUERY_POSITION:
333         {
334                 gint64 cur = 0;
335                 GstFormat format;
336
337                 gst_query_parse_position (query, &format, NULL);
338                 
339                 if (format != GST_FORMAT_TIME)
340                         return gst_pad_query_default (pad, query);
341
342                 ioctl(self->fd, VIDEO_GET_PTS, &cur);
343                 printf("PTS: %08llx", cur);
344                 
345                 cur *= 11111;
346                 
347                 gst_query_set_position (query, format, cur);
348                 
349                 GST_DEBUG_OBJECT (self, "position format %d", format);
350                 return TRUE;
351         }
352         default:
353                 return gst_pad_query_default (pad, query);
354         }
355 }
356
357 static gboolean gst_dvbvideosink_unlock (GstBaseSink * basesink)
358 {
359         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
360
361         SEND_COMMAND (self, CONTROL_STOP);
362
363         return TRUE;
364 }
365
366 static gboolean
367 gst_dvbvideosink_event (GstBaseSink * sink, GstEvent * event)
368 {
369         GstDVBVideoSink *self = GST_DVBVIDEOSINK (sink);
370         GST_DEBUG_OBJECT (self, "EVENT %s", gst_event_type_get_name(GST_EVENT_TYPE (event)));
371
372         switch (GST_EVENT_TYPE (event)) {
373         case GST_EVENT_FLUSH_START:
374                 ioctl(self->fd, VIDEO_CLEAR_BUFFER);
375                 self->must_send_header = TRUE;
376                 break;
377         case GST_EVENT_FLUSH_STOP:
378                 ioctl(self->fd, VIDEO_CLEAR_BUFFER);
379                 self->must_send_header = TRUE;
380                 while (1)
381                 {
382                         gchar command;
383                         int res;
384
385                         READ_COMMAND (self, command, res);
386                         if (res < 0)
387                                 break;
388                 }
389         default:
390                 break;
391         }
392         return TRUE;
393 }
394
395 static GstFlowReturn
396 gst_dvbvideosink_render (GstBaseSink * sink, GstBuffer * buffer)
397 {
398         GstDVBVideoSink *self = GST_DVBVIDEOSINK (sink);
399         unsigned char *data = GST_BUFFER_DATA(buffer);
400         unsigned int data_len = GST_BUFFER_SIZE (buffer);
401         guint8 pes_header[2048];
402         unsigned int pes_header_len=0;
403         unsigned int payload_len=0;
404         fd_set readfds;
405         fd_set writefds;
406         gint retval;
407 //      int i=0;
408
409 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
410         gboolean commit_prev_frame_data = FALSE,
411                         cache_prev_frame = FALSE;
412 #endif
413
414 //      for (;i < (data_len > 0xF ? 0xF : data_len); ++i)
415 //              printf("%02x ", data[i]);
416 //      printf("%d bytes\n", data_len);
417
418 //      printf("timestamp: %08llx\n", (long long)GST_BUFFER_TIMESTAMP(buffer));
419
420         FD_ZERO (&readfds);
421         FD_SET (READ_SOCKET (self), &readfds);
422
423         FD_ZERO (&writefds);
424         FD_SET (self->fd, &writefds);
425         
426         do {
427                 GST_DEBUG_OBJECT (self, "going into select, have %d bytes to write",
428                                 data_len);
429                 retval = select (FD_SETSIZE, &readfds, &writefds, NULL, NULL);
430         } while ((retval == -1 && errno == EINTR));
431
432         if (retval == -1)
433                 goto select_error;
434
435         if (FD_ISSET (READ_SOCKET (self), &readfds)) {
436                 /* read all stop commands */
437                 while (TRUE) {
438                         gchar command;
439                         int res;
440
441                         READ_COMMAND (self, command, res);
442                         if (res < 0) {
443                                 GST_LOG_OBJECT (self, "no more commands");
444                                 /* no more commands */
445                                 break;
446                         }
447                 }
448                 goto stopped;
449         }
450
451         if (self->fd < 0)
452                 return GST_FLOW_OK;
453
454 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
455         if (self->must_pack_bitstream == 1) {
456                 cache_prev_frame = TRUE;
457                 unsigned int pos = 0;
458                 while(pos < data_len) {
459                         if (data[pos++])
460                                 continue;
461                         if (data[pos++])
462                                 continue;
463                         while (!data[pos])
464                                 ++pos;
465                         if (data[pos++] != 1)
466                                 continue;
467                         if ((data[pos++] & 0xF0) == 0x20) { // we need time_inc_res
468                                 gboolean low_delay=FALSE;
469                                 unsigned int ver_id = 1, shape=0, time_inc_res=0, tmp=0;
470                                 struct bitstream bit;
471                                 bitstream_init(&bit, data+pos, 0);
472                                 bitstream_get(&bit, 9);
473                                 if (bitstream_get(&bit, 1)) {
474                                         ver_id = bitstream_get(&bit, 4); // ver_id
475                                         bitstream_get(&bit, 3);
476                                 }
477                                 if ((tmp=bitstream_get(&bit, 4)) == 15) { // Custom Aspect Ration
478                                         bitstream_get(&bit, 8); // skip AR width
479                                         bitstream_get(&bit, 8); // skip AR height
480                                 }
481                                 if (bitstream_get(&bit, 1)) {
482                                         bitstream_get(&bit, 2);
483                                         low_delay = bitstream_get(&bit, 1) ? TRUE : FALSE;
484                                         if (bitstream_get(&bit, 1)) {
485                                                 bitstream_get(&bit, 32);
486                                                 bitstream_get(&bit, 32);
487                                                 bitstream_get(&bit, 15);
488                                         }
489                                 }
490                                 shape = bitstream_get(&bit, 2);
491                                 if (ver_id != 1 && shape == 3 /* Grayscale */)
492                                         bitstream_get(&bit, 4);
493                                 bitstream_get(&bit, 1);
494                                 time_inc_res = bitstream_get(&bit, 16);
495                                 self->time_inc_bits = 0;
496                                 while (time_inc_res) { // count bits
497                                         ++self->time_inc_bits;
498                                         time_inc_res >>= 1;
499                                 }
500 //                              printf("%d time_inc_bits\n", self->time_inc_bits);
501                         }
502                 }
503         }
504
505         if (self->must_pack_bitstream == 1) {
506                 unsigned int pos = 0;
507                 while(pos < data_len) {
508                         if (data[pos++])
509                                 continue;
510                         if (data[pos++])
511                                 continue;
512                         while (!data[pos])
513                                 ++pos;
514                         if (data[pos++] != 1)
515                                 continue;
516                         if (data[pos++] != 0xB2)
517                                 continue;
518                         if (data_len - pos < 13)
519                                 break;
520                         if (!strcmp((char*)data+pos, "DivX503b1393p"))
521                                 self->must_pack_bitstream = 0;
522 //                      if (self->must_pack_bitstream)
523 //                              printf("pack needed\n");
524 //                      else
525 //                              printf("no pack needed\n");
526                 }
527         }
528 #endif
529
530         pes_header[0] = 0;
531         pes_header[1] = 0;
532         pes_header[2] = 1;
533         pes_header[3] = 0xE0;
534
535                 /* do we have a timestamp? */
536         if (GST_BUFFER_TIMESTAMP(buffer) != GST_CLOCK_TIME_NONE) {
537                 unsigned long long pts = GST_BUFFER_TIMESTAMP(buffer) * 9LL / 100000 /* convert ns to 90kHz */;
538
539                 pes_header[6] = 0x80;
540                 pes_header[7] = 0x80;
541                 
542                 pes_header[8] = 5;
543                 
544                 pes_header[9] = 0x31 | ((pts >> 29) & 0xE);
545                 pes_header[10] = pts >> 22;
546                 pes_header[11] = 0x01 | ((pts >> 14) & 0xFE);
547                 pes_header[12] = pts >> 7;
548                 pes_header[13] = 0x01 | ((pts << 1) & 0xFE);
549
550                 pes_header_len = 14;
551
552                 if (self->divx311_header) {  // DIVX311 stuff
553                         if (self->must_send_header) {
554                                 write(self->fd, self->divx311_header, 63);
555                                 self->must_send_header = FALSE;
556                         }
557                         pes_header[14] = 0;
558                         pes_header[15] = 0;
559                         pes_header[16] = 1;
560                         pes_header[17] = 0xb6;
561                         pes_header_len += 4;
562                 }
563                 else if (self->codec_data) {  // MKV stuff
564                         unsigned int pos = 0;
565                         while(TRUE) {
566                                 unsigned int pack_len = (data[pos] << 24) | (data[pos+1] << 16) | (data[pos+2] << 8) | data[pos+3];
567 //                              printf("patch %02x %02x %02x %02x\n",
568 //                                      data[pos],
569 //                                      data[pos + 1],
570 //                                      data[pos + 2],
571 //                                      data[pos + 3]);
572                                 memcpy(data+pos, "\x00\x00\x00\x01", 4);
573 //                              printf("pos %d, (%d) >= %d\n", pos, pos+pack_len, data_len);
574                                 pos += 4;
575                                 if ((pos + pack_len) >= data_len)
576                                         break;
577                                 pos += pack_len;
578                         }
579                         if (self->must_send_header) {
580                                 unsigned char *codec_data = GST_BUFFER_DATA (self->codec_data);
581                                 unsigned int codec_data_len = GST_BUFFER_SIZE (self->codec_data);
582                                 unsigned int pos=0;
583 //                              printf("1\n");
584                                 if (codec_data_len > 7) {
585                                         unsigned short len = (codec_data[6] << 8) | codec_data[7];
586 //                                      printf("2 %d bytes\n", len);
587                                         if (codec_data_len >= (len + 8)) {
588 //                                              printf("3\n");
589                                                 memcpy(pes_header+pes_header_len, "\x00\x00\x00\x01", 4);
590                                                 pes_header_len += 4;
591                                                 memcpy(pes_header+pes_header_len, codec_data+8, len);
592                                                 if (!memcmp(pes_header+pes_header_len, "\x67\x64\x00", 3)) {
593                                                         pes_header[pes_header_len+3] = 0x29; // hardcode h264 level 4.1
594                                                         printf("h264 level patched!\n");
595                                                 }
596                                                 pes_header_len += len;
597                                                 pos = 8 + len;
598                                                 if (codec_data_len > (pos + 2)) {
599                                                         len = (codec_data[pos+1] << 8) | codec_data[pos+2];
600 //                                                      printf("4 %d bytes\n", len);
601                                                         pos += 3;
602                                                         if (codec_data_len >= (pos+len)) {
603                                                                 printf("codec data ok!\n");
604                                                                 memcpy(pes_header+pes_header_len, "\x00\x00\x00\x01", 4);
605                                                                 pes_header_len += 4;
606                                                                 memcpy(pes_header+pes_header_len, codec_data+pos, len);
607                                                                 pes_header_len += len;
608                                                         }
609                                                         else
610                                                                 printf("codec_data to short(4)\n");
611                                                 }
612                                                 else
613                                                         printf("codec_data to short(3)!\n");
614                                         }
615                                         else
616                                                 printf("codec_data to short(2)!\n");
617                                 }
618                                 else
619                                         printf("codec_data to short(1)!\n");
620                                 self->must_send_header = FALSE;
621                         }
622                 }
623         }
624         else {
625 //              printf("no timestamp!\n");
626                 pes_header[6] = 0x80;
627                 pes_header[7] = 0x00;
628                 pes_header[8] = 0;
629                 pes_header_len = 9;
630         }
631
632 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
633         if (self->must_pack_bitstream == 1) {
634                 unsigned int pos = 0;
635                 gboolean i_frame = FALSE;
636 //              gboolean s_frame = FALSE;
637                 while(pos < data_len) {
638                         if (data[pos++])
639                                 continue;
640                         if (data[pos++])
641                                 continue;
642                         while (!data[pos])
643                                 ++pos;
644                         if (data[pos++] != 1)
645                                 continue;
646                         if (data[pos++] != 0xB6)
647                                 continue;
648                         switch ((data[pos] & 0xC0) >> 6) {
649                                 case 0: // I-Frame
650 //                                      printf("I ");
651                                         cache_prev_frame = FALSE;
652                                         i_frame = TRUE;
653                                 case 1: // P-Frame
654 //                                      if (!i_frame)
655 //                                              printf("P ");
656                                         if (self->prev_frame != buffer) {
657                                                 struct bitstream bit;
658                                                 gboolean store_frame=FALSE;
659                                                 if (self->prev_frame) {
660                                                         if (!self->num_non_keyframes) {
661 //                                                              printf("no non keyframes...immediate commit prev frame\n");
662                                                                 GstFlowReturn ret = gst_dvbvideosink_render(sink, self->prev_frame);
663                                                                 gst_buffer_unref(self->prev_frame);
664                                                                 self->prev_frame = NULL;
665                                                                 if (ret != GST_FLOW_OK)
666                                                                         return ret;
667                                                                 store_frame = TRUE;
668                                                         }
669                                                         else {
670 //                                                              int i=-4;
671                                                                 pes_header[pes_header_len++] = 0;
672                                                                 pes_header[pes_header_len++] = 0;
673                                                                 pes_header[pes_header_len++] = 1;
674                                                                 pes_header[pes_header_len++] = 0xB6;
675                                                                 bitstream_init(&bit, pes_header+pes_header_len, 1);
676                                                                 bitstream_put(&bit, 1, 2);
677                                                                 bitstream_put(&bit, 0, 1);
678                                                                 bitstream_put(&bit, 1, 1);
679                                                                 bitstream_put(&bit, self->time_inc, self->time_inc_bits);
680                                                                 bitstream_put(&bit, 1, 1);
681                                                                 bitstream_put(&bit, 0, 1);
682                                                                 bitstream_put(&bit, 0x7F >> bit.avail, 8 - bit.avail);
683 //                                                              printf(" insert pack frame %d non keyframes, time_inc %d, time_inc_bits %d -",
684 //                                                                      self->num_non_keyframes, self->time_inc, self->time_inc_bits);
685 //                                                              for (; i < (bit.data - (pes_header+pes_header_len)); ++i)
686 //                                                                      printf(" %02x", pes_header[pes_header_len+i]);
687 //                                                              printf("\nset data_len to 0!\n");
688                                                                 data_len = 0;
689                                                                 pes_header_len += bit.data - (pes_header+pes_header_len);
690                                                                 cache_prev_frame = TRUE;
691                                                         }
692                                                 }
693                                                 else if (!i_frame)
694                                                         store_frame = TRUE;
695
696                                                 self->num_non_keyframes=0;
697
698                                                 // extract time_inc
699                                                 bitstream_init(&bit, data+pos, 0);
700                                                 bitstream_get(&bit, 2); // skip coding_type
701                                                 while(bitstream_get(&bit, 1));
702                                                 bitstream_get(&bit, 1);
703                                                 self->time_inc = bitstream_get(&bit, self->time_inc_bits);
704 //                                              printf("\ntime_inc is %d\n", self->time_inc);
705
706                                                 if (store_frame) {
707 //                                                      printf("store frame\n");
708                                                         self->prev_frame = buffer;
709                                                         gst_buffer_ref (buffer);
710                                                         return GST_FLOW_OK;
711                                                 }
712                                         }
713                                         else {
714                                                 cache_prev_frame = FALSE;
715 //                                              printf(" I/P Frame without non key frame(s)!!\n");
716                                         }
717                                         break;
718                                 case 3: // S-Frame
719 //                                      printf("S ");
720 //                                      s_frame = TRUE;
721                                 case 2: // B-Frame
722 //                                      if (!s_frame)
723 //                                              printf("B ");
724                                         if (++self->num_non_keyframes == 1 && self->prev_frame) {
725 //                                              printf("send grouped with prev P!\n");
726                                                 commit_prev_frame_data = TRUE;
727                                         }
728                                         break;
729                                 case 4: // N-Frame
730                                 default:
731                                         printf("unhandled divx5/xvid frame type %d\n", (data[pos] & 0xC0) >> 6);
732                                         break;
733                         }
734                 }
735 //              printf("\n");
736         }
737 #endif
738
739         payload_len = data_len + pes_header_len - 6;
740
741 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
742         if (self->prev_frame && self->prev_frame != buffer) {
743                 unsigned long long pts = GST_BUFFER_TIMESTAMP(self->prev_frame) * 9LL / 100000 /* convert ns to 90kHz */;
744 //              printf("use prev timestamp: %08llx\n", (long long)GST_BUFFER_TIMESTAMP(self->prev_frame));
745
746                 pes_header[9] = 0x31 | ((pts >> 29) & 0xE);
747                 pes_header[10] = pts >> 22;
748                 pes_header[11] = 0x01 | ((pts >> 14) & 0xFE);
749                 pes_header[12] = pts >> 7;
750                 pes_header[13] = 0x01 | ((pts << 1) & 0xFE);
751         }
752
753         if (commit_prev_frame_data)
754                 payload_len += GST_BUFFER_SIZE (self->prev_frame);
755 #endif
756
757         if (payload_len <= 0xFFFF) {
758                 pes_header[4] = payload_len >> 8;
759                 pes_header[5] = payload_len & 0xFF;
760         }
761         else {
762                 pes_header[4] = 0;
763                 pes_header[5] = 0;
764         }
765
766         write(self->fd, pes_header, pes_header_len);
767
768 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
769         if (commit_prev_frame_data) {
770 //              printf("commit prev frame data\n");
771                 write(self->fd, GST_BUFFER_DATA (self->prev_frame), GST_BUFFER_SIZE (self->prev_frame));
772         }
773
774         if (self->prev_frame && self->prev_frame != buffer) {
775 //              printf("unref prev_frame buffer\n");
776                 gst_buffer_unref(self->prev_frame);
777                 self->prev_frame = NULL;
778         }
779
780         if (cache_prev_frame) {
781 //              printf("cache prev frame\n");
782                 gst_buffer_ref(buffer);
783                 self->prev_frame = buffer;
784         }
785 #endif
786
787         write(self->fd, data, data_len);
788
789         return GST_FLOW_OK;
790 select_error:
791         {
792                 GST_ELEMENT_ERROR (self, RESOURCE, READ, (NULL),
793                                 ("select on file descriptor: %s.", g_strerror (errno)));
794                 GST_DEBUG_OBJECT (self, "Error during select");
795                 return GST_FLOW_ERROR;
796         }
797 stopped:
798         {
799                 GST_DEBUG_OBJECT (self, "Select stopped");
800                 ioctl(self->fd, VIDEO_CLEAR_BUFFER);
801                 return GST_FLOW_WRONG_STATE;
802         }
803 }
804
805 static gboolean 
806 gst_dvbvideosink_set_caps (GstPad * pad, GstCaps * vscaps)
807 {
808         GstStructure *structure = gst_caps_get_structure (vscaps, 0);
809         const gchar *mimetype = gst_structure_get_name (structure);
810         GstDVBVideoSink *self = GST_DVBVIDEOSINK (GST_PAD_PARENT (pad));
811         int streamtype = -1;
812
813         if (!strcmp (mimetype, "video/mpeg")) {
814                 gint mpegversion;
815                 gst_structure_get_int (structure, "mpegversion", &mpegversion);
816                 switch (mpegversion) {
817                         case 1:
818                                 streamtype = 6;
819                                 printf("MIMETYPE video/mpeg1 -> VIDEO_SET_STREAMTYPE, 6\n");
820                         break;
821                         case 2:
822                                 streamtype = 0;
823                                 printf("MIMETYPE video/mpeg2 -> VIDEO_SET_STREAMTYPE, 0\n");
824                         break;
825                         case 4:
826                                 streamtype = 4;
827                                 printf("MIMETYPE video/mpeg4 -> VIDEO_SET_STREAMTYPE, 4\n");
828                         break;
829                         default:
830                                 GST_ELEMENT_ERROR (self, STREAM, FORMAT, (NULL), ("unhandled mpeg version %i", mpegversion));
831                         break;
832                 }
833         } else if (!strcmp (mimetype, "video/x-h264")) {
834                 const GValue *codec_data = gst_structure_get_value (structure, "codec_data");
835                 streamtype = 1;
836                 if (codec_data) {
837                         printf("H264 have codec data.. force mkv!\n");
838                         self->codec_data = gst_value_get_buffer (codec_data);
839                         gst_buffer_ref (self->codec_data);
840                 }
841                 self->must_send_header = TRUE;
842                 printf("MIMETYPE video/x-h264 VIDEO_SET_STREAMTYPE, 1\n");
843         } else if (!strcmp (mimetype, "video/x-h263")) {
844                 streamtype = 2;
845                 printf("MIMETYPE video/x-h263 VIDEO_SET_STREAMTYPE, 2\n");
846         } else if (!strcmp (mimetype, "video/x-xvid")) {
847                 streamtype = 10;
848 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
849                 self->must_pack_bitstream = 1;
850 #endif
851                 printf("MIMETYPE video/x-xvid -> VIDEO_SET_STREAMTYPE, 10\n");
852         } else if (!strcmp (mimetype, "video/x-divx")) {
853                 gint divxversion;
854                 gst_structure_get_int (structure, "divxversion", &divxversion);
855                 switch (divxversion) {
856                         case 3:
857                         {
858                                 #define B_GET_BITS(w,e,b)  (((w)>>(b))&(((unsigned)(-1))>>((sizeof(unsigned))*8-(e+1-b))))
859                                 #define B_SET_BITS(name,v,e,b)  (((unsigned)(v))<<(b))
860                                 static const guint8 brcm_divx311_sequence_header[] = {
861                                         0x00, 0x00, 0x01, 0xE0, 0x00, 0x34, 0x80, 0x80, // PES HEADER
862                                         0x05, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 
863                                         0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x20, /* 0 .. 7 */
864                                         0x08, 0xC8, 0x0D, 0x40, 0x00, 0x53, 0x88, 0x40, /* 8 .. 15 */
865                                         0x0C, 0x40, 0x01, 0x90, 0x00, 0x97, 0x53, 0x0A, /* 16 .. 24 */
866                                         0x00, 0x00, 0x00, 0x00,
867                                         0x30, 0x7F, 0x00, 0x00, 0x01, 0xB2, 0x44, 0x69, /* 0 .. 7 */
868                                         0x76, 0x58, 0x33, 0x31, 0x31, 0x41, 0x4E, 0x44  /* 8 .. 15 */
869                                 };
870                                 guint8 *data = malloc(63);
871                                 gint height, width;
872                                 gst_structure_get_int (structure, "height", &height);
873                                 gst_structure_get_int (structure, "width", &width);
874                                 memcpy(data, brcm_divx311_sequence_header, 63);
875                                 self->divx311_header = data;
876                                 data += 38;
877                                 data[0] = B_GET_BITS(width,11,4);
878                                 data[1] = B_SET_BITS("width [3..0]", B_GET_BITS(width,3,0), 7, 4) |
879                                         B_SET_BITS("'10'", 0x02, 3, 2) |
880                                         B_SET_BITS("height [11..10]", B_GET_BITS(height,11,10), 1, 0);
881                                 data[2] = B_GET_BITS(height,9,2);
882                                 data[3]= B_SET_BITS("height [1.0]", B_GET_BITS(height,1,0), 7, 6) |
883                                         B_SET_BITS("'100000'", 0x20, 5, 0);
884                                 streamtype = 13;
885                                 self->must_send_header = TRUE;
886                                 printf("MIMETYPE video/x-divx vers. 3 -> VIDEO_SET_STREAMTYPE, 13\n");
887                         }
888                         break;
889                         case 4:
890                                 streamtype = 14;
891                                 printf("MIMETYPE video/x-divx vers. 4 -> VIDEO_SET_STREAMTYPE, 14\n");
892                         break;
893                         case 5:
894                                 streamtype = 15;
895 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
896                                 self->must_pack_bitstream = 1;
897 #endif
898                                 printf("MIMETYPE video/x-divx vers. 5 -> VIDEO_SET_STREAMTYPE, 15\n");
899                         break;
900                         default:
901                                 GST_ELEMENT_ERROR (self, STREAM, FORMAT, (NULL), ("unhandled divx version %i", divxversion));
902                         break;
903                 }
904         }
905         if (streamtype != -1) {
906                 if (ioctl(self->fd, VIDEO_SET_STREAMTYPE, streamtype) < 0 )
907                         if ( streamtype != 0 && streamtype != 6 )
908                                 GST_ELEMENT_ERROR (self, STREAM, DECODE, (NULL), ("hardware decoder can't handle streamtype %i", streamtype));
909         } else
910                 GST_ELEMENT_ERROR (self, STREAM, TYPE_NOT_FOUND, (NULL), ("unimplemented stream type %s", mimetype));
911
912         return TRUE;
913 }
914
915 static gboolean
916 gst_dvbvideosink_start (GstBaseSink * basesink)
917 {
918         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
919         self->fd = open("/dev/dvb/adapter0/video0", O_RDWR);
920 //      self->fd = open("/dump.pes", O_RDWR|O_CREAT|O_TRUNC, 0555);
921
922         gint control_sock[2];
923
924         if (socketpair (PF_UNIX, SOCK_STREAM, 0, control_sock) < 0)
925                 goto socket_pair;
926
927         READ_SOCKET (self) = control_sock[0];
928         WRITE_SOCKET (self) = control_sock[1];
929
930         fcntl (READ_SOCKET (self), F_SETFL, O_NONBLOCK);
931         fcntl (WRITE_SOCKET (self), F_SETFL, O_NONBLOCK);
932
933         if (self->fd >= 0)
934         {
935                 ioctl(self->fd, VIDEO_SELECT_SOURCE, VIDEO_SOURCE_MEMORY);
936                 ioctl(self->fd, VIDEO_PLAY);
937         }
938
939         return TRUE;
940         /* ERRORS */
941 socket_pair:
942         {
943                 GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ_WRITE, (NULL),
944                                 GST_ERROR_SYSTEM);
945                 return FALSE;
946         }
947 }
948
949 static gboolean
950 gst_dvbvideosink_stop (GstBaseSink * basesink)
951 {
952         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
953         if (self->fd >= 0)
954         {
955                 ioctl(self->fd, VIDEO_STOP);
956                 ioctl(self->fd, VIDEO_SELECT_SOURCE, VIDEO_SOURCE_DEMUX);
957                 close(self->fd);
958         }
959
960         close (READ_SOCKET (self));
961         close (WRITE_SOCKET (self));
962
963         if (self->divx311_header)
964                 free(self->divx311_header);
965
966         if (self->codec_data)
967                 gst_buffer_unref(self->codec_data);
968
969 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
970         if (self->prev_frame)
971                 gst_buffer_unref(self->prev_frame);
972 #endif
973
974         return TRUE;
975 }
976
977 /* entry point to initialize the plug-in
978  * initialize the plug-in itself
979  * register the element factories and pad templates
980  * register the features
981  *
982  * exchange the string 'plugin' with your elemnt name
983  */
984 static gboolean
985 plugin_init (GstPlugin *plugin)
986 {
987         return gst_element_register (plugin, "dvbvideosink",
988                                                  GST_RANK_NONE,
989                                                  GST_TYPE_DVBVIDEOSINK);
990 }
991
992 /* this is the structure that gstreamer looks for to register plugins
993  *
994  * exchange the strings 'plugin' and 'Template plugin' with you plugin name and
995  * description
996  */
997 GST_PLUGIN_DEFINE (
998         GST_VERSION_MAJOR,
999         GST_VERSION_MINOR,
1000         "dvb_video_out",
1001         "DVB Video Output",
1002         plugin_init,
1003         VERSION,
1004         "LGPL",
1005         "GStreamer",
1006         "http://gstreamer.net/"
1007 )