2 * Copyright (C) 2004 Benjamin Otte <in7y118@public.uni-hamburg.de>
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * SECTION:element-theoradec
22 * @see_also: theoraenc, oggdemux
24 * This element decodes theora streams into raw video
25 * <ulink url="http://www.theora.org/">Theora</ulink> is a royalty-free
26 * video codec maintained by the <ulink url="http://www.xiph.org/">Xiph.org
27 * Foundation</ulink>, based on the VP3 codec.
30 * <title>Example pipeline</title>
32 * gst-launch -v filesrc location=videotestsrc.ogg ! oggdemux ! theoradec ! xvimagesink
33 * ]| This example pipeline will decode an ogg stream and decodes the theora video. Refer to
34 * the theoraenc example to create the ogg file.
37 * Last reviewed on 2006-03-01 (0.10.4)
44 #include "gsttheoradec.h"
45 #include <gst/tag/tag.h>
46 #include <gst/video/video.h>
48 #define GST_CAT_DEFAULT theoradec_debug
49 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
51 #define THEORA_DEF_CROP TRUE
52 #define THEORA_DEF_TELEMETRY_MV 0
53 #define THEORA_DEF_TELEMETRY_MBMODE 0
54 #define THEORA_DEF_TELEMETRY_QI 0
55 #define THEORA_DEF_TELEMETRY_BITS 0
62 PROP_TELEMETRY_MBMODE,
67 static GstStaticPadTemplate theora_dec_src_factory =
68 GST_STATIC_PAD_TEMPLATE ("src",
71 GST_STATIC_CAPS ("video/x-raw, "
72 "format = (string) { I420, Y42B, Y444 }, "
73 "framerate = (fraction) [0/1, MAX], "
74 "width = (int) [ 1, MAX ], " "height = (int) [ 1, MAX ]")
77 static GstStaticPadTemplate theora_dec_sink_factory =
78 GST_STATIC_PAD_TEMPLATE ("sink",
81 GST_STATIC_CAPS ("video/x-theora")
84 #define gst_theora_dec_parent_class parent_class
85 G_DEFINE_TYPE (GstTheoraDec, gst_theora_dec, GST_TYPE_ELEMENT);
87 static void theora_dec_get_property (GObject * object, guint prop_id,
88 GValue * value, GParamSpec * pspec);
89 static void theora_dec_set_property (GObject * object, guint prop_id,
90 const GValue * value, GParamSpec * pspec);
92 static gboolean theora_dec_setcaps (GstTheoraDec * dec, GstCaps * caps);
93 static gboolean theora_dec_sink_event (GstPad * pad, GstEvent * event);
94 static GstFlowReturn theora_dec_chain (GstPad * pad, GstBuffer * buffer);
95 static GstStateChangeReturn theora_dec_change_state (GstElement * element,
96 GstStateChange transition);
97 static gboolean theora_dec_src_event (GstPad * pad, GstEvent * event);
98 static gboolean theora_dec_src_query (GstPad * pad, GstQuery * query);
99 static gboolean theora_dec_src_convert (GstPad * pad,
100 GstFormat src_format, gint64 src_value,
101 GstFormat * dest_format, gint64 * dest_value);
104 static const GstFormat *theora_get_formats (GstPad * pad);
107 static const GstEventMask *theora_get_event_masks (GstPad * pad);
109 static const GstQueryType *theora_get_query_types (GstPad * pad);
112 gst_theora_dec_ctl_is_supported (int req)
114 /* should return TH_EFAULT or TH_EINVAL if supported, and TH_EIMPL if not */
115 return (th_decode_ctl (NULL, req, NULL, 0) != TH_EIMPL);
119 gst_theora_dec_class_init (GstTheoraDecClass * klass)
121 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
122 GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
124 gobject_class->set_property = theora_dec_set_property;
125 gobject_class->get_property = theora_dec_get_property;
127 g_object_class_install_property (gobject_class, PROP_CROP,
128 g_param_spec_boolean ("crop", "Crop",
129 "Crop the image to the visible region", THEORA_DEF_CROP,
130 (GParamFlags) G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
132 if (gst_theora_dec_ctl_is_supported (TH_DECCTL_SET_TELEMETRY_MV)) {
133 g_object_class_install_property (gobject_class, PROP_TELEMETRY_MV,
134 g_param_spec_int ("visualize-motion-vectors",
135 "Visualize motion vectors",
136 "Show motion vector selection overlaid on image. "
137 "Value gives a mask for motion vector (MV) modes to show",
138 0, 0xffff, THEORA_DEF_TELEMETRY_MV,
139 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
142 if (gst_theora_dec_ctl_is_supported (TH_DECCTL_SET_TELEMETRY_MBMODE)) {
143 g_object_class_install_property (gobject_class, PROP_TELEMETRY_MBMODE,
144 g_param_spec_int ("visualize-macroblock-modes",
145 "Visualize macroblock modes",
146 "Show macroblock mode selection overlaid on image. "
147 "Value gives a mask for macroblock (MB) modes to show",
148 0, 0xffff, THEORA_DEF_TELEMETRY_MBMODE,
149 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
152 if (gst_theora_dec_ctl_is_supported (TH_DECCTL_SET_TELEMETRY_QI)) {
153 g_object_class_install_property (gobject_class, PROP_TELEMETRY_QI,
154 g_param_spec_int ("visualize-quantization-modes",
155 "Visualize adaptive quantization modes",
156 "Show adaptive quantization mode selection overlaid on image. "
157 "Value gives a mask for quantization (QI) modes to show",
158 0, 0xffff, THEORA_DEF_TELEMETRY_QI,
159 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
162 if (gst_theora_dec_ctl_is_supported (TH_DECCTL_SET_TELEMETRY_BITS)) {
163 /* FIXME: make this a boolean instead? The value scales the bars so
164 * they're less wide. Default is to use full width, and anything else
165 * doesn't seem particularly useful, since the smaller bars just disappear
166 * then (they almost disappear for a value of 2 already). */
167 g_object_class_install_property (gobject_class, PROP_TELEMETRY_BITS,
168 g_param_spec_int ("visualize-bit-usage",
169 "Visualize bitstream usage breakdown",
170 "Sets the bitstream breakdown visualization mode. "
171 "Values influence the width of the bit usage bars to show",
172 0, 0xff, THEORA_DEF_TELEMETRY_BITS,
173 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
176 gst_element_class_add_pad_template (gstelement_class,
177 gst_static_pad_template_get (&theora_dec_src_factory));
178 gst_element_class_add_pad_template (gstelement_class,
179 gst_static_pad_template_get (&theora_dec_sink_factory));
180 gst_element_class_set_details_simple (gstelement_class,
181 "Theora video decoder", "Codec/Decoder/Video",
182 "decode raw theora streams to raw YUV video",
183 "Benjamin Otte <otte@gnome.org>, Wim Taymans <wim@fluendo.com>");
185 gstelement_class->change_state = theora_dec_change_state;
187 GST_DEBUG_CATEGORY_INIT (theoradec_debug, "theoradec", 0, "Theora decoder");
191 gst_theora_dec_init (GstTheoraDec * dec)
194 gst_pad_new_from_static_template (&theora_dec_sink_factory, "sink");
195 gst_pad_set_event_function (dec->sinkpad, theora_dec_sink_event);
196 gst_pad_set_chain_function (dec->sinkpad, theora_dec_chain);
197 gst_element_add_pad (GST_ELEMENT (dec), dec->sinkpad);
200 gst_pad_new_from_static_template (&theora_dec_src_factory, "src");
201 gst_pad_set_event_function (dec->srcpad, theora_dec_src_event);
202 gst_pad_set_query_type_function (dec->srcpad, theora_get_query_types);
203 gst_pad_set_query_function (dec->srcpad, theora_dec_src_query);
204 gst_pad_use_fixed_caps (dec->srcpad);
206 gst_element_add_pad (GST_ELEMENT (dec), dec->srcpad);
208 dec->crop = THEORA_DEF_CROP;
209 dec->telemetry_mv = THEORA_DEF_TELEMETRY_MV;
210 dec->telemetry_mbmode = THEORA_DEF_TELEMETRY_MBMODE;
211 dec->telemetry_qi = THEORA_DEF_TELEMETRY_QI;
212 dec->telemetry_bits = THEORA_DEF_TELEMETRY_BITS;
216 dec->pendingevents = NULL;
220 gst_theora_dec_reset (GstTheoraDec * dec)
222 dec->need_keyframe = TRUE;
223 dec->last_timestamp = -1;
226 dec->seqnum = gst_util_seqnum_next ();
229 gst_segment_init (&dec->segment, GST_FORMAT_TIME);
231 GST_OBJECT_LOCK (dec);
232 dec->proportion = 1.0;
233 dec->earliest_time = -1;
234 GST_OBJECT_UNLOCK (dec);
236 g_list_foreach (dec->queued, (GFunc) gst_mini_object_unref, NULL);
237 g_list_free (dec->queued);
239 g_list_foreach (dec->gather, (GFunc) gst_mini_object_unref, NULL);
240 g_list_free (dec->gather);
242 g_list_foreach (dec->decode, (GFunc) gst_mini_object_unref, NULL);
243 g_list_free (dec->decode);
245 g_list_foreach (dec->pendingevents, (GFunc) gst_mini_object_unref, NULL);
246 g_list_free (dec->pendingevents);
247 dec->pendingevents = NULL;
250 gst_tag_list_free (dec->tags);
256 static const GstFormat *
257 theora_get_formats (GstPad * pad)
259 static GstFormat src_formats[] = {
260 GST_FORMAT_DEFAULT, /* frames in this case */
265 static GstFormat sink_formats[] = {
271 return (GST_PAD_IS_SRC (pad) ? src_formats : sink_formats);
276 static const GstEventMask *
277 theora_get_event_masks (GstPad * pad)
279 static const GstEventMask theora_src_event_masks[] = {
280 {GST_EVENT_SEEK, GST_SEEK_METHOD_SET | GST_SEEK_FLAG_FLUSH},
284 return theora_src_event_masks;
288 static const GstQueryType *
289 theora_get_query_types (GstPad * pad)
291 static const GstQueryType theora_src_query_types[] = {
298 return theora_src_query_types;
303 theora_dec_src_convert (GstPad * pad,
304 GstFormat src_format, gint64 src_value,
305 GstFormat * dest_format, gint64 * dest_value)
311 if (src_format == *dest_format) {
312 *dest_value = src_value;
316 dec = GST_THEORA_DEC (gst_pad_get_parent (pad));
318 /* we need the info part before we can done something */
319 if (!dec->have_header)
322 switch (src_format) {
323 case GST_FORMAT_BYTES:
324 switch (*dest_format) {
325 case GST_FORMAT_DEFAULT:
326 *dest_value = gst_util_uint64_scale_int (src_value, 8,
327 dec->info.pic_height * dec->info.pic_width * dec->output_bpp);
329 case GST_FORMAT_TIME:
330 /* seems like a rather silly conversion, implement me if you like */
335 case GST_FORMAT_TIME:
336 switch (*dest_format) {
337 case GST_FORMAT_BYTES:
339 dec->output_bpp * (dec->info.pic_width * dec->info.pic_height) /
341 case GST_FORMAT_DEFAULT:
342 *dest_value = scale * gst_util_uint64_scale (src_value,
343 dec->info.fps_numerator, dec->info.fps_denominator * GST_SECOND);
349 case GST_FORMAT_DEFAULT:
350 switch (*dest_format) {
351 case GST_FORMAT_TIME:
352 *dest_value = gst_util_uint64_scale (src_value,
353 GST_SECOND * dec->info.fps_denominator, dec->info.fps_numerator);
355 case GST_FORMAT_BYTES:
356 *dest_value = gst_util_uint64_scale_int (src_value,
357 dec->output_bpp * dec->info.pic_width * dec->info.pic_height, 8);
367 gst_object_unref (dec);
373 GST_DEBUG_OBJECT (dec, "no header yet, cannot convert");
381 theora_dec_sink_convert (GstPad * pad,
382 GstFormat src_format, gint64 src_value,
383 GstFormat * dest_format, gint64 * dest_value)
388 if (src_format == *dest_format) {
389 *dest_value = src_value;
393 dec = GST_THEORA_DEC (gst_pad_get_parent (pad));
395 /* we need the info part before we can done something */
396 if (!dec->have_header)
399 switch (src_format) {
400 case GST_FORMAT_DEFAULT:
401 switch (*dest_format) {
402 case GST_FORMAT_TIME:
403 *dest_value = _theora_granule_start_time (dec, src_value);
409 case GST_FORMAT_TIME:
410 switch (*dest_format) {
411 case GST_FORMAT_DEFAULT:
416 *dest_value = gst_util_uint64_scale (src_value,
417 dec->info.fps_numerator, GST_SECOND * dec->info.fps_denominator);
419 /* funny way of calculating granulepos in theora */
420 rest = *dest_value / dec->info.keyframe_granule_shift;
422 *dest_value <<= dec->granule_shift;
435 gst_object_unref (dec);
441 GST_DEBUG_OBJECT (dec, "no header yet, cannot convert");
449 theora_dec_src_query (GstPad * pad, GstQuery * query)
453 gboolean res = FALSE;
455 dec = GST_THEORA_DEC (gst_pad_get_parent (pad));
457 switch (GST_QUERY_TYPE (query)) {
458 case GST_QUERY_POSITION:
465 gst_query_parse_position (query, &format, NULL);
467 time = dec->last_timestamp;
468 time = gst_segment_to_stream_time (&dec->segment, GST_FORMAT_TIME, time);
471 "query %p: our time: %" GST_TIME_FORMAT, query, GST_TIME_ARGS (time));
474 theora_dec_src_convert (pad, GST_FORMAT_TIME, time, &format,
478 gst_query_set_position (query, format, value);
481 "query %p: we return %" G_GINT64_FORMAT " (format %u)", query, value,
485 case GST_QUERY_DURATION:
487 /* forward to peer for total */
488 res = gst_pad_peer_query (dec->sinkpad, query);
494 case GST_QUERY_CONVERT:
496 GstFormat src_fmt, dest_fmt;
497 gint64 src_val, dest_val;
499 gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
501 theora_dec_src_convert (pad, src_fmt, src_val, &dest_fmt,
505 gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
509 res = gst_pad_query_default (pad, query);
513 gst_object_unref (dec);
520 GST_DEBUG_OBJECT (dec, "query failed");
526 theora_dec_src_event (GstPad * pad, GstEvent * event)
531 dec = GST_THEORA_DEC (gst_pad_get_parent (pad));
533 switch (GST_EVENT_TYPE (event)) {
536 GstFormat format, tformat;
540 GstSeekType cur_type, stop_type;
545 gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
547 seqnum = gst_event_get_seqnum (event);
548 gst_event_unref (event);
550 /* we have to ask our peer to seek to time here as we know
551 * nothing about how to generate a granulepos from the src
552 * formats or anything.
554 * First bring the requested format to time
556 tformat = GST_FORMAT_TIME;
557 if (!(res = theora_dec_src_convert (pad, format, cur, &tformat, &tcur)))
559 if (!(res = theora_dec_src_convert (pad, format, stop, &tformat, &tstop)))
562 /* then seek with time on the peer */
563 real_seek = gst_event_new_seek (rate, GST_FORMAT_TIME,
564 flags, cur_type, tcur, stop_type, tstop);
565 gst_event_set_seqnum (real_seek, seqnum);
567 res = gst_pad_push_event (dec->sinkpad, real_seek);
573 GstClockTimeDiff diff;
574 GstClockTime timestamp;
576 gst_event_parse_qos (event, NULL, &proportion, &diff, ×tamp);
578 /* we cannot randomly skip frame decoding since we don't have
579 * B frames. we can however use the timestamp and diff to not
580 * push late frames. This would at least save us the time to
581 * crop/memcpy the data. */
582 GST_OBJECT_LOCK (dec);
583 dec->proportion = proportion;
584 dec->earliest_time = timestamp + diff;
585 GST_OBJECT_UNLOCK (dec);
587 GST_DEBUG_OBJECT (dec, "got QoS %" GST_TIME_FORMAT ", %" G_GINT64_FORMAT,
588 GST_TIME_ARGS (timestamp), diff);
590 res = gst_pad_push_event (dec->sinkpad, event);
594 res = gst_pad_push_event (dec->sinkpad, event);
598 gst_object_unref (dec);
605 GST_DEBUG_OBJECT (dec, "could not convert format");
611 theora_dec_sink_event (GstPad * pad, GstEvent * event)
613 gboolean ret = FALSE;
616 dec = GST_THEORA_DEC (gst_pad_get_parent (pad));
618 GST_LOG_OBJECT (dec, "handling event");
619 switch (GST_EVENT_TYPE (event)) {
620 case GST_EVENT_FLUSH_START:
621 ret = gst_pad_push_event (dec->srcpad, event);
623 case GST_EVENT_FLUSH_STOP:
624 gst_theora_dec_reset (dec);
625 ret = gst_pad_push_event (dec->srcpad, event);
628 ret = gst_pad_push_event (dec->srcpad, event);
630 case GST_EVENT_SEGMENT:
632 const GstSegment *segment;
634 gst_event_parse_segment (event, &segment);
636 /* we need TIME format */
637 if (segment->format != GST_FORMAT_TIME)
638 goto newseg_wrong_format;
640 GST_DEBUG_OBJECT (dec, "segment: %" GST_SEGMENT_FORMAT, segment);
642 /* now configure the values */
643 gst_segment_copy_into (segment, &dec->segment);
644 dec->seqnum = gst_event_get_seqnum (event);
646 /* We don't forward this unless/until the decoder is initialised */
647 if (dec->have_header) {
648 ret = gst_pad_push_event (dec->srcpad, event);
650 dec->pendingevents = g_list_append (dec->pendingevents, event);
659 gst_event_parse_caps (event, &caps);
660 ret = theora_dec_setcaps (dec, caps);
661 gst_event_unref (event);
666 if (dec->have_header)
668 ret = gst_pad_push_event (dec->srcpad, event);
670 /* store it to send once we're initialized */
671 dec->pendingevents = g_list_append (dec->pendingevents, event);
677 ret = gst_pad_event_default (pad, event);
681 gst_object_unref (dec);
688 GST_DEBUG_OBJECT (dec, "received non TIME newsegment");
689 gst_event_unref (event);
695 theora_dec_setcaps (GstTheoraDec * dec, GstCaps * caps)
698 const GValue *codec_data;
700 s = gst_caps_get_structure (caps, 0);
702 /* parse the par, this overrides the encoded par */
703 dec->have_par = gst_structure_get_fraction (s, "pixel-aspect-ratio",
704 &dec->par_num, &dec->par_den);
706 if ((codec_data = gst_structure_get_value (s, "codec_data"))) {
707 if (G_VALUE_TYPE (codec_data) == GST_TYPE_BUFFER) {
713 buffer = gst_value_get_buffer (codec_data);
716 data = gst_buffer_map (buffer, &size, NULL, GST_MAP_READ);
725 psize = (ptr[0] << 8) | ptr[1];
731 /* make sure we don't read too much */
732 psize = MIN (psize, left);
735 gst_buffer_copy_region (buffer, GST_BUFFER_COPY_ALL, offset, psize);
737 /* first buffer is a discont buffer */
739 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
741 /* now feed it to the decoder we can ignore the error */
742 theora_dec_chain (dec->sinkpad, buf);
749 gst_buffer_unmap (buffer, data, size);
757 theora_handle_comment_packet (GstTheoraDec * dec, ogg_packet * packet)
759 gchar *encoder = NULL;
762 GST_DEBUG_OBJECT (dec, "parsing comment packet");
765 gst_tag_list_from_vorbiscomment (packet->packet, packet->bytes,
766 (guint8 *) "\201theora", 7, &encoder);
769 GST_ERROR_OBJECT (dec, "couldn't decode comments");
770 list = gst_tag_list_new ();
773 gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
774 GST_TAG_ENCODER, encoder, NULL);
777 gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
778 GST_TAG_ENCODER_VERSION, dec->info.version_major,
779 GST_TAG_VIDEO_CODEC, "Theora", NULL);
781 if (dec->info.target_bitrate > 0) {
782 gst_tag_list_add (list, GST_TAG_MERGE_REPLACE,
783 GST_TAG_BITRATE, dec->info.target_bitrate,
784 GST_TAG_NOMINAL_BITRATE, dec->info.target_bitrate, NULL);
793 theora_negotiate_pool (GstTheoraDec * dec, GstCaps * caps)
796 GstBufferPool *pool = NULL;
797 guint size, min, max, prefix, alignment;
799 /* find a pool for the negotiated caps now */
800 query = gst_query_new_allocation (caps, TRUE);
802 if (gst_pad_peer_query (dec->srcpad, query)) {
803 GST_DEBUG_OBJECT (dec, "got downstream ALLOCATION hints");
804 /* we got configuration from our peer, parse them */
805 gst_query_parse_allocation_params (query, &size, &min, &max, &prefix,
808 GST_DEBUG_OBJECT (dec, "didn't get downstream ALLOCATION hints");
809 size = gst_video_format_get_size (dec->format, dec->width, dec->height);
816 GstStructure *config;
818 /* we did not get a pool, make one ourselves then */
819 pool = gst_buffer_pool_new ();
821 config = gst_buffer_pool_get_config (pool);
822 gst_buffer_pool_config_set (config, caps, size, min, max, prefix,
824 gst_buffer_pool_set_config (pool, config);
828 gst_object_unref (dec->pool);
831 /* FIXME, we can check if downstream supports clipping and/or video
835 gst_buffer_pool_set_active (pool, TRUE);
841 theora_handle_type_packet (GstTheoraDec * dec, ogg_packet * packet)
844 gint par_num, par_den;
845 GstFlowReturn ret = GST_FLOW_OK;
848 GST_DEBUG_OBJECT (dec, "fps %d/%d, PAR %d/%d",
849 dec->info.fps_numerator, dec->info.fps_denominator,
850 dec->info.aspect_numerator, dec->info.aspect_denominator);
853 * the info.aspect_* values reflect PAR;
854 * 0:x and x:0 are allowed and can be interpreted as 1:1.
857 /* we had a par on the sink caps, override the encoded par */
858 GST_DEBUG_OBJECT (dec, "overriding with input PAR");
859 par_num = dec->par_num;
860 par_den = dec->par_den;
862 /* take encoded par */
863 par_num = dec->info.aspect_numerator;
864 par_den = dec->info.aspect_denominator;
866 if (par_num == 0 || par_den == 0) {
867 par_num = par_den = 1;
871 * width/height : dimension of the encoded frame
872 * pic_width/pic_height : dimension of the visible part
873 * pic_x/pic_y : offset in encoded frame where visible part starts
875 GST_DEBUG_OBJECT (dec, "dimension %dx%d, PAR %d/%d", dec->info.pic_width,
876 dec->info.pic_height, par_num, par_den);
877 GST_DEBUG_OBJECT (dec, "frame dimension %dx%d, offset %d:%d",
878 dec->info.pic_width, dec->info.pic_height,
879 dec->info.pic_x, dec->info.pic_y);
881 switch (dec->info.pixel_fmt) {
883 dec->output_bpp = 24;
884 dec->format = GST_VIDEO_FORMAT_Y444;
887 dec->output_bpp = 12; /* Average bits per pixel. */
888 dec->format = GST_VIDEO_FORMAT_I420;
891 dec->output_bpp = 16;
892 dec->format = GST_VIDEO_FORMAT_Y42B;
899 dec->width = dec->info.pic_width;
900 dec->height = dec->info.pic_height;
901 dec->offset_x = dec->info.pic_x;
902 dec->offset_y = dec->info.pic_y;
903 /* Ensure correct offsets in chroma for formats that need it
904 * by rounding the offset. libtheora will add proper pixels,
905 * so no need to handle them ourselves. */
906 if (dec->offset_x & 1 && dec->info.pixel_fmt != TH_PF_444) {
910 if (dec->offset_y & 1 && dec->info.pixel_fmt == TH_PF_420) {
915 /* no cropping, use the encoded dimensions */
916 dec->width = dec->info.frame_width;
917 dec->height = dec->info.frame_height;
922 GST_DEBUG_OBJECT (dec, "after fixup frame dimension %dx%d, offset %d:%d",
923 dec->width, dec->height, dec->offset_x, dec->offset_y);
926 dec->decoder = th_decode_alloc (&dec->info, dec->setup);
928 if (th_decode_ctl (dec->decoder, TH_DECCTL_SET_TELEMETRY_MV,
929 &dec->telemetry_mv, sizeof (dec->telemetry_mv)) != TH_EIMPL) {
930 GST_WARNING_OBJECT (dec, "Could not enable MV visualisation");
932 if (th_decode_ctl (dec->decoder, TH_DECCTL_SET_TELEMETRY_MBMODE,
933 &dec->telemetry_mbmode, sizeof (dec->telemetry_mbmode)) != TH_EIMPL) {
934 GST_WARNING_OBJECT (dec, "Could not enable MB mode visualisation");
936 if (th_decode_ctl (dec->decoder, TH_DECCTL_SET_TELEMETRY_QI,
937 &dec->telemetry_qi, sizeof (dec->telemetry_qi)) != TH_EIMPL) {
938 GST_WARNING_OBJECT (dec, "Could not enable QI mode visualisation");
940 if (th_decode_ctl (dec->decoder, TH_DECCTL_SET_TELEMETRY_BITS,
941 &dec->telemetry_bits, sizeof (dec->telemetry_bits)) != TH_EIMPL) {
942 GST_WARNING_OBJECT (dec, "Could not enable BITS mode visualisation");
945 caps = gst_caps_new_simple ("video/x-raw",
946 "format", G_TYPE_STRING, gst_video_format_to_string (dec->format),
947 "framerate", GST_TYPE_FRACTION,
948 dec->info.fps_numerator, dec->info.fps_denominator,
949 "pixel-aspect-ratio", GST_TYPE_FRACTION, par_num, par_den,
950 "width", G_TYPE_INT, dec->width, "height", G_TYPE_INT, dec->height,
951 "color-matrix", G_TYPE_STRING, "sdtv",
952 "chroma-site", G_TYPE_STRING, "jpeg", NULL);
953 gst_pad_set_caps (dec->srcpad, caps);
954 gst_caps_unref (caps);
956 /* negotiate a bufferpool */
957 if ((ret = theora_negotiate_pool (dec, caps)) != GST_FLOW_OK)
960 dec->have_header = TRUE;
962 if (dec->pendingevents) {
963 for (walk = dec->pendingevents; walk; walk = g_list_next (walk))
964 gst_pad_push_event (dec->srcpad, GST_EVENT_CAST (walk->data));
965 g_list_free (dec->pendingevents);
966 dec->pendingevents = NULL;
970 gst_element_found_tags_for_pad (GST_ELEMENT_CAST (dec), dec->srcpad,
980 GST_ERROR_OBJECT (dec, "Invalid pixel format %d", dec->info.pixel_fmt);
981 return GST_FLOW_ERROR;
990 theora_handle_header_packet (GstTheoraDec * dec, ogg_packet * packet)
995 GST_DEBUG_OBJECT (dec, "parsing header packet");
997 ret = th_decode_headerin (&dec->info, &dec->comment, &dec->setup, packet);
999 goto header_read_error;
1001 switch (packet->packet[0]) {
1003 res = theora_handle_comment_packet (dec, packet);
1006 res = theora_handle_type_packet (dec, packet);
1010 g_warning ("unknown theora header packet found");
1012 /* nothing special, this is the identification header */
1021 GST_ELEMENT_ERROR (GST_ELEMENT (dec), STREAM, DECODE,
1022 (NULL), ("couldn't read header packet"));
1023 return GST_FLOW_ERROR;
1027 /* returns TRUE if buffer is within segment, else FALSE.
1028 * if Buffer is on segment border, it's timestamp and duration will be clipped */
1030 clip_buffer (GstTheoraDec * dec, GstBuffer * buf)
1032 gboolean res = TRUE;
1033 GstClockTime in_ts, in_dur, stop;
1034 guint64 cstart, cstop;
1036 in_ts = GST_BUFFER_TIMESTAMP (buf);
1037 in_dur = GST_BUFFER_DURATION (buf);
1039 GST_LOG_OBJECT (dec,
1040 "timestamp:%" GST_TIME_FORMAT " , duration:%" GST_TIME_FORMAT,
1041 GST_TIME_ARGS (in_ts), GST_TIME_ARGS (in_dur));
1043 /* can't clip without TIME segment */
1044 if (dec->segment.format != GST_FORMAT_TIME)
1047 /* we need a start time */
1048 if (!GST_CLOCK_TIME_IS_VALID (in_ts))
1051 /* generate valid stop, if duration unknown, we have unknown stop */
1053 GST_CLOCK_TIME_IS_VALID (in_dur) ? (in_ts + in_dur) : GST_CLOCK_TIME_NONE;
1056 if (!(res = gst_segment_clip (&dec->segment, GST_FORMAT_TIME,
1057 in_ts, stop, &cstart, &cstop)))
1060 /* update timestamp and possibly duration if the clipped stop time is
1062 GST_BUFFER_TIMESTAMP (buf) = cstart;
1063 if (GST_CLOCK_TIME_IS_VALID (cstop))
1064 GST_BUFFER_DURATION (buf) = cstop - cstart;
1067 GST_LOG_OBJECT (dec, "%sdropping", (res ? "not " : ""));
1071 static GstFlowReturn
1072 theora_dec_push_forward (GstTheoraDec * dec, GstBuffer * buf)
1074 GstFlowReturn result = GST_FLOW_OK;
1076 if (clip_buffer (dec, buf)) {
1078 GST_LOG_OBJECT (dec, "setting DISCONT");
1079 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1080 dec->discont = FALSE;
1082 result = gst_pad_push (dec->srcpad, buf);
1084 gst_buffer_unref (buf);
1090 static GstFlowReturn
1091 theora_dec_push_reverse (GstTheoraDec * dec, GstBuffer * buf)
1093 GstFlowReturn result = GST_FLOW_OK;
1095 dec->queued = g_list_prepend (dec->queued, buf);
1100 /* Allocate buffer and copy image data into Y444 format */
1101 static GstFlowReturn
1102 theora_handle_image (GstTheoraDec * dec, th_ycbcr_buffer buf, GstBuffer ** out)
1104 gint width, height, stride;
1105 GstFlowReturn result;
1111 if (gst_pad_check_reconfigure (dec->srcpad)) {
1114 caps = gst_pad_get_current_caps (dec->srcpad);
1115 theora_negotiate_pool (dec, caps);
1116 gst_caps_unref (caps);
1119 result = gst_buffer_pool_acquire_buffer (dec->pool, out, NULL);
1120 if (G_UNLIKELY (result != GST_FLOW_OK))
1123 data = gst_buffer_map (*out, &size, NULL, GST_MAP_WRITE);
1125 /* FIXME, we can do things slightly more efficient when we know that
1126 * downstream understands clipping and video metadata */
1128 for (plane = 0; plane < 3; plane++) {
1130 gst_video_format_get_component_width (dec->format, plane, dec->width);
1132 gst_video_format_get_component_height (dec->format, plane, dec->height);
1133 stride = gst_video_format_get_row_stride (dec->format, plane, dec->width);
1135 dest = data + gst_video_format_get_component_offset (dec->format,
1136 plane, dec->width, dec->height);
1137 src = buf[plane].data;
1138 src += ((height == dec->height) ? dec->offset_y : dec->offset_y / 2)
1139 * buf[plane].stride;
1140 src += (width == dec->width) ? dec->offset_x : dec->offset_x / 2;
1142 for (i = 0; i < height; i++) {
1143 memcpy (dest, src, width);
1146 src += buf[plane].stride;
1149 gst_buffer_unmap (*out, data, size);
1156 GST_DEBUG_OBJECT (dec, "could not get buffer, reason: %s",
1157 gst_flow_get_name (result));
1162 static GstFlowReturn
1163 theora_handle_data_packet (GstTheoraDec * dec, ogg_packet * packet,
1164 GstClockTime outtime, GstClockTime outdur)
1166 /* normal data packet */
1167 th_ycbcr_buffer buf;
1170 GstFlowReturn result;
1173 if (G_UNLIKELY (!dec->have_header))
1174 goto not_initialized;
1176 /* get timestamp and durations */
1178 outtime = dec->last_timestamp;
1180 outdur = gst_util_uint64_scale_int (GST_SECOND, dec->info.fps_denominator,
1181 dec->info.fps_numerator);
1183 /* calculate expected next timestamp */
1184 if (outtime != -1 && outdur != -1)
1185 dec->last_timestamp = outtime + outdur;
1187 /* the second most significant bit of the first data byte is cleared
1188 * for keyframes. We can only check it if it's not a zero-length packet. */
1189 keyframe = packet->bytes && ((packet->packet[0] & 0x40) == 0);
1190 if (G_UNLIKELY (keyframe)) {
1191 GST_DEBUG_OBJECT (dec, "we have a keyframe");
1192 dec->need_keyframe = FALSE;
1193 } else if (G_UNLIKELY (dec->need_keyframe)) {
1197 GST_DEBUG_OBJECT (dec, "parsing data packet");
1199 /* this does the decoding */
1200 if (G_UNLIKELY (th_decode_packetin (dec->decoder, packet, &gp) < 0))
1203 if (outtime != -1) {
1205 GstClockTime running_time;
1206 GstClockTime earliest_time;
1209 /* qos needs to be done on running time */
1210 running_time = gst_segment_to_running_time (&dec->segment, GST_FORMAT_TIME,
1213 GST_OBJECT_LOCK (dec);
1214 proportion = dec->proportion;
1215 earliest_time = dec->earliest_time;
1216 /* check for QoS, don't perform the last steps of getting and
1217 * pushing the buffers that are known to be late. */
1218 need_skip = earliest_time != -1 && running_time <= earliest_time;
1219 GST_OBJECT_UNLOCK (dec);
1222 GstMessage *qos_msg;
1223 guint64 stream_time;
1226 GST_DEBUG_OBJECT (dec, "skipping decoding: qostime %"
1227 GST_TIME_FORMAT " <= %" GST_TIME_FORMAT,
1228 GST_TIME_ARGS (running_time), GST_TIME_ARGS (earliest_time));
1233 gst_segment_to_stream_time (&dec->segment, GST_FORMAT_TIME, outtime);
1234 jitter = GST_CLOCK_DIFF (running_time, earliest_time);
1237 gst_message_new_qos (GST_OBJECT_CAST (dec), FALSE, running_time,
1238 stream_time, outtime, outdur);
1239 gst_message_set_qos_values (qos_msg, jitter, proportion, 1000000);
1240 gst_message_set_qos_stats (qos_msg, GST_FORMAT_BUFFERS,
1241 dec->processed, dec->dropped);
1242 gst_element_post_message (GST_ELEMENT_CAST (dec), qos_msg);
1248 /* this does postprocessing and set up the decoded frame
1249 * pointers in our yuv variable */
1250 if (G_UNLIKELY (th_decode_ycbcr_out (dec->decoder, buf) < 0))
1253 if (G_UNLIKELY ((buf[0].width != dec->info.frame_width)
1254 || (buf[0].height != dec->info.frame_height)))
1255 goto wrong_dimensions;
1257 result = theora_handle_image (dec, buf, &out);
1258 if (result != GST_FLOW_OK)
1261 GST_BUFFER_OFFSET (out) = dec->frame_nr;
1262 if (dec->frame_nr != -1)
1264 GST_BUFFER_OFFSET_END (out) = dec->frame_nr;
1266 GST_BUFFER_TIMESTAMP (out) = outtime;
1267 GST_BUFFER_DURATION (out) = outdur;
1271 if (dec->segment.rate >= 0.0)
1272 result = theora_dec_push_forward (dec, out);
1274 result = theora_dec_push_reverse (dec, out);
1281 GST_ELEMENT_ERROR (GST_ELEMENT (dec), STREAM, DECODE,
1282 (NULL), ("no header sent yet"));
1283 return GST_FLOW_ERROR;
1287 GST_WARNING_OBJECT (dec, "dropping frame because we need a keyframe");
1288 dec->discont = TRUE;
1293 if (dec->frame_nr != -1)
1295 dec->discont = TRUE;
1296 GST_WARNING_OBJECT (dec, "dropping frame because of QoS");
1301 GST_ELEMENT_ERROR (GST_ELEMENT (dec), STREAM, DECODE,
1302 (NULL), ("theora decoder did not decode data packet"));
1303 return GST_FLOW_ERROR;
1307 GST_ELEMENT_ERROR (GST_ELEMENT (dec), STREAM, DECODE,
1308 (NULL), ("couldn't read out YUV image"));
1309 return GST_FLOW_ERROR;
1313 GST_ELEMENT_ERROR (GST_ELEMENT (dec), STREAM, FORMAT,
1314 (NULL), ("dimensions of image do not match header"));
1315 return GST_FLOW_ERROR;
1319 static GstFlowReturn
1320 theora_dec_decode_buffer (GstTheoraDec * dec, GstBuffer * buf)
1323 GstFlowReturn result = GST_FLOW_OK;
1324 GstClockTime timestamp, duration;
1327 /* make ogg_packet out of the buffer */
1328 packet.packet = gst_buffer_map (buf, &size, NULL, GST_MAP_READ);
1329 packet.bytes = size;
1330 packet.granulepos = -1;
1331 packet.packetno = 0; /* we don't really care */
1332 packet.b_o_s = dec->have_header ? 0 : 1;
1333 /* EOS does not matter for the decoder */
1336 GST_LOG_OBJECT (dec, "decode buffer of size %ld", packet.bytes);
1338 /* save last seem timestamp for interpolating the next timestamps using the
1339 * framerate when we need to */
1340 timestamp = GST_BUFFER_TIMESTAMP (buf);
1341 duration = GST_BUFFER_DURATION (buf);
1343 GST_DEBUG_OBJECT (dec, "header=%02x, outtime=%" GST_TIME_FORMAT,
1344 packet.bytes ? packet.packet[0] : -1, GST_TIME_ARGS (timestamp));
1346 /* switch depending on packet type. A zero byte packet is always a data
1347 * packet; we don't dereference it in that case. */
1348 if (packet.bytes && packet.packet[0] & 0x80) {
1349 if (dec->have_header) {
1350 GST_WARNING_OBJECT (GST_OBJECT (dec), "Ignoring header");
1353 result = theora_handle_header_packet (dec, &packet);
1355 result = theora_handle_data_packet (dec, &packet, timestamp, duration);
1358 gst_buffer_unmap (buf, packet.packet, size);
1363 /* For reverse playback we use a technique that can be used for
1364 * any keyframe based video codec.
1367 * Buffer decoding order: 7 8 9 4 5 6 1 2 3 EOS
1368 * Keyframe flag: K K
1369 * Discont flag: D D D
1371 * - Each Discont marks a discont in the decoding order.
1372 * - The keyframes mark where we can start decoding.
1374 * First we prepend incomming buffers to the gather queue, whenever we receive
1375 * a discont, we flush out the gather queue.
1377 * The above data will be accumulated in the gather queue like this:
1379 * gather queue: 9 8 7
1382 * Whe buffer 4 is received (with a DISCONT), we flush the gather queue like
1386 * take head of queue and prepend to decode queue.
1387 * if we copied a keyframe, decode the decode queue.
1389 * After we flushed the gather queue, we add 4 to the (now empty) gather queue.
1390 * We get the following situation:
1393 * decode queue: 7 8 9
1395 * After we received 5 (Keyframe) and 6:
1397 * gather queue: 6 5 4
1398 * decode queue: 7 8 9
1400 * When we receive 1 (DISCONT) which triggers a flush of the gather queue:
1402 * Copy head of the gather queue (6) to decode queue:
1405 * decode queue: 6 7 8 9
1407 * Copy head of the gather queue (5) to decode queue. This is a keyframe so we
1408 * can start decoding.
1411 * decode queue: 5 6 7 8 9
1413 * Decode frames in decode queue, store raw decoded data in output queue, we
1414 * can take the head of the decode queue and prepend the decoded result in the
1419 * output queue: 9 8 7 6 5
1421 * Now output all the frames in the output queue, picking a frame from the
1422 * head of the queue.
1424 * Copy head of the gather queue (4) to decode queue, we flushed the gather
1425 * queue and can now store input buffer in the gather queue:
1430 * When we receive EOS, the queue looks like:
1432 * gather queue: 3 2 1
1435 * Fill decode queue, first keyframe we copy is 2:
1438 * decode queue: 2 3 4
1444 * output queue: 4 3 2
1446 * Leftover buffer 1 cannot be decoded and must be discarded.
1448 static GstFlowReturn
1449 theora_dec_flush_decode (GstTheoraDec * dec)
1451 GstFlowReturn res = GST_FLOW_OK;
1453 while (dec->decode) {
1454 GstBuffer *buf = GST_BUFFER_CAST (dec->decode->data);
1456 GST_DEBUG_OBJECT (dec, "decoding buffer %p, ts %" GST_TIME_FORMAT,
1457 buf, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1459 /* decode buffer, prepend to output queue */
1460 res = theora_dec_decode_buffer (dec, buf);
1462 /* don't need it anymore now */
1463 gst_buffer_unref (buf);
1465 dec->decode = g_list_delete_link (dec->decode, dec->decode);
1467 while (dec->queued) {
1468 GstBuffer *buf = GST_BUFFER_CAST (dec->queued->data);
1470 /* iterate ouput queue an push downstream */
1471 res = gst_pad_push (dec->srcpad, buf);
1473 dec->queued = g_list_delete_link (dec->queued, dec->queued);
1479 static GstFlowReturn
1480 theora_dec_chain_reverse (GstTheoraDec * dec, gboolean discont, GstBuffer * buf)
1482 GstFlowReturn res = GST_FLOW_OK;
1484 /* if we have a discont, move buffers to the decode list */
1485 if (G_UNLIKELY (discont)) {
1486 GST_DEBUG_OBJECT (dec, "received discont,gathering buffers");
1487 while (dec->gather) {
1491 gbuf = GST_BUFFER_CAST (dec->gather->data);
1492 /* remove from the gather list */
1493 dec->gather = g_list_delete_link (dec->gather, dec->gather);
1494 /* copy to decode queue */
1495 dec->decode = g_list_prepend (dec->decode, gbuf);
1497 /* if we copied a keyframe, flush and decode the decode queue */
1498 gst_buffer_extract (gbuf, 0, data, 1);
1499 if ((data[0] & 0x40) == 0) {
1500 GST_DEBUG_OBJECT (dec, "copied keyframe");
1501 res = theora_dec_flush_decode (dec);
1506 /* add buffer to gather queue */
1507 GST_DEBUG_OBJECT (dec, "gathering buffer %p, size %u", buf,
1508 gst_buffer_get_size (buf));
1509 dec->gather = g_list_prepend (dec->gather, buf);
1514 static GstFlowReturn
1515 theora_dec_chain_forward (GstTheoraDec * dec, gboolean discont,
1518 GstFlowReturn result;
1520 result = theora_dec_decode_buffer (dec, buffer);
1522 gst_buffer_unref (buffer);
1527 static GstFlowReturn
1528 theora_dec_chain (GstPad * pad, GstBuffer * buf)
1534 dec = GST_THEORA_DEC (gst_pad_get_parent (pad));
1536 /* peel of DISCONT flag */
1537 discont = GST_BUFFER_IS_DISCONT (buf);
1539 /* resync on DISCONT */
1540 if (G_UNLIKELY (discont)) {
1541 GST_DEBUG_OBJECT (dec, "received DISCONT buffer");
1542 dec->need_keyframe = TRUE;
1543 dec->last_timestamp = -1;
1544 dec->discont = TRUE;
1547 if (dec->segment.rate > 0.0)
1548 res = theora_dec_chain_forward (dec, discont, buf);
1550 res = theora_dec_chain_reverse (dec, discont, buf);
1552 gst_object_unref (dec);
1557 static GstStateChangeReturn
1558 theora_dec_change_state (GstElement * element, GstStateChange transition)
1560 GstTheoraDec *dec = GST_THEORA_DEC (element);
1561 GstStateChangeReturn ret;
1563 switch (transition) {
1564 case GST_STATE_CHANGE_NULL_TO_READY:
1566 case GST_STATE_CHANGE_READY_TO_PAUSED:
1567 th_info_clear (&dec->info);
1568 th_comment_clear (&dec->comment);
1569 GST_DEBUG_OBJECT (dec, "Setting have_header to FALSE in READY->PAUSED");
1570 dec->have_header = FALSE;
1571 dec->have_par = FALSE;
1572 gst_theora_dec_reset (dec);
1574 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1580 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1582 switch (transition) {
1583 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1585 case GST_STATE_CHANGE_PAUSED_TO_READY:
1586 th_info_clear (&dec->info);
1587 th_comment_clear (&dec->comment);
1588 th_setup_free (dec->setup);
1590 th_decode_free (dec->decoder);
1591 dec->decoder = NULL;
1592 gst_theora_dec_reset (dec);
1594 gst_buffer_pool_set_active (dec->pool, FALSE);
1595 gst_object_unref (dec->pool);
1599 case GST_STATE_CHANGE_READY_TO_NULL:
1609 theora_dec_set_property (GObject * object, guint prop_id,
1610 const GValue * value, GParamSpec * pspec)
1612 GstTheoraDec *dec = GST_THEORA_DEC (object);
1616 dec->crop = g_value_get_boolean (value);
1618 case PROP_TELEMETRY_MV:
1619 dec->telemetry_mv = g_value_get_int (value);
1621 case PROP_TELEMETRY_MBMODE:
1622 dec->telemetry_mbmode = g_value_get_int (value);
1624 case PROP_TELEMETRY_QI:
1625 dec->telemetry_qi = g_value_get_int (value);
1627 case PROP_TELEMETRY_BITS:
1628 dec->telemetry_bits = g_value_get_int (value);
1631 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1637 theora_dec_get_property (GObject * object, guint prop_id,
1638 GValue * value, GParamSpec * pspec)
1640 GstTheoraDec *dec = GST_THEORA_DEC (object);
1644 g_value_set_boolean (value, dec->crop);
1646 case PROP_TELEMETRY_MV:
1647 g_value_set_int (value, dec->telemetry_mv);
1649 case PROP_TELEMETRY_MBMODE:
1650 g_value_set_int (value, dec->telemetry_mbmode);
1652 case PROP_TELEMETRY_QI:
1653 g_value_set_int (value, dec->telemetry_qi);
1655 case PROP_TELEMETRY_BITS:
1656 g_value_set_int (value, dec->telemetry_bits);
1659 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);