small cleanup
[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 #define GST_DVBVIDEOSINK_GET_PRIVATE(obj)  \
79    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_DVBVIDEOSINK, GstDVBVideoSinkPrivate))
80
81 struct _GstDVBVideoSinkPrivate
82 {
83
84         hardwaretype_t model;
85
86 };
87
88 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
89 struct bitstream
90 {
91         guint8 *data;
92         guint8 last;
93         int avail;
94 };
95
96 void bitstream_init(struct bitstream *bit, const void *buffer, gboolean wr)
97 {
98         bit->data = (guint8*) buffer;
99         if (wr) {
100                 bit->avail = 0;
101                 bit->last = 0;
102         }
103         else {
104                 bit->avail = 8;
105                 bit->last = *bit->data++;
106         }
107 }
108
109 unsigned long bitstream_get(struct bitstream *bit, int bits)
110 {
111         unsigned long res=0;
112         while (bits)
113         {
114                 unsigned int d=bits;
115                 if (!bit->avail) {
116                         bit->last = *bit->data++;
117                         bit->avail = 8;
118                 }
119                 if (d > bit->avail)
120                         d=bit->avail;
121                 res<<=d;
122                 res|=(bit->last>>(bit->avail-d))&~(-1<<d);
123                 bit->avail-=d;
124                 bits-=d;
125         }
126         return res;
127 }
128
129 void bitstream_put(struct bitstream *bit, unsigned long val, int bits)
130 {
131         while (bits)
132         {
133                 bit->last |= ((val & (1 << (bits-1))) ? 1 : 0) << (7 - bit->avail);
134                 if (++bit->avail == 8) {
135                         *bit->data = bit->last;
136                         ++bit->data;
137                         bit->last = 0;
138                         bit->avail = 0;
139                 }
140                 --bits;
141         }
142 }
143 #endif
144
145 /* We add a control socket as in fdsrc to make it shutdown quickly when it's blocking on the fd.
146  * Select is used to determine when the fd is ready for use. When the element state is changed,
147  * it happens from another thread while fdsink is select'ing on the fd. The state-change thread 
148  * sends a control message, so fdsink wakes up and changes state immediately otherwise
149  * it would stay blocked until it receives some data. */
150
151 /* the select call is also performed on the control sockets, that way
152  * we can send special commands to unblock the select call */
153 #define CONTROL_STOP            'S'                     /* stop the select call */
154 #define CONTROL_SOCKETS(sink)   sink->control_sock
155 #define WRITE_SOCKET(sink)      sink->control_sock[1]
156 #define READ_SOCKET(sink)       sink->control_sock[0]
157
158 #define SEND_COMMAND(sink, command)                     \
159 G_STMT_START {                                          \
160         unsigned char c; c = command;                   \
161         write (WRITE_SOCKET(sink), &c, 1);              \
162 } G_STMT_END
163
164 #define READ_COMMAND(sink, command, res)                \
165 G_STMT_START {                                          \
166         res = read(READ_SOCKET(sink), &command, 1);     \
167 } G_STMT_END
168
169 GST_DEBUG_CATEGORY_STATIC (dvbvideosink_debug);
170 #define GST_CAT_DEFAULT dvbvideosink_debug
171
172 /* Filter signals and args */
173 enum {
174         /* FILL ME */
175         LAST_SIGNAL
176 };
177
178 enum {
179         ARG_0,
180         ARG_SILENT
181 };
182
183 #define COMMON_VIDEO_CAPS \
184   "width = (int) [ 16, 4096 ], " \
185   "height = (int) [ 16, 4096 ], " \
186   "framerate = (fraction) [ 0, MAX ]"
187
188 static GstStaticPadTemplate sink_factory =
189 GST_STATIC_PAD_TEMPLATE (
190         "sink",
191         GST_PAD_SINK,
192         GST_PAD_ALWAYS,
193         GST_STATIC_CAPS (
194                 "video/mpeg, "
195                 "mpegversion = (int) { 1, 2, 4 }, "
196                 "systemstream = (boolean) false, "
197         COMMON_VIDEO_CAPS "; "
198                 "video/x-msmpeg, "
199         COMMON_VIDEO_CAPS ", mspegversion = (int) 43; "
200                 "video/x-h264, "
201         COMMON_VIDEO_CAPS "; "
202                 "video/x-h263, "
203         COMMON_VIDEO_CAPS "; "
204                 "video/x-divx, "
205         COMMON_VIDEO_CAPS ", divxversion = (int) [ 3, 5 ]; "
206                 "video/x-xvid, "
207         COMMON_VIDEO_CAPS "; ")
208 );
209
210 #define DEBUG_INIT(bla) \
211         GST_DEBUG_CATEGORY_INIT (dvbvideosink_debug, "dvbvideosink", 0, "dvbvideosink element");
212
213 GST_BOILERPLATE_FULL (GstDVBVideoSink, gst_dvbvideosink, GstBaseSink,
214         GST_TYPE_BASE_SINK, DEBUG_INIT);
215
216 static void     gst_dvbvideosink_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec);
217 static void     gst_dvbvideosink_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec);
218 static gboolean gst_dvbvideosink_start (GstBaseSink * sink);
219 static gboolean gst_dvbvideosink_stop (GstBaseSink * sink);
220 static gboolean gst_dvbvideosink_event (GstBaseSink * sink, GstEvent * event);
221 static GstFlowReturn gst_dvbvideosink_preroll (GstBaseSink * sink, GstBuffer * buffer);
222 static GstFlowReturn gst_dvbvideosink_render (GstBaseSink * sink, GstBuffer * buffer);
223 static gboolean gst_dvbvideosink_query (GstElement * element, GstQuery * query);
224 static gboolean gst_dvbvideosink_set_caps (GstBaseSink * sink, GstCaps * caps);
225 static GstCaps *gst_dvbvideosink_get_caps (GstBaseSink * bsink);
226 static gboolean gst_dvbvideosink_unlock (GstBaseSink * basesink);
227 static gboolean gst_dvbvideosink_unlock_stop (GstBaseSink * basesink);
228 static void gst_dvbvideosink_dispose (GObject * object);
229
230
231 static void
232 gst_dvbvideosink_base_init (gpointer klass)
233 {
234         static GstElementDetails element_details = {
235                 "A DVB video sink",
236                 "Generic/DVBVideoSink",
237                 "Output video PES / ES into a DVB video device for hardware playback",
238                 "Felix Domke <tmbinc@elitedvb.net>"
239         };
240         GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
241
242         gst_element_class_add_pad_template (element_class,
243                 gst_static_pad_template_get (&sink_factory));
244         gst_element_class_set_details (element_class, &element_details);
245 }
246
247 /* initialize the plugin's class */
248 static void
249 gst_dvbvideosink_class_init (GstDVBVideoSinkClass *klass)
250 {
251         GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
252         GstBaseSinkClass *gstbasesink_class = GST_BASE_SINK_CLASS (klass);
253         GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
254         g_type_class_add_private (klass, sizeof (GstDVBVideoSinkPrivate));
255
256         gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_dvbvideosink_set_property);
257         gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_dvbvideosink_get_property);
258         gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_dvbvideosink_dispose);
259
260         gstbasesink_class->get_times = NULL;
261         gstbasesink_class->start = GST_DEBUG_FUNCPTR (gst_dvbvideosink_start);
262         gstbasesink_class->stop = GST_DEBUG_FUNCPTR (gst_dvbvideosink_stop);
263         gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_dvbvideosink_render);
264         gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_dvbvideosink_event);
265         gstbasesink_class->unlock = GST_DEBUG_FUNCPTR (gst_dvbvideosink_unlock);
266         gstbasesink_class->unlock_stop = GST_DEBUG_FUNCPTR ( gst_dvbvideosink_unlock_stop);
267         gstbasesink_class->set_caps = GST_DEBUG_FUNCPTR (gst_dvbvideosink_set_caps);
268         gstbasesink_class->get_caps = GST_DEBUG_FUNCPTR (gst_dvbvideosink_get_caps);
269         gstbasesink_class->preroll = GST_DEBUG_FUNCPTR (gst_dvbvideosink_preroll);
270
271         element_class->query = GST_DEBUG_FUNCPTR (gst_dvbvideosink_query);
272
273         g_object_class_install_property (gobject_class, ARG_SILENT,
274                 g_param_spec_boolean ("silent", "Silent", "Produce verbose output ?", FALSE, G_PARAM_READWRITE));
275 }
276
277 #define H264_BUFFER_SIZE (64*1024+2048)
278
279 /* initialize the new element
280  * instantiate pads and add them to element
281  * set functions
282  * initialize structure
283  */
284 static void
285 gst_dvbvideosink_init (GstDVBVideoSink *klass, GstDVBVideoSinkClass * gclass)
286 {
287         klass->priv = GST_DVBVIDEOSINK_GET_PRIVATE (klass);
288         FILE *f = fopen("/proc/stb/vmpeg/0/fallback_framerate", "r");
289         klass->dec_running = FALSE;
290         klass->silent = FALSE;
291         klass->must_send_header = TRUE;
292         klass->h264_buffer = NULL;
293         klass->h264_nal_len_size = 0;
294         klass->codec_data = NULL;
295         klass->codec_type = CT_H264;
296 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
297         klass->must_pack_bitstream = 0;
298         klass->num_non_keyframes = 0;
299         klass->prev_frame = NULL;
300 #endif
301
302         if (f) {
303                 fgets(klass->saved_fallback_framerate, 16, f);
304                 fclose(f);
305         }
306
307         klass->priv->model = DMLEGACY;
308         int fd = open("/proc/stb/info/model", O_RDONLY);
309         if ( fd > 0 )
310         {
311                 gchar string[8] = { 0, };
312                 ssize_t rd = read(fd, string, 7);
313                 if ( rd >= 5 )
314                 {
315                         if ( !strncasecmp(string, "DM7025", 6) )
316                                 klass->priv->model = DM7025;
317                         else if ( !strncasecmp(string, "DM8000", 6) )
318                                 klass->priv->model = DM8000;
319                         else if ( !strncasecmp(string, "DM800", 5) )
320                                 klass->priv->model = DM800;
321                         else if ( !strncasecmp(string, "DM500HD", 7) )
322                                 klass->priv->model = DM500HD;
323                 }
324                 close(fd);
325                 GST_INFO_OBJECT (klass, "found hardware model %s (%i)",string,klass->priv->model);
326         }
327
328         GST_BASE_SINK (klass)->sync = TRUE;
329 }
330
331 static void gst_dvbvideosink_dispose (GObject * object)
332 {
333         GstDVBVideoSink *self;
334         
335         self = GST_DVBVIDEOSINK (object);
336         
337         close (READ_SOCKET (self));
338         close (WRITE_SOCKET (self));
339         READ_SOCKET (self) = -1;
340         WRITE_SOCKET (self) = -1;
341
342         G_OBJECT_CLASS (parent_class)->dispose (object);
343 }
344
345 static void
346 gst_dvbvideosink_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec)
347 {
348         GstDVBVideoSink *sink;
349
350         g_return_if_fail (GST_IS_DVBVIDEOSINK (object));
351         sink = GST_DVBVIDEOSINK (object);
352
353         switch (prop_id)
354         {
355         case ARG_SILENT:
356                 sink->silent = g_value_get_boolean (value);
357                 break;
358         default:
359                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
360                 break;
361         }
362 }
363
364 static void
365 gst_dvbvideosink_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec)
366 {
367         GstDVBVideoSink *sink;
368
369         g_return_if_fail (GST_IS_DVBVIDEOSINK (object));
370         sink = GST_DVBVIDEOSINK (object);
371
372         switch (prop_id) {
373         case ARG_SILENT:
374                 g_value_set_boolean (value, sink->silent);
375                 break;
376         default:
377                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
378                 break;
379         }
380 }
381
382 static gboolean
383 gst_dvbvideosink_query (GstElement * element, GstQuery * query)
384 {
385         GstDVBVideoSink *self = GST_DVBVIDEOSINK (element);
386
387         switch (GST_QUERY_TYPE (query)) {
388         case GST_QUERY_POSITION:
389         {
390                 gint64 cur = 0, res = 0;
391                 GstFormat format;
392
393                 gst_query_parse_position (query, &format, NULL);
394
395                 if (format != GST_FORMAT_TIME)
396                         goto query_default;
397
398                 ioctl(self->fd, VIDEO_GET_PTS, &cur);
399                 
400                 res = cur *11111;
401
402                 gst_query_set_position (query, format, res);
403
404                 GST_LOG_OBJECT (self, "GST_QUERY_POSITION pts=%lld: %" G_GUINT64_FORMAT ", time: %" GST_TIME_FORMAT, cur, GST_TIME_ARGS (res));
405                 return TRUE;
406         }
407         default:
408 query_default:
409                 return GST_ELEMENT_CLASS (parent_class)->query (element, query);
410         }
411 }
412
413 static gboolean gst_dvbvideosink_unlock (GstBaseSink * basesink)
414 {
415         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
416
417         SEND_COMMAND (self, CONTROL_STOP);
418
419         return TRUE;
420 }
421
422 static gboolean gst_dvbvideosink_unlock_stop (GstBaseSink * sink)
423 {
424         GstDVBVideoSink *self = GST_DVBVIDEOSINK (sink);
425         while (TRUE)
426         {
427                 gchar command;
428                 int res;
429                 
430                 READ_COMMAND (self, command, res);
431                 if (res < 0)
432                 {
433                 GST_LOG_OBJECT (self, "no more commands");
434                 /* no more commands */
435                 break;
436                 }
437         }
438         return TRUE;
439 }
440
441 static gboolean
442 gst_dvbvideosink_event (GstBaseSink * sink, GstEvent * event)
443 {
444         GstDVBVideoSink *self = GST_DVBVIDEOSINK (sink);
445         GST_DEBUG_OBJECT (self, "EVENT %s", gst_event_type_get_name(GST_EVENT_TYPE (event)));
446
447         switch (GST_EVENT_TYPE (event)) {
448         case GST_EVENT_FLUSH_START:
449                 ioctl(self->fd, VIDEO_CLEAR_BUFFER);
450                 self->must_send_header = TRUE;
451                 break;
452         case GST_EVENT_FLUSH_STOP:
453                 ioctl(self->fd, VIDEO_CLEAR_BUFFER);
454                 self->must_send_header = TRUE;
455                 break;
456
457         case GST_EVENT_NEWSEGMENT:{
458                 GstFormat fmt;
459                 gboolean update;
460                 gdouble rate, applied_rate;
461                 gint64 cur, stop, time;
462                 int skip = 0, repeat = 0, ret;
463                 gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate, &fmt, &cur, &stop, &time);
464                 GST_LOG_OBJECT (self, "GST_EVENT_NEWSEGMENT rate=%f applied_rate=%f\n", rate, applied_rate);
465                 
466                 if (fmt == GST_FORMAT_TIME)
467                 {       
468                         if ( rate > 1 )
469                                 skip = (int) rate;
470                         else if ( rate < 1 )
471                                 repeat = 1.0/rate;
472
473                         ret = ioctl(self->fd, VIDEO_SLOWMOTION, repeat);
474                         ret = ioctl(self->fd, VIDEO_FAST_FORWARD, skip);
475 //                      gst_segment_set_newsegment_full (&dec->segment, update, rate, applied_rate, dformat, cur, stop, time);
476                 }
477                 break;
478         }
479
480         default:
481                 break;
482         }
483         return TRUE;
484 }
485
486 static GstFlowReturn
487 gst_dvbvideosink_render (GstBaseSink * sink, GstBuffer * buffer)
488 {
489         GstDVBVideoSink *self = GST_DVBVIDEOSINK (sink);
490         unsigned char *data = GST_BUFFER_DATA(buffer);
491         unsigned int data_len = GST_BUFFER_SIZE (buffer);
492         guint8 pes_header[2048];
493         unsigned int pes_header_len=0;
494         unsigned int payload_len=0;
495         fd_set readfds;
496         fd_set writefds;
497         fd_set priofds;
498         gint retval;
499 //      int i=0;
500
501 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
502         gboolean commit_prev_frame_data = FALSE,
503                         cache_prev_frame = FALSE;
504 #endif
505
506 //      for (;i < (data_len > 0xF ? 0xF : data_len); ++i)
507 //              printf("%02x ", data[i]);
508 //      printf("%d bytes\n", data_len);
509 //      printf("timestamp: %08llx\n", (long long)GST_BUFFER_TIMESTAMP(buffer));
510
511         FD_ZERO (&readfds);
512         FD_SET (READ_SOCKET (self), &readfds);
513
514         FD_ZERO (&writefds);
515         FD_SET (self->fd, &writefds);
516
517         FD_ZERO (&priofds);
518         FD_SET (self->fd, &priofds);
519
520         do {
521                 GST_LOG_OBJECT (self, "going into select, have %d bytes to write",
522                                 data_len);
523                 retval = select (FD_SETSIZE, &readfds, &writefds, &priofds, NULL);
524         } while ((retval == -1 && errno == EINTR));
525
526         if (retval == -1)
527                 goto select_error;
528
529         if (FD_ISSET (READ_SOCKET (self), &readfds)) {
530                 /* read all stop commands */
531                 while (TRUE) {
532                         gchar command;
533                         int res;
534
535                         READ_COMMAND (self, command, res);
536                         if (res < 0) {
537                                 GST_LOG_OBJECT (self, "no more commands");
538                                 /* no more commands */
539                                 break;
540                         }
541                 }
542                 goto stopped;
543         }
544
545         if (FD_ISSET (self->fd, &priofds))
546         {
547                 GstStructure *s;
548                 GstMessage *msg;
549
550                 struct video_event evt;
551                 if (ioctl(self->fd, VIDEO_GET_EVENT, &evt) < 0)
552                         g_warning ("failed to ioctl VIDEO_GET_EVENT!");
553                 else
554                 {
555                         GST_INFO_OBJECT (self, "VIDEO_EVENT %d", evt.type);
556                         if (evt.type == VIDEO_EVENT_SIZE_CHANGED)
557                         {
558                                 s = gst_structure_new ("eventSizeChanged",
559                                         "aspect_ratio", G_TYPE_INT, evt.u.size.aspect_ratio == 0 ? 2 : 3,
560                                         "width", G_TYPE_INT, evt.u.size.w,
561                                         "height", G_TYPE_INT, evt.u.size.h, NULL);
562                                 msg = gst_message_new_element (GST_OBJECT (sink), s);
563                                 gst_element_post_message (GST_ELEMENT (sink), msg);
564                         }
565                         else if (evt.type == VIDEO_EVENT_FRAME_RATE_CHANGED)
566                         {
567                                 s = gst_structure_new ("eventFrameRateChanged",
568                                         "frame_rate", G_TYPE_INT, evt.u.frame_rate, NULL);
569                                 msg = gst_message_new_element (GST_OBJECT (sink), s);
570                                 gst_element_post_message (GST_ELEMENT (sink), msg);
571                         }
572                         else if (evt.type == 16 /*VIDEO_EVENT_PROGRESSIVE_CHANGED*/)
573                         {
574                                 s = gst_structure_new ("eventProgressiveChanged",
575                                         "progressive", G_TYPE_INT, evt.u.frame_rate, NULL);
576                                 msg = gst_message_new_element (GST_OBJECT (sink), s);
577                                 gst_element_post_message (GST_ELEMENT (sink), msg);
578                         }
579                         else
580                                 g_warning ("unhandled DVBAPI Video Event %d", evt.type);
581                 }
582         }
583
584         if (self->fd < 0)
585                 return GST_FLOW_OK;
586
587 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
588         if (self->must_pack_bitstream == 1) {
589                 cache_prev_frame = TRUE;
590                 unsigned int pos = 0;
591                 while(pos < data_len) {
592                         if (data[pos++])
593                                 continue;
594                         if (data[pos++])
595                                 continue;
596                         while (!data[pos])
597                                 ++pos;
598                         if (data[pos++] != 1)
599                                 continue;
600                         if ((data[pos++] & 0xF0) == 0x20) { // we need time_inc_res
601                                 gboolean low_delay=FALSE;
602                                 unsigned int ver_id = 1, shape=0, time_inc_res=0, tmp=0;
603                                 struct bitstream bit;
604                                 bitstream_init(&bit, data+pos, 0);
605                                 bitstream_get(&bit, 9);
606                                 if (bitstream_get(&bit, 1)) {
607                                         ver_id = bitstream_get(&bit, 4); // ver_id
608                                         bitstream_get(&bit, 3);
609                                 }
610                                 if ((tmp=bitstream_get(&bit, 4)) == 15) { // Custom Aspect Ration
611                                         bitstream_get(&bit, 8); // skip AR width
612                                         bitstream_get(&bit, 8); // skip AR height
613                                 }
614                                 if (bitstream_get(&bit, 1)) {
615                                         bitstream_get(&bit, 2);
616                                         low_delay = bitstream_get(&bit, 1) ? TRUE : FALSE;
617                                         if (bitstream_get(&bit, 1)) {
618                                                 bitstream_get(&bit, 32);
619                                                 bitstream_get(&bit, 32);
620                                                 bitstream_get(&bit, 15);
621                                         }
622                                 }
623                                 shape = bitstream_get(&bit, 2);
624                                 if (ver_id != 1 && shape == 3 /* Grayscale */)
625                                         bitstream_get(&bit, 4);
626                                 bitstream_get(&bit, 1);
627                                 time_inc_res = bitstream_get(&bit, 16);
628                                 self->time_inc_bits = 0;
629                                 while (time_inc_res) { // count bits
630                                         ++self->time_inc_bits;
631                                         time_inc_res >>= 1;
632                                 }
633 //                              printf("%d time_inc_bits\n", self->time_inc_bits);
634                         }
635                 }
636         }
637
638         if (self->must_pack_bitstream == 1) {
639                 int tmp1, tmp2;
640                 unsigned char c1, c2;
641                 unsigned int pos = 0;
642                 while(pos < data_len) {
643                         if (data[pos++])
644                                 continue;
645                         if (data[pos++])
646                                 continue;
647                         while (!data[pos])
648                                 ++pos;
649                         if (data[pos++] != 1)
650                                 continue;
651                         if (data[pos++] != 0xB2)
652                                 continue;
653                         if (data_len - pos < 13)
654                                 break;
655                         if (sscanf((char*)data+pos, "DivX%d%c%d%cp", &tmp1, &c1, &tmp2, &c2) == 4 && (c1 == 'b' || c1 == 'B') && (c2 == 'p' || c2 == 'P')) {
656                                 GST_INFO_OBJECT (self, "%s seen... already packed!", (char*)data+pos);
657                                 self->must_pack_bitstream = 0;
658                         }
659 //                      if (self->must_pack_bitstream)
660 //                              printf("pack needed\n");
661 //                      else
662 //                              printf("no pack needed\n");
663                 }
664         }
665 #endif
666
667         pes_header[0] = 0;
668         pes_header[1] = 0;
669         pes_header[2] = 1;
670         pes_header[3] = 0xE0;
671
672                 /* do we have a timestamp? */
673         if (GST_BUFFER_TIMESTAMP(buffer) != GST_CLOCK_TIME_NONE) {
674                 unsigned long long pts = GST_BUFFER_TIMESTAMP(buffer) * 9LL / 100000 /* convert ns to 90kHz */;
675
676                 pes_header[6] = 0x80;
677                 pes_header[7] = 0x80;
678                 
679                 pes_header[8] = 5;
680                 
681                 pes_header[9] =  0x21 | ((pts >> 29) & 0xE);
682                 pes_header[10] = pts >> 22;
683                 pes_header[11] = 0x01 | ((pts >> 14) & 0xFE);
684                 pes_header[12] = pts >> 7;
685                 pes_header[13] = 0x01 | ((pts << 1) & 0xFE);
686
687                 pes_header_len = 14;
688
689                 if (self->codec_data) {
690                         if (self->must_send_header) {
691                                 if (self->codec_type != CT_MPEG1 && self->codec_type != CT_MPEG2) {
692                                         unsigned char *codec_data = GST_BUFFER_DATA (self->codec_data);
693                                         unsigned int codec_data_len = GST_BUFFER_SIZE (self->codec_data);
694                                         if (self->codec_type == CT_DIVX311)
695                                                 write(self->fd, codec_data, codec_data_len);
696                                         else {
697                                                 memcpy(pes_header+pes_header_len, codec_data, codec_data_len);
698                                                 pes_header_len += codec_data_len;
699                                         }
700                                         self->must_send_header = FALSE;
701                                 }
702                         }
703                         if (self->codec_type == CT_H264) {  // MKV stuff
704                                 unsigned int pos = 0;
705                                 if (self->h264_nal_len_size == 4) {
706                                         while(TRUE) {
707                                                 unsigned int pack_len = (data[pos] << 24) | (data[pos+1] << 16) | (data[pos+2] << 8) | data[pos+3];
708 //                                              printf("patch %02x %02x %02x %02x\n",
709 //                                                      data[pos],
710 //                                                      data[pos + 1],
711 //                                                      data[pos + 2],
712 //                                                      data[pos + 3]);
713                                                 memcpy(data+pos, "\x00\x00\x00\x01", 4);
714 //                                              printf("pos %d, (%d) >= %d\n", pos, pos+pack_len, data_len);
715                                                 pos += 4;
716                                                 if ((pos + pack_len) >= data_len)
717                                                         break;
718                                                 pos += pack_len;
719                                         }
720                                 }
721                                 else if (self->h264_nal_len_size == 3) {
722                                         while(TRUE) {
723                                                 unsigned int pack_len = (data[pos] << 16) | (data[pos+1] << 8) | data[pos+2];
724 //                                              printf("patch %02x %02x %02x\n",
725 //                                                      data[pos],
726 //                                                      data[pos + 1],
727 //                                                      data[pos + 2]);
728                                                 memcpy(data+pos, "\x00\x00\x01", 3);
729 //                                              printf("pos %d, (%d) >= %d\n", pos, pos+pack_len, data_len);
730                                                 pos += 3;
731                                                 if ((pos + pack_len) >= data_len)
732                                                         break;
733                                                 pos += pack_len;
734                                         }
735                                 }
736                                 else {
737                                         unsigned char *dest = GST_BUFFER_DATA (self->h264_buffer);
738                                         unsigned int dest_pos = 0;
739                                         while(TRUE) {
740                                                 unsigned int pack_len = self->h264_nal_len_size == 2 ? (data[pos] << 8) | data[pos+1] : data[pos];
741                                                 if (dest_pos + pack_len <= H264_BUFFER_SIZE) {
742                                                         memcpy(dest+dest_pos, "\x00\x00\x01", 3);
743                                                         dest_pos += 3;
744                                                         pos += self->h264_nal_len_size;
745                                                         memcpy(dest+dest_pos, data+pos, pack_len);
746                                                         dest_pos += pack_len;
747                                                         if ((pos + pack_len) >= data_len)
748                                                                 break;
749                                                         pos += pack_len;
750                                                 }
751                                                 else {
752                                                         g_error("BUG!!!!!!!! H264 buffer to small skip video data!!.. please report!\n");
753                                                         break;
754                                                 }
755                                         }
756                                         data = dest;
757                                         data_len = dest_pos;
758                                 }
759                         }
760                         else if (self->codec_type == CT_MPEG4_PART2) {
761                                 if (data[0] || data[1] || data[2] != 1) {
762                                         memcpy(pes_header+pes_header_len, "\x00\x00\x01", 3);
763                                         pes_header_len += 3;
764                                 }
765                         }
766                         else if (self->codec_type == CT_DIVX311) {
767                                 if (data[0] || data[1] || data[2] != 1 || data[3] != 0xb6) {
768                                         memcpy(pes_header+pes_header_len, "\x00\x00\x01\xb6", 4);
769                                         pes_header_len += 4;
770                                 }
771                         }
772                 }
773         }
774         else {
775 //              printf("no timestamp!\n");
776                 pes_header[6] = 0x80;
777                 pes_header[7] = 0x00;
778                 pes_header[8] = 0;
779                 pes_header_len = 9;
780         }
781
782 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
783         if (self->must_pack_bitstream == 1) {
784                 unsigned int pos = 0;
785                 gboolean i_frame = FALSE;
786 //              gboolean s_frame = FALSE;
787                 while(pos < data_len) {
788                         if (data[pos++])
789                                 continue;
790                         if (data[pos++])
791                                 continue;
792                         while (!data[pos])
793                                 ++pos;
794                         if (data[pos++] != 1)
795                                 continue;
796                         if (data[pos++] != 0xB6)
797                                 continue;
798                         switch ((data[pos] & 0xC0) >> 6) {
799                                 case 0: // I-Frame
800 //                                      printf("I ");
801                                         cache_prev_frame = FALSE;
802                                         i_frame = TRUE;
803                                 case 1: // P-Frame
804 //                                      if (!i_frame)
805 //                                              printf("P ");
806                                         if (self->prev_frame != buffer) {
807                                                 struct bitstream bit;
808                                                 gboolean store_frame=FALSE;
809                                                 if (self->prev_frame) {
810                                                         if (!self->num_non_keyframes) {
811 //                                                              printf("no non keyframes...immediate commit prev frame\n");
812                                                                 GstFlowReturn ret = gst_dvbvideosink_render(sink, self->prev_frame);
813                                                                 gst_buffer_unref(self->prev_frame);
814                                                                 self->prev_frame = NULL;
815                                                                 if (ret != GST_FLOW_OK)
816                                                                         return ret;
817                                                                 store_frame = TRUE;
818                                                         }
819                                                         else {
820 //                                                              int i=-4;
821                                                                 pes_header[pes_header_len++] = 0;
822                                                                 pes_header[pes_header_len++] = 0;
823                                                                 pes_header[pes_header_len++] = 1;
824                                                                 pes_header[pes_header_len++] = 0xB6;
825                                                                 bitstream_init(&bit, pes_header+pes_header_len, 1);
826                                                                 bitstream_put(&bit, 1, 2);
827                                                                 bitstream_put(&bit, 0, 1);
828                                                                 bitstream_put(&bit, 1, 1);
829                                                                 bitstream_put(&bit, self->time_inc, self->time_inc_bits);
830                                                                 bitstream_put(&bit, 1, 1);
831                                                                 bitstream_put(&bit, 0, 1);
832                                                                 bitstream_put(&bit, 0x7F >> bit.avail, 8 - bit.avail);
833 //                                                              printf(" insert pack frame %d non keyframes, time_inc %d, time_inc_bits %d -",
834 //                                                                      self->num_non_keyframes, self->time_inc, self->time_inc_bits);
835 //                                                              for (; i < (bit.data - (pes_header+pes_header_len)); ++i)
836 //                                                                      printf(" %02x", pes_header[pes_header_len+i]);
837 //                                                              printf("\nset data_len to 0!\n");
838                                                                 data_len = 0;
839                                                                 pes_header_len += bit.data - (pes_header+pes_header_len);
840                                                                 cache_prev_frame = TRUE;
841                                                         }
842                                                 }
843                                                 else if (!i_frame)
844                                                         store_frame = TRUE;
845
846                                                 self->num_non_keyframes=0;
847
848                                                 // extract time_inc
849                                                 bitstream_init(&bit, data+pos, 0);
850                                                 bitstream_get(&bit, 2); // skip coding_type
851                                                 while(bitstream_get(&bit, 1));
852                                                 bitstream_get(&bit, 1);
853                                                 self->time_inc = bitstream_get(&bit, self->time_inc_bits);
854 //                                              printf("\ntime_inc is %d\n", self->time_inc);
855
856                                                 if (store_frame) {
857 //                                                      printf("store frame\n");
858                                                         self->prev_frame = buffer;
859                                                         gst_buffer_ref (buffer);
860                                                         return GST_FLOW_OK;
861                                                 }
862                                         }
863                                         else {
864                                                 cache_prev_frame = FALSE;
865 //                                              printf(" I/P Frame without non key frame(s)!!\n");
866                                         }
867                                         break;
868                                 case 3: // S-Frame
869 //                                      printf("S ");
870 //                                      s_frame = TRUE;
871                                 case 2: // B-Frame
872 //                                      if (!s_frame)
873 //                                              printf("B ");
874                                         if (++self->num_non_keyframes == 1 && self->prev_frame) {
875 //                                              printf("send grouped with prev P!\n");
876                                                 commit_prev_frame_data = TRUE;
877                                         }
878                                         break;
879                                 case 4: // N-Frame
880                                 default:
881                                         g_warning("unhandled divx5/xvid frame type %d\n", (data[pos] & 0xC0) >> 6);
882                                         break;
883                         }
884                 }
885 //              printf("\n");
886         }
887 #endif
888
889         payload_len = data_len + pes_header_len - 6;
890
891 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
892         if (self->prev_frame && self->prev_frame != buffer) {
893                 unsigned long long pts = GST_BUFFER_TIMESTAMP(self->prev_frame) * 9LL / 100000 /* convert ns to 90kHz */;
894 //              printf("use prev timestamp: %08llx\n", (long long)GST_BUFFER_TIMESTAMP(self->prev_frame));
895
896                 pes_header[9] =  0x21 | ((pts >> 29) & 0xE);
897                 pes_header[10] = pts >> 22;
898                 pes_header[11] = 0x01 | ((pts >> 14) & 0xFE);
899                 pes_header[12] = pts >> 7;
900                 pes_header[13] = 0x01 | ((pts << 1) & 0xFE);
901         }
902
903         if (commit_prev_frame_data)
904                 payload_len += GST_BUFFER_SIZE (self->prev_frame);
905 #endif
906
907         if (self->codec_type == CT_MPEG2 || self->codec_type == CT_MPEG1) {
908                 if (!self->codec_data && data_len > 3 && !data[0] && !data[1] && data[2] == 1 && data[3] == 0xb3) { // sequence header?
909                         gboolean ok = TRUE;
910                         unsigned int pos = 4;
911                         unsigned int sheader_data_len=0;
912                         while(pos < data_len && ok) {
913                                 if ( pos >= data_len )
914                                         break;
915                                 pos+=7;
916                                 if ( pos >=data_len )
917                                         break;
918                                 sheader_data_len=12;
919                                 if ( data[pos] & 2 ) { // intra matrix avail?
920                                         pos+=64;
921                                         if ( pos >=data_len )
922                                                 break;
923                                         sheader_data_len+=64;
924                                 }
925                                 if ( data[pos] & 1 ) { // non intra matrix avail?
926                                         pos+=64;
927                                         if ( pos >=data_len )
928                                                 break;
929                                         sheader_data_len+=64;
930                                 }
931                                 pos+=1;
932                                 if ( pos+3 >=data_len )
933                                         break;
934                                 // extended start code
935                                 if ( !data[pos] && !data[pos+1] && data[pos+2] == 1 && data[pos+3] == 0xB5 ) {
936                                         pos+=3;
937                                         sheader_data_len+=3;
938                                         do {
939                                                 pos+=1;
940                                                 ++sheader_data_len;
941                                                 if (pos+2 > data_len)
942                                                         goto leave;
943                                         }
944                                         while( data[pos] || data[pos+1] || data[pos+2] != 1 );
945                                 }
946                                 if ( pos+3 >=data_len )
947                                         break;
948                                 // private data
949                                 if ( !data[pos] && !data[pos+1] && data[pos+2] && data[pos+3] == 0xB2 ) {
950                                         pos+=3;
951                                         sheader_data_len+=3;
952                                         do {
953                                                 pos+=1;
954                                                 ++sheader_data_len;
955                                                 if (pos+2 > data_len)
956                                                         goto leave;
957                                         }
958                                         while( data[pos] || data[pos+1] || data[pos+2] != 1 );
959                                 }
960                                 self->codec_data = gst_buffer_new_and_alloc(sheader_data_len);
961                                 memcpy(GST_BUFFER_DATA(self->codec_data), data+pos-sheader_data_len, sheader_data_len);
962                                 self->must_send_header = FALSE;
963 leave:
964                                 ok = FALSE;
965                         }
966                 }
967                 else if (self->codec_data && self->must_send_header) {
968                         unsigned char *codec_data = GST_BUFFER_DATA (self->codec_data);
969                         unsigned int codec_data_len = GST_BUFFER_SIZE (self->codec_data);
970                         int pos = 0;
971                         while(pos < data_len) {
972                                 if ( data[pos++] )
973                                         continue;
974                                 if ( data[pos++] )
975                                         continue;
976                                 while ( !data[pos] )
977                                         pos++;
978                                 if ( data[pos++] != 1 )
979                                         continue;
980                                 if ( data[pos++] != 0xb8 ) // group start code
981                                         continue;
982                                 pos-=4; // before group start
983                                 payload_len += codec_data_len;
984                                 if (payload_len <= 0xFFFF) {
985                                         pes_header[4] = payload_len >> 8;
986                                         pes_header[5] = payload_len & 0xFF;
987                                 }
988                                 else {
989                                         pes_header[4] = 0;
990                                         pes_header[5] = 0;
991                                 }
992                                 write(self->fd, pes_header, pes_header_len);
993                                 write(self->fd, data, pos);
994                                 write(self->fd, codec_data, codec_data_len);
995                                 write(self->fd, data+pos, data_len - pos);
996                                 self->must_send_header = FALSE;
997                                 return GST_FLOW_OK;
998                         }
999                 }
1000         }
1001
1002         if (payload_len <= 0xFFFF) {
1003                 pes_header[4] = payload_len >> 8;
1004                 pes_header[5] = payload_len & 0xFF;
1005         }
1006         else {
1007                 pes_header[4] = 0;
1008                 pes_header[5] = 0;
1009         }
1010
1011         write(self->fd, pes_header, pes_header_len);
1012
1013 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
1014         if (commit_prev_frame_data) {
1015 //              printf("commit prev frame data\n");
1016                 write(self->fd, GST_BUFFER_DATA (self->prev_frame), GST_BUFFER_SIZE (self->prev_frame));
1017         }
1018
1019         if (self->prev_frame && self->prev_frame != buffer) {
1020 //              printf("unref prev_frame buffer\n");
1021                 gst_buffer_unref(self->prev_frame);
1022                 self->prev_frame = NULL;
1023         }
1024
1025         if (cache_prev_frame) {
1026 //              printf("cache prev frame\n");
1027                 gst_buffer_ref(buffer);
1028                 self->prev_frame = buffer;
1029         }
1030 #endif
1031
1032         write(self->fd, data, data_len);
1033
1034         return GST_FLOW_OK;
1035 select_error:
1036         {
1037                 GST_ELEMENT_ERROR (self, RESOURCE, READ, (NULL),
1038                                 ("select on file descriptor: %s.", g_strerror (errno)));
1039                 GST_WARNING_OBJECT (self, "Error during select");
1040                 return GST_FLOW_ERROR;
1041         }
1042 stopped:
1043         {
1044                 GST_WARNING_OBJECT (self, "Select stopped");
1045                 ioctl(self->fd, VIDEO_CLEAR_BUFFER);
1046                 return GST_FLOW_WRONG_STATE;
1047         }
1048 }
1049
1050 static GstCaps *gst_dvbvideosink_get_caps (GstBaseSink * basesink)
1051 {
1052         GstElementClass *element_class;
1053         GstPadTemplate *pad_template;
1054         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
1055         GstCaps *in_caps, *caps;
1056
1057         element_class = GST_ELEMENT_GET_CLASS (self);
1058         pad_template = gst_element_class_get_pad_template(element_class, "sink");
1059         g_return_val_if_fail (pad_template != NULL, NULL);
1060         
1061         in_caps = gst_caps_copy (gst_pad_template_get_caps (pad_template));
1062         in_caps = gst_caps_make_writable (in_caps);
1063
1064         GstStructure *s;
1065         gint i;
1066         
1067         caps = gst_caps_new_empty ();
1068
1069         for (i = 0; i < gst_caps_get_size (in_caps); ++i)
1070         {       
1071                 s = gst_caps_get_structure (in_caps, i);
1072                 if ( gst_structure_has_name (s, "video/mpeg") )
1073                 {
1074                         GstStructure *mp1_struct = gst_structure_copy (s);
1075                         gst_structure_set (mp1_struct, "mpegversion", G_TYPE_INT, 1, NULL);
1076                         gst_caps_append_structure (caps, mp1_struct);
1077
1078                         GstStructure *mp2_struct = gst_structure_copy (s);
1079                         gst_structure_set (mp2_struct, "mpegversion", G_TYPE_INT, 2, NULL);
1080                         gst_caps_append_structure (caps, mp2_struct);
1081
1082                         if ( self->priv->model > DM800 )
1083                         {
1084                                 GstStructure *mp4_struct = gst_structure_copy (s);
1085                                 gst_structure_set (mp4_struct, "mpegversion", G_TYPE_INT, 4, NULL);
1086                                 gst_caps_append_structure (caps, mp4_struct);
1087                         }
1088                 }
1089                 if ( gst_structure_has_name (s, "video/x-h264" ) && ( self->priv->model >= DM800 ) )
1090                 {
1091                         gst_caps_append_structure (caps, gst_structure_copy (s));
1092                 }
1093                 if ( gst_structure_has_name (s, "video/x-h263" ) && ( self->priv->model > DM800 ) )
1094                 {
1095                         gst_caps_append_structure (caps, gst_structure_copy (s));
1096                 }
1097                 if ( gst_structure_has_name (s, "video/x-msmpeg" ) && ( self->priv->model > DM800 ) )
1098                 {
1099                         gst_caps_append_structure (caps, gst_structure_copy (s));
1100                 }
1101                 if ( gst_structure_has_name (s, "video/x-divx" ) && ( self->priv->model > DM800 ) )
1102                 {
1103                         gst_caps_append_structure (caps, gst_structure_copy (s));
1104                 }
1105                 if ( gst_structure_has_name (s, "video/x-xvid" ) && ( self->priv->model > DM800 ) )
1106                 {
1107                         gst_caps_append_structure (caps, gst_structure_copy (s));
1108                 }
1109         }
1110
1111         GST_DEBUG_OBJECT (self, "old caps: %s\nnew caps: %s\n", gst_caps_to_string(in_caps), gst_caps_to_string(caps));
1112
1113         gst_caps_unref (in_caps);
1114
1115         return caps;
1116 }
1117
1118 static gboolean 
1119 gst_dvbvideosink_set_caps (GstBaseSink * basesink, GstCaps * caps)
1120 {
1121         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
1122         GstStructure *structure = gst_caps_get_structure (caps, 0);
1123         const char *mimetype = gst_structure_get_name (structure);
1124         int streamtype = -1;
1125
1126         if (!strcmp (mimetype, "video/mpeg")) {
1127                 gint mpegversion;
1128                 gst_structure_get_int (structure, "mpegversion", &mpegversion);
1129                 switch (mpegversion) {
1130                         case 1:
1131                                 streamtype = 6;
1132                                 self->codec_type = CT_MPEG1;
1133                                 GST_INFO_OBJECT (self, "MIMETYPE video/mpeg1 -> VIDEO_SET_STREAMTYPE, 6");
1134                         break;
1135                         case 2:
1136                                 streamtype = 0;
1137                                 self->codec_type = CT_MPEG2;
1138                                 GST_INFO_OBJECT (self, "MIMETYPE video/mpeg2 -> VIDEO_SET_STREAMTYPE, 0");
1139                         break;
1140                         case 4:
1141                         {
1142                                 const GValue *codec_data = gst_structure_get_value (structure, "codec_data");
1143                                 if (codec_data) {
1144                                         GST_INFO_OBJECT (self, "MPEG4 have codec data");
1145                                         self->codec_data = gst_value_get_buffer (codec_data);
1146                                         self->codec_type = CT_MPEG4_PART2;
1147                                         gst_buffer_ref (self->codec_data);
1148                                 }
1149                                 streamtype = 4;
1150                                 GST_INFO_OBJECT (self, "MIMETYPE video/mpeg4 -> VIDEO_SET_STREAMTYPE, 4");
1151                         }
1152                         break;
1153                         default:
1154                                 GST_ELEMENT_ERROR (self, STREAM, FORMAT, (NULL), ("unhandled mpeg version %i", mpegversion));
1155                         break;
1156                 }
1157         } else if (!strcmp (mimetype, "video/x-h264")) {
1158                 const GValue *cd_data = gst_structure_get_value (structure, "codec_data");
1159                 streamtype = 1;
1160                 if (cd_data) {
1161                         unsigned char tmp[2048];
1162                         unsigned int tmp_len = 0;
1163                         GstBuffer *codec_data = gst_value_get_buffer (cd_data);
1164                         unsigned char *data = GST_BUFFER_DATA (codec_data);
1165                         unsigned int cd_len = GST_BUFFER_SIZE (codec_data);
1166                         unsigned int cd_pos = 0;
1167                         GST_INFO_OBJECT (self, "H264 have codec data..!");
1168                         if (cd_len > 7 && data[0] == 1) {
1169                                 unsigned short len = (data[6] << 8) | data[7];
1170 //                              printf("2 %d bytes\n", len);
1171                                 if (cd_len >= (len + 8)) {
1172                                         unsigned int i=0;
1173                                         uint8_t profile_num[] = { 66, 77, 88, 100 };
1174                                         uint8_t profile_cmp[2] = { 0x67, 0x00 };
1175                                         const char *profile_str[] = { "baseline", "main", "extended", "high" };
1176 //                                      printf("3\n");
1177                                         memcpy(tmp, "\x00\x00\x00\x01", 4);
1178                                         tmp_len += 4;
1179 //                                      printf("header part1 ");
1180 //                                      for (i = 0; i < len; ++i)
1181 //                                              printf("%02x ", data[8+i]);
1182 //                                      printf("\n");
1183                                         memcpy(tmp+tmp_len, data+8, len);
1184                                         for (i = 0; i < 4; ++i) {
1185                                                 profile_cmp[1] = profile_num[i];
1186                                                 if (!memcmp(tmp+tmp_len, profile_cmp, 2)) {
1187                                                         uint8_t level_org = tmp[tmp_len+3];
1188                                                         if (level_org > 0x29) {
1189                                                                 GST_INFO_OBJECT (self, "H264 %s profile@%d.%d patched down to 4.1!", profile_str[i], level_org / 10 , level_org % 10);
1190                                                                 tmp[tmp_len+3] = 0x29; // level 4.1
1191                                                         }
1192                                                         else
1193                                                                 GST_INFO_OBJECT (self, "H264 %s profile@%d.%d", profile_str[i], level_org / 10 , level_org % 10);
1194                                                         break;
1195                                                 }
1196                                         }
1197                                         tmp_len += len;
1198                                         cd_pos = 8 + len;
1199                                         if (cd_len > (cd_pos + 2)) {
1200                                                 len = (data[cd_pos+1] << 8) | data[cd_pos+2];
1201 //                                              printf("4 %d bytes\n", len);
1202                                                 cd_pos += 3;
1203                                                 if (cd_len >= (cd_pos+len)) {
1204 //                                                      printf("codec data ok!\n");
1205                                                         memcpy(tmp+tmp_len, "\x00\x00\x00\x01", 4);
1206                                                         tmp_len += 4;
1207 //                                                      printf("header part2 %02x %02x %02x %02x ... %d bytes\n", data[cd_pos], data[cd_pos+1], data[cd_pos+2], data[cd_pos+3], len);
1208                                                         memcpy(tmp+tmp_len, data+cd_pos, len);
1209                                                         tmp_len += len;
1210                                                         self->codec_data = gst_buffer_new_and_alloc(tmp_len);
1211                                                         memcpy(GST_BUFFER_DATA(self->codec_data), tmp, tmp_len);
1212                                                         self->h264_nal_len_size = (data[4] & 0x03) + 1;
1213                                                         if (self->h264_nal_len_size < 3)
1214                                                                 self->h264_buffer = gst_buffer_new_and_alloc(H264_BUFFER_SIZE);
1215                                                 }
1216                                                 else
1217                                                         GST_WARNING_OBJECT (self, "codec_data to short(4)");
1218                                         }
1219                                         else
1220                                                 GST_WARNING_OBJECT (self, "codec_data to short(3)");
1221                                 }
1222                                 else
1223                                         GST_WARNING_OBJECT (self, "codec_data to short(2)");
1224                         }
1225                         else if (cd_len <= 7)
1226                                 GST_WARNING_OBJECT (self, "codec_data to short(1)");
1227                         else
1228                                 GST_WARNING_OBJECT (self, "wrong avcC version %d!", data[0]);
1229                 }
1230                 else
1231                         self->h264_nal_len_size = 0;
1232                 GST_INFO_OBJECT (self, "MIMETYPE video/x-h264 VIDEO_SET_STREAMTYPE, 1");
1233         } else if (!strcmp (mimetype, "video/x-h263")) {
1234                 streamtype = 2;
1235                 GST_INFO_OBJECT (self, "MIMETYPE video/x-h263 VIDEO_SET_STREAMTYPE, 2");
1236         } else if (!strcmp (mimetype, "video/x-xvid")) {
1237                 streamtype = 10;
1238 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
1239                 self->must_pack_bitstream = 1;
1240 #endif
1241                 GST_INFO_OBJECT (self, "MIMETYPE video/x-xvid -> VIDEO_SET_STREAMTYPE, 10");
1242         } else if (!strcmp (mimetype, "video/x-divx") || !strcmp (mimetype, "video/x-msmpeg")) {
1243                 gint divxversion = -1;
1244                 if (!gst_structure_get_int (structure, "divxversion", &divxversion) && !gst_structure_get_int (structure, "msmpegversion", &divxversion))
1245                         ;
1246                 switch (divxversion) {
1247                         case 3:
1248                         case 43:
1249                         {
1250                                 #define B_GET_BITS(w,e,b)  (((w)>>(b))&(((unsigned)(-1))>>((sizeof(unsigned))*8-(e+1-b))))
1251                                 #define B_SET_BITS(name,v,e,b)  (((unsigned)(v))<<(b))
1252                                 static const guint8 brcm_divx311_sequence_header[] = {
1253                                         0x00, 0x00, 0x01, 0xE0, 0x00, 0x34, 0x80, 0x80, // PES HEADER
1254                                         0x05, 0x2F, 0xFF, 0xFF, 0xFF, 0xFF, 
1255                                         0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x20, /* 0 .. 7 */
1256                                         0x08, 0xC8, 0x0D, 0x40, 0x00, 0x53, 0x88, 0x40, /* 8 .. 15 */
1257                                         0x0C, 0x40, 0x01, 0x90, 0x00, 0x97, 0x53, 0x0A, /* 16 .. 24 */
1258                                         0x00, 0x00, 0x00, 0x00,
1259                                         0x30, 0x7F, 0x00, 0x00, 0x01, 0xB2, 0x44, 0x69, /* 0 .. 7 */
1260                                         0x76, 0x58, 0x33, 0x31, 0x31, 0x41, 0x4E, 0x44  /* 8 .. 15 */
1261                                 };
1262                                 self->codec_data = gst_buffer_new_and_alloc(63);
1263                                 guint8 *data = GST_BUFFER_DATA(self->codec_data);
1264                                 gint height, width;
1265                                 gst_structure_get_int (structure, "height", &height);
1266                                 gst_structure_get_int (structure, "width", &width);
1267                                 memcpy(data, brcm_divx311_sequence_header, 63);
1268                                 data += 38;
1269                                 data[0] = B_GET_BITS(width,11,4);
1270                                 data[1] = B_SET_BITS("width [3..0]", B_GET_BITS(width,3,0), 7, 4) |
1271                                         B_SET_BITS("'10'", 0x02, 3, 2) |
1272                                         B_SET_BITS("height [11..10]", B_GET_BITS(height,11,10), 1, 0);
1273                                 data[2] = B_GET_BITS(height,9,2);
1274                                 data[3]= B_SET_BITS("height [1.0]", B_GET_BITS(height,1,0), 7, 6) |
1275                                         B_SET_BITS("'100000'", 0x20, 5, 0);
1276                                 streamtype = 13;
1277                                 self->codec_type = CT_DIVX311;
1278                                 GST_INFO_OBJECT (self, "MIMETYPE video/x-divx vers. 3 -> VIDEO_SET_STREAMTYPE, 13");
1279                         }
1280                         break;
1281                         case 4:
1282                                 streamtype = 14;
1283                                 GST_INFO_OBJECT (self, "MIMETYPE video/x-divx vers. 4 -> VIDEO_SET_STREAMTYPE, 14");
1284                         break;
1285                         case 6:
1286                         case 5:
1287                                 streamtype = 15;
1288 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
1289                                 self->must_pack_bitstream = 1;
1290 #endif
1291                                 GST_INFO_OBJECT (self, "MIMETYPE video/x-divx vers. 5 -> VIDEO_SET_STREAMTYPE, 15");
1292                         break;
1293                         default:
1294                                 GST_ELEMENT_ERROR (self, STREAM, FORMAT, (NULL), ("unhandled divx version %i", divxversion));
1295                         break;
1296                 }
1297         }
1298         if (streamtype != -1) {
1299                 gint numerator, denominator;
1300                 if (gst_structure_get_fraction (structure, "framerate", &numerator, &denominator)) {
1301                         FILE *f = fopen("/proc/stb/vmpeg/0/fallback_framerate", "w");
1302                         if (f) {
1303                                 int valid_framerates[] = { 23976, 24000, 25000, 29970, 30000, 50000, 59940, 60000 };
1304                                 int framerate = (int)(((double)numerator * 1000) / denominator);
1305                                 int diff = 60000;
1306                                 int best = 0;
1307                                 int i = 0;
1308                                 for (; i < 7; ++i) {
1309                                         int ndiff = abs(framerate - valid_framerates[i]);
1310                                         if (ndiff < diff) {
1311                                                 diff = ndiff;
1312                                                 best = i;
1313                                         }
1314                                 }
1315                                 fprintf(f, "%d", valid_framerates[best]);
1316                                 fclose(f);
1317                         }
1318                 }
1319                 if (self->dec_running) {
1320                         ioctl(self->fd, VIDEO_STOP, 0);
1321                         self->dec_running = FALSE;
1322                 }
1323                 if (ioctl(self->fd, VIDEO_SET_STREAMTYPE, streamtype) < 0 )
1324                         if ( streamtype != 0 && streamtype != 6 )
1325                                 GST_ELEMENT_ERROR (self, STREAM, CODEC_NOT_FOUND, (NULL), ("hardware decoder can't handle streamtype %i", streamtype));
1326                 ioctl(self->fd, VIDEO_PLAY);
1327                 self->dec_running = TRUE;
1328         } else
1329                 GST_ELEMENT_ERROR (self, STREAM, TYPE_NOT_FOUND, (NULL), ("unimplemented stream type %s", mimetype));
1330
1331         return TRUE;
1332 }
1333
1334 static int readMpegProc(char *str, int decoder)
1335 {
1336         int val = -1;
1337         char tmp[64];
1338         sprintf(tmp, "/proc/stb/vmpeg/%d/%s", decoder, str);
1339         FILE *f = fopen(tmp, "r");
1340         if (f)
1341         {
1342                 fscanf(f, "%x", &val);
1343                 fclose(f);
1344         }
1345         return val;
1346 }
1347
1348 static int readApiSize(int fd, int *xres, int *yres, int *aspect)
1349 {
1350         video_size_t size;
1351         if (!ioctl(fd, VIDEO_GET_SIZE, &size))
1352         {
1353                 *xres = size.w;
1354                 *yres = size.h;
1355                 *aspect = size.aspect_ratio == 0 ? 2 : 3;  // convert dvb api to etsi
1356                 return 0;
1357         }
1358         return -1;
1359 }
1360
1361 static int readApiFrameRate(int fd, int *framerate)
1362 {
1363         unsigned int frate;
1364         if (!ioctl(fd, VIDEO_GET_FRAME_RATE, &frate))
1365         {
1366                 *framerate = frate;
1367                 return 0;
1368         }
1369         return -1;
1370 }
1371
1372 static gboolean
1373 gst_dvbvideosink_start (GstBaseSink * basesink)
1374 {
1375         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
1376         gint control_sock[2];
1377         self->fd = open("/dev/dvb/adapter0/video0", O_RDWR);
1378 //      self->fd = open("/dump.pes", O_RDWR|O_CREAT|O_TRUNC, 0555);
1379
1380         if (socketpair(PF_UNIX, SOCK_STREAM, 0, control_sock) < 0) {
1381                 perror("socketpair");
1382                 goto socket_pair;
1383         }
1384
1385         READ_SOCKET (self) = control_sock[0];
1386         WRITE_SOCKET (self) = control_sock[1];
1387
1388         fcntl (READ_SOCKET (self), F_SETFL, O_NONBLOCK);
1389         fcntl (WRITE_SOCKET (self), F_SETFL, O_NONBLOCK);
1390
1391         if (self->fd >= 0)
1392                 ioctl(self->fd, VIDEO_SELECT_SOURCE, VIDEO_SOURCE_MEMORY);
1393
1394         return TRUE;
1395         /* ERRORS */
1396 socket_pair:
1397         {
1398                 GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ_WRITE, (NULL),
1399                                 GST_ERROR_SYSTEM);
1400                 return FALSE;
1401         }
1402 }
1403
1404 static gboolean
1405 gst_dvbvideosink_stop (GstBaseSink * basesink)
1406 {
1407         GstDVBVideoSink *self = GST_DVBVIDEOSINK (basesink);
1408         FILE *f = fopen("/proc/stb/vmpeg/0/fallback_framerate", "w");
1409         if (self->fd >= 0)
1410         {
1411                 if (self->dec_running) {
1412                         ioctl(self->fd, VIDEO_STOP);
1413                         self->dec_running = FALSE;
1414                 }
1415                 ioctl(self->fd, VIDEO_SLOWMOTION, 0);
1416                 ioctl(self->fd, VIDEO_FAST_FORWARD, 0);
1417                 ioctl(self->fd, VIDEO_SELECT_SOURCE, VIDEO_SOURCE_DEMUX);
1418                 close(self->fd);
1419         }
1420
1421         close (READ_SOCKET (self));
1422         close (WRITE_SOCKET (self));
1423
1424         if (self->codec_data)
1425                 gst_buffer_unref(self->codec_data);
1426
1427         if (self->h264_buffer)
1428                 gst_buffer_unref(self->h264_buffer);
1429
1430 #ifdef PACK_UNPACKED_XVID_DIVX5_BITSTREAM
1431         if (self->prev_frame)
1432                 gst_buffer_unref(self->prev_frame);
1433 #endif
1434
1435         if (f) {
1436                 fputs(self->saved_fallback_framerate, f);
1437                 fclose(f);
1438         }
1439
1440         return TRUE;
1441 }
1442
1443 static GstFlowReturn
1444 gst_dvbvideosink_preroll (GstBaseSink * basesink, GstBuffer * buffer)
1445 {
1446         GstFlowReturn res = GST_FLOW_OK;
1447         GstDVBVideoSink *sink;
1448         sink = GST_DVBVIDEOSINK (basesink);
1449
1450         if (sink->fd >= 0)
1451         {
1452                 GstStructure *s = 0;
1453                 GstMessage *msg = 0;
1454                 int aspect = -1, width = -1, height = -1, framerate = -1,
1455                         progressive = readMpegProc("progressive", 0);
1456
1457                 if (readApiSize(sink->fd, &width, &height, &aspect) == -1)
1458                 {
1459                         aspect = readMpegProc("aspect", 0);
1460                         width = readMpegProc("xres", 0);
1461                         height = readMpegProc("yres", 0);
1462                 }
1463                 else
1464                         aspect = aspect == 0 ? 2 : 3; // dvb api to etsi
1465                 if (readApiFrameRate(sink->fd, &framerate) == -1)
1466                         framerate = readMpegProc("framerate", 0);
1467
1468                 s = gst_structure_new ("eventSizeAvail",
1469                         "aspect_ratio", G_TYPE_INT, aspect == 0 ? 2 : 3,
1470                         "width", G_TYPE_INT, width,
1471                         "height", G_TYPE_INT, height, NULL);
1472                 msg = gst_message_new_element (GST_OBJECT (basesink), s);
1473                 gst_element_post_message (GST_ELEMENT (basesink), msg);
1474
1475                 s = gst_structure_new ("eventFrameRateAvail",
1476                         "frame_rate", G_TYPE_INT, framerate, NULL);
1477                 msg = gst_message_new_element (GST_OBJECT (basesink), s);
1478                 gst_element_post_message (GST_ELEMENT (basesink), msg);
1479
1480                 s = gst_structure_new ("eventProgressiveAvail",
1481                         "progressive", G_TYPE_INT, progressive, NULL);
1482                 msg = gst_message_new_element (GST_OBJECT (basesink), s);
1483                 gst_element_post_message (GST_ELEMENT (basesink), msg);
1484         }
1485
1486         return res;
1487 }
1488
1489 /* entry point to initialize the plug-in
1490  * initialize the plug-in itself
1491  * register the element factories and pad templates
1492  * register the features
1493  *
1494  * exchange the string 'plugin' with your elemnt name
1495  */
1496 static gboolean
1497 plugin_init (GstPlugin *plugin)
1498 {
1499         return gst_element_register (plugin, "dvbvideosink",
1500                                                  GST_RANK_PRIMARY,
1501                                                  GST_TYPE_DVBVIDEOSINK);
1502 }
1503
1504 /* this is the structure that gstreamer looks for to register plugins
1505  *
1506  * exchange the strings 'plugin' and 'Template plugin' with you plugin name and
1507  * description
1508  */
1509 GST_PLUGIN_DEFINE (
1510         GST_VERSION_MAJOR,
1511         GST_VERSION_MINOR,
1512         "dvb_video_out",
1513         "DVB Video Output",
1514         plugin_init,
1515         VERSION,
1516         "LGPL",
1517         "GStreamer",
1518         "http://gstreamer.net/"
1519 )