change element priority to PRIMARY (prefer our native sinks for decodebin autoplugging)
[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         klass->codec_data_type = CDT_H264;
278 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
279         klass->must_pack_bitstream = 0;
280         klass->num_non_keyframes = 0;
281         klass->prev_frame = NULL;
282 #endif
283         GST_BASE_SINK (klass)->sync = FALSE;
284 }
285
286 static void
287 gst_dvbvideosink_set_property (GObject *object, guint prop_id,
288                                                                                                                                         const GValue *value, GParamSpec *pspec)
289 {
290         GstDVBVideoSink *filter;
291
292         g_return_if_fail (GST_IS_DVBVIDEOSINK (object));
293         filter = GST_DVBVIDEOSINK (object);
294
295         switch (prop_id)
296         {
297         case ARG_SILENT:
298                 filter->silent = g_value_get_boolean (value);
299                 break;
300         default:
301                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
302                 break;
303         }
304 }
305
306 static void
307 gst_dvbvideosink_get_property (GObject *object, guint prop_id,
308                                                                                                                                         GValue *value, GParamSpec *pspec)
309 {
310         GstDVBVideoSink *filter;
311
312         g_return_if_fail (GST_IS_DVBVIDEOSINK (object));
313         filter = GST_DVBVIDEOSINK (object);
314
315         switch (prop_id) {
316         case ARG_SILENT:
317                 g_value_set_boolean (value, filter->silent);
318                 break;
319         default:
320                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
321                 break;
322         }
323 }
324
325 static gboolean
326 gst_dvbvideosink_query (GstPad * pad, GstQuery * query)
327 {
328         GstDVBVideoSink *self = GST_DVBVIDEOSINK (GST_PAD_PARENT (pad));
329 //      GstFormat format;
330         
331         printf("QUERY: type: %d\n", GST_QUERY_TYPE(query));
332         switch (GST_QUERY_TYPE (query)) {
333         case GST_QUERY_POSITION:
334         {
335                 gint64 cur = 0;
336                 GstFormat format;
337
338                 gst_query_parse_position (query, &format, NULL);
339                 
340                 if (format != GST_FORMAT_TIME)
341                         return gst_pad_query_default (pad, query);
342
343                 ioctl(self->fd, VIDEO_GET_PTS, &cur);
344                 printf("PTS: %08llx", cur);
345                 
346                 cur *= 11111;
347                 
348                 gst_query_set_position (query, format, cur);
349                 
350                 GST_DEBUG_OBJECT (self, "position format %d", format);
351                 return TRUE;
352         }
353         default:
354                 return gst_pad_query_default (pad, query);
355         }
356 }
357
358 static gboolean gst_dvbvideosink_unlock (GstBaseSink * basesink)
359 {
360         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
361
362         SEND_COMMAND (self, CONTROL_STOP);
363
364         return TRUE;
365 }
366
367 static gboolean
368 gst_dvbvideosink_event (GstBaseSink * sink, GstEvent * event)
369 {
370         GstDVBVideoSink *self = GST_DVBVIDEOSINK (sink);
371         GST_DEBUG_OBJECT (self, "EVENT %s", gst_event_type_get_name(GST_EVENT_TYPE (event)));
372
373         switch (GST_EVENT_TYPE (event)) {
374         case GST_EVENT_FLUSH_START:
375                 ioctl(self->fd, VIDEO_CLEAR_BUFFER);
376                 self->must_send_header = TRUE;
377                 break;
378         case GST_EVENT_FLUSH_STOP:
379                 ioctl(self->fd, VIDEO_CLEAR_BUFFER);
380                 self->must_send_header = TRUE;
381                 while (1)
382                 {
383                         gchar command;
384                         int res;
385
386                         READ_COMMAND (self, command, res);
387                         if (res < 0)
388                                 break;
389                 }
390         default:
391                 break;
392         }
393         return TRUE;
394 }
395
396 static GstFlowReturn
397 gst_dvbvideosink_render (GstBaseSink * sink, GstBuffer * buffer)
398 {
399         GstDVBVideoSink *self = GST_DVBVIDEOSINK (sink);
400         unsigned char *data = GST_BUFFER_DATA(buffer);
401         unsigned int data_len = GST_BUFFER_SIZE (buffer);
402         guint8 pes_header[2048];
403         unsigned int pes_header_len=0;
404         unsigned int payload_len=0;
405         fd_set readfds;
406         fd_set writefds;
407         fd_set priofds;
408         gint retval;
409 //      int i=0;
410
411 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
412         gboolean commit_prev_frame_data = FALSE,
413                         cache_prev_frame = FALSE;
414 #endif
415
416 //      for (;i < (data_len > 0xF ? 0xF : data_len); ++i)
417 //              printf("%02x ", data[i]);
418 //      printf("%d bytes\n", data_len);
419
420 //      printf("timestamp: %08llx\n", (long long)GST_BUFFER_TIMESTAMP(buffer));
421
422         FD_ZERO (&readfds);
423         FD_SET (READ_SOCKET (self), &readfds);
424
425         FD_ZERO (&writefds);
426         FD_SET (self->fd, &writefds);
427
428         FD_ZERO (&priofds);
429         FD_SET (self->fd, &priofds);
430
431         do {
432                 GST_DEBUG_OBJECT (self, "going into select, have %d bytes to write",
433                                 data_len);
434                 retval = select (FD_SETSIZE, &readfds, &writefds, &priofds, NULL);
435         } while ((retval == -1 && errno == EINTR));
436
437         if (retval == -1)
438                 goto select_error;
439
440         if (FD_ISSET (READ_SOCKET (self), &readfds)) {
441                 /* read all stop commands */
442                 while (TRUE) {
443                         gchar command;
444                         int res;
445
446                         READ_COMMAND (self, command, res);
447                         if (res < 0) {
448                                 GST_LOG_OBJECT (self, "no more commands");
449                                 /* no more commands */
450                                 break;
451                         }
452                 }
453                 goto stopped;
454         }
455
456         if (FD_ISSET (self->fd, &priofds))
457         {
458                 GstStructure *s;
459                 GstMessage *msg;
460
461                 struct video_event evt;
462                 if (ioctl(self->fd, VIDEO_GET_EVENT, &evt) < 0)
463                         g_warning ("failed to ioctl VIDEO_GET_EVENT!");
464                 else
465                 {
466                         if (evt.type == VIDEO_EVENT_SIZE_CHANGED)
467                         {
468                                 s = gst_structure_new ("eventSizeChanged", "aspect_ratio", G_TYPE_INT,
469                                 evt.u.size.aspect_ratio, "width", G_TYPE_INT, evt.u.size.w, "height", G_TYPE_INT, evt.u.size.h, NULL);
470                                 msg = gst_message_new_element (GST_OBJECT (sink), s);
471                                 gst_element_post_message (GST_ELEMENT (sink), msg);
472                         }
473                         else if (evt.type == VIDEO_EVENT_FRAME_RATE_CHANGED)
474                         {
475                                 s = gst_structure_new ("eventFrameRateChanged", "frame_rate", G_TYPE_INT,
476                                 evt.u.frame_rate, NULL);
477                                 msg = gst_message_new_element (GST_OBJECT (sink), s);
478                                 gst_element_post_message (GST_ELEMENT (sink), msg);
479                         }
480                         else if (evt.type == 16 /*VIDEO_EVENT_PROGRESSIVE_CHANGED*/)
481                         {
482                                 s = gst_structure_new ("eventProgressiveChanged", "progressive", G_TYPE_INT,
483                                 evt.u.frame_rate, NULL);
484                                 msg = gst_message_new_element (GST_OBJECT (sink), s);
485                                 gst_element_post_message (GST_ELEMENT (sink), msg);
486                         }
487                         else
488                                 g_warning ("unhandled DVBAPI Video Event %d", evt.type);
489                 }
490         }
491
492         if (self->fd < 0)
493                 return GST_FLOW_OK;
494
495 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
496         if (self->must_pack_bitstream == 1) {
497                 cache_prev_frame = TRUE;
498                 unsigned int pos = 0;
499                 while(pos < data_len) {
500                         if (data[pos++])
501                                 continue;
502                         if (data[pos++])
503                                 continue;
504                         while (!data[pos])
505                                 ++pos;
506                         if (data[pos++] != 1)
507                                 continue;
508                         if ((data[pos++] & 0xF0) == 0x20) { // we need time_inc_res
509                                 gboolean low_delay=FALSE;
510                                 unsigned int ver_id = 1, shape=0, time_inc_res=0, tmp=0;
511                                 struct bitstream bit;
512                                 bitstream_init(&bit, data+pos, 0);
513                                 bitstream_get(&bit, 9);
514                                 if (bitstream_get(&bit, 1)) {
515                                         ver_id = bitstream_get(&bit, 4); // ver_id
516                                         bitstream_get(&bit, 3);
517                                 }
518                                 if ((tmp=bitstream_get(&bit, 4)) == 15) { // Custom Aspect Ration
519                                         bitstream_get(&bit, 8); // skip AR width
520                                         bitstream_get(&bit, 8); // skip AR height
521                                 }
522                                 if (bitstream_get(&bit, 1)) {
523                                         bitstream_get(&bit, 2);
524                                         low_delay = bitstream_get(&bit, 1) ? TRUE : FALSE;
525                                         if (bitstream_get(&bit, 1)) {
526                                                 bitstream_get(&bit, 32);
527                                                 bitstream_get(&bit, 32);
528                                                 bitstream_get(&bit, 15);
529                                         }
530                                 }
531                                 shape = bitstream_get(&bit, 2);
532                                 if (ver_id != 1 && shape == 3 /* Grayscale */)
533                                         bitstream_get(&bit, 4);
534                                 bitstream_get(&bit, 1);
535                                 time_inc_res = bitstream_get(&bit, 16);
536                                 self->time_inc_bits = 0;
537                                 while (time_inc_res) { // count bits
538                                         ++self->time_inc_bits;
539                                         time_inc_res >>= 1;
540                                 }
541 //                              printf("%d time_inc_bits\n", self->time_inc_bits);
542                         }
543                 }
544         }
545
546         if (self->must_pack_bitstream == 1) {
547                 int tmp1, tmp2;
548                 unsigned char c1, c2;
549                 unsigned int pos = 0;
550                 while(pos < data_len) {
551                         if (data[pos++])
552                                 continue;
553                         if (data[pos++])
554                                 continue;
555                         while (!data[pos])
556                                 ++pos;
557                         if (data[pos++] != 1)
558                                 continue;
559                         if (data[pos++] != 0xB2)
560                                 continue;
561                         if (data_len - pos < 13)
562                                 break;
563                         if (sscanf((char*)data+pos, "DivX%d%c%d%cp", &tmp1, &c1, &tmp2, &c2) == 4 && (c1 == 'b' || c1 == 'B') && (c2 == 'p' || c2 == 'P')) {
564                                 printf("%s seen... already packed!\n", (char*)data+pos);
565                                 self->must_pack_bitstream = 0;
566                         }
567 //                      if (self->must_pack_bitstream)
568 //                              printf("pack needed\n");
569 //                      else
570 //                              printf("no pack needed\n");
571                 }
572         }
573 #endif
574
575         pes_header[0] = 0;
576         pes_header[1] = 0;
577         pes_header[2] = 1;
578         pes_header[3] = 0xE0;
579
580                 /* do we have a timestamp? */
581         if (GST_BUFFER_TIMESTAMP(buffer) != GST_CLOCK_TIME_NONE) {
582                 unsigned long long pts = GST_BUFFER_TIMESTAMP(buffer) * 9LL / 100000 /* convert ns to 90kHz */;
583
584                 pes_header[6] = 0x80;
585                 pes_header[7] = 0x80;
586                 
587                 pes_header[8] = 5;
588                 
589                 pes_header[9] =  0x21 | ((pts >> 29) & 0xE);
590                 pes_header[10] = pts >> 22;
591                 pes_header[11] = 0x01 | ((pts >> 14) & 0xFE);
592                 pes_header[12] = pts >> 7;
593                 pes_header[13] = 0x01 | ((pts << 1) & 0xFE);
594
595                 pes_header_len = 14;
596
597                 if (self->divx311_header) {  // DIVX311 stuff
598                         if (self->must_send_header) {
599                                 write(self->fd, self->divx311_header, 63);
600                                 self->must_send_header = FALSE;
601                         }
602                         pes_header[14] = 0;
603                         pes_header[15] = 0;
604                         pes_header[16] = 1;
605                         pes_header[17] = 0xb6;
606                         pes_header_len += 4;
607                 }
608                 else if (self->codec_data && self->codec_data_type == CDT_H264) {  // MKV stuff
609                         unsigned int pos = 0;
610                         while(TRUE) {
611                                 unsigned int pack_len = (data[pos] << 24) | (data[pos+1] << 16) | (data[pos+2] << 8) | data[pos+3];
612 //                              printf("patch %02x %02x %02x %02x\n",
613 //                                      data[pos],
614 //                                      data[pos + 1],
615 //                                      data[pos + 2],
616 //                                      data[pos + 3]);
617                                 memcpy(data+pos, "\x00\x00\x00\x01", 4);
618 //                              printf("pos %d, (%d) >= %d\n", pos, pos+pack_len, data_len);
619                                 pos += 4;
620                                 if ((pos + pack_len) >= data_len)
621                                         break;
622                                 pos += pack_len;
623                         }
624                         if (self->must_send_header) {
625                                 unsigned char *codec_data = GST_BUFFER_DATA (self->codec_data);
626                                 unsigned int codec_data_len = GST_BUFFER_SIZE (self->codec_data);
627                                 unsigned int pos=0;
628 //                              printf("1\n");
629                                 if (codec_data_len > 7) {
630                                         unsigned short len = (codec_data[6] << 8) | codec_data[7];
631 //                                      printf("2 %d bytes\n", len);
632                                         if (codec_data_len >= (len + 8)) {
633 //                                              printf("3\n");
634                                                 memcpy(pes_header+pes_header_len, "\x00\x00\x00\x01", 4);
635                                                 pes_header_len += 4;
636                                                 memcpy(pes_header+pes_header_len, codec_data+8, len);
637                                                 if (!memcmp(pes_header+pes_header_len, "\x67\x64\x00", 3)) {
638                                                         pes_header[pes_header_len+3] = 0x29; // hardcode h264 level 4.1
639                                                         printf("h264 level patched!\n");
640                                                 }
641                                                 pes_header_len += len;
642                                                 pos = 8 + len;
643                                                 if (codec_data_len > (pos + 2)) {
644                                                         len = (codec_data[pos+1] << 8) | codec_data[pos+2];
645 //                                                      printf("4 %d bytes\n", len);
646                                                         pos += 3;
647                                                         if (codec_data_len >= (pos+len)) {
648 //                                                              printf("codec data ok!\n");
649                                                                 memcpy(pes_header+pes_header_len, "\x00\x00\x00\x01", 4);
650                                                                 pes_header_len += 4;
651                                                                 memcpy(pes_header+pes_header_len, codec_data+pos, len);
652                                                                 pes_header_len += len;
653                                                         }
654                                                         else
655                                                                 printf("codec_data to short(4)\n");
656                                                 }
657                                                 else
658                                                         printf("codec_data to short(3)!\n");
659                                         }
660                                         else
661                                                 printf("codec_data to short(2)!\n");
662                                 }
663                                 else
664                                         printf("codec_data to short(1)!\n");
665                                 self->must_send_header = FALSE;
666                         }
667                 }
668                 else if (self->codec_data && self->codec_data_type == CDT_MPEG4_PART2) {
669                         if (self->must_send_header) {
670                                 unsigned char *codec_data = GST_BUFFER_DATA (self->codec_data);
671                                 unsigned int codec_data_len = GST_BUFFER_SIZE (self->codec_data);
672                                 memcpy(pes_header+pes_header_len, codec_data, codec_data_len);
673                                 pes_header_len += codec_data_len;
674                                 self->must_send_header = FALSE;
675                         }
676                 }
677         }
678         else {
679 //              printf("no timestamp!\n");
680                 pes_header[6] = 0x80;
681                 pes_header[7] = 0x00;
682                 pes_header[8] = 0;
683                 pes_header_len = 9;
684         }
685
686 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
687         if (self->must_pack_bitstream == 1) {
688                 unsigned int pos = 0;
689                 gboolean i_frame = FALSE;
690 //              gboolean s_frame = FALSE;
691                 while(pos < data_len) {
692                         if (data[pos++])
693                                 continue;
694                         if (data[pos++])
695                                 continue;
696                         while (!data[pos])
697                                 ++pos;
698                         if (data[pos++] != 1)
699                                 continue;
700                         if (data[pos++] != 0xB6)
701                                 continue;
702                         switch ((data[pos] & 0xC0) >> 6) {
703                                 case 0: // I-Frame
704 //                                      printf("I ");
705                                         cache_prev_frame = FALSE;
706                                         i_frame = TRUE;
707                                 case 1: // P-Frame
708 //                                      if (!i_frame)
709 //                                              printf("P ");
710                                         if (self->prev_frame != buffer) {
711                                                 struct bitstream bit;
712                                                 gboolean store_frame=FALSE;
713                                                 if (self->prev_frame) {
714                                                         if (!self->num_non_keyframes) {
715 //                                                              printf("no non keyframes...immediate commit prev frame\n");
716                                                                 GstFlowReturn ret = gst_dvbvideosink_render(sink, self->prev_frame);
717                                                                 gst_buffer_unref(self->prev_frame);
718                                                                 self->prev_frame = NULL;
719                                                                 if (ret != GST_FLOW_OK)
720                                                                         return ret;
721                                                                 store_frame = TRUE;
722                                                         }
723                                                         else {
724 //                                                              int i=-4;
725                                                                 pes_header[pes_header_len++] = 0;
726                                                                 pes_header[pes_header_len++] = 0;
727                                                                 pes_header[pes_header_len++] = 1;
728                                                                 pes_header[pes_header_len++] = 0xB6;
729                                                                 bitstream_init(&bit, pes_header+pes_header_len, 1);
730                                                                 bitstream_put(&bit, 1, 2);
731                                                                 bitstream_put(&bit, 0, 1);
732                                                                 bitstream_put(&bit, 1, 1);
733                                                                 bitstream_put(&bit, self->time_inc, self->time_inc_bits);
734                                                                 bitstream_put(&bit, 1, 1);
735                                                                 bitstream_put(&bit, 0, 1);
736                                                                 bitstream_put(&bit, 0x7F >> bit.avail, 8 - bit.avail);
737 //                                                              printf(" insert pack frame %d non keyframes, time_inc %d, time_inc_bits %d -",
738 //                                                                      self->num_non_keyframes, self->time_inc, self->time_inc_bits);
739 //                                                              for (; i < (bit.data - (pes_header+pes_header_len)); ++i)
740 //                                                                      printf(" %02x", pes_header[pes_header_len+i]);
741 //                                                              printf("\nset data_len to 0!\n");
742                                                                 data_len = 0;
743                                                                 pes_header_len += bit.data - (pes_header+pes_header_len);
744                                                                 cache_prev_frame = TRUE;
745                                                         }
746                                                 }
747                                                 else if (!i_frame)
748                                                         store_frame = TRUE;
749
750                                                 self->num_non_keyframes=0;
751
752                                                 // extract time_inc
753                                                 bitstream_init(&bit, data+pos, 0);
754                                                 bitstream_get(&bit, 2); // skip coding_type
755                                                 while(bitstream_get(&bit, 1));
756                                                 bitstream_get(&bit, 1);
757                                                 self->time_inc = bitstream_get(&bit, self->time_inc_bits);
758 //                                              printf("\ntime_inc is %d\n", self->time_inc);
759
760                                                 if (store_frame) {
761 //                                                      printf("store frame\n");
762                                                         self->prev_frame = buffer;
763                                                         gst_buffer_ref (buffer);
764                                                         return GST_FLOW_OK;
765                                                 }
766                                         }
767                                         else {
768                                                 cache_prev_frame = FALSE;
769 //                                              printf(" I/P Frame without non key frame(s)!!\n");
770                                         }
771                                         break;
772                                 case 3: // S-Frame
773 //                                      printf("S ");
774 //                                      s_frame = TRUE;
775                                 case 2: // B-Frame
776 //                                      if (!s_frame)
777 //                                              printf("B ");
778                                         if (++self->num_non_keyframes == 1 && self->prev_frame) {
779 //                                              printf("send grouped with prev P!\n");
780                                                 commit_prev_frame_data = TRUE;
781                                         }
782                                         break;
783                                 case 4: // N-Frame
784                                 default:
785                                         printf("unhandled divx5/xvid frame type %d\n", (data[pos] & 0xC0) >> 6);
786                                         break;
787                         }
788                 }
789 //              printf("\n");
790         }
791 #endif
792
793         payload_len = data_len + pes_header_len - 6;
794
795 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
796         if (self->prev_frame && self->prev_frame != buffer) {
797                 unsigned long long pts = GST_BUFFER_TIMESTAMP(self->prev_frame) * 9LL / 100000 /* convert ns to 90kHz */;
798 //              printf("use prev timestamp: %08llx\n", (long long)GST_BUFFER_TIMESTAMP(self->prev_frame));
799
800                 pes_header[9] =  0x21 | ((pts >> 29) & 0xE);
801                 pes_header[10] = pts >> 22;
802                 pes_header[11] = 0x01 | ((pts >> 14) & 0xFE);
803                 pes_header[12] = pts >> 7;
804                 pes_header[13] = 0x01 | ((pts << 1) & 0xFE);
805         }
806
807         if (commit_prev_frame_data)
808                 payload_len += GST_BUFFER_SIZE (self->prev_frame);
809 #endif
810
811         if (payload_len <= 0xFFFF) {
812                 pes_header[4] = payload_len >> 8;
813                 pes_header[5] = payload_len & 0xFF;
814         }
815         else {
816                 pes_header[4] = 0;
817                 pes_header[5] = 0;
818         }
819
820         write(self->fd, pes_header, pes_header_len);
821
822 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
823         if (commit_prev_frame_data) {
824 //              printf("commit prev frame data\n");
825                 write(self->fd, GST_BUFFER_DATA (self->prev_frame), GST_BUFFER_SIZE (self->prev_frame));
826         }
827
828         if (self->prev_frame && self->prev_frame != buffer) {
829 //              printf("unref prev_frame buffer\n");
830                 gst_buffer_unref(self->prev_frame);
831                 self->prev_frame = NULL;
832         }
833
834         if (cache_prev_frame) {
835 //              printf("cache prev frame\n");
836                 gst_buffer_ref(buffer);
837                 self->prev_frame = buffer;
838         }
839 #endif
840
841         write(self->fd, data, data_len);
842
843         return GST_FLOW_OK;
844 select_error:
845         {
846                 GST_ELEMENT_ERROR (self, RESOURCE, READ, (NULL),
847                                 ("select on file descriptor: %s.", g_strerror (errno)));
848                 GST_DEBUG_OBJECT (self, "Error during select");
849                 return GST_FLOW_ERROR;
850         }
851 stopped:
852         {
853                 GST_DEBUG_OBJECT (self, "Select stopped");
854                 ioctl(self->fd, VIDEO_CLEAR_BUFFER);
855                 return GST_FLOW_WRONG_STATE;
856         }
857 }
858
859 static gboolean 
860 gst_dvbvideosink_set_caps (GstPad * pad, GstCaps * vscaps)
861 {
862         GstStructure *structure = gst_caps_get_structure (vscaps, 0);
863         const gchar *mimetype = gst_structure_get_name (structure);
864         GstDVBVideoSink *self = GST_DVBVIDEOSINK (GST_PAD_PARENT (pad));
865         int streamtype = -1;
866
867         if (!strcmp (mimetype, "video/mpeg")) {
868                 gint mpegversion;
869                 gst_structure_get_int (structure, "mpegversion", &mpegversion);
870                 switch (mpegversion) {
871                         case 1:
872                                 streamtype = 6;
873                                 printf("MIMETYPE video/mpeg1 -> VIDEO_SET_STREAMTYPE, 6\n");
874                         break;
875                         case 2:
876                                 streamtype = 0;
877                                 printf("MIMETYPE video/mpeg2 -> VIDEO_SET_STREAMTYPE, 0\n");
878                         break;
879                         case 4:
880                         {
881                                 const GValue *codec_data = gst_structure_get_value (structure, "codec_data");
882                                 if (codec_data) {
883                                         printf("MPEG4 have codec data\n");
884                                         self->codec_data = gst_value_get_buffer (codec_data);
885                                         self->codec_data_type = CDT_MPEG4_PART2;
886                                         gst_buffer_ref (self->codec_data);
887                                         self->must_send_header = TRUE;
888                                 }
889                                 streamtype = 4;
890                                 printf("MIMETYPE video/mpeg4 -> VIDEO_SET_STREAMTYPE, 4\n");
891                         }
892                         break;
893                         default:
894                                 GST_ELEMENT_ERROR (self, STREAM, FORMAT, (NULL), ("unhandled mpeg version %i", mpegversion));
895                         break;
896                 }
897         } else if (!strcmp (mimetype, "video/x-h264")) {
898                 const GValue *codec_data = gst_structure_get_value (structure, "codec_data");
899                 streamtype = 1;
900                 if (codec_data) {
901                         printf("H264 have codec data..!\n");
902                         self->codec_data = gst_value_get_buffer (codec_data);
903                         gst_buffer_ref (self->codec_data);
904                         self->must_send_header = TRUE;
905                 }
906                 printf("MIMETYPE video/x-h264 VIDEO_SET_STREAMTYPE, 1\n");
907         } else if (!strcmp (mimetype, "video/x-h263")) {
908                 streamtype = 2;
909                 printf("MIMETYPE video/x-h263 VIDEO_SET_STREAMTYPE, 2\n");
910         } else if (!strcmp (mimetype, "video/x-xvid")) {
911                 streamtype = 10;
912 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
913                 self->must_pack_bitstream = 1;
914 #endif
915                 printf("MIMETYPE video/x-xvid -> VIDEO_SET_STREAMTYPE, 10\n");
916         } else if (!strcmp (mimetype, "video/x-divx")) {
917                 gint divxversion;
918                 gst_structure_get_int (structure, "divxversion", &divxversion);
919                 switch (divxversion) {
920                         case 3:
921                         {
922                                 #define B_GET_BITS(w,e,b)  (((w)>>(b))&(((unsigned)(-1))>>((sizeof(unsigned))*8-(e+1-b))))
923                                 #define B_SET_BITS(name,v,e,b)  (((unsigned)(v))<<(b))
924                                 static const guint8 brcm_divx311_sequence_header[] = {
925                                         0x00, 0x00, 0x01, 0xE0, 0x00, 0x34, 0x80, 0x80, // PES HEADER
926                                         0x05, 0x2F, 0xFF, 0xFF, 0xFF, 0xFF, 
927                                         0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x20, /* 0 .. 7 */
928                                         0x08, 0xC8, 0x0D, 0x40, 0x00, 0x53, 0x88, 0x40, /* 8 .. 15 */
929                                         0x0C, 0x40, 0x01, 0x90, 0x00, 0x97, 0x53, 0x0A, /* 16 .. 24 */
930                                         0x00, 0x00, 0x00, 0x00,
931                                         0x30, 0x7F, 0x00, 0x00, 0x01, 0xB2, 0x44, 0x69, /* 0 .. 7 */
932                                         0x76, 0x58, 0x33, 0x31, 0x31, 0x41, 0x4E, 0x44  /* 8 .. 15 */
933                                 };
934                                 guint8 *data = malloc(63);
935                                 gint height, width;
936                                 gst_structure_get_int (structure, "height", &height);
937                                 gst_structure_get_int (structure, "width", &width);
938                                 memcpy(data, brcm_divx311_sequence_header, 63);
939                                 self->divx311_header = data;
940                                 data += 38;
941                                 data[0] = B_GET_BITS(width,11,4);
942                                 data[1] = B_SET_BITS("width [3..0]", B_GET_BITS(width,3,0), 7, 4) |
943                                         B_SET_BITS("'10'", 0x02, 3, 2) |
944                                         B_SET_BITS("height [11..10]", B_GET_BITS(height,11,10), 1, 0);
945                                 data[2] = B_GET_BITS(height,9,2);
946                                 data[3]= B_SET_BITS("height [1.0]", B_GET_BITS(height,1,0), 7, 6) |
947                                         B_SET_BITS("'100000'", 0x20, 5, 0);
948                                 streamtype = 13;
949                                 self->must_send_header = TRUE;
950                                 printf("MIMETYPE video/x-divx vers. 3 -> VIDEO_SET_STREAMTYPE, 13\n");
951                         }
952                         break;
953                         case 4:
954                                 streamtype = 14;
955                                 printf("MIMETYPE video/x-divx vers. 4 -> VIDEO_SET_STREAMTYPE, 14\n");
956                         break;
957                         case 5:
958                                 streamtype = 15;
959 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
960                                 self->must_pack_bitstream = 1;
961 #endif
962                                 printf("MIMETYPE video/x-divx vers. 5 -> VIDEO_SET_STREAMTYPE, 15\n");
963                         break;
964                         default:
965                                 GST_ELEMENT_ERROR (self, STREAM, FORMAT, (NULL), ("unhandled divx version %i", divxversion));
966                         break;
967                 }
968         }
969         if (streamtype != -1) {
970                 if (ioctl(self->fd, VIDEO_SET_STREAMTYPE, streamtype) < 0 )
971                         if ( streamtype != 0 && streamtype != 6 )
972                                 GST_ELEMENT_ERROR (self, STREAM, CODEC_NOT_FOUND, (NULL), ("hardware decoder can't handle streamtype %i", streamtype));
973         } else
974                 GST_ELEMENT_ERROR (self, STREAM, TYPE_NOT_FOUND, (NULL), ("unimplemented stream type %s", mimetype));
975
976         return TRUE;
977 }
978
979 static gboolean
980 gst_dvbvideosink_start (GstBaseSink * basesink)
981 {
982         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
983         self->fd = open("/dev/dvb/adapter0/video0", O_RDWR);
984 //      self->fd = open("/dump.pes", O_RDWR|O_CREAT|O_TRUNC, 0555);
985
986         gint control_sock[2];
987
988         if (socketpair (PF_UNIX, SOCK_STREAM, 0, control_sock) < 0)
989                 goto socket_pair;
990
991         READ_SOCKET (self) = control_sock[0];
992         WRITE_SOCKET (self) = control_sock[1];
993
994         fcntl (READ_SOCKET (self), F_SETFL, O_NONBLOCK);
995         fcntl (WRITE_SOCKET (self), F_SETFL, O_NONBLOCK);
996
997         if (self->fd >= 0)
998         {
999                 ioctl(self->fd, VIDEO_SELECT_SOURCE, VIDEO_SOURCE_MEMORY);
1000                 ioctl(self->fd, VIDEO_PLAY);
1001         }
1002
1003         return TRUE;
1004         /* ERRORS */
1005 socket_pair:
1006         {
1007                 GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ_WRITE, (NULL),
1008                                 GST_ERROR_SYSTEM);
1009                 return FALSE;
1010         }
1011 }
1012
1013 static gboolean
1014 gst_dvbvideosink_stop (GstBaseSink * basesink)
1015 {
1016         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
1017         if (self->fd >= 0)
1018         {
1019                 ioctl(self->fd, VIDEO_STOP);
1020                 ioctl(self->fd, VIDEO_SELECT_SOURCE, VIDEO_SOURCE_DEMUX);
1021                 close(self->fd);
1022         }
1023
1024         close (READ_SOCKET (self));
1025         close (WRITE_SOCKET (self));
1026
1027         if (self->divx311_header)
1028                 free(self->divx311_header);
1029
1030         if (self->codec_data)
1031                 gst_buffer_unref(self->codec_data);
1032
1033 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
1034         if (self->prev_frame)
1035                 gst_buffer_unref(self->prev_frame);
1036 #endif
1037
1038         return TRUE;
1039 }
1040
1041 /* entry point to initialize the plug-in
1042  * initialize the plug-in itself
1043  * register the element factories and pad templates
1044  * register the features
1045  *
1046  * exchange the string 'plugin' with your elemnt name
1047  */
1048 static gboolean
1049 plugin_init (GstPlugin *plugin)
1050 {
1051         return gst_element_register (plugin, "dvbvideosink",
1052                                                  GST_RANK_PRIMARY,
1053                                                  GST_TYPE_DVBVIDEOSINK);
1054 }
1055
1056 /* this is the structure that gstreamer looks for to register plugins
1057  *
1058  * exchange the strings 'plugin' and 'Template plugin' with you plugin name and
1059  * description
1060  */
1061 GST_PLUGIN_DEFINE (
1062         GST_VERSION_MAJOR,
1063         GST_VERSION_MINOR,
1064         "dvb_video_out",
1065         "DVB Video Output",
1066         plugin_init,
1067         VERSION,
1068         "LGPL",
1069         "GStreamer",
1070         "http://gstreamer.net/"
1071 )