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